@fedify/fedify 2.2.11 → 2.2.13

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-8d-PNxcc.mjs → builder-uTlVksLw.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-BdneH5EA.mjs → deno-Cg_cZHcI.mjs} +1 -1
  12. package/dist/{docloader-dW-3XcQa.mjs → docloader-BwXP5fDH.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-DcjN1Tul.mjs → http-B3V9unT4.mjs} +3 -3
  33. package/dist/{http-CVNTMjI8.cjs → http-BdbKIiay.cjs} +166 -6
  34. package/dist/{http-dst14yhu.js → http-DaLdtguq.js} +155 -7
  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-C6EM8eSE.mjs → key-CLRfRmA_.mjs} +154 -6
  38. package/dist/{keycache-EGATflN-.mjs → keycache-C1aVprwy.mjs} +12 -4
  39. package/dist/{kv-cache-CSs1SO_n.cjs → kv-cache-K6eHO_YH.cjs} +1 -1
  40. package/dist/{kv-cache-Dg1p1urK.js → kv-cache-TPuR5wYg.js} +1 -1
  41. package/dist/{ld-Ci6Z4_tn.mjs → ld-C0s4f-GU.mjs} +2 -2
  42. package/dist/{middleware-DdSIe9K3.js → middleware-BDRZkGPG.js} +90 -14
  43. package/dist/{middleware-BVBL4Ug9.cjs → middleware-BDc7xyOx.cjs} +90 -14
  44. package/dist/{middleware-D7VPt6Mr.mjs → middleware-BsDiZP9H.mjs} +31 -20
  45. package/dist/{middleware-iVyNebWP.cjs → middleware-D6bGiZn6.cjs} +1 -1
  46. package/dist/{middleware-cU-cDO0w.mjs → middleware-uaOjlLEG.mjs} +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-DLbN_4jZ.mjs +175 -0
  67. package/dist/{proof-DMMFfNsL.cjs → proof-CTIG9UEI.cjs} +112 -58
  68. package/dist/{proof-BEwrQa7q.mjs → proof-CW3Zrxmd.mjs} +4 -4
  69. package/dist/{proof-nHHslj31.js → proof-CqyprEYB.js} +112 -58
  70. package/dist/{send-B1XNYk6n.mjs → send-B5QvdrZ1.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-DaRJ05za.mjs → temporal-CFLRXAcm.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-ByUYl7Xn.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,7 +1,7 @@
1
1
  const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  const require_chunk = require("./chunk-DDcVe30Y.cjs");
4
- const require_http = require("./http-CVNTMjI8.cjs");
4
+ const require_http = require("./http-BdbKIiay.cjs");
5
5
  let _logtape_logtape = require("@logtape/logtape");
6
6
  let _fedify_vocab = require("@fedify/vocab");
7
7
  let _opentelemetry_api = require("@opentelemetry/api");
@@ -13,7 +13,7 @@ _fedify_vocab_runtime_jsonld = require_chunk.__toESM(_fedify_vocab_runtime_jsonl
13
13
  let json_canon = require("json-canon");
14
14
  json_canon = require_chunk.__toESM(json_canon);
15
15
  //#region src/sig/ld.ts
16
- const logger$3 = (0, _logtape_logtape.getLogger)([
16
+ const logger$4 = (0, _logtape_logtape.getLogger)([
17
17
  "fedify",
18
18
  "sig",
19
19
  "ld"
@@ -443,7 +443,7 @@ async function verifySignature(jsonLd, options = {}) {
443
443
  try {
444
444
  signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
445
445
  } catch (error) {
446
- logger$3.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
446
+ logger$4.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
447
447
  ...sig,
448
448
  error
449
449
  });
@@ -462,7 +462,7 @@ async function verifySignature(jsonLd, options = {}) {
462
462
  try {
463
463
  sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
464
464
  } catch (error) {
465
- logger$3.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
465
+ logger$4.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
466
466
  signatureOptions: sigOpts,
467
467
  error
468
468
  });
@@ -474,7 +474,7 @@ async function verifySignature(jsonLd, options = {}) {
474
474
  try {
475
475
  docHash = await hashJsonLd(document, options.contextLoader);
476
476
  } catch (error) {
477
- logger$3.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
477
+ logger$4.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
478
478
  document,
479
479
  error
480
480
  });
@@ -485,7 +485,7 @@ async function verifySignature(jsonLd, options = {}) {
485
485
  const messageBytes = encoder.encode(message);
486
486
  if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
487
487
  if (cached) {
488
- logger$3.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
488
+ logger$4.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
489
489
  keyId: sig.creator,
490
490
  ...sig
491
491
  });
@@ -499,7 +499,7 @@ async function verifySignature(jsonLd, options = {}) {
499
499
  if (key == null) return null;
500
500
  return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
501
501
  }
502
- 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}", {
502
+ 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}", {
503
503
  keyId: sig.creator,
504
504
  ...sig,
505
505
  message
@@ -543,12 +543,12 @@ async function verifyJsonLdInternal(jsonLd, options, compact) {
543
543
  const key = await verifySignature(compacted, verificationOptions);
544
544
  if (key == null) return false;
545
545
  if (key.ownerId == null) {
546
- logger$3.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
546
+ logger$4.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
547
547
  return false;
548
548
  }
549
549
  attributions.delete(key.ownerId.href);
550
550
  if (attributions.size > 0) {
551
- logger$3.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
551
+ logger$4.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
552
552
  return false;
553
553
  }
554
554
  return true;
@@ -573,8 +573,20 @@ async function hashJsonLd(jsonLd, contextLoader) {
573
573
  }
574
574
  //#endregion
575
575
  //#region src/sig/owner.ts
576
+ const logger$3 = (0, _logtape_logtape.getLogger)([
577
+ "fedify",
578
+ "sig",
579
+ "owner"
580
+ ]);
576
581
  /**
577
582
  * Checks if the actor of the given activity owns the specified key.
583
+ *
584
+ * Ownership is never taken from what the activity or the key say about
585
+ * themselves, as both are written by whoever sent the activity. It is
586
+ * established from a document that the owner itself serves: either the key's
587
+ * claimed owner links back to the key, or the actor the activity claims lists
588
+ * the key as its own.
589
+ *
578
590
  * @param activity The activity to check.
579
591
  * @param key The public key to check.
580
592
  * @param options Options for checking the key ownership.
@@ -589,23 +601,30 @@ async function doesActorOwnKey(activity, key, options) {
589
601
  }
590
602
  }, async (span) => {
591
603
  try {
592
- if (key.ownerId != null) {
593
- const owns = key.ownerId.href === activity.actorId?.href;
594
- span.setAttribute("activitypub.key_ownership.verified", owns);
595
- span.setAttribute("activitypub.key_ownership.method", "owner_id");
596
- return owns;
597
- }
598
- const actor = await activity.getActor(options);
599
- if (actor == null || !(0, _fedify_vocab.isActor)(actor)) {
604
+ const actorId = activity.actorId;
605
+ if (actorId == null) {
600
606
  span.setAttribute("activitypub.key_ownership.verified", false);
601
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
607
+ span.setAttribute("activitypub.key_ownership.method", "none");
602
608
  return false;
603
609
  }
604
- for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
610
+ if (key.ownerId != null) {
611
+ const owner = await require_http.verifyKeyOwnership(key, options);
612
+ if (owner?.id != null && owner.id.href === actorId.href) {
613
+ span.setAttribute("activitypub.key_ownership.verified", true);
614
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
615
+ return true;
616
+ }
617
+ }
618
+ const actor = await require_http.fetchActorDocument(actorId, options);
619
+ if (actor != null && await doesActorListKey(actor, key, options)) {
605
620
  span.setAttribute("activitypub.key_ownership.verified", true);
606
621
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
607
622
  return true;
608
623
  }
624
+ 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.", {
625
+ actorId: actorId.href,
626
+ keyId: key.id?.href
627
+ });
609
628
  span.setAttribute("activitypub.key_ownership.verified", false);
610
629
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
611
630
  return false;
@@ -622,9 +641,46 @@ async function doesActorOwnKey(activity, key, options) {
622
641
  });
623
642
  }
624
643
  /**
644
+ * Determines whether the given actor's own document lists the given key among
645
+ * its public keys.
646
+ *
647
+ * Keys are matched by id, which is what an actor document links to. A key
648
+ * document may leave its id implicit, though, and then there is no id for the
649
+ * actor to link to; the key material itself is the only thing the two can
650
+ * have in common, so that is what gets compared.
651
+ */
652
+ async function doesActorListKey(actor, key, options) {
653
+ if (key.id != null) {
654
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
655
+ return false;
656
+ }
657
+ if (key.publicKey == null) return false;
658
+ const publicKeys = actor.getPublicKeys({
659
+ ...options,
660
+ suppressError: true
661
+ });
662
+ for await (const publicKey of publicKeys) {
663
+ if (publicKey.publicKey == null) continue;
664
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
665
+ }
666
+ return false;
667
+ }
668
+ /**
669
+ * Compares two public keys by their key material, ignoring the metadata that
670
+ * surrounds it.
671
+ */
672
+ async function isSamePublicKey(a, b) {
673
+ const [x, y] = await Promise.all([require_http.exportJwk(a), require_http.exportJwk(b)]);
674
+ 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;
675
+ }
676
+ /**
625
677
  * Gets the actor that owns the specified key. Returns `null` if the key has no
626
678
  * known owner.
627
679
  *
680
+ * The owner is only returned when the key and the owner link to each other:
681
+ * a document that merely claims to own a key is not enough, as the claim and
682
+ * the key can come from the same host.
683
+ *
628
684
  * @param keyId The ID of the key to check, or the key itself.
629
685
  * @param options Options for getting the key owner.
630
686
  * @returns The actor that owns the key, or `null` if the key has no known
@@ -634,52 +690,50 @@ async function doesActorOwnKey(activity, key, options) {
634
690
  async function getKeyOwner(keyId, options) {
635
691
  const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
636
692
  const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
637
- const contextLoader = options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
693
+ const fetchOptions = {
694
+ documentLoader,
695
+ contextLoader: options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)(),
696
+ tracerProvider
697
+ };
698
+ if (keyId instanceof _fedify_vocab.CryptographicKey) return await require_http.verifyKeyOwnership(keyId, fetchOptions);
699
+ let keyDoc;
700
+ let documentUrl = keyId;
701
+ try {
702
+ const remoteDocument = await documentLoader(keyId.href);
703
+ keyDoc = remoteDocument.document;
704
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
705
+ } catch (_) {
706
+ return null;
707
+ }
638
708
  let object;
639
- if (keyId instanceof _fedify_vocab.CryptographicKey) {
640
- object = keyId;
641
- if (object.id == null) return null;
642
- keyId = object.id;
643
- } else {
644
- let keyDoc;
645
- try {
646
- const { document } = await documentLoader(keyId.href);
647
- keyDoc = document;
648
- } catch (_) {
649
- return null;
650
- }
709
+ try {
710
+ object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
711
+ ...fetchOptions,
712
+ baseUrl: documentUrl
713
+ });
714
+ } catch (e) {
715
+ if (!(e instanceof TypeError)) throw e;
651
716
  try {
652
- object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
653
- documentLoader,
654
- contextLoader,
655
- tracerProvider
656
- });
717
+ object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
657
718
  } catch (e) {
658
- if (!(e instanceof TypeError)) throw e;
659
- try {
660
- object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, {
661
- documentLoader,
662
- contextLoader,
663
- tracerProvider
664
- });
665
- } catch (e) {
666
- if (e instanceof TypeError) return null;
667
- throw e;
668
- }
719
+ if (e instanceof TypeError) return null;
720
+ throw e;
669
721
  }
670
722
  }
671
- let owner = null;
672
723
  if (object instanceof _fedify_vocab.CryptographicKey) {
673
- if (object.ownerId == null) return null;
674
- owner = await object.getOwner({
675
- documentLoader,
676
- contextLoader,
677
- tracerProvider
724
+ if (object.id != null && object.id.href !== keyId.href) return null;
725
+ return await require_http.verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
726
+ }
727
+ if (!(0, _fedify_vocab.isActor)(object)) return null;
728
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
729
+ 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}.", {
730
+ documentUrl: documentUrl.href,
731
+ actorId: object.id?.href,
732
+ keyId: keyId.href
678
733
  });
679
- } else if ((0, _fedify_vocab.isActor)(object)) owner = object;
680
- else return null;
681
- if (owner == null) return null;
682
- for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
734
+ return null;
735
+ }
736
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
683
737
  return null;
684
738
  }
685
739
  //#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-BdneH5EA.mjs";
5
- import { n as fetchKey, o as validateCryptoKey } from "./key-C6EM8eSE.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-Cg_cZHcI.mjs";
5
+ import { r as fetchKey, s as validateCryptoKey } from "./key-CLRfRmA_.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,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-dst14yhu.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-DaLdtguq.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,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-BdneH5EA.mjs";
5
- import { n as doubleKnock } from "./http-DcjN1Tul.mjs";
4
+ import { n as version, t as name } from "./deno-Cg_cZHcI.mjs";
5
+ import { n as doubleKnock } from "./http-B3V9unT4.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