@fedify/fedify 2.1.31 → 2.1.32

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 (97) hide show
  1. package/dist/attachment-arrays-DZ4JHJD8.mjs +111 -0
  2. package/dist/{builder-isMRh_I6.mjs → builder--sc-rozj.mjs} +3 -3
  3. package/dist/callback-BARPujV7.d.mts +2388 -0
  4. package/dist/{client-BIBzqEIp.d.cts → client-9DPcy_Yx.d.ts} +16 -0
  5. package/dist/{client-jE7oGvRh.d.ts → client-B3ruDgWg.d.cts} +16 -0
  6. package/dist/{client-BZr7TGyu.mjs → client-cpPaW7Ww.mjs} +86 -11
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +254 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/transformers.test.mjs +1 -1
  12. package/dist/{context-C0uGVzgk.d.ts → context-DE2YrQwM.d.ts} +30 -13
  13. package/dist/{context-CLaLxi49.d.cts → context-y6ZUQCMf.d.cts} +30 -13
  14. package/dist/{deno-CiaJqTcu.mjs → deno-L23b3Hba.mjs} +1 -1
  15. package/dist/{docloader-DOrwedT7.mjs → docloader-DUXr9k_O.mjs} +2 -2
  16. package/dist/federation/attachment-responses.test.d.mts +2 -0
  17. package/dist/federation/attachment-responses.test.mjs +182 -0
  18. package/dist/federation/builder.test.mjs +1 -1
  19. package/dist/federation/collection.test.mjs +1 -1
  20. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  21. package/dist/federation/delivery-attachments.test.mjs +280 -0
  22. package/dist/federation/handler.test.mjs +208 -16
  23. package/dist/federation/idempotency.test.mjs +2 -2
  24. package/dist/federation/inbox.test.mjs +1 -1
  25. package/dist/federation/middleware.test.mjs +1185 -8
  26. package/dist/federation/mod.cjs +1 -1
  27. package/dist/federation/mod.d.cts +2 -2
  28. package/dist/federation/mod.d.ts +2 -2
  29. package/dist/federation/mod.js +1 -1
  30. package/dist/federation/negotiation.test.mjs +1 -1
  31. package/dist/federation/retry.test.mjs +1 -1
  32. package/dist/federation/send.test.mjs +283 -3
  33. package/dist/federation/temporal.test.mjs +25 -1
  34. package/dist/federation/webfinger.test.mjs +1 -1
  35. package/dist/{http-Crml3gei.js → http-BtbMAgTA.js} +6 -4
  36. package/dist/{http-9IFUxdkp.d.cts → http-C8qLHs_Z.d.cts} +3 -3
  37. package/dist/{http-CRiVlZd5.cjs → http-D5woFKA_.cjs} +6 -4
  38. package/dist/{http-SbfezERn.d.ts → http-D8WmcRAF.d.ts} +3 -3
  39. package/dist/{http-A9mP2uM7.mjs → http-HX6wVyJh.mjs} +6 -4
  40. package/dist/{inbox-KESLudq4.mjs → inbox-CL7A0HXT.mjs} +1 -1
  41. package/dist/{key-Dg6-DV_O.mjs → key-Dai3f5yI.mjs} +3 -2
  42. package/dist/{kv-cache-Cqmm-yQa.cjs → kv-cache-B0V_e231.cjs} +1 -1
  43. package/dist/{kv-cache-DQcyZL5T.js → kv-cache-BsDg-cT8.js} +1 -1
  44. package/dist/{ld-COjDN6Nb.mjs → ld-DN6x1iZ8.mjs} +153 -21
  45. package/dist/ld-signature-DoZcbsZR.mjs +23 -0
  46. package/dist/{middleware-BtDQUCcz.cjs → middleware-Cl6k5Hrm.cjs} +1 -1
  47. package/dist/{middleware-BbgR7xOI.cjs → middleware-CrfRuKCf.cjs} +561 -101
  48. package/dist/{middleware-COFlKeYn.mjs → middleware-DiquMgtt.mjs} +378 -89
  49. package/dist/{middleware-DIW5S_5L.js → middleware-DunNtbo9.js} +560 -101
  50. package/dist/{middleware-CuQvczZd.mjs → middleware-SnQS8eIb.mjs} +1 -1
  51. package/dist/{mod-LOEOKbYd.d.cts → mod-CehHJOV4.d.cts} +30 -13
  52. package/dist/{mod-CFRocFeQ.d.ts → mod-DLJpnqdw.d.ts} +1 -1
  53. package/dist/{mod-C7w-QVUv.d.ts → mod-Mh3oIuRK.d.ts} +30 -13
  54. package/dist/{mod-BRnwh2oy.d.ts → mod-REfljt0T.d.ts} +3 -3
  55. package/dist/{mod-Co7LEK9X.d.cts → mod-UvIGUHqW.d.cts} +3 -3
  56. package/dist/{mod-CGUH8Ujp.d.cts → mod-sTa1Zzxk.d.cts} +1 -1
  57. package/dist/mod.cjs +5 -5
  58. package/dist/mod.d.cts +8 -8
  59. package/dist/mod.d.ts +8 -8
  60. package/dist/mod.js +5 -5
  61. package/dist/nodeinfo/client.test.mjs +432 -5
  62. package/dist/nodeinfo/handler.test.mjs +1 -1
  63. package/dist/nodeinfo/mod.cjs +1 -1
  64. package/dist/nodeinfo/mod.d.cts +1 -1
  65. package/dist/nodeinfo/mod.d.ts +1 -1
  66. package/dist/nodeinfo/mod.js +1 -1
  67. package/dist/nodeinfo/types.test.mjs +1 -1
  68. package/dist/{owner-CFHq61cq.mjs → owner-DwyDorZI.mjs} +2 -2
  69. package/dist/{proof-0JkSC_pT.cjs → proof-Be-4K4jn.cjs} +193 -46
  70. package/dist/{proof-KSHlbPCG.mjs → proof-DYjmyrHh.mjs} +38 -13
  71. package/dist/{proof-DzksJFK7.js → proof-Du4-5SHY.js} +187 -46
  72. package/dist/{send-DaDe2YCb.mjs → send-BGSfQkIK.mjs} +92 -21
  73. package/dist/sig/http.test.mjs +2 -2
  74. package/dist/sig/key-types.test.d.mts +218 -0
  75. package/dist/sig/key-types.test.mjs +8 -0
  76. package/dist/sig/key.test.mjs +2 -2
  77. package/dist/sig/ld.test.mjs +573 -8
  78. package/dist/sig/mod.cjs +2 -2
  79. package/dist/sig/mod.d.cts +3 -3
  80. package/dist/sig/mod.d.ts +3 -3
  81. package/dist/sig/mod.js +2 -2
  82. package/dist/sig/owner.test.mjs +1 -1
  83. package/dist/sig/proof.test.mjs +95 -3
  84. package/dist/{temporal-DNGH8o2E.mjs → temporal-CNCchWly.mjs} +3 -5
  85. package/dist/testing/mod.d.mts +2 -2203
  86. package/dist/{types-DOvyymM4.cjs → types-B5wRhemi.cjs} +85 -10
  87. package/dist/{types-B1_pRFE_.js → types-CXy2lRVU.js} +86 -11
  88. package/dist/utils/docloader.test.mjs +2 -2
  89. package/dist/utils/mod.cjs +1 -1
  90. package/dist/utils/mod.d.cts +1 -1
  91. package/dist/utils/mod.d.ts +1 -1
  92. package/dist/utils/mod.js +1 -1
  93. package/package.json +6 -6
  94. /package/dist/{collection-BD6-SZ6O.mjs → collection-DnoYNwBC.mjs} +0 -0
  95. /package/dist/{negotiation-BehA2uul.mjs → negotiation-xb0QR3u_.mjs} +0 -0
  96. /package/dist/{retry-B_E3V_Dx.mjs → retry-CI1flGDD.mjs} +0 -0
  97. /package/dist/{types-DCP0WLdt.mjs → types-s4mCTGkT.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-CRiVlZd5.cjs");
6
- const require_types = require("./types-DOvyymM4.cjs");
7
- const require_proof = require("./proof-0JkSC_pT.cjs");
8
- const require_kv_cache = require("./kv-cache-Cqmm-yQa.cjs");
5
+ const require_http = require("./http-D5woFKA_.cjs");
6
+ const require_types = require("./types-B5wRhemi.cjs");
7
+ const require_proof = require("./proof-Be-4K4jn.cjs");
8
+ const require_kv_cache = require("./kv-cache-B0V_e231.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/inbox.ts
24
27
  var InboxListenerSet = class InboxListenerSet {
@@ -351,7 +354,7 @@ var FederationBuilderImpl = class {
351
354
  this.collectionTypeIds = {};
352
355
  }
353
356
  async build(options) {
354
- const { FederationImpl } = await Promise.resolve().then(() => require("./middleware-BtDQUCcz.cjs"));
357
+ const { FederationImpl } = await Promise.resolve().then(() => require("./middleware-Cl6k5Hrm.cjs"));
355
358
  const f = new FederationImpl(options);
356
359
  const trailingSlashInsensitiveValue = f.router.trailingSlashInsensitive;
357
360
  f.router = this.router.clone();
@@ -883,6 +886,110 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
883
886
  return `collectionId="${collectionId}", url="${url}", digest="${(0, byte_encodings_hex.encodeHex)(await digest(actorIds))}"`;
884
887
  }
885
888
  //#endregion
889
+ //#region src/compat/attachment-arrays.ts
890
+ const logger$1 = (0, _logtape_logtape.getLogger)([
891
+ "fedify",
892
+ "compat",
893
+ "attachment-arrays"
894
+ ]);
895
+ const MAX_DEPTH = 64;
896
+ const ATTACHMENT = "https://www.w3.org/ns/activitystreams#attachment";
897
+ const PROOF = "https://w3id.org/security#proof";
898
+ /** Recognizes JSON-LD maps without accepting arrays or scalar values. */
899
+ function isMap(value) {
900
+ return typeof value === "object" && value != null && !Array.isArray(value);
901
+ }
902
+ /** Copies only changed branches; cached vocabulary JSON belongs to its owner. */
903
+ function walk(value, depth = 0) {
904
+ if (depth >= MAX_DEPTH) throw new RangeError("JSON-LD nesting limit exceeded.");
905
+ if (Array.isArray(value)) {
906
+ const items = value.map((item) => walk(item, depth + 1));
907
+ return items.some((item, i) => item !== value[i]) ? items : value;
908
+ }
909
+ if (!isMap(value)) return value;
910
+ if (Object.hasOwn(value, "@value")) return value;
911
+ let result;
912
+ for (const [key, item] of Object.entries(value)) {
913
+ let next = key === "@context" ? item : walk(item, depth + 1);
914
+ if ((key === "attachment" || key === ATTACHMENT) && next != null && !Array.isArray(next) && !(isMap(next) && Object.hasOwn(next, "@list"))) next = [next];
915
+ if (next !== item) {
916
+ result ??= Object.assign(Object.create(null), value);
917
+ result[key] = next;
918
+ }
919
+ }
920
+ return result ?? value;
921
+ }
922
+ const preloadedLoader = (url) => {
923
+ if (!Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.reject(/* @__PURE__ */ new Error("Unknown JSON-LD context: " + url));
924
+ return Promise.resolve({
925
+ contextUrl: null,
926
+ documentUrl: url,
927
+ document: _fedify_vocab_runtime.preloadedContexts[url]
928
+ });
929
+ };
930
+ /** Reuses each context resolution across the complete equivalence check. */
931
+ function memoizeLoader(loader) {
932
+ const pending = /* @__PURE__ */ new Map();
933
+ return (url, options) => {
934
+ let result = pending.get(url);
935
+ if (result == null) {
936
+ result = loader(url, options);
937
+ pending.set(url, result);
938
+ }
939
+ return result;
940
+ };
941
+ }
942
+ /** Finds security predicates in expanded nodes, never inside JSON literals. */
943
+ function hasSecurityPredicate(value) {
944
+ if (Array.isArray(value)) return value.some(hasSecurityPredicate);
945
+ if (!isMap(value) || Object.hasOwn(value, "@value")) return false;
946
+ for (const [key, child] of Object.entries(value)) {
947
+ if (key === PROOF || key === "https://w3id.org/security#signature") return true;
948
+ if (hasSecurityPredicate(child)) return true;
949
+ }
950
+ return false;
951
+ }
952
+ /**
953
+ * Keeps singleton attachments in arrays for raw-JSON ActivityPub consumers.
954
+ * Mastodon's property_values() ignores valid compact JSON-LD scalar values,
955
+ * and its caller clears the profile fields in that case:
956
+ * https://github.com/mastodon/mastodon/blob/594166519a623584920c7e696bae9a009d9183ab/app/services/activitypub/process_account_service.rb#L465-L472
957
+ * Pixelfed likewise rejects singleton media attachments:
958
+ * https://github.com/pixelfed/pixelfed/issues/6588
959
+ *
960
+ * This workaround changes only attachment representation, after serialization.
961
+ * RDF equality protects custom contexts, including JSON literals; it does not
962
+ * protect JCS signatures. Any semantic proof or Linked Data signature leaves
963
+ * the whole serialized document unchanged, as does an unresolved context.
964
+ * This layer does not compose signed objects or repair vocabulary serialization.
965
+ * Remove this
966
+ * workaround only when the supported consumer versions, including deployed
967
+ * older releases, accept scalar attachments. Do not replace it with a
968
+ * vocabulary transformer: subsequent compaction collapses arrays.
969
+ * @internal
970
+ */
971
+ async function normalizeAttachmentArrays(document, contextLoader) {
972
+ try {
973
+ const normalized = walk(document);
974
+ if (normalized === document) return document;
975
+ const loader = memoizeLoader(contextLoader ?? preloadedLoader);
976
+ if (hasSecurityPredicate(await _fedify_vocab_runtime_jsonld.default.expand(document, { documentLoader: loader }))) return document;
977
+ const [before, after] = await Promise.allSettled([_fedify_vocab_runtime_jsonld.default.canonize(document, {
978
+ format: "application/n-quads",
979
+ documentLoader: loader
980
+ }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
981
+ format: "application/n-quads",
982
+ documentLoader: loader
983
+ })]);
984
+ if (before.status === "rejected") throw before.reason;
985
+ if (after.status === "rejected") throw after.reason;
986
+ if (before.value === after.value) return normalized;
987
+ } catch (error) {
988
+ logger$1.debug("Could not safely normalize attachment arrays; preserving the document: {error}", { error });
989
+ }
990
+ return document;
991
+ }
992
+ //#endregion
886
993
  //#region src/federation/keycache.ts
887
994
  const KEY_CACHE_GENERATION = "3";
888
995
  var KvKeyCache = class {
@@ -1070,13 +1177,10 @@ function acceptsJsonLd(request) {
1070
1177
  function isPlainObject(value) {
1071
1178
  return typeof value === "object" && value != null && !Array.isArray(value);
1072
1179
  }
1073
- function normalizeDateTimeLiteral(value) {
1074
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1075
- }
1076
1180
  function isMalformedDateTimeLiteral(value) {
1077
1181
  if (typeof value !== "string") return false;
1078
1182
  try {
1079
- Temporal.Instant.from(normalizeDateTimeLiteral(value));
1183
+ Temporal.Instant.from((0, _fedify_vocab_runtime_temporal.normalizeDateTimeLiteral)(value));
1080
1184
  return false;
1081
1185
  } catch {
1082
1186
  return true;
@@ -1114,7 +1218,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1114
1218
  if (typeof literal === "boolean") return false;
1115
1219
  if (typeof literal !== "string") return false;
1116
1220
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1117
- if (new Date(literal).toString() === "Invalid Date") return false;
1221
+ if (new Date(literal).toString() === "Invalid Date" && new Date((0, _fedify_vocab_runtime_temporal.normalizeDateTimeLiteral)(literal)).toString() === "Invalid Date") return false;
1118
1222
  return isMalformedDateTimeLiteral(literal);
1119
1223
  }
1120
1224
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1208,7 +1312,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1208
1312
  if (authorizePredicate != null) {
1209
1313
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1210
1314
  }
1211
- const jsonLd = await actor.toJsonLd(context);
1315
+ const jsonLd = await serializeForResponse(actor, context);
1212
1316
  return new Response(JSON.stringify(jsonLd), { headers: {
1213
1317
  "Content-Type": "application/activity+json",
1214
1318
  Vary: "Accept"
@@ -1228,7 +1332,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1228
1332
  if (authorizePredicate != null) {
1229
1333
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1230
1334
  }
1231
- const jsonLd = await object.toJsonLd(context);
1335
+ const jsonLd = await serializeForResponse(object, context);
1232
1336
  return new Response(JSON.stringify(jsonLd), { headers: {
1233
1337
  "Content-Type": "application/activity+json",
1234
1338
  Vary: "Accept"
@@ -1359,7 +1463,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1359
1463
  if (collectionCallbacks.authorizePredicate != null) {
1360
1464
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
1361
1465
  }
1362
- const jsonLd = await collection.toJsonLd(context);
1466
+ const jsonLd = await serializeForResponse(collection, context);
1363
1467
  return new Response(JSON.stringify(jsonLd), { headers: {
1364
1468
  "Content-Type": "application/activity+json",
1365
1469
  Vary: "Accept"
@@ -1511,7 +1615,11 @@ async function handleInboxInternal(request, parameters, span) {
1511
1615
  }
1512
1616
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
1513
1617
  const jsonWithoutSig = require_proof.detachSignature(json);
1514
- const hasLdSignature = require_proof.hasSignature(json);
1618
+ const hasLdSignature = require_proof.hasVerifiableSignature(json);
1619
+ if (!hasLdSignature) {
1620
+ const shape = require_proof.describeSignatureShape(json);
1621
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
1622
+ }
1515
1623
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
1516
1624
  let deferredLdSignatureError = void 0;
1517
1625
  const respondInvalidActivity = async (error) => {
@@ -1990,7 +2098,7 @@ var CustomCollectionHandler = class {
1990
2098
  * @returns A promise that resolves to the JSON-LD representation.
1991
2099
  */
1992
2100
  async toJsonLd() {
1993
- return (await this.collection).toJsonLd(this.context);
2101
+ return serializeForResponse(await this.collection, this.context);
1994
2102
  }
1995
2103
  /**
1996
2104
  * Fetches the collection with optional cursor for pagination.
@@ -2293,7 +2401,7 @@ var UnauthorizedError = class extends HandlerError {
2293
2401
  * @since 0.3.0
2294
2402
  */
2295
2403
  async function respondWithObject(object, options) {
2296
- const jsonLd = await object.toJsonLd(options);
2404
+ const jsonLd = await serializeForResponse(object, options);
2297
2405
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
2298
2406
  }
2299
2407
  /**
@@ -2381,6 +2489,106 @@ const MIN_COMPONENTS = [
2381
2489
  "@target-uri",
2382
2490
  "@authority"
2383
2491
  ];
2492
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
2493
+ async function serializeForResponse(object, options) {
2494
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
2495
+ }
2496
+ //#endregion
2497
+ //#region src/sig/proof-creation.ts
2498
+ /** Signs the exact serialized message supplied by an internal producer. */
2499
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
2500
+ require_http.validateCryptoKey(privateKey, "private");
2501
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
2502
+ const encoder = new TextEncoder();
2503
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode((0, json_canon.default)(jsonLd)));
2504
+ created ??= Temporal.Now.instant();
2505
+ const proofConfig = {
2506
+ "@context": jsonLd["@context"],
2507
+ type: "DataIntegrityProof",
2508
+ cryptosuite: "eddsa-jcs-2022",
2509
+ verificationMethod: keyId.href,
2510
+ proofPurpose: "assertionMethod",
2511
+ created: created.toString()
2512
+ };
2513
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode((0, json_canon.default)(proofConfig)));
2514
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
2515
+ digest.set(new Uint8Array(proofDigest), 0);
2516
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
2517
+ const sig = await crypto.subtle.sign("Ed25519", (0, _fedify_vocab_runtime_internal.asCryptoKey)(privateKey), digest);
2518
+ return new _fedify_vocab.DataIntegrityProof({
2519
+ cryptosuite: "eddsa-jcs-2022",
2520
+ verificationMethod: keyId,
2521
+ proofPurpose: "assertionMethod",
2522
+ created,
2523
+ proofValue: new Uint8Array(sig)
2524
+ });
2525
+ }
2526
+ //#endregion
2527
+ //#region src/compat/delivery-jsonld.ts
2528
+ /**
2529
+ * Returns changed attachment JSON only; unchanged documents keep the existing
2530
+ * delivery signing path. This uses ordinary vocabulary serialization, without
2531
+ * retaining or repairing independently signed child representations.
2532
+ */
2533
+ async function prepareActivityJsonLd(activity, contextLoader) {
2534
+ if (activity.proofIds.length > 0) return void 0;
2535
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
2536
+ const source = await activity.clone().toJsonLd({
2537
+ format: "compact",
2538
+ contextLoader
2539
+ });
2540
+ const prepared = await normalizeAttachmentArrays(source, contextLoader);
2541
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
2542
+ }
2543
+ /** Signs a changed, proof-free delivery map without serializing it again. */
2544
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
2545
+ const proofs = [];
2546
+ const serializedProofs = [];
2547
+ const tracer = (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version);
2548
+ for (const { privateKey, keyId } of keys) {
2549
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": (0, _fedify_vocab.getTypeId)(activity).href } }, async (span) => {
2550
+ try {
2551
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
2552
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
2553
+ if (span.isRecording()) {
2554
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
2555
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
2556
+ span.setAttribute("object_integrity_proofs.signature", (0, byte_encodings_hex.encodeHex)(proof.proofValue));
2557
+ }
2558
+ return proof;
2559
+ } catch (error) {
2560
+ span.setStatus({
2561
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
2562
+ message: String(error)
2563
+ });
2564
+ throw error;
2565
+ } finally {
2566
+ span.end();
2567
+ }
2568
+ });
2569
+ proofs.push(proof);
2570
+ serializedProofs.push({
2571
+ "@context": unsigned["@context"],
2572
+ type: "DataIntegrityProof",
2573
+ cryptosuite: proof.cryptosuite,
2574
+ verificationMethod: keyId.href,
2575
+ proofPurpose: "assertionMethod",
2576
+ created: proof.created.toString(),
2577
+ proofValue: new TextDecoder().decode((0, _fedify_vocab_runtime.encodeMultibase)("base58btc", proof.proofValue))
2578
+ });
2579
+ }
2580
+ if (proofs.length === 0) return {
2581
+ activity,
2582
+ jsonLd: unsigned
2583
+ };
2584
+ return {
2585
+ activity: activity.clone({ proofs }),
2586
+ jsonLd: {
2587
+ ...unsigned,
2588
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
2589
+ }
2590
+ };
2591
+ }
2384
2592
  //#endregion
2385
2593
  //#region src/nodeinfo/handler.ts
2386
2594
  /**
@@ -2480,7 +2688,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2480
2688
  * @param parameters The parameters for sending the activity.
2481
2689
  * See also {@link SendActivityParameters}.
2482
2690
  * @param deps The dependencies, for tests.
2483
- * @throws {Error} If the activity fails to send.
2691
+ * @throws {FetchError} If the delivery times out before receiving a response.
2692
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
2484
2693
  */
2485
2694
  function sendActivity(options, deps = {}) {
2486
2695
  const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
@@ -2507,7 +2716,25 @@ function sendActivity(options, deps = {}) {
2507
2716
  });
2508
2717
  }
2509
2718
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
2510
- async function readLimitedResponseBody(response, maxBytes) {
2719
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
2720
+ function raceWithAbort(promise, signal) {
2721
+ if (signal.aborted) return Promise.reject(signal.reason);
2722
+ return new Promise((resolve, reject) => {
2723
+ const onAbort = () => {
2724
+ signal.removeEventListener("abort", onAbort);
2725
+ reject(signal.reason);
2726
+ };
2727
+ signal.addEventListener("abort", onAbort, { once: true });
2728
+ promise.then((value) => {
2729
+ signal.removeEventListener("abort", onAbort);
2730
+ resolve(value);
2731
+ }, (error) => {
2732
+ signal.removeEventListener("abort", onAbort);
2733
+ reject(error);
2734
+ });
2735
+ });
2736
+ }
2737
+ async function readLimitedResponseBody(response, maxBytes, signal) {
2511
2738
  if (response.body == null) return "";
2512
2739
  const reader = response.body.getReader();
2513
2740
  const decoder = new TextDecoder();
@@ -2516,7 +2743,8 @@ async function readLimitedResponseBody(response, maxBytes) {
2516
2743
  let truncated = false;
2517
2744
  try {
2518
2745
  while (true) {
2519
- const { done, value } = await reader.read();
2746
+ signal.throwIfAborted();
2747
+ const { done, value } = await raceWithAbort(reader.read(), signal);
2520
2748
  if (done) break;
2521
2749
  if (totalBytes + value.length > maxBytes) {
2522
2750
  const remaining = maxBytes - totalBytes;
@@ -2528,8 +2756,10 @@ async function readLimitedResponseBody(response, maxBytes) {
2528
2756
  totalBytes += value.length;
2529
2757
  }
2530
2758
  } finally {
2531
- if (truncated) reader.cancel().catch(() => {});
2532
- reader.releaseLock();
2759
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
2760
+ try {
2761
+ reader.releaseLock();
2762
+ } catch (_) {}
2533
2763
  }
2534
2764
  let result = chunks.join("");
2535
2765
  if (truncated) result += "… (truncated)";
@@ -2541,12 +2771,24 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2541
2771
  "federation",
2542
2772
  "outbox"
2543
2773
  ]);
2544
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? _fedify_vocab_runtime_internal.openDirectFetch : (url) => (0, _fedify_vocab_runtime_internal.openPublicFetch)(url));
2774
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
2775
+ const controller = new AbortController();
2776
+ const { signal } = controller;
2777
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? _fedify_vocab_runtime_internal.openDirectFetch : (url) => (0, _fedify_vocab_runtime_internal.openPublicFetch)(url, { signal }));
2545
2778
  let opened = false;
2546
2779
  async function openHop(url) {
2547
2780
  let session;
2548
2781
  try {
2549
- session = await openUnvalidatedHop(url);
2782
+ signal.throwIfAborted();
2783
+ const opening = openUnvalidatedHop(url);
2784
+ opening.then((lateSession) => {
2785
+ if (signal.aborted) closeAfterError(lateSession, logger);
2786
+ }, () => {});
2787
+ session = await raceWithAbort(opening, signal);
2788
+ if (signal.aborted) {
2789
+ closeAfterError(session, logger);
2790
+ signal.throwIfAborted();
2791
+ }
2550
2792
  } catch (error) {
2551
2793
  if (error instanceof _fedify_vocab_runtime.UrlError && error.reason === "dns") {
2552
2794
  logger.error("DNS resolution failed for URL: {url}", {
@@ -2572,7 +2814,8 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2572
2814
  method: "POST",
2573
2815
  headers,
2574
2816
  body: JSON.stringify(activity),
2575
- redirect: "manual"
2817
+ redirect: "manual",
2818
+ signal
2576
2819
  });
2577
2820
  let rsaKey = null;
2578
2821
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -2587,18 +2830,48 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2587
2830
  }))
2588
2831
  });
2589
2832
  let outcome;
2833
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
2834
+ determineSpec(origin) {
2835
+ signal.throwIfAborted();
2836
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
2837
+ },
2838
+ rememberSpec(origin, spec) {
2839
+ if (signal.aborted) return;
2840
+ try {
2841
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
2842
+ origin,
2843
+ error
2844
+ }));
2845
+ } catch (error) {
2846
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
2847
+ origin,
2848
+ error
2849
+ });
2850
+ }
2851
+ }
2852
+ };
2853
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
2590
2854
  try {
2591
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox)) : await require_http.doubleKnockScoped(request, rsaKey, {
2855
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await require_http.doubleKnockScoped(request, rsaKey, {
2592
2856
  tracerProvider,
2593
- specDeterminer
2594
- }, openHop, (response) => consumeSendActivityResponse(response, inbox));
2857
+ specDeterminer: boundedSpecDeterminer,
2858
+ signal
2859
+ }, openHop, (response) => consumeSendActivityResponse(response, inbox, signal));
2595
2860
  } catch (error) {
2596
- if (opened) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
2861
+ let failureError = error;
2862
+ if (signal.aborted && !(error instanceof SendActivityError)) {
2863
+ const failure = new _fedify_vocab_runtime.FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
2864
+ failure.cause = signal.reason;
2865
+ failureError = failure;
2866
+ }
2867
+ if (opened || signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
2597
2868
  activityId,
2598
2869
  inbox: inbox.href,
2599
- error
2870
+ error: failureError
2600
2871
  });
2601
- throw error;
2872
+ throw failureError;
2873
+ } finally {
2874
+ clearTimeout(timer);
2602
2875
  }
2603
2876
  if (!outcome.ok) {
2604
2877
  const { status, statusText, error } = outcome;
@@ -2640,17 +2913,18 @@ function cancelResponseBody(response, url) {
2640
2913
  * session is open: the body of a successful response is cancelled, and at
2641
2914
  * most 1 KiB of an error response body is read.
2642
2915
  */
2643
- async function consumeSendActivityResponse(response, inbox) {
2916
+ async function consumeSendActivityResponse(response, inbox, signal) {
2644
2917
  if (response.ok) {
2645
2918
  cancelResponseBody(response, response.url || inbox.href);
2646
2919
  return { ok: true };
2647
2920
  }
2648
2921
  let error;
2649
2922
  try {
2650
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
2923
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
2651
2924
  } catch (_) {
2652
2925
  error = "";
2653
2926
  }
2927
+ if (signal.aborted) error = "(timed out reading response body)";
2654
2928
  return {
2655
2929
  ok: false,
2656
2930
  status: response.status,
@@ -2669,7 +2943,7 @@ async function consumeSendActivityResponse(response, inbox) {
2669
2943
  * @param consume The function to consume the final response.
2670
2944
  * @returns The value returned by `consume`.
2671
2945
  */
2672
- async function fetchWithValidatedRedirects(request, openHop, consume) {
2946
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
2673
2947
  const logger = (0, _logtape_logtape.getLogger)([
2674
2948
  "fedify",
2675
2949
  "federation",
@@ -2677,10 +2951,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
2677
2951
  ]);
2678
2952
  let body = await request.clone().text();
2679
2953
  for (let redirects = 0;; redirects++) {
2954
+ signal?.throwIfAborted();
2680
2955
  const session = await openHop(request.url);
2681
2956
  let response;
2682
2957
  try {
2683
- response = await session.fetch(request, { redirect: "manual" });
2958
+ response = await session.fetch(request, {
2959
+ redirect: "manual",
2960
+ signal
2961
+ });
2684
2962
  } catch (error) {
2685
2963
  await closeAfterError(session, logger);
2686
2964
  throw error;
@@ -2730,7 +3008,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
2730
3008
  method,
2731
3009
  headers,
2732
3010
  body,
2733
- redirect: "manual"
3011
+ redirect: "manual",
3012
+ signal: signal ?? request.signal
2734
3013
  });
2735
3014
  }
2736
3015
  }
@@ -3083,8 +3362,25 @@ var FederationImpl = class extends FederationBuilderImpl {
3083
3362
  _getTracer() {
3084
3363
  return this.tracerProvider.getTracer(require_http.name, require_http.version);
3085
3364
  }
3365
+ /**
3366
+ * Starts listening on a queue, converting a synchronous throw into
3367
+ * a rejected promise.
3368
+ *
3369
+ * `MessageQueue.listen()` is documented to never reject, but some
3370
+ * implementations (e.g., `WorkersMessageQueue`) throw synchronously. Without
3371
+ * this normalization, one such throw aborts {@link _startQueueInternal} while
3372
+ * it is still collecting listener promises, so listeners started earlier are
3373
+ * never awaited and later queues are never started.
3374
+ */
3375
+ #listenQueue(queue, ctxData, signal) {
3376
+ try {
3377
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
3378
+ } catch (error) {
3379
+ return Promise.reject(error);
3380
+ }
3381
+ }
3086
3382
  async _startQueueInternal(ctxData, signal, queue) {
3087
- if (this.inboxQueue == null && this.outboxQueue == null) return;
3383
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
3088
3384
  const logger = (0, _logtape_logtape.getLogger)([
3089
3385
  "fedify",
3090
3386
  "federation",
@@ -3094,20 +3390,38 @@ var FederationImpl = class extends FederationBuilderImpl {
3094
3390
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
3095
3391
  logger.debug("Starting an inbox task worker.");
3096
3392
  this.inboxQueueStarted = true;
3097
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3393
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
3098
3394
  }
3099
3395
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
3100
3396
  logger.debug("Starting an outbox task worker.");
3101
3397
  this.outboxQueueStarted = true;
3102
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3398
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
3103
3399
  }
3104
3400
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
3105
3401
  logger.debug("Starting a fanout task worker.");
3106
3402
  this.fanoutQueueStarted = true;
3107
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3403
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
3108
3404
  }
3109
3405
  await Promise.all(promises);
3110
3406
  }
3407
+ /**
3408
+ * Starts the queue workers automatically, reporting a failure instead of
3409
+ * leaving the returned promise unobserved.
3410
+ *
3411
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
3412
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
3413
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
3414
+ * callers that start workers deliberately.
3415
+ */
3416
+ _startQueueAutomatically(ctxData) {
3417
+ this._startQueueInternal(ctxData).catch((error) => {
3418
+ (0, _logtape_logtape.getLogger)([
3419
+ "fedify",
3420
+ "federation",
3421
+ "queue"
3422
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
3423
+ });
3424
+ }
3111
3425
  processQueuedTask(contextData, message) {
3112
3426
  const tracer = this._getTracer();
3113
3427
  const extractedContext = _opentelemetry_api.propagation.extract(_opentelemetry_api.context.active(), message.traceContext);
@@ -3216,7 +3530,8 @@ var FederationImpl = class extends FederationBuilderImpl {
3216
3530
  await this.sendActivity(keys, message.inboxes, activity, {
3217
3531
  collectionSync: message.collectionSync,
3218
3532
  orderingKey: message.orderingKey,
3219
- context
3533
+ context,
3534
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
3220
3535
  });
3221
3536
  }
3222
3537
  async #listenOutboxMessage(_, message, span) {
@@ -3419,7 +3734,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3419
3734
  let parseInput = void 0;
3420
3735
  let parseContextLoader = context.contextLoader;
3421
3736
  try {
3422
- const hasSignatureField = require_proof.hasSignature(message.activity);
3737
+ const hasSignatureField = require_proof.hasVerifiableSignature(message.activity);
3423
3738
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
3424
3739
  const parseContext = hasSignatureField ? {
3425
3740
  ...context,
@@ -3614,19 +3929,29 @@ var FederationImpl = class extends FederationBuilderImpl {
3614
3929
  proofCreated = true;
3615
3930
  break;
3616
3931
  }
3617
- if (!proofCreated) {
3618
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3619
- activity = await require_proof.signObject(activity, privateKey, keyId, {
3620
- contextLoader,
3621
- tracerProvider: this.tracerProvider
3622
- });
3623
- proofCreated = true;
3932
+ const prepared = !proofCreated && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
3933
+ let jsonLd;
3934
+ if (prepared != null) {
3935
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
3936
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
3937
+ activity = signed.activity;
3938
+ jsonLd = signed.jsonLd;
3939
+ proofCreated = signingKeys.length > 0;
3940
+ } else {
3941
+ if (!proofCreated) {
3942
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3943
+ activity = await require_proof.signObject(activity, privateKey, keyId, {
3944
+ contextLoader,
3945
+ tracerProvider: this.tracerProvider
3946
+ });
3947
+ proofCreated = true;
3948
+ }
3624
3949
  }
3950
+ jsonLd = options.activityJsonLd != null ? require_proof.detachSignature(options.activityJsonLd) : await activity.toJsonLd({
3951
+ format: "compact",
3952
+ contextLoader
3953
+ });
3625
3954
  }
3626
- let jsonLd = await activity.toJsonLd({
3627
- format: "compact",
3628
- contextLoader
3629
- });
3630
3955
  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.", {
3631
3956
  activityId,
3632
3957
  keys: keys.map((pair) => ({
@@ -3663,19 +3988,27 @@ var FederationImpl = class extends FederationBuilderImpl {
3663
3988
  activity: jsonLd
3664
3989
  });
3665
3990
  const promises = [];
3666
- for (const inbox in inboxes) promises.push(sendActivity({
3667
- allowPrivateAddress: this.allowPrivateAddress,
3668
- keys,
3669
- activity: jsonLd,
3670
- activityId: activity.id?.href,
3671
- activityType: (0, _fedify_vocab.getTypeId)(activity).href,
3672
- inbox: new URL(inbox),
3673
- sharedInbox: inboxes[inbox].sharedInbox,
3674
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3675
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3676
- tracerProvider: this.tracerProvider
3677
- }));
3678
- await Promise.all(promises);
3991
+ try {
3992
+ for (const inbox in inboxes) {
3993
+ const promise = sendActivity({
3994
+ allowPrivateAddress: this.allowPrivateAddress,
3995
+ keys,
3996
+ activity: jsonLd,
3997
+ activityId: activity.id?.href,
3998
+ activityType: (0, _fedify_vocab.getTypeId)(activity).href,
3999
+ inbox: new URL(inbox),
4000
+ sharedInbox: inboxes[inbox].sharedInbox,
4001
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
4002
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
4003
+ tracerProvider: this.tracerProvider
4004
+ });
4005
+ promise.catch(() => {});
4006
+ promises.push(promise);
4007
+ }
4008
+ await Promise.all(promises);
4009
+ } finally {
4010
+ await Promise.allSettled(promises);
4011
+ }
3679
4012
  return;
3680
4013
  }
3681
4014
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -3690,7 +4023,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3690
4023
  privateKey: privateKeyJwk
3691
4024
  });
3692
4025
  }
3693
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
4026
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
3694
4027
  const carrier = {};
3695
4028
  _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), carrier);
3696
4029
  const messages = [];
@@ -3902,7 +4235,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3902
4235
  const identity = await this.sharedInboxKeyDispatcher(context);
3903
4236
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
3904
4237
  }
3905
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
4238
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
3906
4239
  const inboxContextFactory = context.toInboxContext.bind(context);
3907
4240
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
3908
4241
  return await handleInbox(request, {
@@ -4225,6 +4558,8 @@ var ContextImpl = class ContextImpl {
4225
4558
  for (const keyPair of keyPairs) {
4226
4559
  const newPair = {
4227
4560
  ...keyPair,
4561
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(keyPair.privateKey),
4562
+ publicKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(keyPair.publicKey),
4228
4563
  cryptographicKey: new _fedify_vocab.CryptographicKey({
4229
4564
  id: keyPair.keyId,
4230
4565
  owner,
@@ -4301,10 +4636,16 @@ var ContextImpl = class ContextImpl {
4301
4636
  } else identifierPromise = Promise.resolve(identity.identifier);
4302
4637
  return identifierPromise.then((identifier) => {
4303
4638
  if (identifier == null) return this.documentLoader;
4304
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
4639
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
4640
+ keyId: pair.keyId,
4641
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(pair.privateKey)
4642
+ }));
4305
4643
  });
4306
4644
  }
4307
- return this.federation.authenticatedDocumentLoaderFactory(identity);
4645
+ return this.federation.authenticatedDocumentLoaderFactory({
4646
+ keyId: identity.keyId,
4647
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(identity.privateKey)
4648
+ });
4308
4649
  }
4309
4650
  lookupObject(identifier, options = {}) {
4310
4651
  return (0, _fedify_vocab.lookupObject)(identifier, {
@@ -4327,10 +4668,14 @@ var ContextImpl = class ContextImpl {
4327
4668
  return options.parse === "none" ? require_types.getNodeInfo(url, {
4328
4669
  parse: "none",
4329
4670
  direct: options.direct,
4671
+ timeout: options.timeout,
4672
+ signal: options.signal,
4330
4673
  userAgent: options?.userAgent ?? this.federation.userAgent
4331
4674
  }) : require_types.getNodeInfo(url, {
4332
4675
  parse: options.parse,
4333
4676
  direct: options.direct,
4677
+ timeout: options.timeout,
4678
+ signal: options.signal,
4334
4679
  userAgent: options?.userAgent ?? this.federation.userAgent
4335
4680
  });
4336
4681
  }
@@ -4342,7 +4687,17 @@ var ContextImpl = class ContextImpl {
4342
4687
  allowPrivateAddress: this.federation.allowPrivateAddress
4343
4688
  });
4344
4689
  }
4345
- sendActivity(sender, recipients, activity, options = {}) {
4690
+ async sendActivity(sender, recipients, activity, options = {}) {
4691
+ let activityJsonLd = void 0;
4692
+ let hasProof = activity.proofIds.length > 0;
4693
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
4694
+ hasProof = true;
4695
+ break;
4696
+ }
4697
+ if (hasProof) {
4698
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
4699
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
4700
+ }
4346
4701
  return this.tracerProvider.getTracer(require_http.name, require_http.version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
4347
4702
  kind: this.federation.outboxQueue == null || options.immediate ? _opentelemetry_api.SpanKind.CLIENT : _opentelemetry_api.SpanKind.PRODUCER,
4348
4703
  attributes: {
@@ -4355,7 +4710,7 @@ var ContextImpl = class ContextImpl {
4355
4710
  }, async (span) => {
4356
4711
  try {
4357
4712
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
4358
- await this.sendActivityInternal(sender, recipients, activity, options, span);
4713
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
4359
4714
  } catch (e) {
4360
4715
  span.setStatus({
4361
4716
  code: _opentelemetry_api.SpanStatusCode.ERROR,
@@ -4367,7 +4722,7 @@ var ContextImpl = class ContextImpl {
4367
4722
  }
4368
4723
  });
4369
4724
  }
4370
- async sendActivityInternal(sender, recipients, activity, options, span) {
4725
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
4371
4726
  const logger = (0, _logtape_logtape.getLogger)([
4372
4727
  "fedify",
4373
4728
  "federation",
@@ -4414,14 +4769,23 @@ var ContextImpl = class ContextImpl {
4414
4769
  if (!(error instanceof RouterError)) throw error;
4415
4770
  }
4416
4771
  } else expandedRecipients = [recipients];
4417
- const opts = {
4418
- context: this,
4419
- orderingKey: options.orderingKey,
4420
- collectionSync,
4421
- immediate: options.immediate
4422
- };
4423
4772
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
4424
4773
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
4774
+ let contextMatches = false;
4775
+ if (activityJsonLd != null) {
4776
+ const capturedJsonLd = activityJsonLd;
4777
+ const transformedJsonLd = await activity.toJsonLd({
4778
+ format: "compact",
4779
+ contextLoader: this.contextLoader
4780
+ });
4781
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
4782
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
4783
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
4784
+ if (contentChanged || !contextMatches && proofsChanged) {
4785
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) });
4786
+ activityJsonLd = void 0;
4787
+ } else if (proofsChanged) activityJsonLd = void 0;
4788
+ }
4425
4789
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
4426
4790
  if (activity.actorId == null) {
4427
4791
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -4432,14 +4796,39 @@ var ContextImpl = class ContextImpl {
4432
4796
  }
4433
4797
  if (actorKeyPairs != null) {
4434
4798
  const contextLoader = this.contextLoader;
4435
- for (const kp of actorKeyPairs) {
4436
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4437
- activity = await require_proof.signObject(activity, kp.privateKey, kp.multikey.id, {
4438
- contextLoader,
4439
- tracerProvider: this.tracerProvider
4440
- });
4799
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
4800
+ if (willSign) {
4801
+ if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
4802
+ }
4803
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
4804
+ if (prepared != null) {
4805
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
4806
+ privateKey: kp.privateKey,
4807
+ keyId: kp.multikey.id
4808
+ }] : []);
4809
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
4810
+ activity = signed.activity;
4811
+ activityJsonLd = signed.jsonLd;
4812
+ } else {
4813
+ let proofAdded = false;
4814
+ for (const kp of actorKeyPairs) {
4815
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4816
+ activity = await require_proof.signObject(activity, kp.privateKey, kp.multikey.id, {
4817
+ contextLoader,
4818
+ tracerProvider: this.tracerProvider
4819
+ });
4820
+ proofAdded = true;
4821
+ }
4822
+ if (proofAdded) activityJsonLd = void 0;
4441
4823
  }
4442
4824
  }
4825
+ const opts = {
4826
+ context: this,
4827
+ orderingKey: options.orderingKey,
4828
+ collectionSync,
4829
+ immediate: options.immediate,
4830
+ activityJsonLd
4831
+ };
4443
4832
  const inboxes = extractInboxes({
4444
4833
  recipients: expandedRecipients,
4445
4834
  preferSharedInbox: options.preferSharedInbox,
@@ -4469,7 +4858,7 @@ var ContextImpl = class ContextImpl {
4469
4858
  actorIds: [...actorIds],
4470
4859
  sharedInbox
4471
4860
  }])),
4472
- activity: await activity.toJsonLd({
4861
+ activity: activityJsonLd != null ? require_proof.detachSignature(activityJsonLd) : await activity.toJsonLd({
4473
4862
  format: "compact",
4474
4863
  contextLoader: this.contextLoader
4475
4864
  }),
@@ -4479,7 +4868,7 @@ var ContextImpl = class ContextImpl {
4479
4868
  orderingKey: options.orderingKey,
4480
4869
  traceContext: carrier
4481
4870
  };
4482
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
4871
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
4483
4872
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
4484
4873
  }
4485
4874
  async *getFollowers(identifier) {
@@ -4833,7 +5222,7 @@ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
4833
5222
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
4834
5223
  keys = forwarder;
4835
5224
  } else keys = [forwarder];
4836
- if (!require_proof.hasSignature(this.activity)) {
5225
+ if (!require_proof.hasVerifiableSignature(this.activity)) {
4837
5226
  let hasProof;
4838
5227
  try {
4839
5228
  hasProof = await (await _fedify_vocab.Activity.fromJsonLd(this.activity, this)).getProof() != null;
@@ -4865,18 +5254,26 @@ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
4865
5254
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
4866
5255
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
4867
5256
  const promises = [];
4868
- for (const inbox in inboxes) promises.push(sendActivity({
4869
- allowPrivateAddress: this.federation.allowPrivateAddress,
4870
- keys,
4871
- activity: this.activity,
4872
- activityId: this.activityId,
4873
- activityType: this.activityType,
4874
- inbox: new URL(inbox),
4875
- sharedInbox: inboxes[inbox].sharedInbox,
4876
- tracerProvider: this.tracerProvider,
4877
- specDeterminer: new KvSpecDeterminer(this.federation.kv, this.federation.kvPrefixes.httpMessageSignaturesSpec, this.federation.firstKnock)
4878
- }));
4879
- await Promise.all(promises);
5257
+ try {
5258
+ for (const inbox in inboxes) {
5259
+ const promise = sendActivity({
5260
+ allowPrivateAddress: this.federation.allowPrivateAddress,
5261
+ keys,
5262
+ activity: this.activity,
5263
+ activityId: this.activityId,
5264
+ activityType: this.activityType,
5265
+ inbox: new URL(inbox),
5266
+ sharedInbox: inboxes[inbox].sharedInbox,
5267
+ tracerProvider: this.tracerProvider,
5268
+ specDeterminer: new KvSpecDeterminer(this.federation.kv, this.federation.kvPrefixes.httpMessageSignaturesSpec, this.federation.firstKnock)
5269
+ });
5270
+ promise.catch(() => {});
5271
+ promises.push(promise);
5272
+ }
5273
+ await Promise.all(promises);
5274
+ } finally {
5275
+ await Promise.allSettled(promises);
5276
+ }
4880
5277
  return;
4881
5278
  }
4882
5279
  logger.debug("Enqueuing activity {activityId} to forward later.", {
@@ -4971,6 +5368,69 @@ var KvSpecDeterminer = class {
4971
5368
  function notFound(_request) {
4972
5369
  return new Response("Not Found", { status: 404 });
4973
5370
  }
5371
+ function hasTopLevelProof(value) {
5372
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
5373
+ }
5374
+ function getContentFields(value) {
5375
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5376
+ const record = { ...value };
5377
+ delete record["@context"];
5378
+ delete record.proof;
5379
+ delete record.signature;
5380
+ return JSON.stringify(sortJsonKeys(record));
5381
+ }
5382
+ function getContextFields(value) {
5383
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5384
+ const context = value["@context"];
5385
+ return JSON.stringify(sortJsonKeys(context ?? null));
5386
+ }
5387
+ function getProofEntries(value) {
5388
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
5389
+ const proof = value.proof;
5390
+ if (proof == null) return [];
5391
+ return Array.isArray(proof) ? proof : [proof];
5392
+ }
5393
+ function normalizeProofEntry(proof) {
5394
+ const stripped = stripContexts(proof);
5395
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
5396
+ const record = { ...stripped };
5397
+ if (typeof record.created === "string") try {
5398
+ record.created = Temporal.Instant.from(record.created).toString();
5399
+ } catch {}
5400
+ return record;
5401
+ }
5402
+ function getProofEntryFields(proof) {
5403
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
5404
+ }
5405
+ function getProofFields(value) {
5406
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
5407
+ }
5408
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
5409
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
5410
+ const retainedProofs = [];
5411
+ for await (const proof of activity.getProofs({ contextLoader })) {
5412
+ const proofJsonLd = await proof.toJsonLd({
5413
+ format: "compact",
5414
+ contextLoader
5415
+ });
5416
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
5417
+ }
5418
+ return retainedProofs;
5419
+ }
5420
+ function stripContexts(value) {
5421
+ if (Array.isArray(value)) return value.map(stripContexts);
5422
+ if (typeof value !== "object" || value == null) return value;
5423
+ const record = { ...value };
5424
+ delete record["@context"];
5425
+ delete record.signature;
5426
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
5427
+ return record;
5428
+ }
5429
+ function sortJsonKeys(value) {
5430
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
5431
+ if (typeof value !== "object" || value == null) return value;
5432
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
5433
+ }
4974
5434
  function notAcceptable(_request) {
4975
5435
  return new Response("Not Acceptable", {
4976
5436
  status: 406,