@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,10 +2,10 @@ const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  const require_chunk = require("./chunk-DDcVe30Y.cjs");
4
4
  const require_transformers = require("./transformers-NeAONrAq.cjs");
5
- const require_http = require("./http-D8I7LBfx.cjs");
6
- const require_types = require("./types-DOvyymM4.cjs");
7
- const require_proof = require("./proof-qiuGJCD7.cjs");
8
- const require_kv_cache = require("./kv-cache-DC9LcfoC.cjs");
5
+ const require_http = require("./http-BNaPJVnF.cjs");
6
+ const require_proof = require("./proof-Dbz6ApNP.cjs");
7
+ const require_types = require("./types-BWx7zw3Y.cjs");
8
+ const require_kv_cache = require("./kv-cache-Bj3CY9Jo.cjs");
9
9
  let _logtape_logtape = require("@logtape/logtape");
10
10
  let _fedify_vocab = require("@fedify/vocab");
11
11
  let _opentelemetry_api = require("@opentelemetry/api");
@@ -14,11 +14,14 @@ let uri_template_router = require("uri-template-router");
14
14
  let url_template = require("url-template");
15
15
  let byte_encodings_hex = require("byte-encodings/hex");
16
16
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
17
- let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
18
17
  let _fedify_vocab_runtime_jsonld = require("@fedify/vocab-runtime/jsonld");
19
18
  _fedify_vocab_runtime_jsonld = require_chunk.__toESM(_fedify_vocab_runtime_jsonld);
20
- let _fedify_webfinger = require("@fedify/webfinger");
21
19
  let _fedify_vocab_runtime_internal = require("@fedify/vocab-runtime/internal");
20
+ let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
21
+ let json_canon = require("json-canon");
22
+ json_canon = require_chunk.__toESM(json_canon);
23
+ let _fedify_vocab_runtime_temporal = require("@fedify/vocab-runtime/temporal");
24
+ let _fedify_webfinger = require("@fedify/webfinger");
22
25
  let node_url = require("node:url");
23
26
  //#region src/federation/activity-listener.ts
24
27
  var ActivityListenerSet = class {
@@ -214,7 +217,7 @@ var FederationBuilderImpl = class {
214
217
  this.collectionTypeIds = {};
215
218
  }
216
219
  async build(options) {
217
- const { FederationImpl } = await Promise.resolve().then(() => require("./middleware-DmcY2TWS.cjs"));
220
+ const { FederationImpl } = await Promise.resolve().then(() => require("./middleware-CWOzxb3o.cjs"));
218
221
  const f = new FederationImpl(options);
219
222
  const trailingSlashInsensitiveValue = f.router.trailingSlashInsensitive;
220
223
  f.router = this.router.clone();
@@ -782,6 +785,17 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
782
785
  return `collectionId="${collectionId}", url="${url}", digest="${(0, byte_encodings_hex.encodeHex)(await digest(actorIds))}"`;
783
786
  }
784
787
  //#endregion
788
+ //#region src/compat/attachment-arrays.ts
789
+ /**
790
+ * Applies the shared attachment workaround to served documents without
791
+ * rewriting any document that contains a semantic proof or LD signature.
792
+ * RDF equivalence alone cannot preserve JCS signatures.
793
+ * @internal
794
+ */
795
+ function normalizeAttachmentArrays(document, contextLoader) {
796
+ return require_proof.normalizeAttachmentArrays(document, contextLoader, true);
797
+ }
798
+ //#endregion
785
799
  //#region src/federation/inbox.ts
786
800
  /**
787
801
  * Checks whether an activity's ID and all of its actor IDs have the same
@@ -1123,13 +1137,10 @@ function acceptsJsonLd(request) {
1123
1137
  function isPlainObject(value) {
1124
1138
  return typeof value === "object" && value != null && !Array.isArray(value);
1125
1139
  }
1126
- function normalizeDateTimeLiteral(value) {
1127
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1128
- }
1129
1140
  function isMalformedDateTimeLiteral(value) {
1130
1141
  if (typeof value !== "string") return false;
1131
1142
  try {
1132
- Temporal.Instant.from(normalizeDateTimeLiteral(value));
1143
+ Temporal.Instant.from((0, _fedify_vocab_runtime_temporal.normalizeDateTimeLiteral)(value));
1133
1144
  return false;
1134
1145
  } catch {
1135
1146
  return true;
@@ -1167,7 +1178,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1167
1178
  if (typeof literal === "boolean") return false;
1168
1179
  if (typeof literal !== "string") return false;
1169
1180
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1170
- if (new Date(literal).toString() === "Invalid Date") return false;
1181
+ if (new Date(literal).toString() === "Invalid Date" && new Date((0, _fedify_vocab_runtime_temporal.normalizeDateTimeLiteral)(literal)).toString() === "Invalid Date") return false;
1171
1182
  return isMalformedDateTimeLiteral(literal);
1172
1183
  }
1173
1184
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1262,7 +1273,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1262
1273
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1263
1274
  }
1264
1275
  if (actor instanceof _fedify_vocab.Tombstone) {
1265
- const jsonLd = await actor.toJsonLd(context);
1276
+ const jsonLd = await serializeForResponse(actor, context);
1266
1277
  return new Response(JSON.stringify(jsonLd), {
1267
1278
  status: 410,
1268
1279
  headers: {
@@ -1271,7 +1282,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1271
1282
  }
1272
1283
  });
1273
1284
  }
1274
- const jsonLd = await actor.toJsonLd(context);
1285
+ const jsonLd = await serializeForResponse(actor, context);
1275
1286
  return new Response(JSON.stringify(jsonLd), { headers: {
1276
1287
  "Content-Type": "application/activity+json",
1277
1288
  Vary: "Accept"
@@ -1291,7 +1302,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1291
1302
  if (authorizePredicate != null) {
1292
1303
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1293
1304
  }
1294
- const jsonLd = await object.toJsonLd(context);
1305
+ const jsonLd = await serializeForResponse(object, context);
1295
1306
  return new Response(JSON.stringify(jsonLd), { headers: {
1296
1307
  "Content-Type": "application/activity+json",
1297
1308
  Vary: "Accept"
@@ -1422,7 +1433,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1422
1433
  if (collectionCallbacks.authorizePredicate != null) {
1423
1434
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
1424
1435
  }
1425
- const jsonLd = await collection.toJsonLd(context);
1436
+ const jsonLd = await serializeForResponse(collection, context);
1426
1437
  return new Response(JSON.stringify(jsonLd), { headers: {
1427
1438
  "Content-Type": "application/activity+json",
1428
1439
  Vary: "Accept"
@@ -1771,7 +1782,11 @@ async function handleInboxInternal(request, parameters, span) {
1771
1782
  }
1772
1783
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
1773
1784
  const jsonWithoutSig = require_proof.detachSignature(json);
1774
- const hasLdSignature = require_proof.hasSignature(json);
1785
+ const hasLdSignature = require_proof.hasVerifiableSignature(json);
1786
+ if (!hasLdSignature) {
1787
+ const shape = require_proof.describeSignatureShape(json);
1788
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
1789
+ }
1775
1790
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
1776
1791
  let deferredLdSignatureError = void 0;
1777
1792
  const respondInvalidActivity = async (error) => {
@@ -2250,7 +2265,7 @@ var CustomCollectionHandler = class {
2250
2265
  * @returns A promise that resolves to the JSON-LD representation.
2251
2266
  */
2252
2267
  async toJsonLd() {
2253
- return (await this.collection).toJsonLd(this.context);
2268
+ return serializeForResponse(await this.collection, this.context);
2254
2269
  }
2255
2270
  /**
2256
2271
  * Fetches the collection with optional cursor for pagination.
@@ -2553,7 +2568,7 @@ var UnauthorizedError = class extends HandlerError {
2553
2568
  * @since 0.3.0
2554
2569
  */
2555
2570
  async function respondWithObject(object, options) {
2556
- const jsonLd = await object.toJsonLd(options);
2571
+ const jsonLd = await serializeForResponse(object, options);
2557
2572
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
2558
2573
  }
2559
2574
  /**
@@ -2641,6 +2656,106 @@ const MIN_COMPONENTS = [
2641
2656
  "@target-uri",
2642
2657
  "@authority"
2643
2658
  ];
2659
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
2660
+ async function serializeForResponse(object, options) {
2661
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
2662
+ }
2663
+ //#endregion
2664
+ //#region src/sig/proof-creation.ts
2665
+ /** Signs the exact serialized message supplied by an internal producer. */
2666
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
2667
+ require_http.validateCryptoKey(privateKey, "private");
2668
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
2669
+ const encoder = new TextEncoder();
2670
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode((0, json_canon.default)(jsonLd)));
2671
+ created ??= Temporal.Now.instant();
2672
+ const proofConfig = {
2673
+ "@context": jsonLd["@context"],
2674
+ type: "DataIntegrityProof",
2675
+ cryptosuite: "eddsa-jcs-2022",
2676
+ verificationMethod: keyId.href,
2677
+ proofPurpose: "assertionMethod",
2678
+ created: created.toString()
2679
+ };
2680
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode((0, json_canon.default)(proofConfig)));
2681
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
2682
+ digest.set(new Uint8Array(proofDigest), 0);
2683
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
2684
+ const sig = await crypto.subtle.sign("Ed25519", (0, _fedify_vocab_runtime_internal.asCryptoKey)(privateKey), digest);
2685
+ return new _fedify_vocab.DataIntegrityProof({
2686
+ cryptosuite: "eddsa-jcs-2022",
2687
+ verificationMethod: keyId,
2688
+ proofPurpose: "assertionMethod",
2689
+ created,
2690
+ proofValue: new Uint8Array(sig)
2691
+ });
2692
+ }
2693
+ //#endregion
2694
+ //#region src/compat/delivery-jsonld.ts
2695
+ /**
2696
+ * Returns changed wire JSON only; unchanged documents keep the existing
2697
+ * delivery signing path. This uses ordinary vocabulary serialization, without
2698
+ * retaining or repairing independently signed child representations.
2699
+ */
2700
+ async function prepareActivityJsonLd(activity, contextLoader) {
2701
+ if (activity.proofIds.length > 0) return void 0;
2702
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
2703
+ const source = await activity.clone().toJsonLd({
2704
+ format: "compact",
2705
+ contextLoader
2706
+ });
2707
+ const prepared = await require_proof.normalizeOutgoingActivityJsonLd(source, contextLoader, true);
2708
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
2709
+ }
2710
+ /** Signs a changed, proof-free delivery map without serializing it again. */
2711
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
2712
+ const proofs = [];
2713
+ const serializedProofs = [];
2714
+ const tracer = (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version);
2715
+ for (const { privateKey, keyId } of keys) {
2716
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": (0, _fedify_vocab.getTypeId)(activity).href } }, async (span) => {
2717
+ try {
2718
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
2719
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
2720
+ if (span.isRecording()) {
2721
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
2722
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
2723
+ span.setAttribute("object_integrity_proofs.signature", (0, byte_encodings_hex.encodeHex)(proof.proofValue));
2724
+ }
2725
+ return proof;
2726
+ } catch (error) {
2727
+ span.setStatus({
2728
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
2729
+ message: String(error)
2730
+ });
2731
+ throw error;
2732
+ } finally {
2733
+ span.end();
2734
+ }
2735
+ });
2736
+ proofs.push(proof);
2737
+ serializedProofs.push({
2738
+ "@context": unsigned["@context"],
2739
+ type: "DataIntegrityProof",
2740
+ cryptosuite: proof.cryptosuite,
2741
+ verificationMethod: keyId.href,
2742
+ proofPurpose: "assertionMethod",
2743
+ created: proof.created.toString(),
2744
+ proofValue: new TextDecoder().decode((0, _fedify_vocab_runtime.encodeMultibase)("base58btc", proof.proofValue))
2745
+ });
2746
+ }
2747
+ if (proofs.length === 0) return {
2748
+ activity,
2749
+ jsonLd: unsigned
2750
+ };
2751
+ return {
2752
+ activity: activity.clone({ proofs }),
2753
+ jsonLd: {
2754
+ ...unsigned,
2755
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
2756
+ }
2757
+ };
2758
+ }
2644
2759
  //#endregion
2645
2760
  //#region src/nodeinfo/handler.ts
2646
2761
  /**
@@ -2740,7 +2855,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2740
2855
  * @param parameters The parameters for sending the activity.
2741
2856
  * See also {@link SendActivityParameters}.
2742
2857
  * @param deps The dependencies, for tests.
2743
- * @throws {Error} If the activity fails to send.
2858
+ * @throws {FetchError} If the delivery times out before receiving a response.
2859
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
2744
2860
  */
2745
2861
  function sendActivity(options, deps = {}) {
2746
2862
  const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
@@ -2767,7 +2883,25 @@ function sendActivity(options, deps = {}) {
2767
2883
  });
2768
2884
  }
2769
2885
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
2770
- async function readLimitedResponseBody(response, maxBytes) {
2886
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
2887
+ function raceWithAbort(promise, signal) {
2888
+ if (signal.aborted) return Promise.reject(signal.reason);
2889
+ return new Promise((resolve, reject) => {
2890
+ const onAbort = () => {
2891
+ signal.removeEventListener("abort", onAbort);
2892
+ reject(signal.reason);
2893
+ };
2894
+ signal.addEventListener("abort", onAbort, { once: true });
2895
+ promise.then((value) => {
2896
+ signal.removeEventListener("abort", onAbort);
2897
+ resolve(value);
2898
+ }, (error) => {
2899
+ signal.removeEventListener("abort", onAbort);
2900
+ reject(error);
2901
+ });
2902
+ });
2903
+ }
2904
+ async function readLimitedResponseBody(response, maxBytes, signal) {
2771
2905
  if (response.body == null) return "";
2772
2906
  const reader = response.body.getReader();
2773
2907
  const decoder = new TextDecoder();
@@ -2776,7 +2910,8 @@ async function readLimitedResponseBody(response, maxBytes) {
2776
2910
  let truncated = false;
2777
2911
  try {
2778
2912
  while (true) {
2779
- const { done, value } = await reader.read();
2913
+ signal.throwIfAborted();
2914
+ const { done, value } = await raceWithAbort(reader.read(), signal);
2780
2915
  if (done) break;
2781
2916
  if (totalBytes + value.length > maxBytes) {
2782
2917
  const remaining = maxBytes - totalBytes;
@@ -2788,8 +2923,10 @@ async function readLimitedResponseBody(response, maxBytes) {
2788
2923
  totalBytes += value.length;
2789
2924
  }
2790
2925
  } finally {
2791
- if (truncated) reader.cancel().catch(() => {});
2792
- reader.releaseLock();
2926
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
2927
+ try {
2928
+ reader.releaseLock();
2929
+ } catch (_) {}
2793
2930
  }
2794
2931
  let result = chunks.join("");
2795
2932
  if (truncated) result += "… (truncated)";
@@ -2801,12 +2938,24 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2801
2938
  "federation",
2802
2939
  "outbox"
2803
2940
  ]);
2804
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? _fedify_vocab_runtime_internal.openDirectFetch : (url) => (0, _fedify_vocab_runtime_internal.openPublicFetch)(url));
2941
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
2942
+ const controller = new AbortController();
2943
+ const { signal } = controller;
2944
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? _fedify_vocab_runtime_internal.openDirectFetch : (url) => (0, _fedify_vocab_runtime_internal.openPublicFetch)(url, { signal }));
2805
2945
  let opened = false;
2806
2946
  async function openHop(url) {
2807
2947
  let session;
2808
2948
  try {
2809
- session = await openUnvalidatedHop(url);
2949
+ signal.throwIfAborted();
2950
+ const opening = openUnvalidatedHop(url);
2951
+ opening.then((lateSession) => {
2952
+ if (signal.aborted) closeAfterError(lateSession, logger);
2953
+ }, () => {});
2954
+ session = await raceWithAbort(opening, signal);
2955
+ if (signal.aborted) {
2956
+ closeAfterError(session, logger);
2957
+ signal.throwIfAborted();
2958
+ }
2810
2959
  } catch (error) {
2811
2960
  if (error instanceof _fedify_vocab_runtime.UrlError && error.reason === "dns") {
2812
2961
  logger.error("DNS resolution failed for URL: {url}", {
@@ -2832,7 +2981,8 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2832
2981
  method: "POST",
2833
2982
  headers,
2834
2983
  body: JSON.stringify(activity),
2835
- redirect: "manual"
2984
+ redirect: "manual",
2985
+ signal
2836
2986
  });
2837
2987
  let rsaKey = null;
2838
2988
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -2847,18 +2997,48 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2847
2997
  }))
2848
2998
  });
2849
2999
  let outcome;
3000
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
3001
+ determineSpec(origin) {
3002
+ signal.throwIfAborted();
3003
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
3004
+ },
3005
+ rememberSpec(origin, spec) {
3006
+ if (signal.aborted) return;
3007
+ try {
3008
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
3009
+ origin,
3010
+ error
3011
+ }));
3012
+ } catch (error) {
3013
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
3014
+ origin,
3015
+ error
3016
+ });
3017
+ }
3018
+ }
3019
+ };
3020
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
2850
3021
  try {
2851
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox)) : await require_http.doubleKnockScoped(request, rsaKey, {
3022
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await require_http.doubleKnockScoped(request, rsaKey, {
2852
3023
  tracerProvider,
2853
- specDeterminer
2854
- }, openHop, (response) => consumeSendActivityResponse(response, inbox));
3024
+ specDeterminer: boundedSpecDeterminer,
3025
+ signal
3026
+ }, openHop, (response) => consumeSendActivityResponse(response, inbox, signal));
2855
3027
  } catch (error) {
2856
- if (opened) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
3028
+ let failureError = error;
3029
+ if (signal.aborted && !(error instanceof SendActivityError)) {
3030
+ const failure = new _fedify_vocab_runtime.FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
3031
+ failure.cause = signal.reason;
3032
+ failureError = failure;
3033
+ }
3034
+ if (opened || signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
2857
3035
  activityId,
2858
3036
  inbox: inbox.href,
2859
- error
3037
+ error: failureError
2860
3038
  });
2861
- throw error;
3039
+ throw failureError;
3040
+ } finally {
3041
+ clearTimeout(timer);
2862
3042
  }
2863
3043
  if (!outcome.ok) {
2864
3044
  const { status, statusText, error } = outcome;
@@ -2900,17 +3080,18 @@ function cancelResponseBody(response, url) {
2900
3080
  * session is open: the body of a successful response is cancelled, and at
2901
3081
  * most 1 KiB of an error response body is read.
2902
3082
  */
2903
- async function consumeSendActivityResponse(response, inbox) {
3083
+ async function consumeSendActivityResponse(response, inbox, signal) {
2904
3084
  if (response.ok) {
2905
3085
  cancelResponseBody(response, response.url || inbox.href);
2906
3086
  return { ok: true };
2907
3087
  }
2908
3088
  let error;
2909
3089
  try {
2910
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
3090
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
2911
3091
  } catch (_) {
2912
3092
  error = "";
2913
3093
  }
3094
+ if (signal.aborted) error = "(timed out reading response body)";
2914
3095
  return {
2915
3096
  ok: false,
2916
3097
  status: response.status,
@@ -2929,7 +3110,7 @@ async function consumeSendActivityResponse(response, inbox) {
2929
3110
  * @param consume The function to consume the final response.
2930
3111
  * @returns The value returned by `consume`.
2931
3112
  */
2932
- async function fetchWithValidatedRedirects(request, openHop, consume) {
3113
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
2933
3114
  const logger = (0, _logtape_logtape.getLogger)([
2934
3115
  "fedify",
2935
3116
  "federation",
@@ -2937,10 +3118,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
2937
3118
  ]);
2938
3119
  let body = await request.clone().text();
2939
3120
  for (let redirects = 0;; redirects++) {
3121
+ signal?.throwIfAborted();
2940
3122
  const session = await openHop(request.url);
2941
3123
  let response;
2942
3124
  try {
2943
- response = await session.fetch(request, { redirect: "manual" });
3125
+ response = await session.fetch(request, {
3126
+ redirect: "manual",
3127
+ signal
3128
+ });
2944
3129
  } catch (error) {
2945
3130
  await closeAfterError(session, logger);
2946
3131
  throw error;
@@ -2990,7 +3175,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
2990
3175
  method,
2991
3176
  headers,
2992
3177
  body,
2993
- redirect: "manual"
3178
+ redirect: "manual",
3179
+ signal: signal ?? request.signal
2994
3180
  });
2995
3181
  }
2996
3182
  }
@@ -3347,8 +3533,25 @@ var FederationImpl = class extends FederationBuilderImpl {
3347
3533
  _getTracer() {
3348
3534
  return this.tracerProvider.getTracer(require_http.name, require_http.version);
3349
3535
  }
3536
+ /**
3537
+ * Starts listening on a queue, converting a synchronous throw into
3538
+ * a rejected promise.
3539
+ *
3540
+ * `MessageQueue.listen()` is documented to never reject, but some
3541
+ * implementations (e.g., `WorkersMessageQueue`) throw synchronously. Without
3542
+ * this normalization, one such throw aborts {@link _startQueueInternal} while
3543
+ * it is still collecting listener promises, so listeners started earlier are
3544
+ * never awaited and later queues are never started.
3545
+ */
3546
+ #listenQueue(queue, ctxData, signal) {
3547
+ try {
3548
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
3549
+ } catch (error) {
3550
+ return Promise.reject(error);
3551
+ }
3552
+ }
3350
3553
  async _startQueueInternal(ctxData, signal, queue) {
3351
- if (this.inboxQueue == null && this.outboxQueue == null) return;
3554
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
3352
3555
  const logger = (0, _logtape_logtape.getLogger)([
3353
3556
  "fedify",
3354
3557
  "federation",
@@ -3358,20 +3561,38 @@ var FederationImpl = class extends FederationBuilderImpl {
3358
3561
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
3359
3562
  logger.debug("Starting an inbox task worker.");
3360
3563
  this.inboxQueueStarted = true;
3361
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3564
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
3362
3565
  }
3363
3566
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
3364
3567
  logger.debug("Starting an outbox task worker.");
3365
3568
  this.outboxQueueStarted = true;
3366
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3569
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
3367
3570
  }
3368
3571
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
3369
3572
  logger.debug("Starting a fanout task worker.");
3370
3573
  this.fanoutQueueStarted = true;
3371
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3574
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
3372
3575
  }
3373
3576
  await Promise.all(promises);
3374
3577
  }
3578
+ /**
3579
+ * Starts the queue workers automatically, reporting a failure instead of
3580
+ * leaving the returned promise unobserved.
3581
+ *
3582
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
3583
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
3584
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
3585
+ * callers that start workers deliberately.
3586
+ */
3587
+ _startQueueAutomatically(ctxData) {
3588
+ this._startQueueInternal(ctxData).catch((error) => {
3589
+ (0, _logtape_logtape.getLogger)([
3590
+ "fedify",
3591
+ "federation",
3592
+ "queue"
3593
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
3594
+ });
3595
+ }
3375
3596
  processQueuedTask(contextData, message) {
3376
3597
  const tracer = this._getTracer();
3377
3598
  const extractedContext = _opentelemetry_api.propagation.extract(_opentelemetry_api.context.active(), message.traceContext);
@@ -3481,7 +3702,8 @@ var FederationImpl = class extends FederationBuilderImpl {
3481
3702
  collectionSync: message.collectionSync,
3482
3703
  orderingKey: message.orderingKey,
3483
3704
  normalizeExistingProofs: message.normalizeExistingProofs,
3484
- context
3705
+ context,
3706
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
3485
3707
  });
3486
3708
  }
3487
3709
  async #listenOutboxMessage(_, message, span) {
@@ -3684,7 +3906,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3684
3906
  let parseInput = void 0;
3685
3907
  let parseContextLoader = context.contextLoader;
3686
3908
  try {
3687
- const hasSignatureField = require_proof.hasSignature(message.activity);
3909
+ const hasSignatureField = require_proof.hasVerifiableSignature(message.activity);
3688
3910
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
3689
3911
  const parseContext = hasSignatureField ? {
3690
3912
  ...context,
@@ -3880,21 +4102,31 @@ var FederationImpl = class extends FederationBuilderImpl {
3880
4102
  hasProof = true;
3881
4103
  break;
3882
4104
  }
3883
- if (!hasProof) {
3884
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3885
- activity = await require_proof.signObject(activity, privateKey, keyId, {
3886
- contextLoader,
3887
- tracerProvider: this.tracerProvider
3888
- });
3889
- hasProof = true;
3890
- proofCreated = true;
4105
+ const prepared = !hasProof && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
4106
+ let jsonLd;
4107
+ if (prepared != null) {
4108
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
4109
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
4110
+ activity = signed.activity;
4111
+ jsonLd = signed.jsonLd;
4112
+ proofCreated = signingKeys.length > 0;
4113
+ } else {
4114
+ if (!hasProof) {
4115
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
4116
+ activity = await require_proof.signObject(activity, privateKey, keyId, {
4117
+ contextLoader,
4118
+ tracerProvider: this.tracerProvider
4119
+ });
4120
+ proofCreated = true;
4121
+ }
3891
4122
  }
4123
+ jsonLd = options.activityJsonLd != null ? require_proof.detachSignature(options.activityJsonLd) : await activity.toJsonLd({
4124
+ format: "compact",
4125
+ contextLoader
4126
+ });
3892
4127
  }
3893
- let jsonLd = await activity.toJsonLd({
3894
- format: "compact",
3895
- contextLoader
3896
- });
3897
- if (proofCreated || !hasProof || options.normalizeExistingProofs) jsonLd = await require_proof.normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
4128
+ if (prepared == null && (proofCreated || !hasProof || options.normalizeExistingProofs)) jsonLd = await require_proof.normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
4129
+ hasProof ||= proofCreated;
3898
4130
  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.", {
3899
4131
  activityId,
3900
4132
  keys: keys.map((pair) => ({
@@ -3931,19 +4163,27 @@ var FederationImpl = class extends FederationBuilderImpl {
3931
4163
  activity: jsonLd
3932
4164
  });
3933
4165
  const promises = [];
3934
- for (const inbox in inboxes) promises.push(sendActivity({
3935
- allowPrivateAddress: this.allowPrivateAddress,
3936
- keys,
3937
- activity: jsonLd,
3938
- activityId: activity.id?.href,
3939
- activityType: (0, _fedify_vocab.getTypeId)(activity).href,
3940
- inbox: new URL(inbox),
3941
- sharedInbox: inboxes[inbox].sharedInbox,
3942
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3943
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3944
- tracerProvider: this.tracerProvider
3945
- }));
3946
- await Promise.all(promises);
4166
+ try {
4167
+ for (const inbox in inboxes) {
4168
+ const promise = sendActivity({
4169
+ allowPrivateAddress: this.allowPrivateAddress,
4170
+ keys,
4171
+ activity: jsonLd,
4172
+ activityId: activity.id?.href,
4173
+ activityType: (0, _fedify_vocab.getTypeId)(activity).href,
4174
+ inbox: new URL(inbox),
4175
+ sharedInbox: inboxes[inbox].sharedInbox,
4176
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
4177
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
4178
+ tracerProvider: this.tracerProvider
4179
+ });
4180
+ promise.catch(() => {});
4181
+ promises.push(promise);
4182
+ }
4183
+ await Promise.all(promises);
4184
+ } finally {
4185
+ await Promise.allSettled(promises);
4186
+ }
3947
4187
  return;
3948
4188
  }
3949
4189
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -3958,7 +4198,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3958
4198
  privateKey: privateKeyJwk
3959
4199
  });
3960
4200
  }
3961
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
4201
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
3962
4202
  const carrier = {};
3963
4203
  _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), carrier);
3964
4204
  const messages = [];
@@ -4191,7 +4431,7 @@ var FederationImpl = class extends FederationBuilderImpl {
4191
4431
  const identity = await this.sharedInboxKeyDispatcher(context);
4192
4432
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
4193
4433
  }
4194
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
4434
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
4195
4435
  const inboxContextFactory = context.toInboxContext.bind(context);
4196
4436
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
4197
4437
  return await handleInbox(request, {
@@ -4524,6 +4764,8 @@ var ContextImpl = class ContextImpl {
4524
4764
  for (const keyPair of keyPairs) {
4525
4765
  const newPair = {
4526
4766
  ...keyPair,
4767
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(keyPair.privateKey),
4768
+ publicKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(keyPair.publicKey),
4527
4769
  cryptographicKey: new _fedify_vocab.CryptographicKey({
4528
4770
  id: keyPair.keyId,
4529
4771
  owner,
@@ -4600,10 +4842,16 @@ var ContextImpl = class ContextImpl {
4600
4842
  } else identifierPromise = Promise.resolve(identity.identifier);
4601
4843
  return identifierPromise.then((identifier) => {
4602
4844
  if (identifier == null) return this.documentLoader;
4603
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
4845
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
4846
+ keyId: pair.keyId,
4847
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(pair.privateKey)
4848
+ }));
4604
4849
  });
4605
4850
  }
4606
- return this.federation.authenticatedDocumentLoaderFactory(identity);
4851
+ return this.federation.authenticatedDocumentLoaderFactory({
4852
+ keyId: identity.keyId,
4853
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(identity.privateKey)
4854
+ });
4607
4855
  }
4608
4856
  lookupObject(identifier, options = {}) {
4609
4857
  return (0, _fedify_vocab.lookupObject)(identifier, {
@@ -4626,10 +4874,14 @@ var ContextImpl = class ContextImpl {
4626
4874
  return options.parse === "none" ? require_types.getNodeInfo(url, {
4627
4875
  parse: "none",
4628
4876
  direct: options.direct,
4877
+ timeout: options.timeout,
4878
+ signal: options.signal,
4629
4879
  userAgent: options?.userAgent ?? this.federation.userAgent
4630
4880
  }) : require_types.getNodeInfo(url, {
4631
4881
  parse: options.parse,
4632
4882
  direct: options.direct,
4883
+ timeout: options.timeout,
4884
+ signal: options.signal,
4633
4885
  userAgent: options?.userAgent ?? this.federation.userAgent
4634
4886
  });
4635
4887
  }
@@ -4641,7 +4893,17 @@ var ContextImpl = class ContextImpl {
4641
4893
  allowPrivateAddress: this.federation.allowPrivateAddress
4642
4894
  });
4643
4895
  }
4644
- sendActivity(sender, recipients, activity, options = {}) {
4896
+ async sendActivity(sender, recipients, activity, options = {}) {
4897
+ let activityJsonLd = void 0;
4898
+ let hasProof = activity.proofIds.length > 0;
4899
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
4900
+ hasProof = true;
4901
+ break;
4902
+ }
4903
+ if (hasProof) {
4904
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
4905
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
4906
+ }
4645
4907
  return this.tracerProvider.getTracer(require_http.name, require_http.version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
4646
4908
  kind: this.federation.outboxQueue == null || options.immediate ? _opentelemetry_api.SpanKind.CLIENT : _opentelemetry_api.SpanKind.PRODUCER,
4647
4909
  attributes: {
@@ -4654,7 +4916,7 @@ var ContextImpl = class ContextImpl {
4654
4916
  }, async (span) => {
4655
4917
  try {
4656
4918
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
4657
- await this.sendActivityInternal(sender, recipients, activity, options, span);
4919
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
4658
4920
  } catch (e) {
4659
4921
  span.setStatus({
4660
4922
  code: _opentelemetry_api.SpanStatusCode.ERROR,
@@ -4666,7 +4928,7 @@ var ContextImpl = class ContextImpl {
4666
4928
  }
4667
4929
  });
4668
4930
  }
4669
- async sendActivityInternal(sender, recipients, activity, options, span) {
4931
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
4670
4932
  const logger = (0, _logtape_logtape.getLogger)([
4671
4933
  "fedify",
4672
4934
  "federation",
@@ -4713,15 +4975,23 @@ var ContextImpl = class ContextImpl {
4713
4975
  if (!(error instanceof RouterError)) throw error;
4714
4976
  }
4715
4977
  } else expandedRecipients = [recipients];
4716
- const opts = {
4717
- context: this,
4718
- orderingKey: options.orderingKey,
4719
- collectionSync,
4720
- immediate: options.immediate,
4721
- normalizeExistingProofs: options.normalizeExistingProofs
4722
- };
4723
4978
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
4724
4979
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
4980
+ let contextMatches = false;
4981
+ if (activityJsonLd != null) {
4982
+ const capturedJsonLd = activityJsonLd;
4983
+ const transformedJsonLd = await activity.toJsonLd({
4984
+ format: "compact",
4985
+ contextLoader: this.contextLoader
4986
+ });
4987
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
4988
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
4989
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
4990
+ if (contentChanged || !contextMatches && proofsChanged) {
4991
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) });
4992
+ activityJsonLd = void 0;
4993
+ } else if (proofsChanged) activityJsonLd = void 0;
4994
+ }
4725
4995
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
4726
4996
  if (activity.actorId == null) {
4727
4997
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -4733,15 +5003,42 @@ var ContextImpl = class ContextImpl {
4733
5003
  let proofCreated = false;
4734
5004
  if (actorKeyPairs != null) {
4735
5005
  const contextLoader = this.contextLoader;
4736
- for (const kp of actorKeyPairs) {
4737
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4738
- activity = await require_proof.signObject(activity, kp.privateKey, kp.multikey.id, {
4739
- contextLoader,
4740
- tracerProvider: this.tracerProvider
4741
- });
4742
- proofCreated = true;
5006
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
5007
+ if (willSign) {
5008
+ if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
5009
+ }
5010
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
5011
+ if (prepared != null) {
5012
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
5013
+ privateKey: kp.privateKey,
5014
+ keyId: kp.multikey.id
5015
+ }] : []);
5016
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
5017
+ activity = signed.activity;
5018
+ activityJsonLd = signed.jsonLd;
5019
+ proofCreated = signingKeys.length > 0;
5020
+ } else {
5021
+ let proofAdded = false;
5022
+ for (const kp of actorKeyPairs) {
5023
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
5024
+ activity = await require_proof.signObject(activity, kp.privateKey, kp.multikey.id, {
5025
+ contextLoader,
5026
+ tracerProvider: this.tracerProvider
5027
+ });
5028
+ proofAdded = true;
5029
+ }
5030
+ if (proofAdded) activityJsonLd = void 0;
5031
+ proofCreated = proofAdded;
4743
5032
  }
4744
5033
  }
5034
+ const opts = {
5035
+ context: this,
5036
+ orderingKey: options.orderingKey,
5037
+ collectionSync,
5038
+ immediate: options.immediate,
5039
+ activityJsonLd,
5040
+ normalizeExistingProofs: options.normalizeExistingProofs
5041
+ };
4745
5042
  const inboxes = extractInboxes({
4746
5043
  recipients: expandedRecipients,
4747
5044
  preferSharedInbox: options.preferSharedInbox,
@@ -4781,7 +5078,7 @@ var ContextImpl = class ContextImpl {
4781
5078
  actorIds: [...actorIds],
4782
5079
  sharedInbox
4783
5080
  }])),
4784
- activity: await activity.toJsonLd({
5081
+ activity: activityJsonLd != null ? require_proof.detachSignature(activityJsonLd) : await activity.toJsonLd({
4785
5082
  format: "compact",
4786
5083
  contextLoader: this.contextLoader
4787
5084
  }),
@@ -4792,7 +5089,7 @@ var ContextImpl = class ContextImpl {
4792
5089
  normalizeExistingProofs: proofCreated || options.normalizeExistingProofs,
4793
5090
  traceContext: carrier
4794
5091
  };
4795
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
5092
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
4796
5093
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
4797
5094
  return true;
4798
5095
  }
@@ -5119,7 +5416,7 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
5119
5416
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
5120
5417
  keys = forwarder;
5121
5418
  } else keys = [forwarder];
5122
- if (!require_proof.hasSignatureLike(ctx.activity)) {
5419
+ if (!require_proof.hasVerifiableSignature(ctx.activity) && !require_proof.hasSignatureLike(ctx.activity)) {
5123
5420
  if (!require_proof.hasProofLike(ctx.activity)) {
5124
5421
  if (options?.skipIfUnsigned) return false;
5125
5422
  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.", {
@@ -5157,25 +5454,33 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
5157
5454
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
5158
5455
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
5159
5456
  const promises = [];
5160
- for (const inbox in inboxes) promises.push(sendActivity({
5161
- allowPrivateAddress: ctx.federation.allowPrivateAddress,
5162
- keys,
5163
- activity: ctx.activity,
5164
- activityId: ctx.activityId,
5165
- activityType: ctx.activityType,
5166
- inbox: new URL(inbox),
5167
- sharedInbox: inboxes[inbox].sharedInbox,
5168
- tracerProvider: ctx.tracerProvider,
5169
- specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
5170
- }));
5171
- await Promise.all(promises);
5457
+ try {
5458
+ for (const inbox in inboxes) {
5459
+ const promise = sendActivity({
5460
+ allowPrivateAddress: ctx.federation.allowPrivateAddress,
5461
+ keys,
5462
+ activity: ctx.activity,
5463
+ activityId: ctx.activityId,
5464
+ activityType: ctx.activityType,
5465
+ inbox: new URL(inbox),
5466
+ sharedInbox: inboxes[inbox].sharedInbox,
5467
+ tracerProvider: ctx.tracerProvider,
5468
+ specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
5469
+ });
5470
+ promise.catch(() => {});
5471
+ promises.push(promise);
5472
+ }
5473
+ await Promise.all(promises);
5474
+ } finally {
5475
+ await Promise.allSettled(promises);
5476
+ }
5172
5477
  return true;
5173
5478
  }
5174
5479
  logger.debug("Enqueuing activity {activityId} to forward later.", {
5175
5480
  activityId: ctx.activityId,
5176
5481
  activity: ctx.activity
5177
5482
  });
5178
- if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
5483
+ if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueAutomatically(ctx.data);
5179
5484
  const keyJwkPairs = [];
5180
5485
  for (const { keyId, privateKey } of keys) {
5181
5486
  const privateKeyJwk = await require_http.exportJwk(privateKey);
@@ -5347,6 +5652,69 @@ var KvSpecDeterminer = class {
5347
5652
  function notFound(_request) {
5348
5653
  return new Response("Not Found", { status: 404 });
5349
5654
  }
5655
+ function hasTopLevelProof(value) {
5656
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
5657
+ }
5658
+ function getContentFields(value) {
5659
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5660
+ const record = { ...value };
5661
+ delete record["@context"];
5662
+ delete record.proof;
5663
+ delete record.signature;
5664
+ return JSON.stringify(sortJsonKeys(record));
5665
+ }
5666
+ function getContextFields(value) {
5667
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5668
+ const context = value["@context"];
5669
+ return JSON.stringify(sortJsonKeys(context ?? null));
5670
+ }
5671
+ function getProofEntries(value) {
5672
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
5673
+ const proof = value.proof;
5674
+ if (proof == null) return [];
5675
+ return Array.isArray(proof) ? proof : [proof];
5676
+ }
5677
+ function normalizeProofEntry(proof) {
5678
+ const stripped = stripContexts(proof);
5679
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
5680
+ const record = { ...stripped };
5681
+ if (typeof record.created === "string") try {
5682
+ record.created = Temporal.Instant.from(record.created).toString();
5683
+ } catch {}
5684
+ return record;
5685
+ }
5686
+ function getProofEntryFields(proof) {
5687
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
5688
+ }
5689
+ function getProofFields(value) {
5690
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
5691
+ }
5692
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
5693
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
5694
+ const retainedProofs = [];
5695
+ for await (const proof of activity.getProofs({ contextLoader })) {
5696
+ const proofJsonLd = await proof.toJsonLd({
5697
+ format: "compact",
5698
+ contextLoader
5699
+ });
5700
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
5701
+ }
5702
+ return retainedProofs;
5703
+ }
5704
+ function stripContexts(value) {
5705
+ if (Array.isArray(value)) return value.map(stripContexts);
5706
+ if (typeof value !== "object" || value == null) return value;
5707
+ const record = { ...value };
5708
+ delete record["@context"];
5709
+ delete record.signature;
5710
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
5711
+ return record;
5712
+ }
5713
+ function sortJsonKeys(value) {
5714
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
5715
+ if (typeof value !== "object" || value == null) return value;
5716
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
5717
+ }
5350
5718
  function notAcceptable(_request) {
5351
5719
  return new Response("Not Acceptable", {
5352
5720
  status: 406,