@fedify/fedify 2.1.22 → 2.1.24

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 (98) hide show
  1. package/dist/{assert_instance_of-C4Ri6VuN.mjs → assert-BhQd8QHP.mjs} +19 -1
  2. package/dist/{builder-uOFBJkK3.mjs → builder-BatYe9a2.mjs} +3 -3
  3. package/dist/{client-CZWLyLmp.mjs → client-DNiBssfx.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/transformers.test.mjs +3 -4
  7. package/dist/{context-_l9t359k.d.ts → context-BgU5UWTx.d.ts} +4 -3
  8. package/dist/{context-o22vjzS2.d.cts → context-D4s0Wk3N.d.cts} +4 -3
  9. package/dist/{deno-Dq7ws4iI.mjs → deno-BXkm_rws.mjs} +1 -1
  10. package/dist/{docloader-BC4p0nXc.mjs → docloader-DdEK2tXP.mjs} +2 -2
  11. package/dist/federation/builder.test.mjs +2 -2
  12. package/dist/federation/collection.test.mjs +1 -1
  13. package/dist/federation/handler.test.mjs +127 -9
  14. package/dist/federation/idempotency.test.mjs +4 -4
  15. package/dist/federation/inbox.test.mjs +1 -1
  16. package/dist/federation/keycache.test.mjs +44 -10
  17. package/dist/federation/kv.test.mjs +1 -1
  18. package/dist/federation/middleware.test.mjs +99 -11
  19. package/dist/federation/mod.cjs +1 -1
  20. package/dist/federation/mod.d.cts +2 -2
  21. package/dist/federation/mod.d.ts +2 -2
  22. package/dist/federation/mod.js +1 -1
  23. package/dist/federation/mq.test.mjs +1 -1
  24. package/dist/federation/negotiation.test.mjs +2 -2
  25. package/dist/federation/retry.test.mjs +1 -1
  26. package/dist/federation/router.test.mjs +1 -1
  27. package/dist/federation/send.test.mjs +138 -6
  28. package/dist/federation/temporal.test.mjs +2 -2
  29. package/dist/federation/webfinger.test.mjs +2 -2
  30. package/dist/{http-CWMbnDWz.cjs → http-7FmLhLDv.cjs} +166 -6
  31. package/dist/{http-C5HQIcH6.js → http-Chr54tTL.js} +155 -7
  32. package/dist/{http-BDZeS5om.d.ts → http-Dl00HXr4.d.ts} +1 -1
  33. package/dist/{http-C87EWkO0.d.cts → http-DqZhyEso.d.cts} +1 -1
  34. package/dist/{http-DFOoxt_R.mjs → http-UyebnM2c.mjs} +3 -3
  35. package/dist/{inbox-B07FmpqX.mjs → inbox-ByQ2iD14.mjs} +1 -1
  36. package/dist/{key-BhxG-x5D.mjs → key-A8SuFznD.mjs} +154 -6
  37. package/dist/{keycache-CCSwkQcY.mjs → keycache-CaO7wyQA.mjs} +12 -4
  38. package/dist/{kv-cache-ByRYF-t6.cjs → kv-cache-DJhBDA9T.cjs} +1 -1
  39. package/dist/{kv-cache-C4CXZOaq.js → kv-cache-J6hmiAEd.js} +1 -1
  40. package/dist/{ld-CHqytT_K.mjs → ld-BSvHU-S0.mjs} +2 -2
  41. package/dist/{middleware-B1736exe.cjs → middleware-Bddj287b.cjs} +1 -1
  42. package/dist/{middleware-_PzelxB9.cjs → middleware-CCYqHlzn.cjs} +90 -14
  43. package/dist/{middleware-Dyz-bNVJ.js → middleware-Do50b12a.js} +90 -14
  44. package/dist/{middleware-DRMVB2Bf.mjs → middleware-DvxNTKpl.mjs} +1 -1
  45. package/dist/{middleware-CFbSzb-d.mjs → middleware-Dy18K1xP.mjs} +31 -20
  46. package/dist/{mod-CjiK2zrW.d.ts → mod-BLDHhuW0.d.ts} +1 -1
  47. package/dist/{mod-0dF0OeGw.d.cts → mod-Bx80LUTA.d.cts} +1 -1
  48. package/dist/{mod-BTWFtZwa.d.ts → mod-CMK_S-eX.d.ts} +1 -1
  49. package/dist/{mod-Bv1elC-b.d.ts → mod-DcAiY74j.d.ts} +1 -1
  50. package/dist/{mod-D5YlzzP3.d.cts → mod-DiuFTYUt.d.cts} +1 -1
  51. package/dist/{mod-dxOnKp2Y.d.cts → mod-DniKVJ_C.d.cts} +1 -1
  52. package/dist/mod.cjs +5 -5
  53. package/dist/mod.d.cts +6 -6
  54. package/dist/mod.d.ts +6 -6
  55. package/dist/mod.js +5 -5
  56. package/dist/nodeinfo/client.test.mjs +28 -1
  57. package/dist/nodeinfo/handler.test.mjs +2 -2
  58. package/dist/nodeinfo/mod.cjs +1 -1
  59. package/dist/nodeinfo/mod.js +1 -1
  60. package/dist/nodeinfo/types.test.mjs +1 -1
  61. package/dist/otel/exporter.test.mjs +1 -1
  62. package/dist/{owner-DEvZuyOE.d.cts → owner-B3hNQCG8.d.cts} +11 -0
  63. package/dist/owner-CaaCVHsG.mjs +175 -0
  64. package/dist/{owner-CnngXDNJ.d.ts → owner-CiBPcC6F.d.ts} +11 -0
  65. package/dist/{proof-DtJrGFAd.js → proof-BrOQrPQf.js} +112 -58
  66. package/dist/{proof-BLCy90_K.cjs → proof-CaCUMcvk.cjs} +112 -58
  67. package/dist/{proof-B9xBlvFD.mjs → proof-_AyA4r7z.mjs} +2 -2
  68. package/dist/{send-TxZWfiOg.mjs → send-B1CRgb14.mjs} +64 -6
  69. package/dist/sig/accept.test.mjs +1 -1
  70. package/dist/sig/http.test.mjs +4 -4
  71. package/dist/sig/key.test.mjs +170 -3
  72. package/dist/sig/ld.test.mjs +56 -4
  73. package/dist/sig/mod.cjs +2 -2
  74. package/dist/sig/mod.d.cts +3 -3
  75. package/dist/sig/mod.d.ts +3 -3
  76. package/dist/sig/mod.js +2 -2
  77. package/dist/sig/owner.test.mjs +105 -6
  78. package/dist/sig/proof.test.mjs +72 -3
  79. package/dist/{temporal-Q6m8vHyx.mjs → temporal-Pmk5ouB1.mjs} +1 -1
  80. package/dist/{types-m8u9L86X.cjs → types-DWs-qZaY.cjs} +94 -2
  81. package/dist/{types-DTONwNqL.js → types-sXITXcWa.js} +78 -4
  82. package/dist/utils/docloader.test.mjs +28 -4
  83. package/dist/utils/kv-cache.test.mjs +1 -1
  84. package/dist/utils/mod.cjs +1 -1
  85. package/dist/utils/mod.d.cts +1 -1
  86. package/dist/utils/mod.d.ts +1 -1
  87. package/dist/utils/mod.js +1 -1
  88. package/package.json +5 -5
  89. package/dist/assert-ddO5KLpe.mjs +0 -23
  90. package/dist/owner-D79Nd_56.mjs +0 -120
  91. /package/dist/{accept-Dd__NiUL.mjs → accept-BavzedPB.mjs} +0 -0
  92. /package/dist/{collection-BD6-SZ6O.mjs → collection-ChgDTHLz.mjs} +0 -0
  93. /package/dist/{keys-BAK-tUlf.mjs → keys-CtZLJq76.mjs} +0 -0
  94. /package/dist/{kv-tL2TOE9X.mjs → kv-BrZHNugx.mjs} +0 -0
  95. /package/dist/{kv-cache-FsT1ljhs.mjs → kv-cache-DqEKe5E0.mjs} +0 -0
  96. /package/dist/{negotiation-DnsfFF8I.mjs → negotiation-BehA2uul.mjs} +0 -0
  97. /package/dist/{retry-CJL0poaU.mjs → retry-B_E3V_Dx.mjs} +0 -0
  98. /package/dist/{types-DCP0WLdt.mjs → types-C37hquWI.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-CWMbnDWz.cjs");
4
+ const require_http = require("./http-7FmLhLDv.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$1 = (0, _logtape_logtape.getLogger)([
16
+ const logger$2 = (0, _logtape_logtape.getLogger)([
17
17
  "fedify",
18
18
  "sig",
19
19
  "ld"
@@ -420,7 +420,7 @@ async function verifySignature(jsonLd, options = {}) {
420
420
  try {
421
421
  signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
422
422
  } catch (error) {
423
- logger$1.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
423
+ logger$2.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
424
424
  ...sig,
425
425
  error
426
426
  });
@@ -439,7 +439,7 @@ async function verifySignature(jsonLd, options = {}) {
439
439
  try {
440
440
  sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
441
441
  } catch (error) {
442
- logger$1.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
442
+ logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
443
443
  signatureOptions: sigOpts,
444
444
  error
445
445
  });
@@ -451,7 +451,7 @@ async function verifySignature(jsonLd, options = {}) {
451
451
  try {
452
452
  docHash = await hashJsonLd(document, options.contextLoader);
453
453
  } catch (error) {
454
- logger$1.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
454
+ logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
455
455
  document,
456
456
  error
457
457
  });
@@ -462,7 +462,7 @@ async function verifySignature(jsonLd, options = {}) {
462
462
  const messageBytes = encoder.encode(message);
463
463
  if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
464
464
  if (cached) {
465
- logger$1.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
465
+ logger$2.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
466
466
  keyId: sig.creator,
467
467
  ...sig
468
468
  });
@@ -476,7 +476,7 @@ async function verifySignature(jsonLd, options = {}) {
476
476
  if (key == null) return null;
477
477
  return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
478
478
  }
479
- logger$1.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}", {
479
+ logger$2.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}", {
480
480
  keyId: sig.creator,
481
481
  ...sig,
482
482
  message
@@ -520,12 +520,12 @@ async function verifyJsonLdInternal(jsonLd, options, compact) {
520
520
  const key = await verifySignature(compacted, verificationOptions);
521
521
  if (key == null) return false;
522
522
  if (key.ownerId == null) {
523
- logger$1.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
523
+ logger$2.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
524
524
  return false;
525
525
  }
526
526
  attributions.delete(key.ownerId.href);
527
527
  if (attributions.size > 0) {
528
- logger$1.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
528
+ logger$2.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
529
529
  return false;
530
530
  }
531
531
  return true;
@@ -550,8 +550,20 @@ async function hashJsonLd(jsonLd, contextLoader) {
550
550
  }
551
551
  //#endregion
552
552
  //#region src/sig/owner.ts
553
+ const logger$1 = (0, _logtape_logtape.getLogger)([
554
+ "fedify",
555
+ "sig",
556
+ "owner"
557
+ ]);
553
558
  /**
554
559
  * Checks if the actor of the given activity owns the specified key.
560
+ *
561
+ * Ownership is never taken from what the activity or the key say about
562
+ * themselves, as both are written by whoever sent the activity. It is
563
+ * established from a document that the owner itself serves: either the key's
564
+ * claimed owner links back to the key, or the actor the activity claims lists
565
+ * the key as its own.
566
+ *
555
567
  * @param activity The activity to check.
556
568
  * @param key The public key to check.
557
569
  * @param options Options for checking the key ownership.
@@ -566,23 +578,30 @@ async function doesActorOwnKey(activity, key, options) {
566
578
  }
567
579
  }, async (span) => {
568
580
  try {
569
- if (key.ownerId != null) {
570
- const owns = key.ownerId.href === activity.actorId?.href;
571
- span.setAttribute("activitypub.key_ownership.verified", owns);
572
- span.setAttribute("activitypub.key_ownership.method", "owner_id");
573
- return owns;
574
- }
575
- const actor = await activity.getActor(options);
576
- if (actor == null || !(0, _fedify_vocab.isActor)(actor)) {
581
+ const actorId = activity.actorId;
582
+ if (actorId == null) {
577
583
  span.setAttribute("activitypub.key_ownership.verified", false);
578
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
584
+ span.setAttribute("activitypub.key_ownership.method", "none");
579
585
  return false;
580
586
  }
581
- for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
587
+ if (key.ownerId != null) {
588
+ const owner = await require_http.verifyKeyOwnership(key, options);
589
+ if (owner?.id != null && owner.id.href === actorId.href) {
590
+ span.setAttribute("activitypub.key_ownership.verified", true);
591
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
592
+ return true;
593
+ }
594
+ }
595
+ const actor = await require_http.fetchActorDocument(actorId, options);
596
+ if (actor != null && await doesActorListKey(actor, key, options)) {
582
597
  span.setAttribute("activitypub.key_ownership.verified", true);
583
598
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
584
599
  return true;
585
600
  }
601
+ logger$1.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.", {
602
+ actorId: actorId.href,
603
+ keyId: key.id?.href
604
+ });
586
605
  span.setAttribute("activitypub.key_ownership.verified", false);
587
606
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
588
607
  return false;
@@ -599,9 +618,46 @@ async function doesActorOwnKey(activity, key, options) {
599
618
  });
600
619
  }
601
620
  /**
621
+ * Determines whether the given actor's own document lists the given key among
622
+ * its public keys.
623
+ *
624
+ * Keys are matched by id, which is what an actor document links to. A key
625
+ * document may leave its id implicit, though, and then there is no id for the
626
+ * actor to link to; the key material itself is the only thing the two can
627
+ * have in common, so that is what gets compared.
628
+ */
629
+ async function doesActorListKey(actor, key, options) {
630
+ if (key.id != null) {
631
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
632
+ return false;
633
+ }
634
+ if (key.publicKey == null) return false;
635
+ const publicKeys = actor.getPublicKeys({
636
+ ...options,
637
+ suppressError: true
638
+ });
639
+ for await (const publicKey of publicKeys) {
640
+ if (publicKey.publicKey == null) continue;
641
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
642
+ }
643
+ return false;
644
+ }
645
+ /**
646
+ * Compares two public keys by their key material, ignoring the metadata that
647
+ * surrounds it.
648
+ */
649
+ async function isSamePublicKey(a, b) {
650
+ const [x, y] = await Promise.all([require_http.exportJwk(a), require_http.exportJwk(b)]);
651
+ 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;
652
+ }
653
+ /**
602
654
  * Gets the actor that owns the specified key. Returns `null` if the key has no
603
655
  * known owner.
604
656
  *
657
+ * The owner is only returned when the key and the owner link to each other:
658
+ * a document that merely claims to own a key is not enough, as the claim and
659
+ * the key can come from the same host.
660
+ *
605
661
  * @param keyId The ID of the key to check, or the key itself.
606
662
  * @param options Options for getting the key owner.
607
663
  * @returns The actor that owns the key, or `null` if the key has no known
@@ -611,52 +667,50 @@ async function doesActorOwnKey(activity, key, options) {
611
667
  async function getKeyOwner(keyId, options) {
612
668
  const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
613
669
  const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
614
- const contextLoader = options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
670
+ const fetchOptions = {
671
+ documentLoader,
672
+ contextLoader: options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)(),
673
+ tracerProvider
674
+ };
675
+ if (keyId instanceof _fedify_vocab.CryptographicKey) return await require_http.verifyKeyOwnership(keyId, fetchOptions);
676
+ let keyDoc;
677
+ let documentUrl = keyId;
678
+ try {
679
+ const remoteDocument = await documentLoader(keyId.href);
680
+ keyDoc = remoteDocument.document;
681
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
682
+ } catch (_) {
683
+ return null;
684
+ }
615
685
  let object;
616
- if (keyId instanceof _fedify_vocab.CryptographicKey) {
617
- object = keyId;
618
- if (object.id == null) return null;
619
- keyId = object.id;
620
- } else {
621
- let keyDoc;
622
- try {
623
- const { document } = await documentLoader(keyId.href);
624
- keyDoc = document;
625
- } catch (_) {
626
- return null;
627
- }
686
+ try {
687
+ object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
688
+ ...fetchOptions,
689
+ baseUrl: documentUrl
690
+ });
691
+ } catch (e) {
692
+ if (!(e instanceof TypeError)) throw e;
628
693
  try {
629
- object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
630
- documentLoader,
631
- contextLoader,
632
- tracerProvider
633
- });
694
+ object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
634
695
  } catch (e) {
635
- if (!(e instanceof TypeError)) throw e;
636
- try {
637
- object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, {
638
- documentLoader,
639
- contextLoader,
640
- tracerProvider
641
- });
642
- } catch (e) {
643
- if (e instanceof TypeError) return null;
644
- throw e;
645
- }
696
+ if (e instanceof TypeError) return null;
697
+ throw e;
646
698
  }
647
699
  }
648
- let owner = null;
649
700
  if (object instanceof _fedify_vocab.CryptographicKey) {
650
- if (object.ownerId == null) return null;
651
- owner = await object.getOwner({
652
- documentLoader,
653
- contextLoader,
654
- tracerProvider
701
+ if (object.id != null && object.id.href !== keyId.href) return null;
702
+ return await require_http.verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
703
+ }
704
+ if (!(0, _fedify_vocab.isActor)(object)) return null;
705
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
706
+ logger$1.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}.", {
707
+ documentUrl: documentUrl.href,
708
+ actorId: object.id?.href,
709
+ keyId: keyId.href
655
710
  });
656
- } else if ((0, _fedify_vocab.isActor)(object)) owner = object;
657
- else return null;
658
- if (owner == null) return null;
659
- for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
711
+ return null;
712
+ }
713
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
660
714
  return null;
661
715
  }
662
716
  //#endregion
@@ -1,8 +1,8 @@
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-Dq7ws4iI.mjs";
5
- import { n as fetchKey, o as validateCryptoKey } from "./key-BhxG-x5D.mjs";
4
+ import { n as version, t as name } from "./deno-BXkm_rws.mjs";
5
+ import { r as fetchKey, s as validateCryptoKey } from "./key-A8SuFznD.mjs";
6
6
  import { Activity, DataIntegrityProof, Multikey, getTypeId } from "@fedify/vocab";
7
7
  import { SpanStatusCode, trace } from "@opentelemetry/api";
8
8
  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-Dq7ws4iI.mjs";
5
- import { n as doubleKnock } from "./http-DFOoxt_R.mjs";
4
+ import { n as version, t as name } from "./deno-BXkm_rws.mjs";
5
+ import { n as doubleKnock } from "./http-UyebnM2c.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-Dd__NiUL.mjs";
4
+ import { i as validateAcceptSignature, n as fulfillAcceptSignature, r as parseAcceptSignature, t as formatAcceptSignature } from "../accept-BavzedPB.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 { a as assertExists, t as assertStringIncludes } from "../std__assert-Duiq_YC9.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-ddO5KLpe.mjs";
10
- import { t as exportJwk } from "../key-BhxG-x5D.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-DFOoxt_R.mjs";
12
- import { i as rsaPrivateKey2, l as rsaPublicKey5, o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-BAK-tUlf.mjs";
10
+ import { t as exportJwk } from "../key-A8SuFznD.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-UyebnM2c.mjs";
12
+ import { i as rsaPrivateKey2, l as rsaPublicKey5, o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-CtZLJq76.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-Duiq_YC9.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-BhxG-x5D.mjs";
9
- import { c as rsaPublicKey3, i as rsaPrivateKey2, o as rsaPublicKey1, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-BAK-tUlf.mjs";
9
+ import { a as generateCryptoKeyPair, i as fetchKeyDetailed, o as importJwk, r as fetchKey, s as validateCryptoKey, t as exportJwk } from "../key-A8SuFznD.mjs";
10
+ import { c as rsaPublicKey3, i as rsaPrivateKey2, o as rsaPublicKey1, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-CtZLJq76.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 {};