@fedify/fedify 2.5.0-dev.2687 → 2.5.0-dev.2726

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 (244) hide show
  1. package/dist/federation/mod.cjs +1 -1
  2. package/dist/federation/mod.js +1 -1
  3. package/dist/{federation-pFFwPyoZ.cjs → federation-C0zalE9W.cjs} +8 -3
  4. package/dist/{http-T7h9GBAN.js → http-BC5Bd3-E.js} +1 -1
  5. package/dist/{http-CXX-QPzs.cjs → http-Dqzgc4Rj.cjs} +1 -1
  6. package/dist/{kv-cache-EFcb1kkU.js → kv-cache-CQ0u0Ry0.js} +1 -1
  7. package/dist/{kv-cache-C6XX_fwz.cjs → kv-cache-ihEHdx1v.cjs} +1 -1
  8. package/dist/{middleware-Bj91r7r2.js → middleware-Bgm3A90j.js} +8 -3
  9. package/dist/mod.cjs +4 -4
  10. package/dist/mod.js +4 -4
  11. package/dist/{portable-collection-Do5QA2oy.js → portable-collection-DZ_XqNUM.js} +1 -1
  12. package/dist/{portable-collection-BOl9oKrt.cjs → portable-collection-nvog8lS6.cjs} +1 -1
  13. package/dist/sig/mod.cjs +2 -2
  14. package/dist/sig/mod.js +2 -2
  15. package/dist/utils/mod.cjs +1 -1
  16. package/dist/utils/mod.js +1 -1
  17. package/package.json +22 -9
  18. package/skills/fedify/SKILL.md +35 -0
  19. package/dist/accept-CPVqki78.mjs +0 -145
  20. package/dist/activity-listener-CELFAodc.mjs +0 -44
  21. package/dist/assert-D1Eafmd_.mjs +0 -23
  22. package/dist/assert_equals-Z6IcEbWU.mjs +0 -987
  23. package/dist/assert_exists-cffSpJ7X.mjs +0 -28
  24. package/dist/assert_false-CPdRnc3E.mjs +0 -23
  25. package/dist/assert_greater_or_equal-BlafOF4-.mjs +0 -31
  26. package/dist/assert_instance_of-mrXWWNY-.mjs +0 -37
  27. package/dist/assert_not_equals-CpPK2t89.mjs +0 -30
  28. package/dist/assert_rejects-CTptdYck.mjs +0 -39
  29. package/dist/assert_strict_equals-CYvBmkpC.mjs +0 -42
  30. package/dist/assert_throws-BYITOvPO.mjs +0 -74
  31. package/dist/assertion_error-B-cx0fFA.mjs +0 -31
  32. package/dist/audience-CHQ-FlLD.mjs +0 -95
  33. package/dist/builder-D1FP_5nQ.mjs +0 -911
  34. package/dist/circuit-breaker-XJ53md4S.mjs +0 -544
  35. package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +0 -14
  36. package/dist/client-5SIFzW3q.mjs +0 -441
  37. package/dist/codec-C6rTrpIp.mjs +0 -147
  38. package/dist/collection-CnnP1UAv.mjs +0 -44
  39. package/dist/compat/outgoing-jsonld.test.d.mts +0 -2
  40. package/dist/compat/outgoing-jsonld.test.mjs +0 -257
  41. package/dist/compat/public-audience.test.d.mts +0 -2
  42. package/dist/compat/public-audience.test.mjs +0 -187
  43. package/dist/compat/secured-document.test.d.mts +0 -2
  44. package/dist/compat/secured-document.test.mjs +0 -58
  45. package/dist/compat/transformers.test.d.mts +0 -2
  46. package/dist/compat/transformers.test.mjs +0 -62
  47. package/dist/compound-proof-DSHhnOEW.mjs +0 -1019
  48. package/dist/context-LgGFFSz7.mjs +0 -146
  49. package/dist/deno-C50ikGBU.mjs +0 -8
  50. package/dist/dist-_geWsuaI.mjs +0 -189
  51. package/dist/docloader-BY-SEID0.mjs +0 -136
  52. package/dist/esm-BHXXx4Wx.mjs +0 -1233
  53. package/dist/exporter-DVG68ozH.mjs +0 -263
  54. package/dist/federation/audience.test.d.mts +0 -2
  55. package/dist/federation/audience.test.mjs +0 -130
  56. package/dist/federation/builder.test.d.mts +0 -2
  57. package/dist/federation/builder.test.mjs +0 -396
  58. package/dist/federation/circuit-breaker.test.d.mts +0 -2
  59. package/dist/federation/circuit-breaker.test.mjs +0 -1277
  60. package/dist/federation/collection.test.d.mts +0 -2
  61. package/dist/federation/collection.test.mjs +0 -21
  62. package/dist/federation/compound-fanout.test.d.mts +0 -2
  63. package/dist/federation/compound-fanout.test.mjs +0 -231
  64. package/dist/federation/handler-compound-proof.test.d.mts +0 -2
  65. package/dist/federation/handler-compound-proof.test.mjs +0 -384
  66. package/dist/federation/handler.test.d.mts +0 -2
  67. package/dist/federation/handler.test.mjs +0 -5445
  68. package/dist/federation/hashlink-media.test.d.mts +0 -2
  69. package/dist/federation/hashlink-media.test.mjs +0 -422
  70. package/dist/federation/idempotency.test.d.mts +0 -2
  71. package/dist/federation/idempotency.test.mjs +0 -207
  72. package/dist/federation/inbox-actorless.test.d.mts +0 -2
  73. package/dist/federation/inbox-actorless.test.mjs +0 -522
  74. package/dist/federation/inbox-authentication.test.d.mts +0 -2
  75. package/dist/federation/inbox-authentication.test.mjs +0 -220
  76. package/dist/federation/inbox-report.test.d.mts +0 -2
  77. package/dist/federation/inbox-report.test.mjs +0 -719
  78. package/dist/federation/inbox-view.test.d.mts +0 -2
  79. package/dist/federation/inbox-view.test.mjs +0 -369
  80. package/dist/federation/inbox.test.d.mts +0 -2
  81. package/dist/federation/inbox.test.mjs +0 -139
  82. package/dist/federation/keycache.test.d.mts +0 -2
  83. package/dist/federation/keycache.test.mjs +0 -337
  84. package/dist/federation/kv.test.d.mts +0 -2
  85. package/dist/federation/kv.test.mjs +0 -88
  86. package/dist/federation/metrics.test.d.mts +0 -2
  87. package/dist/federation/metrics.test.mjs +0 -634
  88. package/dist/federation/middleware.test.d.mts +0 -2
  89. package/dist/federation/middleware.test.mjs +0 -9314
  90. package/dist/federation/mq.test.d.mts +0 -2
  91. package/dist/federation/mq.test.mjs +0 -591
  92. package/dist/federation/negotiation.test.d.mts +0 -2
  93. package/dist/federation/negotiation.test.mjs +0 -18
  94. package/dist/federation/outbound-body.test.d.mts +0 -2
  95. package/dist/federation/outbound-body.test.mjs +0 -149
  96. package/dist/federation/outbound-capture.test.d.mts +0 -2
  97. package/dist/federation/outbound-capture.test.mjs +0 -394
  98. package/dist/federation/outbound-dispatch.test.d.mts +0 -2
  99. package/dist/federation/outbound-dispatch.test.mjs +0 -368
  100. package/dist/federation/outbound-document.test.d.mts +0 -2
  101. package/dist/federation/outbound-document.test.mjs +0 -171
  102. package/dist/federation/outbound-provenance.test.d.mts +0 -2
  103. package/dist/federation/outbound-provenance.test.mjs +0 -543
  104. package/dist/federation/outbound-report.test.d.mts +0 -2
  105. package/dist/federation/outbound-report.test.mjs +0 -5475
  106. package/dist/federation/outbound-workers.test.d.mts +0 -2
  107. package/dist/federation/outbound-workers.test.mjs +0 -64
  108. package/dist/federation/outbound-workflow.test.d.mts +0 -2
  109. package/dist/federation/outbound-workflow.test.mjs +0 -154
  110. package/dist/federation/outgoing-proof.test.d.mts +0 -2
  111. package/dist/federation/outgoing-proof.test.mjs +0 -933
  112. package/dist/federation/portable-actor.test.d.mts +0 -2
  113. package/dist/federation/portable-actor.test.mjs +0 -496
  114. package/dist/federation/portable-chain.test.d.mts +0 -2
  115. package/dist/federation/portable-chain.test.mjs +0 -370
  116. package/dist/federation/portable-collection.test.d.mts +0 -2
  117. package/dist/federation/portable-collection.test.mjs +0 -832
  118. package/dist/federation/portable-delivery.test.d.mts +0 -2
  119. package/dist/federation/portable-delivery.test.mjs +0 -845
  120. package/dist/federation/portable-gateway-keys.test.d.mts +0 -2
  121. package/dist/federation/portable-gateway-keys.test.mjs +0 -692
  122. package/dist/federation/portable-inbox.test.d.mts +0 -2
  123. package/dist/federation/portable-inbox.test.mjs +0 -1960
  124. package/dist/federation/portable-parse-uri.test.d.mts +0 -2
  125. package/dist/federation/portable-parse-uri.test.mjs +0 -348
  126. package/dist/federation/portable-route-activity.test.d.mts +0 -2
  127. package/dist/federation/portable-route-activity.test.mjs +0 -259
  128. package/dist/federation/portable.test.d.mts +0 -2
  129. package/dist/federation/portable.test.mjs +0 -1072
  130. package/dist/federation/retry.test.d.mts +0 -2
  131. package/dist/federation/retry.test.mjs +0 -42
  132. package/dist/federation/router.test.d.mts +0 -2
  133. package/dist/federation/router.test.mjs +0 -123
  134. package/dist/federation/send.test.d.mts +0 -2
  135. package/dist/federation/send.test.mjs +0 -1421
  136. package/dist/federation/tasks/codec.test.d.mts +0 -2
  137. package/dist/federation/tasks/codec.test.mjs +0 -302
  138. package/dist/federation/tasks/enqueue.test.d.mts +0 -2
  139. package/dist/federation/tasks/enqueue.test.mjs +0 -1095
  140. package/dist/federation/tasks/tasks.test.d.mts +0 -2
  141. package/dist/federation/tasks/tasks.test.mjs +0 -1229
  142. package/dist/federation/temporal.test.d.mts +0 -2
  143. package/dist/federation/temporal.test.mjs +0 -71
  144. package/dist/federation/webfinger.test.d.mts +0 -2
  145. package/dist/federation/webfinger.test.mjs +0 -944
  146. package/dist/http-BXbQQZDM.mjs +0 -1449
  147. package/dist/inbox-authentication-CgonVRkg.mjs +0 -198
  148. package/dist/inbox-cS97XzOD.mjs +0 -399
  149. package/dist/inbox-view-D-d0Ar6o.mjs +0 -385
  150. package/dist/key-owner-evidence-APB6NpSk.mjs +0 -108
  151. package/dist/keycache-N2opu4-3.mjs +0 -221
  152. package/dist/keys-DIJNHW-Y.mjs +0 -120
  153. package/dist/kv-DBRWVx3Q.mjs +0 -104
  154. package/dist/kv-DCHkaJ9-.mjs +0 -92
  155. package/dist/kv-cache-fgbLHGVL.mjs +0 -121
  156. package/dist/ld-BpkhkDGj.mjs +0 -1752
  157. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +0 -204
  158. package/dist/map-local-create-note-B0SeXJms.mjs +0 -214
  159. package/dist/metrics-Uqf8GomB.mjs +0 -818
  160. package/dist/middleware-DcXzz-YK.mjs +0 -9971
  161. package/dist/middleware-DgwZkvJR.mjs +0 -5
  162. package/dist/mq-eF96QxUT.mjs +0 -288
  163. package/dist/negotiation-BAKO9nih.mjs +0 -96
  164. package/dist/nodeinfo/client.test.d.mts +0 -2
  165. package/dist/nodeinfo/client.test.mjs +0 -1364
  166. package/dist/nodeinfo/handler.test.d.mts +0 -2
  167. package/dist/nodeinfo/handler.test.mjs +0 -94
  168. package/dist/nodeinfo/types.test.d.mts +0 -2
  169. package/dist/nodeinfo/types.test.mjs +0 -192
  170. package/dist/otel/exporter.test.d.mts +0 -2
  171. package/dist/otel/exporter.test.mjs +0 -887
  172. package/dist/outbound-body-CckPA5gc.mjs +0 -83
  173. package/dist/outbound-capture-DVgnRzlf.mjs +0 -184
  174. package/dist/outbound-document-BMgwLXTY.mjs +0 -179
  175. package/dist/outgoing-jsonld-4IJqPYos.mjs +0 -205
  176. package/dist/owner-BVenIFg1.mjs +0 -267
  177. package/dist/portable-collection-DIk9gpjL.mjs +0 -418
  178. package/dist/portable-key-C7pVaHNR.mjs +0 -549
  179. package/dist/portable-key-id-Ca30-hOa.mjs +0 -248
  180. package/dist/proof-BlfZ95--.mjs +0 -1420
  181. package/dist/public-audience--klBIOk1.mjs +0 -197
  182. package/dist/retry-zX5xw5e0.mjs +0 -34
  183. package/dist/router-u5O5KCQr.mjs +0 -156
  184. package/dist/secured-document-CxzZZ9nL.mjs +0 -35
  185. package/dist/send-DEGHPGFk.mjs +0 -710
  186. package/dist/sig/accept.test.d.mts +0 -2
  187. package/dist/sig/accept.test.mjs +0 -416
  188. package/dist/sig/compound-proof-discovery.test.d.mts +0 -2
  189. package/dist/sig/compound-proof-discovery.test.mjs +0 -331
  190. package/dist/sig/compound-proof-producer.test.d.mts +0 -2
  191. package/dist/sig/compound-proof-producer.test.mjs +0 -107
  192. package/dist/sig/compound-proof-verification.test.d.mts +0 -2
  193. package/dist/sig/compound-proof-verification.test.mjs +0 -1017
  194. package/dist/sig/compound-proof.test.d.mts +0 -2
  195. package/dist/sig/compound-proof.test.mjs +0 -411
  196. package/dist/sig/http.test.d.mts +0 -2
  197. package/dist/sig/http.test.mjs +0 -3328
  198. package/dist/sig/key-owner-evidence.test.d.mts +0 -2
  199. package/dist/sig/key-owner-evidence.test.mjs +0 -100
  200. package/dist/sig/key.test.d.mts +0 -2
  201. package/dist/sig/key.test.mjs +0 -1250
  202. package/dist/sig/ld.test.d.mts +0 -2
  203. package/dist/sig/ld.test.mjs +0 -1044
  204. package/dist/sig/mitra-receive-interop.test.d.mts +0 -2
  205. package/dist/sig/mitra-receive-interop.test.mjs +0 -260
  206. package/dist/sig/mitra-send-interop.test.d.mts +0 -2
  207. package/dist/sig/mitra-send-interop.test.mjs +0 -461
  208. package/dist/sig/owner.test.d.mts +0 -2
  209. package/dist/sig/owner.test.mjs +0 -202
  210. package/dist/sig/portable-collection.test.d.mts +0 -2
  211. package/dist/sig/portable-collection.test.mjs +0 -697
  212. package/dist/sig/portable-interop.test.d.mts +0 -2
  213. package/dist/sig/portable-interop.test.mjs +0 -156
  214. package/dist/sig/portable-key-id.test.d.mts +0 -2
  215. package/dist/sig/portable-key-id.test.mjs +0 -67
  216. package/dist/sig/portable-key.test.d.mts +0 -2
  217. package/dist/sig/portable-key.test.mjs +0 -1438
  218. package/dist/sig/proof.test.d.mts +0 -2
  219. package/dist/sig/proof.test.mjs +0 -2638
  220. package/dist/sig/tootik-request-interop.test.d.mts +0 -2
  221. package/dist/sig/tootik-request-interop.test.mjs +0 -190
  222. package/dist/sig/tootik-send-interop.test.d.mts +0 -2
  223. package/dist/sig/tootik-send-interop.test.mjs +0 -331
  224. package/dist/sig/verification.test.d.mts +0 -2
  225. package/dist/sig/verification.test.mjs +0 -310
  226. package/dist/std__assert-DvMDRPes.mjs +0 -8
  227. package/dist/tasks-BCUmQbbz.mjs +0 -77
  228. package/dist/temporal-B4oQ8HpW.mjs +0 -95
  229. package/dist/testing/context.test.d.mts +0 -2
  230. package/dist/testing/context.test.mjs +0 -19
  231. package/dist/testing/kv.test.d.mts +0 -2
  232. package/dist/testing/kv.test.mjs +0 -101
  233. package/dist/testing/mod.d.mts +0 -6099
  234. package/dist/testing/mod.mjs +0 -9
  235. package/dist/testing-vrnD5Uaa.mjs +0 -8
  236. package/dist/types-DE_LV1JB.mjs +0 -46
  237. package/dist/utils/docloader.test.d.mts +0 -2
  238. package/dist/utils/docloader.test.mjs +0 -1076
  239. package/dist/utils/kv-cache.test.d.mts +0 -2
  240. package/dist/utils/kv-cache.test.mjs +0 -261
  241. package/dist/verification-C3954hQh.mjs +0 -5
  242. package/dist/verification-Dpfcw8ml.mjs +0 -105
  243. package/dist/vocab/cjs.test.d.mts +0 -2
  244. package/dist/vocab/cjs.test.mjs +0 -27
@@ -1,1420 +0,0 @@
1
- import { Temporal } from "temporal-polyfill";
2
- import "urlpattern-polyfill";
3
- globalThis.addEventListener = () => {};
4
- import { i as getPortableDid, l as isPortableId } from "./portable-key-id-Ca30-hOa.mjs";
5
- import { a as verificationObservation, i as triedKey, n as observeCheck, t as observeAttempt } from "./verification-Dpfcw8ml.mjs";
6
- import { n as version, t as name } from "./deno-C50ikGBU.mjs";
7
- import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-Uqf8GomB.mjs";
8
- import { C as fetchKey, D as validateCryptoKey, b as bypassKeyCacheReads, c as getNormalizationContextLoader } from "./ld-BpkhkDGj.mjs";
9
- import { n as preloadedOnlyDocumentLoader } from "./public-audience--klBIOk1.mjs";
10
- import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-4IJqPYos.mjs";
11
- import { getLogger } from "@logtape/logtape";
12
- import { Activity, DataIntegrityProof, Multikey, getTypeId } from "@fedify/vocab";
13
- import { SpanStatusCode, trace } from "@opentelemetry/api";
14
- import { encodeMultibase, formatIri, fromCompatibleEf61Id, getDocumentLoader, getFe34Origin, isTransientFetchError, parseGatewayUrl, parseIri } from "@fedify/vocab-runtime";
15
- import { encodeHex } from "byte-encodings/hex";
16
- import { getPortableActorGateways } from "@fedify/vocab-runtime/internal/jsonld-cache";
17
- import { isPlainJsonTree, retainSignedRepresentation } from "@fedify/vocab-runtime/internal/signed-representation";
18
- import jsonld from "@fedify/vocab-runtime/jsonld";
19
- import serialize from "json-canon";
20
- //#region src/sig/proof.ts
21
- /**
22
- * Known Object Integrity Proof `cryptosuite` values, used to keep
23
- * `object_integrity_proofs.cryptosuite` on a bounded set of spec-defined
24
- * string values. Fedify currently signs and verifies only
25
- * `eddsa-jcs-2022`; other values come in only from external proofs and are
26
- * dropped from the metric attribute to avoid attacker-controlled
27
- * cardinality.
28
- */
29
- const OIP_KNOWN_CRYPTOSUITES = /* @__PURE__ */ new Set(["eddsa-jcs-2022"]);
30
- const logger = getLogger([
31
- "fedify",
32
- "sig",
33
- "proof"
34
- ]);
35
- const SECURITY_NAMESPACE = "https://w3id.org/security#";
36
- const SECURITY_PROOF = `${SECURITY_NAMESPACE}proof`;
37
- const SECURITY_PROOF_VALUE = `${SECURITY_NAMESPACE}proofValue`;
38
- const DATA_INTEGRITY_PROOF = `${SECURITY_NAMESPACE}DataIntegrityProof`;
39
- const SECURITY_VERIFICATION_METHOD = `${SECURITY_NAMESPACE}verificationMethod`;
40
- const SECURITY_EXPIRATION = `${SECURITY_NAMESPACE}expiration`;
41
- const SECURITY_DOMAIN = `${SECURITY_NAMESPACE}domain`;
42
- const SECURITY_CHALLENGE = `${SECURITY_NAMESPACE}challenge`;
43
- const SECURITY_NONCE = `${SECURITY_NAMESPACE}nonce`;
44
- const SECURITY_PREVIOUS_PROOF = `${SECURITY_NAMESPACE}previousProof`;
45
- /**
46
- * Checks if the given JSON-LD document has a DataIntegrityProof-like object,
47
- * without fully deserializing it into vocabulary classes.
48
- * @param jsonLd The JSON-LD document to check.
49
- * @returns `true` if the document has a proof-like object; `false` otherwise.
50
- * @since 2.2.0
51
- */
52
- function hasProofLike(jsonLd) {
53
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
54
- const record = jsonLd;
55
- const proof = record.proof ?? record["https://w3id.org/security#proof"];
56
- const getField = (source, compact, expanded) => source[compact] ?? source[expanded];
57
- const isReference = (value) => {
58
- if (typeof value === "string") return true;
59
- if (Array.isArray(value)) return value.some(isReference);
60
- return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string" || "@value" in value && typeof value["@value"] === "string");
61
- };
62
- const hasType = (value) => {
63
- if (typeof value === "string") return value === "DataIntegrityProof" || value === "https://w3id.org/security#DataIntegrityProof";
64
- if (Array.isArray(value)) return value.some(hasType);
65
- return false;
66
- };
67
- const isProofLike = (value) => {
68
- if (typeof value !== "object" || value == null) return false;
69
- const proofRecord = value;
70
- return hasType(proofRecord.type ?? proofRecord["@type"]) && isReference(getField(proofRecord, "verificationMethod", "https://w3id.org/security#verificationMethod")) && isReference(getField(proofRecord, "proofPurpose", "https://w3id.org/security#proofPurpose")) && isReference(getField(proofRecord, "proofValue", "https://w3id.org/security#proofValue"));
71
- };
72
- return Array.isArray(proof) ? proof.some(isProofLike) : isProofLike(proof);
73
- }
74
- function isJsonMap(value) {
75
- return typeof value === "object" && value != null && !Array.isArray(value);
76
- }
77
- /**
78
- * Assembles the secured JSON document from the bytes that were just signed.
79
- *
80
- * The document is not re-derived from the vocabulary object: it is
81
- * `compactMsg`, the value whose JCS form was hashed, with the serialized
82
- * proof added. Every part of it is then checked against the digests and the
83
- * signature that {@link createProofInternal} produced, so a document that is
84
- * returned verifies under the map-local compound-proof profile by
85
- * construction. Anything that does not check out yields `null`, and the
86
- * caller simply does not retain a representation.
87
- */
88
- async function captureSecuredDocument(proof, compactMsg, msgCanon, proofCanon, proofValue, contextLoader) {
89
- if (!isJsonMap(compactMsg)) return null;
90
- const documentContext = compactMsg["@context"];
91
- if (documentContext == null) return null;
92
- if (globalThis.Object.hasOwn(compactMsg, "proof")) return null;
93
- try {
94
- const proofJson = await proof.toJsonLd({
95
- format: "compact",
96
- contextLoader,
97
- context: documentContext
98
- });
99
- if (!isJsonMap(proofJson)) return null;
100
- const { proofValue: serializedProofValue, ...proofConfiguration } = proofJson;
101
- if (serializedProofValue !== proofValue) return null;
102
- if (serialize(proofConfiguration) !== proofCanon) return null;
103
- const securedDocument = {
104
- ...structuredClone(compactMsg),
105
- proof: structuredClone(proofJson)
106
- };
107
- const { proof: _embeddedProof, ...unsecuredDocument } = securedDocument;
108
- if (serialize(unsecuredDocument) !== msgCanon) return null;
109
- if (!isPlainJsonTree(securedDocument)) return null;
110
- return securedDocument;
111
- } catch (error) {
112
- logger.debug("Failed to capture the secured JSON document for a created proof; the signed object will not preserve its representation when it is embedded in another object.\n{error}", { error });
113
- return null;
114
- }
115
- }
116
- async function createProofInternal(object, privateKey, keyId, { contextLoader, context, created } = {}, capture = false) {
117
- validateCryptoKey(privateKey, "private");
118
- if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
119
- let compactMsg = await object.clone({ proofs: [] }).toJsonLd({
120
- format: "compact",
121
- contextLoader,
122
- context
123
- });
124
- compactMsg = await normalizeOutgoingActivityJsonLd(compactMsg, contextLoader, { preserveNestedSecuredDocuments: true });
125
- const msgCanon = serialize(compactMsg);
126
- const encoder = new TextEncoder();
127
- const msgBytes = encoder.encode(msgCanon);
128
- const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
129
- created ??= Temporal.Now.instant();
130
- const proofCanon = serialize({
131
- "@context": compactMsg["@context"],
132
- type: "DataIntegrityProof",
133
- cryptosuite: "eddsa-jcs-2022",
134
- verificationMethod: keyId.href,
135
- proofPurpose: "assertionMethod",
136
- created: created.toString()
137
- });
138
- const proofBytes = encoder.encode(proofCanon);
139
- const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
140
- const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
141
- digest.set(new Uint8Array(proofDigest), 0);
142
- digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
143
- const sig = new Uint8Array(await crypto.subtle.sign("Ed25519", privateKey, digest));
144
- const proof = new DataIntegrityProof({
145
- cryptosuite: "eddsa-jcs-2022",
146
- verificationMethod: keyId,
147
- proofPurpose: "assertionMethod",
148
- created,
149
- proofValue: sig
150
- });
151
- return {
152
- proof,
153
- securedDocument: capture ? await captureSecuredDocument(proof, compactMsg, msgCanon, proofCanon, new TextDecoder().decode(encodeMultibase("base58btc", sig)), contextLoader) : null
154
- };
155
- }
156
- /**
157
- * Creates a proof for the given object.
158
- * @param object The object to create a proof for.
159
- * @param privateKey The private key to sign the proof with.
160
- * @param keyId The key ID to use in the proof. It will be used by the verifier.
161
- * @param options Additional options. See also {@link CreateProofOptions}.
162
- * @returns The created proof.
163
- * @throws {TypeError} If the private key is invalid or unsupported.
164
- * @since 0.10.0
165
- */
166
- async function createProof(object, privateKey, keyId, options = {}) {
167
- const { proof } = await createProofInternal(object, privateKey, keyId, options);
168
- return proof;
169
- }
170
- /**
171
- * Signs the given object with the private key and returns the signed object.
172
- * @param object The object to create a proof for.
173
- * @param privateKey The private key to sign the proof with.
174
- * @param keyId The key ID to use in the proof. It will be used by the verifier.
175
- * @param options Additional options. See also {@link SignObjectOptions}.
176
- * @returns The signed object.
177
- * @throws {TypeError} If the private key is invalid or unsupported.
178
- * @since 0.10.0
179
- */
180
- async function signObject(object, privateKey, keyId, options = {}) {
181
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
182
- try {
183
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
184
- const existingProofs = [];
185
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
186
- const { proof, securedDocument } = await createProofInternal(object, privateKey, keyId, options, existingProofs.length < 1);
187
- if (span.isRecording()) {
188
- if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
189
- if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
190
- if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
191
- }
192
- const signed = object.clone({ proofs: [...existingProofs, proof] });
193
- if (securedDocument != null) retainSignedRepresentation(signed, securedDocument);
194
- else if (existingProofs.length > 0) logger.debug("The object {objectId} already had {proofCount} proof(s), so its signed representation is not retained for embedding; the map-local compound-proof profile accepts exactly one direct proof per map.", {
195
- objectId: object.id?.href,
196
- proofCount: existingProofs.length
197
- });
198
- return signed;
199
- } catch (error) {
200
- span.setStatus({
201
- code: SpanStatusCode.ERROR,
202
- message: String(error)
203
- });
204
- throw error;
205
- } finally {
206
- span.end();
207
- }
208
- });
209
- }
210
- /**
211
- * Verifies the given proof for the object.
212
- * @param jsonLd The JSON-LD object to verify the proof for. Its proof
213
- * properties are excluded from the message, but matching proof
214
- * occurrences are used to authenticate the received proof
215
- * configuration.
216
- * @param proof The proof to verify.
217
- * @param options Additional options. See also {@link VerifyProofOptions}.
218
- * @returns The public key that was used to sign the proof, or `null` if the
219
- * proof is invalid.
220
- * @since 0.10.0
221
- * @since 2.4.0 Matching proof configurations are authenticated.
222
- */
223
- async function verifyProof(jsonLd, proof, options = {}) {
224
- return await verifyProofWithMessageDigestCache(jsonLd, proof, options);
225
- }
226
- /**
227
- * Verifies the one direct literal proof on a map-local secured document.
228
- *
229
- * Unlike {@link verifyProof}, this removes only the literal `proof` member
230
- * from the message digest. JSON-LD aliases remain part of the signed input,
231
- * and the document's received `@context` is not replaced by the proof
232
- * configuration context.
233
- *
234
- * @internal
235
- */
236
- async function verifyMapLocalProof(jsonLd, options = {}) {
237
- if (!isJsonLdNode(jsonLd) || !globalThis.Object.hasOwn(jsonLd, "proof") || !isJsonLdNode(jsonLd.proof)) return null;
238
- const rawProof = jsonLd.proof;
239
- const previousChecks = options[verificationObservation]?.attempt?.checks.length;
240
- const malformed = () => observeCheck(options, {
241
- mechanism: "objectIntegrity",
242
- proofId: typeof rawProof.id === "string" ? rawProof.id : typeof rawProof["@id"] === "string" ? rawProof["@id"] : null,
243
- proofIndex: previousChecks ?? null
244
- }, getDeclaredProofKeyId(rawProof), () => Promise.resolve(null));
245
- const proofContextLoader = getNormalizationContextLoader(preloadedOnlyDocumentLoader);
246
- try {
247
- const [candidate] = await parseRawProofCandidates(jsonLd, [jsonLd.proof], options, proofContextLoader);
248
- if (candidate.proof == null) return await malformed();
249
- return await verifyProofWithMessageDigestCache(jsonLd, candidate.proof, options, {
250
- proofContextLoader,
251
- proofPropertyMode: "literal"
252
- }, candidate);
253
- } catch {
254
- if (previousChecks != null && options[verificationObservation]?.attempt?.checks.length === previousChecks) return await malformed();
255
- return null;
256
- }
257
- }
258
- function getDeclaredProofKeyId(value, propertyNames = ["verificationMethod", "https://w3id.org/security#verificationMethod"]) {
259
- if (!isJsonLdNode(value)) return null;
260
- const method = Array.from(propertyNames, (name) => value[name]).find((v) => v != null);
261
- const candidate = Array.isArray(method) ? method[0] : method;
262
- if (typeof candidate === "string") return candidate;
263
- return isJsonLdNode(candidate) && typeof candidate["@id"] === "string" ? candidate["@id"] : null;
264
- }
265
- async function verifyProofWithMessageDigestCache(jsonLd, proof, options, messageDigestCache = {}, rawProofCandidate, keyIdBoundByCaller = false) {
266
- if (options[verificationObservation] == null) return await verifyProofWithMessageDigestCache(jsonLd, proof, {
267
- ...options,
268
- [verificationObservation]: {
269
- attempts: [],
270
- attempt: { checks: [] },
271
- captureRawKeyIds: false
272
- }
273
- }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
274
- if (options[verificationObservation]?.attempt != null && options[verificationObservation]?.check == null) return await observeCheck(options, {
275
- mechanism: "objectIntegrity",
276
- proofId: proof.id?.href ?? null,
277
- proofIndex: options[verificationObservation].attempt.checks.length
278
- }, rawProofCandidate?.declaredKeyId ?? getDeclaredProofKeyId(rawProofCandidate?.value) ?? proof.verificationMethodId?.href ?? null, (observation) => verifyProofWithMessageDigestCache(jsonLd, proof, {
279
- ...options,
280
- [verificationObservation]: observation
281
- }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller));
282
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
283
- const start = performance.now();
284
- let verified = false;
285
- let threw = false;
286
- const cryptosuite = proof.cryptosuite != null && OIP_KNOWN_CRYPTOSUITES.has(proof.cryptosuite) ? proof.cryptosuite : void 0;
287
- if (span.isRecording()) {
288
- if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
289
- if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
290
- if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
291
- }
292
- try {
293
- const key = await verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
294
- if (key == null) {
295
- span.setStatus({ code: SpanStatusCode.ERROR });
296
- span.setAttribute("activitypub.verification.failure_reason", options[verificationObservation]?.check?.reason?.type ?? "invalidSignature");
297
- } else verified = true;
298
- return key;
299
- } catch (error) {
300
- threw = true;
301
- span.setStatus({
302
- code: SpanStatusCode.ERROR,
303
- message: String(error)
304
- });
305
- throw error;
306
- } finally {
307
- const classified = threw ? "error" : verified ? "verified" : "rejected";
308
- getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(getDurationMs(start), "object_integrity", classified, {
309
- cryptosuite,
310
- verificationFailureReason: verified || threw ? void 0 : options[verificationObservation]?.check?.reason?.type ?? "invalidSignature"
311
- });
312
- span.end();
313
- }
314
- });
315
- }
316
- function expandContextPropertyIri(activeContext, key) {
317
- const termId = jsonld.getContextValue(activeContext, key, "@id");
318
- if (termId != null) return termId;
319
- const colon = key.indexOf(":");
320
- if (colon < 1) return key;
321
- const prefix = key.substring(0, colon);
322
- const suffix = key.substring(colon + 1);
323
- if (prefix === "_" || suffix.startsWith("//")) return key;
324
- const mapping = jsonld.getContextValue(activeContext, prefix);
325
- if (typeof mapping === "object" && mapping != null && mapping._prefix === true && typeof mapping["@id"] === "string") return mapping["@id"] + suffix;
326
- return key;
327
- }
328
- async function getJsonLdPropertyNames(jsonLd, propertyIri, defaults, documentLoader = preloadedOnlyDocumentLoader, inheritedContext, rejectOnContextError = false, contextState) {
329
- const names = new Set(defaults);
330
- const context = jsonLd["@context"] ?? inheritedContext;
331
- if (context == null && contextState?.initial == null) return names;
332
- try {
333
- const options = { documentLoader };
334
- let activeContext = contextState?.initial ?? await jsonld.processContext(null, null, options);
335
- if (contextState?.scoped != null) activeContext = await jsonld.processContext(activeContext, contextState.scoped, options);
336
- if (context != null) activeContext = await jsonld.processContext(activeContext, context, options);
337
- const typeScopedContext = activeContext;
338
- for (const key of globalThis.Object.keys(jsonLd).sort()) {
339
- if (key !== "@type" && expandContextPropertyIri(activeContext, key) !== "@type") continue;
340
- const value = jsonLd[key];
341
- const types = Array.isArray(value) ? value.slice().sort() : [value];
342
- for (const type of types) {
343
- if (typeof type !== "string") continue;
344
- const scopedContext = jsonld.getContextValue(typeScopedContext, type, "@context");
345
- if (scopedContext != null) activeContext = await jsonld.processContext(activeContext, scopedContext, options);
346
- }
347
- }
348
- if (contextState != null) contextState.active = activeContext;
349
- for (const key of globalThis.Object.keys(jsonLd)) if (expandContextPropertyIri(activeContext, key) === propertyIri) names.add(key);
350
- } catch {
351
- if (rejectOnContextError) return null;
352
- }
353
- return names;
354
- }
355
- async function getProofPropertyNames(jsonLd, documentLoader = preloadedOnlyDocumentLoader) {
356
- return await getJsonLdPropertyNames(jsonLd, SECURITY_PROOF, ["proof", SECURITY_PROOF], documentLoader) ?? /* @__PURE__ */ new Set(["proof", SECURITY_PROOF]);
357
- }
358
- async function createProofMessageDigests(jsonLd, proofContextLoader, context, proofPropertyMode = "jsonLd") {
359
- const msg = { ...jsonLd };
360
- if (proofPropertyMode === "literal") delete msg.proof;
361
- else for (const property of await getProofPropertyNames(msg, proofContextLoader)) delete msg[property];
362
- if (proofPropertyMode === "jsonLd" && context != null) msg["@context"] = structuredClone(context);
363
- const encoder = new TextEncoder();
364
- const digest = async (value) => {
365
- const bytes = encoder.encode(serialize(value));
366
- return await crypto.subtle.digest("SHA-256", bytes);
367
- };
368
- const onWire = await digest(msg);
369
- let normalizedPromise;
370
- return {
371
- onWire,
372
- normalized() {
373
- normalizedPromise ??= (async () => {
374
- const normalized = await normalizeOutgoingActivityJsonLd(msg, preloadedOnlyDocumentLoader);
375
- return normalized === msg ? null : await digest(normalized);
376
- })();
377
- return normalizedPromise;
378
- }
379
- };
380
- }
381
- function contextValues(context) {
382
- return Array.isArray(context) ? context : [context];
383
- }
384
- function equalJsonValues(left, right) {
385
- try {
386
- return serialize(left) === serialize(right);
387
- } catch {
388
- return false;
389
- }
390
- }
391
- function contextStartsWith(documentContext, proofContext) {
392
- if (documentContext == null) return false;
393
- const documentValues = contextValues(documentContext);
394
- const proofValues = contextValues(proofContext);
395
- return proofValues.length <= documentValues.length && proofValues.every((value, index) => equalJsonValues(value, documentValues[index]));
396
- }
397
- function appendProofValues(values, value) {
398
- if (Array.isArray(value)) for (const item of value) appendProofValues(values, item);
399
- else if (isJsonLdNode(value) && Array.isArray(value["@graph"])) for (const item of value["@graph"]) appendProofValues(values, item);
400
- else values.push(value);
401
- }
402
- async function getRawProofValues(jsonLd, documentLoader) {
403
- const propertyNames = await getProofPropertyNames(jsonLd, documentLoader);
404
- const values = [];
405
- for (const [property, value] of globalThis.Object.entries(jsonLd)) if (propertyNames.has(property)) appendProofValues(values, value);
406
- return values;
407
- }
408
- function sameBytes(left, right) {
409
- if (left == null || right == null) return left === right;
410
- return left.length === right.length && left.every((value, index) => value === right[index]);
411
- }
412
- function sameProof(left, right) {
413
- return left.cryptosuite === right.cryptosuite && left.verificationMethodId?.href === right.verificationMethodId?.href && left.proofPurpose === right.proofPurpose && sameBytes(left.proofValue, right.proofValue) && left.created?.toString() === right.created?.toString();
414
- }
415
- function recordProofContexts(documentLoader) {
416
- const documents = /* @__PURE__ */ new Map();
417
- return {
418
- loader: async (url, options) => {
419
- const document = await documentLoader(url, options);
420
- documents.set(url, document);
421
- return document;
422
- },
423
- replay: (url, options) => {
424
- const document = documents.get(url);
425
- return document == null ? preloadedOnlyDocumentLoader(url, options) : Promise.resolve(document);
426
- }
427
- };
428
- }
429
- async function getAliasedDeclaredProofKeyId(value, inheritedContext, contextLoader) {
430
- if (!isJsonLdNode(value)) return null;
431
- const contextState = {};
432
- const names = await getJsonLdPropertyNames(value, "https://w3id.org/security#verificationMethod", ["verificationMethod", "https://w3id.org/security#verificationMethod"], contextLoader, inheritedContext, false, contextState);
433
- const methodName = Array.from(names ?? []).find((name) => value[name] != null);
434
- const method = methodName == null ? void 0 : value[methodName];
435
- const candidate = Array.isArray(method) ? method[0] : method;
436
- if (typeof candidate === "string") return candidate;
437
- if (!isJsonLdNode(candidate)) return null;
438
- const idNames = await getJsonLdPropertyNames(candidate, "@id", ["@id"], contextLoader, void 0, false, {
439
- initial: contextState.active,
440
- scoped: contextState.active == null || methodName == null ? void 0 : jsonld.getContextValue(contextState.active, methodName, "@context")
441
- });
442
- for (const name of idNames ?? []) if (typeof candidate[name] === "string") return candidate[name];
443
- return null;
444
- }
445
- function normalizeDocumentUrl(url) {
446
- try {
447
- return formatIri(parseIri(url));
448
- } catch {
449
- return URL.canParse(url) ? new URL(url).href : url;
450
- }
451
- }
452
- function getRawProofReference(value) {
453
- const node = Array.isArray(value) && value.length === 1 ? value[0] : value;
454
- if (typeof node === "string") return normalizeDocumentUrl(node);
455
- if (!isJsonLdNode(node)) return void 0;
456
- const id = node["@id"] ?? node.id;
457
- return typeof id === "string" ? normalizeDocumentUrl(id) : void 0;
458
- }
459
- async function parseRawProofCandidates(jsonLd, values, options, documentLoader) {
460
- const candidates = [];
461
- for (const value of values) {
462
- let parsed = null;
463
- const contexts = options[verificationObservation] != null && options[verificationObservation]?.captureRawKeyIds !== false ? recordProofContexts(documentLoader) : void 0;
464
- if (isJsonLdNode(value)) {
465
- const proofJsonLd = value["@context"] == null && jsonLd["@context"] != null ? {
466
- "@context": jsonLd["@context"],
467
- ...value
468
- } : value;
469
- try {
470
- parsed = await DataIntegrityProof.fromJsonLd(proofJsonLd, {
471
- ...options,
472
- contextLoader: contexts?.loader ?? documentLoader
473
- });
474
- } catch {}
475
- }
476
- candidates.push({
477
- value,
478
- proof: parsed,
479
- reference: getRawProofReference(value) ?? parsed?.id?.href,
480
- declaredKeyId: contexts == null ? void 0 : await getAliasedDeclaredProofKeyId(value, jsonLd["@context"], contexts.replay)
481
- });
482
- }
483
- return candidates;
484
- }
485
- async function findRawProofCandidate(jsonLd, proof, options, documentLoader) {
486
- const candidates = await parseRawProofCandidates(jsonLd, await getRawProofValues(jsonLd, documentLoader), options, documentLoader);
487
- const matches = [];
488
- for (const candidate of candidates) if (candidate.proof != null && sameProof(candidate.proof, proof)) matches.push(candidate);
489
- if (matches.length < 1) return void 0;
490
- const first = matches[0];
491
- const configurations = await Promise.all(matches.map((candidate) => normalizeProofConfiguration(candidate.value, jsonLd["@context"], documentLoader)));
492
- const firstConfiguration = configurations[0];
493
- return firstConfiguration != null && configurations.every((configuration) => configuration != null && equalJsonValues(configuration.value, firstConfiguration.value)) ? first : null;
494
- }
495
- function takeRawProofCandidate(pool, proof) {
496
- for (let index = 0; index < pool.candidates.length; index++) {
497
- if (pool.used.has(index)) continue;
498
- const candidate = pool.candidates[index];
499
- if (candidate.proof != null && sameProof(candidate.proof, proof)) {
500
- pool.used.add(index);
501
- return candidate;
502
- }
503
- }
504
- }
505
- const STANDARD_COMPACT_PROOF_PROPERTIES = /* @__PURE__ */ new Set([
506
- "@context",
507
- "type",
508
- "cryptosuite",
509
- "verificationMethod",
510
- "proofPurpose",
511
- "proofValue",
512
- "created"
513
- ]);
514
- const STANDARD_EXPANDED_PROOF_PROPERTIES = /* @__PURE__ */ new Set([
515
- "@context",
516
- "@type",
517
- `${SECURITY_NAMESPACE}cryptosuite`,
518
- SECURITY_VERIFICATION_METHOD,
519
- `${SECURITY_NAMESPACE}proofPurpose`,
520
- `${SECURITY_NAMESPACE}proofValue`,
521
- "http://purl.org/dc/terms/created"
522
- ]);
523
- function hasAdditionalProofOptions(value) {
524
- const node = Array.isArray(value) && value.length === 1 ? value[0] : value;
525
- return isJsonLdNode(node) && globalThis.Object.keys(node).some((property) => !STANDARD_COMPACT_PROOF_PROPERTIES.has(property) && !STANDARD_EXPANDED_PROOF_PROPERTIES.has(property));
526
- }
527
- function isExpandedJsonLdNode(value) {
528
- const properties = globalThis.Object.keys(value).filter((key) => !key.startsWith("@"));
529
- return properties.length > 0 && properties.every((property) => URL.canParse(property));
530
- }
531
- async function normalizeProofConfiguration(rawProof, documentContext, documentLoader) {
532
- let node = Array.isArray(rawProof) && rawProof.length === 1 ? rawProof[0] : rawProof;
533
- if (!isJsonLdNode(node)) return null;
534
- if (isExpandedJsonLdNode(node)) {
535
- if (documentContext == null) return null;
536
- node = await jsonld.compact(node, documentContext, { documentLoader });
537
- if (!isJsonLdNode(node)) return null;
538
- } else node = structuredClone(node);
539
- const receivedContext = node["@context"];
540
- if (receivedContext != null && !contextStartsWith(documentContext, receivedContext)) return null;
541
- const context = receivedContext ?? documentContext;
542
- if (context != null) node["@context"] = structuredClone(context);
543
- const proofValueProperties = await getJsonLdPropertyNames(node, SECURITY_PROOF_VALUE, ["proofValue", SECURITY_PROOF_VALUE], documentLoader, context) ?? /* @__PURE__ */ new Set(["proofValue", SECURITY_PROOF_VALUE]);
544
- for (const property of proofValueProperties) delete node[property];
545
- return {
546
- value: node,
547
- context
548
- };
549
- }
550
- async function createProofConfiguration(jsonLd, proof, options, documentLoader, rawProofCandidate) {
551
- let rawProof;
552
- if (rawProofCandidate == null) {
553
- const match = await findRawProofCandidate(jsonLd, proof, options, documentLoader);
554
- if (match === null) return null;
555
- rawProof = match?.value;
556
- } else rawProof = rawProofCandidate.value;
557
- if (rawProof == null) {
558
- const serializedProof = await proof.toJsonLd();
559
- if (hasAdditionalProofOptions(serializedProof)) rawProof = serializedProof;
560
- }
561
- if (rawProof != null) return await normalizeProofConfiguration(rawProof, jsonLd["@context"], documentLoader);
562
- const context = jsonLd["@context"];
563
- return {
564
- value: {
565
- ...context == null ? {} : { "@context": context },
566
- type: "DataIntegrityProof",
567
- cryptosuite: proof.cryptosuite,
568
- verificationMethod: proof.verificationMethodId.href,
569
- proofPurpose: proof.proofPurpose,
570
- created: proof.created.toString()
571
- },
572
- context
573
- };
574
- }
575
- const KNOWN_PROOF_CONFIGURATION_PROPERTIES = /* @__PURE__ */ new Set([
576
- "@context",
577
- "@id",
578
- "@type",
579
- "id",
580
- "type",
581
- "cryptosuite",
582
- `${SECURITY_NAMESPACE}cryptosuite`,
583
- "verificationMethod",
584
- SECURITY_VERIFICATION_METHOD,
585
- "proofPurpose",
586
- `${SECURITY_NAMESPACE}proofPurpose`,
587
- "created",
588
- "http://purl.org/dc/terms/created",
589
- "expires",
590
- SECURITY_EXPIRATION,
591
- "domain",
592
- SECURITY_DOMAIN,
593
- "challenge",
594
- SECURITY_CHALLENGE,
595
- "nonce",
596
- SECURITY_NONCE,
597
- "previousProof",
598
- SECURITY_PREVIOUS_PROOF
599
- ]);
600
- async function getProofOption(proofConfig, propertyIri, defaults, documentLoader) {
601
- let names = await getJsonLdPropertyNames(proofConfig, propertyIri, defaults, documentLoader, proofConfig["@context"], true);
602
- if (names == null) {
603
- if (globalThis.Object.keys(proofConfig).some((property) => !KNOWN_PROOF_CONFIGURATION_PROPERTIES.has(property))) return null;
604
- names = new Set(defaults);
605
- }
606
- const present = globalThis.Object.keys(proofConfig).filter((property) => names.has(property));
607
- if (present.length > 1) return null;
608
- return present.length < 1 ? { present: false } : {
609
- present: true,
610
- value: proofConfig[present[0]]
611
- };
612
- }
613
- function parseStringSet(value) {
614
- if (typeof value === "string") return /* @__PURE__ */ new Set([value]);
615
- if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) return null;
616
- return new Set(value);
617
- }
618
- function equalStringSets(left, right) {
619
- return left.size === right.size && [...left].every((value) => right.has(value));
620
- }
621
- async function hasValidProofOptions(proofConfig, options, documentLoader) {
622
- const expires = await getProofOption(proofConfig, SECURITY_EXPIRATION, ["expires", SECURITY_EXPIRATION], documentLoader);
623
- if (expires == null) return null;
624
- let expiration;
625
- if (expires.present) {
626
- if (typeof expires.value !== "string") return null;
627
- try {
628
- expiration = Temporal.Instant.from(expires.value);
629
- } catch {
630
- return null;
631
- }
632
- if (Temporal.Instant.compare(Temporal.Now.instant(), expiration) >= 0) return null;
633
- }
634
- const domain = await getProofOption(proofConfig, SECURITY_DOMAIN, ["domain", SECURITY_DOMAIN], documentLoader);
635
- if (domain == null) return null;
636
- const proofDomains = domain.present ? parseStringSet(domain.value) : null;
637
- if (domain.present && proofDomains == null) return null;
638
- if (options.domain != null) {
639
- const expectedDomains = parseStringSet(options.domain);
640
- if (expectedDomains == null || proofDomains == null || !equalStringSets(proofDomains, expectedDomains)) return null;
641
- }
642
- const challenge = await getProofOption(proofConfig, SECURITY_CHALLENGE, ["challenge", SECURITY_CHALLENGE], documentLoader);
643
- if (challenge == null || challenge.present && typeof challenge.value !== "string" || options.challenge != null && (!challenge.present || challenge.value !== options.challenge)) return null;
644
- const nonce = await getProofOption(proofConfig, SECURITY_NONCE, ["nonce", SECURITY_NONCE], documentLoader);
645
- if (nonce == null || nonce.present && typeof nonce.value !== "string") return null;
646
- const previousProof = await getProofOption(proofConfig, SECURITY_PREVIOUS_PROOF, ["previousProof", SECURITY_PREVIOUS_PROOF], documentLoader);
647
- if (previousProof == null || previousProof.present && typeof previousProof.value !== "string" && (!Array.isArray(previousProof.value) || previousProof.value.some((item) => typeof item !== "string"))) return null;
648
- return { expires: expiration };
649
- }
650
- async function verifyProofInternal(jsonLd, proof, options, messageDigestCache, rawProofCandidate, keyIdBoundByCaller = false) {
651
- if (!isJsonLdNode(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
652
- const proofContextLoader = messageDigestCache.proofContextLoader ?? preloadedOnlyDocumentLoader;
653
- const proofConfiguration = await createProofConfiguration(jsonLd, proof, options, proofContextLoader, rawProofCandidate);
654
- if (proofConfiguration == null) return null;
655
- const validProofOptions = await hasValidProofOptions(proofConfiguration.value, options, proofContextLoader);
656
- if (validProofOptions == null) return null;
657
- const { expires } = validProofOptions;
658
- if (expires != null && (messageDigestCache.expires == null || Temporal.Instant.compare(expires, messageDigestCache.expires) < 0)) messageDigestCache.expires = expires;
659
- const publicKeyPromise = measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => fetchKey(proof.verificationMethodId, Multikey, {
660
- ...options,
661
- keyIdBoundByCaller
662
- }));
663
- const proofBytes = new TextEncoder().encode(serialize(proofConfiguration.value));
664
- const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
665
- let fetchedKey;
666
- try {
667
- fetchedKey = await publicKeyPromise;
668
- } catch (error) {
669
- logger.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
670
- proof,
671
- keyId: proof.verificationMethodId.href,
672
- error
673
- });
674
- const check = options[verificationObservation]?.check;
675
- if (check != null && check.reason == null) check.reason = {
676
- type: "keyFetchError",
677
- keyId: new URL(proof.verificationMethodId.href),
678
- result: { error: error instanceof Error ? error : new Error(String(error)) }
679
- };
680
- return null;
681
- }
682
- const publicKey = fetchedKey.key;
683
- if (publicKey == null) {
684
- logger.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
685
- proof,
686
- keyId: proof.verificationMethodId.href
687
- });
688
- return null;
689
- }
690
- if (publicKey.publicKey.algorithm.name !== "Ed25519") {
691
- if (fetchedKey.cached) {
692
- logger.debug("The cached key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}; retrying with the freshly fetched key...", {
693
- proof,
694
- keyId: proof.verificationMethodId.href
695
- });
696
- return await verifyProofInternal(jsonLd, proof, {
697
- ...options,
698
- keyCache: bypassKeyCacheReads(options.keyCache)
699
- }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
700
- }
701
- logger.debug("The fetched key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}", {
702
- proof,
703
- keyId: proof.verificationMethodId.href
704
- });
705
- return null;
706
- }
707
- const digest = new Uint8Array(proofDigest.byteLength + 32);
708
- digest.set(new Uint8Array(proofDigest), 0);
709
- const proofValue = proof.proofValue;
710
- let keyTried = false;
711
- const verifyCandidate = async (msgDigest) => {
712
- digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
713
- if (!keyTried) {
714
- triedKey(options, publicKey);
715
- keyTried = true;
716
- }
717
- return await crypto.subtle.verify("Ed25519", publicKey.publicKey, proofValue.slice(), digest);
718
- };
719
- const messageDigestKey = serialize(proofConfiguration.context ?? null);
720
- const messageDigestValues = messageDigestCache.values ??= /* @__PURE__ */ new Map();
721
- let messageDigestsPromise = messageDigestValues.get(messageDigestKey);
722
- if (messageDigestsPromise == null) {
723
- messageDigestsPromise = createProofMessageDigests(jsonLd, messageDigestCache.proofContextLoader, proofConfiguration.context, messageDigestCache.proofPropertyMode);
724
- messageDigestValues.set(messageDigestKey, messageDigestsPromise);
725
- }
726
- const messageDigests = await messageDigestsPromise;
727
- if (await verifyCandidate(messageDigests.onWire)) return publicKey;
728
- if (messageDigestCache.proofPropertyMode !== "literal") {
729
- const normalizedDigest = await messageDigests.normalized();
730
- if (normalizedDigest != null && await verifyCandidate(normalizedDigest)) return publicKey;
731
- }
732
- if (fetchedKey.cached) {
733
- logger.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
734
- keyId: proof.verificationMethodId.href,
735
- proof
736
- });
737
- return await verifyProofInternal(jsonLd, proof, {
738
- ...options,
739
- keyCache: bypassKeyCacheReads(options.keyCache)
740
- }, messageDigestCache, rawProofCandidate, keyIdBoundByCaller);
741
- }
742
- logger.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
743
- keyId: proof.verificationMethodId.href,
744
- proof
745
- });
746
- return null;
747
- }
748
- const AS_NAMESPACE = "https://www.w3.org/ns/activitystreams#";
749
- const FEP_2277_ACTOR_PROPERTIES = ["http://www.w3.org/ns/ldp#inbox", `${AS_NAMESPACE}outbox`];
750
- const FEP_2277_COLLECTION_PROPERTIES = [
751
- "items",
752
- "orderedItems",
753
- "totalItems",
754
- "partOf",
755
- "first",
756
- "last",
757
- "next",
758
- "prev",
759
- "current"
760
- ].map((property) => AS_NAMESPACE + property);
761
- const PORTABLE_OBJECT_ID_PATTERN = /^ap(?:\+ef61)?:\/\//i;
762
- const FUNCTIONAL_PROOF_PROPERTIES = [
763
- `${SECURITY_NAMESPACE}cryptosuite`,
764
- SECURITY_VERIFICATION_METHOD,
765
- `${SECURITY_NAMESPACE}proofPurpose`,
766
- `${SECURITY_NAMESPACE}proofValue`,
767
- "http://purl.org/dc/terms/created"
768
- ];
769
- function isJsonLdNode(value) {
770
- return typeof value === "object" && value != null && !Array.isArray(value);
771
- }
772
- function hasValidPortableProofShape(proofValue) {
773
- if (!isJsonLdNode(proofValue)) return false;
774
- let proofNode = proofValue;
775
- if ("@graph" in proofNode) {
776
- const graph = proofNode["@graph"];
777
- if (!Array.isArray(graph) || graph.length !== 1 || !isJsonLdNode(graph[0])) return false;
778
- proofNode = graph[0];
779
- }
780
- const types = proofNode["@type"];
781
- return Array.isArray(types) && types.length === 1 && types[0] === DATA_INTEGRITY_PROOF && FUNCTIONAL_PROOF_PROPERTIES.every((property) => {
782
- const values = proofNode[property];
783
- return Array.isArray(values) && values.length === 1 && !(isJsonLdNode(values[0]) && "@list" in values[0]);
784
- });
785
- }
786
- /**
787
- * Checks whether an expanded portable actor node has the `gateways` that
788
- * FEP-ef61 requires: a non-empty list whose items are all HTTP(S) URIs with
789
- * an empty path, query, and fragment. Like the generated vocabulary decoder,
790
- * this also tolerates a plain set of values instead of a `@list`, and gateway
791
- * strings given as `@value`s instead of `@id`s. JCS-authenticated actors may
792
- * also supply an unmapped literal `gateways` list.
793
- */
794
- function hasValidPortableActorGateways(node, allowUnmapped) {
795
- const values = getPortableActorGateways(node, allowUnmapped);
796
- if (!Array.isArray(values)) return false;
797
- let items = values;
798
- if (values.some((value) => isJsonLdNode(value) && "@list" in value)) {
799
- if (values.length !== 1 || !isJsonLdNode(values[0])) return false;
800
- items = values[0]["@list"];
801
- }
802
- if (!Array.isArray(items) || items.length < 1) return false;
803
- return items.every((item) => {
804
- if (!isJsonLdNode(item)) return false;
805
- const gateway = typeof item["@id"] === "string" ? item["@id"] : item["@value"];
806
- if (typeof gateway !== "string") return false;
807
- try {
808
- parseGatewayUrl(gateway);
809
- } catch (error) {
810
- if (error instanceof TypeError) return false;
811
- throw error;
812
- }
813
- return true;
814
- });
815
- }
816
- /**
817
- * Classifies an expanded JSON-LD node into an FEP-2277 core type by the
818
- * properties it has.
819
- * @internal
820
- */
821
- function classifyFep2277CoreType(node) {
822
- if (FEP_2277_ACTOR_PROPERTIES.every((property) => property in node)) return "actor";
823
- if (`${SECURITY_NAMESPACE}publicKeyMultibase` in node) return "verificationMethod";
824
- if (`${SECURITY_NAMESPACE}publicKeyPem` in node) return "publicKey";
825
- if (`${AS_NAMESPACE}href` in node) return "link";
826
- if (`${AS_NAMESPACE}actor` in node) return "activity";
827
- if (FEP_2277_COLLECTION_PROPERTIES.some((property) => property in node)) return "collection";
828
- return "object";
829
- }
830
- async function expandPortableObjectRoot(jsonLd, contextLoader) {
831
- if (!isJsonLdNode(jsonLd)) throw new TypeError("Expected a single JSON-LD object.");
832
- const loadedContexts = /* @__PURE__ */ new Map();
833
- const loader = getNormalizationContextLoader(contextLoader);
834
- const recordingLoader = async (url, options) => {
835
- const remoteDocument = await loader(url, options);
836
- const key = URL.canParse(url) ? new URL(url).href : url;
837
- loadedContexts.set(key, structuredClone(remoteDocument));
838
- return remoteDocument;
839
- };
840
- const expanded = await jsonld.expand(jsonLd, {
841
- documentLoader: recordingLoader,
842
- keepFreeFloatingNodes: true
843
- });
844
- if (expanded.length !== 1 || !isJsonLdNode(expanded[0])) throw new TypeError("Expected a single JSON-LD object.");
845
- return {
846
- root: expanded[0],
847
- proofContextLoader: async (url, options) => {
848
- const key = URL.canParse(url) ? new URL(url).href : url;
849
- const remoteDocument = loadedContexts.get(key);
850
- if (remoteDocument != null) return structuredClone(remoteDocument);
851
- return await preloadedOnlyDocumentLoader(url, options);
852
- }
853
- };
854
- }
855
- /**
856
- * Gets the DID of a portable object ID, which is either an `ap:` or
857
- * `ap+ef61:` URI or an FEP-ef61 compatible identifier.
858
- * @throws {TypeError} If the ID is malformed.
859
- */
860
- function getObjectDid(id) {
861
- try {
862
- parseIri(id);
863
- if (PORTABLE_OBJECT_ID_PATTERN.test(id)) return getFe34Origin(id);
864
- const portableId = fromCompatibleEf61Id(id);
865
- if (portableId != null) return getFe34Origin(portableId);
866
- } catch (error) {
867
- if (!(error instanceof TypeError)) throw error;
868
- throw new InvalidPortableObjectIdError(id, { cause: error });
869
- }
870
- throw new InvalidPortableObjectIdError(id);
871
- }
872
- /**
873
- * The error thrown when a document's ID looks portable, i.e., it is an `ap:`
874
- * or `ap+ef61:` URI or looks like an FEP-ef61 compatible identifier, but is
875
- * malformed.
876
- * @internal
877
- */
878
- var InvalidPortableObjectIdError = class extends TypeError {
879
- constructor(id, options) {
880
- super(`Invalid portable object ID: ${id}`, options);
881
- this.name = "InvalidPortableObjectIdError";
882
- }
883
- };
884
- async function preparePortableObjectProof(jsonLd, options) {
885
- if (isJsonLdNode(jsonLd) && typeof jsonLd["@id"] === "string" && !isPortableId(jsonLd["@id"])) return {
886
- prepared: false,
887
- result: {
888
- verified: false,
889
- reason: { type: "notPortableObject" }
890
- }
891
- };
892
- const { root, proofContextLoader } = await expandPortableObjectRoot(jsonLd, options.contextLoader);
893
- const id = root["@id"];
894
- if (typeof id !== "string" || !isPortableId(id)) return {
895
- prepared: false,
896
- result: {
897
- verified: false,
898
- reason: { type: "notPortableObject" }
899
- }
900
- };
901
- const objectDid = getObjectDid(id);
902
- const objectId = parseIri(id);
903
- const objectType = classifyFep2277CoreType(root);
904
- if (objectType === "verificationMethod" || objectType === "publicKey" || objectType === "link") return {
905
- prepared: false,
906
- result: {
907
- verified: false,
908
- reason: {
909
- type: "unsupportedObjectType",
910
- objectType
911
- }
912
- }
913
- };
914
- const proofValues = root[SECURITY_PROOF];
915
- if (proofValues == null || Array.isArray(proofValues) && proofValues.length < 1) return {
916
- prepared: false,
917
- root,
918
- objectType,
919
- result: objectType === "collection" ? {
920
- verified: false,
921
- reason: { type: "unsecuredCollection" }
922
- } : {
923
- verified: false,
924
- reason: { type: "missingProof" }
925
- }
926
- };
927
- if (!Array.isArray(proofValues)) return {
928
- prepared: false,
929
- result: {
930
- verified: false,
931
- reason: {
932
- type: "invalidProof",
933
- proofIndex: 0
934
- }
935
- }
936
- };
937
- const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
938
- const proofs = [];
939
- for (let proofIndex = 0; proofIndex < proofValues.length; proofIndex++) {
940
- const proofValue = proofValues[proofIndex];
941
- if (!hasValidPortableProofShape(proofValue)) return {
942
- prepared: false,
943
- result: {
944
- verified: false,
945
- reason: {
946
- type: "invalidProof",
947
- proofIndex
948
- }
949
- }
950
- };
951
- let proof;
952
- try {
953
- proof = await DataIntegrityProof.fromJsonLd(proofValue, options);
954
- } catch {
955
- return {
956
- prepared: false,
957
- result: {
958
- verified: false,
959
- reason: {
960
- type: "invalidProof",
961
- proofIndex
962
- }
963
- }
964
- };
965
- }
966
- proofs.push(proof);
967
- }
968
- for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
969
- const verificationMethod = proofs[proofIndex].verificationMethodId;
970
- if (verificationMethod == null) return {
971
- prepared: false,
972
- result: {
973
- verified: false,
974
- reason: {
975
- type: "invalidProof",
976
- proofIndex
977
- }
978
- }
979
- };
980
- if (verificationMethod.protocol !== "did:") return {
981
- prepared: false,
982
- result: {
983
- verified: false,
984
- reason: {
985
- type: "unsupportedVerificationMethod",
986
- proofIndex,
987
- verificationMethod
988
- }
989
- }
990
- };
991
- try {
992
- getFe34Origin(verificationMethod);
993
- } catch (error) {
994
- if (!(error instanceof TypeError)) throw error;
995
- return {
996
- prepared: false,
997
- result: {
998
- verified: false,
999
- reason: {
1000
- type: "unsupportedVerificationMethod",
1001
- proofIndex,
1002
- verificationMethod
1003
- }
1004
- }
1005
- };
1006
- }
1007
- if (getFe34Origin(verificationMethod) !== objectDid) return {
1008
- prepared: false,
1009
- result: {
1010
- verified: false,
1011
- reason: {
1012
- type: "verificationMethodMismatch",
1013
- proofIndex,
1014
- objectId,
1015
- verificationMethod
1016
- }
1017
- }
1018
- };
1019
- }
1020
- if (objectType === "actor" && !hasValidPortableActorGateways(root, proofs.every((proof) => proof.cryptosuite === "eddsa-jcs-2022"))) return {
1021
- prepared: false,
1022
- root,
1023
- objectType,
1024
- result: {
1025
- verified: false,
1026
- reason: { type: "invalidGateways" }
1027
- }
1028
- };
1029
- return {
1030
- prepared: true,
1031
- root,
1032
- objectType,
1033
- objectId,
1034
- proofs,
1035
- rawProofValues,
1036
- proofContextLoader
1037
- };
1038
- }
1039
- /**
1040
- * Checks portable-object policy without resolving keys or verifying signatures.
1041
- *
1042
- * @internal
1043
- */
1044
- async function preparePortableObjectProofPolicy(jsonLd, options = {}) {
1045
- const policyOptions = {
1046
- ...options,
1047
- contextLoader: preloadedOnlyDocumentLoader
1048
- };
1049
- const prepared = await preparePortableObjectProof(jsonLd, policyOptions);
1050
- if (!prepared.prepared) return {
1051
- prepared: false,
1052
- result: prepared.result
1053
- };
1054
- const policyProof = prepared.proofs[0];
1055
- const literalProof = isJsonLdNode(jsonLd) && isJsonLdNode(jsonLd.proof) ? (await parseRawProofCandidates(jsonLd, [jsonLd.proof], policyOptions, prepared.proofContextLoader))[0]?.proof : null;
1056
- const verificationMethod = policyProof?.verificationMethodId;
1057
- if (prepared.proofs.length !== 1 || policyProof == null || literalProof == null || !sameProof(policyProof, literalProof) || verificationMethod == null) return {
1058
- prepared: false,
1059
- result: {
1060
- verified: false,
1061
- reason: {
1062
- type: "invalidProof",
1063
- proofIndex: prepared.proofs.length > 1 ? 1 : 0
1064
- }
1065
- }
1066
- };
1067
- return {
1068
- prepared: true,
1069
- verificationMethod,
1070
- objectId: formatIri(prepared.objectId)
1071
- };
1072
- }
1073
- /**
1074
- * Binds prepared portable-object policy to the map-local verified key.
1075
- *
1076
- * @internal
1077
- */
1078
- function verifyPreparedPortableObjectProofPolicy(prepared, key) {
1079
- if (key == null || key.id?.href !== prepared.verificationMethod.href) return {
1080
- verified: false,
1081
- reason: {
1082
- type: "invalidProof",
1083
- proofIndex: 0
1084
- }
1085
- };
1086
- return {
1087
- verified: true,
1088
- keys: [key],
1089
- objectId: prepared.objectId
1090
- };
1091
- }
1092
- /**
1093
- * Applies portable-object proof policy to one map-local cryptographic result.
1094
- *
1095
- * @internal
1096
- */
1097
- async function verifyPortableObjectProofPolicy(jsonLd, key, options = {}) {
1098
- const prepared = await preparePortableObjectProofPolicy(jsonLd, options);
1099
- return prepared.prepared ? verifyPreparedPortableObjectProofPolicy(prepared, key) : prepared.result;
1100
- }
1101
- /**
1102
- * Verifies the FEP-ef61 Object Integrity Proof policy for a portable object.
1103
- *
1104
- * This applies the FEP-2277 core-type classification to the top-level JSON-LD
1105
- * node. Portable actors, activities, and objects require proofs. A portable
1106
- * collection without a proof is reported separately so a caller can apply a
1107
- * gateway trust policy. Embedded portable objects are not traversed.
1108
- *
1109
- * A portable object is a document whose ID is an `ap:` or `ap+ef61:` URI, or
1110
- * an [FEP-ef61] compatible identifier such as
1111
- * `https://gw.example/.well-known/apgateway/did:key:z6Mk…/actor`, which
1112
- * stands for the portable ID `ap+ef61://did:key:z6Mk…/actor`.
1113
- *
1114
- * Every proof must use a DID URL whose DID matches the portable object's
1115
- * authority, i.e., the DID of its canonical portable ID, and every proof must
1116
- * pass {@link verifyProof}. A portable actor must also have a non-empty
1117
- * `gateways` list whose items are all HTTP(S) URIs with an empty path, query,
1118
- * and fragment; otherwise, it is rejected with the `invalidGateways` reason
1119
- * before its proofs are verified. The proofs are verified over the document as
1120
- * given; a compatible identifier is never rewritten into a portable ID.
1121
- * An unmapped literal `gateways` property is also accepted when every proof
1122
- * uses `eddsa-jcs-2022`, which authenticates the original JSON properties.
1123
- *
1124
- * [FEP-ef61]: https://w3id.org/fep/ef61
1125
- *
1126
- * @param jsonLd The JSON-LD document to verify.
1127
- * @param options Additional options. See also
1128
- * {@link VerifyPortableObjectProofOptions}.
1129
- * @returns The detailed portable proof-policy result.
1130
- * @throws {TypeError} If the input is not a single JSON-LD object or has a
1131
- * malformed portable ID or compatible identifier.
1132
- * @since 2.4.0
1133
- */
1134
- async function verifyPortableObjectProof(jsonLd, options = {}) {
1135
- return (await verifyPortableObjectProofWithRoot(jsonLd, options)).result;
1136
- }
1137
- /**
1138
- * Same as {@link verifyPortableObjectProof}, but also returns the expanded
1139
- * root node and its FEP-2277 core type, so that a caller can apply further
1140
- * policy, such as the gateway trust policy for unsecured collections, to the
1141
- * same interpretation of the document.
1142
- * @internal
1143
- */
1144
- async function verifyPortableObjectProofWithRoot(jsonLd, options = {}) {
1145
- const prepared = await preparePortableObjectProof(jsonLd, options);
1146
- if (!prepared.prepared) return {
1147
- result: prepared.result,
1148
- ...prepared.root == null ? {} : { root: prepared.root },
1149
- ...prepared.objectType == null ? {} : { objectType: prepared.objectType }
1150
- };
1151
- const { root, objectType, proofContextLoader } = prepared;
1152
- const messageDigestCache = { proofContextLoader };
1153
- const result = await verifyPreparedPortableObjectProof(jsonLd, prepared, options, messageDigestCache);
1154
- const { expires } = messageDigestCache;
1155
- return {
1156
- result,
1157
- root,
1158
- objectType,
1159
- ...result.verified && expires != null ? { expires } : {}
1160
- };
1161
- }
1162
- async function verifyPreparedPortableObjectProof(jsonLd, prepared, options, messageDigestCache) {
1163
- const { proofs, rawProofValues, proofContextLoader } = prepared;
1164
- const keys = [];
1165
- const rawProofCandidatePool = {
1166
- candidates: await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader),
1167
- used: /* @__PURE__ */ new Set()
1168
- };
1169
- for (let proofIndex = 0; proofIndex < proofs.length; proofIndex++) {
1170
- const rawProofCandidate = takeRawProofCandidate(rawProofCandidatePool, proofs[proofIndex]);
1171
- if (rawProofCandidate == null) return {
1172
- verified: false,
1173
- reason: {
1174
- type: "invalidProof",
1175
- proofIndex
1176
- }
1177
- };
1178
- const key = await verifyProofWithMessageDigestCache(jsonLd, proofs[proofIndex], options, messageDigestCache, rawProofCandidate, true);
1179
- if (key == null) return {
1180
- verified: false,
1181
- reason: {
1182
- type: "invalidProof",
1183
- proofIndex
1184
- }
1185
- };
1186
- keys.push(key);
1187
- }
1188
- return {
1189
- verified: true,
1190
- keys
1191
- };
1192
- }
1193
- /**
1194
- * Verifies the given object. It will verify all the proofs in the object,
1195
- * and succeed only if all the proofs are valid and all attributions and
1196
- * actors are authenticated by the proofs.
1197
- * @template T The type of the object to verify.
1198
- * @param cls The class of the object to verify. It must be a subclass of
1199
- * the {@link Object}.
1200
- * @param jsonLd The JSON-LD object to verify. It's assumed that the object
1201
- * is a compacted JSON-LD representation of a `T` with `@context`.
1202
- * @param options Additional options. See also {@link VerifyObjectOptions}.
1203
- * @returns The object if it's verified, or `null` if it's not.
1204
- * @throws {TypeError} If the object is invalid or unsupported.
1205
- * @since 0.10.0
1206
- */
1207
- async function verifyObject(cls, jsonLd, options = {}) {
1208
- const result = await verifyObjectDetailed(cls, jsonLd, options);
1209
- return result.status === "verified" ? result.object : null;
1210
- }
1211
- /**
1212
- * Same as {@link verifyObject}, but also tells who signed the verified proofs,
1213
- * and whether a failure was caused by a key that could not be obtained for
1214
- * a retryable reason.
1215
- * @param cls The class of the object to verify.
1216
- * @param jsonLd The JSON-LD object to verify.
1217
- * @param options Additional options.
1218
- * @returns The result.
1219
- * @throws {TypeError} If the object is invalid or unsupported.
1220
- * @internal
1221
- */
1222
- async function verifyObjectDetailed(cls, jsonLd, options = {}) {
1223
- const classify = (result, checks) => {
1224
- if (result != null) return {
1225
- status: "verified",
1226
- object: result.object,
1227
- signers: result.signers
1228
- };
1229
- for (const check of checks) {
1230
- if (check.status === "error" && isTransientFetchError(check.error)) return {
1231
- status: "unavailable",
1232
- error: check.error
1233
- };
1234
- if (check.status === "rejected" && check.reason.type === "keyFetchError" && isRetryableKeyFetchError(check.reason.result)) return {
1235
- status: "unavailable",
1236
- error: "error" in check.reason.result ? check.reason.result.error : /* @__PURE__ */ new Error(`Fetching key ${check.reason.keyId.href} failed with ${check.reason.result.status}.`)
1237
- };
1238
- }
1239
- return { status: "invalid" };
1240
- };
1241
- if (options[verificationObservation]?.attempt == null) {
1242
- const observedOptions = {
1243
- ...options,
1244
- [verificationObservation]: options[verificationObservation] ?? {
1245
- attempts: [],
1246
- captureRawKeyIds: false
1247
- }
1248
- };
1249
- return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.verify_object", async (span) => {
1250
- try {
1251
- return await observeAttempt(observedOptions, "objectIntegrity", async (observation) => {
1252
- const result = await verifyObjectCore(cls, jsonLd, {
1253
- ...options,
1254
- [verificationObservation]: observation
1255
- });
1256
- if (result == null) {
1257
- span.setStatus({ code: SpanStatusCode.ERROR });
1258
- span.setAttribute("activitypub.verification.failure_reason", observation.attempt?.reason?.type ?? "signatureVerificationFailed");
1259
- }
1260
- return classify(result, observation.attempt?.checks ?? []);
1261
- }, (value) => value.status === "verified");
1262
- } catch (error) {
1263
- span.setStatus({
1264
- code: SpanStatusCode.ERROR,
1265
- message: String(error)
1266
- });
1267
- throw error;
1268
- } finally {
1269
- span.end();
1270
- }
1271
- });
1272
- }
1273
- const checks = options[verificationObservation].attempt.checks;
1274
- const before = checks.length;
1275
- return classify(await verifyObjectCore(cls, jsonLd, options), checks.slice(before));
1276
- }
1277
- function isRetryableKeyFetchError(result) {
1278
- if ("error" in result) return isTransientFetchError(result.error);
1279
- return result.status >= 500 || result.status === 408 || result.status === 429;
1280
- }
1281
- async function verifyObjectCore(cls, jsonLd, options) {
1282
- const observation = options[verificationObservation];
1283
- const logger = getLogger([
1284
- "fedify",
1285
- "sig",
1286
- "proof"
1287
- ]);
1288
- const object = await cls.fromJsonLd(jsonLd, options);
1289
- observation?.parsedObject?.(object);
1290
- if (observation?.subject != null) observation.subject.id = object.id == null ? null : new URL(object.id.href);
1291
- const defaultDocumentLoader = getDocumentLoader();
1292
- const proofContextLoader = options.contextLoader ?? defaultDocumentLoader;
1293
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
1294
- const signers = [];
1295
- if (object instanceof Activity) for (const uri of object.actorIds) attributions.add(uri.href);
1296
- const rawProofValues = isJsonLdNode(jsonLd) ? await getRawProofValues(jsonLd, proofContextLoader) : [];
1297
- const rawProofCandidates = isJsonLdNode(jsonLd) ? await parseRawProofCandidates(jsonLd, rawProofValues, options, proofContextLoader) : [];
1298
- const rawProofCandidatePool = {
1299
- candidates: rawProofCandidates,
1300
- used: /* @__PURE__ */ new Set()
1301
- };
1302
- const baseDocumentLoader = options.documentLoader ?? defaultDocumentLoader;
1303
- const hydratedCandidates = /* @__PURE__ */ new Set();
1304
- let loadedPortableProofs = 0;
1305
- let acceptedPortableProofs = 0;
1306
- const acceptPortableProofDocument = async () => {
1307
- acceptedPortableProofs++;
1308
- return { verified: true };
1309
- };
1310
- const proofDocumentLoader = async (url, loaderOptions) => {
1311
- const remoteDocument = await baseDocumentLoader(url, loaderOptions);
1312
- if (isPortableId(url)) loadedPortableProofs++;
1313
- const reference = normalizeDocumentUrl(url);
1314
- const candidateIndex = rawProofCandidates.findIndex((candidate, index) => !hydratedCandidates.has(index) && !rawProofCandidatePool.used.has(index) && candidate.reference === reference);
1315
- if (candidateIndex >= 0) {
1316
- hydratedCandidates.add(candidateIndex);
1317
- let parsed = null;
1318
- const contexts = options[verificationObservation] != null && options[verificationObservation]?.captureRawKeyIds !== false ? recordProofContexts(proofContextLoader) : void 0;
1319
- try {
1320
- parsed = await DataIntegrityProof.fromJsonLd(remoteDocument.document, {
1321
- documentLoader: baseDocumentLoader,
1322
- contextLoader: contexts?.loader ?? proofContextLoader,
1323
- tracerProvider: options.tracerProvider,
1324
- baseUrl: parseIri(remoteDocument.documentUrl)
1325
- });
1326
- } catch {}
1327
- rawProofCandidates[candidateIndex] = {
1328
- value: structuredClone(remoteDocument.document),
1329
- proof: parsed,
1330
- reference,
1331
- declaredKeyId: contexts == null ? void 0 : await getAliasedDeclaredProofKeyId(remoteDocument.document, void 0, contexts.replay)
1332
- };
1333
- }
1334
- return remoteDocument;
1335
- };
1336
- for await (const proof of object.getProofs({
1337
- ...options,
1338
- documentLoader: proofDocumentLoader,
1339
- gateways: [],
1340
- verifyPortableObject: acceptPortableProofDocument,
1341
- inheritPortableObjectVerifier: false
1342
- })) {
1343
- const rawProofCandidate = takeRawProofCandidate(rawProofCandidatePool, proof);
1344
- if (rawProofCandidate == null) return null;
1345
- const key = await verifyProofWithMessageDigestCache(jsonLd, proof, options, { proofContextLoader }, rawProofCandidate);
1346
- if (key === null) return null;
1347
- if (proof.verificationMethodId == null) return null;
1348
- if (key.controllerId == null) {
1349
- logger.debug("Key {keyId} does not have a controller.", { keyId: key.id?.href });
1350
- continue;
1351
- }
1352
- deleteAuthenticatedAttribution(attributions, key.controllerId, proof.verificationMethodId);
1353
- const signer = getAuthenticatedController(key.controllerId, proof.verificationMethodId);
1354
- if (signer != null && !signers.some((s) => s.kind === signer.kind && s.id.href === signer.id.href && s.keyId.href === proof.verificationMethodId.href)) signers.push({
1355
- ...signer,
1356
- keyId: proof.verificationMethodId
1357
- });
1358
- }
1359
- if (acceptedPortableProofs < loadedPortableProofs) {
1360
- logger.debug("Some portable proof references could not be dereferenced.");
1361
- return null;
1362
- }
1363
- if (attributions.size > 0) {
1364
- if (observation?.attempt != null) observation.attempt.reason = observation.attempt.checks.length === 0 ? { type: "noSignature" } : {
1365
- type: "uncoveredAttribution",
1366
- attributionIds: [...attributions].map((id) => new URL(id))
1367
- };
1368
- logger.debug("Some attributions are not authenticated by the proofs: {attributions}.", { attributions: [...attributions] });
1369
- return null;
1370
- }
1371
- return {
1372
- object,
1373
- signers
1374
- };
1375
- }
1376
- /**
1377
- * Tells whom a key that verified an Object Integrity Proof authenticates.
1378
- * @param key The key, i.e., the proof's verification method.
1379
- * @returns The signer, or `null` if the key authenticates nobody.
1380
- * @internal
1381
- */
1382
- function getProofSigner(key) {
1383
- if (key.id == null || key.controllerId == null) return null;
1384
- const signer = getAuthenticatedController(key.controllerId, key.id);
1385
- return signer == null ? null : {
1386
- ...signer,
1387
- keyId: key.id
1388
- };
1389
- }
1390
- /**
1391
- * Tells whom a verified proof authenticates: the key's controller if it is an
1392
- * ordinary actor, or the DID of a portable controller if the verification
1393
- * method belongs to the same DID.
1394
- */
1395
- function getAuthenticatedController(controllerId, verificationMethodId) {
1396
- if (!hasCryptographicOrigin(controllerId.href) && !isPortableId(controllerId)) return {
1397
- kind: "actor",
1398
- id: controllerId
1399
- };
1400
- const did = getPortableDid(controllerId);
1401
- if (did == null || !hasCryptographicOrigin(verificationMethodId.href) || getPortableDid(verificationMethodId) !== did || !URL.canParse(did)) return null;
1402
- return {
1403
- kind: "portableAuthority",
1404
- id: new URL(did)
1405
- };
1406
- }
1407
- function deleteAuthenticatedAttribution(attributions, controllerId, verificationMethodId) {
1408
- if (!hasCryptographicOrigin(controllerId.href) && !isPortableId(controllerId)) {
1409
- attributions.delete(controllerId.href);
1410
- return;
1411
- }
1412
- const did = getPortableDid(controllerId);
1413
- if (did == null || !hasCryptographicOrigin(verificationMethodId.href) || getPortableDid(verificationMethodId) !== did) return;
1414
- for (const attribution of [...attributions]) if ((hasCryptographicOrigin(attribution) || isPortableId(attribution)) && getPortableDid(attribution) === did) attributions.delete(attribution);
1415
- }
1416
- function hasCryptographicOrigin(iri) {
1417
- return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
1418
- }
1419
- //#endregion
1420
- export { hasProofLike as a, verifyMapLocalProof as c, verifyPortableObjectProof as d, verifyPortableObjectProofPolicy as f, verifyProof as h, getProofSigner as i, verifyObject as l, verifyPreparedPortableObjectProofPolicy as m, classifyFep2277CoreType as n, preparePortableObjectProofPolicy as o, verifyPortableObjectProofWithRoot as p, createProof as r, signObject as s, InvalidPortableObjectIdError as t, verifyObjectDetailed as u };