@fedify/fedify 2.3.16-dev.2845 → 2.3.16

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 (108) hide show
  1. package/dist/attachment-arrays-BlfpZlWF.mjs +16 -0
  2. package/dist/{builder-B9apzaoK.mjs → builder-D4GE1Gmi.mjs} +3 -3
  3. package/dist/callback-kR_sx2zZ.d.mts +2661 -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-DpUNYKla.mjs → client-DFgYVbUA.mjs} +86 -11
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +255 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/outgoing-jsonld.test.mjs +1 -1
  12. package/dist/compat/public-audience.test.mjs +1 -1
  13. package/dist/compat/transformers.test.mjs +1 -1
  14. package/dist/{context-CE_Tj_Oc.d.cts → context-CEE8vl-b.d.cts} +31 -14
  15. package/dist/{context-H_5tZXg-.d.ts → context-CTJwXHRu.d.ts} +31 -14
  16. package/dist/{deno-CgHxPWA-.mjs → deno-FtdqgHJA.mjs} +1 -1
  17. package/dist/{docloader-CYscMv4m.mjs → docloader-B9iU4DP2.mjs} +2 -2
  18. package/dist/federation/attachment-responses.test.d.mts +2 -0
  19. package/dist/federation/attachment-responses.test.mjs +182 -0
  20. package/dist/federation/builder.test.mjs +1 -1
  21. package/dist/federation/circuit-breaker.test.mjs +2 -2
  22. package/dist/federation/collection.test.mjs +1 -1
  23. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  24. package/dist/federation/delivery-attachments.test.mjs +288 -0
  25. package/dist/federation/handler.test.mjs +208 -16
  26. package/dist/federation/idempotency.test.mjs +2 -2
  27. package/dist/federation/inbox.test.mjs +2 -2
  28. package/dist/federation/metrics.test.mjs +1 -1
  29. package/dist/federation/middleware.test.mjs +1191 -16
  30. package/dist/federation/mod.cjs +1 -1
  31. package/dist/federation/mod.d.cts +2 -2
  32. package/dist/federation/mod.d.ts +2 -2
  33. package/dist/federation/mod.js +1 -1
  34. package/dist/federation/negotiation.test.mjs +1 -1
  35. package/dist/federation/retry.test.mjs +1 -1
  36. package/dist/federation/send.test.mjs +293 -3
  37. package/dist/federation/temporal.test.mjs +25 -1
  38. package/dist/federation/webfinger.test.mjs +1 -1
  39. package/dist/{http-CfxAK-RL.cjs → http-2RyDQ0tE.cjs} +6 -4
  40. package/dist/{http-DmP0sr2l.d.ts → http-Bs5mXWlH.d.ts} +3 -3
  41. package/dist/{http-CZPYFK3b.d.cts → http-D8DgRhHU.d.cts} +3 -3
  42. package/dist/{http-dzXtCtOp.mjs → http-D8tiOrZf.mjs} +7 -5
  43. package/dist/{http-BzIb8Gk0.js → http-mLeLYFj-.js} +6 -4
  44. package/dist/{inbox-BMytDl21.mjs → inbox-Dy8awbi8.mjs} +2 -2
  45. package/dist/{key-fdTPEBhG.mjs → key-o1SmN5s0.mjs} +4 -3
  46. package/dist/{kv-cache-ShxnSuNt.mjs → kv-cache-BwUrzCVO.mjs} +1 -1
  47. package/dist/{kv-cache-dQUFD_pa.cjs → kv-cache-CI6Z0WiS.cjs} +1 -1
  48. package/dist/{kv-cache-CwqJUNNd.js → kv-cache-Dsq8C8D8.js} +1 -1
  49. package/dist/{ld-B8mU49Dg.mjs → ld-DCKrqj9y.mjs} +155 -22
  50. package/dist/ld-signature-Dgz_b89j.mjs +23 -0
  51. package/dist/{metrics-C0ZYkgVy.mjs → metrics-CaoYRhNH.mjs} +1 -1
  52. package/dist/{middleware-DK_kGeMl.mjs → middleware-4p3opEMT.mjs} +1 -1
  53. package/dist/{middleware-9mBkHYci.cjs → middleware-CP-8P7kk.cjs} +492 -117
  54. package/dist/{middleware-D0GPqg_7.js → middleware-Cce0nLDw.js} +491 -117
  55. package/dist/{middleware-Hr9ci9uD.mjs → middleware-D31fNcY4.mjs} +399 -109
  56. package/dist/{mod-C_gFmeNq.d.cts → mod-BD0-_vya.d.ts} +31 -13
  57. package/dist/{mod-HQXFvOHs.d.ts → mod-BMX6nsHP.d.cts} +31 -13
  58. package/dist/{mod-CDFFESfL.d.ts → mod-BTvP5Hva.d.ts} +1 -1
  59. package/dist/{mod-DMjhnFbg.d.ts → mod-DgMTlwUO.d.ts} +3 -3
  60. package/dist/{mod-DDVkmZ_h.d.cts → mod-Q1Fo3FJk.d.cts} +3 -3
  61. package/dist/{mod-DDjtbkZO.d.cts → mod-n51LED4J.d.cts} +1 -1
  62. package/dist/mod.cjs +5 -5
  63. package/dist/mod.d.cts +8 -8
  64. package/dist/mod.d.ts +8 -8
  65. package/dist/mod.js +5 -5
  66. package/dist/nodeinfo/client.test.mjs +432 -4
  67. package/dist/nodeinfo/handler.test.mjs +1 -1
  68. package/dist/nodeinfo/mod.cjs +1 -1
  69. package/dist/nodeinfo/mod.d.cts +1 -1
  70. package/dist/nodeinfo/mod.d.ts +1 -1
  71. package/dist/nodeinfo/mod.js +1 -1
  72. package/dist/nodeinfo/types.test.mjs +1 -1
  73. package/dist/{outgoing-jsonld-D4iTv7uM.mjs → outgoing-jsonld-BZEAVK_Q.mjs} +38 -8
  74. package/dist/{owner-BqnaV4zl.mjs → owner-Bdj0nHhf.mjs} +2 -2
  75. package/dist/{proof-BSRF2hIP.js → proof-B9XJiyz-.js} +1030 -858
  76. package/dist/{proof-D9VX-J1n.cjs → proof-CmcP8yqP.cjs} +1243 -1059
  77. package/dist/{proof-BvpOtXRD.mjs → proof-DrbjYma9.mjs} +41 -16
  78. package/dist/{send-BPel6SCW.mjs → send-VD_WG3dN.mjs} +100 -22
  79. package/dist/sig/http.test.mjs +2 -2
  80. package/dist/sig/key-types.test.d.mts +218 -0
  81. package/dist/sig/key-types.test.mjs +8 -0
  82. package/dist/sig/key.test.mjs +2 -2
  83. package/dist/sig/ld.test.mjs +573 -8
  84. package/dist/sig/mod.cjs +2 -2
  85. package/dist/sig/mod.d.cts +3 -3
  86. package/dist/sig/mod.d.ts +3 -3
  87. package/dist/sig/mod.js +2 -2
  88. package/dist/sig/owner.test.mjs +1 -1
  89. package/dist/sig/proof.test.mjs +96 -4
  90. package/dist/{temporal-CaD1O1QX.mjs → temporal-CMvoB-vD.mjs} +3 -5
  91. package/dist/testing/mod.d.mts +2 -2476
  92. package/dist/{types-DOvyymM4.cjs → types-BWx7zw3Y.cjs} +85 -10
  93. package/dist/{types-B1_pRFE_.js → types-Dx_w2JSM.js} +86 -11
  94. package/dist/utils/docloader.test.mjs +2 -2
  95. package/dist/utils/kv-cache.test.mjs +1 -1
  96. package/dist/utils/mod.cjs +1 -1
  97. package/dist/utils/mod.d.cts +1 -1
  98. package/dist/utils/mod.d.ts +1 -1
  99. package/dist/utils/mod.js +1 -1
  100. package/package.json +6 -6
  101. /package/dist/{activity-listener-tztVvlNb.mjs → activity-listener-BeTGV3wc.mjs} +0 -0
  102. /package/dist/{circuit-breaker-D1fxthDI.mjs → circuit-breaker-B1fLHmg2.mjs} +0 -0
  103. /package/dist/{circuit-breaker-test-utils-CAdwjgMi.mjs → circuit-breaker-test-utils-BGHm_MsT.mjs} +0 -0
  104. /package/dist/{collection-Cc3DVAhE.mjs → collection-Dp5ky45w.mjs} +0 -0
  105. /package/dist/{negotiation-DDstyBvc.mjs → negotiation-DC8nG6J_.mjs} +0 -0
  106. /package/dist/{public-audience-Dp4ZScSr.mjs → public-audience-rnYUGj8a.mjs} +0 -0
  107. /package/dist/{retry-CXg_MBI-.mjs → retry-C4G_vIgv.mjs} +0 -0
  108. /package/dist/{types-J53Kw7so.mjs → types-BFowWFTT.mjs} +0 -0
@@ -2,22 +2,25 @@ const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  const require_chunk = require("./chunk-DDcVe30Y.cjs");
4
4
  const require_transformers = require("./transformers-NeAONrAq.cjs");
5
- const require_http = require("./http-CfxAK-RL.cjs");
6
- const require_types = require("./types-DOvyymM4.cjs");
7
- const require_proof = require("./proof-D9VX-J1n.cjs");
8
- const require_kv_cache = require("./kv-cache-dQUFD_pa.cjs");
5
+ const require_http = require("./http-2RyDQ0tE.cjs");
6
+ const require_proof = require("./proof-CmcP8yqP.cjs");
7
+ const require_types = require("./types-BWx7zw3Y.cjs");
8
+ const require_kv_cache = require("./kv-cache-CI6Z0WiS.cjs");
9
9
  let _logtape_logtape = require("@logtape/logtape");
10
10
  let _fedify_uri_template = require("@fedify/uri-template");
11
11
  let _fedify_vocab = require("@fedify/vocab");
12
12
  let _opentelemetry_api = require("@opentelemetry/api");
13
13
  let byte_encodings_hex = require("byte-encodings/hex");
14
14
  let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
15
- let es_toolkit = require("es-toolkit");
16
- let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
17
15
  let _fedify_vocab_runtime_jsonld = require("@fedify/vocab-runtime/jsonld");
18
16
  _fedify_vocab_runtime_jsonld = require_chunk.__toESM(_fedify_vocab_runtime_jsonld, 1);
19
- let _fedify_webfinger = require("@fedify/webfinger");
17
+ let es_toolkit = require("es-toolkit");
20
18
  let _fedify_vocab_runtime_internal = require("@fedify/vocab-runtime/internal");
19
+ let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
20
+ let json_canon = require("json-canon");
21
+ json_canon = require_chunk.__toESM(json_canon, 1);
22
+ let _fedify_vocab_runtime_temporal = require("@fedify/vocab-runtime/temporal");
23
+ let _fedify_webfinger = require("@fedify/webfinger");
21
24
  let _opentelemetry_sdk_metrics = require("@opentelemetry/sdk-metrics");
22
25
  let node_url = require("node:url");
23
26
  //#region src/federation/activity-listener.ts
@@ -1264,6 +1267,17 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
1264
1267
  return `collectionId="${collectionId}", url="${url}", digest="${(0, byte_encodings_hex.encodeHex)(await digest(actorIds))}"`;
1265
1268
  }
1266
1269
  //#endregion
1270
+ //#region src/compat/attachment-arrays.ts
1271
+ /**
1272
+ * Applies the shared attachment workaround to served documents without
1273
+ * rewriting any document that contains a semantic proof or LD signature.
1274
+ * RDF equivalence alone cannot preserve JCS signatures.
1275
+ * @internal
1276
+ */
1277
+ function normalizeAttachmentArrays(document, contextLoader) {
1278
+ return require_proof.normalizeAttachmentArrays(document, contextLoader, true);
1279
+ }
1280
+ //#endregion
1267
1281
  //#region src/federation/inbox.ts
1268
1282
  /**
1269
1283
  * Checks whether an activity's ID and all of its actor IDs have the same
@@ -1651,13 +1665,10 @@ function acceptsJsonLd(request) {
1651
1665
  function isPlainObject(value) {
1652
1666
  return typeof value === "object" && value != null && !Array.isArray(value);
1653
1667
  }
1654
- function normalizeDateTimeLiteral(value) {
1655
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1656
- }
1657
1668
  function isMalformedDateTimeLiteral(value) {
1658
1669
  if (typeof value !== "string") return false;
1659
1670
  try {
1660
- Temporal.Instant.from(normalizeDateTimeLiteral(value));
1671
+ Temporal.Instant.from((0, _fedify_vocab_runtime_temporal.normalizeDateTimeLiteral)(value));
1661
1672
  return false;
1662
1673
  } catch {
1663
1674
  return true;
@@ -1695,7 +1706,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1695
1706
  if (typeof literal === "boolean") return false;
1696
1707
  if (typeof literal !== "string") return false;
1697
1708
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1698
- if (new Date(literal).toString() === "Invalid Date") return false;
1709
+ if (new Date(literal).toString() === "Invalid Date" && new Date((0, _fedify_vocab_runtime_temporal.normalizeDateTimeLiteral)(literal)).toString() === "Invalid Date") return false;
1699
1710
  return isMalformedDateTimeLiteral(literal);
1700
1711
  }
1701
1712
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1790,7 +1801,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1790
1801
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1791
1802
  }
1792
1803
  if (actor instanceof _fedify_vocab.Tombstone) {
1793
- const jsonLd = await actor.toJsonLd(context);
1804
+ const jsonLd = await serializeForResponse(actor, context);
1794
1805
  return new Response(JSON.stringify(jsonLd), {
1795
1806
  status: 410,
1796
1807
  headers: {
@@ -1799,7 +1810,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1799
1810
  }
1800
1811
  });
1801
1812
  }
1802
- const jsonLd = await actor.toJsonLd(context);
1813
+ const jsonLd = await serializeForResponse(actor, context);
1803
1814
  return new Response(JSON.stringify(jsonLd), { headers: {
1804
1815
  "Content-Type": "application/activity+json",
1805
1816
  Vary: "Accept"
@@ -1819,7 +1830,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1819
1830
  if (authorizePredicate != null) {
1820
1831
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1821
1832
  }
1822
- const jsonLd = await object.toJsonLd(context);
1833
+ const jsonLd = await serializeForResponse(object, context);
1823
1834
  return new Response(JSON.stringify(jsonLd), { headers: {
1824
1835
  "Content-Type": "application/activity+json",
1825
1836
  Vary: "Accept"
@@ -1862,13 +1873,13 @@ function recordCollectionMetrics(meterProvider, base, result, options = {}) {
1862
1873
  * @param parameters The parameters for handling the collection.
1863
1874
  * @returns A promise that resolves to an HTTP response.
1864
1875
  */
1865
- async function handleCollection(request, { name: name$1, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
1866
- const spanName = name$1.trim().replace(/\s+/g, "_");
1876
+ async function handleCollection(request, { name: name$2, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
1877
+ const spanName = name$2.trim().replace(/\s+/g, "_");
1867
1878
  tracerProvider = tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
1868
1879
  const tracer = tracerProvider.getTracer(require_http.name, require_http.version);
1869
1880
  const cursor = new URL(request.url).searchParams.get("cursor");
1870
1881
  const metricBase = {
1871
- kind: getCollectionMetricKind(name$1),
1882
+ kind: getCollectionMetricKind(name$2),
1872
1883
  page: cursor != null,
1873
1884
  dispatcher: "built_in"
1874
1885
  };
@@ -1909,7 +1920,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1909
1920
  span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
1910
1921
  return await onNotFound(request);
1911
1922
  }
1912
- const items = filterCollectionItems(page.items, name$1, filterPredicate);
1923
+ const items = filterCollectionItems(page.items, name$2, filterPredicate);
1913
1924
  itemCount = items.length;
1914
1925
  span.setAttribute("fedify.collection.items", itemCount);
1915
1926
  return items;
@@ -1949,7 +1960,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1949
1960
  } else {
1950
1961
  const uri = new URL(baseUri);
1951
1962
  uri.searchParams.set("cursor", cursor);
1952
- const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$1}`, {
1963
+ const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$2}`, {
1953
1964
  kind: _opentelemetry_api.SpanKind.SERVER,
1954
1965
  attributes: {
1955
1966
  "activitypub.collection.id": uri.href,
@@ -1965,7 +1976,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1965
1976
  span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
1966
1977
  return await onNotFound(request);
1967
1978
  }
1968
- const items = filterCollectionItems(page.items, name$1, filterPredicate);
1979
+ const items = filterCollectionItems(page.items, name$2, filterPredicate);
1969
1980
  itemCount = items.length;
1970
1981
  span.setAttribute("fedify.collection.items", itemCount);
1971
1982
  return {
@@ -2008,7 +2019,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
2008
2019
  if (collectionCallbacks.authorizePredicate != null) {
2009
2020
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return finish(await onUnauthorized(request), "unauthorized");
2010
2021
  }
2011
- const jsonLd = await collection.toJsonLd(context);
2022
+ const jsonLd = await serializeForResponse(collection, context);
2012
2023
  return finish(new Response(JSON.stringify(jsonLd), { headers: {
2013
2024
  "Content-Type": "application/activity+json",
2014
2025
  Vary: "Accept"
@@ -2365,7 +2376,11 @@ async function handleInboxInternal(request, parameters, span) {
2365
2376
  }
2366
2377
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
2367
2378
  const jsonWithoutSig = require_proof.detachSignature(json);
2368
- const hasLdSignature = require_proof.hasSignature(json);
2379
+ const hasLdSignature = require_proof.hasVerifiableSignature(json);
2380
+ if (!hasLdSignature) {
2381
+ const shape = require_proof.describeSignatureShape(json);
2382
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
2383
+ }
2369
2384
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
2370
2385
  let deferredLdSignatureError = void 0;
2371
2386
  const respondInvalidActivity = async (error) => {
@@ -2871,8 +2886,8 @@ var CustomCollectionHandler = class {
2871
2886
  * @param CollectionPage The CollectionPage constructor.
2872
2887
  * @param filterPredicate Optional filter predicate for items.
2873
2888
  */
2874
- constructor(name$2, values, context, callbacks, tracerProvider = _opentelemetry_api.trace.getTracerProvider(), meterProvider, Collection, CollectionPage, filterPredicate) {
2875
- this.name = name$2;
2889
+ constructor(name$1, values, context, callbacks, tracerProvider = _opentelemetry_api.trace.getTracerProvider(), meterProvider, Collection, CollectionPage, filterPredicate) {
2890
+ this.name = name$1;
2876
2891
  this.values = values;
2877
2892
  this.context = context;
2878
2893
  this.callbacks = callbacks;
@@ -2891,7 +2906,7 @@ var CustomCollectionHandler = class {
2891
2906
  * @returns A promise that resolves to the JSON-LD representation.
2892
2907
  */
2893
2908
  async toJsonLd() {
2894
- return (await this.collection).toJsonLd(this.context);
2909
+ return serializeForResponse(await this.collection, this.context);
2895
2910
  }
2896
2911
  /**
2897
2912
  * Fetches the collection with optional cursor for pagination.
@@ -3268,7 +3283,7 @@ var UnauthorizedError = class extends HandlerError {
3268
3283
  * @since 0.3.0
3269
3284
  */
3270
3285
  async function respondWithObject(object, options) {
3271
- const jsonLd = await object.toJsonLd(options);
3286
+ const jsonLd = await serializeForResponse(object, options);
3272
3287
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
3273
3288
  }
3274
3289
  /**
@@ -3356,6 +3371,106 @@ const MIN_COMPONENTS = [
3356
3371
  "@target-uri",
3357
3372
  "@authority"
3358
3373
  ];
3374
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
3375
+ async function serializeForResponse(object, options) {
3376
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
3377
+ }
3378
+ //#endregion
3379
+ //#region src/sig/proof-creation.ts
3380
+ /** Signs the exact serialized message supplied by an internal producer. */
3381
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
3382
+ require_http.validateCryptoKey(privateKey, "private");
3383
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
3384
+ const encoder = new TextEncoder();
3385
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode((0, json_canon.default)(jsonLd)));
3386
+ created ??= Temporal.Now.instant();
3387
+ const proofConfig = {
3388
+ "@context": jsonLd["@context"],
3389
+ type: "DataIntegrityProof",
3390
+ cryptosuite: "eddsa-jcs-2022",
3391
+ verificationMethod: keyId.href,
3392
+ proofPurpose: "assertionMethod",
3393
+ created: created.toString()
3394
+ };
3395
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode((0, json_canon.default)(proofConfig)));
3396
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
3397
+ digest.set(new Uint8Array(proofDigest), 0);
3398
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
3399
+ const sig = await crypto.subtle.sign("Ed25519", (0, _fedify_vocab_runtime_internal.asCryptoKey)(privateKey), digest);
3400
+ return new _fedify_vocab.DataIntegrityProof({
3401
+ cryptosuite: "eddsa-jcs-2022",
3402
+ verificationMethod: keyId,
3403
+ proofPurpose: "assertionMethod",
3404
+ created,
3405
+ proofValue: new Uint8Array(sig)
3406
+ });
3407
+ }
3408
+ //#endregion
3409
+ //#region src/compat/delivery-jsonld.ts
3410
+ /**
3411
+ * Returns changed wire JSON only; unchanged documents keep the existing
3412
+ * delivery signing path. This uses ordinary vocabulary serialization, without
3413
+ * retaining or repairing independently signed child representations.
3414
+ */
3415
+ async function prepareActivityJsonLd(activity, contextLoader) {
3416
+ if (activity.proofIds.length > 0) return void 0;
3417
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
3418
+ const source = await activity.clone().toJsonLd({
3419
+ format: "compact",
3420
+ contextLoader
3421
+ });
3422
+ const prepared = await require_proof.normalizeOutgoingActivityJsonLd(source, contextLoader, true);
3423
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
3424
+ }
3425
+ /** Signs a changed, proof-free delivery map without serializing it again. */
3426
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
3427
+ const proofs = [];
3428
+ const serializedProofs = [];
3429
+ const tracer = (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version);
3430
+ for (const { privateKey, keyId } of keys) {
3431
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": (0, _fedify_vocab.getTypeId)(activity).href } }, async (span) => {
3432
+ try {
3433
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
3434
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
3435
+ if (span.isRecording()) {
3436
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
3437
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
3438
+ span.setAttribute("object_integrity_proofs.signature", (0, byte_encodings_hex.encodeHex)(proof.proofValue));
3439
+ }
3440
+ return proof;
3441
+ } catch (error) {
3442
+ span.setStatus({
3443
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
3444
+ message: String(error)
3445
+ });
3446
+ throw error;
3447
+ } finally {
3448
+ span.end();
3449
+ }
3450
+ });
3451
+ proofs.push(proof);
3452
+ serializedProofs.push({
3453
+ "@context": unsigned["@context"],
3454
+ type: "DataIntegrityProof",
3455
+ cryptosuite: proof.cryptosuite,
3456
+ verificationMethod: keyId.href,
3457
+ proofPurpose: "assertionMethod",
3458
+ created: proof.created.toString(),
3459
+ proofValue: new TextDecoder().decode((0, _fedify_vocab_runtime.encodeMultibase)("base58btc", proof.proofValue))
3460
+ });
3461
+ }
3462
+ if (proofs.length === 0) return {
3463
+ activity,
3464
+ jsonLd: unsigned
3465
+ };
3466
+ return {
3467
+ activity: activity.clone({ proofs }),
3468
+ jsonLd: {
3469
+ ...unsigned,
3470
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
3471
+ }
3472
+ };
3473
+ }
3359
3474
  //#endregion
3360
3475
  //#region src/nodeinfo/handler.ts
3361
3476
  /**
@@ -3425,7 +3540,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
3425
3540
  * @param parameters The parameters for sending the activity.
3426
3541
  * See also {@link SendActivityParameters}.
3427
3542
  * @param deps The dependencies, for tests.
3428
- * @throws {Error} If the activity fails to send.
3543
+ * @throws {FetchError} If the delivery times out before receiving a response.
3544
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
3429
3545
  */
3430
3546
  function sendActivity(options, deps = {}) {
3431
3547
  const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
@@ -3452,6 +3568,24 @@ function sendActivity(options, deps = {}) {
3452
3568
  });
3453
3569
  }
3454
3570
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
3571
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
3572
+ function raceWithAbort(promise, signal) {
3573
+ if (signal.aborted) return Promise.reject(signal.reason);
3574
+ return new Promise((resolve, reject) => {
3575
+ const onAbort = () => {
3576
+ signal.removeEventListener("abort", onAbort);
3577
+ reject(signal.reason);
3578
+ };
3579
+ signal.addEventListener("abort", onAbort, { once: true });
3580
+ promise.then((value) => {
3581
+ signal.removeEventListener("abort", onAbort);
3582
+ resolve(value);
3583
+ }, (error) => {
3584
+ signal.removeEventListener("abort", onAbort);
3585
+ reject(error);
3586
+ });
3587
+ });
3588
+ }
3455
3589
  function getActivityActorId(activity) {
3456
3590
  if (!isRecord(activity)) return void 0;
3457
3591
  return getIdValue(activity.actor);
@@ -3471,7 +3605,7 @@ function getIdValue(value) {
3471
3605
  function isRecord(value) {
3472
3606
  return typeof value === "object" && value != null;
3473
3607
  }
3474
- async function readLimitedResponseBody(response, maxBytes) {
3608
+ async function readLimitedResponseBody(response, maxBytes, signal) {
3475
3609
  if (response.body == null) return "";
3476
3610
  const reader = response.body.getReader();
3477
3611
  const decoder = new TextDecoder();
@@ -3480,7 +3614,8 @@ async function readLimitedResponseBody(response, maxBytes) {
3480
3614
  let truncated = false;
3481
3615
  try {
3482
3616
  while (true) {
3483
- const { done, value } = await reader.read();
3617
+ signal.throwIfAborted();
3618
+ const { done, value } = await raceWithAbort(reader.read(), signal);
3484
3619
  if (done) break;
3485
3620
  if (totalBytes + value.length > maxBytes) {
3486
3621
  const remaining = maxBytes - totalBytes;
@@ -3492,8 +3627,10 @@ async function readLimitedResponseBody(response, maxBytes) {
3492
3627
  totalBytes += value.length;
3493
3628
  }
3494
3629
  } finally {
3495
- if (truncated) reader.cancel().catch(() => {});
3496
- reader.releaseLock();
3630
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
3631
+ try {
3632
+ reader.releaseLock();
3633
+ } catch (_) {}
3497
3634
  }
3498
3635
  let result = chunks.join("");
3499
3636
  if (truncated) result += "… (truncated)";
@@ -3508,11 +3645,30 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3508
3645
  const federationMetrics = require_http.getFederationMetrics(meterProvider);
3509
3646
  const started = performance.now();
3510
3647
  let deliverySuccess = false;
3511
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? _fedify_vocab_runtime_internal.openDirectFetch : (url) => (0, _fedify_vocab_runtime_internal.openPublicFetch)(url));
3648
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
3649
+ const controller = new AbortController();
3650
+ const { signal } = controller;
3651
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
3652
+ function timeoutFailure(error) {
3653
+ if (!signal.aborted || error instanceof SendActivityError) return error;
3654
+ const failure = new _fedify_vocab_runtime.FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
3655
+ failure.cause = signal.reason;
3656
+ return failure;
3657
+ }
3658
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? _fedify_vocab_runtime_internal.openDirectFetch : (url) => (0, _fedify_vocab_runtime_internal.openPublicFetch)(url, { signal }));
3512
3659
  async function openHop(url) {
3513
3660
  let session;
3514
3661
  try {
3515
- session = await openUnvalidatedHop(url);
3662
+ signal.throwIfAborted();
3663
+ const opening = openUnvalidatedHop(url);
3664
+ opening.then((lateSession) => {
3665
+ if (signal.aborted) closeAfterError(lateSession, logger);
3666
+ }, () => {});
3667
+ session = await raceWithAbort(opening, signal);
3668
+ if (signal.aborted) {
3669
+ closeAfterError(session, logger);
3670
+ signal.throwIfAborted();
3671
+ }
3516
3672
  } catch (error) {
3517
3673
  if (error instanceof _fedify_vocab_runtime.UrlError && error.reason === "dns") {
3518
3674
  logger.error("DNS resolution failed for URL: {url}", {
@@ -3535,8 +3691,15 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3535
3691
  try {
3536
3692
  initialSession = await openHop(inbox.href);
3537
3693
  } catch (error) {
3538
- if (error instanceof _fedify_vocab_runtime.FetchError) federationMetrics.recordDelivery(inbox, require_http.getDurationMs(started), false, activityType);
3539
- throw error;
3694
+ const failure = timeoutFailure(error);
3695
+ if (failure instanceof _fedify_vocab_runtime.FetchError) federationMetrics.recordDelivery(inbox, require_http.getDurationMs(started), false, activityType);
3696
+ if (signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
3697
+ activityId,
3698
+ inbox: inbox.href,
3699
+ error: failure
3700
+ });
3701
+ clearTimeout(timer);
3702
+ throw failure;
3540
3703
  }
3541
3704
  let initialPending = true;
3542
3705
  const openDeliveryHop = (url) => {
@@ -3553,7 +3716,8 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3553
3716
  method: "POST",
3554
3717
  headers,
3555
3718
  body: JSON.stringify(activity),
3556
- redirect: "manual"
3719
+ redirect: "manual",
3720
+ signal
3557
3721
  });
3558
3722
  let rsaKey = null;
3559
3723
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -3568,13 +3732,35 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3568
3732
  }))
3569
3733
  });
3570
3734
  let outcome;
3735
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
3736
+ determineSpec(origin) {
3737
+ signal.throwIfAborted();
3738
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
3739
+ },
3740
+ rememberSpec(origin, spec) {
3741
+ if (signal.aborted) return;
3742
+ try {
3743
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
3744
+ origin,
3745
+ error
3746
+ }));
3747
+ } catch (error) {
3748
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
3749
+ origin,
3750
+ error
3751
+ });
3752
+ }
3753
+ }
3754
+ };
3571
3755
  try {
3572
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox)) : await require_http.doubleKnockScoped(request, rsaKey, {
3756
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await require_http.doubleKnockScoped(request, rsaKey, {
3573
3757
  tracerProvider,
3574
- specDeterminer
3575
- }, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox));
3758
+ specDeterminer: boundedSpecDeterminer,
3759
+ signal
3760
+ }, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox, signal));
3576
3761
  } catch (error) {
3577
- const failure = error instanceof _fedify_vocab_runtime.FetchError || error instanceof _fedify_vocab_runtime.UrlError ? error : createFetchError(inbox.href, error);
3762
+ const boundedError = timeoutFailure(error);
3763
+ const failure = boundedError instanceof _fedify_vocab_runtime.FetchError || boundedError instanceof _fedify_vocab_runtime.UrlError ? boundedError : createFetchError(inbox.href, boundedError);
3578
3764
  logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
3579
3765
  activityId,
3580
3766
  inbox: inbox.href,
@@ -3608,6 +3794,7 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3608
3794
  federationMetrics.recordDelivery(inbox, require_http.getDurationMs(started), deliverySuccess, activityType);
3609
3795
  }
3610
3796
  } finally {
3797
+ clearTimeout(timer);
3611
3798
  if (initialPending) await initialSession.close();
3612
3799
  }
3613
3800
  }
@@ -3639,17 +3826,18 @@ function cancelResponseBody(response, url) {
3639
3826
  * session is open: the body of a successful response is cancelled, and at
3640
3827
  * most 1 KiB of an error response body is read.
3641
3828
  */
3642
- async function consumeSendActivityResponse(response, inbox) {
3829
+ async function consumeSendActivityResponse(response, inbox, signal) {
3643
3830
  if (response.ok) {
3644
3831
  cancelResponseBody(response, response.url || inbox.href);
3645
3832
  return { ok: true };
3646
3833
  }
3647
3834
  let error;
3648
3835
  try {
3649
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
3836
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
3650
3837
  } catch (_) {
3651
3838
  error = "";
3652
3839
  }
3840
+ if (signal.aborted) error = "(timed out reading response body)";
3653
3841
  return {
3654
3842
  ok: false,
3655
3843
  status: response.status,
@@ -3669,7 +3857,7 @@ async function consumeSendActivityResponse(response, inbox) {
3669
3857
  * @param consume The function to consume the final response.
3670
3858
  * @returns The value returned by `consume`.
3671
3859
  */
3672
- async function fetchWithValidatedRedirects(request, openHop, consume) {
3860
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
3673
3861
  const logger = (0, _logtape_logtape.getLogger)([
3674
3862
  "fedify",
3675
3863
  "federation",
@@ -3677,10 +3865,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
3677
3865
  ]);
3678
3866
  let body = await request.clone().text();
3679
3867
  for (let redirects = 0;; redirects++) {
3868
+ signal?.throwIfAborted();
3680
3869
  const session = await openHop(request.url);
3681
3870
  let response;
3682
3871
  try {
3683
- response = await session.fetch(request, { redirect: "manual" });
3872
+ response = await session.fetch(request, {
3873
+ redirect: "manual",
3874
+ signal
3875
+ });
3684
3876
  } catch (error) {
3685
3877
  await closeAfterError(session, logger);
3686
3878
  throw error;
@@ -3730,7 +3922,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
3730
3922
  method,
3731
3923
  headers,
3732
3924
  body,
3733
- redirect: "manual"
3925
+ redirect: "manual",
3926
+ signal: signal ?? request.signal
3734
3927
  });
3735
3928
  }
3736
3929
  }
@@ -4585,8 +4778,25 @@ var FederationImpl = class extends FederationBuilderImpl {
4585
4778
  _getTracer() {
4586
4779
  return this.tracerProvider.getTracer(require_http.name, require_http.version);
4587
4780
  }
4781
+ /**
4782
+ * Starts listening on a queue, converting a synchronous throw into
4783
+ * a rejected promise.
4784
+ *
4785
+ * `MessageQueue.listen()` is documented to never reject, but some
4786
+ * implementations (e.g., `WorkersMessageQueue`) throw synchronously. Without
4787
+ * this normalization, one such throw aborts {@link _startQueueInternal} while
4788
+ * it is still collecting listener promises, so listeners started earlier are
4789
+ * never awaited and later queues are never started.
4790
+ */
4791
+ #listenQueue(queue, ctxData, signal) {
4792
+ try {
4793
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
4794
+ } catch (error) {
4795
+ return Promise.reject(error);
4796
+ }
4797
+ }
4588
4798
  async _startQueueInternal(ctxData, signal, queue) {
4589
- if (this.inboxQueue == null && this.outboxQueue == null) return;
4799
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
4590
4800
  const logger = (0, _logtape_logtape.getLogger)([
4591
4801
  "fedify",
4592
4802
  "federation",
@@ -4596,20 +4806,38 @@ var FederationImpl = class extends FederationBuilderImpl {
4596
4806
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
4597
4807
  logger.debug("Starting an inbox task worker.");
4598
4808
  this.inboxQueueStarted = true;
4599
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
4809
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
4600
4810
  }
4601
4811
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
4602
4812
  logger.debug("Starting an outbox task worker.");
4603
4813
  this.outboxQueueStarted = true;
4604
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
4814
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
4605
4815
  }
4606
4816
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
4607
4817
  logger.debug("Starting a fanout task worker.");
4608
4818
  this.fanoutQueueStarted = true;
4609
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
4819
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
4610
4820
  }
4611
4821
  await Promise.all(promises);
4612
4822
  }
4823
+ /**
4824
+ * Starts the queue workers automatically, reporting a failure instead of
4825
+ * leaving the returned promise unobserved.
4826
+ *
4827
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
4828
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
4829
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
4830
+ * callers that start workers deliberately.
4831
+ */
4832
+ _startQueueAutomatically(ctxData) {
4833
+ this._startQueueInternal(ctxData).catch((error) => {
4834
+ (0, _logtape_logtape.getLogger)([
4835
+ "fedify",
4836
+ "federation",
4837
+ "queue"
4838
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
4839
+ });
4840
+ }
4613
4841
  processQueuedTask(contextData, message) {
4614
4842
  const tracer = this._getTracer();
4615
4843
  const extractedContext = _opentelemetry_api.propagation.extract(_opentelemetry_api.context.active(), message.traceContext);
@@ -4764,7 +4992,8 @@ var FederationImpl = class extends FederationBuilderImpl {
4764
4992
  collectionSync: message.collectionSync,
4765
4993
  orderingKey: message.orderingKey,
4766
4994
  normalizeExistingProofs: message.normalizeExistingProofs,
4767
- context
4995
+ context,
4996
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
4768
4997
  });
4769
4998
  }
4770
4999
  async #listenOutboxMessage(_, message, span) {
@@ -5177,7 +5406,7 @@ var FederationImpl = class extends FederationBuilderImpl {
5177
5406
  let parseInput = void 0;
5178
5407
  let parseContextLoader = context.contextLoader;
5179
5408
  try {
5180
- const hasSignatureField = require_proof.hasSignature(message.activity);
5409
+ const hasSignatureField = require_proof.hasVerifiableSignature(message.activity);
5181
5410
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
5182
5411
  const parseContext = hasSignatureField ? {
5183
5412
  ...context,
@@ -5389,21 +5618,31 @@ var FederationImpl = class extends FederationBuilderImpl {
5389
5618
  hasProof = true;
5390
5619
  break;
5391
5620
  }
5392
- if (!hasProof) {
5393
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
5394
- activity = await require_proof.signObject(activity, privateKey, keyId, {
5395
- contextLoader,
5396
- tracerProvider: this.tracerProvider
5397
- });
5398
- hasProof = true;
5399
- proofCreated = true;
5621
+ const prepared = !hasProof && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
5622
+ let jsonLd;
5623
+ if (prepared != null) {
5624
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
5625
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
5626
+ activity = signed.activity;
5627
+ jsonLd = signed.jsonLd;
5628
+ proofCreated = signingKeys.length > 0;
5629
+ } else {
5630
+ if (!hasProof) {
5631
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
5632
+ activity = await require_proof.signObject(activity, privateKey, keyId, {
5633
+ contextLoader,
5634
+ tracerProvider: this.tracerProvider
5635
+ });
5636
+ proofCreated = true;
5637
+ }
5400
5638
  }
5639
+ jsonLd = options.activityJsonLd != null ? require_proof.detachSignature(options.activityJsonLd) : await activity.toJsonLd({
5640
+ format: "compact",
5641
+ contextLoader
5642
+ });
5401
5643
  }
5402
- let jsonLd = await activity.toJsonLd({
5403
- format: "compact",
5404
- contextLoader
5405
- });
5406
- if (proofCreated || !hasProof || options.normalizeExistingProofs) jsonLd = await require_proof.normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
5644
+ if (prepared == null && (proofCreated || !hasProof || options.normalizeExistingProofs)) jsonLd = await require_proof.normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
5645
+ hasProof ||= proofCreated;
5407
5646
  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.", {
5408
5647
  activityId,
5409
5648
  keys: keys.map((pair) => ({
@@ -5440,20 +5679,28 @@ var FederationImpl = class extends FederationBuilderImpl {
5440
5679
  activity: jsonLd
5441
5680
  });
5442
5681
  const promises = [];
5443
- for (const inbox in inboxes) promises.push(sendActivity({
5444
- allowPrivateAddress: this.allowPrivateAddress,
5445
- keys,
5446
- activity: jsonLd,
5447
- activityId: activity.id?.href,
5448
- activityType: (0, _fedify_vocab.getTypeId)(activity).href,
5449
- inbox: new URL(inbox),
5450
- sharedInbox: inboxes[inbox].sharedInbox,
5451
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
5452
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
5453
- meterProvider: this.meterProvider,
5454
- tracerProvider: this.tracerProvider
5455
- }));
5456
- await Promise.all(promises);
5682
+ try {
5683
+ for (const inbox in inboxes) {
5684
+ const promise = sendActivity({
5685
+ allowPrivateAddress: this.allowPrivateAddress,
5686
+ keys,
5687
+ activity: jsonLd,
5688
+ activityId: activity.id?.href,
5689
+ activityType: (0, _fedify_vocab.getTypeId)(activity).href,
5690
+ inbox: new URL(inbox),
5691
+ sharedInbox: inboxes[inbox].sharedInbox,
5692
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
5693
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
5694
+ meterProvider: this.meterProvider,
5695
+ tracerProvider: this.tracerProvider
5696
+ });
5697
+ promise.catch(() => {});
5698
+ promises.push(promise);
5699
+ }
5700
+ await Promise.all(promises);
5701
+ } finally {
5702
+ await Promise.allSettled(promises);
5703
+ }
5457
5704
  return;
5458
5705
  }
5459
5706
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -5468,7 +5715,7 @@ var FederationImpl = class extends FederationBuilderImpl {
5468
5715
  privateKey: privateKeyJwk
5469
5716
  });
5470
5717
  }
5471
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
5718
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
5472
5719
  const carrier = {};
5473
5720
  _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), carrier);
5474
5721
  const messages = [];
@@ -5727,7 +5974,7 @@ var FederationImpl = class extends FederationBuilderImpl {
5727
5974
  const identity = await this.sharedInboxKeyDispatcher(context);
5728
5975
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
5729
5976
  }
5730
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
5977
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
5731
5978
  const inboxContextFactory = context.toInboxContext.bind(context);
5732
5979
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
5733
5980
  return await handleInbox(request, {
@@ -6117,6 +6364,8 @@ var ContextImpl = class ContextImpl {
6117
6364
  for (const keyPair of keyPairs) {
6118
6365
  const newPair = {
6119
6366
  ...keyPair,
6367
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(keyPair.privateKey),
6368
+ publicKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(keyPair.publicKey),
6120
6369
  cryptographicKey: new _fedify_vocab.CryptographicKey({
6121
6370
  id: keyPair.keyId,
6122
6371
  owner,
@@ -6193,10 +6442,16 @@ var ContextImpl = class ContextImpl {
6193
6442
  } else identifierPromise = Promise.resolve(identity.identifier);
6194
6443
  return identifierPromise.then((identifier) => {
6195
6444
  if (identifier == null) return this.documentLoader;
6196
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
6445
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
6446
+ keyId: pair.keyId,
6447
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(pair.privateKey)
6448
+ }));
6197
6449
  });
6198
6450
  }
6199
- return this.federation.authenticatedDocumentLoaderFactory(identity);
6451
+ return this.federation.authenticatedDocumentLoaderFactory({
6452
+ keyId: identity.keyId,
6453
+ privateKey: (0, _fedify_vocab_runtime_internal.asCryptoKey)(identity.privateKey)
6454
+ });
6200
6455
  }
6201
6456
  lookupObject(identifier, options = {}) {
6202
6457
  return (0, _fedify_vocab.lookupObject)(identifier, {
@@ -6220,10 +6475,14 @@ var ContextImpl = class ContextImpl {
6220
6475
  return options.parse === "none" ? require_types.getNodeInfo(url, {
6221
6476
  parse: "none",
6222
6477
  direct: options.direct,
6478
+ timeout: options.timeout,
6479
+ signal: options.signal,
6223
6480
  userAgent: options?.userAgent ?? this.federation.userAgent
6224
6481
  }) : require_types.getNodeInfo(url, {
6225
6482
  parse: options.parse,
6226
6483
  direct: options.direct,
6484
+ timeout: options.timeout,
6485
+ signal: options.signal,
6227
6486
  userAgent: options?.userAgent ?? this.federation.userAgent
6228
6487
  });
6229
6488
  }
@@ -6236,7 +6495,17 @@ var ContextImpl = class ContextImpl {
6236
6495
  allowPrivateAddress: this.federation.allowPrivateAddress
6237
6496
  });
6238
6497
  }
6239
- sendActivity(sender, recipients, activity, options = {}) {
6498
+ async sendActivity(sender, recipients, activity, options = {}) {
6499
+ let activityJsonLd = void 0;
6500
+ let hasProof = activity.proofIds.length > 0;
6501
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
6502
+ hasProof = true;
6503
+ break;
6504
+ }
6505
+ if (hasProof) {
6506
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
6507
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
6508
+ }
6240
6509
  return this.tracerProvider.getTracer(require_http.name, require_http.version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
6241
6510
  kind: this.federation.outboxQueue == null || options.immediate ? _opentelemetry_api.SpanKind.CLIENT : _opentelemetry_api.SpanKind.PRODUCER,
6242
6511
  attributes: {
@@ -6249,7 +6518,7 @@ var ContextImpl = class ContextImpl {
6249
6518
  }, async (span) => {
6250
6519
  try {
6251
6520
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
6252
- await this.sendActivityInternal(sender, recipients, activity, options, span);
6521
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
6253
6522
  } catch (e) {
6254
6523
  span.setStatus({
6255
6524
  code: _opentelemetry_api.SpanStatusCode.ERROR,
@@ -6261,7 +6530,7 @@ var ContextImpl = class ContextImpl {
6261
6530
  }
6262
6531
  });
6263
6532
  }
6264
- async sendActivityInternal(sender, recipients, activity, options, span) {
6533
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
6265
6534
  const logger = (0, _logtape_logtape.getLogger)([
6266
6535
  "fedify",
6267
6536
  "federation",
@@ -6308,15 +6577,23 @@ var ContextImpl = class ContextImpl {
6308
6577
  if (!(error instanceof _fedify_uri_template.RouterError)) throw error;
6309
6578
  }
6310
6579
  } else expandedRecipients = [recipients];
6311
- const opts = {
6312
- context: this,
6313
- orderingKey: options.orderingKey,
6314
- collectionSync,
6315
- immediate: options.immediate,
6316
- normalizeExistingProofs: options.normalizeExistingProofs
6317
- };
6318
6580
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
6319
6581
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
6582
+ let contextMatches = false;
6583
+ if (activityJsonLd != null) {
6584
+ const capturedJsonLd = activityJsonLd;
6585
+ const transformedJsonLd = await activity.toJsonLd({
6586
+ format: "compact",
6587
+ contextLoader: this.contextLoader
6588
+ });
6589
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
6590
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
6591
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
6592
+ if (contentChanged || !contextMatches && proofsChanged) {
6593
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) });
6594
+ activityJsonLd = void 0;
6595
+ } else if (proofsChanged) activityJsonLd = void 0;
6596
+ }
6320
6597
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
6321
6598
  if (activity.actorId == null) {
6322
6599
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -6328,15 +6605,42 @@ var ContextImpl = class ContextImpl {
6328
6605
  let proofCreated = false;
6329
6606
  if (actorKeyPairs != null) {
6330
6607
  const contextLoader = this.contextLoader;
6331
- for (const kp of actorKeyPairs) {
6332
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
6333
- activity = await require_proof.signObject(activity, kp.privateKey, kp.multikey.id, {
6334
- contextLoader,
6335
- tracerProvider: this.tracerProvider
6336
- });
6337
- proofCreated = true;
6608
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
6609
+ if (willSign) {
6610
+ if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
6611
+ }
6612
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
6613
+ if (prepared != null) {
6614
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
6615
+ privateKey: kp.privateKey,
6616
+ keyId: kp.multikey.id
6617
+ }] : []);
6618
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
6619
+ activity = signed.activity;
6620
+ activityJsonLd = signed.jsonLd;
6621
+ proofCreated = signingKeys.length > 0;
6622
+ } else {
6623
+ let proofAdded = false;
6624
+ for (const kp of actorKeyPairs) {
6625
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
6626
+ activity = await require_proof.signObject(activity, kp.privateKey, kp.multikey.id, {
6627
+ contextLoader,
6628
+ tracerProvider: this.tracerProvider
6629
+ });
6630
+ proofAdded = true;
6631
+ }
6632
+ if (proofAdded) activityJsonLd = void 0;
6633
+ proofCreated = proofAdded;
6338
6634
  }
6339
6635
  }
6636
+ const opts = {
6637
+ context: this,
6638
+ orderingKey: options.orderingKey,
6639
+ collectionSync,
6640
+ immediate: options.immediate,
6641
+ activityJsonLd,
6642
+ normalizeExistingProofs: options.normalizeExistingProofs
6643
+ };
6340
6644
  const inboxes = extractInboxes({
6341
6645
  recipients: expandedRecipients,
6342
6646
  preferSharedInbox: options.preferSharedInbox,
@@ -6376,7 +6680,7 @@ var ContextImpl = class ContextImpl {
6376
6680
  actorIds: [...actorIds],
6377
6681
  sharedInbox
6378
6682
  }])),
6379
- activity: await activity.toJsonLd({
6683
+ activity: activityJsonLd != null ? require_proof.detachSignature(activityJsonLd) : await activity.toJsonLd({
6380
6684
  format: "compact",
6381
6685
  contextLoader: this.contextLoader
6382
6686
  }),
@@ -6387,7 +6691,7 @@ var ContextImpl = class ContextImpl {
6387
6691
  normalizeExistingProofs: proofCreated || options.normalizeExistingProofs,
6388
6692
  traceContext: carrier
6389
6693
  };
6390
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
6694
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
6391
6695
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
6392
6696
  require_http.getFederationMetrics(this.federation.meterProvider).recordQueueTaskEnqueued({
6393
6697
  role: "fanout",
@@ -6723,7 +7027,7 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
6723
7027
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
6724
7028
  keys = forwarder;
6725
7029
  } else keys = [forwarder];
6726
- if (!require_proof.hasSignatureLike(ctx.activity)) {
7030
+ if (!require_proof.hasVerifiableSignature(ctx.activity) && !require_proof.hasSignatureLike(ctx.activity)) {
6727
7031
  if (!require_proof.hasProofLike(ctx.activity)) {
6728
7032
  if (options?.skipIfUnsigned) return false;
6729
7033
  logger.warn("The activity {activityId} is not signed; even if it is forwarded to other servers as is, it may not be accepted by them due to the lack of a signature/proof.", {
@@ -6761,26 +7065,34 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
6761
7065
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
6762
7066
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
6763
7067
  const promises = [];
6764
- for (const inbox in inboxes) promises.push(sendActivity({
6765
- allowPrivateAddress: ctx.federation.allowPrivateAddress,
6766
- keys,
6767
- activity: ctx.activity,
6768
- activityId: ctx.activityId,
6769
- activityType: ctx.activityType,
6770
- inbox: new URL(inbox),
6771
- sharedInbox: inboxes[inbox].sharedInbox,
6772
- meterProvider: ctx.meterProvider,
6773
- tracerProvider: ctx.tracerProvider,
6774
- specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
6775
- }));
6776
- await Promise.all(promises);
7068
+ try {
7069
+ for (const inbox in inboxes) {
7070
+ const promise = sendActivity({
7071
+ allowPrivateAddress: ctx.federation.allowPrivateAddress,
7072
+ keys,
7073
+ activity: ctx.activity,
7074
+ activityId: ctx.activityId,
7075
+ activityType: ctx.activityType,
7076
+ inbox: new URL(inbox),
7077
+ sharedInbox: inboxes[inbox].sharedInbox,
7078
+ meterProvider: ctx.meterProvider,
7079
+ tracerProvider: ctx.tracerProvider,
7080
+ specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
7081
+ });
7082
+ promise.catch(() => {});
7083
+ promises.push(promise);
7084
+ }
7085
+ await Promise.all(promises);
7086
+ } finally {
7087
+ await Promise.allSettled(promises);
7088
+ }
6777
7089
  return true;
6778
7090
  }
6779
7091
  logger.debug("Enqueuing activity {activityId} to forward later.", {
6780
7092
  activityId: ctx.activityId,
6781
7093
  activity: ctx.activity
6782
7094
  });
6783
- if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
7095
+ if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueAutomatically(ctx.data);
6784
7096
  const keyJwkPairs = [];
6785
7097
  for (const { keyId, privateKey } of keys) {
6786
7098
  const privateKeyJwk = await require_http.exportJwk(privateKey);
@@ -6957,6 +7269,69 @@ var KvSpecDeterminer = class {
6957
7269
  function notFound(_request) {
6958
7270
  return new Response("Not Found", { status: 404 });
6959
7271
  }
7272
+ function hasTopLevelProof(value) {
7273
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
7274
+ }
7275
+ function getContentFields(value) {
7276
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
7277
+ const record = { ...value };
7278
+ delete record["@context"];
7279
+ delete record.proof;
7280
+ delete record.signature;
7281
+ return JSON.stringify(sortJsonKeys(record));
7282
+ }
7283
+ function getContextFields(value) {
7284
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
7285
+ const context = value["@context"];
7286
+ return JSON.stringify(sortJsonKeys(context ?? null));
7287
+ }
7288
+ function getProofEntries(value) {
7289
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
7290
+ const proof = value.proof;
7291
+ if (proof == null) return [];
7292
+ return Array.isArray(proof) ? proof : [proof];
7293
+ }
7294
+ function normalizeProofEntry(proof) {
7295
+ const stripped = stripContexts(proof);
7296
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
7297
+ const record = { ...stripped };
7298
+ if (typeof record.created === "string") try {
7299
+ record.created = Temporal.Instant.from(record.created).toString();
7300
+ } catch {}
7301
+ return record;
7302
+ }
7303
+ function getProofEntryFields(proof) {
7304
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
7305
+ }
7306
+ function getProofFields(value) {
7307
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
7308
+ }
7309
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
7310
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
7311
+ const retainedProofs = [];
7312
+ for await (const proof of activity.getProofs({ contextLoader })) {
7313
+ const proofJsonLd = await proof.toJsonLd({
7314
+ format: "compact",
7315
+ contextLoader
7316
+ });
7317
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
7318
+ }
7319
+ return retainedProofs;
7320
+ }
7321
+ function stripContexts(value) {
7322
+ if (Array.isArray(value)) return value.map(stripContexts);
7323
+ if (typeof value !== "object" || value == null) return value;
7324
+ const record = { ...value };
7325
+ delete record["@context"];
7326
+ delete record.signature;
7327
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
7328
+ return record;
7329
+ }
7330
+ function sortJsonKeys(value) {
7331
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
7332
+ if (typeof value !== "object" || value == null) return value;
7333
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
7334
+ }
6960
7335
  function notAcceptable(_request) {
6961
7336
  return new Response("Not Acceptable", {
6962
7337
  status: 406,