@fedify/fedify 2.0.36-dev.2746 → 2.0.36-dev.2779

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 (67) hide show
  1. package/dist/attachment-arrays-D43igPLB.mjs +111 -0
  2. package/dist/{builder-CnyFdlUn.mjs → builder-UXDfZSno.mjs} +3 -3
  3. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  4. package/dist/compat/attachment-arrays.test.mjs +254 -0
  5. package/dist/compat/transformers.test.mjs +1 -1
  6. package/dist/{deno-DCXndlEx.mjs → deno-Bwn7hAXr.mjs} +1 -1
  7. package/dist/{docloader-7M06kit4.mjs → docloader-DSQXpyiJ.mjs} +2 -2
  8. package/dist/federation/attachment-responses.test.d.mts +2 -0
  9. package/dist/federation/attachment-responses.test.mjs +182 -0
  10. package/dist/federation/builder.test.mjs +1 -1
  11. package/dist/federation/collection.test.mjs +1 -1
  12. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  13. package/dist/federation/delivery-attachments.test.mjs +280 -0
  14. package/dist/federation/handler.test.mjs +43 -14
  15. package/dist/federation/idempotency.test.mjs +2 -2
  16. package/dist/federation/inbox.test.mjs +1 -1
  17. package/dist/federation/keycache.test.mjs +1 -1
  18. package/dist/federation/middleware.test.mjs +7 -7
  19. package/dist/federation/mod.cjs +1 -1
  20. package/dist/federation/mod.js +1 -1
  21. package/dist/federation/negotiation.test.mjs +1 -1
  22. package/dist/federation/retry.test.mjs +1 -1
  23. package/dist/federation/send.test.mjs +3 -3
  24. package/dist/federation/temporal.test.mjs +1 -1
  25. package/dist/federation/webfinger.test.mjs +1 -1
  26. package/dist/{http-hjoPA7jZ.js → http-C-P8JP1h.js} +1 -1
  27. package/dist/{http-hi5IS6qw.mjs → http-DuIId6ul.mjs} +2 -2
  28. package/dist/{http-BhaAN2KG.cjs → http-aVfiO4CG.cjs} +1 -1
  29. package/dist/{inbox-Bygi511A.mjs → inbox-Cq4_-nPi.mjs} +1 -1
  30. package/dist/{key-DYyRTxPH.mjs → key-BMJlknME.mjs} +1 -1
  31. package/dist/{kv-cache-Bjnv9p9e.cjs → kv-cache-C6BYEp2D.cjs} +1 -1
  32. package/dist/{kv-cache-YZ2bpa_P.js → kv-cache-PAsTBkxX.js} +1 -1
  33. package/dist/{ld-CKUnk1Ps.mjs → ld-oemavcUi.mjs} +2 -2
  34. package/dist/{middleware-D5uql06B.js → middleware-BSMUxoX2.js} +259 -32
  35. package/dist/{middleware-dYPOyDLN.mjs → middleware-Bw59VTh0.mjs} +1 -1
  36. package/dist/{middleware-C_4rWloR.cjs → middleware-CjwdngG9.cjs} +260 -32
  37. package/dist/{middleware-yx080dbw.mjs → middleware-D8Hh8RSu.mjs} +170 -45
  38. package/dist/{middleware-BDCfPddM.cjs → middleware-sDUMisQG.cjs} +1 -1
  39. package/dist/mod.cjs +4 -4
  40. package/dist/mod.js +4 -4
  41. package/dist/nodeinfo/handler.test.mjs +1 -1
  42. package/dist/nodeinfo/types.test.mjs +1 -1
  43. package/dist/{owner-CqHBbNXl.mjs → owner-CYTWux20.mjs} +2 -2
  44. package/dist/{proof-CDalRU9r.mjs → proof-B7pdOJb5.mjs} +2 -2
  45. package/dist/{proof-D2RNLHHt.js → proof-DWny6g-g.js} +2 -2
  46. package/dist/{proof-DLqGjdaL.cjs → proof-DXp_5fqW.cjs} +3 -3
  47. package/dist/{send-XHpoZpxW.mjs → send-7rTXYfE8.mjs} +2 -2
  48. package/dist/sig/http.test.mjs +2 -2
  49. package/dist/sig/key-types.test.d.mts +1 -1
  50. package/dist/sig/key.test.mjs +2 -2
  51. package/dist/sig/ld.test.mjs +2 -2
  52. package/dist/sig/mod.cjs +2 -2
  53. package/dist/sig/mod.js +2 -2
  54. package/dist/sig/owner.test.mjs +1 -1
  55. package/dist/sig/proof.test.mjs +26 -3
  56. package/dist/{temporal-D3yEsvvS.mjs → temporal-CxaXuWOi.mjs} +1 -1
  57. package/dist/testing/mod.d.mts +1 -1
  58. package/dist/utils/docloader.test.mjs +2 -2
  59. package/dist/utils/mod.cjs +1 -1
  60. package/dist/utils/mod.js +1 -1
  61. package/package.json +6 -6
  62. /package/dist/{callback-BFMEE_9V.d.mts → callback-ySj5p3Ml.d.mts} +0 -0
  63. /package/dist/{collection-ChgDTHLz.mjs → collection-BD6-SZ6O.mjs} +0 -0
  64. /package/dist/{keycache-crDMn2HK.mjs → keycache-BhLorx33.mjs} +0 -0
  65. /package/dist/{negotiation-BehA2uul.mjs → negotiation-DnsfFF8I.mjs} +0 -0
  66. /package/dist/{retry-B_E3V_Dx.mjs → retry-CJL0poaU.mjs} +0 -0
  67. /package/dist/{types-C37hquWI.mjs → types-DCP0WLdt.mjs} +0 -0
@@ -2,21 +2,22 @@ import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  import { t as __exportAll } from "./chunk-CRNNMoPX.js";
4
4
  import { r as getDefaultActivityTransformers } from "./transformers-BGMIq1cs.js";
5
- import { c as importJwk, d as name, f as version, i as exportJwk, l as validateCryptoKey, r as verifyRequest, t as doubleKnockScoped } from "./http-hjoPA7jZ.js";
5
+ import { c as importJwk, d as name, f as version, i as exportJwk, l as validateCryptoKey, r as verifyRequest, t as doubleKnockScoped } from "./http-C-P8JP1h.js";
6
6
  import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-B1_pRFE_.js";
7
- import { S as wrapContextLoaderForJsonLd, _ as isInvalidUrlTypeError, a as doesActorOwnKey, c as assertSafeJsonLd, f as describeSignatureShape, g as isClearlyMalformedContextReference, h as hasVerifiableSignature, m as getNormalizationContextLoader, n as signObject, o as getKeyOwner, p as detachSignature, r as verifyObject, s as InvalidContextReferenceError, u as compactJsonLd, v as signJsonLd, y as verifyCompactJsonLd } from "./proof-D2RNLHHt.js";
8
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-YZ2bpa_P.js";
7
+ import { S as wrapContextLoaderForJsonLd, _ as isInvalidUrlTypeError, a as doesActorOwnKey, c as assertSafeJsonLd, f as describeSignatureShape, g as isClearlyMalformedContextReference, h as hasVerifiableSignature, m as getNormalizationContextLoader, n as signObject, o as getKeyOwner, p as detachSignature, r as verifyObject, s as InvalidContextReferenceError, u as compactJsonLd, v as signJsonLd, y as verifyCompactJsonLd } from "./proof-DWny6g-g.js";
8
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-PAsTBkxX.js";
9
9
  import { getLogger, withContext } from "@logtape/logtape";
10
- import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
10
+ import { Activity, Collection, CollectionPage, CryptographicKey, DataIntegrityProof, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
11
11
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
12
12
  import { cloneDeep } from "es-toolkit";
13
13
  import { Router } from "uri-template-router";
14
14
  import { parseTemplate } from "url-template";
15
15
  import { encodeHex } from "byte-encodings/hex";
16
- import { FetchError, UrlError, getDocumentLoader } from "@fedify/vocab-runtime";
16
+ import { FetchError, UrlError, encodeMultibase, getDocumentLoader, preloadedContexts } from "@fedify/vocab-runtime";
17
+ import jsonld from "@fedify/vocab-runtime/jsonld";
17
18
  import { asCryptoKey, openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
18
19
  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";
19
- import jsonld from "@fedify/vocab-runtime/jsonld";
20
+ import serialize from "json-canon";
20
21
  import { normalizeDateTimeLiteral } from "@fedify/vocab-runtime/temporal";
21
22
  import { lookupWebFinger } from "@fedify/webfinger";
22
23
  import { domainToASCII } from "node:url";
@@ -877,6 +878,110 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
877
878
  return `collectionId="${collectionId}", url="${url}", digest="${encodeHex(await digest(actorIds))}"`;
878
879
  }
879
880
  //#endregion
881
+ //#region src/compat/attachment-arrays.ts
882
+ const logger$1 = getLogger([
883
+ "fedify",
884
+ "compat",
885
+ "attachment-arrays"
886
+ ]);
887
+ const MAX_DEPTH = 64;
888
+ const ATTACHMENT = "https://www.w3.org/ns/activitystreams#attachment";
889
+ const PROOF = "https://w3id.org/security#proof";
890
+ /** Recognizes JSON-LD maps without accepting arrays or scalar values. */
891
+ function isMap(value) {
892
+ return typeof value === "object" && value != null && !Array.isArray(value);
893
+ }
894
+ /** Copies only changed branches; cached vocabulary JSON belongs to its owner. */
895
+ function walk(value, depth = 0) {
896
+ if (depth >= MAX_DEPTH) throw new RangeError("JSON-LD nesting limit exceeded.");
897
+ if (Array.isArray(value)) {
898
+ const items = value.map((item) => walk(item, depth + 1));
899
+ return items.some((item, i) => item !== value[i]) ? items : value;
900
+ }
901
+ if (!isMap(value)) return value;
902
+ if (Object.hasOwn(value, "@value")) return value;
903
+ let result;
904
+ for (const [key, item] of Object.entries(value)) {
905
+ let next = key === "@context" ? item : walk(item, depth + 1);
906
+ if ((key === "attachment" || key === ATTACHMENT) && next != null && !Array.isArray(next) && !(isMap(next) && Object.hasOwn(next, "@list"))) next = [next];
907
+ if (next !== item) {
908
+ result ??= Object.assign(Object.create(null), value);
909
+ result[key] = next;
910
+ }
911
+ }
912
+ return result ?? value;
913
+ }
914
+ const preloadedLoader = (url) => {
915
+ if (!Object.hasOwn(preloadedContexts, url)) return Promise.reject(/* @__PURE__ */ new Error("Unknown JSON-LD context: " + url));
916
+ return Promise.resolve({
917
+ contextUrl: null,
918
+ documentUrl: url,
919
+ document: preloadedContexts[url]
920
+ });
921
+ };
922
+ /** Reuses each context resolution across the complete equivalence check. */
923
+ function memoizeLoader(loader) {
924
+ const pending = /* @__PURE__ */ new Map();
925
+ return (url, options) => {
926
+ let result = pending.get(url);
927
+ if (result == null) {
928
+ result = loader(url, options);
929
+ pending.set(url, result);
930
+ }
931
+ return result;
932
+ };
933
+ }
934
+ /** Finds security predicates in expanded nodes, never inside JSON literals. */
935
+ function hasSecurityPredicate(value) {
936
+ if (Array.isArray(value)) return value.some(hasSecurityPredicate);
937
+ if (!isMap(value) || Object.hasOwn(value, "@value")) return false;
938
+ for (const [key, child] of Object.entries(value)) {
939
+ if (key === PROOF || key === "https://w3id.org/security#signature") return true;
940
+ if (hasSecurityPredicate(child)) return true;
941
+ }
942
+ return false;
943
+ }
944
+ /**
945
+ * Keeps singleton attachments in arrays for raw-JSON ActivityPub consumers.
946
+ * Mastodon's property_values() ignores valid compact JSON-LD scalar values,
947
+ * and its caller clears the profile fields in that case:
948
+ * https://github.com/mastodon/mastodon/blob/594166519a623584920c7e696bae9a009d9183ab/app/services/activitypub/process_account_service.rb#L465-L472
949
+ * Pixelfed likewise rejects singleton media attachments:
950
+ * https://github.com/pixelfed/pixelfed/issues/6588
951
+ *
952
+ * This workaround changes only attachment representation, after serialization.
953
+ * RDF equality protects custom contexts, including JSON literals; it does not
954
+ * protect JCS signatures. Any semantic proof or Linked Data signature leaves
955
+ * the whole serialized document unchanged, as does an unresolved context.
956
+ * This layer does not compose signed objects or repair vocabulary serialization.
957
+ * Remove this
958
+ * workaround only when the supported consumer versions, including deployed
959
+ * older releases, accept scalar attachments. Do not replace it with a
960
+ * vocabulary transformer: subsequent compaction collapses arrays.
961
+ * @internal
962
+ */
963
+ async function normalizeAttachmentArrays(document, contextLoader) {
964
+ try {
965
+ const normalized = walk(document);
966
+ if (normalized === document) return document;
967
+ const loader = memoizeLoader(contextLoader ?? preloadedLoader);
968
+ if (hasSecurityPredicate(await jsonld.expand(document, { documentLoader: loader }))) return document;
969
+ const [before, after] = await Promise.allSettled([jsonld.canonize(document, {
970
+ format: "application/n-quads",
971
+ documentLoader: loader
972
+ }), jsonld.canonize(normalized, {
973
+ format: "application/n-quads",
974
+ documentLoader: loader
975
+ })]);
976
+ if (before.status === "rejected") throw before.reason;
977
+ if (after.status === "rejected") throw after.reason;
978
+ if (before.value === after.value) return normalized;
979
+ } catch (error) {
980
+ logger$1.debug("Could not safely normalize attachment arrays; preserving the document: {error}", { error });
981
+ }
982
+ return document;
983
+ }
984
+ //#endregion
880
985
  //#region src/federation/keycache.ts
881
986
  const NULL_KEY_CACHE_VALUE = { _fedify: "key-unavailable" };
882
987
  const NULL_KEY_CACHE_TTL = Temporal.Duration.from({ minutes: 5 });
@@ -1135,7 +1240,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1135
1240
  if (authorizePredicate != null) {
1136
1241
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1137
1242
  }
1138
- const jsonLd = await actor.toJsonLd(context);
1243
+ const jsonLd = await serializeForResponse(actor, context);
1139
1244
  return new Response(JSON.stringify(jsonLd), { headers: {
1140
1245
  "Content-Type": "application/activity+json",
1141
1246
  Vary: "Accept"
@@ -1155,7 +1260,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1155
1260
  if (authorizePredicate != null) {
1156
1261
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1157
1262
  }
1158
- const jsonLd = await object.toJsonLd(context);
1263
+ const jsonLd = await serializeForResponse(object, context);
1159
1264
  return new Response(JSON.stringify(jsonLd), { headers: {
1160
1265
  "Content-Type": "application/activity+json",
1161
1266
  Vary: "Accept"
@@ -1286,7 +1391,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1286
1391
  if (collectionCallbacks.authorizePredicate != null) {
1287
1392
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
1288
1393
  }
1289
- const jsonLd = await collection.toJsonLd(context);
1394
+ const jsonLd = await serializeForResponse(collection, context);
1290
1395
  return new Response(JSON.stringify(jsonLd), { headers: {
1291
1396
  "Content-Type": "application/activity+json",
1292
1397
  Vary: "Accept"
@@ -1846,7 +1951,7 @@ var CustomCollectionHandler = class {
1846
1951
  * @returns A promise that resolves to the JSON-LD representation.
1847
1952
  */
1848
1953
  async toJsonLd() {
1849
- return (await this.collection).toJsonLd(this.context);
1954
+ return serializeForResponse(await this.collection, this.context);
1850
1955
  }
1851
1956
  /**
1852
1957
  * Fetches the collection with optional cursor for pagination.
@@ -2149,7 +2254,7 @@ var UnauthorizedError = class extends HandlerError {
2149
2254
  * @since 0.3.0
2150
2255
  */
2151
2256
  async function respondWithObject(object, options) {
2152
- const jsonLd = await object.toJsonLd(options);
2257
+ const jsonLd = await serializeForResponse(object, options);
2153
2258
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
2154
2259
  }
2155
2260
  /**
@@ -2167,6 +2272,106 @@ async function respondWithObjectIfAcceptable(object, request, options) {
2167
2272
  response.headers.set("Vary", "Accept");
2168
2273
  return response;
2169
2274
  }
2275
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
2276
+ async function serializeForResponse(object, options) {
2277
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
2278
+ }
2279
+ //#endregion
2280
+ //#region src/sig/proof-creation.ts
2281
+ /** Signs the exact serialized message supplied by an internal producer. */
2282
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
2283
+ validateCryptoKey(privateKey, "private");
2284
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
2285
+ const encoder = new TextEncoder();
2286
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(jsonLd)));
2287
+ created ??= Temporal.Now.instant();
2288
+ const proofConfig = {
2289
+ "@context": jsonLd["@context"],
2290
+ type: "DataIntegrityProof",
2291
+ cryptosuite: "eddsa-jcs-2022",
2292
+ verificationMethod: keyId.href,
2293
+ proofPurpose: "assertionMethod",
2294
+ created: created.toString()
2295
+ };
2296
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(proofConfig)));
2297
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
2298
+ digest.set(new Uint8Array(proofDigest), 0);
2299
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
2300
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
2301
+ return new DataIntegrityProof({
2302
+ cryptosuite: "eddsa-jcs-2022",
2303
+ verificationMethod: keyId,
2304
+ proofPurpose: "assertionMethod",
2305
+ created,
2306
+ proofValue: new Uint8Array(sig)
2307
+ });
2308
+ }
2309
+ //#endregion
2310
+ //#region src/compat/delivery-jsonld.ts
2311
+ /**
2312
+ * Returns changed attachment JSON only; unchanged documents keep the existing
2313
+ * delivery signing path. This uses ordinary vocabulary serialization, without
2314
+ * retaining or repairing independently signed child representations.
2315
+ */
2316
+ async function prepareActivityJsonLd(activity, contextLoader) {
2317
+ if (activity.proofIds.length > 0) return void 0;
2318
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
2319
+ const source = await activity.clone().toJsonLd({
2320
+ format: "compact",
2321
+ contextLoader
2322
+ });
2323
+ const prepared = await normalizeAttachmentArrays(source, contextLoader);
2324
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
2325
+ }
2326
+ /** Signs a changed, proof-free delivery map without serializing it again. */
2327
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
2328
+ const proofs = [];
2329
+ const serializedProofs = [];
2330
+ const tracer = (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version);
2331
+ for (const { privateKey, keyId } of keys) {
2332
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(activity).href } }, async (span) => {
2333
+ try {
2334
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
2335
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
2336
+ if (span.isRecording()) {
2337
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
2338
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
2339
+ span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
2340
+ }
2341
+ return proof;
2342
+ } catch (error) {
2343
+ span.setStatus({
2344
+ code: SpanStatusCode.ERROR,
2345
+ message: String(error)
2346
+ });
2347
+ throw error;
2348
+ } finally {
2349
+ span.end();
2350
+ }
2351
+ });
2352
+ proofs.push(proof);
2353
+ serializedProofs.push({
2354
+ "@context": unsigned["@context"],
2355
+ type: "DataIntegrityProof",
2356
+ cryptosuite: proof.cryptosuite,
2357
+ verificationMethod: keyId.href,
2358
+ proofPurpose: "assertionMethod",
2359
+ created: proof.created.toString(),
2360
+ proofValue: new TextDecoder().decode(encodeMultibase("base58btc", proof.proofValue))
2361
+ });
2362
+ }
2363
+ if (proofs.length === 0) return {
2364
+ activity,
2365
+ jsonLd: unsigned
2366
+ };
2367
+ return {
2368
+ activity: activity.clone({ proofs }),
2369
+ jsonLd: {
2370
+ ...unsigned,
2371
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
2372
+ }
2373
+ };
2374
+ }
2170
2375
  //#endregion
2171
2376
  //#region src/nodeinfo/handler.ts
2172
2377
  /**
@@ -3440,19 +3645,29 @@ var FederationImpl = class extends FederationBuilderImpl {
3440
3645
  proofCreated = true;
3441
3646
  break;
3442
3647
  }
3443
- if (!proofCreated) {
3444
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3445
- activity = await signObject(activity, privateKey, keyId, {
3446
- contextLoader,
3447
- tracerProvider: this.tracerProvider
3448
- });
3449
- proofCreated = true;
3648
+ const prepared = !proofCreated && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
3649
+ let jsonLd;
3650
+ if (prepared != null) {
3651
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
3652
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
3653
+ activity = signed.activity;
3654
+ jsonLd = signed.jsonLd;
3655
+ proofCreated = signingKeys.length > 0;
3656
+ } else {
3657
+ if (!proofCreated) {
3658
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3659
+ activity = await signObject(activity, privateKey, keyId, {
3660
+ contextLoader,
3661
+ tracerProvider: this.tracerProvider
3662
+ });
3663
+ proofCreated = true;
3664
+ }
3450
3665
  }
3666
+ jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
3667
+ format: "compact",
3668
+ contextLoader
3669
+ });
3451
3670
  }
3452
- let jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
3453
- format: "compact",
3454
- contextLoader
3455
- });
3456
3671
  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.", {
3457
3672
  activityId,
3458
3673
  keys: keys.map((pair) => ({
@@ -4291,19 +4506,31 @@ var ContextImpl = class ContextImpl {
4291
4506
  }
4292
4507
  if (actorKeyPairs != null) {
4293
4508
  const contextLoader = this.contextLoader;
4294
- if (actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null)) {
4509
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
4510
+ if (willSign) {
4295
4511
  if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
4296
4512
  }
4297
- let proofAdded = false;
4298
- for (const kp of actorKeyPairs) {
4299
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4300
- activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4301
- contextLoader,
4302
- tracerProvider: this.tracerProvider
4303
- });
4304
- proofAdded = true;
4513
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
4514
+ if (prepared != null) {
4515
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
4516
+ privateKey: kp.privateKey,
4517
+ keyId: kp.multikey.id
4518
+ }] : []);
4519
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
4520
+ activity = signed.activity;
4521
+ activityJsonLd = signed.jsonLd;
4522
+ } else {
4523
+ let proofAdded = false;
4524
+ for (const kp of actorKeyPairs) {
4525
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4526
+ activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4527
+ contextLoader,
4528
+ tracerProvider: this.tracerProvider
4529
+ });
4530
+ proofAdded = true;
4531
+ }
4532
+ if (proofAdded) activityJsonLd = void 0;
4305
4533
  }
4306
- if (proofAdded) activityJsonLd = void 0;
4307
4534
  }
4308
4535
  const opts = {
4309
4536
  context: this,
@@ -1,5 +1,5 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as FederationImpl } from "./middleware-yx080dbw.mjs";
4
+ import { n as FederationImpl } from "./middleware-D8Hh8RSu.mjs";
5
5
  export { FederationImpl };