@fedify/fedify 2.3.16-dev.2841 → 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-G4wSHQX-.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-DmDVx5sE.mjs → deno-FtdqgHJA.mjs} +1 -1
  17. package/dist/{docloader-0fjyUmvI.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-CKX94hfh.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-DCK-QQfE.mjs → http-D8tiOrZf.mjs} +7 -5
  43. package/dist/{http-DwIMsxu9.js → http-mLeLYFj-.js} +6 -4
  44. package/dist/{inbox-Bx6PCMeE.mjs → inbox-Dy8awbi8.mjs} +2 -2
  45. package/dist/{key-SkLDUmPM.mjs → key-o1SmN5s0.mjs} +4 -3
  46. package/dist/{kv-cache-BaJOO6O3.mjs → kv-cache-BwUrzCVO.mjs} +1 -1
  47. package/dist/{kv-cache-BnZ4KLMY.cjs → kv-cache-CI6Z0WiS.cjs} +1 -1
  48. package/dist/{kv-cache-xIexNacM.js → kv-cache-Dsq8C8D8.js} +1 -1
  49. package/dist/{ld-DUG6cq9q.mjs → ld-DCKrqj9y.mjs} +155 -22
  50. package/dist/ld-signature-Dgz_b89j.mjs +23 -0
  51. package/dist/{metrics-D3OnAgfj.mjs → metrics-CaoYRhNH.mjs} +1 -1
  52. package/dist/{middleware-CUwjLKp3.mjs → middleware-4p3opEMT.mjs} +1 -1
  53. package/dist/{middleware-C9RexCTx.cjs → middleware-CP-8P7kk.cjs} +492 -117
  54. package/dist/{middleware-DU2jy5eY.js → middleware-Cce0nLDw.js} +491 -117
  55. package/dist/{middleware-zEy-wJYI.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-Baf_LRb2.mjs → owner-Bdj0nHhf.mjs} +2 -2
  75. package/dist/{proof-CNGy7TJL.js → proof-B9XJiyz-.js} +1030 -858
  76. package/dist/{proof-BdAFbOFg.cjs → proof-CmcP8yqP.cjs} +1243 -1059
  77. package/dist/{proof-LTsbjXnQ.mjs → proof-DrbjYma9.mjs} +41 -16
  78. package/dist/{send-DOf5y1nB.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-fl4sM1Gs.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 +7 -7
  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,21 +2,23 @@ import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  import { t as __exportAll } from "./chunk-CRNNMoPX.js";
4
4
  import { r as getDefaultActivityTransformers } from "./transformers-BGMIq1cs.js";
5
- import { A as recordWebFingerHandle, C as recordCollectionRequest, D as recordInboxActivity, E as recordFanoutRecipients, I as name, L as version, M as formatAcceptSignature, O as recordOutboxActivity, S as recordCollectionPageItems, _ as instrumentDocumentLoader, a as verifyRequestDetailed, b as recordCircuitBreakerStateChange, d as importJwk, f as validateCryptoKey, g as getRemoteHost, h as getFederationMetrics, i as verifyRequest, j as registerQueueDepthGauge, k as recordOutboxEnqueue, m as getDurationMs, n as parseRfc9421SignatureInput, o as exportJwk, t as doubleKnockScoped, v as isAbortError, w as recordCollectionTotalItems, x as recordCollectionDispatchDuration } from "./http-DwIMsxu9.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 hasSignatureLike, b as signJsonLd, c as getKeyOwner, f as compactJsonLd, g as hasSignature, h as getNormalizationContextLoader, i as verifyObject, l as InvalidContextReferenceError, m as detachSignature, n as hasProofLike, o as normalizeOutgoingActivityJsonLd, r as signObject, s as doesActorOwnKey, u as assertSafeJsonLd, v as isClearlyMalformedContextReference, w as wrapContextLoaderForJsonLd, x as verifyCompactJsonLd, y as isInvalidUrlTypeError } from "./proof-CNGy7TJL.js";
8
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-xIexNacM.js";
5
+ import { A as recordWebFingerHandle, C as recordCollectionRequest, D as recordInboxActivity, E as recordFanoutRecipients, I as name, L as version, M as formatAcceptSignature, O as recordOutboxActivity, S as recordCollectionPageItems, _ as instrumentDocumentLoader, a as verifyRequestDetailed, b as recordCircuitBreakerStateChange, d as importJwk, f as validateCryptoKey, g as getRemoteHost, h as getFederationMetrics, i as verifyRequest, j as registerQueueDepthGauge, k as recordOutboxEnqueue, m as getDurationMs, n as parseRfc9421SignatureInput, o as exportJwk, t as doubleKnockScoped, v as isAbortError, w as recordCollectionTotalItems, x as recordCollectionDispatchDuration } from "./http-mLeLYFj-.js";
6
+ import { E as normalizeOutgoingActivityJsonLd, T as normalizeAttachmentArrays$1, _ as hasVerifiableSignature, b as signJsonLd, c as InvalidContextReferenceError, d as compactJsonLd, g as hasSignatureLike, h as getNormalizationContextLoader, i as verifyObject, l as assertSafeJsonLd, m as detachSignature, n as hasProofLike, o as doesActorOwnKey, p as describeSignatureShape, r as signObject, s as getKeyOwner, v as isClearlyMalformedContextReference, w as wrapContextLoaderForJsonLd, x as verifyCompactJsonLd, y as isInvalidUrlTypeError } from "./proof-B9XJiyz-.js";
7
+ import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-Dx_w2JSM.js";
8
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-Dsq8C8D8.js";
9
9
  import { getLogger, withContext } from "@logtape/logtape";
10
10
  import { Router, RouterError, assertPath } from "@fedify/uri-template";
11
- import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
11
+ import { Activity, Collection, CollectionPage, CryptographicKey, DataIntegrityProof, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
12
12
  import { SpanKind, SpanStatusCode, context, metrics, propagation, trace } from "@opentelemetry/api";
13
13
  import { encodeHex } from "byte-encodings/hex";
14
- import { FetchError, UrlError, getDocumentLoader } from "@fedify/vocab-runtime";
14
+ import { FetchError, UrlError, encodeMultibase, getDocumentLoader } from "@fedify/vocab-runtime";
15
+ import jsonld from "@fedify/vocab-runtime/jsonld";
15
16
  import { uniq } from "es-toolkit";
17
+ import { asCryptoKey, openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
16
18
  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";
17
- import jsonld from "@fedify/vocab-runtime/jsonld";
19
+ import serialize from "json-canon";
20
+ import { normalizeDateTimeLiteral } from "@fedify/vocab-runtime/temporal";
18
21
  import { lookupWebFinger } from "@fedify/webfinger";
19
- import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
20
22
  import { DataPointType, MeterProvider as MeterProvider$1, MetricReader } from "@opentelemetry/sdk-metrics";
21
23
  import { domainToASCII } from "node:url";
22
24
  //#region src/federation/activity-listener.ts
@@ -1263,6 +1265,17 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
1263
1265
  return `collectionId="${collectionId}", url="${url}", digest="${encodeHex(await digest(actorIds))}"`;
1264
1266
  }
1265
1267
  //#endregion
1268
+ //#region src/compat/attachment-arrays.ts
1269
+ /**
1270
+ * Applies the shared attachment workaround to served documents without
1271
+ * rewriting any document that contains a semantic proof or LD signature.
1272
+ * RDF equivalence alone cannot preserve JCS signatures.
1273
+ * @internal
1274
+ */
1275
+ function normalizeAttachmentArrays(document, contextLoader) {
1276
+ return normalizeAttachmentArrays$1(document, contextLoader, true);
1277
+ }
1278
+ //#endregion
1266
1279
  //#region src/federation/inbox.ts
1267
1280
  /**
1268
1281
  * Checks whether an activity's ID and all of its actor IDs have the same
@@ -1650,9 +1663,6 @@ function acceptsJsonLd(request) {
1650
1663
  function isPlainObject(value) {
1651
1664
  return typeof value === "object" && value != null && !Array.isArray(value);
1652
1665
  }
1653
- function normalizeDateTimeLiteral(value) {
1654
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1655
- }
1656
1666
  function isMalformedDateTimeLiteral(value) {
1657
1667
  if (typeof value !== "string") return false;
1658
1668
  try {
@@ -1694,7 +1704,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1694
1704
  if (typeof literal === "boolean") return false;
1695
1705
  if (typeof literal !== "string") return false;
1696
1706
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1697
- if (new Date(literal).toString() === "Invalid Date") return false;
1707
+ if (new Date(literal).toString() === "Invalid Date" && new Date(normalizeDateTimeLiteral(literal)).toString() === "Invalid Date") return false;
1698
1708
  return isMalformedDateTimeLiteral(literal);
1699
1709
  }
1700
1710
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1789,7 +1799,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1789
1799
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1790
1800
  }
1791
1801
  if (actor instanceof Tombstone) {
1792
- const jsonLd = await actor.toJsonLd(context);
1802
+ const jsonLd = await serializeForResponse(actor, context);
1793
1803
  return new Response(JSON.stringify(jsonLd), {
1794
1804
  status: 410,
1795
1805
  headers: {
@@ -1798,7 +1808,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1798
1808
  }
1799
1809
  });
1800
1810
  }
1801
- const jsonLd = await actor.toJsonLd(context);
1811
+ const jsonLd = await serializeForResponse(actor, context);
1802
1812
  return new Response(JSON.stringify(jsonLd), { headers: {
1803
1813
  "Content-Type": "application/activity+json",
1804
1814
  Vary: "Accept"
@@ -1818,7 +1828,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1818
1828
  if (authorizePredicate != null) {
1819
1829
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1820
1830
  }
1821
- const jsonLd = await object.toJsonLd(context);
1831
+ const jsonLd = await serializeForResponse(object, context);
1822
1832
  return new Response(JSON.stringify(jsonLd), { headers: {
1823
1833
  "Content-Type": "application/activity+json",
1824
1834
  Vary: "Accept"
@@ -1861,13 +1871,13 @@ function recordCollectionMetrics(meterProvider, base, result, options = {}) {
1861
1871
  * @param parameters The parameters for handling the collection.
1862
1872
  * @returns A promise that resolves to an HTTP response.
1863
1873
  */
1864
- async function handleCollection(request, { name: name$1, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
1865
- const spanName = name$1.trim().replace(/\s+/g, "_");
1874
+ async function handleCollection(request, { name: name$2, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
1875
+ const spanName = name$2.trim().replace(/\s+/g, "_");
1866
1876
  tracerProvider = tracerProvider ?? trace.getTracerProvider();
1867
1877
  const tracer = tracerProvider.getTracer(name, version);
1868
1878
  const cursor = new URL(request.url).searchParams.get("cursor");
1869
1879
  const metricBase = {
1870
- kind: getCollectionMetricKind(name$1),
1880
+ kind: getCollectionMetricKind(name$2),
1871
1881
  page: cursor != null,
1872
1882
  dispatcher: "built_in"
1873
1883
  };
@@ -1908,7 +1918,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1908
1918
  span.setStatus({ code: SpanStatusCode.ERROR });
1909
1919
  return await onNotFound(request);
1910
1920
  }
1911
- const items = filterCollectionItems(page.items, name$1, filterPredicate);
1921
+ const items = filterCollectionItems(page.items, name$2, filterPredicate);
1912
1922
  itemCount = items.length;
1913
1923
  span.setAttribute("fedify.collection.items", itemCount);
1914
1924
  return items;
@@ -1948,7 +1958,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1948
1958
  } else {
1949
1959
  const uri = new URL(baseUri);
1950
1960
  uri.searchParams.set("cursor", cursor);
1951
- const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$1}`, {
1961
+ const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$2}`, {
1952
1962
  kind: SpanKind.SERVER,
1953
1963
  attributes: {
1954
1964
  "activitypub.collection.id": uri.href,
@@ -1964,7 +1974,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1964
1974
  span.setStatus({ code: SpanStatusCode.ERROR });
1965
1975
  return await onNotFound(request);
1966
1976
  }
1967
- const items = filterCollectionItems(page.items, name$1, filterPredicate);
1977
+ const items = filterCollectionItems(page.items, name$2, filterPredicate);
1968
1978
  itemCount = items.length;
1969
1979
  span.setAttribute("fedify.collection.items", itemCount);
1970
1980
  return {
@@ -2007,7 +2017,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
2007
2017
  if (collectionCallbacks.authorizePredicate != null) {
2008
2018
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return finish(await onUnauthorized(request), "unauthorized");
2009
2019
  }
2010
- const jsonLd = await collection.toJsonLd(context);
2020
+ const jsonLd = await serializeForResponse(collection, context);
2011
2021
  return finish(new Response(JSON.stringify(jsonLd), { headers: {
2012
2022
  "Content-Type": "application/activity+json",
2013
2023
  Vary: "Accept"
@@ -2364,7 +2374,11 @@ async function handleInboxInternal(request, parameters, span) {
2364
2374
  }
2365
2375
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
2366
2376
  const jsonWithoutSig = detachSignature(json);
2367
- const hasLdSignature = hasSignature(json);
2377
+ const hasLdSignature = hasVerifiableSignature(json);
2378
+ if (!hasLdSignature) {
2379
+ const shape = describeSignatureShape(json);
2380
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
2381
+ }
2368
2382
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
2369
2383
  let deferredLdSignatureError = void 0;
2370
2384
  const respondInvalidActivity = async (error) => {
@@ -2870,8 +2884,8 @@ var CustomCollectionHandler = class {
2870
2884
  * @param CollectionPage The CollectionPage constructor.
2871
2885
  * @param filterPredicate Optional filter predicate for items.
2872
2886
  */
2873
- constructor(name$2, values, context, callbacks, tracerProvider = trace.getTracerProvider(), meterProvider, Collection, CollectionPage, filterPredicate) {
2874
- this.name = name$2;
2887
+ constructor(name$1, values, context, callbacks, tracerProvider = trace.getTracerProvider(), meterProvider, Collection, CollectionPage, filterPredicate) {
2888
+ this.name = name$1;
2875
2889
  this.values = values;
2876
2890
  this.context = context;
2877
2891
  this.callbacks = callbacks;
@@ -2890,7 +2904,7 @@ var CustomCollectionHandler = class {
2890
2904
  * @returns A promise that resolves to the JSON-LD representation.
2891
2905
  */
2892
2906
  async toJsonLd() {
2893
- return (await this.collection).toJsonLd(this.context);
2907
+ return serializeForResponse(await this.collection, this.context);
2894
2908
  }
2895
2909
  /**
2896
2910
  * Fetches the collection with optional cursor for pagination.
@@ -3267,7 +3281,7 @@ var UnauthorizedError = class extends HandlerError {
3267
3281
  * @since 0.3.0
3268
3282
  */
3269
3283
  async function respondWithObject(object, options) {
3270
- const jsonLd = await object.toJsonLd(options);
3284
+ const jsonLd = await serializeForResponse(object, options);
3271
3285
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
3272
3286
  }
3273
3287
  /**
@@ -3355,6 +3369,106 @@ const MIN_COMPONENTS = [
3355
3369
  "@target-uri",
3356
3370
  "@authority"
3357
3371
  ];
3372
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
3373
+ async function serializeForResponse(object, options) {
3374
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
3375
+ }
3376
+ //#endregion
3377
+ //#region src/sig/proof-creation.ts
3378
+ /** Signs the exact serialized message supplied by an internal producer. */
3379
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
3380
+ validateCryptoKey(privateKey, "private");
3381
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
3382
+ const encoder = new TextEncoder();
3383
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(jsonLd)));
3384
+ created ??= Temporal.Now.instant();
3385
+ const proofConfig = {
3386
+ "@context": jsonLd["@context"],
3387
+ type: "DataIntegrityProof",
3388
+ cryptosuite: "eddsa-jcs-2022",
3389
+ verificationMethod: keyId.href,
3390
+ proofPurpose: "assertionMethod",
3391
+ created: created.toString()
3392
+ };
3393
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(proofConfig)));
3394
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
3395
+ digest.set(new Uint8Array(proofDigest), 0);
3396
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
3397
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
3398
+ return new DataIntegrityProof({
3399
+ cryptosuite: "eddsa-jcs-2022",
3400
+ verificationMethod: keyId,
3401
+ proofPurpose: "assertionMethod",
3402
+ created,
3403
+ proofValue: new Uint8Array(sig)
3404
+ });
3405
+ }
3406
+ //#endregion
3407
+ //#region src/compat/delivery-jsonld.ts
3408
+ /**
3409
+ * Returns changed wire JSON only; unchanged documents keep the existing
3410
+ * delivery signing path. This uses ordinary vocabulary serialization, without
3411
+ * retaining or repairing independently signed child representations.
3412
+ */
3413
+ async function prepareActivityJsonLd(activity, contextLoader) {
3414
+ if (activity.proofIds.length > 0) return void 0;
3415
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
3416
+ const source = await activity.clone().toJsonLd({
3417
+ format: "compact",
3418
+ contextLoader
3419
+ });
3420
+ const prepared = await normalizeOutgoingActivityJsonLd(source, contextLoader, true);
3421
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
3422
+ }
3423
+ /** Signs a changed, proof-free delivery map without serializing it again. */
3424
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
3425
+ const proofs = [];
3426
+ const serializedProofs = [];
3427
+ const tracer = (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version);
3428
+ for (const { privateKey, keyId } of keys) {
3429
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(activity).href } }, async (span) => {
3430
+ try {
3431
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
3432
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
3433
+ if (span.isRecording()) {
3434
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
3435
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
3436
+ span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
3437
+ }
3438
+ return proof;
3439
+ } catch (error) {
3440
+ span.setStatus({
3441
+ code: SpanStatusCode.ERROR,
3442
+ message: String(error)
3443
+ });
3444
+ throw error;
3445
+ } finally {
3446
+ span.end();
3447
+ }
3448
+ });
3449
+ proofs.push(proof);
3450
+ serializedProofs.push({
3451
+ "@context": unsigned["@context"],
3452
+ type: "DataIntegrityProof",
3453
+ cryptosuite: proof.cryptosuite,
3454
+ verificationMethod: keyId.href,
3455
+ proofPurpose: "assertionMethod",
3456
+ created: proof.created.toString(),
3457
+ proofValue: new TextDecoder().decode(encodeMultibase("base58btc", proof.proofValue))
3458
+ });
3459
+ }
3460
+ if (proofs.length === 0) return {
3461
+ activity,
3462
+ jsonLd: unsigned
3463
+ };
3464
+ return {
3465
+ activity: activity.clone({ proofs }),
3466
+ jsonLd: {
3467
+ ...unsigned,
3468
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
3469
+ }
3470
+ };
3471
+ }
3358
3472
  //#endregion
3359
3473
  //#region src/nodeinfo/handler.ts
3360
3474
  /**
@@ -3424,7 +3538,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
3424
3538
  * @param parameters The parameters for sending the activity.
3425
3539
  * See also {@link SendActivityParameters}.
3426
3540
  * @param deps The dependencies, for tests.
3427
- * @throws {Error} If the activity fails to send.
3541
+ * @throws {FetchError} If the delivery times out before receiving a response.
3542
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
3428
3543
  */
3429
3544
  function sendActivity(options, deps = {}) {
3430
3545
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
@@ -3451,6 +3566,24 @@ function sendActivity(options, deps = {}) {
3451
3566
  });
3452
3567
  }
3453
3568
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
3569
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
3570
+ function raceWithAbort(promise, signal) {
3571
+ if (signal.aborted) return Promise.reject(signal.reason);
3572
+ return new Promise((resolve, reject) => {
3573
+ const onAbort = () => {
3574
+ signal.removeEventListener("abort", onAbort);
3575
+ reject(signal.reason);
3576
+ };
3577
+ signal.addEventListener("abort", onAbort, { once: true });
3578
+ promise.then((value) => {
3579
+ signal.removeEventListener("abort", onAbort);
3580
+ resolve(value);
3581
+ }, (error) => {
3582
+ signal.removeEventListener("abort", onAbort);
3583
+ reject(error);
3584
+ });
3585
+ });
3586
+ }
3454
3587
  function getActivityActorId(activity) {
3455
3588
  if (!isRecord(activity)) return void 0;
3456
3589
  return getIdValue(activity.actor);
@@ -3470,7 +3603,7 @@ function getIdValue(value) {
3470
3603
  function isRecord(value) {
3471
3604
  return typeof value === "object" && value != null;
3472
3605
  }
3473
- async function readLimitedResponseBody(response, maxBytes) {
3606
+ async function readLimitedResponseBody(response, maxBytes, signal) {
3474
3607
  if (response.body == null) return "";
3475
3608
  const reader = response.body.getReader();
3476
3609
  const decoder = new TextDecoder();
@@ -3479,7 +3612,8 @@ async function readLimitedResponseBody(response, maxBytes) {
3479
3612
  let truncated = false;
3480
3613
  try {
3481
3614
  while (true) {
3482
- const { done, value } = await reader.read();
3615
+ signal.throwIfAborted();
3616
+ const { done, value } = await raceWithAbort(reader.read(), signal);
3483
3617
  if (done) break;
3484
3618
  if (totalBytes + value.length > maxBytes) {
3485
3619
  const remaining = maxBytes - totalBytes;
@@ -3491,8 +3625,10 @@ async function readLimitedResponseBody(response, maxBytes) {
3491
3625
  totalBytes += value.length;
3492
3626
  }
3493
3627
  } finally {
3494
- if (truncated) reader.cancel().catch(() => {});
3495
- reader.releaseLock();
3628
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
3629
+ try {
3630
+ reader.releaseLock();
3631
+ } catch (_) {}
3496
3632
  }
3497
3633
  let result = chunks.join("");
3498
3634
  if (truncated) result += "… (truncated)";
@@ -3507,11 +3643,30 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3507
3643
  const federationMetrics = getFederationMetrics(meterProvider);
3508
3644
  const started = performance.now();
3509
3645
  let deliverySuccess = false;
3510
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url));
3646
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
3647
+ const controller = new AbortController();
3648
+ const { signal } = controller;
3649
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
3650
+ function timeoutFailure(error) {
3651
+ if (!signal.aborted || error instanceof SendActivityError) return error;
3652
+ const failure = new FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
3653
+ failure.cause = signal.reason;
3654
+ return failure;
3655
+ }
3656
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url, { signal }));
3511
3657
  async function openHop(url) {
3512
3658
  let session;
3513
3659
  try {
3514
- session = await openUnvalidatedHop(url);
3660
+ signal.throwIfAborted();
3661
+ const opening = openUnvalidatedHop(url);
3662
+ opening.then((lateSession) => {
3663
+ if (signal.aborted) closeAfterError(lateSession, logger);
3664
+ }, () => {});
3665
+ session = await raceWithAbort(opening, signal);
3666
+ if (signal.aborted) {
3667
+ closeAfterError(session, logger);
3668
+ signal.throwIfAborted();
3669
+ }
3515
3670
  } catch (error) {
3516
3671
  if (error instanceof UrlError && error.reason === "dns") {
3517
3672
  logger.error("DNS resolution failed for URL: {url}", {
@@ -3534,8 +3689,15 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3534
3689
  try {
3535
3690
  initialSession = await openHop(inbox.href);
3536
3691
  } catch (error) {
3537
- if (error instanceof FetchError) federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
3538
- throw error;
3692
+ const failure = timeoutFailure(error);
3693
+ if (failure instanceof FetchError) federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
3694
+ if (signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
3695
+ activityId,
3696
+ inbox: inbox.href,
3697
+ error: failure
3698
+ });
3699
+ clearTimeout(timer);
3700
+ throw failure;
3539
3701
  }
3540
3702
  let initialPending = true;
3541
3703
  const openDeliveryHop = (url) => {
@@ -3552,7 +3714,8 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3552
3714
  method: "POST",
3553
3715
  headers,
3554
3716
  body: JSON.stringify(activity),
3555
- redirect: "manual"
3717
+ redirect: "manual",
3718
+ signal
3556
3719
  });
3557
3720
  let rsaKey = null;
3558
3721
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -3567,13 +3730,35 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3567
3730
  }))
3568
3731
  });
3569
3732
  let outcome;
3733
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
3734
+ determineSpec(origin) {
3735
+ signal.throwIfAborted();
3736
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
3737
+ },
3738
+ rememberSpec(origin, spec) {
3739
+ if (signal.aborted) return;
3740
+ try {
3741
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
3742
+ origin,
3743
+ error
3744
+ }));
3745
+ } catch (error) {
3746
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
3747
+ origin,
3748
+ error
3749
+ });
3750
+ }
3751
+ }
3752
+ };
3570
3753
  try {
3571
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox)) : await doubleKnockScoped(request, rsaKey, {
3754
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await doubleKnockScoped(request, rsaKey, {
3572
3755
  tracerProvider,
3573
- specDeterminer
3574
- }, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox));
3756
+ specDeterminer: boundedSpecDeterminer,
3757
+ signal
3758
+ }, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox, signal));
3575
3759
  } catch (error) {
3576
- const failure = error instanceof FetchError || error instanceof UrlError ? error : createFetchError(inbox.href, error);
3760
+ const boundedError = timeoutFailure(error);
3761
+ const failure = boundedError instanceof FetchError || boundedError instanceof UrlError ? boundedError : createFetchError(inbox.href, boundedError);
3577
3762
  logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
3578
3763
  activityId,
3579
3764
  inbox: inbox.href,
@@ -3607,6 +3792,7 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
3607
3792
  federationMetrics.recordDelivery(inbox, getDurationMs(started), deliverySuccess, activityType);
3608
3793
  }
3609
3794
  } finally {
3795
+ clearTimeout(timer);
3610
3796
  if (initialPending) await initialSession.close();
3611
3797
  }
3612
3798
  }
@@ -3638,17 +3824,18 @@ function cancelResponseBody(response, url) {
3638
3824
  * session is open: the body of a successful response is cancelled, and at
3639
3825
  * most 1 KiB of an error response body is read.
3640
3826
  */
3641
- async function consumeSendActivityResponse(response, inbox) {
3827
+ async function consumeSendActivityResponse(response, inbox, signal) {
3642
3828
  if (response.ok) {
3643
3829
  cancelResponseBody(response, response.url || inbox.href);
3644
3830
  return { ok: true };
3645
3831
  }
3646
3832
  let error;
3647
3833
  try {
3648
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
3834
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
3649
3835
  } catch (_) {
3650
3836
  error = "";
3651
3837
  }
3838
+ if (signal.aborted) error = "(timed out reading response body)";
3652
3839
  return {
3653
3840
  ok: false,
3654
3841
  status: response.status,
@@ -3668,7 +3855,7 @@ async function consumeSendActivityResponse(response, inbox) {
3668
3855
  * @param consume The function to consume the final response.
3669
3856
  * @returns The value returned by `consume`.
3670
3857
  */
3671
- async function fetchWithValidatedRedirects(request, openHop, consume) {
3858
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
3672
3859
  const logger = getLogger([
3673
3860
  "fedify",
3674
3861
  "federation",
@@ -3676,10 +3863,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
3676
3863
  ]);
3677
3864
  let body = await request.clone().text();
3678
3865
  for (let redirects = 0;; redirects++) {
3866
+ signal?.throwIfAborted();
3679
3867
  const session = await openHop(request.url);
3680
3868
  let response;
3681
3869
  try {
3682
- response = await session.fetch(request, { redirect: "manual" });
3870
+ response = await session.fetch(request, {
3871
+ redirect: "manual",
3872
+ signal
3873
+ });
3683
3874
  } catch (error) {
3684
3875
  await closeAfterError(session, logger);
3685
3876
  throw error;
@@ -3729,7 +3920,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
3729
3920
  method,
3730
3921
  headers,
3731
3922
  body,
3732
- redirect: "manual"
3923
+ redirect: "manual",
3924
+ signal: signal ?? request.signal
3733
3925
  });
3734
3926
  }
3735
3927
  }
@@ -4584,8 +4776,25 @@ var FederationImpl = class extends FederationBuilderImpl {
4584
4776
  _getTracer() {
4585
4777
  return this.tracerProvider.getTracer(name, version);
4586
4778
  }
4779
+ /**
4780
+ * Starts listening on a queue, converting a synchronous throw into
4781
+ * a rejected promise.
4782
+ *
4783
+ * `MessageQueue.listen()` is documented to never reject, but some
4784
+ * implementations (e.g., `WorkersMessageQueue`) throw synchronously. Without
4785
+ * this normalization, one such throw aborts {@link _startQueueInternal} while
4786
+ * it is still collecting listener promises, so listeners started earlier are
4787
+ * never awaited and later queues are never started.
4788
+ */
4789
+ #listenQueue(queue, ctxData, signal) {
4790
+ try {
4791
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
4792
+ } catch (error) {
4793
+ return Promise.reject(error);
4794
+ }
4795
+ }
4587
4796
  async _startQueueInternal(ctxData, signal, queue) {
4588
- if (this.inboxQueue == null && this.outboxQueue == null) return;
4797
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
4589
4798
  const logger = getLogger([
4590
4799
  "fedify",
4591
4800
  "federation",
@@ -4595,20 +4804,38 @@ var FederationImpl = class extends FederationBuilderImpl {
4595
4804
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
4596
4805
  logger.debug("Starting an inbox task worker.");
4597
4806
  this.inboxQueueStarted = true;
4598
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
4807
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
4599
4808
  }
4600
4809
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
4601
4810
  logger.debug("Starting an outbox task worker.");
4602
4811
  this.outboxQueueStarted = true;
4603
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
4812
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
4604
4813
  }
4605
4814
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
4606
4815
  logger.debug("Starting a fanout task worker.");
4607
4816
  this.fanoutQueueStarted = true;
4608
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
4817
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
4609
4818
  }
4610
4819
  await Promise.all(promises);
4611
4820
  }
4821
+ /**
4822
+ * Starts the queue workers automatically, reporting a failure instead of
4823
+ * leaving the returned promise unobserved.
4824
+ *
4825
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
4826
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
4827
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
4828
+ * callers that start workers deliberately.
4829
+ */
4830
+ _startQueueAutomatically(ctxData) {
4831
+ this._startQueueInternal(ctxData).catch((error) => {
4832
+ getLogger([
4833
+ "fedify",
4834
+ "federation",
4835
+ "queue"
4836
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
4837
+ });
4838
+ }
4612
4839
  processQueuedTask(contextData, message) {
4613
4840
  const tracer = this._getTracer();
4614
4841
  const extractedContext = propagation.extract(context.active(), message.traceContext);
@@ -4763,7 +4990,8 @@ var FederationImpl = class extends FederationBuilderImpl {
4763
4990
  collectionSync: message.collectionSync,
4764
4991
  orderingKey: message.orderingKey,
4765
4992
  normalizeExistingProofs: message.normalizeExistingProofs,
4766
- context
4993
+ context,
4994
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
4767
4995
  });
4768
4996
  }
4769
4997
  async #listenOutboxMessage(_, message, span) {
@@ -5176,7 +5404,7 @@ var FederationImpl = class extends FederationBuilderImpl {
5176
5404
  let parseInput = void 0;
5177
5405
  let parseContextLoader = context.contextLoader;
5178
5406
  try {
5179
- const hasSignatureField = hasSignature(message.activity);
5407
+ const hasSignatureField = hasVerifiableSignature(message.activity);
5180
5408
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
5181
5409
  const parseContext = hasSignatureField ? {
5182
5410
  ...context,
@@ -5388,21 +5616,31 @@ var FederationImpl = class extends FederationBuilderImpl {
5388
5616
  hasProof = true;
5389
5617
  break;
5390
5618
  }
5391
- if (!hasProof) {
5392
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
5393
- activity = await signObject(activity, privateKey, keyId, {
5394
- contextLoader,
5395
- tracerProvider: this.tracerProvider
5396
- });
5397
- hasProof = true;
5398
- proofCreated = true;
5619
+ const prepared = !hasProof && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
5620
+ let jsonLd;
5621
+ if (prepared != null) {
5622
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
5623
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
5624
+ activity = signed.activity;
5625
+ jsonLd = signed.jsonLd;
5626
+ proofCreated = signingKeys.length > 0;
5627
+ } else {
5628
+ if (!hasProof) {
5629
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
5630
+ activity = await signObject(activity, privateKey, keyId, {
5631
+ contextLoader,
5632
+ tracerProvider: this.tracerProvider
5633
+ });
5634
+ proofCreated = true;
5635
+ }
5399
5636
  }
5637
+ jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
5638
+ format: "compact",
5639
+ contextLoader
5640
+ });
5400
5641
  }
5401
- let jsonLd = await activity.toJsonLd({
5402
- format: "compact",
5403
- contextLoader
5404
- });
5405
- if (proofCreated || !hasProof || options.normalizeExistingProofs) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
5642
+ if (prepared == null && (proofCreated || !hasProof || options.normalizeExistingProofs)) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
5643
+ hasProof ||= proofCreated;
5406
5644
  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.", {
5407
5645
  activityId,
5408
5646
  keys: keys.map((pair) => ({
@@ -5439,20 +5677,28 @@ var FederationImpl = class extends FederationBuilderImpl {
5439
5677
  activity: jsonLd
5440
5678
  });
5441
5679
  const promises = [];
5442
- for (const inbox in inboxes) promises.push(sendActivity({
5443
- allowPrivateAddress: this.allowPrivateAddress,
5444
- keys,
5445
- activity: jsonLd,
5446
- activityId: activity.id?.href,
5447
- activityType: getTypeId(activity).href,
5448
- inbox: new URL(inbox),
5449
- sharedInbox: inboxes[inbox].sharedInbox,
5450
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
5451
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
5452
- meterProvider: this.meterProvider,
5453
- tracerProvider: this.tracerProvider
5454
- }));
5455
- await Promise.all(promises);
5680
+ try {
5681
+ for (const inbox in inboxes) {
5682
+ const promise = sendActivity({
5683
+ allowPrivateAddress: this.allowPrivateAddress,
5684
+ keys,
5685
+ activity: jsonLd,
5686
+ activityId: activity.id?.href,
5687
+ activityType: getTypeId(activity).href,
5688
+ inbox: new URL(inbox),
5689
+ sharedInbox: inboxes[inbox].sharedInbox,
5690
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
5691
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
5692
+ meterProvider: this.meterProvider,
5693
+ tracerProvider: this.tracerProvider
5694
+ });
5695
+ promise.catch(() => {});
5696
+ promises.push(promise);
5697
+ }
5698
+ await Promise.all(promises);
5699
+ } finally {
5700
+ await Promise.allSettled(promises);
5701
+ }
5456
5702
  return;
5457
5703
  }
5458
5704
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -5467,7 +5713,7 @@ var FederationImpl = class extends FederationBuilderImpl {
5467
5713
  privateKey: privateKeyJwk
5468
5714
  });
5469
5715
  }
5470
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
5716
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
5471
5717
  const carrier = {};
5472
5718
  propagation.inject(context.active(), carrier);
5473
5719
  const messages = [];
@@ -5726,7 +5972,7 @@ var FederationImpl = class extends FederationBuilderImpl {
5726
5972
  const identity = await this.sharedInboxKeyDispatcher(context);
5727
5973
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
5728
5974
  }
5729
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
5975
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
5730
5976
  const inboxContextFactory = context.toInboxContext.bind(context);
5731
5977
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
5732
5978
  return await handleInbox(request, {
@@ -6116,6 +6362,8 @@ var ContextImpl = class ContextImpl {
6116
6362
  for (const keyPair of keyPairs) {
6117
6363
  const newPair = {
6118
6364
  ...keyPair,
6365
+ privateKey: asCryptoKey(keyPair.privateKey),
6366
+ publicKey: asCryptoKey(keyPair.publicKey),
6119
6367
  cryptographicKey: new CryptographicKey({
6120
6368
  id: keyPair.keyId,
6121
6369
  owner,
@@ -6192,10 +6440,16 @@ var ContextImpl = class ContextImpl {
6192
6440
  } else identifierPromise = Promise.resolve(identity.identifier);
6193
6441
  return identifierPromise.then((identifier) => {
6194
6442
  if (identifier == null) return this.documentLoader;
6195
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
6443
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
6444
+ keyId: pair.keyId,
6445
+ privateKey: asCryptoKey(pair.privateKey)
6446
+ }));
6196
6447
  });
6197
6448
  }
6198
- return this.federation.authenticatedDocumentLoaderFactory(identity);
6449
+ return this.federation.authenticatedDocumentLoaderFactory({
6450
+ keyId: identity.keyId,
6451
+ privateKey: asCryptoKey(identity.privateKey)
6452
+ });
6199
6453
  }
6200
6454
  lookupObject(identifier, options = {}) {
6201
6455
  return lookupObject(identifier, {
@@ -6219,10 +6473,14 @@ var ContextImpl = class ContextImpl {
6219
6473
  return options.parse === "none" ? getNodeInfo(url, {
6220
6474
  parse: "none",
6221
6475
  direct: options.direct,
6476
+ timeout: options.timeout,
6477
+ signal: options.signal,
6222
6478
  userAgent: options?.userAgent ?? this.federation.userAgent
6223
6479
  }) : getNodeInfo(url, {
6224
6480
  parse: options.parse,
6225
6481
  direct: options.direct,
6482
+ timeout: options.timeout,
6483
+ signal: options.signal,
6226
6484
  userAgent: options?.userAgent ?? this.federation.userAgent
6227
6485
  });
6228
6486
  }
@@ -6235,7 +6493,17 @@ var ContextImpl = class ContextImpl {
6235
6493
  allowPrivateAddress: this.federation.allowPrivateAddress
6236
6494
  });
6237
6495
  }
6238
- sendActivity(sender, recipients, activity, options = {}) {
6496
+ async sendActivity(sender, recipients, activity, options = {}) {
6497
+ let activityJsonLd = void 0;
6498
+ let hasProof = activity.proofIds.length > 0;
6499
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
6500
+ hasProof = true;
6501
+ break;
6502
+ }
6503
+ if (hasProof) {
6504
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
6505
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
6506
+ }
6239
6507
  return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
6240
6508
  kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
6241
6509
  attributes: {
@@ -6248,7 +6516,7 @@ var ContextImpl = class ContextImpl {
6248
6516
  }, async (span) => {
6249
6517
  try {
6250
6518
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
6251
- await this.sendActivityInternal(sender, recipients, activity, options, span);
6519
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
6252
6520
  } catch (e) {
6253
6521
  span.setStatus({
6254
6522
  code: SpanStatusCode.ERROR,
@@ -6260,7 +6528,7 @@ var ContextImpl = class ContextImpl {
6260
6528
  }
6261
6529
  });
6262
6530
  }
6263
- async sendActivityInternal(sender, recipients, activity, options, span) {
6531
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
6264
6532
  const logger = getLogger([
6265
6533
  "fedify",
6266
6534
  "federation",
@@ -6307,15 +6575,23 @@ var ContextImpl = class ContextImpl {
6307
6575
  if (!(error instanceof RouterError)) throw error;
6308
6576
  }
6309
6577
  } else expandedRecipients = [recipients];
6310
- const opts = {
6311
- context: this,
6312
- orderingKey: options.orderingKey,
6313
- collectionSync,
6314
- immediate: options.immediate,
6315
- normalizeExistingProofs: options.normalizeExistingProofs
6316
- };
6317
6578
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
6318
6579
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
6580
+ let contextMatches = false;
6581
+ if (activityJsonLd != null) {
6582
+ const capturedJsonLd = activityJsonLd;
6583
+ const transformedJsonLd = await activity.toJsonLd({
6584
+ format: "compact",
6585
+ contextLoader: this.contextLoader
6586
+ });
6587
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
6588
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
6589
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
6590
+ if (contentChanged || !contextMatches && proofsChanged) {
6591
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) });
6592
+ activityJsonLd = void 0;
6593
+ } else if (proofsChanged) activityJsonLd = void 0;
6594
+ }
6319
6595
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
6320
6596
  if (activity.actorId == null) {
6321
6597
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -6327,15 +6603,42 @@ var ContextImpl = class ContextImpl {
6327
6603
  let proofCreated = false;
6328
6604
  if (actorKeyPairs != null) {
6329
6605
  const contextLoader = this.contextLoader;
6330
- for (const kp of actorKeyPairs) {
6331
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
6332
- activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
6333
- contextLoader,
6334
- tracerProvider: this.tracerProvider
6335
- });
6336
- proofCreated = true;
6606
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
6607
+ if (willSign) {
6608
+ if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
6609
+ }
6610
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
6611
+ if (prepared != null) {
6612
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
6613
+ privateKey: kp.privateKey,
6614
+ keyId: kp.multikey.id
6615
+ }] : []);
6616
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
6617
+ activity = signed.activity;
6618
+ activityJsonLd = signed.jsonLd;
6619
+ proofCreated = signingKeys.length > 0;
6620
+ } else {
6621
+ let proofAdded = false;
6622
+ for (const kp of actorKeyPairs) {
6623
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
6624
+ activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
6625
+ contextLoader,
6626
+ tracerProvider: this.tracerProvider
6627
+ });
6628
+ proofAdded = true;
6629
+ }
6630
+ if (proofAdded) activityJsonLd = void 0;
6631
+ proofCreated = proofAdded;
6337
6632
  }
6338
6633
  }
6634
+ const opts = {
6635
+ context: this,
6636
+ orderingKey: options.orderingKey,
6637
+ collectionSync,
6638
+ immediate: options.immediate,
6639
+ activityJsonLd,
6640
+ normalizeExistingProofs: options.normalizeExistingProofs
6641
+ };
6339
6642
  const inboxes = extractInboxes({
6340
6643
  recipients: expandedRecipients,
6341
6644
  preferSharedInbox: options.preferSharedInbox,
@@ -6375,7 +6678,7 @@ var ContextImpl = class ContextImpl {
6375
6678
  actorIds: [...actorIds],
6376
6679
  sharedInbox
6377
6680
  }])),
6378
- activity: await activity.toJsonLd({
6681
+ activity: activityJsonLd != null ? detachSignature(activityJsonLd) : await activity.toJsonLd({
6379
6682
  format: "compact",
6380
6683
  contextLoader: this.contextLoader
6381
6684
  }),
@@ -6386,7 +6689,7 @@ var ContextImpl = class ContextImpl {
6386
6689
  normalizeExistingProofs: proofCreated || options.normalizeExistingProofs,
6387
6690
  traceContext: carrier
6388
6691
  };
6389
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
6692
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
6390
6693
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
6391
6694
  getFederationMetrics(this.federation.meterProvider).recordQueueTaskEnqueued({
6392
6695
  role: "fanout",
@@ -6722,7 +7025,7 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
6722
7025
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
6723
7026
  keys = forwarder;
6724
7027
  } else keys = [forwarder];
6725
- if (!hasSignatureLike(ctx.activity)) {
7028
+ if (!hasVerifiableSignature(ctx.activity) && !hasSignatureLike(ctx.activity)) {
6726
7029
  if (!hasProofLike(ctx.activity)) {
6727
7030
  if (options?.skipIfUnsigned) return false;
6728
7031
  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.", {
@@ -6760,26 +7063,34 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
6760
7063
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
6761
7064
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
6762
7065
  const promises = [];
6763
- for (const inbox in inboxes) promises.push(sendActivity({
6764
- allowPrivateAddress: ctx.federation.allowPrivateAddress,
6765
- keys,
6766
- activity: ctx.activity,
6767
- activityId: ctx.activityId,
6768
- activityType: ctx.activityType,
6769
- inbox: new URL(inbox),
6770
- sharedInbox: inboxes[inbox].sharedInbox,
6771
- meterProvider: ctx.meterProvider,
6772
- tracerProvider: ctx.tracerProvider,
6773
- specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
6774
- }));
6775
- await Promise.all(promises);
7066
+ try {
7067
+ for (const inbox in inboxes) {
7068
+ const promise = sendActivity({
7069
+ allowPrivateAddress: ctx.federation.allowPrivateAddress,
7070
+ keys,
7071
+ activity: ctx.activity,
7072
+ activityId: ctx.activityId,
7073
+ activityType: ctx.activityType,
7074
+ inbox: new URL(inbox),
7075
+ sharedInbox: inboxes[inbox].sharedInbox,
7076
+ meterProvider: ctx.meterProvider,
7077
+ tracerProvider: ctx.tracerProvider,
7078
+ specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
7079
+ });
7080
+ promise.catch(() => {});
7081
+ promises.push(promise);
7082
+ }
7083
+ await Promise.all(promises);
7084
+ } finally {
7085
+ await Promise.allSettled(promises);
7086
+ }
6776
7087
  return true;
6777
7088
  }
6778
7089
  logger.debug("Enqueuing activity {activityId} to forward later.", {
6779
7090
  activityId: ctx.activityId,
6780
7091
  activity: ctx.activity
6781
7092
  });
6782
- if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
7093
+ if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueAutomatically(ctx.data);
6783
7094
  const keyJwkPairs = [];
6784
7095
  for (const { keyId, privateKey } of keys) {
6785
7096
  const privateKeyJwk = await exportJwk(privateKey);
@@ -6956,6 +7267,69 @@ var KvSpecDeterminer = class {
6956
7267
  function notFound(_request) {
6957
7268
  return new Response("Not Found", { status: 404 });
6958
7269
  }
7270
+ function hasTopLevelProof(value) {
7271
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
7272
+ }
7273
+ function getContentFields(value) {
7274
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
7275
+ const record = { ...value };
7276
+ delete record["@context"];
7277
+ delete record.proof;
7278
+ delete record.signature;
7279
+ return JSON.stringify(sortJsonKeys(record));
7280
+ }
7281
+ function getContextFields(value) {
7282
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
7283
+ const context = value["@context"];
7284
+ return JSON.stringify(sortJsonKeys(context ?? null));
7285
+ }
7286
+ function getProofEntries(value) {
7287
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
7288
+ const proof = value.proof;
7289
+ if (proof == null) return [];
7290
+ return Array.isArray(proof) ? proof : [proof];
7291
+ }
7292
+ function normalizeProofEntry(proof) {
7293
+ const stripped = stripContexts(proof);
7294
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
7295
+ const record = { ...stripped };
7296
+ if (typeof record.created === "string") try {
7297
+ record.created = Temporal.Instant.from(record.created).toString();
7298
+ } catch {}
7299
+ return record;
7300
+ }
7301
+ function getProofEntryFields(proof) {
7302
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
7303
+ }
7304
+ function getProofFields(value) {
7305
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
7306
+ }
7307
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
7308
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
7309
+ const retainedProofs = [];
7310
+ for await (const proof of activity.getProofs({ contextLoader })) {
7311
+ const proofJsonLd = await proof.toJsonLd({
7312
+ format: "compact",
7313
+ contextLoader
7314
+ });
7315
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
7316
+ }
7317
+ return retainedProofs;
7318
+ }
7319
+ function stripContexts(value) {
7320
+ if (Array.isArray(value)) return value.map(stripContexts);
7321
+ if (typeof value !== "object" || value == null) return value;
7322
+ const record = { ...value };
7323
+ delete record["@context"];
7324
+ delete record.signature;
7325
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
7326
+ return record;
7327
+ }
7328
+ function sortJsonKeys(value) {
7329
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
7330
+ if (typeof value !== "object" || value == null) return value;
7331
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
7332
+ }
6959
7333
  function notAcceptable(_request) {
6960
7334
  return new Response("Not Acceptable", {
6961
7335
  status: 406,