@fedify/fedify 2.4.0-dev.1964 → 2.4.0-dev.1988

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 (83) hide show
  1. package/dist/{builder-B4zpKIFU.mjs → builder-Cts78G9N.mjs} +2 -2
  2. package/dist/{client-CtxvmazV.mjs → client-DpnpgjyX.mjs} +78 -4
  3. package/dist/compat/mod.d.cts +1 -1
  4. package/dist/compat/mod.d.ts +1 -1
  5. package/dist/compat/transformers.test.mjs +1 -1
  6. package/dist/{context-COLwHogJ.d.cts → context-BeDnDuF3.d.cts} +4 -3
  7. package/dist/{context-DiiCt4S7.d.ts → context-uyRUWoZQ.d.ts} +4 -3
  8. package/dist/{deno-CtG93ohj.mjs → deno-BgMEefEr.mjs} +1 -1
  9. package/dist/{docloader-dk_k3S8d.mjs → docloader-DEYs99FZ.mjs} +2 -2
  10. package/dist/federation/builder.test.mjs +1 -1
  11. package/dist/federation/handler.test.mjs +122 -4
  12. package/dist/federation/idempotency.test.mjs +2 -2
  13. package/dist/federation/keycache.test.mjs +52 -9
  14. package/dist/federation/metrics.test.mjs +1 -1
  15. package/dist/federation/middleware.test.mjs +111 -15
  16. package/dist/federation/mod.cjs +1 -1
  17. package/dist/federation/mod.d.cts +2 -2
  18. package/dist/federation/mod.d.ts +2 -2
  19. package/dist/federation/mod.js +1 -1
  20. package/dist/federation/send.test.mjs +139 -4
  21. package/dist/federation/tasks/enqueue.test.mjs +1 -1
  22. package/dist/federation/tasks/tasks.test.mjs +2 -2
  23. package/dist/federation/temporal.test.mjs +1 -1
  24. package/dist/federation/webfinger.test.mjs +1 -1
  25. package/dist/{federation-Drjlrrax.cjs → federation-DzPUG_AP.cjs} +93 -17
  26. package/dist/{http-6TI0tI03.d.cts → http-65PYi9jY.d.ts} +34 -2
  27. package/dist/{http-CdrSn2ip.d.ts → http-CP-7OdSq.d.cts} +34 -2
  28. package/dist/{http-Dj4s1UQ0.js → http-CgwqtxAy.js} +169 -7
  29. package/dist/{http-D7LX-BL9.mjs → http-CtidZS_t.mjs} +3 -3
  30. package/dist/{http-B3skRvGo.cjs → http-Z3anvCd-.cjs} +180 -6
  31. package/dist/{key-BVjgbs_9.mjs → key-Cwbg5ggV.mjs} +169 -7
  32. package/dist/{keycache-ZLqIfrkL.mjs → keycache-BUDHB5rY.mjs} +12 -4
  33. package/dist/{kv-cache-DtsjH_bY.cjs → kv-cache-BM2-w-Wq.cjs} +2 -2
  34. package/dist/{kv-cache-tGNbvDCF.js → kv-cache-CykuL0ya.js} +2 -2
  35. package/dist/{kv-cache-xRcC_xxP.mjs → kv-cache-DHiR8yTf.mjs} +1 -1
  36. package/dist/{ld-OuCeQFny.mjs → ld-CzhdWyTt.mjs} +3 -3
  37. package/dist/{metrics-B9N27cCB.mjs → metrics-CrqsHP0l.mjs} +1 -1
  38. package/dist/{middleware-Cd_vPqDH.mjs → middleware-CZpYxSKD.mjs} +1 -1
  39. package/dist/{middleware-CPTDFMmJ.js → middleware-CeCj5caM.js} +101 -25
  40. package/dist/{middleware-TeLjzoxn.mjs → middleware-DCpiAsZi.mjs} +34 -23
  41. package/dist/{mod-DypxPS9H.d.ts → mod-C0BYc0OU.d.ts} +1 -1
  42. package/dist/{mod-CnGLNoVw.d.cts → mod-CbKDOnCt.d.cts} +1 -1
  43. package/dist/{mod-CLHkCwLm.d.cts → mod-CyiSjRkk.d.cts} +1 -1
  44. package/dist/{mod-CSH1Ee-I.d.ts → mod-D882_Xsg.d.ts} +1 -1
  45. package/dist/{mod-DzRXACM5.d.ts → mod-UDwMjuHM.d.ts} +1 -1
  46. package/dist/{mod-BZldCEU0.d.cts → mod-x9W0d0Pk.d.cts} +1 -1
  47. package/dist/mod.cjs +5 -5
  48. package/dist/mod.d.cts +6 -6
  49. package/dist/mod.d.ts +6 -6
  50. package/dist/mod.js +5 -5
  51. package/dist/nodeinfo/client.test.mjs +28 -1
  52. package/dist/nodeinfo/handler.test.mjs +1 -1
  53. package/dist/nodeinfo/mod.cjs +1 -1
  54. package/dist/nodeinfo/mod.js +1 -1
  55. package/dist/{owner-DGSfntI-.d.ts → owner-BF0L9cMt.d.cts} +12 -1
  56. package/dist/{owner-r_waTiQj.d.cts → owner-BSzr5-I8.d.ts} +12 -1
  57. package/dist/owner-BqVXJLW8.mjs +175 -0
  58. package/dist/{proof-BO_esQii.js → proof-CUghqhAf.js} +122 -65
  59. package/dist/{proof-Dua0d906.cjs → proof-DHu5zI0Z.cjs} +122 -65
  60. package/dist/{proof-D5Ajk4DJ.mjs → proof-DL8Iid3a.mjs} +14 -11
  61. package/dist/{send-DVXyUqhO.mjs → send-6jS4xFsX.mjs} +68 -11
  62. package/dist/sig/http.test.mjs +2 -2
  63. package/dist/sig/key.test.mjs +169 -2
  64. package/dist/sig/ld.test.mjs +55 -2
  65. package/dist/sig/mod.cjs +2 -2
  66. package/dist/sig/mod.d.cts +3 -3
  67. package/dist/sig/mod.d.ts +3 -3
  68. package/dist/sig/mod.js +2 -2
  69. package/dist/sig/owner.test.mjs +103 -4
  70. package/dist/sig/proof.test.mjs +120 -1
  71. package/dist/{temporal-BoDw51A-.mjs → temporal-DcyzeytP.mjs} +1 -1
  72. package/dist/testing/kv.test.mjs +1 -1
  73. package/dist/testing/mod.d.mts +2 -1
  74. package/dist/{types-RXm5YxpC.cjs → types-Be2zbyeG.cjs} +94 -2
  75. package/dist/{types-Dtyf8lVj.js → types-C_cNlNVK.js} +78 -4
  76. package/dist/utils/docloader.test.mjs +27 -3
  77. package/dist/utils/kv-cache.test.mjs +1 -1
  78. package/dist/utils/mod.cjs +1 -1
  79. package/dist/utils/mod.d.cts +1 -1
  80. package/dist/utils/mod.d.ts +1 -1
  81. package/dist/utils/mod.js +1 -1
  82. package/package.json +6 -6
  83. package/dist/owner-DTEqTzSr.mjs +0 -120
@@ -5,7 +5,7 @@ import { r as createRequestContext } from "../context-CbS35fLr.mjs";
5
5
  import { t as MemoryKvStore } from "../kv-DCHkaJ9-.mjs";
6
6
  import { t as assertEquals } from "../assert_equals-CBlRfA-_.mjs";
7
7
  import "../std__assert-CxFT0MNt.mjs";
8
- import { _ as handleNodeInfo, o as createFederation, v as handleNodeInfoJrd } from "../middleware-TeLjzoxn.mjs";
8
+ import { _ as handleNodeInfo, o as createFederation, v as handleNodeInfoJrd } from "../middleware-DCpiAsZi.mjs";
9
9
  import { test } from "@fedify/fixture";
10
10
  //#region src/nodeinfo/handler.test.ts
11
11
  test("handleNodeInfo()", async () => {
@@ -1,6 +1,6 @@
1
1
  const { URLPattern } = require("urlpattern-polyfill");
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_types = require("../types-RXm5YxpC.cjs");
3
+ const require_types = require("../types-Be2zbyeG.cjs");
4
4
  exports.getNodeInfo = require_types.getNodeInfo;
5
5
  exports.nodeInfoToJson = require_types.nodeInfoToJson;
6
6
  exports.parseNodeInfo = require_types.parseNodeInfo;
@@ -1,4 +1,4 @@
1
1
  import { Temporal } from "temporal-polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { n as getNodeInfo, r as parseNodeInfo, t as nodeInfoToJson } from "../types-Dtyf8lVj.js";
3
+ import { n as getNodeInfo, r as parseNodeInfo, t as nodeInfoToJson } from "../types-C_cNlNVK.js";
4
4
  export { getNodeInfo, nodeInfoToJson, parseNodeInfo };
@@ -1,7 +1,7 @@
1
1
  /// <reference lib="esnext.temporal" />
2
2
  import { Activity, Actor, CryptographicKey } from "@fedify/vocab";
3
- import { TracerProvider } from "@opentelemetry/api";
4
3
  import { DocumentLoader } from "@fedify/vocab-runtime";
4
+ import { TracerProvider } from "@opentelemetry/api";
5
5
 
6
6
  //#region src/sig/owner.d.ts
7
7
  /**
@@ -26,6 +26,13 @@ interface DoesActorOwnKeyOptions {
26
26
  }
27
27
  /**
28
28
  * Checks if the actor of the given activity owns the specified key.
29
+ *
30
+ * Ownership is never taken from what the activity or the key say about
31
+ * themselves, as both are written by whoever sent the activity. It is
32
+ * established from a document that the owner itself serves: either the key's
33
+ * claimed owner links back to the key, or the actor the activity claims lists
34
+ * the key as its own.
35
+ *
29
36
  * @param activity The activity to check.
30
37
  * @param key The public key to check.
31
38
  * @param options Options for checking the key ownership.
@@ -56,6 +63,10 @@ interface GetKeyOwnerOptions {
56
63
  * Gets the actor that owns the specified key. Returns `null` if the key has no
57
64
  * known owner.
58
65
  *
66
+ * The owner is only returned when the key and the owner link to each other:
67
+ * a document that merely claims to own a key is not enough, as the claim and
68
+ * the key can come from the same host.
69
+ *
59
70
  * @param keyId The ID of the key to check, or the key itself.
60
71
  * @param options Options for getting the key owner.
61
72
  * @returns The actor that owns the key, or `null` if the key has no known
@@ -1,7 +1,7 @@
1
1
  /// <reference lib="esnext.temporal" />
2
2
  import { Activity, Actor, CryptographicKey } from "@fedify/vocab";
3
- import { DocumentLoader } from "@fedify/vocab-runtime";
4
3
  import { TracerProvider } from "@opentelemetry/api";
4
+ import { DocumentLoader } from "@fedify/vocab-runtime";
5
5
 
6
6
  //#region src/sig/owner.d.ts
7
7
  /**
@@ -26,6 +26,13 @@ interface DoesActorOwnKeyOptions {
26
26
  }
27
27
  /**
28
28
  * Checks if the actor of the given activity owns the specified key.
29
+ *
30
+ * Ownership is never taken from what the activity or the key say about
31
+ * themselves, as both are written by whoever sent the activity. It is
32
+ * established from a document that the owner itself serves: either the key's
33
+ * claimed owner links back to the key, or the actor the activity claims lists
34
+ * the key as its own.
35
+ *
29
36
  * @param activity The activity to check.
30
37
  * @param key The public key to check.
31
38
  * @param options Options for checking the key ownership.
@@ -56,6 +63,10 @@ interface GetKeyOwnerOptions {
56
63
  * Gets the actor that owns the specified key. Returns `null` if the key has no
57
64
  * known owner.
58
65
  *
66
+ * The owner is only returned when the key and the owner link to each other:
67
+ * a document that merely claims to own a key is not enough, as the claim and
68
+ * the key can come from the same host.
69
+ *
59
70
  * @param keyId The ID of the key to check, or the key itself.
60
71
  * @param options Options for getting the key owner.
61
72
  * @returns The actor that owns the key, or `null` if the key has no known
@@ -0,0 +1,175 @@
1
+ import "temporal-polyfill";
2
+ import "urlpattern-polyfill";
3
+ globalThis.addEventListener = () => {};
4
+ import { n as version, t as name } from "./deno-BgMEefEr.mjs";
5
+ import { c as verifyKeyOwnership, n as fetchActorDocument, t as exportJwk } from "./key-Cwbg5ggV.mjs";
6
+ import { getLogger } from "@logtape/logtape";
7
+ import { CryptographicKey, Object as Object$1, isActor } from "@fedify/vocab";
8
+ import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
9
+ import { getDocumentLoader } from "@fedify/vocab-runtime";
10
+ //#region src/sig/owner.ts
11
+ const logger = getLogger([
12
+ "fedify",
13
+ "sig",
14
+ "owner"
15
+ ]);
16
+ /**
17
+ * Checks if the actor of the given activity owns the specified key.
18
+ *
19
+ * Ownership is never taken from what the activity or the key say about
20
+ * themselves, as both are written by whoever sent the activity. It is
21
+ * established from a document that the owner itself serves: either the key's
22
+ * claimed owner links back to the key, or the actor the activity claims lists
23
+ * the key as its own.
24
+ *
25
+ * @param activity The activity to check.
26
+ * @param key The public key to check.
27
+ * @param options Options for checking the key ownership.
28
+ * @returns Whether the actor is the owner of the key.
29
+ */
30
+ async function doesActorOwnKey(activity, key, options) {
31
+ return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("activitypub.verify_key_ownership", {
32
+ kind: SpanKind.INTERNAL,
33
+ attributes: {
34
+ "activitypub.actor.id": activity.actorId?.href ?? "",
35
+ "activitypub.key.id": key.id?.href ?? ""
36
+ }
37
+ }, async (span) => {
38
+ try {
39
+ const actorId = activity.actorId;
40
+ if (actorId == null) {
41
+ span.setAttribute("activitypub.key_ownership.verified", false);
42
+ span.setAttribute("activitypub.key_ownership.method", "none");
43
+ return false;
44
+ }
45
+ if (key.ownerId != null) {
46
+ const owner = await verifyKeyOwnership(key, options);
47
+ if (owner?.id != null && owner.id.href === actorId.href) {
48
+ span.setAttribute("activitypub.key_ownership.verified", true);
49
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
50
+ return true;
51
+ }
52
+ }
53
+ const actor = await fetchActorDocument(actorId, options);
54
+ if (actor != null && await doesActorListKey(actor, key, options)) {
55
+ span.setAttribute("activitypub.key_ownership.verified", true);
56
+ span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
57
+ return true;
58
+ }
59
+ logger.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.", {
60
+ actorId: actorId.href,
61
+ keyId: key.id?.href
62
+ });
63
+ span.setAttribute("activitypub.key_ownership.verified", false);
64
+ span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
65
+ return false;
66
+ } catch (error) {
67
+ span.recordException(error);
68
+ span.setStatus({
69
+ code: SpanStatusCode.ERROR,
70
+ message: String(error)
71
+ });
72
+ throw error;
73
+ } finally {
74
+ span.end();
75
+ }
76
+ });
77
+ }
78
+ /**
79
+ * Determines whether the given actor's own document lists the given key among
80
+ * its public keys.
81
+ *
82
+ * Keys are matched by id, which is what an actor document links to. A key
83
+ * document may leave its id implicit, though, and then there is no id for the
84
+ * actor to link to; the key material itself is the only thing the two can
85
+ * have in common, so that is what gets compared.
86
+ */
87
+ async function doesActorListKey(actor, key, options) {
88
+ if (key.id != null) {
89
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
90
+ return false;
91
+ }
92
+ if (key.publicKey == null) return false;
93
+ const publicKeys = actor.getPublicKeys({
94
+ ...options,
95
+ suppressError: true
96
+ });
97
+ for await (const publicKey of publicKeys) {
98
+ if (publicKey.publicKey == null) continue;
99
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
100
+ }
101
+ return false;
102
+ }
103
+ /**
104
+ * Compares two public keys by their key material, ignoring the metadata that
105
+ * surrounds it.
106
+ */
107
+ async function isSamePublicKey(a, b) {
108
+ const [x, y] = await Promise.all([exportJwk(a), exportJwk(b)]);
109
+ 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;
110
+ }
111
+ /**
112
+ * Gets the actor that owns the specified key. Returns `null` if the key has no
113
+ * known owner.
114
+ *
115
+ * The owner is only returned when the key and the owner link to each other:
116
+ * a document that merely claims to own a key is not enough, as the claim and
117
+ * the key can come from the same host.
118
+ *
119
+ * @param keyId The ID of the key to check, or the key itself.
120
+ * @param options Options for getting the key owner.
121
+ * @returns The actor that owns the key, or `null` if the key has no known
122
+ * owner.
123
+ * @since 0.7.0
124
+ */
125
+ async function getKeyOwner(keyId, options) {
126
+ const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
127
+ const documentLoader = options.documentLoader ?? getDocumentLoader();
128
+ const fetchOptions = {
129
+ documentLoader,
130
+ contextLoader: options.contextLoader ?? getDocumentLoader(),
131
+ tracerProvider
132
+ };
133
+ if (keyId instanceof CryptographicKey) return await verifyKeyOwnership(keyId, fetchOptions);
134
+ let keyDoc;
135
+ let documentUrl = keyId;
136
+ try {
137
+ const remoteDocument = await documentLoader(keyId.href);
138
+ keyDoc = remoteDocument.document;
139
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
140
+ } catch (_) {
141
+ return null;
142
+ }
143
+ let object;
144
+ try {
145
+ object = await Object$1.fromJsonLd(keyDoc, {
146
+ ...fetchOptions,
147
+ baseUrl: documentUrl
148
+ });
149
+ } catch (e) {
150
+ if (!(e instanceof TypeError)) throw e;
151
+ try {
152
+ object = await CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
153
+ } catch (e) {
154
+ if (e instanceof TypeError) return null;
155
+ throw e;
156
+ }
157
+ }
158
+ if (object instanceof CryptographicKey) {
159
+ if (object.id != null && object.id.href !== keyId.href) return null;
160
+ return await verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
161
+ }
162
+ if (!isActor(object)) return null;
163
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
164
+ logger.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}.", {
165
+ documentUrl: documentUrl.href,
166
+ actorId: object.id?.href,
167
+ keyId: keyId.href
168
+ });
169
+ return null;
170
+ }
171
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
172
+ return null;
173
+ }
174
+ //#endregion
175
+ export { getKeyOwner as n, doesActorOwnKey as t };
@@ -1,6 +1,6 @@
1
1
  import { Temporal } from "temporal-polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { F as version, P as name, _ as measureSignatureKeyFetch, d as validateCryptoKey, f as getDurationMs, p as getFederationMetrics, s as fetchKey } from "./http-Dj4s1UQ0.js";
3
+ import { I as name, L as version, c as fetchKey, f as validateCryptoKey, h as getFederationMetrics, m as getDurationMs, o as exportJwk, p as verifyKeyOwnership, s as fetchActorDocument, y as measureSignatureKeyFetch } from "./http-CgwqtxAy.js";
4
4
  import { getLogger } from "@logtape/logtape";
5
5
  import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, PUBLIC_COLLECTION, getTypeId, isActor } from "@fedify/vocab";
6
6
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
@@ -10,7 +10,7 @@ import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
10
10
  import jsonld from "@fedify/vocab-runtime/jsonld";
11
11
  import serialize from "json-canon";
12
12
  //#region src/sig/ld.ts
13
- const logger$3 = getLogger([
13
+ const logger$4 = getLogger([
14
14
  "fedify",
15
15
  "sig",
16
16
  "ld"
@@ -453,7 +453,7 @@ async function verifySignature(jsonLd, options = {}) {
453
453
  try {
454
454
  signature = decodeBase64(sig.signatureValue);
455
455
  } catch (error) {
456
- logger$3.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
456
+ logger$4.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
457
457
  ...sig,
458
458
  error
459
459
  });
@@ -472,7 +472,7 @@ async function verifySignature(jsonLd, options = {}) {
472
472
  try {
473
473
  sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
474
474
  } catch (error) {
475
- logger$3.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
475
+ logger$4.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
476
476
  signatureOptions: sigOpts,
477
477
  error
478
478
  });
@@ -484,7 +484,7 @@ async function verifySignature(jsonLd, options = {}) {
484
484
  try {
485
485
  docHash = await hashJsonLd(document, options.contextLoader);
486
486
  } catch (error) {
487
- logger$3.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
487
+ logger$4.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
488
488
  document,
489
489
  error
490
490
  });
@@ -495,7 +495,7 @@ async function verifySignature(jsonLd, options = {}) {
495
495
  const messageBytes = encoder.encode(message);
496
496
  if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
497
497
  if (cached) {
498
- logger$3.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
498
+ logger$4.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
499
499
  keyId: sig.creator,
500
500
  ...sig
501
501
  });
@@ -509,7 +509,7 @@ async function verifySignature(jsonLd, options = {}) {
509
509
  if (key == null) return null;
510
510
  return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
511
511
  }
512
- logger$3.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
512
+ logger$4.debug("Failed to verify with the fetched key {keyId}; signature {signatureValue} is invalid. Check if the key is correct or if the signed message is correct. The message to sign is:\n{message}", {
513
513
  keyId: sig.creator,
514
514
  ...sig,
515
515
  message
@@ -588,12 +588,12 @@ async function verifyJsonLdInternal(jsonLd, options, compact) {
588
588
  const key = await verifySignature(compacted, verificationOptions);
589
589
  if (key == null) return false;
590
590
  if (key.ownerId == null) {
591
- logger$3.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
591
+ logger$4.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
592
592
  return false;
593
593
  }
594
594
  attributions.delete(key.ownerId.href);
595
595
  if (attributions.size > 0) {
596
- logger$3.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
596
+ logger$4.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
597
597
  return false;
598
598
  }
599
599
  verified = true;
@@ -622,8 +622,20 @@ async function hashJsonLd(jsonLd, contextLoader) {
622
622
  }
623
623
  //#endregion
624
624
  //#region src/sig/owner.ts
625
+ const logger$3 = getLogger([
626
+ "fedify",
627
+ "sig",
628
+ "owner"
629
+ ]);
625
630
  /**
626
631
  * Checks if the actor of the given activity owns the specified key.
632
+ *
633
+ * Ownership is never taken from what the activity or the key say about
634
+ * themselves, as both are written by whoever sent the activity. It is
635
+ * established from a document that the owner itself serves: either the key's
636
+ * claimed owner links back to the key, or the actor the activity claims lists
637
+ * the key as its own.
638
+ *
627
639
  * @param activity The activity to check.
628
640
  * @param key The public key to check.
629
641
  * @param options Options for checking the key ownership.
@@ -638,23 +650,30 @@ async function doesActorOwnKey(activity, key, options) {
638
650
  }
639
651
  }, async (span) => {
640
652
  try {
641
- if (key.ownerId != null) {
642
- const owns = key.ownerId.href === activity.actorId?.href;
643
- span.setAttribute("activitypub.key_ownership.verified", owns);
644
- span.setAttribute("activitypub.key_ownership.method", "owner_id");
645
- return owns;
646
- }
647
- const actor = await activity.getActor(options);
648
- if (actor == null || !isActor(actor)) {
653
+ const actorId = activity.actorId;
654
+ if (actorId == null) {
649
655
  span.setAttribute("activitypub.key_ownership.verified", false);
650
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
656
+ span.setAttribute("activitypub.key_ownership.method", "none");
651
657
  return false;
652
658
  }
653
- for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
659
+ if (key.ownerId != null) {
660
+ const owner = await verifyKeyOwnership(key, options);
661
+ if (owner?.id != null && owner.id.href === actorId.href) {
662
+ span.setAttribute("activitypub.key_ownership.verified", true);
663
+ span.setAttribute("activitypub.key_ownership.method", "key_owner");
664
+ return true;
665
+ }
666
+ }
667
+ const actor = await fetchActorDocument(actorId, options);
668
+ if (actor != null && await doesActorListKey(actor, key, options)) {
654
669
  span.setAttribute("activitypub.key_ownership.verified", true);
655
670
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
656
671
  return true;
657
672
  }
673
+ logger$3.debug("The actor {actorId} does not own key {keyId}: neither the owner the key claims nor the actor's own document links the two to each other.", {
674
+ actorId: actorId.href,
675
+ keyId: key.id?.href
676
+ });
658
677
  span.setAttribute("activitypub.key_ownership.verified", false);
659
678
  span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
660
679
  return false;
@@ -671,9 +690,46 @@ async function doesActorOwnKey(activity, key, options) {
671
690
  });
672
691
  }
673
692
  /**
693
+ * Determines whether the given actor's own document lists the given key among
694
+ * its public keys.
695
+ *
696
+ * Keys are matched by id, which is what an actor document links to. A key
697
+ * document may leave its id implicit, though, and then there is no id for the
698
+ * actor to link to; the key material itself is the only thing the two can
699
+ * have in common, so that is what gets compared.
700
+ */
701
+ async function doesActorListKey(actor, key, options) {
702
+ if (key.id != null) {
703
+ for (const publicKeyId of actor.publicKeyIds) if (publicKeyId.href === key.id.href) return true;
704
+ return false;
705
+ }
706
+ if (key.publicKey == null) return false;
707
+ const publicKeys = actor.getPublicKeys({
708
+ ...options,
709
+ suppressError: true
710
+ });
711
+ for await (const publicKey of publicKeys) {
712
+ if (publicKey.publicKey == null) continue;
713
+ if (await isSamePublicKey(publicKey.publicKey, key.publicKey)) return true;
714
+ }
715
+ return false;
716
+ }
717
+ /**
718
+ * Compares two public keys by their key material, ignoring the metadata that
719
+ * surrounds it.
720
+ */
721
+ async function isSamePublicKey(a, b) {
722
+ const [x, y] = await Promise.all([exportJwk(a), exportJwk(b)]);
723
+ return x.kty === y.kty && x.crv === y.crv && x.n === y.n && x.e === y.e && x.x === y.x && x.y === y.y;
724
+ }
725
+ /**
674
726
  * Gets the actor that owns the specified key. Returns `null` if the key has no
675
727
  * known owner.
676
728
  *
729
+ * The owner is only returned when the key and the owner link to each other:
730
+ * a document that merely claims to own a key is not enough, as the claim and
731
+ * the key can come from the same host.
732
+ *
677
733
  * @param keyId The ID of the key to check, or the key itself.
678
734
  * @param options Options for getting the key owner.
679
735
  * @returns The actor that owns the key, or `null` if the key has no known
@@ -683,52 +739,50 @@ async function doesActorOwnKey(activity, key, options) {
683
739
  async function getKeyOwner(keyId, options) {
684
740
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
685
741
  const documentLoader = options.documentLoader ?? getDocumentLoader();
686
- const contextLoader = options.contextLoader ?? getDocumentLoader();
742
+ const fetchOptions = {
743
+ documentLoader,
744
+ contextLoader: options.contextLoader ?? getDocumentLoader(),
745
+ tracerProvider
746
+ };
747
+ if (keyId instanceof CryptographicKey) return await verifyKeyOwnership(keyId, fetchOptions);
748
+ let keyDoc;
749
+ let documentUrl = keyId;
750
+ try {
751
+ const remoteDocument = await documentLoader(keyId.href);
752
+ keyDoc = remoteDocument.document;
753
+ documentUrl = new URL(remoteDocument.documentUrl ?? "", keyId);
754
+ } catch (_) {
755
+ return null;
756
+ }
687
757
  let object;
688
- if (keyId instanceof CryptographicKey) {
689
- object = keyId;
690
- if (object.id == null) return null;
691
- keyId = object.id;
692
- } else {
693
- let keyDoc;
694
- try {
695
- const { document } = await documentLoader(keyId.href);
696
- keyDoc = document;
697
- } catch (_) {
698
- return null;
699
- }
758
+ try {
759
+ object = await Object$1.fromJsonLd(keyDoc, {
760
+ ...fetchOptions,
761
+ baseUrl: documentUrl
762
+ });
763
+ } catch (e) {
764
+ if (!(e instanceof TypeError)) throw e;
700
765
  try {
701
- object = await Object$1.fromJsonLd(keyDoc, {
702
- documentLoader,
703
- contextLoader,
704
- tracerProvider
705
- });
766
+ object = await CryptographicKey.fromJsonLd(keyDoc, fetchOptions);
706
767
  } catch (e) {
707
- if (!(e instanceof TypeError)) throw e;
708
- try {
709
- object = await CryptographicKey.fromJsonLd(keyDoc, {
710
- documentLoader,
711
- contextLoader,
712
- tracerProvider
713
- });
714
- } catch (e) {
715
- if (e instanceof TypeError) return null;
716
- throw e;
717
- }
768
+ if (e instanceof TypeError) return null;
769
+ throw e;
718
770
  }
719
771
  }
720
- let owner = null;
721
772
  if (object instanceof CryptographicKey) {
722
- if (object.ownerId == null) return null;
723
- owner = await object.getOwner({
724
- documentLoader,
725
- contextLoader,
726
- tracerProvider
773
+ if (object.id != null && object.id.href !== keyId.href) return null;
774
+ return await verifyKeyOwnership(object.id == null ? object.clone({ id: keyId }) : object, fetchOptions);
775
+ }
776
+ if (!isActor(object)) return null;
777
+ if (object.id == null || object.id.origin !== documentUrl.origin) {
778
+ logger$3.debug("The document served at {documentUrl} claims to be the actor {actorId}, which belongs to another origin; refusing to treat it as the owner of key {keyId}.", {
779
+ documentUrl: documentUrl.href,
780
+ actorId: object.id?.href,
781
+ keyId: keyId.href
727
782
  });
728
- } else if (isActor(object)) owner = object;
729
- else return null;
730
- if (owner == null) return null;
731
- for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
783
+ return null;
784
+ }
785
+ for (const kid of object.publicKeyIds) if (kid.href === keyId.href) return object;
732
786
  return null;
733
787
  }
734
788
  //#endregion
@@ -1262,7 +1316,7 @@ async function signObject(object, privateKey, keyId, options = {}) {
1262
1316
  async function verifyProof(jsonLd, proof, options = {}) {
1263
1317
  return await verifyProofWithMessageDigestCache(jsonLd, proof, options);
1264
1318
  }
1265
- async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate) {
1319
+ async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate, keyIdBoundByCaller = false) {
1266
1320
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
1267
1321
  const start = performance.now();
1268
1322
  let verified = false;
@@ -1274,7 +1328,7 @@ async function verifyProofWithMessageDigestCache(jsonLd, proof, options, message
1274
1328
  if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
1275
1329
  }
1276
1330
  try {
1277
- const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate);
1331
+ const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1278
1332
  if (key == null) span.setStatus({ code: SpanStatusCode.ERROR });
1279
1333
  else verified = true;
1280
1334
  return key;
@@ -1591,12 +1645,15 @@ async function hasValidProofOptions(proofConfig, options, documentLoader) {
1591
1645
  if (previousProof == null || previousProof.present && typeof previousProof.value !== "string" && (!Array.isArray(previousProof.value) || previousProof.value.some((item) => typeof item !== "string"))) return false;
1592
1646
  return true;
1593
1647
  }
1594
- async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate) {
1648
+ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller = false) {
1595
1649
  if (!isJsonLdNode(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
1596
1650
  const proofContextLoader = messageDigestCache.proofContextLoader ?? preloadedOnlyDocumentLoader;
1597
1651
  const proofConfiguration = await createProofConfiguration(jsonLd, proof, options, proofContextLoader, rawProofCandidate);
1598
1652
  if (proofConfiguration == null || !await hasValidProofOptions(proofConfiguration.value, options, proofContextLoader)) return null;
1599
- const publicKeyPromise = measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => fetchKey(proof.verificationMethodId, Multikey, options));
1653
+ const publicKeyPromise = measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => fetchKey(proof.verificationMethodId, Multikey, {
1654
+ ...options,
1655
+ keyIdBoundByCaller
1656
+ }));
1600
1657
  const proofBytes = new TextEncoder().encode(serialize(proofConfiguration.value));
1601
1658
  const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
1602
1659
  let fetchedKey;
@@ -1630,7 +1687,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1630
1687
  get: () => Promise.resolve(void 0),
1631
1688
  set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1632
1689
  }
1633
- }, messageDigestCache, rawProofCandidate);
1690
+ }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1634
1691
  }
1635
1692
  logger.debug("The fetched key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}", {
1636
1693
  proof,
@@ -1667,7 +1724,7 @@ async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, r
1667
1724
  get: () => Promise.resolve(void 0),
1668
1725
  set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1669
1726
  }
1670
- }, messageDigestCache, rawProofCandidate);
1727
+ }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
1671
1728
  }
1672
1729
  logger.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
1673
1730
  keyId: proof.verificationMethodId.href,
@@ -1882,7 +1939,7 @@ async function verifyPortableObjectProof(jsonLd, options = {}) {
1882
1939
  proofIndex
1883
1940
  }
1884
1941
  };
1885
- const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate);
1942
+ const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate, true);
1886
1943
  if (key == null) return {
1887
1944
  verified: false,
1888
1945
  reason: {