@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
@@ -1,38 +1,138 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-DmDVx5sE.mjs";
5
- 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-D3OnAgfj.mjs";
4
+ import { n as version, t as name } from "./deno-FtdqgHJA.mjs";
5
+ 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-CaoYRhNH.mjs";
6
6
  import { t as formatAcceptSignature } from "./accept-Dd__NiUL.mjs";
7
- import { o as importJwk, s as validateCryptoKey, t as exportJwk } from "./key-SkLDUmPM.mjs";
8
- import { d as verifyRequestDetailed, s as parseRfc9421SignatureInput, u as verifyRequest } from "./http-DCK-QQfE.mjs";
9
- import { n as getAuthenticatedDocumentLoader } from "./docloader-0fjyUmvI.mjs";
10
- import { n as kvCache } from "./kv-cache-BaJOO6O3.mjs";
7
+ import { o as importJwk, s as validateCryptoKey, t as exportJwk } from "./key-o1SmN5s0.mjs";
8
+ import { d as verifyRequestDetailed, s as parseRfc9421SignatureInput, u as verifyRequest } from "./http-D8tiOrZf.mjs";
9
+ import { n as getAuthenticatedDocumentLoader } from "./docloader-B9iU4DP2.mjs";
10
+ import { n as kvCache } from "./kv-cache-BwUrzCVO.mjs";
11
11
  import { t as KvKeyCache } from "./keycache-BimEQucx.mjs";
12
- import { _ 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 } from "./ld-DUG6cq9q.mjs";
13
- import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-Baf_LRb2.mjs";
14
- import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-D4iTv7uM.mjs";
15
- import { i as verifyObject, n as hasProofLike, r as signObject } from "./proof-LTsbjXnQ.mjs";
16
- import { d as MAX_BODY_SIZE, f as readBoundedText, t as getNodeInfo, u as BodyTooLargeError } from "./client-DpUNYKla.mjs";
17
- import { t as nodeInfoToJson } from "./types-J53Kw7so.mjs";
18
- import { i as sendActivity, n as extractInboxes, t as SendActivityError } from "./send-DOf5y1nB.mjs";
19
- import { n as FederationBuilderImpl, t as ACTOR_ALIAS_PREFIX } from "./builder-G4wSHQX-.mjs";
20
- import { t as CircuitBreaker } from "./circuit-breaker-D1fxthDI.mjs";
21
- import { t as buildCollectionSynchronizationHeader } from "./collection-Cc3DVAhE.mjs";
22
- import { n as routeActivity, t as actorsHaveSameOrigin } from "./inbox-Bx6PCMeE.mjs";
23
- import { t as acceptsJsonLd } from "./negotiation-DDstyBvc.mjs";
24
- import { t as hasMalformedKnownTemporalLiteral } from "./temporal-fl4sM1Gs.mjs";
25
- import { t as createExponentialBackoffPolicy } from "./retry-CXg_MBI-.mjs";
12
+ import { a as compactJsonLd, c as detachSignature, d as hasSignatureLike, f as hasVerifiableSignature, g as verifyCompactJsonLd, h as signJsonLd, l as getNormalizationContextLoader, m as isInvalidUrlTypeError, p as isClearlyMalformedContextReference, r as assertSafeJsonLd, s as describeSignatureShape, t as InvalidContextReferenceError, y as wrapContextLoaderForJsonLd } from "./ld-DCKrqj9y.mjs";
13
+ import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-Bdj0nHhf.mjs";
14
+ import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-BZEAVK_Q.mjs";
15
+ import { i as verifyObject, n as hasProofLike, r as signObject } from "./proof-DrbjYma9.mjs";
16
+ import { d as MAX_BODY_SIZE, f as readBoundedText, t as getNodeInfo, u as BodyTooLargeError } from "./client-DFgYVbUA.mjs";
17
+ import { t as nodeInfoToJson } from "./types-BFowWFTT.mjs";
18
+ import { i as sendActivity, n as extractInboxes, t as SendActivityError } from "./send-VD_WG3dN.mjs";
19
+ import { n as FederationBuilderImpl, t as ACTOR_ALIAS_PREFIX } from "./builder-D4GE1Gmi.mjs";
20
+ import { t as CircuitBreaker } from "./circuit-breaker-B1fLHmg2.mjs";
21
+ import { t as buildCollectionSynchronizationHeader } from "./collection-Dp5ky45w.mjs";
22
+ import { t as normalizeAttachmentArrays } from "./attachment-arrays-BlfpZlWF.mjs";
23
+ import { n as routeActivity, t as actorsHaveSameOrigin } from "./inbox-Dy8awbi8.mjs";
24
+ import { t as acceptsJsonLd } from "./negotiation-DC8nG6J_.mjs";
25
+ import { t as hasMalformedKnownTemporalLiteral } from "./temporal-CMvoB-vD.mjs";
26
+ import { t as createExponentialBackoffPolicy } from "./retry-C4G_vIgv.mjs";
26
27
  import { getLogger, withContext } from "@logtape/logtape";
27
28
  import { RouterError } from "@fedify/uri-template";
28
- import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
29
+ import { Activity, Collection, CollectionPage, CryptographicKey, DataIntegrityProof, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
29
30
  import { lookupWebFinger } from "@fedify/webfinger";
30
31
  import { SpanKind, SpanStatusCode, context, metrics, propagation, trace } from "@opentelemetry/api";
31
- import { FetchError, getDocumentLoader } from "@fedify/vocab-runtime";
32
+ import { FetchError, encodeMultibase, getDocumentLoader } from "@fedify/vocab-runtime";
33
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
32
34
  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";
35
+ import { encodeHex } from "byte-encodings/hex";
33
36
  import { uniq } from "es-toolkit";
37
+ import serialize from "json-canon";
34
38
  import { DataPointType, MeterProvider as MeterProvider$1, MetricReader } from "@opentelemetry/sdk-metrics";
35
39
  import { domainToASCII } from "node:url";
40
+ //#region src/sig/proof-creation.ts
41
+ /** Signs the exact serialized message supplied by an internal producer. */
42
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
43
+ validateCryptoKey(privateKey, "private");
44
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
45
+ const encoder = new TextEncoder();
46
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(jsonLd)));
47
+ created ??= Temporal.Now.instant();
48
+ const proofConfig = {
49
+ "@context": jsonLd["@context"],
50
+ type: "DataIntegrityProof",
51
+ cryptosuite: "eddsa-jcs-2022",
52
+ verificationMethod: keyId.href,
53
+ proofPurpose: "assertionMethod",
54
+ created: created.toString()
55
+ };
56
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(proofConfig)));
57
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
58
+ digest.set(new Uint8Array(proofDigest), 0);
59
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
60
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
61
+ return new DataIntegrityProof({
62
+ cryptosuite: "eddsa-jcs-2022",
63
+ verificationMethod: keyId,
64
+ proofPurpose: "assertionMethod",
65
+ created,
66
+ proofValue: new Uint8Array(sig)
67
+ });
68
+ }
69
+ //#endregion
70
+ //#region src/compat/delivery-jsonld.ts
71
+ /**
72
+ * Returns changed wire JSON only; unchanged documents keep the existing
73
+ * delivery signing path. This uses ordinary vocabulary serialization, without
74
+ * retaining or repairing independently signed child representations.
75
+ */
76
+ async function prepareActivityJsonLd(activity, contextLoader) {
77
+ if (activity.proofIds.length > 0) return void 0;
78
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
79
+ const source = await activity.clone().toJsonLd({
80
+ format: "compact",
81
+ contextLoader
82
+ });
83
+ const prepared = await normalizeOutgoingActivityJsonLd(source, contextLoader, true);
84
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
85
+ }
86
+ /** Signs a changed, proof-free delivery map without serializing it again. */
87
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
88
+ const proofs = [];
89
+ const serializedProofs = [];
90
+ const tracer = (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version);
91
+ for (const { privateKey, keyId } of keys) {
92
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(activity).href } }, async (span) => {
93
+ try {
94
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
95
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
96
+ if (span.isRecording()) {
97
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
98
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
99
+ span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
100
+ }
101
+ return proof;
102
+ } catch (error) {
103
+ span.setStatus({
104
+ code: SpanStatusCode.ERROR,
105
+ message: String(error)
106
+ });
107
+ throw error;
108
+ } finally {
109
+ span.end();
110
+ }
111
+ });
112
+ proofs.push(proof);
113
+ serializedProofs.push({
114
+ "@context": unsigned["@context"],
115
+ type: "DataIntegrityProof",
116
+ cryptosuite: proof.cryptosuite,
117
+ verificationMethod: keyId.href,
118
+ proofPurpose: "assertionMethod",
119
+ created: proof.created.toString(),
120
+ proofValue: new TextDecoder().decode(encodeMultibase("base58btc", proof.proofValue))
121
+ });
122
+ }
123
+ if (proofs.length === 0) return {
124
+ activity,
125
+ jsonLd: unsigned
126
+ };
127
+ return {
128
+ activity: activity.clone({ proofs }),
129
+ jsonLd: {
130
+ ...unsigned,
131
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
132
+ }
133
+ };
134
+ }
135
+ //#endregion
36
136
  //#region src/compat/transformers.ts
37
137
  const logger$1 = getLogger([
38
138
  "fedify",
@@ -407,7 +507,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
407
507
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
408
508
  }
409
509
  if (actor instanceof Tombstone) {
410
- const jsonLd = await actor.toJsonLd(context);
510
+ const jsonLd = await serializeForResponse(actor, context);
411
511
  return new Response(JSON.stringify(jsonLd), {
412
512
  status: 410,
413
513
  headers: {
@@ -416,7 +516,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
416
516
  }
417
517
  });
418
518
  }
419
- const jsonLd = await actor.toJsonLd(context);
519
+ const jsonLd = await serializeForResponse(actor, context);
420
520
  return new Response(JSON.stringify(jsonLd), { headers: {
421
521
  "Content-Type": "application/activity+json",
422
522
  Vary: "Accept"
@@ -436,7 +536,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
436
536
  if (authorizePredicate != null) {
437
537
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
438
538
  }
439
- const jsonLd = await object.toJsonLd(context);
539
+ const jsonLd = await serializeForResponse(object, context);
440
540
  return new Response(JSON.stringify(jsonLd), { headers: {
441
541
  "Content-Type": "application/activity+json",
442
542
  Vary: "Accept"
@@ -479,13 +579,13 @@ function recordCollectionMetrics(meterProvider, base, result, options = {}) {
479
579
  * @param parameters The parameters for handling the collection.
480
580
  * @returns A promise that resolves to an HTTP response.
481
581
  */
482
- async function handleCollection(request, { name: name$1, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
483
- const spanName = name$1.trim().replace(/\s+/g, "_");
582
+ async function handleCollection(request, { name: name$2, identifier, uriGetter, filter, filterPredicate, context, collectionCallbacks, tracerProvider, meterProvider, onUnauthorized, onNotFound }) {
583
+ const spanName = name$2.trim().replace(/\s+/g, "_");
484
584
  tracerProvider = tracerProvider ?? trace.getTracerProvider();
485
585
  const tracer = tracerProvider.getTracer(name, version);
486
586
  const cursor = new URL(request.url).searchParams.get("cursor");
487
587
  const metricBase = {
488
- kind: getCollectionMetricKind(name$1),
588
+ kind: getCollectionMetricKind(name$2),
489
589
  page: cursor != null,
490
590
  dispatcher: "built_in"
491
591
  };
@@ -526,7 +626,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
526
626
  span.setStatus({ code: SpanStatusCode.ERROR });
527
627
  return await onNotFound(request);
528
628
  }
529
- const items = filterCollectionItems(page.items, name$1, filterPredicate);
629
+ const items = filterCollectionItems(page.items, name$2, filterPredicate);
530
630
  itemCount = items.length;
531
631
  span.setAttribute("fedify.collection.items", itemCount);
532
632
  return items;
@@ -566,7 +666,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
566
666
  } else {
567
667
  const uri = new URL(baseUri);
568
668
  uri.searchParams.set("cursor", cursor);
569
- const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$1}`, {
669
+ const pageOrResponse = await tracer.startActiveSpan(`activitypub.dispatch_collection_page ${name$2}`, {
570
670
  kind: SpanKind.SERVER,
571
671
  attributes: {
572
672
  "activitypub.collection.id": uri.href,
@@ -582,7 +682,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
582
682
  span.setStatus({ code: SpanStatusCode.ERROR });
583
683
  return await onNotFound(request);
584
684
  }
585
- const items = filterCollectionItems(page.items, name$1, filterPredicate);
685
+ const items = filterCollectionItems(page.items, name$2, filterPredicate);
586
686
  itemCount = items.length;
587
687
  span.setAttribute("fedify.collection.items", itemCount);
588
688
  return {
@@ -625,7 +725,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
625
725
  if (collectionCallbacks.authorizePredicate != null) {
626
726
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return finish(await onUnauthorized(request), "unauthorized");
627
727
  }
628
- const jsonLd = await collection.toJsonLd(context);
728
+ const jsonLd = await serializeForResponse(collection, context);
629
729
  return finish(new Response(JSON.stringify(jsonLd), { headers: {
630
730
  "Content-Type": "application/activity+json",
631
731
  Vary: "Accept"
@@ -982,7 +1082,11 @@ async function handleInboxInternal(request, parameters, span) {
982
1082
  }
983
1083
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
984
1084
  const jsonWithoutSig = detachSignature(json);
985
- const hasLdSignature = hasSignature(json);
1085
+ const hasLdSignature = hasVerifiableSignature(json);
1086
+ if (!hasLdSignature) {
1087
+ const shape = describeSignatureShape(json);
1088
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
1089
+ }
986
1090
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
987
1091
  let deferredLdSignatureError = void 0;
988
1092
  const respondInvalidActivity = async (error) => {
@@ -1488,8 +1592,8 @@ var CustomCollectionHandler = class {
1488
1592
  * @param CollectionPage The CollectionPage constructor.
1489
1593
  * @param filterPredicate Optional filter predicate for items.
1490
1594
  */
1491
- constructor(name$2, values, context, callbacks, tracerProvider = trace.getTracerProvider(), meterProvider, Collection, CollectionPage, filterPredicate) {
1492
- this.name = name$2;
1595
+ constructor(name$1, values, context, callbacks, tracerProvider = trace.getTracerProvider(), meterProvider, Collection, CollectionPage, filterPredicate) {
1596
+ this.name = name$1;
1493
1597
  this.values = values;
1494
1598
  this.context = context;
1495
1599
  this.callbacks = callbacks;
@@ -1508,7 +1612,7 @@ var CustomCollectionHandler = class {
1508
1612
  * @returns A promise that resolves to the JSON-LD representation.
1509
1613
  */
1510
1614
  async toJsonLd() {
1511
- return (await this.collection).toJsonLd(this.context);
1615
+ return serializeForResponse(await this.collection, this.context);
1512
1616
  }
1513
1617
  /**
1514
1618
  * Fetches the collection with optional cursor for pagination.
@@ -1885,7 +1989,7 @@ var UnauthorizedError = class extends HandlerError {
1885
1989
  * @since 0.3.0
1886
1990
  */
1887
1991
  async function respondWithObject(object, options) {
1888
- const jsonLd = await object.toJsonLd(options);
1992
+ const jsonLd = await serializeForResponse(object, options);
1889
1993
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
1890
1994
  }
1891
1995
  /**
@@ -1973,6 +2077,10 @@ const MIN_COMPONENTS = [
1973
2077
  "@target-uri",
1974
2078
  "@authority"
1975
2079
  ];
2080
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
2081
+ async function serializeForResponse(object, options) {
2082
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
2083
+ }
1976
2084
  //#endregion
1977
2085
  //#region src/federation/webfinger.ts
1978
2086
  const logger = getLogger([
@@ -2537,8 +2645,25 @@ var FederationImpl = class extends FederationBuilderImpl {
2537
2645
  _getTracer() {
2538
2646
  return this.tracerProvider.getTracer(name, version);
2539
2647
  }
2648
+ /**
2649
+ * Starts listening on a queue, converting a synchronous throw into
2650
+ * a rejected promise.
2651
+ *
2652
+ * `MessageQueue.listen()` is documented to never reject, but some
2653
+ * implementations (e.g., `WorkersMessageQueue`) throw synchronously. Without
2654
+ * this normalization, one such throw aborts {@link _startQueueInternal} while
2655
+ * it is still collecting listener promises, so listeners started earlier are
2656
+ * never awaited and later queues are never started.
2657
+ */
2658
+ #listenQueue(queue, ctxData, signal) {
2659
+ try {
2660
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
2661
+ } catch (error) {
2662
+ return Promise.reject(error);
2663
+ }
2664
+ }
2540
2665
  async _startQueueInternal(ctxData, signal, queue) {
2541
- if (this.inboxQueue == null && this.outboxQueue == null) return;
2666
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
2542
2667
  const logger = getLogger([
2543
2668
  "fedify",
2544
2669
  "federation",
@@ -2548,20 +2673,38 @@ var FederationImpl = class extends FederationBuilderImpl {
2548
2673
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
2549
2674
  logger.debug("Starting an inbox task worker.");
2550
2675
  this.inboxQueueStarted = true;
2551
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2676
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
2552
2677
  }
2553
2678
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
2554
2679
  logger.debug("Starting an outbox task worker.");
2555
2680
  this.outboxQueueStarted = true;
2556
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2681
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
2557
2682
  }
2558
2683
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
2559
2684
  logger.debug("Starting a fanout task worker.");
2560
2685
  this.fanoutQueueStarted = true;
2561
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2686
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
2562
2687
  }
2563
2688
  await Promise.all(promises);
2564
2689
  }
2690
+ /**
2691
+ * Starts the queue workers automatically, reporting a failure instead of
2692
+ * leaving the returned promise unobserved.
2693
+ *
2694
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
2695
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
2696
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
2697
+ * callers that start workers deliberately.
2698
+ */
2699
+ _startQueueAutomatically(ctxData) {
2700
+ this._startQueueInternal(ctxData).catch((error) => {
2701
+ getLogger([
2702
+ "fedify",
2703
+ "federation",
2704
+ "queue"
2705
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
2706
+ });
2707
+ }
2565
2708
  processQueuedTask(contextData, message) {
2566
2709
  const tracer = this._getTracer();
2567
2710
  const extractedContext = propagation.extract(context.active(), message.traceContext);
@@ -2716,7 +2859,8 @@ var FederationImpl = class extends FederationBuilderImpl {
2716
2859
  collectionSync: message.collectionSync,
2717
2860
  orderingKey: message.orderingKey,
2718
2861
  normalizeExistingProofs: message.normalizeExistingProofs,
2719
- context
2862
+ context,
2863
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
2720
2864
  });
2721
2865
  }
2722
2866
  async #listenOutboxMessage(_, message, span) {
@@ -3129,7 +3273,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3129
3273
  let parseInput = void 0;
3130
3274
  let parseContextLoader = context.contextLoader;
3131
3275
  try {
3132
- const hasSignatureField = hasSignature(message.activity);
3276
+ const hasSignatureField = hasVerifiableSignature(message.activity);
3133
3277
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
3134
3278
  const parseContext = hasSignatureField ? {
3135
3279
  ...context,
@@ -3341,21 +3485,31 @@ var FederationImpl = class extends FederationBuilderImpl {
3341
3485
  hasProof = true;
3342
3486
  break;
3343
3487
  }
3344
- if (!hasProof) {
3345
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3346
- activity = await signObject(activity, privateKey, keyId, {
3347
- contextLoader,
3348
- tracerProvider: this.tracerProvider
3349
- });
3350
- hasProof = true;
3351
- proofCreated = true;
3488
+ const prepared = !hasProof && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
3489
+ let jsonLd;
3490
+ if (prepared != null) {
3491
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
3492
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
3493
+ activity = signed.activity;
3494
+ jsonLd = signed.jsonLd;
3495
+ proofCreated = signingKeys.length > 0;
3496
+ } else {
3497
+ if (!hasProof) {
3498
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3499
+ activity = await signObject(activity, privateKey, keyId, {
3500
+ contextLoader,
3501
+ tracerProvider: this.tracerProvider
3502
+ });
3503
+ proofCreated = true;
3504
+ }
3352
3505
  }
3506
+ jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
3507
+ format: "compact",
3508
+ contextLoader
3509
+ });
3353
3510
  }
3354
- let jsonLd = await activity.toJsonLd({
3355
- format: "compact",
3356
- contextLoader
3357
- });
3358
- if (proofCreated || !hasProof || options.normalizeExistingProofs) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
3511
+ if (prepared == null && (proofCreated || !hasProof || options.normalizeExistingProofs)) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
3512
+ hasProof ||= proofCreated;
3359
3513
  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.", {
3360
3514
  activityId,
3361
3515
  keys: keys.map((pair) => ({
@@ -3392,20 +3546,28 @@ var FederationImpl = class extends FederationBuilderImpl {
3392
3546
  activity: jsonLd
3393
3547
  });
3394
3548
  const promises = [];
3395
- for (const inbox in inboxes) promises.push(sendActivity({
3396
- allowPrivateAddress: this.allowPrivateAddress,
3397
- keys,
3398
- activity: jsonLd,
3399
- activityId: activity.id?.href,
3400
- activityType: getTypeId(activity).href,
3401
- inbox: new URL(inbox),
3402
- sharedInbox: inboxes[inbox].sharedInbox,
3403
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3404
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3405
- meterProvider: this.meterProvider,
3406
- tracerProvider: this.tracerProvider
3407
- }));
3408
- await Promise.all(promises);
3549
+ try {
3550
+ for (const inbox in inboxes) {
3551
+ const promise = sendActivity({
3552
+ allowPrivateAddress: this.allowPrivateAddress,
3553
+ keys,
3554
+ activity: jsonLd,
3555
+ activityId: activity.id?.href,
3556
+ activityType: getTypeId(activity).href,
3557
+ inbox: new URL(inbox),
3558
+ sharedInbox: inboxes[inbox].sharedInbox,
3559
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3560
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3561
+ meterProvider: this.meterProvider,
3562
+ tracerProvider: this.tracerProvider
3563
+ });
3564
+ promise.catch(() => {});
3565
+ promises.push(promise);
3566
+ }
3567
+ await Promise.all(promises);
3568
+ } finally {
3569
+ await Promise.allSettled(promises);
3570
+ }
3409
3571
  return;
3410
3572
  }
3411
3573
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -3420,7 +3582,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3420
3582
  privateKey: privateKeyJwk
3421
3583
  });
3422
3584
  }
3423
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
3585
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
3424
3586
  const carrier = {};
3425
3587
  propagation.inject(context.active(), carrier);
3426
3588
  const messages = [];
@@ -3679,7 +3841,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3679
3841
  const identity = await this.sharedInboxKeyDispatcher(context);
3680
3842
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
3681
3843
  }
3682
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
3844
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
3683
3845
  const inboxContextFactory = context.toInboxContext.bind(context);
3684
3846
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
3685
3847
  return await handleInbox(request, {
@@ -4069,6 +4231,8 @@ var ContextImpl = class ContextImpl {
4069
4231
  for (const keyPair of keyPairs) {
4070
4232
  const newPair = {
4071
4233
  ...keyPair,
4234
+ privateKey: asCryptoKey(keyPair.privateKey),
4235
+ publicKey: asCryptoKey(keyPair.publicKey),
4072
4236
  cryptographicKey: new CryptographicKey({
4073
4237
  id: keyPair.keyId,
4074
4238
  owner,
@@ -4145,10 +4309,16 @@ var ContextImpl = class ContextImpl {
4145
4309
  } else identifierPromise = Promise.resolve(identity.identifier);
4146
4310
  return identifierPromise.then((identifier) => {
4147
4311
  if (identifier == null) return this.documentLoader;
4148
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
4312
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
4313
+ keyId: pair.keyId,
4314
+ privateKey: asCryptoKey(pair.privateKey)
4315
+ }));
4149
4316
  });
4150
4317
  }
4151
- return this.federation.authenticatedDocumentLoaderFactory(identity);
4318
+ return this.federation.authenticatedDocumentLoaderFactory({
4319
+ keyId: identity.keyId,
4320
+ privateKey: asCryptoKey(identity.privateKey)
4321
+ });
4152
4322
  }
4153
4323
  lookupObject(identifier, options = {}) {
4154
4324
  return lookupObject(identifier, {
@@ -4172,10 +4342,14 @@ var ContextImpl = class ContextImpl {
4172
4342
  return options.parse === "none" ? getNodeInfo(url, {
4173
4343
  parse: "none",
4174
4344
  direct: options.direct,
4345
+ timeout: options.timeout,
4346
+ signal: options.signal,
4175
4347
  userAgent: options?.userAgent ?? this.federation.userAgent
4176
4348
  }) : getNodeInfo(url, {
4177
4349
  parse: options.parse,
4178
4350
  direct: options.direct,
4351
+ timeout: options.timeout,
4352
+ signal: options.signal,
4179
4353
  userAgent: options?.userAgent ?? this.federation.userAgent
4180
4354
  });
4181
4355
  }
@@ -4188,7 +4362,17 @@ var ContextImpl = class ContextImpl {
4188
4362
  allowPrivateAddress: this.federation.allowPrivateAddress
4189
4363
  });
4190
4364
  }
4191
- sendActivity(sender, recipients, activity, options = {}) {
4365
+ async sendActivity(sender, recipients, activity, options = {}) {
4366
+ let activityJsonLd = void 0;
4367
+ let hasProof = activity.proofIds.length > 0;
4368
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
4369
+ hasProof = true;
4370
+ break;
4371
+ }
4372
+ if (hasProof) {
4373
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
4374
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
4375
+ }
4192
4376
  return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
4193
4377
  kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
4194
4378
  attributes: {
@@ -4201,7 +4385,7 @@ var ContextImpl = class ContextImpl {
4201
4385
  }, async (span) => {
4202
4386
  try {
4203
4387
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
4204
- await this.sendActivityInternal(sender, recipients, activity, options, span);
4388
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
4205
4389
  } catch (e) {
4206
4390
  span.setStatus({
4207
4391
  code: SpanStatusCode.ERROR,
@@ -4213,7 +4397,7 @@ var ContextImpl = class ContextImpl {
4213
4397
  }
4214
4398
  });
4215
4399
  }
4216
- async sendActivityInternal(sender, recipients, activity, options, span) {
4400
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
4217
4401
  const logger = getLogger([
4218
4402
  "fedify",
4219
4403
  "federation",
@@ -4260,15 +4444,23 @@ var ContextImpl = class ContextImpl {
4260
4444
  if (!(error instanceof RouterError)) throw error;
4261
4445
  }
4262
4446
  } else expandedRecipients = [recipients];
4263
- const opts = {
4264
- context: this,
4265
- orderingKey: options.orderingKey,
4266
- collectionSync,
4267
- immediate: options.immediate,
4268
- normalizeExistingProofs: options.normalizeExistingProofs
4269
- };
4270
4447
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
4271
4448
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
4449
+ let contextMatches = false;
4450
+ if (activityJsonLd != null) {
4451
+ const capturedJsonLd = activityJsonLd;
4452
+ const transformedJsonLd = await activity.toJsonLd({
4453
+ format: "compact",
4454
+ contextLoader: this.contextLoader
4455
+ });
4456
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
4457
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
4458
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
4459
+ if (contentChanged || !contextMatches && proofsChanged) {
4460
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) });
4461
+ activityJsonLd = void 0;
4462
+ } else if (proofsChanged) activityJsonLd = void 0;
4463
+ }
4272
4464
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
4273
4465
  if (activity.actorId == null) {
4274
4466
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -4280,15 +4472,42 @@ var ContextImpl = class ContextImpl {
4280
4472
  let proofCreated = false;
4281
4473
  if (actorKeyPairs != null) {
4282
4474
  const contextLoader = this.contextLoader;
4283
- for (const kp of actorKeyPairs) {
4284
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4285
- activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4286
- contextLoader,
4287
- tracerProvider: this.tracerProvider
4288
- });
4289
- proofCreated = true;
4475
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
4476
+ if (willSign) {
4477
+ if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
4478
+ }
4479
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
4480
+ if (prepared != null) {
4481
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
4482
+ privateKey: kp.privateKey,
4483
+ keyId: kp.multikey.id
4484
+ }] : []);
4485
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
4486
+ activity = signed.activity;
4487
+ activityJsonLd = signed.jsonLd;
4488
+ proofCreated = signingKeys.length > 0;
4489
+ } else {
4490
+ let proofAdded = false;
4491
+ for (const kp of actorKeyPairs) {
4492
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4493
+ activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4494
+ contextLoader,
4495
+ tracerProvider: this.tracerProvider
4496
+ });
4497
+ proofAdded = true;
4498
+ }
4499
+ if (proofAdded) activityJsonLd = void 0;
4500
+ proofCreated = proofAdded;
4290
4501
  }
4291
4502
  }
4503
+ const opts = {
4504
+ context: this,
4505
+ orderingKey: options.orderingKey,
4506
+ collectionSync,
4507
+ immediate: options.immediate,
4508
+ activityJsonLd,
4509
+ normalizeExistingProofs: options.normalizeExistingProofs
4510
+ };
4292
4511
  const inboxes = extractInboxes({
4293
4512
  recipients: expandedRecipients,
4294
4513
  preferSharedInbox: options.preferSharedInbox,
@@ -4328,7 +4547,7 @@ var ContextImpl = class ContextImpl {
4328
4547
  actorIds: [...actorIds],
4329
4548
  sharedInbox
4330
4549
  }])),
4331
- activity: await activity.toJsonLd({
4550
+ activity: activityJsonLd != null ? detachSignature(activityJsonLd) : await activity.toJsonLd({
4332
4551
  format: "compact",
4333
4552
  contextLoader: this.contextLoader
4334
4553
  }),
@@ -4339,7 +4558,7 @@ var ContextImpl = class ContextImpl {
4339
4558
  normalizeExistingProofs: proofCreated || options.normalizeExistingProofs,
4340
4559
  traceContext: carrier
4341
4560
  };
4342
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
4561
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
4343
4562
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
4344
4563
  getFederationMetrics(this.federation.meterProvider).recordQueueTaskEnqueued({
4345
4564
  role: "fanout",
@@ -4675,7 +4894,7 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
4675
4894
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
4676
4895
  keys = forwarder;
4677
4896
  } else keys = [forwarder];
4678
- if (!hasSignatureLike(ctx.activity)) {
4897
+ if (!hasVerifiableSignature(ctx.activity) && !hasSignatureLike(ctx.activity)) {
4679
4898
  if (!hasProofLike(ctx.activity)) {
4680
4899
  if (options?.skipIfUnsigned) return false;
4681
4900
  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.", {
@@ -4713,26 +4932,34 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
4713
4932
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
4714
4933
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
4715
4934
  const promises = [];
4716
- for (const inbox in inboxes) promises.push(sendActivity({
4717
- allowPrivateAddress: ctx.federation.allowPrivateAddress,
4718
- keys,
4719
- activity: ctx.activity,
4720
- activityId: ctx.activityId,
4721
- activityType: ctx.activityType,
4722
- inbox: new URL(inbox),
4723
- sharedInbox: inboxes[inbox].sharedInbox,
4724
- meterProvider: ctx.meterProvider,
4725
- tracerProvider: ctx.tracerProvider,
4726
- specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
4727
- }));
4728
- await Promise.all(promises);
4935
+ try {
4936
+ for (const inbox in inboxes) {
4937
+ const promise = sendActivity({
4938
+ allowPrivateAddress: ctx.federation.allowPrivateAddress,
4939
+ keys,
4940
+ activity: ctx.activity,
4941
+ activityId: ctx.activityId,
4942
+ activityType: ctx.activityType,
4943
+ inbox: new URL(inbox),
4944
+ sharedInbox: inboxes[inbox].sharedInbox,
4945
+ meterProvider: ctx.meterProvider,
4946
+ tracerProvider: ctx.tracerProvider,
4947
+ specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
4948
+ });
4949
+ promise.catch(() => {});
4950
+ promises.push(promise);
4951
+ }
4952
+ await Promise.all(promises);
4953
+ } finally {
4954
+ await Promise.allSettled(promises);
4955
+ }
4729
4956
  return true;
4730
4957
  }
4731
4958
  logger.debug("Enqueuing activity {activityId} to forward later.", {
4732
4959
  activityId: ctx.activityId,
4733
4960
  activity: ctx.activity
4734
4961
  });
4735
- if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
4962
+ if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueAutomatically(ctx.data);
4736
4963
  const keyJwkPairs = [];
4737
4964
  for (const { keyId, privateKey } of keys) {
4738
4965
  const privateKeyJwk = await exportJwk(privateKey);
@@ -4909,6 +5136,69 @@ var KvSpecDeterminer = class {
4909
5136
  function notFound(_request) {
4910
5137
  return new Response("Not Found", { status: 404 });
4911
5138
  }
5139
+ function hasTopLevelProof(value) {
5140
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
5141
+ }
5142
+ function getContentFields(value) {
5143
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5144
+ const record = { ...value };
5145
+ delete record["@context"];
5146
+ delete record.proof;
5147
+ delete record.signature;
5148
+ return JSON.stringify(sortJsonKeys(record));
5149
+ }
5150
+ function getContextFields(value) {
5151
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5152
+ const context = value["@context"];
5153
+ return JSON.stringify(sortJsonKeys(context ?? null));
5154
+ }
5155
+ function getProofEntries(value) {
5156
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
5157
+ const proof = value.proof;
5158
+ if (proof == null) return [];
5159
+ return Array.isArray(proof) ? proof : [proof];
5160
+ }
5161
+ function normalizeProofEntry(proof) {
5162
+ const stripped = stripContexts(proof);
5163
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
5164
+ const record = { ...stripped };
5165
+ if (typeof record.created === "string") try {
5166
+ record.created = Temporal.Instant.from(record.created).toString();
5167
+ } catch {}
5168
+ return record;
5169
+ }
5170
+ function getProofEntryFields(proof) {
5171
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
5172
+ }
5173
+ function getProofFields(value) {
5174
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
5175
+ }
5176
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
5177
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
5178
+ const retainedProofs = [];
5179
+ for await (const proof of activity.getProofs({ contextLoader })) {
5180
+ const proofJsonLd = await proof.toJsonLd({
5181
+ format: "compact",
5182
+ contextLoader
5183
+ });
5184
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
5185
+ }
5186
+ return retainedProofs;
5187
+ }
5188
+ function stripContexts(value) {
5189
+ if (Array.isArray(value)) return value.map(stripContexts);
5190
+ if (typeof value !== "object" || value == null) return value;
5191
+ const record = { ...value };
5192
+ delete record["@context"];
5193
+ delete record.signature;
5194
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
5195
+ return record;
5196
+ }
5197
+ function sortJsonKeys(value) {
5198
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
5199
+ if (typeof value !== "object" || value == null) return value;
5200
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
5201
+ }
4912
5202
  function notAcceptable(_request) {
4913
5203
  return new Response("Not Acceptable", {
4914
5204
  status: 406,
@@ -4940,4 +5230,4 @@ function getRequestId(request) {
4940
5230
  return `req_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
4941
5231
  }
4942
5232
  //#endregion
4943
- export { handleNodeInfo as _, OutboxContextImpl as a, autoIdAssigner as b, handleActor as c, handleInbox as d, handleObject as f, handleBenchmarkTrigger as g, respondWithObjectIfAcceptable as h, KvSpecDeterminer as i, handleCollection as l, respondWithObject as m, FederationImpl as n, createFederation as o, handleOutbox as p, InboxContextImpl as r, handleWebFinger as s, ContextImpl as t, handleCustomCollection as u, handleNodeInfoJrd as v, actorDehydrator as y };
5233
+ export { handleNodeInfo as _, OutboxContextImpl as a, autoIdAssigner as b, handleActor as c, handleInbox as d, handleObject as f, handleBenchmarkTrigger as g, respondWithObjectIfAcceptable as h, KvSpecDeterminer as i, handleCollection as l, respondWithObject as m, FederationImpl as n, createFederation as o, handleOutbox as p, InboxContextImpl as r, handleWebFinger as s, ContextImpl as t, handleCustomCollection as u, handleNodeInfoJrd as v, prepareActivityJsonLd as x, actorDehydrator as y };