@fedify/fedify 2.2.19 → 2.2.21

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 (109) hide show
  1. package/dist/attachment-arrays-CalAATqD.mjs +16 -0
  2. package/dist/{builder-UmydCxtK.mjs → builder-4ImvtjG4.mjs} +3 -3
  3. package/dist/callback-0KrwzutD.d.mts +2607 -0
  4. package/dist/{client-CSddvgWN.d.ts → client-9DPcy_Yx.d.ts} +16 -1
  5. package/dist/{client-CAM_bQXx.d.cts → client-B3ruDgWg.d.cts} +16 -1
  6. package/dist/{client-9F_u23dc.mjs → client-XYMC0Mmk.mjs} +189 -65
  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-tJbL_Hkw.d.cts → context-CjWuov0g.d.cts} +57 -14
  15. package/dist/{context-OkwEpc3-.d.ts → context-DZqI2LJD.d.ts} +57 -14
  16. package/dist/{deno-CD-8UlUi.mjs → deno-AWk3S2Ug.mjs} +1 -1
  17. package/dist/docloader-Bogpjg4d.mjs +125 -0
  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/collection.test.mjs +1 -1
  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.test.mjs +208 -16
  25. package/dist/federation/idempotency.test.mjs +2 -2
  26. package/dist/federation/inbox.test.mjs +2 -2
  27. package/dist/federation/middleware.test.mjs +1567 -30
  28. package/dist/federation/mod.cjs +1 -1
  29. package/dist/federation/mod.d.cts +2 -2
  30. package/dist/federation/mod.d.ts +2 -2
  31. package/dist/federation/mod.js +1 -1
  32. package/dist/federation/negotiation.test.mjs +1 -1
  33. package/dist/federation/retry.test.mjs +1 -1
  34. package/dist/federation/send.test.mjs +723 -68
  35. package/dist/federation/temporal.test.mjs +25 -1
  36. package/dist/federation/webfinger.test.mjs +1 -1
  37. package/dist/{http-BBBUbwKh.mjs → http-B3wCvgu8.mjs} +199 -99
  38. package/dist/{http-DrUG4fPS.cjs → http-BNaPJVnF.cjs} +178 -107
  39. package/dist/{http-DJK2udgX.js → http-BpdLaGy8.js} +177 -106
  40. package/dist/{http-Dl00HXr4.d.ts → http-C8qLHs_Z.d.cts} +3 -4
  41. package/dist/{http-DqZhyEso.d.cts → http-D8WmcRAF.d.ts} +3 -4
  42. package/dist/{inbox-Dca_0fwc.mjs → inbox-DLy6WBXU.mjs} +1 -1
  43. package/dist/{key-DolXUaLH.mjs → key-Bhc8cQC7.mjs} +3 -2
  44. package/dist/{kv-cache-Bk3V1Tiu.cjs → kv-cache-Bj3CY9Jo.cjs} +59 -17
  45. package/dist/{kv-cache-DDm80t1K.js → kv-cache-CvjLUQTf.js} +60 -18
  46. package/dist/{ld-rTdIfZ63.mjs → ld-DTeykI0e.mjs} +153 -21
  47. package/dist/ld-signature-Dgz_b89j.mjs +23 -0
  48. package/dist/{middleware-BWOwEGpy.cjs → middleware-BSQP4d9p.cjs} +642 -149
  49. package/dist/{middleware-B4-Rzdi3.cjs → middleware-CWOzxb3o.cjs} +1 -1
  50. package/dist/{middleware-DYK_res8.mjs → middleware-DkMsC5mQ.mjs} +1 -1
  51. package/dist/{middleware-BimXKBcP.js → middleware-Dx1iwFk8.js} +641 -149
  52. package/dist/{middleware-CpXoRHs3.mjs → middleware-dlGvSrXl.mjs} +452 -122
  53. package/dist/{mod-D2JyWtW3.d.cts → mod-BmxqcEnU.d.ts} +30 -13
  54. package/dist/{mod-a6kmB8xD.d.cts → mod-DWEx2D4q.d.cts} +1 -1
  55. package/dist/{mod-DQGjRJUG.d.ts → mod-DnPmz3-S.d.ts} +1 -1
  56. package/dist/{mod-ej_rLx8h.d.ts → mod-INjDw-m0.d.cts} +30 -13
  57. package/dist/{mod-B6LmugJ4.d.ts → mod-REfljt0T.d.ts} +4 -10
  58. package/dist/{mod-V2vDnYNu.d.cts → mod-UvIGUHqW.d.cts} +4 -10
  59. package/dist/mod.cjs +5 -5
  60. package/dist/mod.d.cts +8 -8
  61. package/dist/mod.d.ts +8 -8
  62. package/dist/mod.js +5 -5
  63. package/dist/nodeinfo/client.test.mjs +764 -18
  64. package/dist/nodeinfo/handler.test.mjs +1 -1
  65. package/dist/nodeinfo/mod.cjs +1 -1
  66. package/dist/nodeinfo/mod.d.cts +1 -1
  67. package/dist/nodeinfo/mod.d.ts +1 -1
  68. package/dist/nodeinfo/mod.js +1 -1
  69. package/dist/nodeinfo/types.test.mjs +1 -1
  70. package/dist/otel/exporter.test.mjs +292 -30
  71. package/dist/otel/mod.cjs +36 -30
  72. package/dist/otel/mod.d.cts +13 -0
  73. package/dist/otel/mod.d.ts +13 -0
  74. package/dist/otel/mod.js +36 -30
  75. package/dist/{outgoing-jsonld-amccRMrV.mjs → outgoing-jsonld-DHf_DYXp.mjs} +38 -8
  76. package/dist/{owner-CVfzyM5V.mjs → owner-BsA7qMHB.mjs} +2 -2
  77. package/dist/{proof-gOGM-sJS.mjs → proof-C63Hqt9N.mjs} +40 -15
  78. package/dist/{proof-DhaTTn-P.cjs → proof-Dbz6ApNP.cjs} +1190 -1007
  79. package/dist/{proof-CaQ4KG6y.js → proof-QV_o5ZqS.js} +1174 -1003
  80. package/dist/send-CAdpwbFX.mjs +416 -0
  81. package/dist/sig/http.test.mjs +528 -2
  82. package/dist/sig/key-types.test.d.mts +218 -0
  83. package/dist/sig/key-types.test.mjs +8 -0
  84. package/dist/sig/key.test.mjs +2 -2
  85. package/dist/sig/ld.test.mjs +573 -8
  86. package/dist/sig/mod.cjs +2 -2
  87. package/dist/sig/mod.d.cts +3 -3
  88. package/dist/sig/mod.d.ts +3 -3
  89. package/dist/sig/mod.js +2 -2
  90. package/dist/sig/owner.test.mjs +1 -1
  91. package/dist/sig/proof.test.mjs +96 -4
  92. package/dist/{temporal-CA4Y9hBJ.mjs → temporal-B3JGkVgk.mjs} +3 -5
  93. package/dist/testing/mod.d.mts +1 -2396
  94. package/dist/{types-DRPjmHVV.cjs → types-BWx7zw3Y.cjs} +187 -63
  95. package/dist/{types-miAYfiGO.js → types-Dx_w2JSM.js} +188 -64
  96. package/dist/utils/docloader.test.mjs +318 -34
  97. package/dist/utils/mod.cjs +1 -1
  98. package/dist/utils/mod.d.cts +1 -1
  99. package/dist/utils/mod.d.ts +1 -1
  100. package/dist/utils/mod.js +1 -1
  101. package/package.json +6 -6
  102. package/dist/docloader-D1ghurDJ.mjs +0 -83
  103. package/dist/send-D35Va72B.mjs +0 -260
  104. /package/dist/{activity-listener-ell7W1s9.mjs → activity-listener-tztVvlNb.mjs} +0 -0
  105. /package/dist/{collection-D-HqUuA2.mjs → collection-CA3V5zyK.mjs} +0 -0
  106. /package/dist/{negotiation-SQvQgUqe.mjs → negotiation-VnHNB0Q5.mjs} +0 -0
  107. /package/dist/{public-audience-DpJqzPuh.mjs → public-audience-4g3_Ze4y.mjs} +0 -0
  108. /package/dist/{retry-v_sGLH1d.mjs → retry-CXg_MBI-.mjs} +0 -0
  109. /package/dist/{types-J53Kw7so.mjs → types-BFowWFTT.mjs} +0 -0
@@ -2,34 +2,134 @@ import { Temporal } from "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
4
  import { n as RouterError } from "./router-CrMLXoOr.mjs";
5
- import { n as version, t as name } from "./deno-CD-8UlUi.mjs";
5
+ import { n as version, t as name } from "./deno-AWk3S2Ug.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-DolXUaLH.mjs";
8
- import { l as verifyRequest, o as parseRfc9421SignatureInput, u as verifyRequestDetailed } from "./http-BBBUbwKh.mjs";
9
- import { t as getAuthenticatedDocumentLoader } from "./docloader-D1ghurDJ.mjs";
7
+ import { o as importJwk, s as validateCryptoKey, t as exportJwk } from "./key-Bhc8cQC7.mjs";
8
+ import { d as verifyRequestDetailed, s as parseRfc9421SignatureInput, u as verifyRequest } from "./http-B3wCvgu8.mjs";
9
+ import { n as getAuthenticatedDocumentLoader } from "./docloader-Bogpjg4d.mjs";
10
10
  import { n as kvCache } from "./kv-cache-FsT1ljhs.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-rTdIfZ63.mjs";
13
- import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-CVfzyM5V.mjs";
14
- import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-amccRMrV.mjs";
15
- import { i as verifyObject, n as hasProofLike, r as signObject } from "./proof-gOGM-sJS.mjs";
16
- import { d as readBoundedText, l as BodyTooLargeError, t as getNodeInfo, u as MAX_BODY_SIZE } from "./client-9F_u23dc.mjs";
17
- import { t as nodeInfoToJson } from "./types-J53Kw7so.mjs";
18
- import { t as FederationBuilderImpl } from "./builder-UmydCxtK.mjs";
19
- import { t as buildCollectionSynchronizationHeader } from "./collection-D-HqUuA2.mjs";
20
- import { n as routeActivity, t as actorsHaveSameOrigin } from "./inbox-Dca_0fwc.mjs";
21
- import { t as acceptsJsonLd } from "./negotiation-SQvQgUqe.mjs";
22
- import { t as hasMalformedKnownTemporalLiteral } from "./temporal-CA4Y9hBJ.mjs";
23
- import { t as createExponentialBackoffPolicy } from "./retry-v_sGLH1d.mjs";
24
- import { n as extractInboxes, r as sendActivity, t as SendActivityError } from "./send-D35Va72B.mjs";
25
- import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
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-DTeykI0e.mjs";
13
+ import { n as getKeyOwner, t as doesActorOwnKey } from "./owner-BsA7qMHB.mjs";
14
+ import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-DHf_DYXp.mjs";
15
+ import { i as verifyObject, n as hasProofLike, r as signObject } from "./proof-C63Hqt9N.mjs";
16
+ import { d as MAX_BODY_SIZE, f as readBoundedText, t as getNodeInfo, u as BodyTooLargeError } from "./client-XYMC0Mmk.mjs";
17
+ import { t as nodeInfoToJson } from "./types-BFowWFTT.mjs";
18
+ import { t as FederationBuilderImpl } from "./builder-4ImvtjG4.mjs";
19
+ import { t as buildCollectionSynchronizationHeader } from "./collection-CA3V5zyK.mjs";
20
+ import { t as normalizeAttachmentArrays } from "./attachment-arrays-CalAATqD.mjs";
21
+ import { n as routeActivity, t as actorsHaveSameOrigin } from "./inbox-DLy6WBXU.mjs";
22
+ import { t as acceptsJsonLd } from "./negotiation-VnHNB0Q5.mjs";
23
+ import { t as hasMalformedKnownTemporalLiteral } from "./temporal-B3JGkVgk.mjs";
24
+ import { t as createExponentialBackoffPolicy } from "./retry-CXg_MBI-.mjs";
25
+ import { i as sendActivity, n as extractInboxes, t as SendActivityError } from "./send-CAdpwbFX.mjs";
26
+ import { Activity, Collection, CollectionPage, CryptographicKey, DataIntegrityProof, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
26
27
  import { lookupWebFinger } from "@fedify/webfinger";
27
28
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
28
29
  import { uniq } from "es-toolkit";
29
- import { FetchError, getDocumentLoader } from "@fedify/vocab-runtime";
30
+ import { FetchError, encodeMultibase, getDocumentLoader } from "@fedify/vocab-runtime";
31
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
30
32
  import { getLogger, withContext } from "@logtape/logtape";
31
33
  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";
34
+ import { encodeHex } from "byte-encodings/hex";
35
+ import serialize from "json-canon";
32
36
  import { domainToASCII } from "node:url";
37
+ //#region src/sig/proof-creation.ts
38
+ /** Signs the exact serialized message supplied by an internal producer. */
39
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
40
+ validateCryptoKey(privateKey, "private");
41
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
42
+ const encoder = new TextEncoder();
43
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(jsonLd)));
44
+ created ??= Temporal.Now.instant();
45
+ const proofConfig = {
46
+ "@context": jsonLd["@context"],
47
+ type: "DataIntegrityProof",
48
+ cryptosuite: "eddsa-jcs-2022",
49
+ verificationMethod: keyId.href,
50
+ proofPurpose: "assertionMethod",
51
+ created: created.toString()
52
+ };
53
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(proofConfig)));
54
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
55
+ digest.set(new Uint8Array(proofDigest), 0);
56
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
57
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
58
+ return new DataIntegrityProof({
59
+ cryptosuite: "eddsa-jcs-2022",
60
+ verificationMethod: keyId,
61
+ proofPurpose: "assertionMethod",
62
+ created,
63
+ proofValue: new Uint8Array(sig)
64
+ });
65
+ }
66
+ //#endregion
67
+ //#region src/compat/delivery-jsonld.ts
68
+ /**
69
+ * Returns changed wire JSON only; unchanged documents keep the existing
70
+ * delivery signing path. This uses ordinary vocabulary serialization, without
71
+ * retaining or repairing independently signed child representations.
72
+ */
73
+ async function prepareActivityJsonLd(activity, contextLoader) {
74
+ if (activity.proofIds.length > 0) return void 0;
75
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
76
+ const source = await activity.clone().toJsonLd({
77
+ format: "compact",
78
+ contextLoader
79
+ });
80
+ const prepared = await normalizeOutgoingActivityJsonLd(source, contextLoader, true);
81
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
82
+ }
83
+ /** Signs a changed, proof-free delivery map without serializing it again. */
84
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
85
+ const proofs = [];
86
+ const serializedProofs = [];
87
+ const tracer = (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version);
88
+ for (const { privateKey, keyId } of keys) {
89
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(activity).href } }, async (span) => {
90
+ try {
91
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
92
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
93
+ if (span.isRecording()) {
94
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
95
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
96
+ span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
97
+ }
98
+ return proof;
99
+ } catch (error) {
100
+ span.setStatus({
101
+ code: SpanStatusCode.ERROR,
102
+ message: String(error)
103
+ });
104
+ throw error;
105
+ } finally {
106
+ span.end();
107
+ }
108
+ });
109
+ proofs.push(proof);
110
+ serializedProofs.push({
111
+ "@context": unsigned["@context"],
112
+ type: "DataIntegrityProof",
113
+ cryptosuite: proof.cryptosuite,
114
+ verificationMethod: keyId.href,
115
+ proofPurpose: "assertionMethod",
116
+ created: proof.created.toString(),
117
+ proofValue: new TextDecoder().decode(encodeMultibase("base58btc", proof.proofValue))
118
+ });
119
+ }
120
+ if (proofs.length === 0) return {
121
+ activity,
122
+ jsonLd: unsigned
123
+ };
124
+ return {
125
+ activity: activity.clone({ proofs }),
126
+ jsonLd: {
127
+ ...unsigned,
128
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
129
+ }
130
+ };
131
+ }
132
+ //#endregion
33
133
  //#region src/compat/transformers.ts
34
134
  const logger$1 = getLogger([
35
135
  "fedify",
@@ -209,7 +309,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
209
309
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
210
310
  }
211
311
  if (actor instanceof Tombstone) {
212
- const jsonLd = await actor.toJsonLd(context);
312
+ const jsonLd = await serializeForResponse(actor, context);
213
313
  return new Response(JSON.stringify(jsonLd), {
214
314
  status: 410,
215
315
  headers: {
@@ -218,7 +318,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
218
318
  }
219
319
  });
220
320
  }
221
- const jsonLd = await actor.toJsonLd(context);
321
+ const jsonLd = await serializeForResponse(actor, context);
222
322
  return new Response(JSON.stringify(jsonLd), { headers: {
223
323
  "Content-Type": "application/activity+json",
224
324
  Vary: "Accept"
@@ -238,7 +338,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
238
338
  if (authorizePredicate != null) {
239
339
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
240
340
  }
241
- const jsonLd = await object.toJsonLd(context);
341
+ const jsonLd = await serializeForResponse(object, context);
242
342
  return new Response(JSON.stringify(jsonLd), { headers: {
243
343
  "Content-Type": "application/activity+json",
244
344
  Vary: "Accept"
@@ -369,7 +469,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
369
469
  if (collectionCallbacks.authorizePredicate != null) {
370
470
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
371
471
  }
372
- const jsonLd = await collection.toJsonLd(context);
472
+ const jsonLd = await serializeForResponse(collection, context);
373
473
  return new Response(JSON.stringify(jsonLd), { headers: {
374
474
  "Content-Type": "application/activity+json",
375
475
  Vary: "Accept"
@@ -718,7 +818,11 @@ async function handleInboxInternal(request, parameters, span) {
718
818
  }
719
819
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
720
820
  const jsonWithoutSig = detachSignature(json);
721
- const hasLdSignature = hasSignature(json);
821
+ const hasLdSignature = hasVerifiableSignature(json);
822
+ if (!hasLdSignature) {
823
+ const shape = describeSignatureShape(json);
824
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
825
+ }
722
826
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
723
827
  let deferredLdSignatureError = void 0;
724
828
  const respondInvalidActivity = async (error) => {
@@ -1197,7 +1301,7 @@ var CustomCollectionHandler = class {
1197
1301
  * @returns A promise that resolves to the JSON-LD representation.
1198
1302
  */
1199
1303
  async toJsonLd() {
1200
- return (await this.collection).toJsonLd(this.context);
1304
+ return serializeForResponse(await this.collection, this.context);
1201
1305
  }
1202
1306
  /**
1203
1307
  * Fetches the collection with optional cursor for pagination.
@@ -1500,7 +1604,7 @@ var UnauthorizedError = class extends HandlerError {
1500
1604
  * @since 0.3.0
1501
1605
  */
1502
1606
  async function respondWithObject(object, options) {
1503
- const jsonLd = await object.toJsonLd(options);
1607
+ const jsonLd = await serializeForResponse(object, options);
1504
1608
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
1505
1609
  }
1506
1610
  /**
@@ -1588,6 +1692,10 @@ const MIN_COMPONENTS = [
1588
1692
  "@target-uri",
1589
1693
  "@authority"
1590
1694
  ];
1695
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
1696
+ async function serializeForResponse(object, options) {
1697
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
1698
+ }
1591
1699
  //#endregion
1592
1700
  //#region src/federation/webfinger.ts
1593
1701
  const logger = getLogger([
@@ -1894,8 +2002,25 @@ var FederationImpl = class extends FederationBuilderImpl {
1894
2002
  _getTracer() {
1895
2003
  return this.tracerProvider.getTracer(name, version);
1896
2004
  }
2005
+ /**
2006
+ * Starts listening on a queue, converting a synchronous throw into
2007
+ * a rejected promise.
2008
+ *
2009
+ * `MessageQueue.listen()` is documented to never reject, but some
2010
+ * implementations (e.g., `WorkersMessageQueue`) throw synchronously. Without
2011
+ * this normalization, one such throw aborts {@link _startQueueInternal} while
2012
+ * it is still collecting listener promises, so listeners started earlier are
2013
+ * never awaited and later queues are never started.
2014
+ */
2015
+ #listenQueue(queue, ctxData, signal) {
2016
+ try {
2017
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
2018
+ } catch (error) {
2019
+ return Promise.reject(error);
2020
+ }
2021
+ }
1897
2022
  async _startQueueInternal(ctxData, signal, queue) {
1898
- if (this.inboxQueue == null && this.outboxQueue == null) return;
2023
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
1899
2024
  const logger = getLogger([
1900
2025
  "fedify",
1901
2026
  "federation",
@@ -1905,20 +2030,38 @@ var FederationImpl = class extends FederationBuilderImpl {
1905
2030
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
1906
2031
  logger.debug("Starting an inbox task worker.");
1907
2032
  this.inboxQueueStarted = true;
1908
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2033
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
1909
2034
  }
1910
2035
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
1911
2036
  logger.debug("Starting an outbox task worker.");
1912
2037
  this.outboxQueueStarted = true;
1913
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2038
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
1914
2039
  }
1915
2040
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
1916
2041
  logger.debug("Starting a fanout task worker.");
1917
2042
  this.fanoutQueueStarted = true;
1918
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
2043
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
1919
2044
  }
1920
2045
  await Promise.all(promises);
1921
2046
  }
2047
+ /**
2048
+ * Starts the queue workers automatically, reporting a failure instead of
2049
+ * leaving the returned promise unobserved.
2050
+ *
2051
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
2052
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
2053
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
2054
+ * callers that start workers deliberately.
2055
+ */
2056
+ _startQueueAutomatically(ctxData) {
2057
+ this._startQueueInternal(ctxData).catch((error) => {
2058
+ getLogger([
2059
+ "fedify",
2060
+ "federation",
2061
+ "queue"
2062
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
2063
+ });
2064
+ }
1922
2065
  processQueuedTask(contextData, message) {
1923
2066
  const tracer = this._getTracer();
1924
2067
  const extractedContext = propagation.extract(context.active(), message.traceContext);
@@ -2028,7 +2171,8 @@ var FederationImpl = class extends FederationBuilderImpl {
2028
2171
  collectionSync: message.collectionSync,
2029
2172
  orderingKey: message.orderingKey,
2030
2173
  normalizeExistingProofs: message.normalizeExistingProofs,
2031
- context
2174
+ context,
2175
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
2032
2176
  });
2033
2177
  }
2034
2178
  async #listenOutboxMessage(_, message, span) {
@@ -2231,7 +2375,7 @@ var FederationImpl = class extends FederationBuilderImpl {
2231
2375
  let parseInput = void 0;
2232
2376
  let parseContextLoader = context.contextLoader;
2233
2377
  try {
2234
- const hasSignatureField = hasSignature(message.activity);
2378
+ const hasSignatureField = hasVerifiableSignature(message.activity);
2235
2379
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
2236
2380
  const parseContext = hasSignatureField ? {
2237
2381
  ...context,
@@ -2427,21 +2571,31 @@ var FederationImpl = class extends FederationBuilderImpl {
2427
2571
  hasProof = true;
2428
2572
  break;
2429
2573
  }
2430
- if (!hasProof) {
2431
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
2432
- activity = await signObject(activity, privateKey, keyId, {
2433
- contextLoader,
2434
- tracerProvider: this.tracerProvider
2435
- });
2436
- hasProof = true;
2437
- proofCreated = true;
2574
+ const prepared = !hasProof && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
2575
+ let jsonLd;
2576
+ if (prepared != null) {
2577
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
2578
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
2579
+ activity = signed.activity;
2580
+ jsonLd = signed.jsonLd;
2581
+ proofCreated = signingKeys.length > 0;
2582
+ } else {
2583
+ if (!hasProof) {
2584
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
2585
+ activity = await signObject(activity, privateKey, keyId, {
2586
+ contextLoader,
2587
+ tracerProvider: this.tracerProvider
2588
+ });
2589
+ proofCreated = true;
2590
+ }
2438
2591
  }
2592
+ jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
2593
+ format: "compact",
2594
+ contextLoader
2595
+ });
2439
2596
  }
2440
- let jsonLd = await activity.toJsonLd({
2441
- format: "compact",
2442
- contextLoader
2443
- });
2444
- if (proofCreated || !hasProof || options.normalizeExistingProofs) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
2597
+ if (prepared == null && (proofCreated || !hasProof || options.normalizeExistingProofs)) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
2598
+ hasProof ||= proofCreated;
2445
2599
  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.", {
2446
2600
  activityId,
2447
2601
  keys: keys.map((pair) => ({
@@ -2478,19 +2632,27 @@ var FederationImpl = class extends FederationBuilderImpl {
2478
2632
  activity: jsonLd
2479
2633
  });
2480
2634
  const promises = [];
2481
- for (const inbox in inboxes) promises.push(sendActivity({
2482
- allowPrivateAddress: this.allowPrivateAddress,
2483
- keys,
2484
- activity: jsonLd,
2485
- activityId: activity.id?.href,
2486
- activityType: getTypeId(activity).href,
2487
- inbox: new URL(inbox),
2488
- sharedInbox: inboxes[inbox].sharedInbox,
2489
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
2490
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
2491
- tracerProvider: this.tracerProvider
2492
- }));
2493
- await Promise.all(promises);
2635
+ try {
2636
+ for (const inbox in inboxes) {
2637
+ const promise = sendActivity({
2638
+ allowPrivateAddress: this.allowPrivateAddress,
2639
+ keys,
2640
+ activity: jsonLd,
2641
+ activityId: activity.id?.href,
2642
+ activityType: getTypeId(activity).href,
2643
+ inbox: new URL(inbox),
2644
+ sharedInbox: inboxes[inbox].sharedInbox,
2645
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
2646
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
2647
+ tracerProvider: this.tracerProvider
2648
+ });
2649
+ promise.catch(() => {});
2650
+ promises.push(promise);
2651
+ }
2652
+ await Promise.all(promises);
2653
+ } finally {
2654
+ await Promise.allSettled(promises);
2655
+ }
2494
2656
  return;
2495
2657
  }
2496
2658
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -2505,7 +2667,7 @@ var FederationImpl = class extends FederationBuilderImpl {
2505
2667
  privateKey: privateKeyJwk
2506
2668
  });
2507
2669
  }
2508
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
2670
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
2509
2671
  const carrier = {};
2510
2672
  propagation.inject(context.active(), carrier);
2511
2673
  const messages = [];
@@ -2738,7 +2900,7 @@ var FederationImpl = class extends FederationBuilderImpl {
2738
2900
  const identity = await this.sharedInboxKeyDispatcher(context);
2739
2901
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
2740
2902
  }
2741
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
2903
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
2742
2904
  const inboxContextFactory = context.toInboxContext.bind(context);
2743
2905
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
2744
2906
  return await handleInbox(request, {
@@ -3071,6 +3233,8 @@ var ContextImpl = class ContextImpl {
3071
3233
  for (const keyPair of keyPairs) {
3072
3234
  const newPair = {
3073
3235
  ...keyPair,
3236
+ privateKey: asCryptoKey(keyPair.privateKey),
3237
+ publicKey: asCryptoKey(keyPair.publicKey),
3074
3238
  cryptographicKey: new CryptographicKey({
3075
3239
  id: keyPair.keyId,
3076
3240
  owner,
@@ -3147,10 +3311,16 @@ var ContextImpl = class ContextImpl {
3147
3311
  } else identifierPromise = Promise.resolve(identity.identifier);
3148
3312
  return identifierPromise.then((identifier) => {
3149
3313
  if (identifier == null) return this.documentLoader;
3150
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
3314
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
3315
+ keyId: pair.keyId,
3316
+ privateKey: asCryptoKey(pair.privateKey)
3317
+ }));
3151
3318
  });
3152
3319
  }
3153
- return this.federation.authenticatedDocumentLoaderFactory(identity);
3320
+ return this.federation.authenticatedDocumentLoaderFactory({
3321
+ keyId: identity.keyId,
3322
+ privateKey: asCryptoKey(identity.privateKey)
3323
+ });
3154
3324
  }
3155
3325
  lookupObject(identifier, options = {}) {
3156
3326
  return lookupObject(identifier, {
@@ -3173,10 +3343,14 @@ var ContextImpl = class ContextImpl {
3173
3343
  return options.parse === "none" ? getNodeInfo(url, {
3174
3344
  parse: "none",
3175
3345
  direct: options.direct,
3346
+ timeout: options.timeout,
3347
+ signal: options.signal,
3176
3348
  userAgent: options?.userAgent ?? this.federation.userAgent
3177
3349
  }) : getNodeInfo(url, {
3178
3350
  parse: options.parse,
3179
3351
  direct: options.direct,
3352
+ timeout: options.timeout,
3353
+ signal: options.signal,
3180
3354
  userAgent: options?.userAgent ?? this.federation.userAgent
3181
3355
  });
3182
3356
  }
@@ -3188,7 +3362,17 @@ var ContextImpl = class ContextImpl {
3188
3362
  allowPrivateAddress: this.federation.allowPrivateAddress
3189
3363
  });
3190
3364
  }
3191
- sendActivity(sender, recipients, activity, options = {}) {
3365
+ async sendActivity(sender, recipients, activity, options = {}) {
3366
+ let activityJsonLd = void 0;
3367
+ let hasProof = activity.proofIds.length > 0;
3368
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
3369
+ hasProof = true;
3370
+ break;
3371
+ }
3372
+ if (hasProof) {
3373
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
3374
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
3375
+ }
3192
3376
  return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
3193
3377
  kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
3194
3378
  attributes: {
@@ -3201,7 +3385,7 @@ var ContextImpl = class ContextImpl {
3201
3385
  }, async (span) => {
3202
3386
  try {
3203
3387
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
3204
- await this.sendActivityInternal(sender, recipients, activity, options, span);
3388
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
3205
3389
  } catch (e) {
3206
3390
  span.setStatus({
3207
3391
  code: SpanStatusCode.ERROR,
@@ -3213,7 +3397,7 @@ var ContextImpl = class ContextImpl {
3213
3397
  }
3214
3398
  });
3215
3399
  }
3216
- async sendActivityInternal(sender, recipients, activity, options, span) {
3400
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
3217
3401
  const logger = getLogger([
3218
3402
  "fedify",
3219
3403
  "federation",
@@ -3260,15 +3444,23 @@ var ContextImpl = class ContextImpl {
3260
3444
  if (!(error instanceof RouterError)) throw error;
3261
3445
  }
3262
3446
  } else expandedRecipients = [recipients];
3263
- const opts = {
3264
- context: this,
3265
- orderingKey: options.orderingKey,
3266
- collectionSync,
3267
- immediate: options.immediate,
3268
- normalizeExistingProofs: options.normalizeExistingProofs
3269
- };
3270
3447
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
3271
3448
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
3449
+ let contextMatches = false;
3450
+ if (activityJsonLd != null) {
3451
+ const capturedJsonLd = activityJsonLd;
3452
+ const transformedJsonLd = await activity.toJsonLd({
3453
+ format: "compact",
3454
+ contextLoader: this.contextLoader
3455
+ });
3456
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
3457
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
3458
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
3459
+ if (contentChanged || !contextMatches && proofsChanged) {
3460
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) });
3461
+ activityJsonLd = void 0;
3462
+ } else if (proofsChanged) activityJsonLd = void 0;
3463
+ }
3272
3464
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
3273
3465
  if (activity.actorId == null) {
3274
3466
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -3280,15 +3472,42 @@ var ContextImpl = class ContextImpl {
3280
3472
  let proofCreated = false;
3281
3473
  if (actorKeyPairs != null) {
3282
3474
  const contextLoader = this.contextLoader;
3283
- for (const kp of actorKeyPairs) {
3284
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
3285
- activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
3286
- contextLoader,
3287
- tracerProvider: this.tracerProvider
3288
- });
3289
- proofCreated = true;
3475
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
3476
+ if (willSign) {
3477
+ if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
3478
+ }
3479
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
3480
+ if (prepared != null) {
3481
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
3482
+ privateKey: kp.privateKey,
3483
+ keyId: kp.multikey.id
3484
+ }] : []);
3485
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
3486
+ activity = signed.activity;
3487
+ activityJsonLd = signed.jsonLd;
3488
+ proofCreated = signingKeys.length > 0;
3489
+ } else {
3490
+ let proofAdded = false;
3491
+ for (const kp of actorKeyPairs) {
3492
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
3493
+ activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
3494
+ contextLoader,
3495
+ tracerProvider: this.tracerProvider
3496
+ });
3497
+ proofAdded = true;
3498
+ }
3499
+ if (proofAdded) activityJsonLd = void 0;
3500
+ proofCreated = proofAdded;
3290
3501
  }
3291
3502
  }
3503
+ const opts = {
3504
+ context: this,
3505
+ orderingKey: options.orderingKey,
3506
+ collectionSync,
3507
+ immediate: options.immediate,
3508
+ activityJsonLd,
3509
+ normalizeExistingProofs: options.normalizeExistingProofs
3510
+ };
3292
3511
  const inboxes = extractInboxes({
3293
3512
  recipients: expandedRecipients,
3294
3513
  preferSharedInbox: options.preferSharedInbox,
@@ -3328,7 +3547,7 @@ var ContextImpl = class ContextImpl {
3328
3547
  actorIds: [...actorIds],
3329
3548
  sharedInbox
3330
3549
  }])),
3331
- activity: await activity.toJsonLd({
3550
+ activity: activityJsonLd != null ? detachSignature(activityJsonLd) : await activity.toJsonLd({
3332
3551
  format: "compact",
3333
3552
  contextLoader: this.contextLoader
3334
3553
  }),
@@ -3339,7 +3558,7 @@ var ContextImpl = class ContextImpl {
3339
3558
  normalizeExistingProofs: proofCreated || options.normalizeExistingProofs,
3340
3559
  traceContext: carrier
3341
3560
  };
3342
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
3561
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
3343
3562
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
3344
3563
  return true;
3345
3564
  }
@@ -3539,43 +3758,83 @@ var RequestContextImpl = class RequestContextImpl extends ContextImpl {
3539
3758
  }
3540
3759
  }), values);
3541
3760
  }
3542
- #signedKey = void 0;
3761
+ #signedKey = null;
3762
+ #signedKeyOwner = null;
3763
+ #signatureChecks = /* @__PURE__ */ new WeakMap();
3764
+ #getSignatureCheck(documentLoader, contextLoader) {
3765
+ let checks = this.#signatureChecks.get(documentLoader);
3766
+ if (checks == null) {
3767
+ checks = /* @__PURE__ */ new WeakMap();
3768
+ this.#signatureChecks.set(documentLoader, checks);
3769
+ }
3770
+ let check = checks.get(contextLoader);
3771
+ if (check == null) {
3772
+ check = {};
3773
+ checks.set(contextLoader, check);
3774
+ }
3775
+ return check;
3776
+ }
3543
3777
  async getSignedKey(options = {}) {
3544
3778
  if (this.#signedKey != null) return this.#signedKey;
3545
- return this.#signedKey = await verifyRequest(this.request, {
3779
+ const documentLoader = options.documentLoader ?? this.documentLoader;
3780
+ const contextLoader = options.contextLoader ?? this.contextLoader;
3781
+ const check = this.#getSignatureCheck(documentLoader, contextLoader);
3782
+ if (check.key != null) return check.key;
3783
+ const promise = verifyRequest(this.request, {
3546
3784
  ...this,
3547
- contextLoader: options.contextLoader ?? this.contextLoader,
3548
- documentLoader: options.documentLoader ?? this.documentLoader,
3785
+ contextLoader,
3786
+ documentLoader,
3549
3787
  timeWindow: this.federation.signatureTimeWindow,
3550
3788
  tracerProvider: options.tracerProvider ?? this.tracerProvider
3789
+ }).then((key) => {
3790
+ if (key != null) this.#signedKey ??= key;
3791
+ return key;
3792
+ }).catch((error) => {
3793
+ if (check.key === promise) check.key = void 0;
3794
+ throw error;
3551
3795
  });
3796
+ check.key = promise;
3797
+ return await promise;
3552
3798
  }
3553
- #signedKeyOwner = void 0;
3554
3799
  async getSignedKeyOwner(options = {}) {
3555
3800
  if (this.#signedKeyOwner != null) return this.#signedKeyOwner;
3556
- const key = await this.getSignedKey(options);
3557
- if (key == null) return this.#signedKeyOwner = null;
3558
- try {
3559
- return this.#signedKeyOwner = await getKeyOwner(key, {
3560
- contextLoader: options.contextLoader ?? this.contextLoader,
3561
- documentLoader: options.documentLoader ?? this.documentLoader,
3562
- tracerProvider: options.tracerProvider ?? this.tracerProvider
3563
- });
3564
- } catch (error) {
3565
- if (error instanceof FetchError) {
3566
- getLogger([
3567
- "fedify",
3568
- "federation",
3569
- "actor"
3570
- ]).warn("Failed to fetch the key owner {keyOwner} of {keyId} while verifying the request signature; treating the request as unauthenticated: {error}", {
3571
- keyId: key.id?.href,
3572
- keyOwner: error.url.href,
3573
- error
3574
- });
3575
- return this.#signedKeyOwner = null;
3801
+ const normalizedOptions = {
3802
+ documentLoader: options.documentLoader ?? this.documentLoader,
3803
+ contextLoader: options.contextLoader ?? this.contextLoader,
3804
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
3805
+ };
3806
+ const check = this.#getSignatureCheck(normalizedOptions.documentLoader, normalizedOptions.contextLoader);
3807
+ if (check.owner != null) return check.owner;
3808
+ const promise = this.getSignedKey(normalizedOptions).then(async (key) => {
3809
+ if (key == null) {
3810
+ if (check.owner === promise) check.owner = void 0;
3811
+ return null;
3812
+ }
3813
+ try {
3814
+ const owner = await getKeyOwner(key, normalizedOptions);
3815
+ if (owner != null) this.#signedKeyOwner ??= owner;
3816
+ return owner;
3817
+ } catch (error) {
3818
+ if (error instanceof FetchError) {
3819
+ getLogger([
3820
+ "fedify",
3821
+ "federation",
3822
+ "actor"
3823
+ ]).warn("Failed to fetch the key owner {keyOwner} of {keyId} while verifying the request signature; treating the request as unauthenticated: {error}", {
3824
+ keyId: key.id?.href,
3825
+ keyOwner: error.url.href,
3826
+ error
3827
+ });
3828
+ return null;
3829
+ }
3830
+ throw error;
3576
3831
  }
3832
+ }).catch((error) => {
3833
+ if (check.owner === promise) check.owner = void 0;
3577
3834
  throw error;
3578
- }
3835
+ });
3836
+ check.owner = promise;
3837
+ return await promise;
3579
3838
  }
3580
3839
  };
3581
3840
  function forwardActivity(ctx, loggerCategory, forwarder, recipients, options) {
@@ -3626,7 +3885,7 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
3626
3885
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
3627
3886
  keys = forwarder;
3628
3887
  } else keys = [forwarder];
3629
- if (!hasSignatureLike(ctx.activity)) {
3888
+ if (!hasVerifiableSignature(ctx.activity) && !hasSignatureLike(ctx.activity)) {
3630
3889
  if (!hasProofLike(ctx.activity)) {
3631
3890
  if (options?.skipIfUnsigned) return false;
3632
3891
  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.", {
@@ -3664,25 +3923,33 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
3664
3923
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
3665
3924
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
3666
3925
  const promises = [];
3667
- for (const inbox in inboxes) promises.push(sendActivity({
3668
- allowPrivateAddress: ctx.federation.allowPrivateAddress,
3669
- keys,
3670
- activity: ctx.activity,
3671
- activityId: ctx.activityId,
3672
- activityType: ctx.activityType,
3673
- inbox: new URL(inbox),
3674
- sharedInbox: inboxes[inbox].sharedInbox,
3675
- tracerProvider: ctx.tracerProvider,
3676
- specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
3677
- }));
3678
- await Promise.all(promises);
3926
+ try {
3927
+ for (const inbox in inboxes) {
3928
+ const promise = sendActivity({
3929
+ allowPrivateAddress: ctx.federation.allowPrivateAddress,
3930
+ keys,
3931
+ activity: ctx.activity,
3932
+ activityId: ctx.activityId,
3933
+ activityType: ctx.activityType,
3934
+ inbox: new URL(inbox),
3935
+ sharedInbox: inboxes[inbox].sharedInbox,
3936
+ tracerProvider: ctx.tracerProvider,
3937
+ specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
3938
+ });
3939
+ promise.catch(() => {});
3940
+ promises.push(promise);
3941
+ }
3942
+ await Promise.all(promises);
3943
+ } finally {
3944
+ await Promise.allSettled(promises);
3945
+ }
3679
3946
  return true;
3680
3947
  }
3681
3948
  logger.debug("Enqueuing activity {activityId} to forward later.", {
3682
3949
  activityId: ctx.activityId,
3683
3950
  activity: ctx.activity
3684
3951
  });
3685
- if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
3952
+ if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueAutomatically(ctx.data);
3686
3953
  const keyJwkPairs = [];
3687
3954
  for (const { keyId, privateKey } of keys) {
3688
3955
  const privateKeyJwk = await exportJwk(privateKey);
@@ -3854,6 +4121,69 @@ var KvSpecDeterminer = class {
3854
4121
  function notFound(_request) {
3855
4122
  return new Response("Not Found", { status: 404 });
3856
4123
  }
4124
+ function hasTopLevelProof(value) {
4125
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
4126
+ }
4127
+ function getContentFields(value) {
4128
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
4129
+ const record = { ...value };
4130
+ delete record["@context"];
4131
+ delete record.proof;
4132
+ delete record.signature;
4133
+ return JSON.stringify(sortJsonKeys(record));
4134
+ }
4135
+ function getContextFields(value) {
4136
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
4137
+ const context = value["@context"];
4138
+ return JSON.stringify(sortJsonKeys(context ?? null));
4139
+ }
4140
+ function getProofEntries(value) {
4141
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
4142
+ const proof = value.proof;
4143
+ if (proof == null) return [];
4144
+ return Array.isArray(proof) ? proof : [proof];
4145
+ }
4146
+ function normalizeProofEntry(proof) {
4147
+ const stripped = stripContexts(proof);
4148
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
4149
+ const record = { ...stripped };
4150
+ if (typeof record.created === "string") try {
4151
+ record.created = Temporal.Instant.from(record.created).toString();
4152
+ } catch {}
4153
+ return record;
4154
+ }
4155
+ function getProofEntryFields(proof) {
4156
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
4157
+ }
4158
+ function getProofFields(value) {
4159
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
4160
+ }
4161
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
4162
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
4163
+ const retainedProofs = [];
4164
+ for await (const proof of activity.getProofs({ contextLoader })) {
4165
+ const proofJsonLd = await proof.toJsonLd({
4166
+ format: "compact",
4167
+ contextLoader
4168
+ });
4169
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
4170
+ }
4171
+ return retainedProofs;
4172
+ }
4173
+ function stripContexts(value) {
4174
+ if (Array.isArray(value)) return value.map(stripContexts);
4175
+ if (typeof value !== "object" || value == null) return value;
4176
+ const record = { ...value };
4177
+ delete record["@context"];
4178
+ delete record.signature;
4179
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
4180
+ return record;
4181
+ }
4182
+ function sortJsonKeys(value) {
4183
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
4184
+ if (typeof value !== "object" || value == null) return value;
4185
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
4186
+ }
3857
4187
  function notAcceptable(_request) {
3858
4188
  return new Response("Not Acceptable", {
3859
4189
  status: 406,
@@ -3885,4 +4215,4 @@ function getRequestId(request) {
3885
4215
  return `req_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
3886
4216
  }
3887
4217
  //#endregion
3888
- export { handleNodeInfoJrd as _, OutboxContextImpl as a, handleActor as c, handleInbox as d, handleObject as f, handleNodeInfo 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, actorDehydrator as v, autoIdAssigner as y };
4218
+ export { handleNodeInfoJrd as _, OutboxContextImpl as a, prepareActivityJsonLd as b, handleActor as c, handleInbox as d, handleObject as f, handleNodeInfo 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, actorDehydrator as v, autoIdAssigner as y };