@fedify/fedify 2.4.6-dev.2837 → 2.4.6

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 (126) hide show
  1. package/dist/attachment-arrays-5yDbmjEb.mjs +16 -0
  2. package/dist/{builder-DYeeuJIZ.mjs → builder-CadJYxhX.mjs} +2 -2
  3. package/dist/callback-DPDs_dxC.d.mts +5280 -0
  4. package/dist/{client-3InDZbba.d.cts → client-DLHsPY7X.d.cts} +16 -0
  5. package/dist/{client-3InDZbba.d.ts → client-DLHsPY7X.d.ts} +16 -0
  6. package/dist/{client-5SIFzW3q.mjs → client-DU3owZBD.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/transformers.test.mjs +1 -1
  13. package/dist/{compound-proof-CxRUa-wY.mjs → compound-proof-CbWKyg2H.mjs} +2 -2
  14. package/dist/{context-D0gFIgev.d.cts → context-DUwicVx-.d.cts} +31 -14
  15. package/dist/{context-CVOOd9pD.d.ts → context-iGMHITvS.d.ts} +31 -14
  16. package/dist/{deno-CRpGtqm6.mjs → deno-BKSRi6w3.mjs} +1 -1
  17. package/dist/{docloader-CZtA3Qjh.mjs → docloader-BcDiJfFl.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/compound-fanout.test.mjs +4 -4
  22. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  23. package/dist/federation/delivery-attachments.test.mjs +288 -0
  24. package/dist/federation/handler-compound-proof.test.mjs +3 -3
  25. package/dist/federation/handler.test.mjs +206 -14
  26. package/dist/federation/hashlink-media.test.mjs +2 -2
  27. package/dist/federation/idempotency.test.mjs +2 -2
  28. package/dist/federation/inbox-report.test.mjs +5 -5
  29. package/dist/federation/inbox.test.mjs +1 -1
  30. package/dist/federation/metrics.test.mjs +1 -1
  31. package/dist/federation/middleware.test.mjs +1188 -13
  32. package/dist/federation/mod.cjs +1 -1
  33. package/dist/federation/mod.d.cts +3 -3
  34. package/dist/federation/mod.d.ts +3 -3
  35. package/dist/federation/mod.js +1 -1
  36. package/dist/federation/outgoing-proof.test.mjs +4 -4
  37. package/dist/federation/portable-actor.test.mjs +3 -3
  38. package/dist/federation/portable-chain.test.mjs +3 -3
  39. package/dist/federation/portable-collection.test.mjs +4 -4
  40. package/dist/federation/portable-delivery.test.mjs +2 -2
  41. package/dist/federation/portable-gateway-keys.test.mjs +5 -5
  42. package/dist/federation/portable-inbox.test.mjs +4 -4
  43. package/dist/federation/portable-parse-uri.test.mjs +1 -1
  44. package/dist/federation/portable-route-activity.test.mjs +2 -2
  45. package/dist/federation/portable.test.mjs +3 -3
  46. package/dist/federation/send.test.mjs +293 -3
  47. package/dist/federation/tasks/enqueue.test.mjs +1 -1
  48. package/dist/federation/tasks/tasks.test.mjs +2 -2
  49. package/dist/federation/temporal.test.mjs +25 -1
  50. package/dist/federation/webfinger.test.mjs +1 -1
  51. package/dist/{federation-DkIcc4TV.cjs → federation-CM4nzbhO.cjs} +500 -144
  52. package/dist/{http-G2ORncQt.mjs → http-B6sfb5xN.mjs} +8 -6
  53. package/dist/{http-DnJvGLuL.js → http-BwgldAIk.js} +2798 -2629
  54. package/dist/{http-DWIArxRV.cjs → http-Tj9eQ_rd.cjs} +2634 -2453
  55. package/dist/{inbox-WfHbmNbc.mjs → inbox-B7NVkb8j.mjs} +2 -2
  56. package/dist/{key-VEL1QqHF.d.cts → key-CIdQA7Pc.d.cts} +5 -5
  57. package/dist/{key-CyCcut3h.d.ts → key-CjtBFzaE.d.ts} +5 -5
  58. package/dist/{kv-cache-CSJwIUzA.js → kv-cache-C-5yfTw-.js} +1 -1
  59. package/dist/{kv-cache-C9jAD4VW.mjs → kv-cache-CvWuigft.mjs} +1 -1
  60. package/dist/{kv-cache-C7b-sBZL.cjs → kv-cache-Vbq0yM7W.cjs} +1 -1
  61. package/dist/{ld-CKWvh95H.mjs → ld-BGnZDnia.mjs} +155 -22
  62. package/dist/ld-signature-D1tFSFK8.mjs +23 -0
  63. package/dist/{metrics-Og1y_3kX.mjs → metrics-DHUP4F1-.mjs} +1 -1
  64. package/dist/{middleware-BLnbBpsz.mjs → middleware-CUb31OGG.mjs} +1 -1
  65. package/dist/{middleware-ClfuKN0B.js → middleware-DX8wADUa.js} +451 -97
  66. package/dist/{middleware-CcNRQv7R.mjs → middleware-mRXKHq68.mjs} +355 -86
  67. package/dist/{mod-B1Qt5cQQ.d.ts → mod-B6s6hA4y.d.ts} +3 -3
  68. package/dist/{mod-ss0wBUH1.d.cts → mod-CJf5GcVD.d.cts} +3 -3
  69. package/dist/{mod-makPMVMg.d.cts → mod-CSlxqNto.d.cts} +1 -1
  70. package/dist/{mod-CpyjFA9s.d.ts → mod-D2DiA8u5.d.cts} +29 -7
  71. package/dist/{mod-BTxJG7ZH.d.cts → mod-DKRf1FLm.d.ts} +29 -7
  72. package/dist/{mod-B5COx5Wd.d.ts → mod-Dqu6Dl1k.d.ts} +1 -1
  73. package/dist/mod.cjs +5 -5
  74. package/dist/mod.d.cts +8 -8
  75. package/dist/mod.d.ts +8 -8
  76. package/dist/mod.js +5 -5
  77. package/dist/nodeinfo/client.test.mjs +432 -4
  78. package/dist/nodeinfo/handler.test.mjs +1 -1
  79. package/dist/nodeinfo/mod.cjs +1 -1
  80. package/dist/nodeinfo/mod.d.cts +1 -1
  81. package/dist/nodeinfo/mod.d.ts +1 -1
  82. package/dist/nodeinfo/mod.js +1 -1
  83. package/dist/{outgoing-jsonld-4IJqPYos.mjs → outgoing-jsonld-Dsca6G_Y.mjs} +35 -4
  84. package/dist/{owner-DxVC0b0R.mjs → owner-DEiBiiqR.mjs} +3 -3
  85. package/dist/{portable-collection-8BzIIWJb.cjs → portable-collection--h11WDIi.cjs} +1 -1
  86. package/dist/{portable-collection-pWL8BrQk.mjs → portable-collection-D0-tInp2.mjs} +2 -2
  87. package/dist/{portable-collection-Bz3Zn527.js → portable-collection-M6d5I5JQ.js} +1 -1
  88. package/dist/{portable-key-BGmzMBYm.mjs → portable-key-CyVJpWWJ.mjs} +1 -1
  89. package/dist/{proof-Cgvg3rEH.mjs → proof-C4pwAF2k.mjs} +29 -9
  90. package/dist/{send-DheMZ6fh.mjs → send-ivzJCtb-.mjs} +100 -22
  91. package/dist/sig/compound-proof-discovery.test.mjs +1 -1
  92. package/dist/sig/compound-proof-producer.test.mjs +1 -1
  93. package/dist/sig/compound-proof-verification.test.mjs +2 -2
  94. package/dist/sig/compound-proof.test.mjs +3 -3
  95. package/dist/sig/http.test.mjs +2 -2
  96. package/dist/sig/key-types.test.d.mts +162 -0
  97. package/dist/sig/key-types.test.mjs +8 -0
  98. package/dist/sig/key.test.mjs +1 -1
  99. package/dist/sig/ld.test.mjs +572 -7
  100. package/dist/sig/mitra-receive-interop.test.mjs +4 -4
  101. package/dist/sig/mitra-send-interop.test.mjs +3 -3
  102. package/dist/sig/mod.cjs +2 -2
  103. package/dist/sig/mod.d.cts +3 -3
  104. package/dist/sig/mod.d.ts +3 -3
  105. package/dist/sig/mod.js +2 -2
  106. package/dist/sig/owner.test.mjs +1 -1
  107. package/dist/sig/portable-collection.test.mjs +1 -1
  108. package/dist/sig/portable-interop.test.mjs +3 -3
  109. package/dist/sig/portable-key.test.mjs +5 -5
  110. package/dist/sig/proof.test.mjs +100 -6
  111. package/dist/sig/tootik-request-interop.test.mjs +4 -4
  112. package/dist/sig/tootik-send-interop.test.mjs +3 -3
  113. package/dist/sig/verification.test.mjs +3 -3
  114. package/dist/{temporal-B7odHbLs.mjs → temporal-B6OlxwK_.mjs} +3 -5
  115. package/dist/testing/kv.test.mjs +1 -1
  116. package/dist/testing/mod.d.mts +3 -5045
  117. package/dist/{types-DUjZb4i6.js → types-BbCbtwZp.js} +86 -11
  118. package/dist/{types-hKCCjii0.cjs → types-C8gac_AD.cjs} +85 -10
  119. package/dist/utils/docloader.test.mjs +2 -2
  120. package/dist/utils/kv-cache.test.mjs +1 -1
  121. package/dist/utils/mod.cjs +1 -1
  122. package/dist/utils/mod.d.cts +1 -1
  123. package/dist/utils/mod.d.ts +1 -1
  124. package/dist/utils/mod.js +1 -1
  125. package/dist/utils/portable-verifier.test.mjs +3 -3
  126. package/package.json +6 -6
@@ -4,40 +4,44 @@ globalThis.addEventListener = () => {};
4
4
  import { d as isPortableUri, f as isSameObjectId, i as getPortableDid, l as isPortableId, n as getCanonicalPortableId, o as hasPortableActor, r as getGatewayKeyBase, s as isCompatibleKeyId, t as getAuthenticationOrigin, u as isPortableKeyId } from "./portable-key-id-Ca30-hOa.mjs";
5
5
  import { n as isPubliclyAddressedNode, t as isInAudience } from "./audience-CHQ-FlLD.mjs";
6
6
  import { a as verificationObservation, r as snapshotKey, t as observeAttempt } from "./verification-Dpfcw8ml.mjs";
7
- import { n as version, t as name } from "./deno-CRpGtqm6.mjs";
8
- import { a as instrumentDocumentLoader, b as recordWebFingerHandle, c as recordCircuitBreakerStateChange, d as recordCollectionRequest, f as recordCollectionTotalItems, g as recordInboxActivity, h as recordFanoutRecipients, i as getRemoteHost, l as recordCollectionDispatchDuration, n as getDurationMs, o as isAbortError, r as getFederationMetrics, u as recordCollectionPageItems, v as recordOutboxActivity, x as registerQueueDepthGauge, y as recordOutboxEnqueue } from "./metrics-Og1y_3kX.mjs";
7
+ import { n as version, t as name } from "./deno-BKSRi6w3.mjs";
8
+ import { a as instrumentDocumentLoader, b as recordWebFingerHandle, c as recordCircuitBreakerStateChange, d as recordCollectionRequest, f as recordCollectionTotalItems, g as recordInboxActivity, h as recordFanoutRecipients, i as getRemoteHost, l as recordCollectionDispatchDuration, n as getDurationMs, o as isAbortError, r as getFederationMetrics, u as recordCollectionPageItems, v as recordOutboxActivity, x as registerQueueDepthGauge, y as recordOutboxEnqueue } from "./metrics-DHUP4F1-.mjs";
9
9
  import { t as formatAcceptSignature } from "./accept-CPVqki78.mjs";
10
- import { D as getDefaultPortableObjectVerifier, T as validateCryptoKey, _ as wrapContextLoaderForJsonLd, a as compactJsonLd, c as getNormalizationContextLoader, d as isClearlyMalformedContextReference, f as isInvalidUrlTypeError, l as hasSignature, m as verifyCompactJsonLd, p as signJsonLd, r as assertSafeJsonLd, s as detachSignature, t as InvalidContextReferenceError, u as hasSignatureLike, w as importJwk, y as exportJwk } from "./ld-CKWvh95H.mjs";
11
- import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-4IJqPYos.mjs";
12
- import { a as signObject, c as verifyPortableObjectProof, i as hasProofLike, s as verifyObject, t as InvalidPortableObjectIdError, u as verifyPortableObjectProofWithRoot } from "./proof-Cgvg3rEH.mjs";
13
- import { c as parseRfc9421SignatureInput, f as validateMaxSignatures, l as selectRequestSignature, m as verifyRequestDetailed, o as listRequestSignatures, p as verifyRequest } from "./http-G2ORncQt.mjs";
14
- import { n as getAuthenticatedDocumentLoader } from "./docloader-CZtA3Qjh.mjs";
15
- import { n as kvCache } from "./kv-cache-C9jAD4VW.mjs";
16
- import { d as MAX_BODY_SIZE, f as readBoundedText, t as getNodeInfo, u as BodyTooLargeError } from "./client-5SIFzW3q.mjs";
10
+ import { D as validateCryptoKey, E as importJwk, a as compactJsonLd, c as detachSignature, d as hasSignatureLike, f as hasVerifiableSignature, g as verifyCompactJsonLd, h as signJsonLd, k as getDefaultPortableObjectVerifier, l as getNormalizationContextLoader, m as isInvalidUrlTypeError, p as isClearlyMalformedContextReference, r as assertSafeJsonLd, s as describeSignatureShape, t as InvalidContextReferenceError, x as exportJwk, y as wrapContextLoaderForJsonLd } from "./ld-BGnZDnia.mjs";
11
+ import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-Dsca6G_Y.mjs";
12
+ import { a as signObject, c as verifyPortableObjectProof, i as hasProofLike, s as verifyObject, t as InvalidPortableObjectIdError, u as verifyPortableObjectProofWithRoot } from "./proof-C4pwAF2k.mjs";
13
+ import { c as parseRfc9421SignatureInput, f as validateMaxSignatures, l as selectRequestSignature, m as verifyRequestDetailed, o as listRequestSignatures, p as verifyRequest } from "./http-B6sfb5xN.mjs";
14
+ import { n as getAuthenticatedDocumentLoader } from "./docloader-BcDiJfFl.mjs";
15
+ import { n as kvCache } from "./kv-cache-CvWuigft.mjs";
16
+ import { d as MAX_BODY_SIZE, f as readBoundedText, t as getNodeInfo, u as BodyTooLargeError } from "./client-DU3owZBD.mjs";
17
17
  import { t as nodeInfoToJson } from "./types-DE_LV1JB.mjs";
18
- import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-DxVC0b0R.mjs";
19
- import { t as verifyPortableObject } from "./portable-collection-pWL8BrQk.mjs";
20
- import { a as sendActivityThroughGateways, i as sendActivity, n as extractInboxes, o as getOrderingDestination, t as SendActivityError } from "./send-DheMZ6fh.mjs";
21
- import { n as FederationBuilderImpl, t as ACTOR_ALIAS_PREFIX } from "./builder-DYeeuJIZ.mjs";
18
+ import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-DEiBiiqR.mjs";
19
+ import { t as verifyPortableObject } from "./portable-collection-D0-tInp2.mjs";
20
+ import { a as sendActivityThroughGateways, i as sendActivity, n as extractInboxes, o as getOrderingDestination, t as SendActivityError } from "./send-ivzJCtb-.mjs";
21
+ import { n as FederationBuilderImpl, t as ACTOR_ALIAS_PREFIX } from "./builder-CadJYxhX.mjs";
22
22
  import { t as CircuitBreaker } from "./circuit-breaker-XJ53md4S.mjs";
23
23
  import { t as buildCollectionSynchronizationHeader } from "./collection-CnnP1UAv.mjs";
24
- import { a as inspectCompoundPortableObjectApplicability, c as verifyServedPortableObjects, i as findUnsupportedCompoundProofShape, o as verifyCompoundPortableObjectProofs, r as findEmbeddedProofWithoutContext, t as containsCompoundPortableObject } from "./compound-proof-CxRUa-wY.mjs";
25
- import { n as routeActivity, t as actorsHaveSameOrigin } from "./inbox-WfHbmNbc.mjs";
24
+ import { t as normalizeAttachmentArrays } from "./attachment-arrays-5yDbmjEb.mjs";
25
+ import { a as inspectCompoundPortableObjectApplicability, c as verifyServedPortableObjects, i as findUnsupportedCompoundProofShape, o as verifyCompoundPortableObjectProofs, r as findEmbeddedProofWithoutContext, t as containsCompoundPortableObject } from "./compound-proof-CbWKyg2H.mjs";
26
+ import { n as routeActivity, t as actorsHaveSameOrigin } from "./inbox-B7NVkb8j.mjs";
26
27
  import { t as KvKeyCache } from "./keycache-N2opu4-3.mjs";
27
28
  import { t as acceptsJsonLd } from "./negotiation-CCocWT_N.mjs";
28
- import { t as hasMalformedKnownTemporalLiteral } from "./temporal-B7odHbLs.mjs";
29
+ import { t as hasMalformedKnownTemporalLiteral } from "./temporal-B6OlxwK_.mjs";
29
30
  import { t as createExponentialBackoffPolicy } from "./retry-zX5xw5e0.mjs";
30
31
  import { t as TaskCodec } from "./codec-C6rTrpIp.mjs";
31
32
  import { getLogger, withContext } from "@logtape/logtape";
32
33
  import { RouterError } from "@fedify/uri-template";
33
- import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, isActor, lookupObject, traverseCollection } from "@fedify/vocab";
34
+ import { Activity, Collection, CollectionPage, CryptographicKey, DataIntegrityProof, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, isActor, lookupObject, traverseCollection } from "@fedify/vocab";
34
35
  import { lookupWebFinger } from "@fedify/webfinger";
35
36
  import { SpanKind, SpanStatusCode, context, metrics, propagation, trace } from "@opentelemetry/api";
36
- import { FetchError, canonicalizePortableUri, decodeMultibase, formatIri, fromCompatibleEf61Id, getDocumentLoader, getFe34Origin, isGatewayUrl, parseDigestMultibase, parseHashlink, parseIri, resolveDocumentLoaderTimeout, toCompatibleEf61Id } from "@fedify/vocab-runtime";
37
+ import { FetchError, canonicalizePortableUri, decodeMultibase, encodeMultibase, formatIri, fromCompatibleEf61Id, getDocumentLoader, getFe34Origin, isGatewayUrl, parseDigestMultibase, parseHashlink, parseIri, resolveDocumentLoaderTimeout, toCompatibleEf61Id } from "@fedify/vocab-runtime";
37
38
  import { isCompatibleEf61Iri } from "@fedify/vocab-runtime/internal/portable-dereference";
38
39
  import { uniq } from "es-toolkit";
40
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
39
41
  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";
42
+ import { encodeHex } from "byte-encodings/hex";
40
43
  import jsonld from "@fedify/vocab-runtime/jsonld";
44
+ import serialize from "json-canon";
41
45
  import { DataPointType, MeterProvider as MeterProvider$1, MetricReader } from "@opentelemetry/sdk-metrics";
42
46
  import { domainToASCII } from "node:url";
43
47
  //#region src/compat/transformers.ts
@@ -1287,7 +1291,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1287
1291
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1288
1292
  }
1289
1293
  if (actor instanceof Tombstone) {
1290
- const jsonLd = await actor.toJsonLd(context);
1294
+ const jsonLd = await serializeForResponse(actor, context);
1291
1295
  return new Response(JSON.stringify(jsonLd), {
1292
1296
  status: 410,
1293
1297
  headers: {
@@ -1296,7 +1300,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1296
1300
  }
1297
1301
  });
1298
1302
  }
1299
- const jsonLd = await actor.toJsonLd(context);
1303
+ const jsonLd = await serializeForResponse(actor, context);
1300
1304
  return new Response(JSON.stringify(jsonLd), { headers: {
1301
1305
  "Content-Type": "application/activity+json",
1302
1306
  Vary: "Accept"
@@ -1316,7 +1320,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1316
1320
  if (authorizePredicate != null) {
1317
1321
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1318
1322
  }
1319
- const jsonLd = await object.toJsonLd(context);
1323
+ const jsonLd = await serializeForResponse(object, context);
1320
1324
  if (object instanceof Tombstone) return new Response(request.method === "HEAD" ? null : JSON.stringify(jsonLd), {
1321
1325
  status: 410,
1322
1326
  headers: {
@@ -1568,13 +1572,13 @@ function recordCollectionMetrics(meterProvider, base, result, options = {}) {
1568
1572
  * @param parameters The parameters for handling the collection.
1569
1573
  * @returns A promise that resolves to an HTTP response.
1570
1574
  */
1571
- async function handleCollection(request, { name: name$1, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, portable, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
1572
- const spanName = name$1.trim().replace(/\s+/g, "_");
1575
+ async function handleCollection(request, { name: name$2, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, portable, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
1576
+ const spanName = name$2.trim().replace(/\s+/g, "_");
1573
1577
  tracerProvider = tracerProvider ?? trace.getTracerProvider();
1574
1578
  const tracer = tracerProvider.getTracer(name, version);
1575
1579
  const cursor = new URL(request.url).searchParams.get("cursor");
1576
1580
  const metricBase = {
1577
- kind: getCollectionMetricKind(name$1),
1581
+ kind: getCollectionMetricKind(name$2),
1578
1582
  page: cursor != null,
1579
1583
  dispatcher: "built_in"
1580
1584
  };
@@ -1620,7 +1624,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1620
1624
  span.setStatus({ code: SpanStatusCode.ERROR });
1621
1625
  return await onNotFound(request);
1622
1626
  }
1623
- const items = filterCollectionItems(page.items, name$1, filterPredicate);
1627
+ const items = filterCollectionItems(page.items, name$2, filterPredicate);
1624
1628
  itemCount = items.length;
1625
1629
  span.setAttribute("fedify.collection.items", itemCount);
1626
1630
  return items;
@@ -1662,7 +1666,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1662
1666
  } else {
1663
1667
  const uri = new URL(portable == null ? baseUri : pageBase);
1664
1668
  uri.searchParams.set("cursor", cursor);
1665
- const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$1}`, {
1669
+ const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$2}`, {
1666
1670
  kind: SpanKind.SERVER,
1667
1671
  attributes: {
1668
1672
  "activitypub.collection.id": uri.href,
@@ -1678,7 +1682,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1678
1682
  span.setStatus({ code: SpanStatusCode.ERROR });
1679
1683
  return await onNotFound(request);
1680
1684
  }
1681
- const items = filterCollectionItems(page.items, name$1, filterPredicate);
1685
+ const items = filterCollectionItems(page.items, name$2, filterPredicate);
1682
1686
  itemCount = items.length;
1683
1687
  span.setAttribute("fedify.collection.items", itemCount);
1684
1688
  return {
@@ -1722,7 +1726,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1722
1726
  if (portable == null && collectionCallbacks.authorizePredicate != null) {
1723
1727
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return finish(await onUnauthorized(request), "unauthorized");
1724
1728
  }
1725
- const jsonLd = await collection.toJsonLd(context);
1729
+ const jsonLd = await serializeForResponse(collection, context, portable != null);
1726
1730
  if (portable != null) return await verifyPortableCollection(jsonLd, context, portable) ? finish(respondWithPortableCollection(request, jsonLd), "served") : finish(portableObjectInternalServerError(request), "error");
1727
1731
  return finish(new Response(JSON.stringify(jsonLd), { headers: {
1728
1732
  "Content-Type": "application/activity+json",
@@ -2312,7 +2316,11 @@ async function handleInboxInternal(request, parameters, span) {
2312
2316
  keyTtl: publicKeyTtl
2313
2317
  });
2314
2318
  const jsonWithoutSig = detachSignature(json);
2315
- const hasLdSignature = hasSignature(json);
2319
+ const hasLdSignature = hasVerifiableSignature(json);
2320
+ if (!hasLdSignature) {
2321
+ const shape = describeSignatureShape(json);
2322
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
2323
+ }
2316
2324
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
2317
2325
  let deferredLdSignatureError = void 0;
2318
2326
  const respondInvalidActivity = async (error) => {
@@ -3090,8 +3098,8 @@ var CustomCollectionHandler = class {
3090
3098
  * @param CollectionPage The CollectionPage constructor.
3091
3099
  * @param filterPredicate Optional filter predicate for items.
3092
3100
  */
3093
- constructor(name$2, values, context, callbacks, tracerProvider = trace.getTracerProvider(), meterProvider, Collection, CollectionPage, filterPredicate, portable) {
3094
- this.name = name$2;
3101
+ constructor(name$1, values, context, callbacks, tracerProvider = trace.getTracerProvider(), meterProvider, Collection, CollectionPage, filterPredicate, portable) {
3102
+ this.name = name$1;
3095
3103
  this.values = values;
3096
3104
  this.context = context;
3097
3105
  this.callbacks = callbacks;
@@ -3115,7 +3123,7 @@ var CustomCollectionHandler = class {
3115
3123
  * @returns A promise that resolves to the JSON-LD representation.
3116
3124
  */
3117
3125
  async toJsonLd() {
3118
- return (await this.collection).toJsonLd(this.context);
3126
+ return serializeForResponse(await this.collection, this.context, this.portable != null);
3119
3127
  }
3120
3128
  /**
3121
3129
  * Fetches the collection with optional cursor for pagination.
@@ -3511,7 +3519,7 @@ var PortableCollectionRefusedError = class extends HandlerError {
3511
3519
  * @since 0.3.0
3512
3520
  */
3513
3521
  async function respondWithObject(object, options) {
3514
- const jsonLd = await object.toJsonLd(options);
3522
+ const jsonLd = await serializeForResponse(object, options);
3515
3523
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
3516
3524
  }
3517
3525
  /**
@@ -3608,6 +3616,13 @@ const MIN_COMPONENTS = [
3608
3616
  function isPortableActorKey(key) {
3609
3617
  return key?.id != null && isPortableKeyId(key.id) && key.ownerId != null && isPortableId(key.ownerId);
3610
3618
  }
3619
+ /** Applies compatibility changes after ordinary vocabulary serialization. */
3620
+ async function serializeForResponse(object, options, compact = false) {
3621
+ return await normalizeAttachmentArrays(await object.toJsonLd(compact ? {
3622
+ format: "compact",
3623
+ contextLoader: options?.contextLoader
3624
+ } : options), options?.contextLoader);
3625
+ }
3611
3626
  /**
3612
3627
  * Checks whether an activity needs an Object Integrity Proof by its DID:
3613
3628
  * either it is performed by an [FEP-ef61] portable actor, or its own ID is
@@ -3737,6 +3752,102 @@ function buildPortableCollectionView(collectionId, requestUrl) {
3737
3752
  return view;
3738
3753
  }
3739
3754
  //#endregion
3755
+ //#region src/sig/proof-creation.ts
3756
+ /** Signs the exact serialized message supplied by an internal producer. */
3757
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
3758
+ validateCryptoKey(privateKey, "private");
3759
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
3760
+ const encoder = new TextEncoder();
3761
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(jsonLd)));
3762
+ created ??= Temporal.Now.instant();
3763
+ const proofConfig = {
3764
+ "@context": jsonLd["@context"],
3765
+ type: "DataIntegrityProof",
3766
+ cryptosuite: "eddsa-jcs-2022",
3767
+ verificationMethod: keyId.href,
3768
+ proofPurpose: "assertionMethod",
3769
+ created: created.toString()
3770
+ };
3771
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(proofConfig)));
3772
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
3773
+ digest.set(new Uint8Array(proofDigest), 0);
3774
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
3775
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
3776
+ return new DataIntegrityProof({
3777
+ cryptosuite: "eddsa-jcs-2022",
3778
+ verificationMethod: keyId,
3779
+ proofPurpose: "assertionMethod",
3780
+ created,
3781
+ proofValue: new Uint8Array(sig)
3782
+ });
3783
+ }
3784
+ //#endregion
3785
+ //#region src/compat/delivery-jsonld.ts
3786
+ /**
3787
+ * Returns changed wire JSON only; unchanged documents keep the existing
3788
+ * delivery signing path. This uses ordinary vocabulary serialization, without
3789
+ * retaining or repairing independently signed child representations.
3790
+ */
3791
+ async function prepareActivityJsonLd(activity, contextLoader) {
3792
+ if (activity.proofIds.length > 0) return void 0;
3793
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
3794
+ const source = await activity.clone({}, { verifyPortableObject: getDefaultPortableObjectVerifier(activity) }).toJsonLd({
3795
+ format: "compact",
3796
+ contextLoader
3797
+ });
3798
+ const prepared = await normalizeOutgoingActivityJsonLd(source, contextLoader, { preserveSecuredDocuments: true });
3799
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
3800
+ }
3801
+ /** Signs a changed, proof-free delivery map without serializing it again. */
3802
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
3803
+ const proofs = [];
3804
+ const serializedProofs = [];
3805
+ const tracer = (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version);
3806
+ for (const { privateKey, keyId } of keys) {
3807
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(activity).href } }, async (span) => {
3808
+ try {
3809
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
3810
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
3811
+ if (span.isRecording()) {
3812
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
3813
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
3814
+ span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
3815
+ }
3816
+ return proof;
3817
+ } catch (error) {
3818
+ span.setStatus({
3819
+ code: SpanStatusCode.ERROR,
3820
+ message: String(error)
3821
+ });
3822
+ throw error;
3823
+ } finally {
3824
+ span.end();
3825
+ }
3826
+ });
3827
+ proofs.push(proof);
3828
+ serializedProofs.push({
3829
+ "@context": unsigned["@context"],
3830
+ type: "DataIntegrityProof",
3831
+ cryptosuite: proof.cryptosuite,
3832
+ verificationMethod: keyId.href,
3833
+ proofPurpose: "assertionMethod",
3834
+ created: proof.created.toString(),
3835
+ proofValue: new TextDecoder().decode(encodeMultibase("base58btc", proof.proofValue))
3836
+ });
3837
+ }
3838
+ if (proofs.length === 0) return {
3839
+ activity,
3840
+ jsonLd: unsigned
3841
+ };
3842
+ return {
3843
+ activity: activity.clone({ proofs }, { verifyPortableObject: getDefaultPortableObjectVerifier(activity) }),
3844
+ jsonLd: {
3845
+ ...unsigned,
3846
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
3847
+ }
3848
+ };
3849
+ }
3850
+ //#endregion
3740
3851
  //#region src/federation/outgoing-proof.ts
3741
3852
  function formatKeyIds(candidates) {
3742
3853
  return candidates.map((c) => c.verificationMethod.href).join(", ");
@@ -3804,6 +3915,15 @@ async function signOutgoingActivity(activity, candidates, options) {
3804
3915
  const { contextLoader, tracerProvider } = options;
3805
3916
  assertPortableActorActivity(activity);
3806
3917
  const sign = async (selected) => {
3918
+ const prepared = !hasProof ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
3919
+ if (prepared != null) return {
3920
+ ...await signActivityJsonLd(activity, prepared, selected.map(({ verificationMethod, privateKey }) => ({
3921
+ keyId: verificationMethod,
3922
+ privateKey
3923
+ })), { tracerProvider: tracerProvider ?? trace.getTracerProvider() }),
3924
+ hasProof: true,
3925
+ proofCreated: true
3926
+ };
3807
3927
  for (const { verificationMethod, privateKey } of selected) activity = await signObject(activity, privateKey, verificationMethod, {
3808
3928
  contextLoader,
3809
3929
  tracerProvider
@@ -4789,6 +4909,13 @@ var FederationImpl = class extends FederationBuilderImpl {
4789
4909
  if (resolved != null) return resolved;
4790
4910
  return this.taskQueueResolution === "strict" ? void 0 : this.outboxQueue;
4791
4911
  }
4912
+ #listenQueue(queue, ctxData, signal) {
4913
+ try {
4914
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
4915
+ } catch (error) {
4916
+ return Promise.reject(error);
4917
+ }
4918
+ }
4792
4919
  async _startQueueInternal(ctxData, signal, queue) {
4793
4920
  const taskQueue = this.taskQueue ?? (this.taskQueueResolution === "fallback" ? this.outboxQueue : void 0);
4794
4921
  const customQueues = this.taskDefinitions.values().map((def) => ["task", def.queue]);
@@ -4810,10 +4937,31 @@ var FederationImpl = class extends FederationBuilderImpl {
4810
4937
  if (this.startedQueues.has(target)) continue;
4811
4938
  this.startedQueues.add(target);
4812
4939
  logger.debug("Starting a {role} queue worker.", { role });
4813
- promises.push(target.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
4940
+ promises.push(this.#listenQueue(target, ctxData, signal));
4814
4941
  }
4815
4942
  await Promise.all(promises);
4816
4943
  }
4944
+ /**
4945
+ * Starts the queue workers automatically, reporting a failure instead of
4946
+ * leaving the returned promise unobserved.
4947
+ *
4948
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
4949
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
4950
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
4951
+ * callers that start workers deliberately.
4952
+ */
4953
+ #queueStartupFailureReported = false;
4954
+ _startQueueAutomatically(ctxData) {
4955
+ this._startQueueInternal(ctxData).catch((error) => {
4956
+ if (this.#queueStartupFailureReported) return;
4957
+ this.#queueStartupFailureReported = true;
4958
+ getLogger([
4959
+ "fedify",
4960
+ "federation",
4961
+ "queue"
4962
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
4963
+ });
4964
+ }
4817
4965
  processQueuedTask(contextData, message) {
4818
4966
  const extractedContext = propagation.extract(context.active(), message.traceContext);
4819
4967
  return withContext({ messageId: message.id }, async () => {
@@ -5692,7 +5840,7 @@ var FederationImpl = class extends FederationBuilderImpl {
5692
5840
  let parseInput = void 0;
5693
5841
  let parseContextLoader = context.contextLoader;
5694
5842
  try {
5695
- const hasSignatureField = hasSignature(message.activity);
5843
+ const hasSignatureField = hasVerifiableSignature(message.activity);
5696
5844
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
5697
5845
  const parseContext = hasSignatureField ? {
5698
5846
  ...context,
@@ -6009,11 +6157,11 @@ var FederationImpl = class extends FederationBuilderImpl {
6009
6157
  });
6010
6158
  activity = signed.activity;
6011
6159
  const { hasProof, proofCreated } = signed;
6012
- let jsonLd = !proofCreated && options.activityJsonLd != null ? options.activityJsonLd : await activity.toJsonLd({
6160
+ let jsonLd = signed.jsonLd ?? (!proofCreated && options.activityJsonLd != null ? options.activityJsonLd : await activity.toJsonLd({
6013
6161
  format: "compact",
6014
6162
  contextLoader
6015
- });
6016
- if (proofCreated || !hasProof || options.normalizeExistingProofs) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader, { preserveNestedSecuredDocuments: true });
6163
+ }));
6164
+ if (signed.jsonLd == null && (proofCreated || !hasProof || options.normalizeExistingProofs)) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader, { preserveNestedSecuredDocuments: true });
6017
6165
  assertSupportedCompoundProofShape(jsonLd, activityId);
6018
6166
  if (rsaKey == null && !ldSignable) logger.debug("The activity {activityId} is performed by a portable actor, so it is sent without a Linked Data signature.", { activityId });
6019
6167
  else 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.", {
@@ -6052,19 +6200,27 @@ var FederationImpl = class extends FederationBuilderImpl {
6052
6200
  activity: jsonLd
6053
6201
  });
6054
6202
  const promises = [];
6055
- for (const inbox in inboxes) promises.push(sendActivityToInbox(inbox, inboxes[inbox].gatewayInboxes, {
6056
- allowPrivateAddress: this.allowPrivateAddress,
6057
- keys,
6058
- activity: jsonLd,
6059
- activityId: activity.id?.href,
6060
- activityType: getTypeId(activity).href,
6061
- sharedInbox: inboxes[inbox].sharedInbox,
6062
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
6063
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock, { specTtl: this.httpMessageSignaturesSpecTtl }),
6064
- meterProvider: this.meterProvider,
6065
- tracerProvider: this.tracerProvider
6066
- }));
6067
- await Promise.all(promises);
6203
+ try {
6204
+ for (const inbox in inboxes) {
6205
+ const promise = sendActivityToInbox(inbox, inboxes[inbox].gatewayInboxes, {
6206
+ allowPrivateAddress: this.allowPrivateAddress,
6207
+ keys,
6208
+ activity: jsonLd,
6209
+ activityId: activity.id?.href,
6210
+ activityType: getTypeId(activity).href,
6211
+ sharedInbox: inboxes[inbox].sharedInbox,
6212
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
6213
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock, { specTtl: this.httpMessageSignaturesSpecTtl }),
6214
+ meterProvider: this.meterProvider,
6215
+ tracerProvider: this.tracerProvider
6216
+ });
6217
+ promise.catch(() => {});
6218
+ promises.push(promise);
6219
+ }
6220
+ await Promise.all(promises);
6221
+ } finally {
6222
+ await Promise.allSettled(promises);
6223
+ }
6068
6224
  return;
6069
6225
  }
6070
6226
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -6079,7 +6235,7 @@ var FederationImpl = class extends FederationBuilderImpl {
6079
6235
  privateKey: privateKeyJwk
6080
6236
  });
6081
6237
  }
6082
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
6238
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
6083
6239
  const carrier = {};
6084
6240
  propagation.inject(context.active(), carrier);
6085
6241
  const messages = [];
@@ -6759,7 +6915,7 @@ var FederationImpl = class extends FederationBuilderImpl {
6759
6915
  return await observation.run(() => Promise.reject(error), span);
6760
6916
  }
6761
6917
  async #handleInbox(request, { recipient, context, contextData, onNotFound, portableInbox, observation }) {
6762
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
6918
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
6763
6919
  const inboxContextFactory = context.toInboxContext.bind(context);
6764
6920
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
6765
6921
  return await handleInbox(request, {
@@ -6872,7 +7028,7 @@ var FederationImpl = class extends FederationBuilderImpl {
6872
7028
  kv: this.kv,
6873
7029
  kvPrefix: this.kvPrefixes.portableInboxForwarding,
6874
7030
  outboxQueue: this.outboxQueue,
6875
- startQueue: this.manuallyStartQueue ? void 0 : () => this._startQueueInternal(contextData),
7031
+ startQueue: this.manuallyStartQueue ? void 0 : () => this._startQueueAutomatically(contextData),
6876
7032
  allowPrivateAddress: this.allowPrivateAddress,
6877
7033
  getKeys: () => this.#getPortableGatewayKeyPairs(context, identifier, recipient),
6878
7034
  specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock, { specTtl: this.httpMessageSignaturesSpecTtl }),
@@ -7378,6 +7534,8 @@ var ContextImpl = class ContextImpl {
7378
7534
  for (const keyPair of keyPairs) {
7379
7535
  const newPair = {
7380
7536
  ...keyPair,
7537
+ privateKey: asCryptoKey(keyPair.privateKey),
7538
+ publicKey: asCryptoKey(keyPair.publicKey),
7381
7539
  cryptographicKey: new CryptographicKey({
7382
7540
  id: keyPair.keyId,
7383
7541
  owner,
@@ -7475,10 +7633,16 @@ var ContextImpl = class ContextImpl {
7475
7633
  } else identifierPromise = Promise.resolve(identity.identifier);
7476
7634
  return identifierPromise.then((identifier) => {
7477
7635
  if (identifier == null) return this.documentLoader;
7478
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
7636
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
7637
+ keyId: pair.keyId,
7638
+ privateKey: asCryptoKey(pair.privateKey)
7639
+ }));
7479
7640
  });
7480
7641
  }
7481
- return this.federation.authenticatedDocumentLoaderFactory(identity);
7642
+ return this.federation.authenticatedDocumentLoaderFactory({
7643
+ keyId: identity.keyId,
7644
+ privateKey: asCryptoKey(identity.privateKey)
7645
+ });
7482
7646
  }
7483
7647
  lookupObject(identifier, options = {}) {
7484
7648
  return lookupObject(identifier, {
@@ -7504,10 +7668,14 @@ var ContextImpl = class ContextImpl {
7504
7668
  return options.parse === "none" ? getNodeInfo(url, {
7505
7669
  parse: "none",
7506
7670
  direct: options.direct,
7671
+ timeout: options.timeout,
7672
+ signal: options.signal,
7507
7673
  userAgent: options?.userAgent ?? this.federation.userAgent
7508
7674
  }) : getNodeInfo(url, {
7509
7675
  parse: options.parse,
7510
7676
  direct: options.direct,
7677
+ timeout: options.timeout,
7678
+ signal: options.signal,
7511
7679
  userAgent: options?.userAgent ?? this.federation.userAgent
7512
7680
  });
7513
7681
  }
@@ -7526,7 +7694,17 @@ var ContextImpl = class ContextImpl {
7526
7694
  async enqueueTaskMany(task, payloads, options = {}) {
7527
7695
  await this.#enqueueTasks(task, payloads, options);
7528
7696
  }
7529
- sendActivity(sender, recipients, activity, options = {}) {
7697
+ async sendActivity(sender, recipients, activity, options = {}) {
7698
+ let activityJsonLd = void 0;
7699
+ let hasProof = activity.proofIds.length > 0;
7700
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
7701
+ hasProof = true;
7702
+ break;
7703
+ }
7704
+ if (hasProof) {
7705
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
7706
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
7707
+ }
7530
7708
  return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
7531
7709
  kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
7532
7710
  attributes: {
@@ -7539,7 +7717,7 @@ var ContextImpl = class ContextImpl {
7539
7717
  }, async (span) => {
7540
7718
  try {
7541
7719
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
7542
- await this.sendActivityInternal(sender, recipients, activity, options, span);
7720
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
7543
7721
  } catch (e) {
7544
7722
  span.setStatus({
7545
7723
  code: SpanStatusCode.ERROR,
@@ -7551,7 +7729,7 @@ var ContextImpl = class ContextImpl {
7551
7729
  }
7552
7730
  });
7553
7731
  }
7554
- async sendActivityInternal(sender, recipients, activity, options, span) {
7732
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
7555
7733
  const logger = getLogger([
7556
7734
  "fedify",
7557
7735
  "federation",
@@ -7598,15 +7776,23 @@ var ContextImpl = class ContextImpl {
7598
7776
  if (!(error instanceof RouterError)) throw error;
7599
7777
  }
7600
7778
  } else expandedRecipients = [recipients];
7601
- const opts = {
7602
- context: this,
7603
- orderingKey: options.orderingKey,
7604
- collectionSync,
7605
- immediate: options.immediate,
7606
- normalizeExistingProofs: options.normalizeExistingProofs
7607
- };
7608
7779
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
7609
7780
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
7781
+ let contextMatches = false;
7782
+ if (activityJsonLd != null) {
7783
+ const capturedJsonLd = activityJsonLd;
7784
+ const transformedJsonLd = await activity.toJsonLd({
7785
+ format: "compact",
7786
+ contextLoader: this.contextLoader
7787
+ });
7788
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
7789
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
7790
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
7791
+ if (contentChanged || !contextMatches && proofsChanged) {
7792
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) }, { verifyPortableObject: getDefaultPortableObjectVerifier(activity) });
7793
+ activityJsonLd = void 0;
7794
+ } else if (proofsChanged) activityJsonLd = void 0;
7795
+ }
7610
7796
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
7611
7797
  if (activity.actorId == null) {
7612
7798
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -7615,7 +7801,11 @@ var ContextImpl = class ContextImpl {
7615
7801
  });
7616
7802
  throw new TypeError("The activity to send must have at least one actor property.");
7617
7803
  }
7618
- const { activity: signedActivity, proofCreated } = await signOutgoingActivity(activity, actorKeyPairs == null ? keys.map(({ keyId, privateKey }) => ({
7804
+ if (actorKeyPairs != null && activityJsonLd != null && !contextMatches && actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null && !isPortableKeyId(kp.multikey.id))) {
7805
+ activity = activity.clone({ proofs: [] }, { verifyPortableObject: getDefaultPortableObjectVerifier(activity) });
7806
+ activityJsonLd = void 0;
7807
+ }
7808
+ const signed = await signOutgoingActivity(activity, actorKeyPairs == null ? keys.map(({ keyId, privateKey }) => ({
7619
7809
  verificationMethod: keyId,
7620
7810
  privateKey
7621
7811
  })) : actorKeyPairs.flatMap((kp) => kp.multikey.id == null ? [] : [{
@@ -7626,7 +7816,15 @@ var ContextImpl = class ContextImpl {
7626
7816
  tracerProvider: this.tracerProvider,
7627
7817
  appendToExistingProofs: actorKeyPairs != null
7628
7818
  });
7629
- activity = signedActivity;
7819
+ activity = signed.activity;
7820
+ const { proofCreated } = signed;
7821
+ const opts = {
7822
+ context: this,
7823
+ orderingKey: options.orderingKey,
7824
+ collectionSync,
7825
+ immediate: options.immediate,
7826
+ normalizeExistingProofs: options.normalizeExistingProofs
7827
+ };
7630
7828
  const inboxes = extractInboxes({
7631
7829
  recipients: expandedRecipients,
7632
7830
  preferSharedInbox: options.preferSharedInbox,
@@ -7644,10 +7842,10 @@ var ContextImpl = class ContextImpl {
7644
7842
  activityId: activity.id?.href,
7645
7843
  activity
7646
7844
  });
7647
- const activityJsonLd = await activity.toJsonLd({
7845
+ activityJsonLd = signed.jsonLd ?? (!proofCreated && activityJsonLd != null ? activityJsonLd : await activity.toJsonLd({
7648
7846
  format: "compact",
7649
7847
  contextLoader: this.contextLoader
7650
- });
7848
+ }));
7651
7849
  try {
7652
7850
  await warnCompatibleIdsInJson(activityJsonLd, this instanceof RequestContextImpl && !this.isInActorDispatcher() ? this : void 0);
7653
7851
  } catch (error) {
@@ -7689,7 +7887,7 @@ var ContextImpl = class ContextImpl {
7689
7887
  normalizeExistingProofs: proofCreated || options.normalizeExistingProofs,
7690
7888
  traceContext: carrier
7691
7889
  };
7692
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
7890
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
7693
7891
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
7694
7892
  getFederationMetrics(this.federation.meterProvider).recordQueueTaskEnqueued({
7695
7893
  role: "fanout",
@@ -8087,7 +8285,7 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
8087
8285
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
8088
8286
  keys = forwarder;
8089
8287
  } else keys = [forwarder];
8090
- if (!hasSignatureLike(ctx.activity)) {
8288
+ if (!hasVerifiableSignature(ctx.activity) && !hasSignatureLike(ctx.activity)) {
8091
8289
  if (!hasProofLike(ctx.activity)) {
8092
8290
  if (options?.skipIfUnsigned) return false;
8093
8291
  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.", {
@@ -8125,25 +8323,33 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
8125
8323
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
8126
8324
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
8127
8325
  const promises = [];
8128
- for (const inbox in inboxes) promises.push(sendActivityToInbox(inbox, inboxes[inbox].gatewayInboxes, {
8129
- allowPrivateAddress: ctx.federation.allowPrivateAddress,
8130
- keys,
8131
- activity: ctx.activity,
8132
- activityId: ctx.activityId,
8133
- activityType: ctx.activityType,
8134
- sharedInbox: inboxes[inbox].sharedInbox,
8135
- meterProvider: ctx.meterProvider,
8136
- tracerProvider: ctx.tracerProvider,
8137
- specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock, { specTtl: ctx.federation.httpMessageSignaturesSpecTtl })
8138
- }));
8139
- await Promise.all(promises);
8326
+ try {
8327
+ for (const inbox in inboxes) {
8328
+ const promise = sendActivityToInbox(inbox, inboxes[inbox].gatewayInboxes, {
8329
+ allowPrivateAddress: ctx.federation.allowPrivateAddress,
8330
+ keys,
8331
+ activity: ctx.activity,
8332
+ activityId: ctx.activityId,
8333
+ activityType: ctx.activityType,
8334
+ sharedInbox: inboxes[inbox].sharedInbox,
8335
+ meterProvider: ctx.meterProvider,
8336
+ tracerProvider: ctx.tracerProvider,
8337
+ specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock, { specTtl: ctx.federation.httpMessageSignaturesSpecTtl })
8338
+ });
8339
+ promise.catch(() => {});
8340
+ promises.push(promise);
8341
+ }
8342
+ await Promise.all(promises);
8343
+ } finally {
8344
+ await Promise.allSettled(promises);
8345
+ }
8140
8346
  return true;
8141
8347
  }
8142
8348
  logger.debug("Enqueuing activity {activityId} to forward later.", {
8143
8349
  activityId: ctx.activityId,
8144
8350
  activity: ctx.activity
8145
8351
  });
8146
- if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
8352
+ if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueAutomatically(ctx.data);
8147
8353
  const keyJwkPairs = [];
8148
8354
  for (const { keyId, privateKey } of keys) {
8149
8355
  const privateKeyJwk = await exportJwk(privateKey);
@@ -8323,6 +8529,69 @@ var KvSpecDeterminer = class {
8323
8529
  function notFound(_request) {
8324
8530
  return new Response("Not Found", { status: 404 });
8325
8531
  }
8532
+ function hasTopLevelProof(value) {
8533
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
8534
+ }
8535
+ function getContentFields(value) {
8536
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
8537
+ const record = { ...value };
8538
+ delete record["@context"];
8539
+ delete record.proof;
8540
+ delete record.signature;
8541
+ return JSON.stringify(sortJsonKeys(record));
8542
+ }
8543
+ function getContextFields(value) {
8544
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
8545
+ const context = value["@context"];
8546
+ return JSON.stringify(sortJsonKeys(context ?? null));
8547
+ }
8548
+ function getProofEntries(value) {
8549
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
8550
+ const proof = value.proof;
8551
+ if (proof == null) return [];
8552
+ return Array.isArray(proof) ? proof : [proof];
8553
+ }
8554
+ function normalizeProofEntry(proof) {
8555
+ const stripped = stripContexts(proof);
8556
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
8557
+ const record = { ...stripped };
8558
+ if (typeof record.created === "string") try {
8559
+ record.created = Temporal.Instant.from(record.created).toString();
8560
+ } catch {}
8561
+ return record;
8562
+ }
8563
+ function getProofEntryFields(proof) {
8564
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
8565
+ }
8566
+ function getProofFields(value) {
8567
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
8568
+ }
8569
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
8570
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
8571
+ const retainedProofs = [];
8572
+ for await (const proof of activity.getProofs({ contextLoader })) {
8573
+ const proofJsonLd = await proof.toJsonLd({
8574
+ format: "compact",
8575
+ contextLoader
8576
+ });
8577
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
8578
+ }
8579
+ return retainedProofs;
8580
+ }
8581
+ function stripContexts(value) {
8582
+ if (Array.isArray(value)) return value.map(stripContexts);
8583
+ if (typeof value !== "object" || value == null) return value;
8584
+ const record = { ...value };
8585
+ delete record["@context"];
8586
+ delete record.signature;
8587
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
8588
+ return record;
8589
+ }
8590
+ function sortJsonKeys(value) {
8591
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
8592
+ if (typeof value !== "object" || value == null) return value;
8593
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
8594
+ }
8326
8595
  function notAcceptable(_request) {
8327
8596
  return new Response("Not Acceptable", {
8328
8597
  status: 406,
@@ -8354,4 +8623,4 @@ function getRequestId(request) {
8354
8623
  return `req_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
8355
8624
  }
8356
8625
  //#endregion
8357
- export { getEmbeddedFirstGateway as C, handleNodeInfoJrd as D, handleNodeInfo as E, actorDehydrator as O, getCompactRootId as S, handleBenchmarkTrigger as T, coversDelivery as _, OutboxContextImpl as a, PORTABLE_OBJECT_CONTENT_TYPE as b, assertPortableActorActivity as c, handleCustomCollection as d, handleInbox as f, respondWithObjectIfAcceptable as g, respondWithObject as h, KvSpecDeterminer as i, autoIdAssigner as k, handleActor as l, handleOutbox as m, FederationImpl as n, createFederation as o, handleObject as p, InboxContextImpl as r, handleWebFinger as s, ContextImpl as t, handleCollection as u, forwardPortableInboxActivity as v, warnCompatibleIdsInJson as w, parseHashlinkGatewayRequest as x, resolvePortableInboxForwardingOptions as y };
8626
+ export { autoIdAssigner as A, getCompactRootId as C, handleNodeInfo as D, handleBenchmarkTrigger as E, handleNodeInfoJrd as O, parseHashlinkGatewayRequest as S, warnCompatibleIdsInJson as T, respondWithObjectIfAcceptable as _, OutboxContextImpl as a, resolvePortableInboxForwardingOptions as b, assertPortableActorActivity as c, handleCollection as d, handleCustomCollection as f, respondWithObject as g, handleOutbox as h, KvSpecDeterminer as i, actorDehydrator as k, prepareActivityJsonLd as l, handleObject as m, FederationImpl as n, createFederation as o, handleInbox as p, InboxContextImpl as r, handleWebFinger as s, ContextImpl as t, handleActor as u, coversDelivery as v, getEmbeddedFirstGateway as w, PORTABLE_OBJECT_CONTENT_TYPE as x, forwardPortableInboxActivity as y };