@fedify/fedify 2.1.30 → 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 (104) hide show
  1. package/dist/attachment-arrays-DZ4JHJD8.mjs +111 -0
  2. package/dist/{builder-CTpfuuVp.mjs → builder--sc-rozj.mjs} +3 -3
  3. package/dist/callback-BARPujV7.d.mts +2388 -0
  4. package/dist/{client-CAM_bQXx.d.cts → client-9DPcy_Yx.d.ts} +16 -1
  5. package/dist/{client-CSddvgWN.d.ts → client-B3ruDgWg.d.cts} +16 -1
  6. package/dist/{client-CjDMsn4a.mjs → client-cpPaW7Ww.mjs} +189 -65
  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-DLLaDau8.d.ts → context-DE2YrQwM.d.ts} +56 -13
  13. package/dist/{context-BNwv9Q1v.d.cts → context-y6ZUQCMf.d.cts} +56 -13
  14. package/dist/{deno-BATJ1hq6.mjs → deno-L23b3Hba.mjs} +1 -1
  15. package/dist/docloader-DUXr9k_O.mjs +124 -0
  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 +1559 -26
  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 +723 -68
  33. package/dist/federation/temporal.test.mjs +25 -1
  34. package/dist/federation/webfinger.test.mjs +1 -1
  35. package/dist/{http-CK3efjgM.js → http-BtbMAgTA.js} +176 -105
  36. package/dist/{http-Dl00HXr4.d.ts → http-C8qLHs_Z.d.cts} +3 -4
  37. package/dist/{http-BoR1M3W7.cjs → http-D5woFKA_.cjs} +177 -106
  38. package/dist/{http-DqZhyEso.d.cts → http-D8WmcRAF.d.ts} +3 -4
  39. package/dist/{http-Bjd6I92u.mjs → http-HX6wVyJh.mjs} +198 -98
  40. package/dist/{inbox-9MlBGgs9.mjs → inbox-CL7A0HXT.mjs} +1 -1
  41. package/dist/{key-ClQh9Qqh.mjs → key-Dai3f5yI.mjs} +3 -2
  42. package/dist/{kv-cache-BxSx_Iyp.cjs → kv-cache-B0V_e231.cjs} +59 -17
  43. package/dist/{kv-cache-ImApO425.js → kv-cache-BsDg-cT8.js} +60 -18
  44. package/dist/{ld-Crg0Xmwr.mjs → ld-DN6x1iZ8.mjs} +153 -21
  45. package/dist/ld-signature-DoZcbsZR.mjs +23 -0
  46. package/dist/{middleware-jL9p9V9G.cjs → middleware-Cl6k5Hrm.cjs} +1 -1
  47. package/dist/{middleware-CmD3lpy4.cjs → middleware-CrfRuKCf.cjs} +728 -143
  48. package/dist/{middleware-CE0b69gj.mjs → middleware-DiquMgtt.mjs} +444 -115
  49. package/dist/{middleware-C2AJFk8W.js → middleware-DunNtbo9.js} +727 -143
  50. package/dist/{middleware-Bi5D6DBT.mjs → middleware-SnQS8eIb.mjs} +1 -1
  51. package/dist/{mod-DiuFTYUt.d.cts → mod-CehHJOV4.d.cts} +30 -13
  52. package/dist/{mod-CWJNbyju.d.ts → mod-DLJpnqdw.d.ts} +1 -1
  53. package/dist/{mod-BLDHhuW0.d.ts → mod-Mh3oIuRK.d.ts} +30 -13
  54. package/dist/{mod-DNEgTI8M.d.ts → mod-REfljt0T.d.ts} +4 -9
  55. package/dist/{mod-Cn9GJ5ex.d.cts → mod-UvIGUHqW.d.cts} +4 -9
  56. package/dist/{mod-BmlfRBmU.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 +764 -19
  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/otel/exporter.test.mjs +292 -30
  69. package/dist/otel/mod.cjs +36 -30
  70. package/dist/otel/mod.d.cts +13 -0
  71. package/dist/otel/mod.d.ts +13 -0
  72. package/dist/otel/mod.js +36 -30
  73. package/dist/{owner-BRoKojK1.mjs → owner-DwyDorZI.mjs} +2 -2
  74. package/dist/{proof-CHXVlsH_.cjs → proof-Be-4K4jn.cjs} +193 -46
  75. package/dist/{proof-DMIAezxz.mjs → proof-DYjmyrHh.mjs} +38 -13
  76. package/dist/{proof-7R4s10TJ.js → proof-Du4-5SHY.js} +187 -46
  77. package/dist/send-BGSfQkIK.mjs +416 -0
  78. package/dist/sig/http.test.mjs +506 -2
  79. package/dist/sig/key-types.test.d.mts +218 -0
  80. package/dist/sig/key-types.test.mjs +8 -0
  81. package/dist/sig/key.test.mjs +2 -2
  82. package/dist/sig/ld.test.mjs +573 -8
  83. package/dist/sig/mod.cjs +2 -2
  84. package/dist/sig/mod.d.cts +3 -3
  85. package/dist/sig/mod.d.ts +3 -3
  86. package/dist/sig/mod.js +2 -2
  87. package/dist/sig/owner.test.mjs +1 -1
  88. package/dist/sig/proof.test.mjs +95 -3
  89. package/dist/{temporal-DR0JahMu.mjs → temporal-CNCchWly.mjs} +3 -5
  90. package/dist/testing/mod.d.mts +1 -2177
  91. package/dist/{types-DRPjmHVV.cjs → types-B5wRhemi.cjs} +187 -63
  92. package/dist/{types-miAYfiGO.js → types-CXy2lRVU.js} +188 -64
  93. package/dist/utils/docloader.test.mjs +316 -32
  94. package/dist/utils/mod.cjs +1 -1
  95. package/dist/utils/mod.d.cts +1 -1
  96. package/dist/utils/mod.d.ts +1 -1
  97. package/dist/utils/mod.js +1 -1
  98. package/package.json +7 -7
  99. package/dist/docloader-OLWc7P2D.mjs +0 -82
  100. package/dist/send-BHIt_8ia.mjs +0 -260
  101. /package/dist/{collection-BD6-SZ6O.mjs → collection-DnoYNwBC.mjs} +0 -0
  102. /package/dist/{negotiation-BehA2uul.mjs → negotiation-xb0QR3u_.mjs} +0 -0
  103. /package/dist/{retry-B_E3V_Dx.mjs → retry-CI1flGDD.mjs} +0 -0
  104. /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-BoR1M3W7.cjs");
6
- const require_types = require("./types-DRPjmHVV.cjs");
7
- const require_proof = require("./proof-CHXVlsH_.cjs");
8
- const require_kv_cache = require("./kv-cache-BxSx_Iyp.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,9 +14,13 @@ 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);
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");
20
24
  let _fedify_webfinger = require("@fedify/webfinger");
21
25
  let node_url = require("node:url");
22
26
  //#region src/federation/inbox.ts
@@ -350,7 +354,7 @@ var FederationBuilderImpl = class {
350
354
  this.collectionTypeIds = {};
351
355
  }
352
356
  async build(options) {
353
- const { FederationImpl } = await Promise.resolve().then(() => require("./middleware-jL9p9V9G.cjs"));
357
+ const { FederationImpl } = await Promise.resolve().then(() => require("./middleware-Cl6k5Hrm.cjs"));
354
358
  const f = new FederationImpl(options);
355
359
  const trailingSlashInsensitiveValue = f.router.trailingSlashInsensitive;
356
360
  f.router = this.router.clone();
@@ -882,6 +886,110 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
882
886
  return `collectionId="${collectionId}", url="${url}", digest="${(0, byte_encodings_hex.encodeHex)(await digest(actorIds))}"`;
883
887
  }
884
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
885
993
  //#region src/federation/keycache.ts
886
994
  const KEY_CACHE_GENERATION = "3";
887
995
  var KvKeyCache = class {
@@ -1069,13 +1177,10 @@ function acceptsJsonLd(request) {
1069
1177
  function isPlainObject(value) {
1070
1178
  return typeof value === "object" && value != null && !Array.isArray(value);
1071
1179
  }
1072
- function normalizeDateTimeLiteral(value) {
1073
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1074
- }
1075
1180
  function isMalformedDateTimeLiteral(value) {
1076
1181
  if (typeof value !== "string") return false;
1077
1182
  try {
1078
- Temporal.Instant.from(normalizeDateTimeLiteral(value));
1183
+ Temporal.Instant.from((0, _fedify_vocab_runtime_temporal.normalizeDateTimeLiteral)(value));
1079
1184
  return false;
1080
1185
  } catch {
1081
1186
  return true;
@@ -1113,7 +1218,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1113
1218
  if (typeof literal === "boolean") return false;
1114
1219
  if (typeof literal !== "string") return false;
1115
1220
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1116
- 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;
1117
1222
  return isMalformedDateTimeLiteral(literal);
1118
1223
  }
1119
1224
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1207,7 +1312,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1207
1312
  if (authorizePredicate != null) {
1208
1313
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1209
1314
  }
1210
- const jsonLd = await actor.toJsonLd(context);
1315
+ const jsonLd = await serializeForResponse(actor, context);
1211
1316
  return new Response(JSON.stringify(jsonLd), { headers: {
1212
1317
  "Content-Type": "application/activity+json",
1213
1318
  Vary: "Accept"
@@ -1227,7 +1332,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1227
1332
  if (authorizePredicate != null) {
1228
1333
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1229
1334
  }
1230
- const jsonLd = await object.toJsonLd(context);
1335
+ const jsonLd = await serializeForResponse(object, context);
1231
1336
  return new Response(JSON.stringify(jsonLd), { headers: {
1232
1337
  "Content-Type": "application/activity+json",
1233
1338
  Vary: "Accept"
@@ -1358,7 +1463,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1358
1463
  if (collectionCallbacks.authorizePredicate != null) {
1359
1464
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
1360
1465
  }
1361
- const jsonLd = await collection.toJsonLd(context);
1466
+ const jsonLd = await serializeForResponse(collection, context);
1362
1467
  return new Response(JSON.stringify(jsonLd), { headers: {
1363
1468
  "Content-Type": "application/activity+json",
1364
1469
  Vary: "Accept"
@@ -1510,7 +1615,11 @@ async function handleInboxInternal(request, parameters, span) {
1510
1615
  }
1511
1616
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
1512
1617
  const jsonWithoutSig = require_proof.detachSignature(json);
1513
- 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
+ }
1514
1623
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
1515
1624
  let deferredLdSignatureError = void 0;
1516
1625
  const respondInvalidActivity = async (error) => {
@@ -1989,7 +2098,7 @@ var CustomCollectionHandler = class {
1989
2098
  * @returns A promise that resolves to the JSON-LD representation.
1990
2099
  */
1991
2100
  async toJsonLd() {
1992
- return (await this.collection).toJsonLd(this.context);
2101
+ return serializeForResponse(await this.collection, this.context);
1993
2102
  }
1994
2103
  /**
1995
2104
  * Fetches the collection with optional cursor for pagination.
@@ -2292,7 +2401,7 @@ var UnauthorizedError = class extends HandlerError {
2292
2401
  * @since 0.3.0
2293
2402
  */
2294
2403
  async function respondWithObject(object, options) {
2295
- const jsonLd = await object.toJsonLd(options);
2404
+ const jsonLd = await serializeForResponse(object, options);
2296
2405
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
2297
2406
  }
2298
2407
  /**
@@ -2380,6 +2489,106 @@ const MIN_COMPONENTS = [
2380
2489
  "@target-uri",
2381
2490
  "@authority"
2382
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
+ }
2383
2592
  //#endregion
2384
2593
  //#region src/nodeinfo/handler.ts
2385
2594
  /**
@@ -2478,9 +2687,11 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2478
2687
  *
2479
2688
  * @param parameters The parameters for sending the activity.
2480
2689
  * See also {@link SendActivityParameters}.
2481
- * @throws {Error} If the activity fails to send.
2690
+ * @param deps The dependencies, for tests.
2691
+ * @throws {FetchError} If the delivery times out before receiving a response.
2692
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
2482
2693
  */
2483
- function sendActivity(options) {
2694
+ function sendActivity(options, deps = {}) {
2484
2695
  const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
2485
2696
  return tracerProvider.getTracer(require_http.name, require_http.version).startActiveSpan("activitypub.send_activity", {
2486
2697
  kind: _opentelemetry_api.SpanKind.CLIENT,
@@ -2492,7 +2703,7 @@ function sendActivity(options) {
2492
2703
  await sendActivityInternal({
2493
2704
  ...options,
2494
2705
  tracerProvider
2495
- }, span);
2706
+ }, span, deps);
2496
2707
  } catch (e) {
2497
2708
  span.setStatus({
2498
2709
  code: _opentelemetry_api.SpanStatusCode.ERROR,
@@ -2505,7 +2716,25 @@ function sendActivity(options) {
2505
2716
  });
2506
2717
  }
2507
2718
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
2508
- 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) {
2509
2738
  if (response.body == null) return "";
2510
2739
  const reader = response.body.getReader();
2511
2740
  const decoder = new TextDecoder();
@@ -2514,7 +2743,8 @@ async function readLimitedResponseBody(response, maxBytes) {
2514
2743
  let truncated = false;
2515
2744
  try {
2516
2745
  while (true) {
2517
- const { done, value } = await reader.read();
2746
+ signal.throwIfAborted();
2747
+ const { done, value } = await raceWithAbort(reader.read(), signal);
2518
2748
  if (done) break;
2519
2749
  if (totalBytes + value.length > maxBytes) {
2520
2750
  const remaining = maxBytes - totalBytes;
@@ -2526,21 +2756,39 @@ async function readLimitedResponseBody(response, maxBytes) {
2526
2756
  totalBytes += value.length;
2527
2757
  }
2528
2758
  } finally {
2529
- reader.releaseLock();
2759
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
2760
+ try {
2761
+ reader.releaseLock();
2762
+ } catch (_) {}
2530
2763
  }
2531
2764
  let result = chunks.join("");
2532
2765
  if (truncated) result += "… (truncated)";
2533
2766
  return result;
2534
2767
  }
2535
- async function sendActivityInternal({ activity, activityId, keys, inbox, allowPrivateAddress, headers, specDeterminer, tracerProvider }, span) {
2768
+ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPrivateAddress, headers, specDeterminer, tracerProvider }, span, deps) {
2536
2769
  const logger = (0, _logtape_logtape.getLogger)([
2537
2770
  "fedify",
2538
2771
  "federation",
2539
2772
  "outbox"
2540
2773
  ]);
2541
- async function validateUrl(url) {
2542
- if (!allowPrivateAddress) try {
2543
- await (0, _fedify_vocab_runtime.validatePublicUrl)(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 }));
2778
+ let opened = false;
2779
+ async function openHop(url) {
2780
+ let session;
2781
+ try {
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
+ }
2544
2792
  } catch (error) {
2545
2793
  if (error instanceof _fedify_vocab_runtime.UrlError && error.reason === "dns") {
2546
2794
  logger.error("DNS resolution failed for URL: {url}", {
@@ -2557,15 +2805,17 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2557
2805
  });
2558
2806
  throw error;
2559
2807
  }
2808
+ opened = true;
2809
+ return session;
2560
2810
  }
2561
- await validateUrl(inbox.href);
2562
2811
  headers = new Headers(headers);
2563
2812
  headers.set("Content-Type", "application/activity+json");
2564
2813
  const request = new Request(inbox, {
2565
2814
  method: "POST",
2566
2815
  headers,
2567
2816
  body: JSON.stringify(activity),
2568
- redirect: "manual"
2817
+ redirect: "manual",
2818
+ signal
2569
2819
  });
2570
2820
  let rsaKey = null;
2571
2821
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -2579,36 +2829,60 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2579
2829
  privateKey: pair.privateKey
2580
2830
  }))
2581
2831
  });
2582
- let response;
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);
2583
2854
  try {
2584
- response = rsaKey == null ? await fetchWithValidatedRedirects(request, validateUrl) : await require_http.doubleKnock(request, rsaKey, {
2855
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await require_http.doubleKnockScoped(request, rsaKey, {
2585
2856
  tracerProvider,
2586
- specDeterminer,
2587
- validateRedirect: validateUrl
2588
- });
2857
+ specDeterminer: boundedSpecDeterminer,
2858
+ signal
2859
+ }, openHop, (response) => consumeSendActivityResponse(response, inbox, signal));
2589
2860
  } catch (error) {
2590
- 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}", {
2591
2868
  activityId,
2592
2869
  inbox: inbox.href,
2593
- error
2870
+ error: failureError
2594
2871
  });
2595
- throw error;
2872
+ throw failureError;
2873
+ } finally {
2874
+ clearTimeout(timer);
2596
2875
  }
2597
- if (!response.ok) {
2598
- let error;
2599
- try {
2600
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
2601
- } catch (_) {
2602
- error = "";
2603
- }
2876
+ if (!outcome.ok) {
2877
+ const { status, statusText, error } = outcome;
2604
2878
  logger.error("Failed to send activity {activityId} to {inbox} ({status} {statusText}):\n{error}", {
2605
2879
  activityId,
2606
2880
  inbox: inbox.href,
2607
- status: response.status,
2608
- statusText: response.statusText,
2881
+ status,
2882
+ statusText,
2609
2883
  error
2610
2884
  });
2611
- throw new SendActivityError(inbox, response.status, `Failed to send activity ${activityId} to ${inbox.href} (${response.status} ${response.statusText}):\n${error}`, error);
2885
+ throw new SendActivityError(inbox, status, `Failed to send activity ${activityId} to ${inbox.href} (${status} ${statusText}):\n${error}`, error);
2612
2886
  }
2613
2887
  span.addEvent("activitypub.activity.sent", {
2614
2888
  "activitypub.activity.json": JSON.stringify(activity),
@@ -2616,10 +2890,79 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2616
2890
  "activitypub.activity.id": activityId ?? ""
2617
2891
  });
2618
2892
  }
2619
- async function fetchWithValidatedRedirects(request, validateUrl) {
2893
+ /**
2894
+ * Starts cancelling the body of a response without waiting for it to settle.
2895
+ * The cancellation of a branch of a tee (e.g., a body cloned by a fetch mock)
2896
+ * settles only after the other branch is cancelled too, per the Streams
2897
+ * standard, so awaiting it could block forever. Failures are only logged.
2898
+ */
2899
+ function cancelResponseBody(response, url) {
2900
+ response.body?.cancel().catch((error) => {
2901
+ (0, _logtape_logtape.getLogger)([
2902
+ "fedify",
2903
+ "federation",
2904
+ "outbox"
2905
+ ]).debug("Failed to cancel the response body from {url}: {error}", {
2906
+ url,
2907
+ error
2908
+ });
2909
+ });
2910
+ }
2911
+ /**
2912
+ * Reads what is needed from the final response of a delivery while its
2913
+ * session is open: the body of a successful response is cancelled, and at
2914
+ * most 1 KiB of an error response body is read.
2915
+ */
2916
+ async function consumeSendActivityResponse(response, inbox, signal) {
2917
+ if (response.ok) {
2918
+ cancelResponseBody(response, response.url || inbox.href);
2919
+ return { ok: true };
2920
+ }
2921
+ let error;
2922
+ try {
2923
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
2924
+ } catch (_) {
2925
+ error = "";
2926
+ }
2927
+ if (signal.aborted) error = "(timed out reading response body)";
2928
+ return {
2929
+ ok: false,
2930
+ status: response.status,
2931
+ statusText: response.statusText,
2932
+ error
2933
+ };
2934
+ }
2935
+ /**
2936
+ * Sends a request without signing it, following redirects manually like the
2937
+ * Fetch standard does. Every hop is opened with `openHop()`, which validates
2938
+ * the destination, after the previous hop is closed. The final response is
2939
+ * passed to `consume()`, and its session is closed after that.
2940
+ * This is exported only for tests; it is not exported from any entry point.
2941
+ * @param request The request to send.
2942
+ * @param openHop The function to open a session for each hop.
2943
+ * @param consume The function to consume the final response.
2944
+ * @returns The value returned by `consume`.
2945
+ */
2946
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
2947
+ const logger = (0, _logtape_logtape.getLogger)([
2948
+ "fedify",
2949
+ "federation",
2950
+ "outbox"
2951
+ ]);
2620
2952
  let body = await request.clone().text();
2621
2953
  for (let redirects = 0;; redirects++) {
2622
- const response = await fetch(request, { redirect: "manual" });
2954
+ signal?.throwIfAborted();
2955
+ const session = await openHop(request.url);
2956
+ let response;
2957
+ try {
2958
+ response = await session.fetch(request, {
2959
+ redirect: "manual",
2960
+ signal
2961
+ });
2962
+ } catch (error) {
2963
+ await closeAfterError(session, logger);
2964
+ throw error;
2965
+ }
2623
2966
  const location = response.headers.get("Location");
2624
2967
  if (![
2625
2968
  301,
@@ -2627,11 +2970,21 @@ async function fetchWithValidatedRedirects(request, validateUrl) {
2627
2970
  303,
2628
2971
  307,
2629
2972
  308
2630
- ].includes(response.status) || location == null) return response;
2631
- await response.body?.cancel();
2973
+ ].includes(response.status) || location == null) try {
2974
+ return await consume(response);
2975
+ } catch (error) {
2976
+ logger.debug("Failed to consume the response from {url}; closing the session: {error}", {
2977
+ url: request.url,
2978
+ error
2979
+ });
2980
+ throw error;
2981
+ } finally {
2982
+ await session.close();
2983
+ }
2984
+ cancelResponseBody(response, request.url);
2985
+ await session.close();
2632
2986
  if (redirects >= 20) throw new TypeError("Too many redirects");
2633
2987
  const url = new URL(location, request.url);
2634
- await validateUrl(url.href);
2635
2988
  const headers = new Headers(request.headers);
2636
2989
  if (url.origin !== new URL(request.url).origin) {
2637
2990
  headers.delete("Authorization");
@@ -2655,7 +3008,18 @@ async function fetchWithValidatedRedirects(request, validateUrl) {
2655
3008
  method,
2656
3009
  headers,
2657
3010
  body,
2658
- redirect: "manual"
3011
+ redirect: "manual",
3012
+ signal: signal ?? request.signal
3013
+ });
3014
+ }
3015
+ }
3016
+ async function closeAfterError(session, logger) {
3017
+ try {
3018
+ await session.close();
3019
+ } catch (error) {
3020
+ logger.debug("Failed to close the session for {url}: {error}", {
3021
+ url: session.url.href,
3022
+ error
2659
3023
  });
2660
3024
  }
2661
3025
  }
@@ -2998,8 +3362,25 @@ var FederationImpl = class extends FederationBuilderImpl {
2998
3362
  _getTracer() {
2999
3363
  return this.tracerProvider.getTracer(require_http.name, require_http.version);
3000
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
+ }
3001
3382
  async _startQueueInternal(ctxData, signal, queue) {
3002
- if (this.inboxQueue == null && this.outboxQueue == null) return;
3383
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
3003
3384
  const logger = (0, _logtape_logtape.getLogger)([
3004
3385
  "fedify",
3005
3386
  "federation",
@@ -3009,20 +3390,38 @@ var FederationImpl = class extends FederationBuilderImpl {
3009
3390
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
3010
3391
  logger.debug("Starting an inbox task worker.");
3011
3392
  this.inboxQueueStarted = true;
3012
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3393
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
3013
3394
  }
3014
3395
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
3015
3396
  logger.debug("Starting an outbox task worker.");
3016
3397
  this.outboxQueueStarted = true;
3017
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3398
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
3018
3399
  }
3019
3400
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
3020
3401
  logger.debug("Starting a fanout task worker.");
3021
3402
  this.fanoutQueueStarted = true;
3022
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3403
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
3023
3404
  }
3024
3405
  await Promise.all(promises);
3025
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
+ }
3026
3425
  processQueuedTask(contextData, message) {
3027
3426
  const tracer = this._getTracer();
3028
3427
  const extractedContext = _opentelemetry_api.propagation.extract(_opentelemetry_api.context.active(), message.traceContext);
@@ -3131,7 +3530,8 @@ var FederationImpl = class extends FederationBuilderImpl {
3131
3530
  await this.sendActivity(keys, message.inboxes, activity, {
3132
3531
  collectionSync: message.collectionSync,
3133
3532
  orderingKey: message.orderingKey,
3134
- context
3533
+ context,
3534
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
3135
3535
  });
3136
3536
  }
3137
3537
  async #listenOutboxMessage(_, message, span) {
@@ -3334,7 +3734,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3334
3734
  let parseInput = void 0;
3335
3735
  let parseContextLoader = context.contextLoader;
3336
3736
  try {
3337
- const hasSignatureField = require_proof.hasSignature(message.activity);
3737
+ const hasSignatureField = require_proof.hasVerifiableSignature(message.activity);
3338
3738
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
3339
3739
  const parseContext = hasSignatureField ? {
3340
3740
  ...context,
@@ -3529,19 +3929,29 @@ var FederationImpl = class extends FederationBuilderImpl {
3529
3929
  proofCreated = true;
3530
3930
  break;
3531
3931
  }
3532
- if (!proofCreated) {
3533
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3534
- activity = await require_proof.signObject(activity, privateKey, keyId, {
3535
- contextLoader,
3536
- tracerProvider: this.tracerProvider
3537
- });
3538
- 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
+ }
3539
3949
  }
3950
+ jsonLd = options.activityJsonLd != null ? require_proof.detachSignature(options.activityJsonLd) : await activity.toJsonLd({
3951
+ format: "compact",
3952
+ contextLoader
3953
+ });
3540
3954
  }
3541
- let jsonLd = await activity.toJsonLd({
3542
- format: "compact",
3543
- contextLoader
3544
- });
3545
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.", {
3546
3956
  activityId,
3547
3957
  keys: keys.map((pair) => ({
@@ -3578,19 +3988,27 @@ var FederationImpl = class extends FederationBuilderImpl {
3578
3988
  activity: jsonLd
3579
3989
  });
3580
3990
  const promises = [];
3581
- for (const inbox in inboxes) promises.push(sendActivity({
3582
- allowPrivateAddress: this.allowPrivateAddress,
3583
- keys,
3584
- activity: jsonLd,
3585
- activityId: activity.id?.href,
3586
- activityType: (0, _fedify_vocab.getTypeId)(activity).href,
3587
- inbox: new URL(inbox),
3588
- sharedInbox: inboxes[inbox].sharedInbox,
3589
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3590
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3591
- tracerProvider: this.tracerProvider
3592
- }));
3593
- 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
+ }
3594
4012
  return;
3595
4013
  }
3596
4014
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -3605,7 +4023,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3605
4023
  privateKey: privateKeyJwk
3606
4024
  });
3607
4025
  }
3608
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
4026
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
3609
4027
  const carrier = {};
3610
4028
  _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), carrier);
3611
4029
  const messages = [];
@@ -3817,7 +4235,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3817
4235
  const identity = await this.sharedInboxKeyDispatcher(context);
3818
4236
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
3819
4237
  }
3820
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
4238
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
3821
4239
  const inboxContextFactory = context.toInboxContext.bind(context);
3822
4240
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
3823
4241
  return await handleInbox(request, {
@@ -4140,6 +4558,8 @@ var ContextImpl = class ContextImpl {
4140
4558
  for (const keyPair of keyPairs) {
4141
4559
  const newPair = {
4142
4560
  ...keyPair,
4561
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(keyPair.privateKey),
4562
+ publicKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(keyPair.publicKey),
4143
4563
  cryptographicKey: new _fedify_vocab.CryptographicKey({
4144
4564
  id: keyPair.keyId,
4145
4565
  owner,
@@ -4216,10 +4636,16 @@ var ContextImpl = class ContextImpl {
4216
4636
  } else identifierPromise = Promise.resolve(identity.identifier);
4217
4637
  return identifierPromise.then((identifier) => {
4218
4638
  if (identifier == null) return this.documentLoader;
4219
- 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
+ }));
4220
4643
  });
4221
4644
  }
4222
- 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
+ });
4223
4649
  }
4224
4650
  lookupObject(identifier, options = {}) {
4225
4651
  return (0, _fedify_vocab.lookupObject)(identifier, {
@@ -4242,10 +4668,14 @@ var ContextImpl = class ContextImpl {
4242
4668
  return options.parse === "none" ? require_types.getNodeInfo(url, {
4243
4669
  parse: "none",
4244
4670
  direct: options.direct,
4671
+ timeout: options.timeout,
4672
+ signal: options.signal,
4245
4673
  userAgent: options?.userAgent ?? this.federation.userAgent
4246
4674
  }) : require_types.getNodeInfo(url, {
4247
4675
  parse: options.parse,
4248
4676
  direct: options.direct,
4677
+ timeout: options.timeout,
4678
+ signal: options.signal,
4249
4679
  userAgent: options?.userAgent ?? this.federation.userAgent
4250
4680
  });
4251
4681
  }
@@ -4257,7 +4687,17 @@ var ContextImpl = class ContextImpl {
4257
4687
  allowPrivateAddress: this.federation.allowPrivateAddress
4258
4688
  });
4259
4689
  }
4260
- 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
+ }
4261
4701
  return this.tracerProvider.getTracer(require_http.name, require_http.version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
4262
4702
  kind: this.federation.outboxQueue == null || options.immediate ? _opentelemetry_api.SpanKind.CLIENT : _opentelemetry_api.SpanKind.PRODUCER,
4263
4703
  attributes: {
@@ -4270,7 +4710,7 @@ var ContextImpl = class ContextImpl {
4270
4710
  }, async (span) => {
4271
4711
  try {
4272
4712
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
4273
- await this.sendActivityInternal(sender, recipients, activity, options, span);
4713
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
4274
4714
  } catch (e) {
4275
4715
  span.setStatus({
4276
4716
  code: _opentelemetry_api.SpanStatusCode.ERROR,
@@ -4282,7 +4722,7 @@ var ContextImpl = class ContextImpl {
4282
4722
  }
4283
4723
  });
4284
4724
  }
4285
- async sendActivityInternal(sender, recipients, activity, options, span) {
4725
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
4286
4726
  const logger = (0, _logtape_logtape.getLogger)([
4287
4727
  "fedify",
4288
4728
  "federation",
@@ -4329,14 +4769,23 @@ var ContextImpl = class ContextImpl {
4329
4769
  if (!(error instanceof RouterError)) throw error;
4330
4770
  }
4331
4771
  } else expandedRecipients = [recipients];
4332
- const opts = {
4333
- context: this,
4334
- orderingKey: options.orderingKey,
4335
- collectionSync,
4336
- immediate: options.immediate
4337
- };
4338
4772
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
4339
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
+ }
4340
4789
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
4341
4790
  if (activity.actorId == null) {
4342
4791
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -4347,14 +4796,39 @@ var ContextImpl = class ContextImpl {
4347
4796
  }
4348
4797
  if (actorKeyPairs != null) {
4349
4798
  const contextLoader = this.contextLoader;
4350
- for (const kp of actorKeyPairs) {
4351
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4352
- activity = await require_proof.signObject(activity, kp.privateKey, kp.multikey.id, {
4353
- contextLoader,
4354
- tracerProvider: this.tracerProvider
4355
- });
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;
4356
4823
  }
4357
4824
  }
4825
+ const opts = {
4826
+ context: this,
4827
+ orderingKey: options.orderingKey,
4828
+ collectionSync,
4829
+ immediate: options.immediate,
4830
+ activityJsonLd
4831
+ };
4358
4832
  const inboxes = extractInboxes({
4359
4833
  recipients: expandedRecipients,
4360
4834
  preferSharedInbox: options.preferSharedInbox,
@@ -4384,7 +4858,7 @@ var ContextImpl = class ContextImpl {
4384
4858
  actorIds: [...actorIds],
4385
4859
  sharedInbox
4386
4860
  }])),
4387
- activity: await activity.toJsonLd({
4861
+ activity: activityJsonLd != null ? require_proof.detachSignature(activityJsonLd) : await activity.toJsonLd({
4388
4862
  format: "compact",
4389
4863
  contextLoader: this.contextLoader
4390
4864
  }),
@@ -4394,7 +4868,7 @@ var ContextImpl = class ContextImpl {
4394
4868
  orderingKey: options.orderingKey,
4395
4869
  traceContext: carrier
4396
4870
  };
4397
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
4871
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
4398
4872
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
4399
4873
  }
4400
4874
  async *getFollowers(identifier) {
@@ -4591,43 +5065,83 @@ var RequestContextImpl = class RequestContextImpl extends ContextImpl {
4591
5065
  }
4592
5066
  }), values);
4593
5067
  }
4594
- #signedKey = void 0;
5068
+ #signedKey = null;
5069
+ #signedKeyOwner = null;
5070
+ #signatureChecks = /* @__PURE__ */ new WeakMap();
5071
+ #getSignatureCheck(documentLoader, contextLoader) {
5072
+ let checks = this.#signatureChecks.get(documentLoader);
5073
+ if (checks == null) {
5074
+ checks = /* @__PURE__ */ new WeakMap();
5075
+ this.#signatureChecks.set(documentLoader, checks);
5076
+ }
5077
+ let check = checks.get(contextLoader);
5078
+ if (check == null) {
5079
+ check = {};
5080
+ checks.set(contextLoader, check);
5081
+ }
5082
+ return check;
5083
+ }
4595
5084
  async getSignedKey(options = {}) {
4596
5085
  if (this.#signedKey != null) return this.#signedKey;
4597
- return this.#signedKey = await require_http.verifyRequest(this.request, {
5086
+ const documentLoader = options.documentLoader ?? this.documentLoader;
5087
+ const contextLoader = options.contextLoader ?? this.contextLoader;
5088
+ const check = this.#getSignatureCheck(documentLoader, contextLoader);
5089
+ if (check.key != null) return check.key;
5090
+ const promise = require_http.verifyRequest(this.request, {
4598
5091
  ...this,
4599
- contextLoader: options.contextLoader ?? this.contextLoader,
4600
- documentLoader: options.documentLoader ?? this.documentLoader,
5092
+ contextLoader,
5093
+ documentLoader,
4601
5094
  timeWindow: this.federation.signatureTimeWindow,
4602
5095
  tracerProvider: options.tracerProvider ?? this.tracerProvider
5096
+ }).then((key) => {
5097
+ if (key != null) this.#signedKey ??= key;
5098
+ return key;
5099
+ }).catch((error) => {
5100
+ if (check.key === promise) check.key = void 0;
5101
+ throw error;
4603
5102
  });
5103
+ check.key = promise;
5104
+ return await promise;
4604
5105
  }
4605
- #signedKeyOwner = void 0;
4606
5106
  async getSignedKeyOwner(options = {}) {
4607
5107
  if (this.#signedKeyOwner != null) return this.#signedKeyOwner;
4608
- const key = await this.getSignedKey(options);
4609
- if (key == null) return this.#signedKeyOwner = null;
4610
- try {
4611
- return this.#signedKeyOwner = await require_proof.getKeyOwner(key, {
4612
- contextLoader: options.contextLoader ?? this.contextLoader,
4613
- documentLoader: options.documentLoader ?? this.documentLoader,
4614
- tracerProvider: options.tracerProvider ?? this.tracerProvider
4615
- });
4616
- } catch (error) {
4617
- if (error instanceof _fedify_vocab_runtime.FetchError) {
4618
- (0, _logtape_logtape.getLogger)([
4619
- "fedify",
4620
- "federation",
4621
- "actor"
4622
- ]).warn("Failed to fetch the key owner {keyOwner} of {keyId} while verifying the request signature; treating the request as unauthenticated: {error}", {
4623
- keyId: key.id?.href,
4624
- keyOwner: error.url.href,
4625
- error
4626
- });
4627
- return this.#signedKeyOwner = null;
5108
+ const normalizedOptions = {
5109
+ documentLoader: options.documentLoader ?? this.documentLoader,
5110
+ contextLoader: options.contextLoader ?? this.contextLoader,
5111
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
5112
+ };
5113
+ const check = this.#getSignatureCheck(normalizedOptions.documentLoader, normalizedOptions.contextLoader);
5114
+ if (check.owner != null) return check.owner;
5115
+ const promise = this.getSignedKey(normalizedOptions).then(async (key) => {
5116
+ if (key == null) {
5117
+ if (check.owner === promise) check.owner = void 0;
5118
+ return null;
4628
5119
  }
5120
+ try {
5121
+ const owner = await require_proof.getKeyOwner(key, normalizedOptions);
5122
+ if (owner != null) this.#signedKeyOwner ??= owner;
5123
+ return owner;
5124
+ } catch (error) {
5125
+ if (error instanceof _fedify_vocab_runtime.FetchError) {
5126
+ (0, _logtape_logtape.getLogger)([
5127
+ "fedify",
5128
+ "federation",
5129
+ "actor"
5130
+ ]).warn("Failed to fetch the key owner {keyOwner} of {keyId} while verifying the request signature; treating the request as unauthenticated: {error}", {
5131
+ keyId: key.id?.href,
5132
+ keyOwner: error.url.href,
5133
+ error
5134
+ });
5135
+ return null;
5136
+ }
5137
+ throw error;
5138
+ }
5139
+ }).catch((error) => {
5140
+ if (check.owner === promise) check.owner = void 0;
4629
5141
  throw error;
4630
- }
5142
+ });
5143
+ check.owner = promise;
5144
+ return await promise;
4631
5145
  }
4632
5146
  };
4633
5147
  var InboxContextImpl = class InboxContextImpl extends ContextImpl {
@@ -4708,7 +5222,7 @@ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
4708
5222
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
4709
5223
  keys = forwarder;
4710
5224
  } else keys = [forwarder];
4711
- if (!require_proof.hasSignature(this.activity)) {
5225
+ if (!require_proof.hasVerifiableSignature(this.activity)) {
4712
5226
  let hasProof;
4713
5227
  try {
4714
5228
  hasProof = await (await _fedify_vocab.Activity.fromJsonLd(this.activity, this)).getProof() != null;
@@ -4740,18 +5254,26 @@ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
4740
5254
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
4741
5255
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
4742
5256
  const promises = [];
4743
- for (const inbox in inboxes) promises.push(sendActivity({
4744
- allowPrivateAddress: this.federation.allowPrivateAddress,
4745
- keys,
4746
- activity: this.activity,
4747
- activityId: this.activityId,
4748
- activityType: this.activityType,
4749
- inbox: new URL(inbox),
4750
- sharedInbox: inboxes[inbox].sharedInbox,
4751
- tracerProvider: this.tracerProvider,
4752
- specDeterminer: new KvSpecDeterminer(this.federation.kv, this.federation.kvPrefixes.httpMessageSignaturesSpec, this.federation.firstKnock)
4753
- }));
4754
- 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
+ }
4755
5277
  return;
4756
5278
  }
4757
5279
  logger.debug("Enqueuing activity {activityId} to forward later.", {
@@ -4846,6 +5368,69 @@ var KvSpecDeterminer = class {
4846
5368
  function notFound(_request) {
4847
5369
  return new Response("Not Found", { status: 404 });
4848
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
+ }
4849
5434
  function notAcceptable(_request) {
4850
5435
  return new Response("Not Acceptable", {
4851
5436
  status: 406,