@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,20 +2,23 @@ import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  import { t as __exportAll } from "./chunk-CRNNMoPX.js";
4
4
  import { r as getDefaultActivityTransformers } from "./transformers-BGMIq1cs.js";
5
- import { a as verifyRequestDetailed, d as importJwk, f as validateCryptoKey, i as verifyRequest, m as formatAcceptSignature, n as parseRfc9421SignatureInput, o as exportJwk, t as doubleKnock, v as name, y as version } from "./http-CK3efjgM.js";
6
- import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-miAYfiGO.js";
7
- import { _ as signJsonLd, a as doesActorOwnKey, c as assertSafeJsonLd, f as detachSignature, g as isInvalidUrlTypeError, h as isClearlyMalformedContextReference, m as hasSignature, n as signObject, o as getKeyOwner, p as getNormalizationContextLoader, r as verifyObject, s as InvalidContextReferenceError, u as compactJsonLd, v as verifyCompactJsonLd, x as wrapContextLoaderForJsonLd } from "./proof-7R4s10TJ.js";
8
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-ImApO425.js";
5
+ import { a as verifyRequestDetailed, d as importJwk, f as validateCryptoKey, i as verifyRequest, m as formatAcceptSignature, n as parseRfc9421SignatureInput, o as exportJwk, t as doubleKnockScoped, v as name, y as version } from "./http-BtbMAgTA.js";
6
+ import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-CXy2lRVU.js";
7
+ import { S as wrapContextLoaderForJsonLd, _ as isInvalidUrlTypeError, a as doesActorOwnKey, c as assertSafeJsonLd, f as describeSignatureShape, g as isClearlyMalformedContextReference, h as hasVerifiableSignature, m as getNormalizationContextLoader, n as signObject, o as getKeyOwner, p as detachSignature, r as verifyObject, s as InvalidContextReferenceError, u as compactJsonLd, v as signJsonLd, y as verifyCompactJsonLd } from "./proof-Du4-5SHY.js";
8
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-BsDg-cT8.js";
9
9
  import { getLogger, withContext } from "@logtape/logtape";
10
- import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
10
+ import { Activity, Collection, CollectionPage, CryptographicKey, DataIntegrityProof, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
11
11
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
12
12
  import { cloneDeep, uniq } from "es-toolkit";
13
13
  import { Router } from "uri-template-router";
14
14
  import { parseTemplate } from "url-template";
15
15
  import { encodeHex } from "byte-encodings/hex";
16
- import { FetchError, UrlError, getDocumentLoader, validatePublicUrl } from "@fedify/vocab-runtime";
17
- import { ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_HEADER, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
16
+ import { FetchError, UrlError, encodeMultibase, getDocumentLoader, preloadedContexts } from "@fedify/vocab-runtime";
18
17
  import jsonld from "@fedify/vocab-runtime/jsonld";
18
+ import { asCryptoKey, openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
19
+ import { ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_HEADER, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
20
+ import serialize from "json-canon";
21
+ import { normalizeDateTimeLiteral } from "@fedify/vocab-runtime/temporal";
19
22
  import { lookupWebFinger } from "@fedify/webfinger";
20
23
  import { domainToASCII } from "node:url";
21
24
  //#region src/federation/inbox.ts
@@ -881,6 +884,110 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
881
884
  return `collectionId="${collectionId}", url="${url}", digest="${encodeHex(await digest(actorIds))}"`;
882
885
  }
883
886
  //#endregion
887
+ //#region src/compat/attachment-arrays.ts
888
+ const logger$1 = getLogger([
889
+ "fedify",
890
+ "compat",
891
+ "attachment-arrays"
892
+ ]);
893
+ const MAX_DEPTH = 64;
894
+ const ATTACHMENT = "https://www.w3.org/ns/activitystreams#attachment";
895
+ const PROOF = "https://w3id.org/security#proof";
896
+ /** Recognizes JSON-LD maps without accepting arrays or scalar values. */
897
+ function isMap(value) {
898
+ return typeof value === "object" && value != null && !Array.isArray(value);
899
+ }
900
+ /** Copies only changed branches; cached vocabulary JSON belongs to its owner. */
901
+ function walk(value, depth = 0) {
902
+ if (depth >= MAX_DEPTH) throw new RangeError("JSON-LD nesting limit exceeded.");
903
+ if (Array.isArray(value)) {
904
+ const items = value.map((item) => walk(item, depth + 1));
905
+ return items.some((item, i) => item !== value[i]) ? items : value;
906
+ }
907
+ if (!isMap(value)) return value;
908
+ if (Object.hasOwn(value, "@value")) return value;
909
+ let result;
910
+ for (const [key, item] of Object.entries(value)) {
911
+ let next = key === "@context" ? item : walk(item, depth + 1);
912
+ if ((key === "attachment" || key === ATTACHMENT) && next != null && !Array.isArray(next) && !(isMap(next) && Object.hasOwn(next, "@list"))) next = [next];
913
+ if (next !== item) {
914
+ result ??= Object.assign(Object.create(null), value);
915
+ result[key] = next;
916
+ }
917
+ }
918
+ return result ?? value;
919
+ }
920
+ const preloadedLoader = (url) => {
921
+ if (!Object.hasOwn(preloadedContexts, url)) return Promise.reject(/* @__PURE__ */ new Error("Unknown JSON-LD context: " + url));
922
+ return Promise.resolve({
923
+ contextUrl: null,
924
+ documentUrl: url,
925
+ document: preloadedContexts[url]
926
+ });
927
+ };
928
+ /** Reuses each context resolution across the complete equivalence check. */
929
+ function memoizeLoader(loader) {
930
+ const pending = /* @__PURE__ */ new Map();
931
+ return (url, options) => {
932
+ let result = pending.get(url);
933
+ if (result == null) {
934
+ result = loader(url, options);
935
+ pending.set(url, result);
936
+ }
937
+ return result;
938
+ };
939
+ }
940
+ /** Finds security predicates in expanded nodes, never inside JSON literals. */
941
+ function hasSecurityPredicate(value) {
942
+ if (Array.isArray(value)) return value.some(hasSecurityPredicate);
943
+ if (!isMap(value) || Object.hasOwn(value, "@value")) return false;
944
+ for (const [key, child] of Object.entries(value)) {
945
+ if (key === PROOF || key === "https://w3id.org/security#signature") return true;
946
+ if (hasSecurityPredicate(child)) return true;
947
+ }
948
+ return false;
949
+ }
950
+ /**
951
+ * Keeps singleton attachments in arrays for raw-JSON ActivityPub consumers.
952
+ * Mastodon's property_values() ignores valid compact JSON-LD scalar values,
953
+ * and its caller clears the profile fields in that case:
954
+ * https://github.com/mastodon/mastodon/blob/594166519a623584920c7e696bae9a009d9183ab/app/services/activitypub/process_account_service.rb#L465-L472
955
+ * Pixelfed likewise rejects singleton media attachments:
956
+ * https://github.com/pixelfed/pixelfed/issues/6588
957
+ *
958
+ * This workaround changes only attachment representation, after serialization.
959
+ * RDF equality protects custom contexts, including JSON literals; it does not
960
+ * protect JCS signatures. Any semantic proof or Linked Data signature leaves
961
+ * the whole serialized document unchanged, as does an unresolved context.
962
+ * This layer does not compose signed objects or repair vocabulary serialization.
963
+ * Remove this
964
+ * workaround only when the supported consumer versions, including deployed
965
+ * older releases, accept scalar attachments. Do not replace it with a
966
+ * vocabulary transformer: subsequent compaction collapses arrays.
967
+ * @internal
968
+ */
969
+ async function normalizeAttachmentArrays(document, contextLoader) {
970
+ try {
971
+ const normalized = walk(document);
972
+ if (normalized === document) return document;
973
+ const loader = memoizeLoader(contextLoader ?? preloadedLoader);
974
+ if (hasSecurityPredicate(await jsonld.expand(document, { documentLoader: loader }))) return document;
975
+ const [before, after] = await Promise.allSettled([jsonld.canonize(document, {
976
+ format: "application/n-quads",
977
+ documentLoader: loader
978
+ }), jsonld.canonize(normalized, {
979
+ format: "application/n-quads",
980
+ documentLoader: loader
981
+ })]);
982
+ if (before.status === "rejected") throw before.reason;
983
+ if (after.status === "rejected") throw after.reason;
984
+ if (before.value === after.value) return normalized;
985
+ } catch (error) {
986
+ logger$1.debug("Could not safely normalize attachment arrays; preserving the document: {error}", { error });
987
+ }
988
+ return document;
989
+ }
990
+ //#endregion
884
991
  //#region src/federation/keycache.ts
885
992
  const KEY_CACHE_GENERATION = "3";
886
993
  var KvKeyCache = class {
@@ -1068,9 +1175,6 @@ function acceptsJsonLd(request) {
1068
1175
  function isPlainObject(value) {
1069
1176
  return typeof value === "object" && value != null && !Array.isArray(value);
1070
1177
  }
1071
- function normalizeDateTimeLiteral(value) {
1072
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1073
- }
1074
1178
  function isMalformedDateTimeLiteral(value) {
1075
1179
  if (typeof value !== "string") return false;
1076
1180
  try {
@@ -1112,7 +1216,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1112
1216
  if (typeof literal === "boolean") return false;
1113
1217
  if (typeof literal !== "string") return false;
1114
1218
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1115
- if (new Date(literal).toString() === "Invalid Date") return false;
1219
+ if (new Date(literal).toString() === "Invalid Date" && new Date(normalizeDateTimeLiteral(literal)).toString() === "Invalid Date") return false;
1116
1220
  return isMalformedDateTimeLiteral(literal);
1117
1221
  }
1118
1222
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1206,7 +1310,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1206
1310
  if (authorizePredicate != null) {
1207
1311
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1208
1312
  }
1209
- const jsonLd = await actor.toJsonLd(context);
1313
+ const jsonLd = await serializeForResponse(actor, context);
1210
1314
  return new Response(JSON.stringify(jsonLd), { headers: {
1211
1315
  "Content-Type": "application/activity+json",
1212
1316
  Vary: "Accept"
@@ -1226,7 +1330,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1226
1330
  if (authorizePredicate != null) {
1227
1331
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1228
1332
  }
1229
- const jsonLd = await object.toJsonLd(context);
1333
+ const jsonLd = await serializeForResponse(object, context);
1230
1334
  return new Response(JSON.stringify(jsonLd), { headers: {
1231
1335
  "Content-Type": "application/activity+json",
1232
1336
  Vary: "Accept"
@@ -1357,7 +1461,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1357
1461
  if (collectionCallbacks.authorizePredicate != null) {
1358
1462
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
1359
1463
  }
1360
- const jsonLd = await collection.toJsonLd(context);
1464
+ const jsonLd = await serializeForResponse(collection, context);
1361
1465
  return new Response(JSON.stringify(jsonLd), { headers: {
1362
1466
  "Content-Type": "application/activity+json",
1363
1467
  Vary: "Accept"
@@ -1509,7 +1613,11 @@ async function handleInboxInternal(request, parameters, span) {
1509
1613
  }
1510
1614
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
1511
1615
  const jsonWithoutSig = detachSignature(json);
1512
- const hasLdSignature = hasSignature(json);
1616
+ const hasLdSignature = hasVerifiableSignature(json);
1617
+ if (!hasLdSignature) {
1618
+ const shape = describeSignatureShape(json);
1619
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
1620
+ }
1513
1621
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
1514
1622
  let deferredLdSignatureError = void 0;
1515
1623
  const respondInvalidActivity = async (error) => {
@@ -1988,7 +2096,7 @@ var CustomCollectionHandler = class {
1988
2096
  * @returns A promise that resolves to the JSON-LD representation.
1989
2097
  */
1990
2098
  async toJsonLd() {
1991
- return (await this.collection).toJsonLd(this.context);
2099
+ return serializeForResponse(await this.collection, this.context);
1992
2100
  }
1993
2101
  /**
1994
2102
  * Fetches the collection with optional cursor for pagination.
@@ -2291,7 +2399,7 @@ var UnauthorizedError = class extends HandlerError {
2291
2399
  * @since 0.3.0
2292
2400
  */
2293
2401
  async function respondWithObject(object, options) {
2294
- const jsonLd = await object.toJsonLd(options);
2402
+ const jsonLd = await serializeForResponse(object, options);
2295
2403
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
2296
2404
  }
2297
2405
  /**
@@ -2379,6 +2487,106 @@ const MIN_COMPONENTS = [
2379
2487
  "@target-uri",
2380
2488
  "@authority"
2381
2489
  ];
2490
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
2491
+ async function serializeForResponse(object, options) {
2492
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
2493
+ }
2494
+ //#endregion
2495
+ //#region src/sig/proof-creation.ts
2496
+ /** Signs the exact serialized message supplied by an internal producer. */
2497
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
2498
+ validateCryptoKey(privateKey, "private");
2499
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
2500
+ const encoder = new TextEncoder();
2501
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(jsonLd)));
2502
+ created ??= Temporal.Now.instant();
2503
+ const proofConfig = {
2504
+ "@context": jsonLd["@context"],
2505
+ type: "DataIntegrityProof",
2506
+ cryptosuite: "eddsa-jcs-2022",
2507
+ verificationMethod: keyId.href,
2508
+ proofPurpose: "assertionMethod",
2509
+ created: created.toString()
2510
+ };
2511
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(proofConfig)));
2512
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
2513
+ digest.set(new Uint8Array(proofDigest), 0);
2514
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
2515
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
2516
+ return new DataIntegrityProof({
2517
+ cryptosuite: "eddsa-jcs-2022",
2518
+ verificationMethod: keyId,
2519
+ proofPurpose: "assertionMethod",
2520
+ created,
2521
+ proofValue: new Uint8Array(sig)
2522
+ });
2523
+ }
2524
+ //#endregion
2525
+ //#region src/compat/delivery-jsonld.ts
2526
+ /**
2527
+ * Returns changed attachment JSON only; unchanged documents keep the existing
2528
+ * delivery signing path. This uses ordinary vocabulary serialization, without
2529
+ * retaining or repairing independently signed child representations.
2530
+ */
2531
+ async function prepareActivityJsonLd(activity, contextLoader) {
2532
+ if (activity.proofIds.length > 0) return void 0;
2533
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
2534
+ const source = await activity.clone().toJsonLd({
2535
+ format: "compact",
2536
+ contextLoader
2537
+ });
2538
+ const prepared = await normalizeAttachmentArrays(source, contextLoader);
2539
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
2540
+ }
2541
+ /** Signs a changed, proof-free delivery map without serializing it again. */
2542
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
2543
+ const proofs = [];
2544
+ const serializedProofs = [];
2545
+ const tracer = (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version);
2546
+ for (const { privateKey, keyId } of keys) {
2547
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(activity).href } }, async (span) => {
2548
+ try {
2549
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
2550
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
2551
+ if (span.isRecording()) {
2552
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
2553
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
2554
+ span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
2555
+ }
2556
+ return proof;
2557
+ } catch (error) {
2558
+ span.setStatus({
2559
+ code: SpanStatusCode.ERROR,
2560
+ message: String(error)
2561
+ });
2562
+ throw error;
2563
+ } finally {
2564
+ span.end();
2565
+ }
2566
+ });
2567
+ proofs.push(proof);
2568
+ serializedProofs.push({
2569
+ "@context": unsigned["@context"],
2570
+ type: "DataIntegrityProof",
2571
+ cryptosuite: proof.cryptosuite,
2572
+ verificationMethod: keyId.href,
2573
+ proofPurpose: "assertionMethod",
2574
+ created: proof.created.toString(),
2575
+ proofValue: new TextDecoder().decode(encodeMultibase("base58btc", proof.proofValue))
2576
+ });
2577
+ }
2578
+ if (proofs.length === 0) return {
2579
+ activity,
2580
+ jsonLd: unsigned
2581
+ };
2582
+ return {
2583
+ activity: activity.clone({ proofs }),
2584
+ jsonLd: {
2585
+ ...unsigned,
2586
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
2587
+ }
2588
+ };
2589
+ }
2382
2590
  //#endregion
2383
2591
  //#region src/nodeinfo/handler.ts
2384
2592
  /**
@@ -2477,9 +2685,11 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2477
2685
  *
2478
2686
  * @param parameters The parameters for sending the activity.
2479
2687
  * See also {@link SendActivityParameters}.
2480
- * @throws {Error} If the activity fails to send.
2688
+ * @param deps The dependencies, for tests.
2689
+ * @throws {FetchError} If the delivery times out before receiving a response.
2690
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
2481
2691
  */
2482
- function sendActivity(options) {
2692
+ function sendActivity(options, deps = {}) {
2483
2693
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
2484
2694
  return tracerProvider.getTracer(name, version).startActiveSpan("activitypub.send_activity", {
2485
2695
  kind: SpanKind.CLIENT,
@@ -2491,7 +2701,7 @@ function sendActivity(options) {
2491
2701
  await sendActivityInternal({
2492
2702
  ...options,
2493
2703
  tracerProvider
2494
- }, span);
2704
+ }, span, deps);
2495
2705
  } catch (e) {
2496
2706
  span.setStatus({
2497
2707
  code: SpanStatusCode.ERROR,
@@ -2504,7 +2714,25 @@ function sendActivity(options) {
2504
2714
  });
2505
2715
  }
2506
2716
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
2507
- async function readLimitedResponseBody(response, maxBytes) {
2717
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
2718
+ function raceWithAbort(promise, signal) {
2719
+ if (signal.aborted) return Promise.reject(signal.reason);
2720
+ return new Promise((resolve, reject) => {
2721
+ const onAbort = () => {
2722
+ signal.removeEventListener("abort", onAbort);
2723
+ reject(signal.reason);
2724
+ };
2725
+ signal.addEventListener("abort", onAbort, { once: true });
2726
+ promise.then((value) => {
2727
+ signal.removeEventListener("abort", onAbort);
2728
+ resolve(value);
2729
+ }, (error) => {
2730
+ signal.removeEventListener("abort", onAbort);
2731
+ reject(error);
2732
+ });
2733
+ });
2734
+ }
2735
+ async function readLimitedResponseBody(response, maxBytes, signal) {
2508
2736
  if (response.body == null) return "";
2509
2737
  const reader = response.body.getReader();
2510
2738
  const decoder = new TextDecoder();
@@ -2513,7 +2741,8 @@ async function readLimitedResponseBody(response, maxBytes) {
2513
2741
  let truncated = false;
2514
2742
  try {
2515
2743
  while (true) {
2516
- const { done, value } = await reader.read();
2744
+ signal.throwIfAborted();
2745
+ const { done, value } = await raceWithAbort(reader.read(), signal);
2517
2746
  if (done) break;
2518
2747
  if (totalBytes + value.length > maxBytes) {
2519
2748
  const remaining = maxBytes - totalBytes;
@@ -2525,21 +2754,39 @@ async function readLimitedResponseBody(response, maxBytes) {
2525
2754
  totalBytes += value.length;
2526
2755
  }
2527
2756
  } finally {
2528
- reader.releaseLock();
2757
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
2758
+ try {
2759
+ reader.releaseLock();
2760
+ } catch (_) {}
2529
2761
  }
2530
2762
  let result = chunks.join("");
2531
2763
  if (truncated) result += "… (truncated)";
2532
2764
  return result;
2533
2765
  }
2534
- async function sendActivityInternal({ activity, activityId, keys, inbox, allowPrivateAddress, headers, specDeterminer, tracerProvider }, span) {
2766
+ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPrivateAddress, headers, specDeterminer, tracerProvider }, span, deps) {
2535
2767
  const logger = getLogger([
2536
2768
  "fedify",
2537
2769
  "federation",
2538
2770
  "outbox"
2539
2771
  ]);
2540
- async function validateUrl(url) {
2541
- if (!allowPrivateAddress) try {
2542
- await validatePublicUrl(url);
2772
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
2773
+ const controller = new AbortController();
2774
+ const { signal } = controller;
2775
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url, { signal }));
2776
+ let opened = false;
2777
+ async function openHop(url) {
2778
+ let session;
2779
+ try {
2780
+ signal.throwIfAborted();
2781
+ const opening = openUnvalidatedHop(url);
2782
+ opening.then((lateSession) => {
2783
+ if (signal.aborted) closeAfterError(lateSession, logger);
2784
+ }, () => {});
2785
+ session = await raceWithAbort(opening, signal);
2786
+ if (signal.aborted) {
2787
+ closeAfterError(session, logger);
2788
+ signal.throwIfAborted();
2789
+ }
2543
2790
  } catch (error) {
2544
2791
  if (error instanceof UrlError && error.reason === "dns") {
2545
2792
  logger.error("DNS resolution failed for URL: {url}", {
@@ -2556,15 +2803,17 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2556
2803
  });
2557
2804
  throw error;
2558
2805
  }
2806
+ opened = true;
2807
+ return session;
2559
2808
  }
2560
- await validateUrl(inbox.href);
2561
2809
  headers = new Headers(headers);
2562
2810
  headers.set("Content-Type", "application/activity+json");
2563
2811
  const request = new Request(inbox, {
2564
2812
  method: "POST",
2565
2813
  headers,
2566
2814
  body: JSON.stringify(activity),
2567
- redirect: "manual"
2815
+ redirect: "manual",
2816
+ signal
2568
2817
  });
2569
2818
  let rsaKey = null;
2570
2819
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -2578,36 +2827,60 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2578
2827
  privateKey: pair.privateKey
2579
2828
  }))
2580
2829
  });
2581
- let response;
2830
+ let outcome;
2831
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
2832
+ determineSpec(origin) {
2833
+ signal.throwIfAborted();
2834
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
2835
+ },
2836
+ rememberSpec(origin, spec) {
2837
+ if (signal.aborted) return;
2838
+ try {
2839
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
2840
+ origin,
2841
+ error
2842
+ }));
2843
+ } catch (error) {
2844
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
2845
+ origin,
2846
+ error
2847
+ });
2848
+ }
2849
+ }
2850
+ };
2851
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
2582
2852
  try {
2583
- response = rsaKey == null ? await fetchWithValidatedRedirects(request, validateUrl) : await doubleKnock(request, rsaKey, {
2853
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await doubleKnockScoped(request, rsaKey, {
2584
2854
  tracerProvider,
2585
- specDeterminer,
2586
- validateRedirect: validateUrl
2587
- });
2855
+ specDeterminer: boundedSpecDeterminer,
2856
+ signal
2857
+ }, openHop, (response) => consumeSendActivityResponse(response, inbox, signal));
2588
2858
  } catch (error) {
2589
- logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
2859
+ let failureError = error;
2860
+ if (signal.aborted && !(error instanceof SendActivityError)) {
2861
+ const failure = new FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
2862
+ failure.cause = signal.reason;
2863
+ failureError = failure;
2864
+ }
2865
+ if (opened || signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
2590
2866
  activityId,
2591
2867
  inbox: inbox.href,
2592
- error
2868
+ error: failureError
2593
2869
  });
2594
- throw error;
2870
+ throw failureError;
2871
+ } finally {
2872
+ clearTimeout(timer);
2595
2873
  }
2596
- if (!response.ok) {
2597
- let error;
2598
- try {
2599
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
2600
- } catch (_) {
2601
- error = "";
2602
- }
2874
+ if (!outcome.ok) {
2875
+ const { status, statusText, error } = outcome;
2603
2876
  logger.error("Failed to send activity {activityId} to {inbox} ({status} {statusText}):\n{error}", {
2604
2877
  activityId,
2605
2878
  inbox: inbox.href,
2606
- status: response.status,
2607
- statusText: response.statusText,
2879
+ status,
2880
+ statusText,
2608
2881
  error
2609
2882
  });
2610
- throw new SendActivityError(inbox, response.status, `Failed to send activity ${activityId} to ${inbox.href} (${response.status} ${response.statusText}):\n${error}`, error);
2883
+ throw new SendActivityError(inbox, status, `Failed to send activity ${activityId} to ${inbox.href} (${status} ${statusText}):\n${error}`, error);
2611
2884
  }
2612
2885
  span.addEvent("activitypub.activity.sent", {
2613
2886
  "activitypub.activity.json": JSON.stringify(activity),
@@ -2615,10 +2888,79 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2615
2888
  "activitypub.activity.id": activityId ?? ""
2616
2889
  });
2617
2890
  }
2618
- async function fetchWithValidatedRedirects(request, validateUrl) {
2891
+ /**
2892
+ * Starts cancelling the body of a response without waiting for it to settle.
2893
+ * The cancellation of a branch of a tee (e.g., a body cloned by a fetch mock)
2894
+ * settles only after the other branch is cancelled too, per the Streams
2895
+ * standard, so awaiting it could block forever. Failures are only logged.
2896
+ */
2897
+ function cancelResponseBody(response, url) {
2898
+ response.body?.cancel().catch((error) => {
2899
+ getLogger([
2900
+ "fedify",
2901
+ "federation",
2902
+ "outbox"
2903
+ ]).debug("Failed to cancel the response body from {url}: {error}", {
2904
+ url,
2905
+ error
2906
+ });
2907
+ });
2908
+ }
2909
+ /**
2910
+ * Reads what is needed from the final response of a delivery while its
2911
+ * session is open: the body of a successful response is cancelled, and at
2912
+ * most 1 KiB of an error response body is read.
2913
+ */
2914
+ async function consumeSendActivityResponse(response, inbox, signal) {
2915
+ if (response.ok) {
2916
+ cancelResponseBody(response, response.url || inbox.href);
2917
+ return { ok: true };
2918
+ }
2919
+ let error;
2920
+ try {
2921
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
2922
+ } catch (_) {
2923
+ error = "";
2924
+ }
2925
+ if (signal.aborted) error = "(timed out reading response body)";
2926
+ return {
2927
+ ok: false,
2928
+ status: response.status,
2929
+ statusText: response.statusText,
2930
+ error
2931
+ };
2932
+ }
2933
+ /**
2934
+ * Sends a request without signing it, following redirects manually like the
2935
+ * Fetch standard does. Every hop is opened with `openHop()`, which validates
2936
+ * the destination, after the previous hop is closed. The final response is
2937
+ * passed to `consume()`, and its session is closed after that.
2938
+ * This is exported only for tests; it is not exported from any entry point.
2939
+ * @param request The request to send.
2940
+ * @param openHop The function to open a session for each hop.
2941
+ * @param consume The function to consume the final response.
2942
+ * @returns The value returned by `consume`.
2943
+ */
2944
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
2945
+ const logger = getLogger([
2946
+ "fedify",
2947
+ "federation",
2948
+ "outbox"
2949
+ ]);
2619
2950
  let body = await request.clone().text();
2620
2951
  for (let redirects = 0;; redirects++) {
2621
- const response = await fetch(request, { redirect: "manual" });
2952
+ signal?.throwIfAborted();
2953
+ const session = await openHop(request.url);
2954
+ let response;
2955
+ try {
2956
+ response = await session.fetch(request, {
2957
+ redirect: "manual",
2958
+ signal
2959
+ });
2960
+ } catch (error) {
2961
+ await closeAfterError(session, logger);
2962
+ throw error;
2963
+ }
2622
2964
  const location = response.headers.get("Location");
2623
2965
  if (![
2624
2966
  301,
@@ -2626,11 +2968,21 @@ async function fetchWithValidatedRedirects(request, validateUrl) {
2626
2968
  303,
2627
2969
  307,
2628
2970
  308
2629
- ].includes(response.status) || location == null) return response;
2630
- await response.body?.cancel();
2971
+ ].includes(response.status) || location == null) try {
2972
+ return await consume(response);
2973
+ } catch (error) {
2974
+ logger.debug("Failed to consume the response from {url}; closing the session: {error}", {
2975
+ url: request.url,
2976
+ error
2977
+ });
2978
+ throw error;
2979
+ } finally {
2980
+ await session.close();
2981
+ }
2982
+ cancelResponseBody(response, request.url);
2983
+ await session.close();
2631
2984
  if (redirects >= 20) throw new TypeError("Too many redirects");
2632
2985
  const url = new URL(location, request.url);
2633
- await validateUrl(url.href);
2634
2986
  const headers = new Headers(request.headers);
2635
2987
  if (url.origin !== new URL(request.url).origin) {
2636
2988
  headers.delete("Authorization");
@@ -2654,7 +3006,18 @@ async function fetchWithValidatedRedirects(request, validateUrl) {
2654
3006
  method,
2655
3007
  headers,
2656
3008
  body,
2657
- redirect: "manual"
3009
+ redirect: "manual",
3010
+ signal: signal ?? request.signal
3011
+ });
3012
+ }
3013
+ }
3014
+ async function closeAfterError(session, logger) {
3015
+ try {
3016
+ await session.close();
3017
+ } catch (error) {
3018
+ logger.debug("Failed to close the session for {url}: {error}", {
3019
+ url: session.url.href,
3020
+ error
2658
3021
  });
2659
3022
  }
2660
3023
  }
@@ -3004,8 +3367,25 @@ var FederationImpl = class extends FederationBuilderImpl {
3004
3367
  _getTracer() {
3005
3368
  return this.tracerProvider.getTracer(name, version);
3006
3369
  }
3370
+ /**
3371
+ * Starts listening on a queue, converting a synchronous throw into
3372
+ * a rejected promise.
3373
+ *
3374
+ * `MessageQueue.listen()` is documented to never reject, but some
3375
+ * implementations (e.g., `WorkersMessageQueue`) throw synchronously. Without
3376
+ * this normalization, one such throw aborts {@link _startQueueInternal} while
3377
+ * it is still collecting listener promises, so listeners started earlier are
3378
+ * never awaited and later queues are never started.
3379
+ */
3380
+ #listenQueue(queue, ctxData, signal) {
3381
+ try {
3382
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
3383
+ } catch (error) {
3384
+ return Promise.reject(error);
3385
+ }
3386
+ }
3007
3387
  async _startQueueInternal(ctxData, signal, queue) {
3008
- if (this.inboxQueue == null && this.outboxQueue == null) return;
3388
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
3009
3389
  const logger = getLogger([
3010
3390
  "fedify",
3011
3391
  "federation",
@@ -3015,20 +3395,38 @@ var FederationImpl = class extends FederationBuilderImpl {
3015
3395
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
3016
3396
  logger.debug("Starting an inbox task worker.");
3017
3397
  this.inboxQueueStarted = true;
3018
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3398
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
3019
3399
  }
3020
3400
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
3021
3401
  logger.debug("Starting an outbox task worker.");
3022
3402
  this.outboxQueueStarted = true;
3023
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3403
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
3024
3404
  }
3025
3405
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
3026
3406
  logger.debug("Starting a fanout task worker.");
3027
3407
  this.fanoutQueueStarted = true;
3028
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3408
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
3029
3409
  }
3030
3410
  await Promise.all(promises);
3031
3411
  }
3412
+ /**
3413
+ * Starts the queue workers automatically, reporting a failure instead of
3414
+ * leaving the returned promise unobserved.
3415
+ *
3416
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
3417
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
3418
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
3419
+ * callers that start workers deliberately.
3420
+ */
3421
+ _startQueueAutomatically(ctxData) {
3422
+ this._startQueueInternal(ctxData).catch((error) => {
3423
+ getLogger([
3424
+ "fedify",
3425
+ "federation",
3426
+ "queue"
3427
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
3428
+ });
3429
+ }
3032
3430
  processQueuedTask(contextData, message) {
3033
3431
  const tracer = this._getTracer();
3034
3432
  const extractedContext = propagation.extract(context.active(), message.traceContext);
@@ -3137,7 +3535,8 @@ var FederationImpl = class extends FederationBuilderImpl {
3137
3535
  await this.sendActivity(keys, message.inboxes, activity, {
3138
3536
  collectionSync: message.collectionSync,
3139
3537
  orderingKey: message.orderingKey,
3140
- context
3538
+ context,
3539
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
3141
3540
  });
3142
3541
  }
3143
3542
  async #listenOutboxMessage(_, message, span) {
@@ -3340,7 +3739,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3340
3739
  let parseInput = void 0;
3341
3740
  let parseContextLoader = context.contextLoader;
3342
3741
  try {
3343
- const hasSignatureField = hasSignature(message.activity);
3742
+ const hasSignatureField = hasVerifiableSignature(message.activity);
3344
3743
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
3345
3744
  const parseContext = hasSignatureField ? {
3346
3745
  ...context,
@@ -3535,19 +3934,29 @@ var FederationImpl = class extends FederationBuilderImpl {
3535
3934
  proofCreated = true;
3536
3935
  break;
3537
3936
  }
3538
- if (!proofCreated) {
3539
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3540
- activity = await signObject(activity, privateKey, keyId, {
3541
- contextLoader,
3542
- tracerProvider: this.tracerProvider
3543
- });
3544
- proofCreated = true;
3937
+ const prepared = !proofCreated && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
3938
+ let jsonLd;
3939
+ if (prepared != null) {
3940
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
3941
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
3942
+ activity = signed.activity;
3943
+ jsonLd = signed.jsonLd;
3944
+ proofCreated = signingKeys.length > 0;
3945
+ } else {
3946
+ if (!proofCreated) {
3947
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3948
+ activity = await signObject(activity, privateKey, keyId, {
3949
+ contextLoader,
3950
+ tracerProvider: this.tracerProvider
3951
+ });
3952
+ proofCreated = true;
3953
+ }
3545
3954
  }
3955
+ jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
3956
+ format: "compact",
3957
+ contextLoader
3958
+ });
3546
3959
  }
3547
- let jsonLd = await activity.toJsonLd({
3548
- format: "compact",
3549
- contextLoader
3550
- });
3551
3960
  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.", {
3552
3961
  activityId,
3553
3962
  keys: keys.map((pair) => ({
@@ -3584,19 +3993,27 @@ var FederationImpl = class extends FederationBuilderImpl {
3584
3993
  activity: jsonLd
3585
3994
  });
3586
3995
  const promises = [];
3587
- for (const inbox in inboxes) promises.push(sendActivity({
3588
- allowPrivateAddress: this.allowPrivateAddress,
3589
- keys,
3590
- activity: jsonLd,
3591
- activityId: activity.id?.href,
3592
- activityType: getTypeId(activity).href,
3593
- inbox: new URL(inbox),
3594
- sharedInbox: inboxes[inbox].sharedInbox,
3595
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3596
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3597
- tracerProvider: this.tracerProvider
3598
- }));
3599
- await Promise.all(promises);
3996
+ try {
3997
+ for (const inbox in inboxes) {
3998
+ const promise = sendActivity({
3999
+ allowPrivateAddress: this.allowPrivateAddress,
4000
+ keys,
4001
+ activity: jsonLd,
4002
+ activityId: activity.id?.href,
4003
+ activityType: getTypeId(activity).href,
4004
+ inbox: new URL(inbox),
4005
+ sharedInbox: inboxes[inbox].sharedInbox,
4006
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
4007
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
4008
+ tracerProvider: this.tracerProvider
4009
+ });
4010
+ promise.catch(() => {});
4011
+ promises.push(promise);
4012
+ }
4013
+ await Promise.all(promises);
4014
+ } finally {
4015
+ await Promise.allSettled(promises);
4016
+ }
3600
4017
  return;
3601
4018
  }
3602
4019
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -3611,7 +4028,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3611
4028
  privateKey: privateKeyJwk
3612
4029
  });
3613
4030
  }
3614
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
4031
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
3615
4032
  const carrier = {};
3616
4033
  propagation.inject(context.active(), carrier);
3617
4034
  const messages = [];
@@ -3823,7 +4240,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3823
4240
  const identity = await this.sharedInboxKeyDispatcher(context);
3824
4241
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
3825
4242
  }
3826
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
4243
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
3827
4244
  const inboxContextFactory = context.toInboxContext.bind(context);
3828
4245
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
3829
4246
  return await handleInbox(request, {
@@ -4146,6 +4563,8 @@ var ContextImpl = class ContextImpl {
4146
4563
  for (const keyPair of keyPairs) {
4147
4564
  const newPair = {
4148
4565
  ...keyPair,
4566
+ privateKey: asCryptoKey(keyPair.privateKey),
4567
+ publicKey: asCryptoKey(keyPair.publicKey),
4149
4568
  cryptographicKey: new CryptographicKey({
4150
4569
  id: keyPair.keyId,
4151
4570
  owner,
@@ -4222,10 +4641,16 @@ var ContextImpl = class ContextImpl {
4222
4641
  } else identifierPromise = Promise.resolve(identity.identifier);
4223
4642
  return identifierPromise.then((identifier) => {
4224
4643
  if (identifier == null) return this.documentLoader;
4225
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
4644
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
4645
+ keyId: pair.keyId,
4646
+ privateKey: asCryptoKey(pair.privateKey)
4647
+ }));
4226
4648
  });
4227
4649
  }
4228
- return this.federation.authenticatedDocumentLoaderFactory(identity);
4650
+ return this.federation.authenticatedDocumentLoaderFactory({
4651
+ keyId: identity.keyId,
4652
+ privateKey: asCryptoKey(identity.privateKey)
4653
+ });
4229
4654
  }
4230
4655
  lookupObject(identifier, options = {}) {
4231
4656
  return lookupObject(identifier, {
@@ -4248,10 +4673,14 @@ var ContextImpl = class ContextImpl {
4248
4673
  return options.parse === "none" ? getNodeInfo(url, {
4249
4674
  parse: "none",
4250
4675
  direct: options.direct,
4676
+ timeout: options.timeout,
4677
+ signal: options.signal,
4251
4678
  userAgent: options?.userAgent ?? this.federation.userAgent
4252
4679
  }) : getNodeInfo(url, {
4253
4680
  parse: options.parse,
4254
4681
  direct: options.direct,
4682
+ timeout: options.timeout,
4683
+ signal: options.signal,
4255
4684
  userAgent: options?.userAgent ?? this.federation.userAgent
4256
4685
  });
4257
4686
  }
@@ -4263,7 +4692,17 @@ var ContextImpl = class ContextImpl {
4263
4692
  allowPrivateAddress: this.federation.allowPrivateAddress
4264
4693
  });
4265
4694
  }
4266
- sendActivity(sender, recipients, activity, options = {}) {
4695
+ async sendActivity(sender, recipients, activity, options = {}) {
4696
+ let activityJsonLd = void 0;
4697
+ let hasProof = activity.proofIds.length > 0;
4698
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
4699
+ hasProof = true;
4700
+ break;
4701
+ }
4702
+ if (hasProof) {
4703
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
4704
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
4705
+ }
4267
4706
  return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
4268
4707
  kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
4269
4708
  attributes: {
@@ -4276,7 +4715,7 @@ var ContextImpl = class ContextImpl {
4276
4715
  }, async (span) => {
4277
4716
  try {
4278
4717
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
4279
- await this.sendActivityInternal(sender, recipients, activity, options, span);
4718
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
4280
4719
  } catch (e) {
4281
4720
  span.setStatus({
4282
4721
  code: SpanStatusCode.ERROR,
@@ -4288,7 +4727,7 @@ var ContextImpl = class ContextImpl {
4288
4727
  }
4289
4728
  });
4290
4729
  }
4291
- async sendActivityInternal(sender, recipients, activity, options, span) {
4730
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
4292
4731
  const logger = getLogger([
4293
4732
  "fedify",
4294
4733
  "federation",
@@ -4335,14 +4774,23 @@ var ContextImpl = class ContextImpl {
4335
4774
  if (!(error instanceof RouterError)) throw error;
4336
4775
  }
4337
4776
  } else expandedRecipients = [recipients];
4338
- const opts = {
4339
- context: this,
4340
- orderingKey: options.orderingKey,
4341
- collectionSync,
4342
- immediate: options.immediate
4343
- };
4344
4777
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
4345
4778
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
4779
+ let contextMatches = false;
4780
+ if (activityJsonLd != null) {
4781
+ const capturedJsonLd = activityJsonLd;
4782
+ const transformedJsonLd = await activity.toJsonLd({
4783
+ format: "compact",
4784
+ contextLoader: this.contextLoader
4785
+ });
4786
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
4787
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
4788
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
4789
+ if (contentChanged || !contextMatches && proofsChanged) {
4790
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) });
4791
+ activityJsonLd = void 0;
4792
+ } else if (proofsChanged) activityJsonLd = void 0;
4793
+ }
4346
4794
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
4347
4795
  if (activity.actorId == null) {
4348
4796
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -4353,14 +4801,39 @@ var ContextImpl = class ContextImpl {
4353
4801
  }
4354
4802
  if (actorKeyPairs != null) {
4355
4803
  const contextLoader = this.contextLoader;
4356
- for (const kp of actorKeyPairs) {
4357
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4358
- activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4359
- contextLoader,
4360
- tracerProvider: this.tracerProvider
4361
- });
4804
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
4805
+ if (willSign) {
4806
+ if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
4807
+ }
4808
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
4809
+ if (prepared != null) {
4810
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
4811
+ privateKey: kp.privateKey,
4812
+ keyId: kp.multikey.id
4813
+ }] : []);
4814
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
4815
+ activity = signed.activity;
4816
+ activityJsonLd = signed.jsonLd;
4817
+ } else {
4818
+ let proofAdded = false;
4819
+ for (const kp of actorKeyPairs) {
4820
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4821
+ activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4822
+ contextLoader,
4823
+ tracerProvider: this.tracerProvider
4824
+ });
4825
+ proofAdded = true;
4826
+ }
4827
+ if (proofAdded) activityJsonLd = void 0;
4362
4828
  }
4363
4829
  }
4830
+ const opts = {
4831
+ context: this,
4832
+ orderingKey: options.orderingKey,
4833
+ collectionSync,
4834
+ immediate: options.immediate,
4835
+ activityJsonLd
4836
+ };
4364
4837
  const inboxes = extractInboxes({
4365
4838
  recipients: expandedRecipients,
4366
4839
  preferSharedInbox: options.preferSharedInbox,
@@ -4390,7 +4863,7 @@ var ContextImpl = class ContextImpl {
4390
4863
  actorIds: [...actorIds],
4391
4864
  sharedInbox
4392
4865
  }])),
4393
- activity: await activity.toJsonLd({
4866
+ activity: activityJsonLd != null ? detachSignature(activityJsonLd) : await activity.toJsonLd({
4394
4867
  format: "compact",
4395
4868
  contextLoader: this.contextLoader
4396
4869
  }),
@@ -4400,7 +4873,7 @@ var ContextImpl = class ContextImpl {
4400
4873
  orderingKey: options.orderingKey,
4401
4874
  traceContext: carrier
4402
4875
  };
4403
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
4876
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
4404
4877
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
4405
4878
  }
4406
4879
  async *getFollowers(identifier) {
@@ -4597,43 +5070,83 @@ var RequestContextImpl = class RequestContextImpl extends ContextImpl {
4597
5070
  }
4598
5071
  }), values);
4599
5072
  }
4600
- #signedKey = void 0;
5073
+ #signedKey = null;
5074
+ #signedKeyOwner = null;
5075
+ #signatureChecks = /* @__PURE__ */ new WeakMap();
5076
+ #getSignatureCheck(documentLoader, contextLoader) {
5077
+ let checks = this.#signatureChecks.get(documentLoader);
5078
+ if (checks == null) {
5079
+ checks = /* @__PURE__ */ new WeakMap();
5080
+ this.#signatureChecks.set(documentLoader, checks);
5081
+ }
5082
+ let check = checks.get(contextLoader);
5083
+ if (check == null) {
5084
+ check = {};
5085
+ checks.set(contextLoader, check);
5086
+ }
5087
+ return check;
5088
+ }
4601
5089
  async getSignedKey(options = {}) {
4602
5090
  if (this.#signedKey != null) return this.#signedKey;
4603
- return this.#signedKey = await verifyRequest(this.request, {
5091
+ const documentLoader = options.documentLoader ?? this.documentLoader;
5092
+ const contextLoader = options.contextLoader ?? this.contextLoader;
5093
+ const check = this.#getSignatureCheck(documentLoader, contextLoader);
5094
+ if (check.key != null) return check.key;
5095
+ const promise = verifyRequest(this.request, {
4604
5096
  ...this,
4605
- contextLoader: options.contextLoader ?? this.contextLoader,
4606
- documentLoader: options.documentLoader ?? this.documentLoader,
5097
+ contextLoader,
5098
+ documentLoader,
4607
5099
  timeWindow: this.federation.signatureTimeWindow,
4608
5100
  tracerProvider: options.tracerProvider ?? this.tracerProvider
5101
+ }).then((key) => {
5102
+ if (key != null) this.#signedKey ??= key;
5103
+ return key;
5104
+ }).catch((error) => {
5105
+ if (check.key === promise) check.key = void 0;
5106
+ throw error;
4609
5107
  });
5108
+ check.key = promise;
5109
+ return await promise;
4610
5110
  }
4611
- #signedKeyOwner = void 0;
4612
5111
  async getSignedKeyOwner(options = {}) {
4613
5112
  if (this.#signedKeyOwner != null) return this.#signedKeyOwner;
4614
- const key = await this.getSignedKey(options);
4615
- if (key == null) return this.#signedKeyOwner = null;
4616
- try {
4617
- return this.#signedKeyOwner = await getKeyOwner(key, {
4618
- contextLoader: options.contextLoader ?? this.contextLoader,
4619
- documentLoader: options.documentLoader ?? this.documentLoader,
4620
- tracerProvider: options.tracerProvider ?? this.tracerProvider
4621
- });
4622
- } catch (error) {
4623
- if (error instanceof FetchError) {
4624
- getLogger([
4625
- "fedify",
4626
- "federation",
4627
- "actor"
4628
- ]).warn("Failed to fetch the key owner {keyOwner} of {keyId} while verifying the request signature; treating the request as unauthenticated: {error}", {
4629
- keyId: key.id?.href,
4630
- keyOwner: error.url.href,
4631
- error
4632
- });
4633
- return this.#signedKeyOwner = null;
5113
+ const normalizedOptions = {
5114
+ documentLoader: options.documentLoader ?? this.documentLoader,
5115
+ contextLoader: options.contextLoader ?? this.contextLoader,
5116
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
5117
+ };
5118
+ const check = this.#getSignatureCheck(normalizedOptions.documentLoader, normalizedOptions.contextLoader);
5119
+ if (check.owner != null) return check.owner;
5120
+ const promise = this.getSignedKey(normalizedOptions).then(async (key) => {
5121
+ if (key == null) {
5122
+ if (check.owner === promise) check.owner = void 0;
5123
+ return null;
4634
5124
  }
5125
+ try {
5126
+ const owner = await getKeyOwner(key, normalizedOptions);
5127
+ if (owner != null) this.#signedKeyOwner ??= owner;
5128
+ return owner;
5129
+ } catch (error) {
5130
+ if (error instanceof FetchError) {
5131
+ getLogger([
5132
+ "fedify",
5133
+ "federation",
5134
+ "actor"
5135
+ ]).warn("Failed to fetch the key owner {keyOwner} of {keyId} while verifying the request signature; treating the request as unauthenticated: {error}", {
5136
+ keyId: key.id?.href,
5137
+ keyOwner: error.url.href,
5138
+ error
5139
+ });
5140
+ return null;
5141
+ }
5142
+ throw error;
5143
+ }
5144
+ }).catch((error) => {
5145
+ if (check.owner === promise) check.owner = void 0;
4635
5146
  throw error;
4636
- }
5147
+ });
5148
+ check.owner = promise;
5149
+ return await promise;
4637
5150
  }
4638
5151
  };
4639
5152
  var InboxContextImpl = class InboxContextImpl extends ContextImpl {
@@ -4714,7 +5227,7 @@ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
4714
5227
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
4715
5228
  keys = forwarder;
4716
5229
  } else keys = [forwarder];
4717
- if (!hasSignature(this.activity)) {
5230
+ if (!hasVerifiableSignature(this.activity)) {
4718
5231
  let hasProof;
4719
5232
  try {
4720
5233
  hasProof = await (await Activity.fromJsonLd(this.activity, this)).getProof() != null;
@@ -4746,18 +5259,26 @@ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
4746
5259
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
4747
5260
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
4748
5261
  const promises = [];
4749
- for (const inbox in inboxes) promises.push(sendActivity({
4750
- allowPrivateAddress: this.federation.allowPrivateAddress,
4751
- keys,
4752
- activity: this.activity,
4753
- activityId: this.activityId,
4754
- activityType: this.activityType,
4755
- inbox: new URL(inbox),
4756
- sharedInbox: inboxes[inbox].sharedInbox,
4757
- tracerProvider: this.tracerProvider,
4758
- specDeterminer: new KvSpecDeterminer(this.federation.kv, this.federation.kvPrefixes.httpMessageSignaturesSpec, this.federation.firstKnock)
4759
- }));
4760
- await Promise.all(promises);
5262
+ try {
5263
+ for (const inbox in inboxes) {
5264
+ const promise = sendActivity({
5265
+ allowPrivateAddress: this.federation.allowPrivateAddress,
5266
+ keys,
5267
+ activity: this.activity,
5268
+ activityId: this.activityId,
5269
+ activityType: this.activityType,
5270
+ inbox: new URL(inbox),
5271
+ sharedInbox: inboxes[inbox].sharedInbox,
5272
+ tracerProvider: this.tracerProvider,
5273
+ specDeterminer: new KvSpecDeterminer(this.federation.kv, this.federation.kvPrefixes.httpMessageSignaturesSpec, this.federation.firstKnock)
5274
+ });
5275
+ promise.catch(() => {});
5276
+ promises.push(promise);
5277
+ }
5278
+ await Promise.all(promises);
5279
+ } finally {
5280
+ await Promise.allSettled(promises);
5281
+ }
4761
5282
  return;
4762
5283
  }
4763
5284
  logger.debug("Enqueuing activity {activityId} to forward later.", {
@@ -4852,6 +5373,69 @@ var KvSpecDeterminer = class {
4852
5373
  function notFound(_request) {
4853
5374
  return new Response("Not Found", { status: 404 });
4854
5375
  }
5376
+ function hasTopLevelProof(value) {
5377
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
5378
+ }
5379
+ function getContentFields(value) {
5380
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5381
+ const record = { ...value };
5382
+ delete record["@context"];
5383
+ delete record.proof;
5384
+ delete record.signature;
5385
+ return JSON.stringify(sortJsonKeys(record));
5386
+ }
5387
+ function getContextFields(value) {
5388
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5389
+ const context = value["@context"];
5390
+ return JSON.stringify(sortJsonKeys(context ?? null));
5391
+ }
5392
+ function getProofEntries(value) {
5393
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
5394
+ const proof = value.proof;
5395
+ if (proof == null) return [];
5396
+ return Array.isArray(proof) ? proof : [proof];
5397
+ }
5398
+ function normalizeProofEntry(proof) {
5399
+ const stripped = stripContexts(proof);
5400
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
5401
+ const record = { ...stripped };
5402
+ if (typeof record.created === "string") try {
5403
+ record.created = Temporal.Instant.from(record.created).toString();
5404
+ } catch {}
5405
+ return record;
5406
+ }
5407
+ function getProofEntryFields(proof) {
5408
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
5409
+ }
5410
+ function getProofFields(value) {
5411
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
5412
+ }
5413
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
5414
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
5415
+ const retainedProofs = [];
5416
+ for await (const proof of activity.getProofs({ contextLoader })) {
5417
+ const proofJsonLd = await proof.toJsonLd({
5418
+ format: "compact",
5419
+ contextLoader
5420
+ });
5421
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
5422
+ }
5423
+ return retainedProofs;
5424
+ }
5425
+ function stripContexts(value) {
5426
+ if (Array.isArray(value)) return value.map(stripContexts);
5427
+ if (typeof value !== "object" || value == null) return value;
5428
+ const record = { ...value };
5429
+ delete record["@context"];
5430
+ delete record.signature;
5431
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
5432
+ return record;
5433
+ }
5434
+ function sortJsonKeys(value) {
5435
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
5436
+ if (typeof value !== "object" || value == null) return value;
5437
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
5438
+ }
4855
5439
  function notAcceptable(_request) {
4856
5440
  return new Response("Not Acceptable", {
4857
5441
  status: 406,