@fedify/fedify 2.1.31 → 2.1.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/attachment-arrays-DZ4JHJD8.mjs +111 -0
  2. package/dist/{builder-isMRh_I6.mjs → builder--sc-rozj.mjs} +3 -3
  3. package/dist/callback-BARPujV7.d.mts +2388 -0
  4. package/dist/{client-BIBzqEIp.d.cts → client-9DPcy_Yx.d.ts} +16 -0
  5. package/dist/{client-jE7oGvRh.d.ts → client-B3ruDgWg.d.cts} +16 -0
  6. package/dist/{client-BZr7TGyu.mjs → client-cpPaW7Ww.mjs} +86 -11
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +254 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/transformers.test.mjs +1 -1
  12. package/dist/{context-C0uGVzgk.d.ts → context-DE2YrQwM.d.ts} +30 -13
  13. package/dist/{context-CLaLxi49.d.cts → context-y6ZUQCMf.d.cts} +30 -13
  14. package/dist/{deno-CiaJqTcu.mjs → deno-L23b3Hba.mjs} +1 -1
  15. package/dist/{docloader-DOrwedT7.mjs → docloader-DUXr9k_O.mjs} +2 -2
  16. package/dist/federation/attachment-responses.test.d.mts +2 -0
  17. package/dist/federation/attachment-responses.test.mjs +182 -0
  18. package/dist/federation/builder.test.mjs +1 -1
  19. package/dist/federation/collection.test.mjs +1 -1
  20. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  21. package/dist/federation/delivery-attachments.test.mjs +280 -0
  22. package/dist/federation/handler.test.mjs +208 -16
  23. package/dist/federation/idempotency.test.mjs +2 -2
  24. package/dist/federation/inbox.test.mjs +1 -1
  25. package/dist/federation/middleware.test.mjs +1185 -8
  26. package/dist/federation/mod.cjs +1 -1
  27. package/dist/federation/mod.d.cts +2 -2
  28. package/dist/federation/mod.d.ts +2 -2
  29. package/dist/federation/mod.js +1 -1
  30. package/dist/federation/negotiation.test.mjs +1 -1
  31. package/dist/federation/retry.test.mjs +1 -1
  32. package/dist/federation/send.test.mjs +283 -3
  33. package/dist/federation/temporal.test.mjs +25 -1
  34. package/dist/federation/webfinger.test.mjs +1 -1
  35. package/dist/{http-Crml3gei.js → http-BtbMAgTA.js} +6 -4
  36. package/dist/{http-9IFUxdkp.d.cts → http-C8qLHs_Z.d.cts} +3 -3
  37. package/dist/{http-CRiVlZd5.cjs → http-D5woFKA_.cjs} +6 -4
  38. package/dist/{http-SbfezERn.d.ts → http-D8WmcRAF.d.ts} +3 -3
  39. package/dist/{http-A9mP2uM7.mjs → http-HX6wVyJh.mjs} +6 -4
  40. package/dist/{inbox-KESLudq4.mjs → inbox-CL7A0HXT.mjs} +1 -1
  41. package/dist/{key-Dg6-DV_O.mjs → key-Dai3f5yI.mjs} +3 -2
  42. package/dist/{kv-cache-Cqmm-yQa.cjs → kv-cache-B0V_e231.cjs} +1 -1
  43. package/dist/{kv-cache-DQcyZL5T.js → kv-cache-BsDg-cT8.js} +1 -1
  44. package/dist/{ld-COjDN6Nb.mjs → ld-DN6x1iZ8.mjs} +153 -21
  45. package/dist/ld-signature-DoZcbsZR.mjs +23 -0
  46. package/dist/{middleware-BtDQUCcz.cjs → middleware-Cl6k5Hrm.cjs} +1 -1
  47. package/dist/{middleware-BbgR7xOI.cjs → middleware-CrfRuKCf.cjs} +561 -101
  48. package/dist/{middleware-COFlKeYn.mjs → middleware-DiquMgtt.mjs} +378 -89
  49. package/dist/{middleware-DIW5S_5L.js → middleware-DunNtbo9.js} +560 -101
  50. package/dist/{middleware-CuQvczZd.mjs → middleware-SnQS8eIb.mjs} +1 -1
  51. package/dist/{mod-LOEOKbYd.d.cts → mod-CehHJOV4.d.cts} +30 -13
  52. package/dist/{mod-CFRocFeQ.d.ts → mod-DLJpnqdw.d.ts} +1 -1
  53. package/dist/{mod-C7w-QVUv.d.ts → mod-Mh3oIuRK.d.ts} +30 -13
  54. package/dist/{mod-BRnwh2oy.d.ts → mod-REfljt0T.d.ts} +3 -3
  55. package/dist/{mod-Co7LEK9X.d.cts → mod-UvIGUHqW.d.cts} +3 -3
  56. package/dist/{mod-CGUH8Ujp.d.cts → mod-sTa1Zzxk.d.cts} +1 -1
  57. package/dist/mod.cjs +5 -5
  58. package/dist/mod.d.cts +8 -8
  59. package/dist/mod.d.ts +8 -8
  60. package/dist/mod.js +5 -5
  61. package/dist/nodeinfo/client.test.mjs +432 -5
  62. package/dist/nodeinfo/handler.test.mjs +1 -1
  63. package/dist/nodeinfo/mod.cjs +1 -1
  64. package/dist/nodeinfo/mod.d.cts +1 -1
  65. package/dist/nodeinfo/mod.d.ts +1 -1
  66. package/dist/nodeinfo/mod.js +1 -1
  67. package/dist/nodeinfo/types.test.mjs +1 -1
  68. package/dist/{owner-CFHq61cq.mjs → owner-DwyDorZI.mjs} +2 -2
  69. package/dist/{proof-0JkSC_pT.cjs → proof-Be-4K4jn.cjs} +193 -46
  70. package/dist/{proof-KSHlbPCG.mjs → proof-DYjmyrHh.mjs} +38 -13
  71. package/dist/{proof-DzksJFK7.js → proof-Du4-5SHY.js} +187 -46
  72. package/dist/{send-DaDe2YCb.mjs → send-BGSfQkIK.mjs} +92 -21
  73. package/dist/sig/http.test.mjs +2 -2
  74. package/dist/sig/key-types.test.d.mts +218 -0
  75. package/dist/sig/key-types.test.mjs +8 -0
  76. package/dist/sig/key.test.mjs +2 -2
  77. package/dist/sig/ld.test.mjs +573 -8
  78. package/dist/sig/mod.cjs +2 -2
  79. package/dist/sig/mod.d.cts +3 -3
  80. package/dist/sig/mod.d.ts +3 -3
  81. package/dist/sig/mod.js +2 -2
  82. package/dist/sig/owner.test.mjs +1 -1
  83. package/dist/sig/proof.test.mjs +95 -3
  84. package/dist/{temporal-DNGH8o2E.mjs → temporal-CNCchWly.mjs} +3 -5
  85. package/dist/testing/mod.d.mts +2 -2203
  86. package/dist/{types-DOvyymM4.cjs → types-B5wRhemi.cjs} +85 -10
  87. package/dist/{types-B1_pRFE_.js → types-CXy2lRVU.js} +86 -11
  88. package/dist/utils/docloader.test.mjs +2 -2
  89. package/dist/utils/mod.cjs +1 -1
  90. package/dist/utils/mod.d.cts +1 -1
  91. package/dist/utils/mod.d.ts +1 -1
  92. package/dist/utils/mod.js +1 -1
  93. package/package.json +6 -6
  94. /package/dist/{collection-BD6-SZ6O.mjs → collection-DnoYNwBC.mjs} +0 -0
  95. /package/dist/{negotiation-BehA2uul.mjs → negotiation-xb0QR3u_.mjs} +0 -0
  96. /package/dist/{retry-B_E3V_Dx.mjs → retry-CI1flGDD.mjs} +0 -0
  97. /package/dist/{types-DCP0WLdt.mjs → types-s4mCTGkT.mjs} +0 -0
@@ -2,22 +2,24 @@ import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  import { t as __exportAll } from "./chunk-CRNNMoPX.js";
4
4
  import { r as getDefaultActivityTransformers } from "./transformers-BGMIq1cs.js";
5
- import { a as verifyRequestDetailed, d as importJwk, f as validateCryptoKey, i as verifyRequest, m as formatAcceptSignature, n as parseRfc9421SignatureInput, o as exportJwk, t as doubleKnockScoped, v as name, y as version } from "./http-Crml3gei.js";
6
- import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-B1_pRFE_.js";
7
- import { _ as 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-DzksJFK7.js";
8
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-DQcyZL5T.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 } 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
- import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
21
23
  import { domainToASCII } from "node:url";
22
24
  //#region src/federation/inbox.ts
23
25
  var InboxListenerSet = class InboxListenerSet {
@@ -882,6 +884,110 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
882
884
  return `collectionId="${collectionId}", url="${url}", digest="${encodeHex(await digest(actorIds))}"`;
883
885
  }
884
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
885
991
  //#region src/federation/keycache.ts
886
992
  const KEY_CACHE_GENERATION = "3";
887
993
  var KvKeyCache = class {
@@ -1069,9 +1175,6 @@ function acceptsJsonLd(request) {
1069
1175
  function isPlainObject(value) {
1070
1176
  return typeof value === "object" && value != null && !Array.isArray(value);
1071
1177
  }
1072
- function normalizeDateTimeLiteral(value) {
1073
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1074
- }
1075
1178
  function isMalformedDateTimeLiteral(value) {
1076
1179
  if (typeof value !== "string") return false;
1077
1180
  try {
@@ -1113,7 +1216,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1113
1216
  if (typeof literal === "boolean") return false;
1114
1217
  if (typeof literal !== "string") return false;
1115
1218
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1116
- 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;
1117
1220
  return isMalformedDateTimeLiteral(literal);
1118
1221
  }
1119
1222
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1207,7 +1310,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1207
1310
  if (authorizePredicate != null) {
1208
1311
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1209
1312
  }
1210
- const jsonLd = await actor.toJsonLd(context);
1313
+ const jsonLd = await serializeForResponse(actor, context);
1211
1314
  return new Response(JSON.stringify(jsonLd), { headers: {
1212
1315
  "Content-Type": "application/activity+json",
1213
1316
  Vary: "Accept"
@@ -1227,7 +1330,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1227
1330
  if (authorizePredicate != null) {
1228
1331
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1229
1332
  }
1230
- const jsonLd = await object.toJsonLd(context);
1333
+ const jsonLd = await serializeForResponse(object, context);
1231
1334
  return new Response(JSON.stringify(jsonLd), { headers: {
1232
1335
  "Content-Type": "application/activity+json",
1233
1336
  Vary: "Accept"
@@ -1358,7 +1461,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1358
1461
  if (collectionCallbacks.authorizePredicate != null) {
1359
1462
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
1360
1463
  }
1361
- const jsonLd = await collection.toJsonLd(context);
1464
+ const jsonLd = await serializeForResponse(collection, context);
1362
1465
  return new Response(JSON.stringify(jsonLd), { headers: {
1363
1466
  "Content-Type": "application/activity+json",
1364
1467
  Vary: "Accept"
@@ -1510,7 +1613,11 @@ async function handleInboxInternal(request, parameters, span) {
1510
1613
  }
1511
1614
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
1512
1615
  const jsonWithoutSig = detachSignature(json);
1513
- 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
+ }
1514
1621
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
1515
1622
  let deferredLdSignatureError = void 0;
1516
1623
  const respondInvalidActivity = async (error) => {
@@ -1989,7 +2096,7 @@ var CustomCollectionHandler = class {
1989
2096
  * @returns A promise that resolves to the JSON-LD representation.
1990
2097
  */
1991
2098
  async toJsonLd() {
1992
- return (await this.collection).toJsonLd(this.context);
2099
+ return serializeForResponse(await this.collection, this.context);
1993
2100
  }
1994
2101
  /**
1995
2102
  * Fetches the collection with optional cursor for pagination.
@@ -2292,7 +2399,7 @@ var UnauthorizedError = class extends HandlerError {
2292
2399
  * @since 0.3.0
2293
2400
  */
2294
2401
  async function respondWithObject(object, options) {
2295
- const jsonLd = await object.toJsonLd(options);
2402
+ const jsonLd = await serializeForResponse(object, options);
2296
2403
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
2297
2404
  }
2298
2405
  /**
@@ -2380,6 +2487,106 @@ const MIN_COMPONENTS = [
2380
2487
  "@target-uri",
2381
2488
  "@authority"
2382
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
+ }
2383
2590
  //#endregion
2384
2591
  //#region src/nodeinfo/handler.ts
2385
2592
  /**
@@ -2479,7 +2686,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2479
2686
  * @param parameters The parameters for sending the activity.
2480
2687
  * See also {@link SendActivityParameters}.
2481
2688
  * @param deps The dependencies, for tests.
2482
- * @throws {Error} If the activity fails to send.
2689
+ * @throws {FetchError} If the delivery times out before receiving a response.
2690
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
2483
2691
  */
2484
2692
  function sendActivity(options, deps = {}) {
2485
2693
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
@@ -2506,7 +2714,25 @@ function sendActivity(options, deps = {}) {
2506
2714
  });
2507
2715
  }
2508
2716
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
2509
- 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) {
2510
2736
  if (response.body == null) return "";
2511
2737
  const reader = response.body.getReader();
2512
2738
  const decoder = new TextDecoder();
@@ -2515,7 +2741,8 @@ async function readLimitedResponseBody(response, maxBytes) {
2515
2741
  let truncated = false;
2516
2742
  try {
2517
2743
  while (true) {
2518
- const { done, value } = await reader.read();
2744
+ signal.throwIfAborted();
2745
+ const { done, value } = await raceWithAbort(reader.read(), signal);
2519
2746
  if (done) break;
2520
2747
  if (totalBytes + value.length > maxBytes) {
2521
2748
  const remaining = maxBytes - totalBytes;
@@ -2527,8 +2754,10 @@ async function readLimitedResponseBody(response, maxBytes) {
2527
2754
  totalBytes += value.length;
2528
2755
  }
2529
2756
  } finally {
2530
- if (truncated) reader.cancel().catch(() => {});
2531
- reader.releaseLock();
2757
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
2758
+ try {
2759
+ reader.releaseLock();
2760
+ } catch (_) {}
2532
2761
  }
2533
2762
  let result = chunks.join("");
2534
2763
  if (truncated) result += "… (truncated)";
@@ -2540,12 +2769,24 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2540
2769
  "federation",
2541
2770
  "outbox"
2542
2771
  ]);
2543
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(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 }));
2544
2776
  let opened = false;
2545
2777
  async function openHop(url) {
2546
2778
  let session;
2547
2779
  try {
2548
- session = await openUnvalidatedHop(url);
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
+ }
2549
2790
  } catch (error) {
2550
2791
  if (error instanceof UrlError && error.reason === "dns") {
2551
2792
  logger.error("DNS resolution failed for URL: {url}", {
@@ -2571,7 +2812,8 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2571
2812
  method: "POST",
2572
2813
  headers,
2573
2814
  body: JSON.stringify(activity),
2574
- redirect: "manual"
2815
+ redirect: "manual",
2816
+ signal
2575
2817
  });
2576
2818
  let rsaKey = null;
2577
2819
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -2586,18 +2828,48 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2586
2828
  }))
2587
2829
  });
2588
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);
2589
2852
  try {
2590
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox)) : await doubleKnockScoped(request, rsaKey, {
2853
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await doubleKnockScoped(request, rsaKey, {
2591
2854
  tracerProvider,
2592
- specDeterminer
2593
- }, openHop, (response) => consumeSendActivityResponse(response, inbox));
2855
+ specDeterminer: boundedSpecDeterminer,
2856
+ signal
2857
+ }, openHop, (response) => consumeSendActivityResponse(response, inbox, signal));
2594
2858
  } catch (error) {
2595
- if (opened) 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}", {
2596
2866
  activityId,
2597
2867
  inbox: inbox.href,
2598
- error
2868
+ error: failureError
2599
2869
  });
2600
- throw error;
2870
+ throw failureError;
2871
+ } finally {
2872
+ clearTimeout(timer);
2601
2873
  }
2602
2874
  if (!outcome.ok) {
2603
2875
  const { status, statusText, error } = outcome;
@@ -2639,17 +2911,18 @@ function cancelResponseBody(response, url) {
2639
2911
  * session is open: the body of a successful response is cancelled, and at
2640
2912
  * most 1 KiB of an error response body is read.
2641
2913
  */
2642
- async function consumeSendActivityResponse(response, inbox) {
2914
+ async function consumeSendActivityResponse(response, inbox, signal) {
2643
2915
  if (response.ok) {
2644
2916
  cancelResponseBody(response, response.url || inbox.href);
2645
2917
  return { ok: true };
2646
2918
  }
2647
2919
  let error;
2648
2920
  try {
2649
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
2921
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
2650
2922
  } catch (_) {
2651
2923
  error = "";
2652
2924
  }
2925
+ if (signal.aborted) error = "(timed out reading response body)";
2653
2926
  return {
2654
2927
  ok: false,
2655
2928
  status: response.status,
@@ -2668,7 +2941,7 @@ async function consumeSendActivityResponse(response, inbox) {
2668
2941
  * @param consume The function to consume the final response.
2669
2942
  * @returns The value returned by `consume`.
2670
2943
  */
2671
- async function fetchWithValidatedRedirects(request, openHop, consume) {
2944
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
2672
2945
  const logger = getLogger([
2673
2946
  "fedify",
2674
2947
  "federation",
@@ -2676,10 +2949,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
2676
2949
  ]);
2677
2950
  let body = await request.clone().text();
2678
2951
  for (let redirects = 0;; redirects++) {
2952
+ signal?.throwIfAborted();
2679
2953
  const session = await openHop(request.url);
2680
2954
  let response;
2681
2955
  try {
2682
- response = await session.fetch(request, { redirect: "manual" });
2956
+ response = await session.fetch(request, {
2957
+ redirect: "manual",
2958
+ signal
2959
+ });
2683
2960
  } catch (error) {
2684
2961
  await closeAfterError(session, logger);
2685
2962
  throw error;
@@ -2729,7 +3006,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
2729
3006
  method,
2730
3007
  headers,
2731
3008
  body,
2732
- redirect: "manual"
3009
+ redirect: "manual",
3010
+ signal: signal ?? request.signal
2733
3011
  });
2734
3012
  }
2735
3013
  }
@@ -3089,8 +3367,25 @@ var FederationImpl = class extends FederationBuilderImpl {
3089
3367
  _getTracer() {
3090
3368
  return this.tracerProvider.getTracer(name, version);
3091
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
+ }
3092
3387
  async _startQueueInternal(ctxData, signal, queue) {
3093
- if (this.inboxQueue == null && this.outboxQueue == null) return;
3388
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
3094
3389
  const logger = getLogger([
3095
3390
  "fedify",
3096
3391
  "federation",
@@ -3100,20 +3395,38 @@ var FederationImpl = class extends FederationBuilderImpl {
3100
3395
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
3101
3396
  logger.debug("Starting an inbox task worker.");
3102
3397
  this.inboxQueueStarted = true;
3103
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3398
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
3104
3399
  }
3105
3400
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
3106
3401
  logger.debug("Starting an outbox task worker.");
3107
3402
  this.outboxQueueStarted = true;
3108
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3403
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
3109
3404
  }
3110
3405
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
3111
3406
  logger.debug("Starting a fanout task worker.");
3112
3407
  this.fanoutQueueStarted = true;
3113
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3408
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
3114
3409
  }
3115
3410
  await Promise.all(promises);
3116
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
+ }
3117
3430
  processQueuedTask(contextData, message) {
3118
3431
  const tracer = this._getTracer();
3119
3432
  const extractedContext = propagation.extract(context.active(), message.traceContext);
@@ -3222,7 +3535,8 @@ var FederationImpl = class extends FederationBuilderImpl {
3222
3535
  await this.sendActivity(keys, message.inboxes, activity, {
3223
3536
  collectionSync: message.collectionSync,
3224
3537
  orderingKey: message.orderingKey,
3225
- context
3538
+ context,
3539
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
3226
3540
  });
3227
3541
  }
3228
3542
  async #listenOutboxMessage(_, message, span) {
@@ -3425,7 +3739,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3425
3739
  let parseInput = void 0;
3426
3740
  let parseContextLoader = context.contextLoader;
3427
3741
  try {
3428
- const hasSignatureField = hasSignature(message.activity);
3742
+ const hasSignatureField = hasVerifiableSignature(message.activity);
3429
3743
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
3430
3744
  const parseContext = hasSignatureField ? {
3431
3745
  ...context,
@@ -3620,19 +3934,29 @@ var FederationImpl = class extends FederationBuilderImpl {
3620
3934
  proofCreated = true;
3621
3935
  break;
3622
3936
  }
3623
- if (!proofCreated) {
3624
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3625
- activity = await signObject(activity, privateKey, keyId, {
3626
- contextLoader,
3627
- tracerProvider: this.tracerProvider
3628
- });
3629
- 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
+ }
3630
3954
  }
3955
+ jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
3956
+ format: "compact",
3957
+ contextLoader
3958
+ });
3631
3959
  }
3632
- let jsonLd = await activity.toJsonLd({
3633
- format: "compact",
3634
- contextLoader
3635
- });
3636
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.", {
3637
3961
  activityId,
3638
3962
  keys: keys.map((pair) => ({
@@ -3669,19 +3993,27 @@ var FederationImpl = class extends FederationBuilderImpl {
3669
3993
  activity: jsonLd
3670
3994
  });
3671
3995
  const promises = [];
3672
- for (const inbox in inboxes) promises.push(sendActivity({
3673
- allowPrivateAddress: this.allowPrivateAddress,
3674
- keys,
3675
- activity: jsonLd,
3676
- activityId: activity.id?.href,
3677
- activityType: getTypeId(activity).href,
3678
- inbox: new URL(inbox),
3679
- sharedInbox: inboxes[inbox].sharedInbox,
3680
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3681
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3682
- tracerProvider: this.tracerProvider
3683
- }));
3684
- 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
+ }
3685
4017
  return;
3686
4018
  }
3687
4019
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -3696,7 +4028,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3696
4028
  privateKey: privateKeyJwk
3697
4029
  });
3698
4030
  }
3699
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
4031
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
3700
4032
  const carrier = {};
3701
4033
  propagation.inject(context.active(), carrier);
3702
4034
  const messages = [];
@@ -3908,7 +4240,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3908
4240
  const identity = await this.sharedInboxKeyDispatcher(context);
3909
4241
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
3910
4242
  }
3911
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
4243
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
3912
4244
  const inboxContextFactory = context.toInboxContext.bind(context);
3913
4245
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
3914
4246
  return await handleInbox(request, {
@@ -4231,6 +4563,8 @@ var ContextImpl = class ContextImpl {
4231
4563
  for (const keyPair of keyPairs) {
4232
4564
  const newPair = {
4233
4565
  ...keyPair,
4566
+ privateKey: asCryptoKey(keyPair.privateKey),
4567
+ publicKey: asCryptoKey(keyPair.publicKey),
4234
4568
  cryptographicKey: new CryptographicKey({
4235
4569
  id: keyPair.keyId,
4236
4570
  owner,
@@ -4307,10 +4641,16 @@ var ContextImpl = class ContextImpl {
4307
4641
  } else identifierPromise = Promise.resolve(identity.identifier);
4308
4642
  return identifierPromise.then((identifier) => {
4309
4643
  if (identifier == null) return this.documentLoader;
4310
- 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
+ }));
4311
4648
  });
4312
4649
  }
4313
- return this.federation.authenticatedDocumentLoaderFactory(identity);
4650
+ return this.federation.authenticatedDocumentLoaderFactory({
4651
+ keyId: identity.keyId,
4652
+ privateKey: asCryptoKey(identity.privateKey)
4653
+ });
4314
4654
  }
4315
4655
  lookupObject(identifier, options = {}) {
4316
4656
  return lookupObject(identifier, {
@@ -4333,10 +4673,14 @@ var ContextImpl = class ContextImpl {
4333
4673
  return options.parse === "none" ? getNodeInfo(url, {
4334
4674
  parse: "none",
4335
4675
  direct: options.direct,
4676
+ timeout: options.timeout,
4677
+ signal: options.signal,
4336
4678
  userAgent: options?.userAgent ?? this.federation.userAgent
4337
4679
  }) : getNodeInfo(url, {
4338
4680
  parse: options.parse,
4339
4681
  direct: options.direct,
4682
+ timeout: options.timeout,
4683
+ signal: options.signal,
4340
4684
  userAgent: options?.userAgent ?? this.federation.userAgent
4341
4685
  });
4342
4686
  }
@@ -4348,7 +4692,17 @@ var ContextImpl = class ContextImpl {
4348
4692
  allowPrivateAddress: this.federation.allowPrivateAddress
4349
4693
  });
4350
4694
  }
4351
- 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
+ }
4352
4706
  return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
4353
4707
  kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
4354
4708
  attributes: {
@@ -4361,7 +4715,7 @@ var ContextImpl = class ContextImpl {
4361
4715
  }, async (span) => {
4362
4716
  try {
4363
4717
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
4364
- await this.sendActivityInternal(sender, recipients, activity, options, span);
4718
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
4365
4719
  } catch (e) {
4366
4720
  span.setStatus({
4367
4721
  code: SpanStatusCode.ERROR,
@@ -4373,7 +4727,7 @@ var ContextImpl = class ContextImpl {
4373
4727
  }
4374
4728
  });
4375
4729
  }
4376
- async sendActivityInternal(sender, recipients, activity, options, span) {
4730
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
4377
4731
  const logger = getLogger([
4378
4732
  "fedify",
4379
4733
  "federation",
@@ -4420,14 +4774,23 @@ var ContextImpl = class ContextImpl {
4420
4774
  if (!(error instanceof RouterError)) throw error;
4421
4775
  }
4422
4776
  } else expandedRecipients = [recipients];
4423
- const opts = {
4424
- context: this,
4425
- orderingKey: options.orderingKey,
4426
- collectionSync,
4427
- immediate: options.immediate
4428
- };
4429
4777
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
4430
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
+ }
4431
4794
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
4432
4795
  if (activity.actorId == null) {
4433
4796
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -4438,14 +4801,39 @@ var ContextImpl = class ContextImpl {
4438
4801
  }
4439
4802
  if (actorKeyPairs != null) {
4440
4803
  const contextLoader = this.contextLoader;
4441
- for (const kp of actorKeyPairs) {
4442
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4443
- activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4444
- contextLoader,
4445
- tracerProvider: this.tracerProvider
4446
- });
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;
4447
4828
  }
4448
4829
  }
4830
+ const opts = {
4831
+ context: this,
4832
+ orderingKey: options.orderingKey,
4833
+ collectionSync,
4834
+ immediate: options.immediate,
4835
+ activityJsonLd
4836
+ };
4449
4837
  const inboxes = extractInboxes({
4450
4838
  recipients: expandedRecipients,
4451
4839
  preferSharedInbox: options.preferSharedInbox,
@@ -4475,7 +4863,7 @@ var ContextImpl = class ContextImpl {
4475
4863
  actorIds: [...actorIds],
4476
4864
  sharedInbox
4477
4865
  }])),
4478
- activity: await activity.toJsonLd({
4866
+ activity: activityJsonLd != null ? detachSignature(activityJsonLd) : await activity.toJsonLd({
4479
4867
  format: "compact",
4480
4868
  contextLoader: this.contextLoader
4481
4869
  }),
@@ -4485,7 +4873,7 @@ var ContextImpl = class ContextImpl {
4485
4873
  orderingKey: options.orderingKey,
4486
4874
  traceContext: carrier
4487
4875
  };
4488
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
4876
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
4489
4877
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
4490
4878
  }
4491
4879
  async *getFollowers(identifier) {
@@ -4839,7 +5227,7 @@ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
4839
5227
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
4840
5228
  keys = forwarder;
4841
5229
  } else keys = [forwarder];
4842
- if (!hasSignature(this.activity)) {
5230
+ if (!hasVerifiableSignature(this.activity)) {
4843
5231
  let hasProof;
4844
5232
  try {
4845
5233
  hasProof = await (await Activity.fromJsonLd(this.activity, this)).getProof() != null;
@@ -4871,18 +5259,26 @@ var InboxContextImpl = class InboxContextImpl extends ContextImpl {
4871
5259
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
4872
5260
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
4873
5261
  const promises = [];
4874
- for (const inbox in inboxes) promises.push(sendActivity({
4875
- allowPrivateAddress: this.federation.allowPrivateAddress,
4876
- keys,
4877
- activity: this.activity,
4878
- activityId: this.activityId,
4879
- activityType: this.activityType,
4880
- inbox: new URL(inbox),
4881
- sharedInbox: inboxes[inbox].sharedInbox,
4882
- tracerProvider: this.tracerProvider,
4883
- specDeterminer: new KvSpecDeterminer(this.federation.kv, this.federation.kvPrefixes.httpMessageSignaturesSpec, this.federation.firstKnock)
4884
- }));
4885
- 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
+ }
4886
5282
  return;
4887
5283
  }
4888
5284
  logger.debug("Enqueuing activity {activityId} to forward later.", {
@@ -4977,6 +5373,69 @@ var KvSpecDeterminer = class {
4977
5373
  function notFound(_request) {
4978
5374
  return new Response("Not Found", { status: 404 });
4979
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
+ }
4980
5439
  function notAcceptable(_request) {
4981
5440
  return new Response("Not Acceptable", {
4982
5441
  status: 406,