@fedify/fedify 2.3.7 → 2.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/{assert_instance_of-DBC5X09g.mjs → assert-jSdZMYam.mjs} +19 -1
  2. package/dist/{builder-Bg7nkigw.mjs → builder-CDForRSL.mjs} +3 -3
  3. package/dist/{client-D1KuWxjH.mjs → client-DYDoDpMa.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-DVoTs_wM.mjs → context-BepjCFHN.mjs} +1 -0
  10. package/dist/{context-BxVVO5Ro.d.ts → context-CAKnQy1x.d.ts} +4 -3
  11. package/dist/{context-BpmLyiPx.d.cts → context-CSIggG9_.d.cts} +4 -3
  12. package/dist/{deno-CTdCdRmf.mjs → deno--DCBC7WG.mjs} +1 -1
  13. package/dist/{docloader-BVBWf8Bg.mjs → docloader-BAdp-ZeK.mjs} +2 -2
  14. package/dist/federation/builder.test.mjs +2 -2
  15. package/dist/federation/circuit-breaker.test.mjs +3 -3
  16. package/dist/federation/collection.test.mjs +1 -1
  17. package/dist/federation/handler.test.mjs +128 -11
  18. package/dist/federation/idempotency.test.mjs +4 -4
  19. package/dist/federation/inbox.test.mjs +1 -1
  20. package/dist/federation/keycache.test.mjs +44 -10
  21. package/dist/federation/kv.test.mjs +1 -1
  22. package/dist/federation/metrics.test.mjs +1 -1
  23. package/dist/federation/middleware.test.mjs +109 -19
  24. package/dist/federation/mod.cjs +1 -1
  25. package/dist/federation/mod.d.cts +2 -2
  26. package/dist/federation/mod.d.ts +2 -2
  27. package/dist/federation/mod.js +1 -1
  28. package/dist/federation/mq.test.mjs +1 -1
  29. package/dist/federation/negotiation.test.mjs +2 -2
  30. package/dist/federation/retry.test.mjs +1 -1
  31. package/dist/federation/router.test.mjs +1 -1
  32. package/dist/federation/send.test.mjs +141 -7
  33. package/dist/federation/temporal.test.mjs +2 -2
  34. package/dist/federation/webfinger.test.mjs +3 -3
  35. package/dist/{http-DRVY9K4R.js → http-BKJYj9oz.js} +155 -7
  36. package/dist/{http-BjV0BTWd.cjs → http-ChVf88XZ.cjs} +166 -6
  37. package/dist/{http-B3-zan5-.mjs → http-ClEDLGpr.mjs} +4 -4
  38. package/dist/{http-lf8Hsd91.d.ts → http-DQmNpfym.d.ts} +1 -1
  39. package/dist/{http-VyDTd4G3.d.cts → http-DiWQB8Mr.d.cts} +1 -1
  40. package/dist/{key-C_a6iE1-.mjs → key-C-7sqo8D.mjs} +155 -7
  41. package/dist/{keycache-BeU0LCII.mjs → keycache-B3qRQNLj.mjs} +12 -4
  42. package/dist/{kv-cache-BjjcmjtG.mjs → kv-cache-C5FK4PLG.mjs} +1 -1
  43. package/dist/{kv-cache-b1dJZHUx.js → kv-cache-C_w70bFh.js} +2 -2
  44. package/dist/{kv-cache-OzUoHKnZ.cjs → kv-cache-DFBOAyNj.cjs} +2 -2
  45. package/dist/{ld-COo05yJj.mjs → ld-CtFHB6rU.mjs} +3 -3
  46. package/dist/{metrics-V6vX0M13.mjs → metrics-FDcYXRP5.mjs} +1 -1
  47. package/dist/{middleware-EDVv6ewB.cjs → middleware-BdDtzhXb.cjs} +101 -25
  48. package/dist/{middleware-DRk6xiYo.mjs → middleware-COzI8bCL.mjs} +41 -30
  49. package/dist/{middleware-K13LhN5w.js → middleware-DunPXFJL.js} +101 -25
  50. package/dist/{middleware-DRGWEo0V.mjs → middleware-K7mJeIgT.mjs} +1 -1
  51. package/dist/{mod-yvIXFAEi.d.cts → mod-1TuoXkGs.d.cts} +1 -1
  52. package/dist/{mod-B0hW12_O.d.cts → mod-Bid79LFU.d.cts} +1 -1
  53. package/dist/{mod-Rpy4Uwkk.d.ts → mod-CFuyfw3c.d.ts} +1 -1
  54. package/dist/{mod-DFvNJcNb.d.ts → mod-DHgc4ygG.d.ts} +1 -1
  55. package/dist/{mod-CjERT09F.d.cts → mod-PVR75MeU.d.cts} +1 -1
  56. package/dist/{mod-COIAjwRS.d.ts → mod-TLEvgT1i.d.ts} +1 -1
  57. package/dist/mod.cjs +5 -5
  58. package/dist/mod.d.cts +6 -6
  59. package/dist/mod.d.ts +6 -6
  60. package/dist/mod.js +5 -5
  61. package/dist/nodeinfo/client.test.mjs +28 -1
  62. package/dist/nodeinfo/handler.test.mjs +3 -3
  63. package/dist/nodeinfo/mod.cjs +1 -1
  64. package/dist/nodeinfo/mod.js +1 -1
  65. package/dist/nodeinfo/types.test.mjs +1 -1
  66. package/dist/otel/exporter.test.mjs +1 -1
  67. package/dist/{outgoing-jsonld-OFoubetZ.mjs → outgoing-jsonld-HOAywiid.mjs} +1 -1
  68. package/dist/{owner-CnngXDNJ.d.ts → owner-B3hNQCG8.d.cts} +12 -1
  69. package/dist/owner-CGuS9lE7.mjs +175 -0
  70. package/dist/{owner-DEvZuyOE.d.cts → owner-CiBPcC6F.d.ts} +12 -1
  71. package/dist/{proof-kFq0IDK4.mjs → proof--56drUyt.mjs} +5 -5
  72. package/dist/{proof-Xk8lHNc0.cjs → proof-Dgozne0w.cjs} +112 -58
  73. package/dist/{proof-D6gZeewf.js → proof-tjbzynMa.js} +112 -58
  74. package/dist/{send-3lH63Nqf.mjs → send-CC1A7ATC.mjs} +68 -11
  75. package/dist/sig/accept.test.mjs +1 -1
  76. package/dist/sig/http.test.mjs +4 -4
  77. package/dist/sig/key.test.mjs +170 -3
  78. package/dist/sig/ld.test.mjs +56 -4
  79. package/dist/sig/mod.cjs +2 -2
  80. package/dist/sig/mod.d.cts +3 -3
  81. package/dist/sig/mod.d.ts +3 -3
  82. package/dist/sig/mod.js +2 -2
  83. package/dist/sig/owner.test.mjs +105 -6
  84. package/dist/sig/proof.test.mjs +73 -5
  85. package/dist/{temporal-Chwx9cEn.mjs → temporal-DvptXZ7V.mjs} +1 -1
  86. package/dist/testing/mod.mjs +1 -1
  87. package/dist/{types-m8u9L86X.cjs → types-DWs-qZaY.cjs} +94 -2
  88. package/dist/{types-DTONwNqL.js → types-sXITXcWa.js} +78 -4
  89. package/dist/utils/docloader.test.mjs +28 -4
  90. package/dist/utils/kv-cache.test.mjs +1 -1
  91. package/dist/utils/mod.cjs +1 -1
  92. package/dist/utils/mod.d.cts +1 -1
  93. package/dist/utils/mod.d.ts +1 -1
  94. package/dist/utils/mod.js +1 -1
  95. package/package.json +6 -6
  96. package/dist/assert-OguE97r2.mjs +0 -23
  97. package/dist/owner-B3720pz3.mjs +0 -120
  98. /package/dist/{accept-CPkZzmGN.mjs → accept-Dd__NiUL.mjs} +0 -0
  99. /package/dist/{activity-listener-tztVvlNb.mjs → activity-listener-ell7W1s9.mjs} +0 -0
  100. /package/dist/{circuit-breaker-D1fxthDI.mjs → circuit-breaker-CDABzqVf.mjs} +0 -0
  101. /package/dist/{circuit-breaker-test-utils-CAdwjgMi.mjs → circuit-breaker-test-utils-Dm5MM6l9.mjs} +0 -0
  102. /package/dist/{collection-Cc3DVAhE.mjs → collection-CA3V5zyK.mjs} +0 -0
  103. /package/dist/{keys-DGu1NFwu.mjs → keys-BAK-tUlf.mjs} +0 -0
  104. /package/dist/{kv-rV3vodCc.mjs → kv-CX8qfaad.mjs} +0 -0
  105. /package/dist/{negotiation-DDstyBvc.mjs → negotiation-CDW-_gUU.mjs} +0 -0
  106. /package/dist/{public-audience-DZJAUUi8.mjs → public-audience-jwoSIGUw.mjs} +0 -0
  107. /package/dist/{retry-CXg_MBI-.mjs → retry-_VvV0h9f.mjs} +0 -0
  108. /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 { F as version, P as name, _ as measureSignatureKeyFetch, d as validateCryptoKey, f as getDurationMs, p as getFederationMetrics, s as fetchKey } from "./http-DRVY9K4R.js";
3
+ import { I as name, L as version, c as fetchKey, f as validateCryptoKey, h as getFederationMetrics, m as getDurationMs, o as exportJwk, p as verifyKeyOwnership, s as fetchActorDocument, y as measureSignatureKeyFetch } from "./http-BKJYj9oz.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"
@@ -453,7 +453,7 @@ async function verifySignature(jsonLd, options = {}) {
453
453
  try {
454
454
  signature = decodeBase64(sig.signatureValue);
455
455
  } catch (error) {
456
- logger$3.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
456
+ logger$4.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
457
457
  ...sig,
458
458
  error
459
459
  });
@@ -472,7 +472,7 @@ async function verifySignature(jsonLd, options = {}) {
472
472
  try {
473
473
  sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
474
474
  } catch (error) {
475
- logger$3.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
475
+ logger$4.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
476
476
  signatureOptions: sigOpts,
477
477
  error
478
478
  });
@@ -484,7 +484,7 @@ async function verifySignature(jsonLd, options = {}) {
484
484
  try {
485
485
  docHash = await hashJsonLd(document, options.contextLoader);
486
486
  } catch (error) {
487
- logger$3.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
487
+ logger$4.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
488
488
  document,
489
489
  error
490
490
  });
@@ -495,7 +495,7 @@ async function verifySignature(jsonLd, options = {}) {
495
495
  const messageBytes = encoder.encode(message);
496
496
  if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
497
497
  if (cached) {
498
- logger$3.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
498
+ logger$4.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
499
499
  keyId: sig.creator,
500
500
  ...sig
501
501
  });
@@ -509,7 +509,7 @@ async function verifySignature(jsonLd, options = {}) {
509
509
  if (key == null) return null;
510
510
  return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
511
511
  }
512
- 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}", {
512
+ 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}", {
513
513
  keyId: sig.creator,
514
514
  ...sig,
515
515
  message
@@ -588,12 +588,12 @@ async function verifyJsonLdInternal(jsonLd, options, compact) {
588
588
  const key = await verifySignature(compacted, verificationOptions);
589
589
  if (key == null) return false;
590
590
  if (key.ownerId == null) {
591
- logger$3.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
591
+ logger$4.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
592
592
  return false;
593
593
  }
594
594
  attributions.delete(key.ownerId.href);
595
595
  if (attributions.size > 0) {
596
- logger$3.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
596
+ logger$4.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
597
597
  return false;
598
598
  }
599
599
  verified = true;
@@ -622,8 +622,20 @@ async function hashJsonLd(jsonLd, contextLoader) {
622
622
  }
623
623
  //#endregion
624
624
  //#region src/sig/owner.ts
625
+ const logger$3 = getLogger([
626
+ "fedify",
627
+ "sig",
628
+ "owner"
629
+ ]);
625
630
  /**
626
631
  * Checks if the actor of the given activity owns the specified key.
632
+ *
633
+ * Ownership is never taken from what the activity or the key say about
634
+ * themselves, as both are written by whoever sent the activity. It is
635
+ * established from a document that the owner itself serves: either the key's
636
+ * claimed owner links back to the key, or the actor the activity claims lists
637
+ * the key as its own.
638
+ *
627
639
  * @param activity The activity to check.
628
640
  * @param key The public key to check.
629
641
  * @param options Options for checking the key ownership.
@@ -638,23 +650,30 @@ async function doesActorOwnKey(activity, key, options) {
638
650
  }
639
651
  }, async (span) => {
640
652
  try {
641
- if (key.ownerId != null) {
642
- const owns = key.ownerId.href === activity.actorId?.href;
643
- span.setAttribute("activitypub.key_ownership.verified", owns);
644
- span.setAttribute("activitypub.key_ownership.method", "owner_id");
645
- return owns;
646
- }
647
- const actor = await activity.getActor(options);
648
- if (actor == null || !isActor(actor)) {
653
+ const actorId = activity.actorId;
654
+ if (actorId == null) {
649
655
  span.setAttribute("activitypub.key_ownership.verified", false);
650
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
656
+ span.setAttribute("activitypub.key_ownership.method", "none");
651
657
  return false;
652
658
  }
653
- for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
659
+ if (key.ownerId != null) {
660
+ const owner = await verifyKeyOwnership(key, options);
661
+ if (owner?.id != null && owner.id.href === actorId.href) {
662
+ span.setAttribute("activitypub.key_ownership.verified", true);
663
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
664
+ return true;
665
+ }
666
+ }
667
+ const actor = await fetchActorDocument(actorId, options);
668
+ if (actor != null && await doesActorListKey(actor, key, options)) {
654
669
  span.setAttribute("activitypub.key_ownership.verified", true);
655
670
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
656
671
  return true;
657
672
  }
673
+ 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.", {
674
+ actorId: actorId.href,
675
+ keyId: key.id?.href
676
+ });
658
677
  span.setAttribute("activitypub.key_ownership.verified", false);
659
678
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
660
679
  return false;
@@ -671,9 +690,46 @@ async function doesActorOwnKey(activity, key, options) {
671
690
  });
672
691
  }
673
692
  /**
693
+ * Determines whether the given actor's own document lists the given key among
694
+ * its public keys.
695
+ *
696
+ * Keys are matched by id, which is what an actor document links to. A key
697
+ * document may leave its id implicit, though, and then there is no id for the
698
+ * actor to link to; the key material itself is the only thing the two can
699
+ * have in common, so that is what gets compared.
700
+ */
701
+ async function doesActorListKey(actor, key, options) {
702
+ if (key.id != null) {
703
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
704
+ return false;
705
+ }
706
+ if (key.publicKey == null) return false;
707
+ const publicKeys = actor.getPublicKeys({
708
+ ...options,
709
+ suppressError: true
710
+ });
711
+ for await (const publicKey of publicKeys) {
712
+ if (publicKey.publicKey == null) continue;
713
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
714
+ }
715
+ return false;
716
+ }
717
+ /**
718
+ * Compares two public keys by their key material, ignoring the metadata that
719
+ * surrounds it.
720
+ */
721
+ async function isSamePublicKey(a, b) {
722
+ const [x, y] = await Promise.all([exportJwk(a), exportJwk(b)]);
723
+ 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;
724
+ }
725
+ /**
674
726
  * Gets the actor that owns the specified key. Returns `null` if the key has no
675
727
  * known owner.
676
728
  *
729
+ * The owner is only returned when the key and the owner link to each other:
730
+ * a document that merely claims to own a key is not enough, as the claim and
731
+ * the key can come from the same host.
732
+ *
677
733
  * @param keyId The ID of the key to check, or the key itself.
678
734
  * @param options Options for getting the key owner.
679
735
  * @returns The actor that owns the key, or `null` if the key has no known
@@ -683,52 +739,50 @@ async function doesActorOwnKey(activity, key, options) {
683
739
  async function getKeyOwner(keyId, options) {
684
740
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
685
741
  const documentLoader = options.documentLoader ?? getDocumentLoader();
686
- const contextLoader = options.contextLoader ?? getDocumentLoader();
742
+ const fetchOptions = {
743
+ documentLoader,
744
+ contextLoader: options.contextLoader ?? getDocumentLoader(),
745
+ tracerProvider
746
+ };
747
+ if (keyId instanceof CryptographicKey) return await verifyKeyOwnership(keyId, fetchOptions);
748
+ let keyDoc;
749
+ let documentUrl = keyId;
750
+ try {
751
+ const remoteDocument = await documentLoader(keyId.href);
752
+ keyDoc = remoteDocument.document;
753
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
754
+ } catch (_) {
755
+ return null;
756
+ }
687
757
  let object;
688
- if (keyId instanceof CryptographicKey) {
689
- object = keyId;
690
- if (object.id == null) return null;
691
- keyId = object.id;
692
- } else {
693
- let keyDoc;
694
- try {
695
- const { document } = await documentLoader(keyId.href);
696
- keyDoc = document;
697
- } catch (_) {
698
- return null;
699
- }
758
+ try {
759
+ object = await Object$1.fromJsonLd(keyDoc, {
760
+ ...fetchOptions,
761
+ baseUrl: documentUrl
762
+ });
763
+ } catch (e) {
764
+ if (!(e instanceof TypeError)) throw e;
700
765
  try {
701
- object = await Object$1.fromJsonLd(keyDoc, {
702
- documentLoader,
703
- contextLoader,
704
- tracerProvider
705
- });
766
+ object = await CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
706
767
  } catch (e) {
707
- if (!(e instanceof TypeError)) throw e;
708
- try {
709
- object = await CryptographicKey.fromJsonLd(keyDoc, {
710
- documentLoader,
711
- contextLoader,
712
- tracerProvider
713
- });
714
- } catch (e) {
715
- if (e instanceof TypeError) return null;
716
- throw e;
717
- }
768
+ if (e instanceof TypeError) return null;
769
+ throw e;
718
770
  }
719
771
  }
720
- let owner = null;
721
772
  if (object instanceof CryptographicKey) {
722
- if (object.ownerId == null) return null;
723
- owner = await object.getOwner({
724
- documentLoader,
725
- contextLoader,
726
- tracerProvider
773
+ if (object.id != null && object.id.href !== keyId.href) return null;
774
+ return await verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
775
+ }
776
+ if (!isActor(object)) return null;
777
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
778
+ 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}.", {
779
+ documentUrl: documentUrl.href,
780
+ actorId: object.id?.href,
781
+ keyId: keyId.href
727
782
  });
728
- } else if (isActor(object)) owner = object;
729
- else return null;
730
- if (owner == null) return null;
731
- for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
783
+ return null;
784
+ }
785
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
732
786
  return null;
733
787
  }
734
788
  //#endregion
@@ -1,12 +1,12 @@
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-CTdCdRmf.mjs";
5
- import { n as getDurationMs, r as getFederationMetrics } from "./metrics-V6vX0M13.mjs";
6
- import { n as doubleKnock } from "./http-B3-zan5-.mjs";
4
+ import { n as version, t as name } from "./deno--DCBC7WG.mjs";
5
+ import { n as getDurationMs, r as getFederationMetrics } from "./metrics-FDcYXRP5.mjs";
6
+ import { n as doubleKnock } from "./http-ClEDLGpr.mjs";
7
7
  import { getLogger } from "@logtape/logtape";
8
8
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
9
- import { FetchError } from "@fedify/vocab-runtime";
9
+ import { FetchError, UrlError, validatePublicUrl } from "@fedify/vocab-runtime";
10
10
  //#region src/federation/send.ts
11
11
  /**
12
12
  * Extracts the inbox URLs from recipients.
@@ -112,7 +112,7 @@ async function readLimitedResponseBody(response, maxBytes) {
112
112
  if (truncated) result += "… (truncated)";
113
113
  return result;
114
114
  }
115
- async function sendActivityInternal({ activity, activityId, activityType, keys, inbox, headers, specDeterminer, meterProvider, tracerProvider }, span) {
115
+ async function sendActivityInternal({ activity, activityId, activityType, keys, inbox, allowPrivateAddress, headers, specDeterminer, meterProvider, tracerProvider }, span) {
116
116
  const logger = getLogger([
117
117
  "fedify",
118
118
  "federation",
@@ -121,12 +121,25 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
121
121
  const federationMetrics = getFederationMetrics(meterProvider);
122
122
  const started = performance.now();
123
123
  let deliverySuccess = false;
124
+ async function validateUrl(url) {
125
+ if (!allowPrivateAddress) try {
126
+ await validatePublicUrl(url);
127
+ } catch (error) {
128
+ if (error instanceof UrlError) logger.error("Disallowed private URL: {url}", {
129
+ url,
130
+ error
131
+ });
132
+ throw error;
133
+ }
134
+ }
135
+ await validateUrl(inbox.href);
124
136
  headers = new Headers(headers);
125
137
  headers.set("Content-Type", "application/activity+json");
126
138
  const request = new Request(inbox, {
127
139
  method: "POST",
128
140
  headers,
129
- body: JSON.stringify(activity)
141
+ body: JSON.stringify(activity),
142
+ redirect: "manual"
130
143
  });
131
144
  let rsaKey = null;
132
145
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -142,19 +155,20 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
142
155
  });
143
156
  let response;
144
157
  try {
145
- response = rsaKey == null ? await fetch(request) : await doubleKnock(request, rsaKey, {
158
+ response = rsaKey == null ? await fetchWithValidatedRedirects(request, validateUrl) : await doubleKnock(request, rsaKey, {
146
159
  tracerProvider,
147
- specDeterminer
160
+ specDeterminer,
161
+ validateRedirect: validateUrl
148
162
  });
149
163
  } catch (error) {
150
- const transportError = error instanceof FetchError ? error : createFetchError(inbox.href, error);
164
+ const failure = error instanceof FetchError || error instanceof UrlError ? error : createFetchError(inbox.href, error);
151
165
  logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
152
166
  activityId,
153
167
  inbox: inbox.href,
154
- error: transportError
168
+ error: failure
155
169
  });
156
170
  federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
157
- throw transportError;
171
+ throw failure;
158
172
  }
159
173
  try {
160
174
  if (!response.ok) {
@@ -191,6 +205,49 @@ function createFetchError(url, cause) {
191
205
  error.cause = cause;
192
206
  return error;
193
207
  }
208
+ async function fetchWithValidatedRedirects(request, validateUrl) {
209
+ let body = await request.clone().text();
210
+ for (let redirects = 0;; redirects++) {
211
+ const response = await fetch(request, { redirect: "manual" });
212
+ const location = response.headers.get("Location");
213
+ if (![
214
+ 301,
215
+ 302,
216
+ 303,
217
+ 307,
218
+ 308
219
+ ].includes(response.status) || location == null) return response;
220
+ await response.body?.cancel();
221
+ if (redirects >= 20) throw new TypeError("Too many redirects");
222
+ const url = new URL(location, request.url);
223
+ await validateUrl(url.href);
224
+ const headers = new Headers(request.headers);
225
+ if (url.origin !== new URL(request.url).origin) {
226
+ headers.delete("Authorization");
227
+ headers.delete("Proxy-Authorization");
228
+ headers.delete("Cookie");
229
+ headers.delete("Host");
230
+ }
231
+ let method = request.method;
232
+ if ((response.status === 301 || response.status === 302) && method === "POST" || response.status === 303 && method !== "GET" && method !== "HEAD") {
233
+ method = "GET";
234
+ body = void 0;
235
+ for (const name of [
236
+ "Content-Encoding",
237
+ "Content-Language",
238
+ "Content-Length",
239
+ "Content-Location",
240
+ "Content-Type"
241
+ ]) headers.delete(name);
242
+ }
243
+ request = new Request(url, {
244
+ method,
245
+ headers,
246
+ body,
247
+ redirect: "manual"
248
+ });
249
+ }
250
+ }
194
251
  /**
195
252
  * An error that is thrown when an activity fails to send to a remote inbox.
196
253
  * 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-vrlUxr60.mjs";
5
5
  import { t as assertEquals } from "../assert_equals-C-ZRDbaf.mjs";
6
6
  import { r as assertExists, t as assertStringIncludes } from "../std__assert-BBjXFNOb.mjs";
7
7
  import { n as assertGreaterOrEqual, r as assertFalse, t as assertRejects } from "../assert_rejects-DN60FHPX.mjs";
8
+ import { t as assert } from "../assert-jSdZMYam.mjs";
8
9
  import { t as assertThrows } from "../assert_throws-BOkhLGYc.mjs";
9
- import { t as assert } from "../assert-OguE97r2.mjs";
10
- import { t as exportJwk } from "../key-C_a6iE1-.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-B3-zan5-.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-C-7sqo8D.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-ClEDLGpr.mjs";
12
+ import { i as rsaPrivateKey2, l as rsaPublicKey5, o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-BAK-tUlf.mjs";
13
13
  import { createTestMeterProvider, 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-C-ZRDbaf.mjs";
5
5
  import "../std__assert-BBjXFNOb.mjs";
6
6
  import { t as assertRejects } from "../assert_rejects-DN60FHPX.mjs";
7
+ import { t as assert } from "../assert-jSdZMYam.mjs";
7
8
  import { t as assertThrows } from "../assert_throws-BOkhLGYc.mjs";
8
- import { a as importJwk, i as generateCryptoKeyPair, n as fetchKey, o as validateCryptoKey, r as fetchKeyDetailed, t as exportJwk } from "../key-C_a6iE1-.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-C-7sqo8D.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 { CryptographicKey, Multikey } from "@fedify/vocab";
11
12
  import { createTestMeterProvider, createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
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);
@@ -495,5 +496,171 @@ test("fetchKey() returns null for a malformed actor publicKey", async () => {
495
496
  cached: true
496
497
  });
497
498
  });
499
+ test("fetchKey() rejects a key whose owner does not link back", async () => {
500
+ const keyId = "https://attacker.example/key";
501
+ const keyDocument = await rsaPublicKey1.toJsonLd({ contextLoader: mockDocumentLoader });
502
+ const serveKeyOwnedBy = (owner) => ({
503
+ documentLoader(resource) {
504
+ if (resource === keyId) return Promise.resolve({
505
+ contextUrl: null,
506
+ documentUrl: resource,
507
+ document: {
508
+ ...keyDocument,
509
+ id: keyId,
510
+ owner
511
+ }
512
+ });
513
+ return mockDocumentLoader(resource);
514
+ },
515
+ contextLoader: mockDocumentLoader
516
+ });
517
+ assertEquals(await fetchKey(keyId, CryptographicKey, serveKeyOwnedBy("https://example.com/person")), {
518
+ key: null,
519
+ cached: false
520
+ });
521
+ assertEquals(await fetchKey(keyId, CryptographicKey, serveKeyOwnedBy("https://impersonated.invalid/users/victim")), {
522
+ key: null,
523
+ cached: false
524
+ });
525
+ });
526
+ test("fetchKey() rejects a Multikey whose controller does not link back", async () => {
527
+ const keyId = "https://attacker.example/multikey";
528
+ const keyDocument = await ed25519Multikey.toJsonLd({ contextLoader: mockDocumentLoader });
529
+ assertEquals(await fetchKey(keyId, Multikey, {
530
+ documentLoader(resource) {
531
+ if (resource === keyId) return Promise.resolve({
532
+ contextUrl: null,
533
+ documentUrl: resource,
534
+ document: {
535
+ ...keyDocument,
536
+ id: keyId,
537
+ controller: "https://example.com/person2"
538
+ }
539
+ });
540
+ return mockDocumentLoader(resource);
541
+ },
542
+ contextLoader: mockDocumentLoader
543
+ }), {
544
+ key: null,
545
+ cached: false
546
+ });
547
+ });
548
+ test("fetchKey() rejects an actor document from another origin", async () => {
549
+ const keyId = "https://attacker.example/key";
550
+ const impersonated = "https://example.com/person";
551
+ const { publicKeyPem } = await rsaPublicKey1.toJsonLd({ contextLoader: mockDocumentLoader });
552
+ assertEquals(await fetchKey(keyId, CryptographicKey, {
553
+ documentLoader(resource) {
554
+ if (resource === keyId) return Promise.resolve({
555
+ contextUrl: null,
556
+ documentUrl: resource,
557
+ document: {
558
+ "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"],
559
+ id: impersonated,
560
+ type: "Person",
561
+ publicKey: [{
562
+ id: `${impersonated}#main-key`,
563
+ type: "CryptographicKey",
564
+ owner: impersonated,
565
+ publicKeyPem
566
+ }]
567
+ }
568
+ });
569
+ return mockDocumentLoader(resource);
570
+ },
571
+ contextLoader: mockDocumentLoader
572
+ }), {
573
+ key: null,
574
+ cached: false
575
+ });
576
+ });
577
+ test("fetchKey() rejects a key that disowns the actor document holding it", async () => {
578
+ const actorId = "https://attacker.example/actor";
579
+ const keyId = `${actorId}#main-key`;
580
+ const { publicKeyPem } = await rsaPublicKey1.toJsonLd({ contextLoader: mockDocumentLoader });
581
+ assertEquals(await fetchKey(keyId, CryptographicKey, {
582
+ documentLoader(resource) {
583
+ if (resource === keyId || resource === actorId) return Promise.resolve({
584
+ contextUrl: null,
585
+ documentUrl: resource,
586
+ document: {
587
+ "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"],
588
+ id: actorId,
589
+ type: "Person",
590
+ publicKey: [{
591
+ id: keyId,
592
+ type: "CryptographicKey",
593
+ owner: "https://example.com/person",
594
+ publicKeyPem
595
+ }]
596
+ }
597
+ });
598
+ return mockDocumentLoader(resource);
599
+ },
600
+ contextLoader: mockDocumentLoader
601
+ }), {
602
+ key: null,
603
+ cached: false
604
+ });
605
+ });
606
+ test("fetchKey() records the owner its actor document establishes", async () => {
607
+ const { key } = await fetchKey("https://example.com/users/handle#main-key", CryptographicKey, {
608
+ documentLoader: mockDocumentLoader,
609
+ contextLoader: mockDocumentLoader
610
+ });
611
+ assertEquals(key?.ownerId, new URL("https://example.com/users/handle"));
612
+ });
613
+ test("fetchKey() accepts a key document that leaves its id implicit", async () => {
614
+ const keyId = "https://example.com/key";
615
+ const keyDocument = await rsaPublicKey1.toJsonLd({ contextLoader: mockDocumentLoader });
616
+ delete keyDocument.id;
617
+ const { key } = await fetchKey(keyId, CryptographicKey, {
618
+ documentLoader(resource) {
619
+ if (resource === keyId) return Promise.resolve({
620
+ contextUrl: null,
621
+ documentUrl: resource,
622
+ document: keyDocument
623
+ });
624
+ return mockDocumentLoader(resource);
625
+ },
626
+ contextLoader: mockDocumentLoader
627
+ });
628
+ assertEquals(key?.id, new URL(keyId));
629
+ assertEquals(key?.ownerId, new URL("https://example.com/person"));
630
+ assert(key?.publicKey != null);
631
+ });
632
+ test("fetchKey() records the controller an actor document establishes", async () => {
633
+ const actorId = "https://example.com/multikey-actor";
634
+ const keyId = `${actorId}#assertion`;
635
+ const { publicKeyMultibase } = await ed25519Multikey.toJsonLd({ contextLoader: mockDocumentLoader });
636
+ const { key } = await fetchKey(keyId, Multikey, {
637
+ documentLoader(resource) {
638
+ if (resource === actorId || resource === keyId) return Promise.resolve({
639
+ contextUrl: null,
640
+ documentUrl: actorId,
641
+ document: {
642
+ "@context": [
643
+ "https://www.w3.org/ns/activitystreams",
644
+ "https://w3id.org/security/v1",
645
+ "https://w3id.org/security/multikey/v1",
646
+ "https://w3id.org/security/data-integrity/v1",
647
+ "https://www.w3.org/ns/did/v1"
648
+ ],
649
+ id: actorId,
650
+ type: "Person",
651
+ assertionMethod: [{
652
+ id: keyId,
653
+ type: "Multikey",
654
+ publicKeyMultibase
655
+ }]
656
+ }
657
+ });
658
+ return mockDocumentLoader(resource);
659
+ },
660
+ contextLoader: mockDocumentLoader
661
+ });
662
+ assertEquals(key?.controllerId, new URL(actorId));
663
+ assert(key?.publicKey != null);
664
+ });
498
665
  //#endregion
499
666
  export {};