@fedify/fedify 2.1.23 → 2.1.25

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 (101) hide show
  1. package/dist/{assert_instance_of-C4Ri6VuN.mjs → assert-BhQd8QHP.mjs} +19 -1
  2. package/dist/{builder-BlCsjkrX.mjs → builder-DsBAef6b.mjs} +3 -3
  3. package/dist/{client-CZWLyLmp.mjs → client-DM72NZuk.mjs} +85 -7
  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-B_Gwkjh7.mjs → deno-9AaebKOA.mjs} +1 -1
  10. package/dist/docloader-DX96uPUj.mjs +78 -0
  11. package/dist/federation/builder.test.mjs +3 -3
  12. package/dist/federation/collection.test.mjs +2 -2
  13. package/dist/federation/handler.test.mjs +128 -10
  14. package/dist/federation/idempotency.test.mjs +5 -5
  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 +2 -2
  18. package/dist/federation/middleware.test.mjs +227 -12
  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 +99 -44
  24. package/dist/federation/negotiation.test.mjs +3 -3
  25. package/dist/federation/retry.test.mjs +1 -1
  26. package/dist/federation/router.test.mjs +2 -2
  27. package/dist/federation/send.test.mjs +202 -7
  28. package/dist/federation/temporal.test.mjs +3 -3
  29. package/dist/federation/webfinger.test.mjs +3 -3
  30. package/dist/{http-DIh9_s_-.mjs → http-B5qAeoJd.mjs} +8 -4
  31. package/dist/{http-Yoq0YGz7.cjs → http-BJEMpnnY.cjs} +171 -7
  32. package/dist/{http-88deUx3Y.js → http-CdJ6n4rA.js} +160 -8
  33. package/dist/{http-BDZeS5om.d.ts → http-Dl00HXr4.d.ts} +1 -1
  34. package/dist/{http-C87EWkO0.d.cts → http-DqZhyEso.d.cts} +1 -1
  35. package/dist/{inbox-BxCHIWPD.mjs → inbox-BSyjaFbo.mjs} +1 -1
  36. package/dist/{key-DywPPmb0.mjs → key-x9f-H7eO.mjs} +154 -6
  37. package/dist/{keycache-CCSwkQcY.mjs → keycache-CaO7wyQA.mjs} +12 -4
  38. package/dist/{kv-cache-HA011rBG.cjs → kv-cache-BDp2c_QE.cjs} +34 -8
  39. package/dist/{kv-cache-rHQOc5rE.js → kv-cache-Dx3QwNBI.js} +35 -9
  40. package/dist/{ld-Ch6FVq7X.mjs → ld-cfUwoi0C.mjs} +3 -3
  41. package/dist/{middleware-itcr4fAv.cjs → middleware-BXJpAXhO.cjs} +1 -1
  42. package/dist/{middleware-CYsQG25-.js → middleware-CP35ElZv.js} +99 -14
  43. package/dist/{middleware-DABFg_Xy.mjs → middleware-DDT9ljTQ.mjs} +1 -1
  44. package/dist/{middleware-D2O8b03q.mjs → middleware-DHHRwSZH.mjs} +31 -20
  45. package/dist/{middleware-CUNIlYzF.cjs → middleware-XXuSt_6b.cjs} +99 -14
  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-Bv1elC-b.d.ts → mod-DcAiY74j.d.ts} +1 -1
  49. package/dist/{mod-D5YlzzP3.d.cts → mod-DiuFTYUt.d.cts} +1 -1
  50. package/dist/{mod-dxOnKp2Y.d.cts → mod-DkE98l_7.d.cts} +3 -1
  51. package/dist/{mod-BTWFtZwa.d.ts → mod-DqkY4FDr.d.ts} +3 -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 +77 -2
  57. package/dist/nodeinfo/handler.test.mjs +3 -3
  58. package/dist/nodeinfo/mod.cjs +1 -1
  59. package/dist/nodeinfo/mod.js +1 -1
  60. package/dist/nodeinfo/types.test.mjs +2 -2
  61. package/dist/otel/exporter.test.mjs +2 -2
  62. package/dist/{owner-DEvZuyOE.d.cts → owner-B3hNQCG8.d.cts} +11 -0
  63. package/dist/{owner-CnngXDNJ.d.ts → owner-CiBPcC6F.d.ts} +11 -0
  64. package/dist/owner-DklgvZXn.mjs +175 -0
  65. package/dist/{proof-Dt5GV-xi.mjs → proof-CI4rsVLu.mjs} +2 -2
  66. package/dist/{proof-K3inAqnp.js → proof-Dsa_ZC-M.js} +113 -59
  67. package/dist/{proof-CEn2R6W9.cjs → proof-DzFzyfIc.cjs} +113 -59
  68. package/dist/{send-CqaJDT2z.mjs → send-DJmW6Z-I.mjs} +73 -6
  69. package/dist/sig/accept.test.mjs +1 -1
  70. package/dist/sig/http.test.mjs +45 -5
  71. package/dist/sig/key.test.mjs +171 -4
  72. package/dist/sig/ld.test.mjs +59 -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 +106 -7
  78. package/dist/sig/proof.test.mjs +73 -4
  79. package/dist/{std__assert-Duiq_YC9.mjs → std__assert-BUOJXi-Z.mjs} +1 -26
  80. package/dist/{temporal-G_GDghC-.mjs → temporal-BanFifxu.mjs} +1 -1
  81. package/dist/{types-m8u9L86X.cjs → types-DRPjmHVV.cjs} +101 -5
  82. package/dist/{types-DTONwNqL.js → types-miAYfiGO.js} +85 -7
  83. package/dist/utils/docloader.test.mjs +325 -5
  84. package/dist/utils/kv-cache.test.mjs +1 -1
  85. package/dist/utils/mod.cjs +1 -1
  86. package/dist/utils/mod.d.cts +1 -1
  87. package/dist/utils/mod.d.ts +1 -1
  88. package/dist/utils/mod.js +1 -1
  89. package/dist/vocab/cjs.test.mjs +1 -1
  90. package/package.json +7 -7
  91. package/dist/assert-ddO5KLpe.mjs +0 -23
  92. package/dist/docloader-B-IG1dVk.mjs +0 -52
  93. package/dist/owner-Cygg-fHW.mjs +0 -120
  94. /package/dist/{accept-Dd__NiUL.mjs → accept-BavzedPB.mjs} +0 -0
  95. /package/dist/{collection-BD6-SZ6O.mjs → collection-ChgDTHLz.mjs} +0 -0
  96. /package/dist/{keys-BAK-tUlf.mjs → keys-CtZLJq76.mjs} +0 -0
  97. /package/dist/{kv-tL2TOE9X.mjs → kv-BrZHNugx.mjs} +0 -0
  98. /package/dist/{kv-cache-FsT1ljhs.mjs → kv-cache-DqEKe5E0.mjs} +0 -0
  99. /package/dist/{negotiation-DnsfFF8I.mjs → negotiation-BehA2uul.mjs} +0 -0
  100. /package/dist/{retry-CJL0poaU.mjs → retry-B_E3V_Dx.mjs} +0 -0
  101. /package/dist/{types-DCP0WLdt.mjs → types-C37hquWI.mjs} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { _ as version, d as validateCryptoKey, g as name, s as fetchKey } from "./http-88deUx3Y.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-CdJ6n4rA.js";
4
4
  import { getLogger } from "@logtape/logtape";
5
5
  import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, 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$1 = getLogger([
13
+ const logger$2 = getLogger([
14
14
  "fedify",
15
15
  "sig",
16
16
  "ld"
@@ -202,7 +202,7 @@ function normalizeContextReference(reference, baseUrl) {
202
202
  /** @internal */
203
203
  function isInvalidUrlTypeError(error) {
204
204
  const code = error.code;
205
- return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
205
+ return error instanceof TypeError && (code === "ERR_INVALID_URL" || error.message === "Invalid URL string." || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
206
206
  }
207
207
  async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
208
208
  if (context === null) return createGraphAliasContextState();
@@ -417,7 +417,7 @@ async function verifySignature(jsonLd, options = {}) {
417
417
  try {
418
418
  signature = decodeBase64(sig.signatureValue);
419
419
  } catch (error) {
420
- logger$1.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
420
+ logger$2.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
421
421
  ...sig,
422
422
  error
423
423
  });
@@ -436,7 +436,7 @@ async function verifySignature(jsonLd, options = {}) {
436
436
  try {
437
437
  sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
438
438
  } catch (error) {
439
- logger$1.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
439
+ logger$2.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
440
440
  signatureOptions: sigOpts,
441
441
  error
442
442
  });
@@ -448,7 +448,7 @@ async function verifySignature(jsonLd, options = {}) {
448
448
  try {
449
449
  docHash = await hashJsonLd(document, options.contextLoader);
450
450
  } catch (error) {
451
- logger$1.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
451
+ logger$2.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
452
452
  document,
453
453
  error
454
454
  });
@@ -459,7 +459,7 @@ async function verifySignature(jsonLd, options = {}) {
459
459
  const messageBytes = encoder.encode(message);
460
460
  if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
461
461
  if (cached) {
462
- logger$1.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
462
+ logger$2.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
463
463
  keyId: sig.creator,
464
464
  ...sig
465
465
  });
@@ -473,7 +473,7 @@ async function verifySignature(jsonLd, options = {}) {
473
473
  if (key == null) return null;
474
474
  return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
475
475
  }
476
- 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}", {
476
+ 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}", {
477
477
  keyId: sig.creator,
478
478
  ...sig,
479
479
  message
@@ -517,12 +517,12 @@ async function verifyJsonLdInternal(jsonLd, options, compact) {
517
517
  const key = await verifySignature(compacted, verificationOptions);
518
518
  if (key == null) return false;
519
519
  if (key.ownerId == null) {
520
- logger$1.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
520
+ logger$2.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
521
521
  return false;
522
522
  }
523
523
  attributions.delete(key.ownerId.href);
524
524
  if (attributions.size > 0) {
525
- logger$1.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
525
+ logger$2.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
526
526
  return false;
527
527
  }
528
528
  return true;
@@ -547,8 +547,20 @@ async function hashJsonLd(jsonLd, contextLoader) {
547
547
  }
548
548
  //#endregion
549
549
  //#region src/sig/owner.ts
550
+ const logger$1 = getLogger([
551
+ "fedify",
552
+ "sig",
553
+ "owner"
554
+ ]);
550
555
  /**
551
556
  * Checks if the actor of the given activity owns the specified key.
557
+ *
558
+ * Ownership is never taken from what the activity or the key say about
559
+ * themselves, as both are written by whoever sent the activity. It is
560
+ * established from a document that the owner itself serves: either the key's
561
+ * claimed owner links back to the key, or the actor the activity claims lists
562
+ * the key as its own.
563
+ *
552
564
  * @param activity The activity to check.
553
565
  * @param key The public key to check.
554
566
  * @param options Options for checking the key ownership.
@@ -563,23 +575,30 @@ async function doesActorOwnKey(activity, key, options) {
563
575
  }
564
576
  }, async (span) => {
565
577
  try {
566
- if (key.ownerId != null) {
567
- const owns = key.ownerId.href === activity.actorId?.href;
568
- span.setAttribute("activitypub.key_ownership.verified", owns);
569
- span.setAttribute("activitypub.key_ownership.method", "owner_id");
570
- return owns;
571
- }
572
- const actor = await activity.getActor(options);
573
- if (actor == null || !isActor(actor)) {
578
+ const actorId = activity.actorId;
579
+ if (actorId == null) {
574
580
  span.setAttribute("activitypub.key_ownership.verified", false);
575
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
581
+ span.setAttribute("activitypub.key_ownership.method", "none");
576
582
  return false;
577
583
  }
578
- for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
584
+ if (key.ownerId != null) {
585
+ const owner = await verifyKeyOwnership(key, options);
586
+ if (owner?.id != null && owner.id.href === actorId.href) {
587
+ span.setAttribute("activitypub.key_ownership.verified", true);
588
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
589
+ return true;
590
+ }
591
+ }
592
+ const actor = await fetchActorDocument(actorId, options);
593
+ if (actor != null && await doesActorListKey(actor, key, options)) {
579
594
  span.setAttribute("activitypub.key_ownership.verified", true);
580
595
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
581
596
  return true;
582
597
  }
598
+ 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.", {
599
+ actorId: actorId.href,
600
+ keyId: key.id?.href
601
+ });
583
602
  span.setAttribute("activitypub.key_ownership.verified", false);
584
603
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
585
604
  return false;
@@ -596,9 +615,46 @@ async function doesActorOwnKey(activity, key, options) {
596
615
  });
597
616
  }
598
617
  /**
618
+ * Determines whether the given actor's own document lists the given key among
619
+ * its public keys.
620
+ *
621
+ * Keys are matched by id, which is what an actor document links to. A key
622
+ * document may leave its id implicit, though, and then there is no id for the
623
+ * actor to link to; the key material itself is the only thing the two can
624
+ * have in common, so that is what gets compared.
625
+ */
626
+ async function doesActorListKey(actor, key, options) {
627
+ if (key.id != null) {
628
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
629
+ return false;
630
+ }
631
+ if (key.publicKey == null) return false;
632
+ const publicKeys = actor.getPublicKeys({
633
+ ...options,
634
+ suppressError: true
635
+ });
636
+ for await (const publicKey of publicKeys) {
637
+ if (publicKey.publicKey == null) continue;
638
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
639
+ }
640
+ return false;
641
+ }
642
+ /**
643
+ * Compares two public keys by their key material, ignoring the metadata that
644
+ * surrounds it.
645
+ */
646
+ async function isSamePublicKey(a, b) {
647
+ const [x, y] = await Promise.all([exportJwk(a), exportJwk(b)]);
648
+ 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;
649
+ }
650
+ /**
599
651
  * Gets the actor that owns the specified key. Returns `null` if the key has no
600
652
  * known owner.
601
653
  *
654
+ * The owner is only returned when the key and the owner link to each other:
655
+ * a document that merely claims to own a key is not enough, as the claim and
656
+ * the key can come from the same host.
657
+ *
602
658
  * @param keyId The ID of the key to check, or the key itself.
603
659
  * @param options Options for getting the key owner.
604
660
  * @returns The actor that owns the key, or `null` if the key has no known
@@ -608,52 +664,50 @@ async function doesActorOwnKey(activity, key, options) {
608
664
  async function getKeyOwner(keyId, options) {
609
665
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
610
666
  const documentLoader = options.documentLoader ?? getDocumentLoader();
611
- const contextLoader = options.contextLoader ?? getDocumentLoader();
667
+ const fetchOptions = {
668
+ documentLoader,
669
+ contextLoader: options.contextLoader ?? getDocumentLoader(),
670
+ tracerProvider
671
+ };
672
+ if (keyId instanceof CryptographicKey) return await verifyKeyOwnership(keyId, fetchOptions);
673
+ let keyDoc;
674
+ let documentUrl = keyId;
675
+ try {
676
+ const remoteDocument = await documentLoader(keyId.href);
677
+ keyDoc = remoteDocument.document;
678
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
679
+ } catch (_) {
680
+ return null;
681
+ }
612
682
  let object;
613
- if (keyId instanceof CryptographicKey) {
614
- object = keyId;
615
- if (object.id == null) return null;
616
- keyId = object.id;
617
- } else {
618
- let keyDoc;
619
- try {
620
- const { document } = await documentLoader(keyId.href);
621
- keyDoc = document;
622
- } catch (_) {
623
- return null;
624
- }
683
+ try {
684
+ object = await Object$1.fromJsonLd(keyDoc, {
685
+ ...fetchOptions,
686
+ baseUrl: documentUrl
687
+ });
688
+ } catch (e) {
689
+ if (!(e instanceof TypeError)) throw e;
625
690
  try {
626
- object = await Object$1.fromJsonLd(keyDoc, {
627
- documentLoader,
628
- contextLoader,
629
- tracerProvider
630
- });
691
+ object = await CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
631
692
  } catch (e) {
632
- if (!(e instanceof TypeError)) throw e;
633
- try {
634
- object = await CryptographicKey.fromJsonLd(keyDoc, {
635
- documentLoader,
636
- contextLoader,
637
- tracerProvider
638
- });
639
- } catch (e) {
640
- if (e instanceof TypeError) return null;
641
- throw e;
642
- }
693
+ if (e instanceof TypeError) return null;
694
+ throw e;
643
695
  }
644
696
  }
645
- let owner = null;
646
697
  if (object instanceof CryptographicKey) {
647
- if (object.ownerId == null) return null;
648
- owner = await object.getOwner({
649
- documentLoader,
650
- contextLoader,
651
- tracerProvider
698
+ if (object.id != null && object.id.href !== keyId.href) return null;
699
+ return await verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
700
+ }
701
+ if (!isActor(object)) return null;
702
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
703
+ 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}.", {
704
+ documentUrl: documentUrl.href,
705
+ actorId: object.id?.href,
706
+ keyId: keyId.href
652
707
  });
653
- } else if (isActor(object)) owner = object;
654
- else return null;
655
- if (owner == null) return null;
656
- for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
708
+ return null;
709
+ }
710
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
657
711
  return null;
658
712
  }
659
713
  //#endregion
@@ -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-Yoq0YGz7.cjs");
4
+ const require_http = require("./http-BJEMpnnY.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"
@@ -205,7 +205,7 @@ function normalizeContextReference(reference, baseUrl) {
205
205
  /** @internal */
206
206
  function isInvalidUrlTypeError(error) {
207
207
  const code = error.code;
208
- return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
208
+ return error instanceof TypeError && (code === "ERR_INVALID_URL" || error.message === "Invalid URL string." || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
209
209
  }
210
210
  async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
211
211
  if (context === null) return createGraphAliasContextState();
@@ -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,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-B_Gwkjh7.mjs";
5
- import { n as doubleKnock } from "./http-DIh9_s_-.mjs";
4
+ import { n as version, t as name } from "./deno-9AaebKOA.mjs";
5
+ import { n as doubleKnock } from "./http-B5qAeoJd.mjs";
6
6
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
+ import { FetchError, 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,40 @@ 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 && error.reason === "dns") {
106
+ logger.error("DNS resolution failed for URL: {url}", {
107
+ url,
108
+ error
109
+ });
110
+ const failure = new FetchError(url, error.message);
111
+ failure.cause = error;
112
+ throw failure;
113
+ }
114
+ if (error instanceof UrlError) logger.error("Disallowed private URL: {url}", {
115
+ url,
116
+ error
117
+ });
118
+ throw error;
119
+ }
120
+ }
121
+ await validateUrl(inbox.href);
100
122
  headers = new Headers(headers);
101
123
  headers.set("Content-Type", "application/activity+json");
102
124
  const request = new Request(inbox, {
103
125
  method: "POST",
104
126
  headers,
105
- body: JSON.stringify(activity)
127
+ body: JSON.stringify(activity),
128
+ redirect: "manual"
106
129
  });
107
130
  let rsaKey = null;
108
131
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -118,9 +141,10 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, headers
118
141
  });
119
142
  let response;
120
143
  try {
121
- response = rsaKey == null ? await fetch(request) : await doubleKnock(request, rsaKey, {
144
+ response = rsaKey == null ? await fetchWithValidatedRedirects(request, validateUrl) : await doubleKnock(request, rsaKey, {
122
145
  tracerProvider,
123
- specDeterminer
146
+ specDeterminer,
147
+ validateRedirect: validateUrl
124
148
  });
125
149
  } catch (error) {
126
150
  logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
@@ -152,6 +176,49 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, headers
152
176
  "activitypub.activity.id": activityId ?? ""
153
177
  });
154
178
  }
179
+ async function fetchWithValidatedRedirects(request, validateUrl) {
180
+ let body = await request.clone().text();
181
+ for (let redirects = 0;; redirects++) {
182
+ const response = await fetch(request, { redirect: "manual" });
183
+ const location = response.headers.get("Location");
184
+ if (![
185
+ 301,
186
+ 302,
187
+ 303,
188
+ 307,
189
+ 308
190
+ ].includes(response.status) || location == null) return response;
191
+ await response.body?.cancel();
192
+ if (redirects >= 20) throw new TypeError("Too many redirects");
193
+ const url = new URL(location, request.url);
194
+ await validateUrl(url.href);
195
+ const headers = new Headers(request.headers);
196
+ if (url.origin !== new URL(request.url).origin) {
197
+ headers.delete("Authorization");
198
+ headers.delete("Proxy-Authorization");
199
+ headers.delete("Cookie");
200
+ headers.delete("Host");
201
+ }
202
+ let method = request.method;
203
+ if ((response.status === 301 || response.status === 302) && method === "POST" || response.status === 303 && method !== "GET" && method !== "HEAD") {
204
+ method = "GET";
205
+ body = void 0;
206
+ for (const name of [
207
+ "Content-Encoding",
208
+ "Content-Language",
209
+ "Content-Length",
210
+ "Content-Location",
211
+ "Content-Type"
212
+ ]) headers.delete(name);
213
+ }
214
+ request = new Request(url, {
215
+ method,
216
+ headers,
217
+ body,
218
+ redirect: "manual"
219
+ });
220
+ }
221
+ }
155
222
  /**
156
223
  * An error that is thrown when an activity fails to send to a remote inbox.
157
224
  * It contains structured information about the failure, including the HTTP