@fedify/fedify 2.2.12 → 2.2.14-dev.2082

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 (102) hide show
  1. package/dist/{assert_instance_of-C4Ri6VuN.mjs → assert-BhQd8QHP.mjs} +19 -1
  2. package/dist/{builder-TJzcpmDm.mjs → builder-Cwgo1nK5.mjs} +3 -3
  3. package/dist/{client-dx126nMS.mjs → client-CQ7zd8tW.mjs} +78 -4
  4. package/dist/compat/mod.d.cts +1 -1
  5. package/dist/compat/mod.d.ts +1 -1
  6. package/dist/compat/outgoing-jsonld.test.mjs +1 -1
  7. package/dist/compat/public-audience.test.mjs +1 -1
  8. package/dist/compat/transformers.test.mjs +3 -4
  9. package/dist/{context-BU-1O90h.d.ts → context-Bt2jnbC7.d.ts} +4 -3
  10. package/dist/{context-DVA8wHZ0.d.cts → context-Cls_M1HU.d.cts} +4 -3
  11. package/dist/{deno-DeYUdFal.mjs → deno-CV4wsQzy.mjs} +1 -1
  12. package/dist/{docloader-CXH2XqYP.mjs → docloader-DV9F08Dn.mjs} +2 -2
  13. package/dist/federation/builder.test.mjs +2 -2
  14. package/dist/federation/collection.test.mjs +1 -1
  15. package/dist/federation/handler.test.mjs +127 -10
  16. package/dist/federation/idempotency.test.mjs +4 -4
  17. package/dist/federation/inbox.test.mjs +1 -1
  18. package/dist/federation/keycache.test.mjs +44 -10
  19. package/dist/federation/kv.test.mjs +1 -1
  20. package/dist/federation/middleware.test.mjs +103 -15
  21. package/dist/federation/mod.cjs +1 -1
  22. package/dist/federation/mod.d.cts +2 -2
  23. package/dist/federation/mod.d.ts +2 -2
  24. package/dist/federation/mod.js +1 -1
  25. package/dist/federation/mq.test.mjs +1 -1
  26. package/dist/federation/negotiation.test.mjs +2 -2
  27. package/dist/federation/retry.test.mjs +1 -1
  28. package/dist/federation/router.test.mjs +1 -1
  29. package/dist/federation/send.test.mjs +138 -6
  30. package/dist/federation/temporal.test.mjs +2 -2
  31. package/dist/federation/webfinger.test.mjs +2 -2
  32. package/dist/{http-D6cIKrI1.cjs → http-BWNuy1sb.cjs} +166 -6
  33. package/dist/{http-CNsxTbVr.js → http-C5T-lWqB.js} +155 -7
  34. package/dist/{http-79lZeYEo.mjs → http-C9MzFrOj.mjs} +3 -3
  35. package/dist/{http-BDZeS5om.d.ts → http-Dl00HXr4.d.ts} +1 -1
  36. package/dist/{http-C87EWkO0.d.cts → http-DqZhyEso.d.cts} +1 -1
  37. package/dist/{key-B4kUuy3o.mjs → key-DiziIx9e.mjs} +154 -6
  38. package/dist/{keycache-EGATflN-.mjs → keycache-C1aVprwy.mjs} +12 -4
  39. package/dist/{kv-cache-CIZ1m-94.js → kv-cache-CM-zJoep.js} +1 -1
  40. package/dist/{kv-cache-BtXEUvHT.cjs → kv-cache-DGPEHc1T.cjs} +1 -1
  41. package/dist/{ld-2R9vZ_ym.mjs → ld-BAeuDKjx.mjs} +2 -2
  42. package/dist/{middleware-CjrIRAsQ.cjs → middleware-BbbKc-Tr.cjs} +90 -14
  43. package/dist/{middleware-D5NE6PkU.mjs → middleware-CkJOjZjS.mjs} +31 -20
  44. package/dist/{middleware-_qt3kHUU.mjs → middleware-DA2CvTQL.mjs} +1 -1
  45. package/dist/{middleware-DsEAPFhi.js → middleware-J32whqNP.js} +90 -14
  46. package/dist/{middleware-2bSnAJOQ.cjs → middleware-XNvq3NUZ.cjs} +1 -1
  47. package/dist/{mod-BhU_H1I_.d.ts → mod-0MWo2Nu5.d.ts} +1 -1
  48. package/dist/{mod-DXY9JF28.d.cts → mod-D2JyWtW3.d.cts} +1 -1
  49. package/dist/{mod-q-NFLW6B.d.cts → mod-DNvnDTS7.d.cts} +1 -1
  50. package/dist/{mod-BVt6iTmH.d.ts → mod-DaiJDJdQ.d.ts} +1 -1
  51. package/dist/{mod-B0rWmfW5.d.cts → mod-DzPMtIV3.d.cts} +1 -1
  52. package/dist/{mod-DHO9lk3D.d.ts → mod-ej_rLx8h.d.ts} +1 -1
  53. package/dist/mod.cjs +5 -5
  54. package/dist/mod.d.cts +6 -6
  55. package/dist/mod.d.ts +6 -6
  56. package/dist/mod.js +5 -5
  57. package/dist/nodeinfo/client.test.mjs +28 -1
  58. package/dist/nodeinfo/handler.test.mjs +2 -2
  59. package/dist/nodeinfo/mod.cjs +1 -1
  60. package/dist/nodeinfo/mod.js +1 -1
  61. package/dist/nodeinfo/types.test.mjs +1 -1
  62. package/dist/otel/exporter.test.mjs +1 -1
  63. package/dist/{outgoing-jsonld-CfUItkGW.mjs → outgoing-jsonld-Dc2OXyB-.mjs} +1 -1
  64. package/dist/{owner-CnngXDNJ.d.ts → owner-B3hNQCG8.d.cts} +12 -1
  65. package/dist/{owner-DEvZuyOE.d.cts → owner-CiBPcC6F.d.ts} +12 -1
  66. package/dist/owner-D08_JUSb.mjs +175 -0
  67. package/dist/{proof-CmtXtaul.cjs → proof-7T47tIu5.cjs} +112 -58
  68. package/dist/{proof-BhW_iARR.js → proof-BdRnLnh7.js} +112 -58
  69. package/dist/{proof-BzTt6nlk.mjs → proof-_S-wFUFM.mjs} +4 -4
  70. package/dist/{send-CZwOs7XD.mjs → send-DmcKKipr.mjs} +64 -6
  71. package/dist/sig/accept.test.mjs +1 -1
  72. package/dist/sig/http.test.mjs +4 -4
  73. package/dist/sig/key.test.mjs +170 -3
  74. package/dist/sig/ld.test.mjs +56 -4
  75. package/dist/sig/mod.cjs +2 -2
  76. package/dist/sig/mod.d.cts +3 -3
  77. package/dist/sig/mod.d.ts +3 -3
  78. package/dist/sig/mod.js +2 -2
  79. package/dist/sig/owner.test.mjs +105 -6
  80. package/dist/sig/proof.test.mjs +73 -5
  81. package/dist/{temporal-BYCnXIGk.mjs → temporal-CX_L28b-.mjs} +1 -1
  82. package/dist/{types-m8u9L86X.cjs → types-DWs-qZaY.cjs} +94 -2
  83. package/dist/{types-DTONwNqL.js → types-sXITXcWa.js} +78 -4
  84. package/dist/utils/docloader.test.mjs +28 -4
  85. package/dist/utils/kv-cache.test.mjs +1 -1
  86. package/dist/utils/mod.cjs +1 -1
  87. package/dist/utils/mod.d.cts +1 -1
  88. package/dist/utils/mod.d.ts +1 -1
  89. package/dist/utils/mod.js +1 -1
  90. package/package.json +5 -5
  91. package/dist/assert-DikXweDx.mjs +0 -23
  92. package/dist/owner-CqYsVXcd.mjs +0 -120
  93. /package/dist/{accept-CPkZzmGN.mjs → accept-Dd__NiUL.mjs} +0 -0
  94. /package/dist/{activity-listener-ell7W1s9.mjs → activity-listener-IojJ9SVl.mjs} +0 -0
  95. /package/dist/{collection-D-HqUuA2.mjs → collection-DnoYNwBC.mjs} +0 -0
  96. /package/dist/{keys-DGu1NFwu.mjs → keys-BAK-tUlf.mjs} +0 -0
  97. /package/dist/{kv-rV3vodCc.mjs → kv-CX8qfaad.mjs} +0 -0
  98. /package/dist/{kv-cache-DYsF2MhP.mjs → kv-cache-FsT1ljhs.mjs} +0 -0
  99. /package/dist/{negotiation-SQvQgUqe.mjs → negotiation-BHtZN6Y1.mjs} +0 -0
  100. /package/dist/{public-audience-Ci-r-4Q-.mjs → public-audience-CS1udGkN.mjs} +0 -0
  101. /package/dist/{retry-v_sGLH1d.mjs → retry-bMXBL97A.mjs} +0 -0
  102. /package/dist/{types-J53Kw7so.mjs → types-s4mCTGkT.mjs} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { _ as version, d as validateCryptoKey, g as name, s as fetchKey } from "./http-CNsxTbVr.js";
3
+ import { c as fetchKey, f as validateCryptoKey, o as exportJwk, p as verifyKeyOwnership, s as fetchActorDocument, v as name, y as version } from "./http-C5T-lWqB.js";
4
4
  import { getLogger } from "@logtape/logtape";
5
5
  import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, PUBLIC_COLLECTION, getTypeId, isActor } from "@fedify/vocab";
6
6
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
@@ -10,7 +10,7 @@ import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
10
10
  import jsonld from "@fedify/vocab-runtime/jsonld";
11
11
  import serialize from "json-canon";
12
12
  //#region src/sig/ld.ts
13
- const logger$3 = getLogger([
13
+ const logger$4 = getLogger([
14
14
  "fedify",
15
15
  "sig",
16
16
  "ld"
@@ -440,7 +440,7 @@ async function verifySignature(jsonLd, options = {}) {
440
440
  try {
441
441
  signature = decodeBase64(sig.signatureValue);
442
442
  } catch (error) {
443
- logger$3.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
443
+ logger$4.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
444
444
  ...sig,
445
445
  error
446
446
  });
@@ -459,7 +459,7 @@ async function verifySignature(jsonLd, options = {}) {
459
459
  try {
460
460
  sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
461
461
  } catch (error) {
462
- logger$3.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
462
+ logger$4.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
463
463
  signatureOptions: sigOpts,
464
464
  error
465
465
  });
@@ -471,7 +471,7 @@ async function verifySignature(jsonLd, options = {}) {
471
471
  try {
472
472
  docHash = await hashJsonLd(document, options.contextLoader);
473
473
  } catch (error) {
474
- logger$3.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
474
+ logger$4.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
475
475
  document,
476
476
  error
477
477
  });
@@ -482,7 +482,7 @@ async function verifySignature(jsonLd, options = {}) {
482
482
  const messageBytes = encoder.encode(message);
483
483
  if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
484
484
  if (cached) {
485
- logger$3.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
485
+ logger$4.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
486
486
  keyId: sig.creator,
487
487
  ...sig
488
488
  });
@@ -496,7 +496,7 @@ async function verifySignature(jsonLd, options = {}) {
496
496
  if (key == null) return null;
497
497
  return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
498
498
  }
499
- logger$3.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
499
+ logger$4.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
500
500
  keyId: sig.creator,
501
501
  ...sig,
502
502
  message
@@ -540,12 +540,12 @@ async function verifyJsonLdInternal(jsonLd, options, compact) {
540
540
  const key = await verifySignature(compacted, verificationOptions);
541
541
  if (key == null) return false;
542
542
  if (key.ownerId == null) {
543
- logger$3.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
543
+ logger$4.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
544
544
  return false;
545
545
  }
546
546
  attributions.delete(key.ownerId.href);
547
547
  if (attributions.size > 0) {
548
- logger$3.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
548
+ logger$4.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
549
549
  return false;
550
550
  }
551
551
  return true;
@@ -570,8 +570,20 @@ async function hashJsonLd(jsonLd, contextLoader) {
570
570
  }
571
571
  //#endregion
572
572
  //#region src/sig/owner.ts
573
+ const logger$3 = getLogger([
574
+ "fedify",
575
+ "sig",
576
+ "owner"
577
+ ]);
573
578
  /**
574
579
  * Checks if the actor of the given activity owns the specified key.
580
+ *
581
+ * Ownership is never taken from what the activity or the key say about
582
+ * themselves, as both are written by whoever sent the activity. It is
583
+ * established from a document that the owner itself serves: either the key's
584
+ * claimed owner links back to the key, or the actor the activity claims lists
585
+ * the key as its own.
586
+ *
575
587
  * @param activity The activity to check.
576
588
  * @param key The public key to check.
577
589
  * @param options Options for checking the key ownership.
@@ -586,23 +598,30 @@ async function doesActorOwnKey(activity, key, options) {
586
598
  }
587
599
  }, async (span) => {
588
600
  try {
589
- if (key.ownerId != null) {
590
- const owns = key.ownerId.href === activity.actorId?.href;
591
- span.setAttribute("activitypub.key_ownership.verified", owns);
592
- span.setAttribute("activitypub.key_ownership.method", "owner_id");
593
- return owns;
594
- }
595
- const actor = await activity.getActor(options);
596
- if (actor == null || !isActor(actor)) {
601
+ const actorId = activity.actorId;
602
+ if (actorId == null) {
597
603
  span.setAttribute("activitypub.key_ownership.verified", false);
598
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
604
+ span.setAttribute("activitypub.key_ownership.method", "none");
599
605
  return false;
600
606
  }
601
- for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
607
+ if (key.ownerId != null) {
608
+ const owner = await verifyKeyOwnership(key, options);
609
+ if (owner?.id != null && owner.id.href === actorId.href) {
610
+ span.setAttribute("activitypub.key_ownership.verified", true);
611
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
612
+ return true;
613
+ }
614
+ }
615
+ const actor = await fetchActorDocument(actorId, options);
616
+ if (actor != null && await doesActorListKey(actor, key, options)) {
602
617
  span.setAttribute("activitypub.key_ownership.verified", true);
603
618
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
604
619
  return true;
605
620
  }
621
+ logger$3.debug("The actor {actorId} does not own key {keyId}: neither the owner the key claims nor the actor's own document links the two to each other.", {
622
+ actorId: actorId.href,
623
+ keyId: key.id?.href
624
+ });
606
625
  span.setAttribute("activitypub.key_ownership.verified", false);
607
626
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
608
627
  return false;
@@ -619,9 +638,46 @@ async function doesActorOwnKey(activity, key, options) {
619
638
  });
620
639
  }
621
640
  /**
641
+ * Determines whether the given actor's own document lists the given key among
642
+ * its public keys.
643
+ *
644
+ * Keys are matched by id, which is what an actor document links to. A key
645
+ * document may leave its id implicit, though, and then there is no id for the
646
+ * actor to link to; the key material itself is the only thing the two can
647
+ * have in common, so that is what gets compared.
648
+ */
649
+ async function doesActorListKey(actor, key, options) {
650
+ if (key.id != null) {
651
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
652
+ return false;
653
+ }
654
+ if (key.publicKey == null) return false;
655
+ const publicKeys = actor.getPublicKeys({
656
+ ...options,
657
+ suppressError: true
658
+ });
659
+ for await (const publicKey of publicKeys) {
660
+ if (publicKey.publicKey == null) continue;
661
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
662
+ }
663
+ return false;
664
+ }
665
+ /**
666
+ * Compares two public keys by their key material, ignoring the metadata that
667
+ * surrounds it.
668
+ */
669
+ async function isSamePublicKey(a, b) {
670
+ const [x, y] = await Promise.all([exportJwk(a), exportJwk(b)]);
671
+ return x.kty === y.kty && x.crv === y.crv && x.n === y.n && x.e === y.e && x.x === y.x && x.y === y.y;
672
+ }
673
+ /**
622
674
  * Gets the actor that owns the specified key. Returns `null` if the key has no
623
675
  * known owner.
624
676
  *
677
+ * The owner is only returned when the key and the owner link to each other:
678
+ * a document that merely claims to own a key is not enough, as the claim and
679
+ * the key can come from the same host.
680
+ *
625
681
  * @param keyId The ID of the key to check, or the key itself.
626
682
  * @param options Options for getting the key owner.
627
683
  * @returns The actor that owns the key, or `null` if the key has no known
@@ -631,52 +687,50 @@ async function doesActorOwnKey(activity, key, options) {
631
687
  async function getKeyOwner(keyId, options) {
632
688
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
633
689
  const documentLoader = options.documentLoader ?? getDocumentLoader();
634
- const contextLoader = options.contextLoader ?? getDocumentLoader();
690
+ const fetchOptions = {
691
+ documentLoader,
692
+ contextLoader: options.contextLoader ?? getDocumentLoader(),
693
+ tracerProvider
694
+ };
695
+ if (keyId instanceof CryptographicKey) return await verifyKeyOwnership(keyId, fetchOptions);
696
+ let keyDoc;
697
+ let documentUrl = keyId;
698
+ try {
699
+ const remoteDocument = await documentLoader(keyId.href);
700
+ keyDoc = remoteDocument.document;
701
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
702
+ } catch (_) {
703
+ return null;
704
+ }
635
705
  let object;
636
- if (keyId instanceof CryptographicKey) {
637
- object = keyId;
638
- if (object.id == null) return null;
639
- keyId = object.id;
640
- } else {
641
- let keyDoc;
642
- try {
643
- const { document } = await documentLoader(keyId.href);
644
- keyDoc = document;
645
- } catch (_) {
646
- return null;
647
- }
706
+ try {
707
+ object = await Object$1.fromJsonLd(keyDoc, {
708
+ ...fetchOptions,
709
+ baseUrl: documentUrl
710
+ });
711
+ } catch (e) {
712
+ if (!(e instanceof TypeError)) throw e;
648
713
  try {
649
- object = await Object$1.fromJsonLd(keyDoc, {
650
- documentLoader,
651
- contextLoader,
652
- tracerProvider
653
- });
714
+ object = await CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
654
715
  } catch (e) {
655
- if (!(e instanceof TypeError)) throw e;
656
- try {
657
- object = await CryptographicKey.fromJsonLd(keyDoc, {
658
- documentLoader,
659
- contextLoader,
660
- tracerProvider
661
- });
662
- } catch (e) {
663
- if (e instanceof TypeError) return null;
664
- throw e;
665
- }
716
+ if (e instanceof TypeError) return null;
717
+ throw e;
666
718
  }
667
719
  }
668
- let owner = null;
669
720
  if (object instanceof CryptographicKey) {
670
- if (object.ownerId == null) return null;
671
- owner = await object.getOwner({
672
- documentLoader,
673
- contextLoader,
674
- tracerProvider
721
+ if (object.id != null && object.id.href !== keyId.href) return null;
722
+ return await verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
723
+ }
724
+ if (!isActor(object)) return null;
725
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
726
+ logger$3.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as the owner of key {keyId}.", {
727
+ documentUrl: documentUrl.href,
728
+ actorId: object.id?.href,
729
+ keyId: keyId.href
675
730
  });
676
- } else if (isActor(object)) owner = object;
677
- else return null;
678
- if (owner == null) return null;
679
- for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
731
+ return null;
732
+ }
733
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
680
734
  return null;
681
735
  }
682
736
  //#endregion
@@ -1,10 +1,10 @@
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-DeYUdFal.mjs";
5
- import { n as fetchKey, o as validateCryptoKey } from "./key-B4kUuy3o.mjs";
6
- import { n as preloadedOnlyDocumentLoader } from "./public-audience-Ci-r-4Q-.mjs";
7
- import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-CfUItkGW.mjs";
4
+ import { n as version, t as name } from "./deno-CV4wsQzy.mjs";
5
+ import { r as fetchKey, s as validateCryptoKey } from "./key-DiziIx9e.mjs";
6
+ import { n as preloadedOnlyDocumentLoader } from "./public-audience-CS1udGkN.mjs";
7
+ import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-Dc2OXyB-.mjs";
8
8
  import { Activity, DataIntegrityProof, Multikey, getTypeId } from "@fedify/vocab";
9
9
  import { SpanStatusCode, trace } from "@opentelemetry/api";
10
10
  import { getLogger } from "@logtape/logtape";
@@ -1,9 +1,10 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-DeYUdFal.mjs";
5
- import { n as doubleKnock } from "./http-79lZeYEo.mjs";
4
+ import { n as version, t as name } from "./deno-CV4wsQzy.mjs";
5
+ import { n as doubleKnock } from "./http-C9MzFrOj.mjs";
6
6
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
+ import { UrlError, validatePublicUrl } from "@fedify/vocab-runtime";
7
8
  import { getLogger } from "@logtape/logtape";
8
9
  //#region src/federation/send.ts
9
10
  /**
@@ -91,18 +92,31 @@ async function readLimitedResponseBody(response, maxBytes) {
91
92
  if (truncated) result += "… (truncated)";
92
93
  return result;
93
94
  }
94
- async function sendActivityInternal({ activity, activityId, keys, inbox, headers, specDeterminer, tracerProvider }, span) {
95
+ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPrivateAddress, headers, specDeterminer, tracerProvider }, span) {
95
96
  const logger = getLogger([
96
97
  "fedify",
97
98
  "federation",
98
99
  "outbox"
99
100
  ]);
101
+ async function validateUrl(url) {
102
+ if (!allowPrivateAddress) try {
103
+ await validatePublicUrl(url);
104
+ } catch (error) {
105
+ if (error instanceof UrlError) logger.error("Disallowed private URL: {url}", {
106
+ url,
107
+ error
108
+ });
109
+ throw error;
110
+ }
111
+ }
112
+ await validateUrl(inbox.href);
100
113
  headers = new Headers(headers);
101
114
  headers.set("Content-Type", "application/activity+json");
102
115
  const request = new Request(inbox, {
103
116
  method: "POST",
104
117
  headers,
105
- body: JSON.stringify(activity)
118
+ body: JSON.stringify(activity),
119
+ redirect: "manual"
106
120
  });
107
121
  let rsaKey = null;
108
122
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -118,9 +132,10 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, headers
118
132
  });
119
133
  let response;
120
134
  try {
121
- response = rsaKey == null ? await fetch(request) : await doubleKnock(request, rsaKey, {
135
+ response = rsaKey == null ? await fetchWithValidatedRedirects(request, validateUrl) : await doubleKnock(request, rsaKey, {
122
136
  tracerProvider,
123
- specDeterminer
137
+ specDeterminer,
138
+ validateRedirect: validateUrl
124
139
  });
125
140
  } catch (error) {
126
141
  logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
@@ -152,6 +167,49 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, headers
152
167
  "activitypub.activity.id": activityId ?? ""
153
168
  });
154
169
  }
170
+ async function fetchWithValidatedRedirects(request, validateUrl) {
171
+ let body = await request.clone().text();
172
+ for (let redirects = 0;; redirects++) {
173
+ const response = await fetch(request, { redirect: "manual" });
174
+ const location = response.headers.get("Location");
175
+ if (![
176
+ 301,
177
+ 302,
178
+ 303,
179
+ 307,
180
+ 308
181
+ ].includes(response.status) || location == null) return response;
182
+ await response.body?.cancel();
183
+ if (redirects >= 20) throw new TypeError("Too many redirects");
184
+ const url = new URL(location, request.url);
185
+ await validateUrl(url.href);
186
+ const headers = new Headers(request.headers);
187
+ if (url.origin !== new URL(request.url).origin) {
188
+ headers.delete("Authorization");
189
+ headers.delete("Proxy-Authorization");
190
+ headers.delete("Cookie");
191
+ headers.delete("Host");
192
+ }
193
+ let method = request.method;
194
+ if ((response.status === 301 || response.status === 302) && method === "POST" || response.status === 303 && method !== "GET" && method !== "HEAD") {
195
+ method = "GET";
196
+ body = void 0;
197
+ for (const name of [
198
+ "Content-Encoding",
199
+ "Content-Language",
200
+ "Content-Length",
201
+ "Content-Location",
202
+ "Content-Type"
203
+ ]) headers.delete(name);
204
+ }
205
+ request = new Request(url, {
206
+ method,
207
+ headers,
208
+ body,
209
+ redirect: "manual"
210
+ });
211
+ }
212
+ }
155
213
  /**
156
214
  * An error that is thrown when an activity fails to send to a remote inbox.
157
215
  * It contains structured information about the failure, including the HTTP
@@ -1,7 +1,7 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { i as validateAcceptSignature, n as fulfillAcceptSignature, r as parseAcceptSignature, t as formatAcceptSignature } from "../accept-CPkZzmGN.mjs";
4
+ import { i as validateAcceptSignature, n as fulfillAcceptSignature, r as parseAcceptSignature, t as formatAcceptSignature } from "../accept-Dd__NiUL.mjs";
5
5
  import { test } from "@fedify/fixture";
6
6
  import { deepStrictEqual, strictEqual } from "node:assert/strict";
7
7
  //#region src/sig/accept.test.ts
@@ -5,11 +5,11 @@ import { t as esm_default } from "../esm-DVILvP5e.mjs";
5
5
  import { t as assertEquals } from "../assert_equals-Ew3jOFa3.mjs";
6
6
  import { i as assertExists, t as assertStringIncludes } from "../std__assert-CRDpx_HF.mjs";
7
7
  import { n as assertFalse, t as assertRejects } from "../assert_rejects-B-qJtC9Z.mjs";
8
+ import { t as assert } from "../assert-BhQd8QHP.mjs";
8
9
  import { t as assertThrows } from "../assert_throws-4NwKEy2q.mjs";
9
- import { t as assert } from "../assert-DikXweDx.mjs";
10
- import { t as exportJwk } from "../key-B4kUuy3o.mjs";
11
- import { a as parseRfc9421Signature, c as timingSafeEqual, i as formatRfc9421SignatureParameters, l as verifyRequest, n as doubleKnock, o as parseRfc9421SignatureInput, r as formatRfc9421Signature, s as signRequest, t as createRfc9421SignatureBase, u as verifyRequestDetailed } from "../http-79lZeYEo.mjs";
12
- import { i as rsaPrivateKey2, l as rsaPublicKey5, o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-DGu1NFwu.mjs";
10
+ import { t as exportJwk } from "../key-DiziIx9e.mjs";
11
+ import { a as parseRfc9421Signature, c as timingSafeEqual, i as formatRfc9421SignatureParameters, l as verifyRequest, n as doubleKnock, o as parseRfc9421SignatureInput, r as formatRfc9421Signature, s as signRequest, t as createRfc9421SignatureBase, u as verifyRequestDetailed } from "../http-C9MzFrOj.mjs";
12
+ import { i as rsaPrivateKey2, l as rsaPublicKey5, o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-BAK-tUlf.mjs";
13
13
  import { createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
14
14
  import { FetchError, exportSpki } from "@fedify/vocab-runtime";
15
15
  import { encodeBase64 } from "byte-encodings/base64";
@@ -4,9 +4,10 @@ globalThis.addEventListener = () => {};
4
4
  import { t as assertEquals } from "../assert_equals-Ew3jOFa3.mjs";
5
5
  import "../std__assert-CRDpx_HF.mjs";
6
6
  import { t as assertRejects } from "../assert_rejects-B-qJtC9Z.mjs";
7
+ import { t as assert } from "../assert-BhQd8QHP.mjs";
7
8
  import { t as assertThrows } from "../assert_throws-4NwKEy2q.mjs";
8
- import { a as importJwk, i as generateCryptoKeyPair, n as fetchKey, o as validateCryptoKey, r as fetchKeyDetailed, t as exportJwk } from "../key-B4kUuy3o.mjs";
9
- import { c as rsaPublicKey3, i as rsaPrivateKey2, o as rsaPublicKey1, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-DGu1NFwu.mjs";
9
+ import { a as generateCryptoKeyPair, i as fetchKeyDetailed, o as importJwk, r as fetchKey, s as validateCryptoKey, t as exportJwk } from "../key-DiziIx9e.mjs";
10
+ import { c as rsaPublicKey3, i as rsaPrivateKey2, o as rsaPublicKey1, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-BAK-tUlf.mjs";
10
11
  import { createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
11
12
  import { CryptographicKey, Multikey } from "@fedify/vocab";
12
13
  import { FetchError } from "@fedify/vocab-runtime";
@@ -267,7 +268,7 @@ test("fetchKeyDetailed()", async () => {
267
268
  key: rsaPublicKey1,
268
269
  cached: false
269
270
  });
270
- assertEquals(documentLoaderCalls, 1);
271
+ assertEquals(documentLoaderCalls, 2);
271
272
  const spans = exporter.getSpans("activitypub.fetch_key");
272
273
  assertEquals(spans.length, 2);
273
274
  assertEquals(spans[0].attributes["activitypub.actor.key.cached"], true);
@@ -398,5 +399,171 @@ test("fetchKey() returns null for a malformed actor publicKey", async () => {
398
399
  cached: true
399
400
  });
400
401
  });
402
+ test("fetchKey() rejects a key whose owner does not link back", async () => {
403
+ const keyId = "https://attacker.example/key";
404
+ const keyDocument = await rsaPublicKey1.toJsonLd({ contextLoader: mockDocumentLoader });
405
+ const serveKeyOwnedBy = (owner) => ({
406
+ documentLoader(resource) {
407
+ if (resource === keyId) return Promise.resolve({
408
+ contextUrl: null,
409
+ documentUrl: resource,
410
+ document: {
411
+ ...keyDocument,
412
+ id: keyId,
413
+ owner
414
+ }
415
+ });
416
+ return mockDocumentLoader(resource);
417
+ },
418
+ contextLoader: mockDocumentLoader
419
+ });
420
+ assertEquals(await fetchKey(keyId, CryptographicKey, serveKeyOwnedBy("https://example.com/person")), {
421
+ key: null,
422
+ cached: false
423
+ });
424
+ assertEquals(await fetchKey(keyId, CryptographicKey, serveKeyOwnedBy("https://impersonated.invalid/users/victim")), {
425
+ key: null,
426
+ cached: false
427
+ });
428
+ });
429
+ test("fetchKey() rejects a Multikey whose controller does not link back", async () => {
430
+ const keyId = "https://attacker.example/multikey";
431
+ const keyDocument = await ed25519Multikey.toJsonLd({ contextLoader: mockDocumentLoader });
432
+ assertEquals(await fetchKey(keyId, Multikey, {
433
+ documentLoader(resource) {
434
+ if (resource === keyId) return Promise.resolve({
435
+ contextUrl: null,
436
+ documentUrl: resource,
437
+ document: {
438
+ ...keyDocument,
439
+ id: keyId,
440
+ controller: "https://example.com/person2"
441
+ }
442
+ });
443
+ return mockDocumentLoader(resource);
444
+ },
445
+ contextLoader: mockDocumentLoader
446
+ }), {
447
+ key: null,
448
+ cached: false
449
+ });
450
+ });
451
+ test("fetchKey() rejects an actor document from another origin", async () => {
452
+ const keyId = "https://attacker.example/key";
453
+ const impersonated = "https://example.com/person";
454
+ const { publicKeyPem } = await rsaPublicKey1.toJsonLd({ contextLoader: mockDocumentLoader });
455
+ assertEquals(await fetchKey(keyId, CryptographicKey, {
456
+ documentLoader(resource) {
457
+ if (resource === keyId) return Promise.resolve({
458
+ contextUrl: null,
459
+ documentUrl: resource,
460
+ document: {
461
+ "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"],
462
+ id: impersonated,
463
+ type: "Person",
464
+ publicKey: [{
465
+ id: `${impersonated}#main-key`,
466
+ type: "CryptographicKey",
467
+ owner: impersonated,
468
+ publicKeyPem
469
+ }]
470
+ }
471
+ });
472
+ return mockDocumentLoader(resource);
473
+ },
474
+ contextLoader: mockDocumentLoader
475
+ }), {
476
+ key: null,
477
+ cached: false
478
+ });
479
+ });
480
+ test("fetchKey() rejects a key that disowns the actor document holding it", async () => {
481
+ const actorId = "https://attacker.example/actor";
482
+ const keyId = `${actorId}#main-key`;
483
+ const { publicKeyPem } = await rsaPublicKey1.toJsonLd({ contextLoader: mockDocumentLoader });
484
+ assertEquals(await fetchKey(keyId, CryptographicKey, {
485
+ documentLoader(resource) {
486
+ if (resource === keyId || resource === actorId) return Promise.resolve({
487
+ contextUrl: null,
488
+ documentUrl: resource,
489
+ document: {
490
+ "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"],
491
+ id: actorId,
492
+ type: "Person",
493
+ publicKey: [{
494
+ id: keyId,
495
+ type: "CryptographicKey",
496
+ owner: "https://example.com/person",
497
+ publicKeyPem
498
+ }]
499
+ }
500
+ });
501
+ return mockDocumentLoader(resource);
502
+ },
503
+ contextLoader: mockDocumentLoader
504
+ }), {
505
+ key: null,
506
+ cached: false
507
+ });
508
+ });
509
+ test("fetchKey() records the owner its actor document establishes", async () => {
510
+ const { key } = await fetchKey("https://example.com/users/handle#main-key", CryptographicKey, {
511
+ documentLoader: mockDocumentLoader,
512
+ contextLoader: mockDocumentLoader
513
+ });
514
+ assertEquals(key?.ownerId, new URL("https://example.com/users/handle"));
515
+ });
516
+ test("fetchKey() accepts a key document that leaves its id implicit", async () => {
517
+ const keyId = "https://example.com/key";
518
+ const keyDocument = await rsaPublicKey1.toJsonLd({ contextLoader: mockDocumentLoader });
519
+ delete keyDocument.id;
520
+ const { key } = await fetchKey(keyId, CryptographicKey, {
521
+ documentLoader(resource) {
522
+ if (resource === keyId) return Promise.resolve({
523
+ contextUrl: null,
524
+ documentUrl: resource,
525
+ document: keyDocument
526
+ });
527
+ return mockDocumentLoader(resource);
528
+ },
529
+ contextLoader: mockDocumentLoader
530
+ });
531
+ assertEquals(key?.id, new URL(keyId));
532
+ assertEquals(key?.ownerId, new URL("https://example.com/person"));
533
+ assert(key?.publicKey != null);
534
+ });
535
+ test("fetchKey() records the controller an actor document establishes", async () => {
536
+ const actorId = "https://example.com/multikey-actor";
537
+ const keyId = `${actorId}#assertion`;
538
+ const { publicKeyMultibase } = await ed25519Multikey.toJsonLd({ contextLoader: mockDocumentLoader });
539
+ const { key } = await fetchKey(keyId, Multikey, {
540
+ documentLoader(resource) {
541
+ if (resource === actorId || resource === keyId) return Promise.resolve({
542
+ contextUrl: null,
543
+ documentUrl: actorId,
544
+ document: {
545
+ "@context": [
546
+ "https://www.w3.org/ns/activitystreams",
547
+ "https://w3id.org/security/v1",
548
+ "https://w3id.org/security/multikey/v1",
549
+ "https://w3id.org/security/data-integrity/v1",
550
+ "https://www.w3.org/ns/did/v1"
551
+ ],
552
+ id: actorId,
553
+ type: "Person",
554
+ assertionMethod: [{
555
+ id: keyId,
556
+ type: "Multikey",
557
+ publicKeyMultibase
558
+ }]
559
+ }
560
+ });
561
+ return mockDocumentLoader(resource);
562
+ },
563
+ contextLoader: mockDocumentLoader
564
+ });
565
+ assertEquals(key?.controllerId, new URL(actorId));
566
+ assert(key?.publicKey != null);
567
+ });
401
568
  //#endregion
402
569
  export {};