@fedify/fedify 2.4.0-pr.936.41 → 2.5.0-dev.2271

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/README.md +50 -39
  2. package/dist/{assert-CJ1KXcvv.mjs → assert-D1Eafmd_.mjs} +1 -1
  3. package/dist/{assert_equals-BV7oLMxm.mjs → assert_equals-Z6IcEbWU.mjs} +2 -28
  4. package/dist/assert_exists-cffSpJ7X.mjs +28 -0
  5. package/dist/assert_false-CPdRnc3E.mjs +23 -0
  6. package/dist/assert_greater_or_equal-BlafOF4-.mjs +31 -0
  7. package/dist/{assert_instance_of-Q9KTBnrf.mjs → assert_instance_of-mrXWWNY-.mjs} +1 -1
  8. package/dist/{assert_not_equals-EPJPoxuf.mjs → assert_not_equals-CpPK2t89.mjs} +2 -1
  9. package/dist/assert_rejects-CTptdYck.mjs +39 -0
  10. package/dist/{assert_strict_equals-Ec20AUwa.mjs → assert_strict_equals-CYvBmkpC.mjs} +2 -1
  11. package/dist/{assert_throws-NiFfqbnH.mjs → assert_throws-BYITOvPO.mjs} +2 -1
  12. package/dist/assertion_error-B-cx0fFA.mjs +31 -0
  13. package/dist/audience-CHQ-FlLD.mjs +95 -0
  14. package/dist/{builder-DonuxRl_.mjs → builder-Bda6LK7A.mjs} +169 -14
  15. package/dist/{circuit-breaker-CBGyz5F7.mjs → circuit-breaker-XJ53md4S.mjs} +224 -17
  16. package/dist/circuit-breaker-test-utils-DW6YC_Pe.mjs +14 -0
  17. package/dist/{client-CjF5IYQS.mjs → client-CEnNz8O7.mjs} +144 -8
  18. package/dist/{codec-BBga-FWI.mjs → codec-C6rTrpIp.mjs} +26 -3
  19. package/dist/{collection-BIhlldqK.mjs → collection-CnnP1UAv.mjs} +1 -1
  20. package/dist/compat/mod.cjs +1 -1
  21. package/dist/compat/mod.d.cts +1 -1
  22. package/dist/compat/mod.d.ts +1 -1
  23. package/dist/compat/mod.js +1 -1
  24. package/dist/compat/outgoing-jsonld.test.mjs +71 -3
  25. package/dist/compat/public-audience.test.mjs +14 -5
  26. package/dist/compat/secured-document.test.d.mts +2 -0
  27. package/dist/compat/secured-document.test.mjs +58 -0
  28. package/dist/compat/transformers.test.mjs +5 -5
  29. package/dist/compound-proof-B-9mXxFW.mjs +989 -0
  30. package/dist/{context-Zii1f5xS.d.ts → context-7NyiqIcg.d.ts} +1600 -25
  31. package/dist/{context-BJXxPElm.mjs → context-8Tu9kea0.mjs} +21 -63
  32. package/dist/{context-lxX6I7as.d.cts → context-tsYPJ2Ew.d.cts} +1600 -25
  33. package/dist/{deno-BHzKn9Ig.mjs → deno-oR5aJKpU.mjs} +1 -1
  34. package/dist/dist-DJQM4u7i.mjs +189 -0
  35. package/dist/docloader-DBoYbvYW.mjs +87 -0
  36. package/dist/{esm-yYQfPhIY.mjs → esm-BHXXx4Wx.mjs} +13 -6
  37. package/dist/federation/audience.test.d.mts +2 -0
  38. package/dist/federation/audience.test.mjs +130 -0
  39. package/dist/federation/builder.test.mjs +54 -5
  40. package/dist/federation/circuit-breaker.test.mjs +838 -7
  41. package/dist/federation/collection.test.mjs +3 -3
  42. package/dist/federation/compound-fanout.test.d.mts +2 -0
  43. package/dist/federation/compound-fanout.test.mjs +228 -0
  44. package/dist/federation/handler-compound-proof.test.d.mts +2 -0
  45. package/dist/federation/handler-compound-proof.test.mjs +384 -0
  46. package/dist/federation/handler.test.mjs +385 -15
  47. package/dist/federation/hashlink-media.test.d.mts +2 -0
  48. package/dist/federation/hashlink-media.test.mjs +422 -0
  49. package/dist/federation/idempotency.test.mjs +6 -6
  50. package/dist/federation/inbox-report.test.d.mts +2 -0
  51. package/dist/federation/inbox-report.test.mjs +475 -0
  52. package/dist/federation/inbox.test.mjs +3 -3
  53. package/dist/federation/keycache.test.mjs +215 -14
  54. package/dist/federation/kv.test.mjs +3 -3
  55. package/dist/federation/metrics.test.mjs +5 -5
  56. package/dist/federation/middleware.test.mjs +967 -35
  57. package/dist/federation/mod.cjs +18 -261
  58. package/dist/federation/mod.d.cts +5 -5
  59. package/dist/federation/mod.d.ts +5 -5
  60. package/dist/federation/mod.js +279 -1
  61. package/dist/federation/mq.test.mjs +123 -47
  62. package/dist/federation/negotiation.test.mjs +4 -4
  63. package/dist/federation/outgoing-proof.test.d.mts +2 -0
  64. package/dist/federation/outgoing-proof.test.mjs +931 -0
  65. package/dist/federation/portable-actor.test.d.mts +2 -0
  66. package/dist/federation/portable-actor.test.mjs +496 -0
  67. package/dist/federation/portable-chain.test.d.mts +2 -0
  68. package/dist/federation/portable-chain.test.mjs +370 -0
  69. package/dist/federation/portable-collection.test.d.mts +2 -0
  70. package/dist/federation/portable-collection.test.mjs +832 -0
  71. package/dist/federation/portable-delivery.test.d.mts +2 -0
  72. package/dist/federation/portable-delivery.test.mjs +746 -0
  73. package/dist/federation/portable-gateway-keys.test.d.mts +2 -0
  74. package/dist/federation/portable-gateway-keys.test.mjs +686 -0
  75. package/dist/federation/portable-inbox.test.d.mts +2 -0
  76. package/dist/federation/portable-inbox.test.mjs +1535 -0
  77. package/dist/federation/portable-parse-uri.test.d.mts +2 -0
  78. package/dist/federation/portable-parse-uri.test.mjs +348 -0
  79. package/dist/federation/portable-route-activity.test.d.mts +2 -0
  80. package/dist/federation/portable-route-activity.test.mjs +259 -0
  81. package/dist/federation/portable.test.d.mts +2 -0
  82. package/dist/federation/portable.test.mjs +1072 -0
  83. package/dist/federation/retry.test.mjs +4 -3
  84. package/dist/federation/router.test.mjs +9 -159
  85. package/dist/federation/send.test.mjs +245 -27
  86. package/dist/federation/tasks/codec.test.mjs +4 -4
  87. package/dist/federation/tasks/enqueue.test.mjs +42 -4
  88. package/dist/federation/tasks/tasks.test.mjs +7 -6
  89. package/dist/federation/temporal.test.mjs +4 -4
  90. package/dist/federation/webfinger.test.mjs +275 -12
  91. package/dist/{middleware-FrSMAYEx.cjs → federation-CkZiAcWY.cjs} +8640 -3722
  92. package/dist/http-B5JT115n.cjs +10630 -0
  93. package/dist/http-DydWCB7R.js +6527 -0
  94. package/dist/{http-CPVMUgsW.mjs → http-siciWkmx.mjs} +397 -168
  95. package/dist/key-BspPiXqn.mjs +951 -0
  96. package/dist/key-C1nv7_jD.d.ts +1125 -0
  97. package/dist/key-DYxuyd-s.d.cts +1125 -0
  98. package/dist/key-owner-evidence-APB6NpSk.mjs +108 -0
  99. package/dist/keycache-Da8A8mZa.mjs +200 -0
  100. package/dist/{kv-D6hNiMTK.d.ts → kv-B2mzK5tl.d.cts} +3 -2
  101. package/dist/{kv-gJ8LYbxX.d.cts → kv-B2mzK5tl.d.ts} +3 -2
  102. package/dist/kv-DBRWVx3Q.mjs +104 -0
  103. package/dist/{kv-cache-KyGqJqSp.mjs → kv-cache-BF1hnW65.mjs} +1 -1
  104. package/dist/{kv-cache-5bnX3-Jq.js → kv-cache-CTQr1tbn.js} +54 -16
  105. package/dist/{kv-cache-DQ29C4XL.cjs → kv-cache-DCac1nEU.cjs} +55 -19
  106. package/dist/{ld-Cj9F_5AP.mjs → ld-CzaP-hJl.mjs} +44 -12
  107. package/dist/map-local-context-conflict-DOYEEJ3u.mjs +204 -0
  108. package/dist/map-local-create-note-B0SeXJms.mjs +214 -0
  109. package/dist/{metrics-DMk-nTxI.mjs → metrics-CYg9yxBL.mjs} +3 -2
  110. package/dist/metrics-DVKYY6K1.d.cts +36 -0
  111. package/dist/metrics-DoRtI0qU.d.ts +36 -0
  112. package/dist/{middleware-Y-kpsp6S.js → middleware-CsDDXKuL.js} +5493 -1103
  113. package/dist/{middleware-CvwTUgnP.mjs → middleware-D7_LO-Vs.mjs} +3157 -272
  114. package/dist/{middleware-CEctxBN6.mjs → middleware-DWjrfpcz.mjs} +1 -1
  115. package/dist/{mod-gOlPDuT8.d.cts → mod-BojP2Bw3.d.cts} +1 -1
  116. package/dist/mod-CavhAgLw.d.cts +320 -0
  117. package/dist/mod-CtpF2BU5.d.ts +320 -0
  118. package/dist/{mod-BtEaIEcD.d.cts → mod-DEZXwV6J.d.ts} +10 -4
  119. package/dist/{mod-UMmveiO0.d.ts → mod-Dw-nPxQh.d.cts} +10 -4
  120. package/dist/{mod-DLc2Ot6f.d.ts → mod-Xj5P4s4d.d.ts} +1 -1
  121. package/dist/mod.cjs +40 -39
  122. package/dist/mod.d.cts +10 -11
  123. package/dist/mod.d.ts +10 -11
  124. package/dist/mod.js +9 -9
  125. package/dist/{mq-llHKivST.mjs → mq-Dm1Wmtm-.mjs} +6 -0
  126. package/dist/nodeinfo/client.test.mjs +139 -4
  127. package/dist/nodeinfo/handler.test.mjs +5 -5
  128. package/dist/nodeinfo/mod.cjs +1 -1
  129. package/dist/nodeinfo/mod.d.cts +1 -1
  130. package/dist/nodeinfo/mod.d.ts +1 -1
  131. package/dist/nodeinfo/mod.js +1 -1
  132. package/dist/nodeinfo/types.test.mjs +4 -4
  133. package/dist/otel/exporter.test.mjs +3 -3
  134. package/dist/otel/mod.cjs +0 -1
  135. package/dist/otel/mod.d.cts +1 -1
  136. package/dist/otel/mod.d.ts +1 -1
  137. package/dist/{outgoing-jsonld-URuqsICz.mjs → outgoing-jsonld-4IJqPYos.mjs} +12 -10
  138. package/dist/{owner-DEvZuyOE.d.cts → owner-BF0L9cMt.d.cts} +11 -0
  139. package/dist/{owner-CnngXDNJ.d.ts → owner-BSzr5-I8.d.ts} +11 -0
  140. package/dist/owner-DYgfTFHy.mjs +267 -0
  141. package/dist/portable-collection-BpsVsRov.js +670 -0
  142. package/dist/portable-collection-C74P1vtC.mjs +418 -0
  143. package/dist/portable-collection-DZd2bm7M.cjs +686 -0
  144. package/dist/portable-key-BIMLrAP4.mjs +549 -0
  145. package/dist/portable-key-id-Ca30-hOa.mjs +248 -0
  146. package/dist/proof-Dxy6ByqI.mjs +1299 -0
  147. package/dist/{public-audience-Cr5MsnMq.mjs → public-audience--klBIOk1.mjs} +15 -10
  148. package/dist/router-u5O5KCQr.mjs +156 -0
  149. package/dist/runtime/mod.cjs +1 -1
  150. package/dist/runtime/mod.js +1 -1
  151. package/dist/secured-document-CxzZZ9nL.mjs +35 -0
  152. package/dist/send-C4dDpAxm.mjs +495 -0
  153. package/dist/sig/accept.test.mjs +1 -1
  154. package/dist/sig/compound-proof-discovery.test.d.mts +2 -0
  155. package/dist/sig/compound-proof-discovery.test.mjs +331 -0
  156. package/dist/sig/compound-proof-producer.test.d.mts +2 -0
  157. package/dist/sig/compound-proof-producer.test.mjs +107 -0
  158. package/dist/sig/compound-proof-verification.test.d.mts +2 -0
  159. package/dist/sig/compound-proof-verification.test.mjs +833 -0
  160. package/dist/sig/compound-proof.test.d.mts +2 -0
  161. package/dist/sig/compound-proof.test.mjs +411 -0
  162. package/dist/sig/http.test.mjs +702 -31
  163. package/dist/sig/key-owner-evidence.test.d.mts +2 -0
  164. package/dist/sig/key-owner-evidence.test.mjs +100 -0
  165. package/dist/sig/key.test.mjs +220 -8
  166. package/dist/sig/ld.test.mjs +65 -7
  167. package/dist/sig/mitra-receive-interop.test.d.mts +2 -0
  168. package/dist/sig/mitra-receive-interop.test.mjs +260 -0
  169. package/dist/sig/mitra-send-interop.test.d.mts +2 -0
  170. package/dist/sig/mitra-send-interop.test.mjs +461 -0
  171. package/dist/sig/mod.cjs +18 -16
  172. package/dist/sig/mod.d.cts +4 -4
  173. package/dist/sig/mod.d.ts +4 -4
  174. package/dist/sig/mod.js +3 -3
  175. package/dist/sig/owner.test.mjs +108 -9
  176. package/dist/sig/portable-collection.test.d.mts +2 -0
  177. package/dist/sig/portable-collection.test.mjs +697 -0
  178. package/dist/sig/portable-interop.test.d.mts +2 -0
  179. package/dist/sig/portable-interop.test.mjs +156 -0
  180. package/dist/sig/portable-key-id.test.d.mts +2 -0
  181. package/dist/sig/portable-key-id.test.mjs +67 -0
  182. package/dist/sig/portable-key.test.d.mts +2 -0
  183. package/dist/sig/portable-key.test.mjs +1439 -0
  184. package/dist/sig/proof.test.mjs +1753 -16
  185. package/dist/sig/tootik-request-interop.test.d.mts +2 -0
  186. package/dist/sig/tootik-request-interop.test.mjs +190 -0
  187. package/dist/sig/tootik-send-interop.test.d.mts +2 -0
  188. package/dist/sig/tootik-send-interop.test.mjs +331 -0
  189. package/dist/sig/verification.test.d.mts +2 -0
  190. package/dist/sig/verification.test.mjs +310 -0
  191. package/dist/std__assert-DvMDRPes.mjs +8 -0
  192. package/dist/{testing-CO7ftO8A.mjs → tasks-IG3pHfvZ.mjs} +2 -2
  193. package/dist/{temporal-fsXO5IvD.mjs → temporal-D0KJI4NF.mjs} +3 -3
  194. package/dist/testing/context.test.d.mts +2 -0
  195. package/dist/testing/context.test.mjs +19 -0
  196. package/dist/testing/kv.test.d.mts +2 -0
  197. package/dist/testing/kv.test.mjs +101 -0
  198. package/dist/testing/mod.d.mts +1617 -48
  199. package/dist/testing/mod.mjs +6 -3
  200. package/dist/testing-t8xDeJZ5.mjs +8 -0
  201. package/dist/{transformers-DGwl-hD1.cjs → transformers-BalCrSsr.cjs} +0 -1
  202. package/dist/{types-DC1pNgJA.js → types-_S2_MeLF.js} +144 -8
  203. package/dist/{types-CPym83zc.cjs → types-poIao40f.cjs} +160 -7
  204. package/dist/utils/docloader.test.mjs +530 -8
  205. package/dist/utils/kv-cache.test.mjs +2 -2
  206. package/dist/utils/mod.cjs +1 -1
  207. package/dist/utils/mod.d.cts +1 -1
  208. package/dist/utils/mod.d.ts +1 -1
  209. package/dist/utils/mod.js +1 -1
  210. package/dist/verification-C3954hQh.mjs +5 -0
  211. package/dist/verification-Dpfcw8ml.mjs +105 -0
  212. package/dist/vocab/cjs.test.mjs +1 -1
  213. package/package.json +8 -8
  214. package/dist/assert_rejects-EgstcQy5.mjs +0 -82
  215. package/dist/docloader-e1khNUKy.mjs +0 -49
  216. package/dist/http-CsmQ-BQ4.js +0 -2483
  217. package/dist/http-VyDTd4G3.d.cts +0 -553
  218. package/dist/http-hlIjmewS.cjs +0 -2694
  219. package/dist/http-lf8Hsd91.d.ts +0 -553
  220. package/dist/key-DfPsX8hv.mjs +0 -453
  221. package/dist/keycache-_DHqz5z_.mjs +0 -97
  222. package/dist/metrics-CoUJLQhZ.d.cts +0 -276
  223. package/dist/metrics-Dc4jR-IC.d.ts +0 -276
  224. package/dist/mod-B0hW12_O.d.cts +0 -307
  225. package/dist/mod-COIAjwRS.d.ts +0 -307
  226. package/dist/owner-Br9YYzn_.mjs +0 -120
  227. package/dist/proof-B4ngoaNQ.mjs +0 -316
  228. package/dist/proof-B6E0XUXJ.js +0 -1415
  229. package/dist/proof-NN4xCQGL.cjs +0 -1562
  230. package/dist/send-CxHKUNzv.mjs +0 -239
  231. package/dist/std__assert-B2NnY9bq.mjs +0 -79
  232. package/dist/temporal-polyfill-BCdTHexd.cjs +0 -3565
  233. /package/dist/{accept-8PiolDP7.mjs → accept-CPVqki78.mjs} +0 -0
  234. /package/dist/{activity-listener-BtTSxZWA.mjs → activity-listener-C-BSbKI7.mjs} +0 -0
  235. /package/dist/{client-CAM_bQXx.d.cts → client-D-XP_Ccb.d.cts} +0 -0
  236. /package/dist/{client-CSddvgWN.d.ts → client-D-XP_Ccb.d.ts} +0 -0
  237. /package/dist/{keys-Dbyd7bhl.mjs → keys-DIJNHW-Y.mjs} +0 -0
  238. /package/dist/{kv-CXBAok3k.mjs → kv-DCHkaJ9-.mjs} +0 -0
  239. /package/dist/{negotiation-RuwrPFqi.mjs → negotiation-CCocWT_N.mjs} +0 -0
  240. /package/dist/{retry-DgFqeS5k.mjs → retry-zX5xw5e0.mjs} +0 -0
  241. /package/dist/{chunk-D5IdezsZ.js → rolldown-runtime-BC-Eo5Mj.js} +0 -0
  242. /package/dist/{chunk-Czpeue4M.cjs → rolldown-runtime-Dmm3t92W.cjs} +0 -0
  243. /package/dist/{transformers-DXze6FUB.js → transformers-DAtXl_Kc.js} +0 -0
  244. /package/dist/{types-CrtdVuDP.mjs → types-DE_LV1JB.mjs} +0 -0
@@ -1,1562 +0,0 @@
1
- const { URLPattern } = require("urlpattern-polyfill");
2
- const require_chunk = require("./chunk-Czpeue4M.cjs");
3
- const require_http = require("./http-hlIjmewS.cjs");
4
- const require_temporal_polyfill = require("./temporal-polyfill-BCdTHexd.cjs");
5
- let _logtape_logtape = require("@logtape/logtape");
6
- let _fedify_vocab = require("@fedify/vocab");
7
- let _opentelemetry_api = require("@opentelemetry/api");
8
- let byte_encodings_hex = require("byte-encodings/hex");
9
- let _fedify_vocab_runtime = require("@fedify/vocab-runtime");
10
- let byte_encodings_base64 = require("byte-encodings/base64");
11
- let _fedify_vocab_runtime_jsonld = require("@fedify/vocab-runtime/jsonld");
12
- _fedify_vocab_runtime_jsonld = require_chunk.__toESM(_fedify_vocab_runtime_jsonld, 1);
13
- let json_canon = require("json-canon");
14
- json_canon = require_chunk.__toESM(json_canon, 1);
15
- //#region src/sig/ld.ts
16
- const logger$3 = (0, _logtape_logtape.getLogger)([
17
- "fedify",
18
- "sig",
19
- "ld"
20
- ]);
21
- const localContext = [
22
- "https://w3id.org/identity/v1",
23
- "https://www.w3.org/ns/activitystreams",
24
- "https://w3id.org/security/v1",
25
- "https://w3id.org/security/data-integrity/v1"
26
- ];
27
- const localContextUrls = new Set(localContext);
28
- const builtInContextLoader = (0, _fedify_vocab_runtime.getDocumentLoader)();
29
- const disallowedJsonLdKeywords = new Set([
30
- "@graph",
31
- "@included",
32
- "@reverse"
33
- ]);
34
- /** @internal */
35
- var UnsafeJsonLdError = class extends TypeError {
36
- keyword;
37
- constructor(keyword) {
38
- super(`Unsupported JSON-LD keyword: ${keyword}.`);
39
- this.keyword = keyword;
40
- this.name = "UnsafeJsonLdError";
41
- }
42
- };
43
- /** @internal */
44
- var InvalidContextReferenceError = class extends TypeError {
45
- reference;
46
- constructor(reference) {
47
- super(`Invalid JSON-LD context reference: ${reference}.`);
48
- this.reference = reference;
49
- this.name = "InvalidContextReferenceError";
50
- }
51
- };
52
- function createLoadingRemoteContextFailedError(reference, cause) {
53
- const message = cause instanceof Error ? cause.message : String(cause);
54
- const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a valid JSON-LD context: ${reference}. ${message}`);
55
- error.name = "jsonld.InvalidUrl";
56
- error.details = {
57
- code: "loading remote context failed",
58
- url: reference
59
- };
60
- error.cause = cause;
61
- return error;
62
- }
63
- /** @internal */
64
- function isClearlyMalformedContextReference(reference) {
65
- for (const char of reference) {
66
- const code = char.charCodeAt(0);
67
- if (code <= 32 || code === 127) return true;
68
- }
69
- if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(reference) && !URL.canParse(reference)) return true;
70
- for (let i = 0; i < reference.length; i++) {
71
- if (reference[i] !== "%") continue;
72
- if (i + 2 >= reference.length || !/[0-9A-Fa-f]/.test(reference[i + 1]) || !/[0-9A-Fa-f]/.test(reference[i + 2])) return true;
73
- i += 2;
74
- }
75
- if (reference.startsWith("./") || reference.startsWith("../") || reference.startsWith("/") || reference.startsWith("//")) {
76
- for (const char of reference) if ("[]<>\"\\^`{|}".includes(char)) return true;
77
- }
78
- return false;
79
- }
80
- function cloneRemoteDocument(remoteDocument) {
81
- return structuredClone(remoteDocument);
82
- }
83
- function createMemoizedDocumentLoader(documentLoader) {
84
- const cache = /* @__PURE__ */ new Map();
85
- return async (url, options) => {
86
- const cacheKey = URL.canParse(url) ? new URL(url).href : url;
87
- let remoteDocument = cache.get(cacheKey);
88
- if (remoteDocument == null) {
89
- remoteDocument = Promise.resolve(documentLoader(url, options)).then(cloneRemoteDocument);
90
- remoteDocument.catch(() => {
91
- if (cache.get(cacheKey) === remoteDocument) cache.delete(cacheKey);
92
- });
93
- cache.set(cacheKey, remoteDocument);
94
- }
95
- return cloneRemoteDocument(await remoteDocument);
96
- };
97
- }
98
- /** @internal */
99
- function wrapContextLoaderForJsonLd(contextLoader) {
100
- const loader = contextLoader ?? builtInContextLoader;
101
- return async (url, options) => {
102
- try {
103
- return await loader(url, options);
104
- } catch (error) {
105
- if (!isInvalidUrlTypeError(error)) throw error;
106
- if (isClearlyMalformedContextReference(url)) throw new InvalidContextReferenceError(url);
107
- throw createLoadingRemoteContextFailedError(url, error);
108
- }
109
- };
110
- }
111
- /** @internal */
112
- function getNormalizationContextLoader(contextLoader) {
113
- const loader = wrapContextLoaderForJsonLd(contextLoader);
114
- return createMemoizedDocumentLoader(async (url, options) => {
115
- if (URL.canParse(url)) {
116
- const normalizedUrl = new URL(url).href;
117
- if (localContextUrls.has(normalizedUrl)) return await builtInContextLoader(normalizedUrl, options);
118
- }
119
- return await loader(url, options);
120
- });
121
- }
122
- /** @internal */
123
- async function compactJsonLd(jsonLd, contextLoader) {
124
- const hasLds = typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
125
- const signature = hasLds ? jsonLd.signature : void 0;
126
- const normalizationContextLoader = getNormalizationContextLoader(contextLoader);
127
- const document = hasLds ? detachSignature(jsonLd) : jsonLd;
128
- await assertNoGraphBeforeCompaction(document, normalizationContextLoader);
129
- const compacted = await _fedify_vocab_runtime_jsonld.default.compact(document, localContext, { documentLoader: normalizationContextLoader });
130
- if (hasLds && typeof compacted === "object" && compacted != null) compacted.signature = signature;
131
- assertSafeJsonLd(compacted);
132
- return compacted;
133
- }
134
- function createInvalidRemoteContextError(reference) {
135
- const error = /* @__PURE__ */ new Error(`Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object. URL: "${reference}".`);
136
- error.name = "jsonld.InvalidUrl";
137
- error.details = {
138
- code: "invalid remote context",
139
- url: reference
140
- };
141
- return error;
142
- }
143
- function getRemoteContext(remoteDocument, reference) {
144
- const { contextUrl, documentUrl } = remoteDocument;
145
- let { document } = remoteDocument;
146
- if (typeof document === "string") document = JSON.parse(document);
147
- if (typeof document !== "object" || document == null || Array.isArray(document)) throw createInvalidRemoteContextError(reference);
148
- let context = "@context" in document ? document["@context"] : {};
149
- if (contextUrl != null) context = Array.isArray(context) ? [...context, contextUrl] : [context, contextUrl];
150
- return {
151
- context,
152
- baseUrl: documentUrl ?? reference
153
- };
154
- }
155
- function createGraphAliasContextState() {
156
- return {
157
- graphTerms: /* @__PURE__ */ new Set(),
158
- jsonTerms: /* @__PURE__ */ new Set(),
159
- propertyContexts: /* @__PURE__ */ new Map(),
160
- termTargets: /* @__PURE__ */ new Map()
161
- };
162
- }
163
- function cloneGraphAliasContextState(state) {
164
- return {
165
- graphTerms: new Set(state.graphTerms),
166
- jsonTerms: new Set(state.jsonTerms),
167
- propertyContexts: new Map(state.propertyContexts),
168
- termTargets: new Map(state.termTargets)
169
- };
170
- }
171
- function resolveContextTarget(target, state) {
172
- if (target === "@graph") return target;
173
- const mapped = state.termTargets.get(target);
174
- if (mapped == null) return target;
175
- return mapped;
176
- }
177
- function getDirectContextTarget(definition) {
178
- if (definition === null) return null;
179
- if (typeof definition === "string") return definition;
180
- if (typeof definition === "object" && definition != null && "@id" in definition) {
181
- const id = definition["@id"];
182
- if (id === null) return null;
183
- if (typeof id === "string") return id;
184
- }
185
- }
186
- function isJsonTypedDefinition(definition) {
187
- return typeof definition === "object" && definition != null && "@type" in definition && definition["@type"] === "@json";
188
- }
189
- function resolveLocalContextTarget(target, state, localTargets, seen = /* @__PURE__ */ new Set()) {
190
- if (target === "@graph") return target;
191
- if (seen.has(target)) return target;
192
- seen.add(target);
193
- if (localTargets.has(target)) {
194
- const localTarget = localTargets.get(target);
195
- return localTarget == null ? target : resolveLocalContextTarget(localTarget, state, localTargets, seen);
196
- }
197
- return resolveContextTarget(target, state);
198
- }
199
- function refreshGraphAliases(state) {
200
- state.graphTerms.clear();
201
- for (const [term, target] of state.termTargets) if (target === "@graph") state.graphTerms.add(term);
202
- }
203
- function normalizeContextReference(reference, baseUrl) {
204
- if (baseUrl != null) return new URL(reference, baseUrl).href;
205
- return URL.canParse(reference) ? new URL(reference).href : reference;
206
- }
207
- /** @internal */
208
- function isInvalidUrlTypeError(error) {
209
- const code = error.code;
210
- return error instanceof TypeError && (code === "ERR_INVALID_URL" || /^Invalid URL(?::|$)/.test(error.message) || / cannot be parsed as a URL\.?$/.test(error.message));
211
- }
212
- async function applyGraphAliasContext(state, context, documentLoader, remoteContextCache, baseUrl = null, processingContexts = /* @__PURE__ */ new Set()) {
213
- if (context === null) return createGraphAliasContextState();
214
- let nextState = cloneGraphAliasContextState(state);
215
- if (Array.isArray(context)) {
216
- for (const item of context) nextState = await applyGraphAliasContext(nextState, item, documentLoader, remoteContextCache, baseUrl, processingContexts);
217
- return nextState;
218
- }
219
- if (typeof context === "string") {
220
- const reference = normalizeContextReference(context, baseUrl);
221
- const cacheKey = `${baseUrl ?? ""}\n${reference}`;
222
- if (processingContexts.has(cacheKey)) return nextState;
223
- processingContexts.add(cacheKey);
224
- try {
225
- let remoteContext = remoteContextCache.get(cacheKey);
226
- if (remoteContext == null) {
227
- remoteContext = (async () => {
228
- try {
229
- return getRemoteContext(await documentLoader(reference), reference);
230
- } catch (error) {
231
- if (reference === context && isInvalidUrlTypeError(error) && isClearlyMalformedContextReference(context)) throw new InvalidContextReferenceError(context);
232
- throw error;
233
- }
234
- })();
235
- remoteContextCache.set(cacheKey, remoteContext);
236
- }
237
- const loadedRemoteContext = await remoteContext;
238
- return await applyGraphAliasContext(nextState, loadedRemoteContext.context, documentLoader, remoteContextCache, loadedRemoteContext.baseUrl, processingContexts);
239
- } finally {
240
- processingContexts.delete(cacheKey);
241
- }
242
- }
243
- if (typeof context === "object" && context != null) {
244
- if ("@import" in context && typeof context["@import"] === "string") nextState = await applyGraphAliasContext(nextState, context["@import"], documentLoader, remoteContextCache, baseUrl, processingContexts);
245
- const localTargets = /* @__PURE__ */ new Map();
246
- for (const [term, definition] of globalThis.Object.entries(context)) {
247
- if (term.startsWith("@")) continue;
248
- const target = getDirectContextTarget(definition);
249
- if (target == null) localTargets.set(term, null);
250
- else if (typeof target === "string") localTargets.set(term, target);
251
- else localTargets.delete(term);
252
- }
253
- for (const [term, definition] of globalThis.Object.entries(context)) {
254
- if (term.startsWith("@")) continue;
255
- if (localTargets.has(term)) {
256
- const directTarget = localTargets.get(term);
257
- if (directTarget == null) nextState.termTargets.set(term, null);
258
- else nextState.termTargets.set(term, resolveLocalContextTarget(directTarget, nextState, localTargets));
259
- } else nextState.termTargets.delete(term);
260
- if (typeof definition === "object" && definition != null && "@context" in definition) nextState.propertyContexts.set(term, {
261
- context: definition["@context"],
262
- baseUrl
263
- });
264
- else nextState.propertyContexts.delete(term);
265
- if (isJsonTypedDefinition(definition)) nextState.jsonTerms.add(term);
266
- else nextState.jsonTerms.delete(term);
267
- }
268
- refreshGraphAliases(nextState);
269
- }
270
- return nextState;
271
- }
272
- async function assertNoGraphBeforeCompaction(jsonLd, documentLoader, inheritedState = createGraphAliasContextState(), propertyContext, remoteContextCache = /* @__PURE__ */ new Map()) {
273
- if (Array.isArray(jsonLd)) {
274
- for (const item of jsonLd) await assertNoGraphBeforeCompaction(item, documentLoader, inheritedState, propertyContext, remoteContextCache);
275
- return;
276
- }
277
- if (typeof jsonLd !== "object" || jsonLd == null) return;
278
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
279
- let state = inheritedState;
280
- if (propertyContext !== void 0) state = await applyGraphAliasContext(state, propertyContext.context, documentLoader, remoteContextCache, propertyContext.baseUrl);
281
- if ("@context" in jsonLd) state = await applyGraphAliasContext(state, jsonLd["@context"], documentLoader, remoteContextCache);
282
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
283
- if (key === "@context") continue;
284
- if (jsonLiteralWrapper && key === "@value") continue;
285
- if (key === "@graph" || state.graphTerms.has(key)) throw new UnsafeJsonLdError("@graph");
286
- if (state.jsonTerms.has(key)) continue;
287
- await assertNoGraphBeforeCompaction(value, documentLoader, state, state.propertyContexts.get(key), remoteContextCache);
288
- }
289
- }
290
- function isJsonLiteralWrapper(value) {
291
- return "@value" in value && (value["@type"] === "@json" || value.type === "@json");
292
- }
293
- /** @internal */
294
- function assertSafeJsonLd(jsonLd) {
295
- if (Array.isArray(jsonLd)) for (const item of jsonLd) assertSafeJsonLd(item);
296
- else if (typeof jsonLd === "object" && jsonLd != null) {
297
- const jsonLiteralWrapper = isJsonLiteralWrapper(jsonLd);
298
- for (const [key, value] of globalThis.Object.entries(jsonLd)) {
299
- if (disallowedJsonLdKeywords.has(key)) throw new UnsafeJsonLdError(key);
300
- if (jsonLiteralWrapper && key === "@value") continue;
301
- assertSafeJsonLd(value);
302
- }
303
- }
304
- }
305
- /**
306
- * Attaches a LD signature to the given JSON-LD document.
307
- * @param jsonLd The JSON-LD document to attach the signature to. It is not
308
- * modified.
309
- * @param signature The signature to attach.
310
- * @returns The JSON-LD document with the attached signature.
311
- * @throws {TypeError} If the input document is not a valid JSON-LD document.
312
- * @since 1.0.0
313
- */
314
- function attachSignature(jsonLd, signature) {
315
- if (typeof jsonLd !== "object" || jsonLd == null) throw new TypeError("Failed to attach signature; invalid JSON-LD document.");
316
- return {
317
- ...jsonLd,
318
- signature
319
- };
320
- }
321
- /**
322
- * Creates a LD signature for the given JSON-LD document.
323
- * @param jsonLd The JSON-LD document to sign.
324
- * @param privateKey The private key to sign the document.
325
- * @param keyId The ID of the public key that corresponds to the private key.
326
- * @param options Additional options for creating the signature.
327
- * See also {@link CreateSignatureOptions}.
328
- * @return The created signature.
329
- * @throws {TypeError} If the private key is invalid or unsupported.
330
- * @since 1.0.0
331
- */
332
- async function createSignature(jsonLd, privateKey, keyId, { contextLoader, created } = {}) {
333
- require_http.validateCryptoKey(privateKey, "private");
334
- if (privateKey.algorithm.name !== "RSASSA-PKCS1-v1_5") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
335
- const options = {
336
- "@context": "https://w3id.org/identity/v1",
337
- creator: keyId.href,
338
- created: created?.toString() ?? (/* @__PURE__ */ new Date()).toISOString()
339
- };
340
- const message = await hashJsonLd(options, contextLoader) + await hashJsonLd(jsonLd, contextLoader);
341
- const messageBytes = new TextEncoder().encode(message);
342
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, messageBytes);
343
- return {
344
- ...options,
345
- type: "RsaSignature2017",
346
- signatureValue: (0, byte_encodings_base64.encodeBase64)(signature)
347
- };
348
- }
349
- /**
350
- * Signs the given JSON-LD document with the private key and returns the signed
351
- * JSON-LD document.
352
- * @param jsonLd The JSON-LD document to sign.
353
- * @param privateKey The private key to sign the document.
354
- * @param keyId The key ID to use in the signature. It will be used by the
355
- * verifier to fetch the corresponding public key.
356
- * @param options Additional options for signing the document.
357
- * See also {@link SignJsonLdOptions}.
358
- * @returns The signed JSON-LD document.
359
- * @throws {TypeError} If the private key is invalid or unsupported.
360
- * @since 1.0.0
361
- */
362
- async function signJsonLd(jsonLd, privateKey, keyId, options) {
363
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.sign", { attributes: { "ld_signatures.key_id": keyId.href } }, async (span) => {
364
- try {
365
- const signature = await createSignature(jsonLd, privateKey, keyId, options);
366
- if (span.isRecording()) {
367
- span.setAttribute("ld_signatures.type", signature.type);
368
- span.setAttribute("ld_signatures.signature", (0, byte_encodings_hex.encodeHex)((0, byte_encodings_base64.decodeBase64)(signature.signatureValue)));
369
- }
370
- return attachSignature(jsonLd, signature);
371
- } catch (error) {
372
- span.setStatus({
373
- code: _opentelemetry_api.SpanStatusCode.ERROR,
374
- message: String(error)
375
- });
376
- throw error;
377
- } finally {
378
- span.end();
379
- }
380
- });
381
- }
382
- /**
383
- * Checks if the given JSON-LD document has a Linked Data Signature-like
384
- * object, without restricting it to a single suite-specific shape.
385
- * @param jsonLd The JSON-LD document to check.
386
- * @returns `true` if the document has a signature-like object; `false`
387
- * otherwise.
388
- * @since 2.2.0
389
- */
390
- function hasSignatureLike(jsonLd) {
391
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
392
- const signature = jsonLd.signature;
393
- const hasReference = (value) => {
394
- if (typeof value === "string") return true;
395
- if (Array.isArray(value)) return value.some(hasReference);
396
- return typeof value === "object" && value != null && ("id" in value && typeof value.id === "string" || "@id" in value && typeof value["@id"] === "string");
397
- };
398
- const hasSignatureObject = (value) => {
399
- if (typeof value !== "object" || value == null) return false;
400
- const signatureRecord = value;
401
- return (typeof signatureRecord.type === "string" || Array.isArray(signatureRecord.type) && signatureRecord.type.some((item) => typeof item === "string")) && (hasReference(signatureRecord.creator) || hasReference(signatureRecord.verificationMethod)) && (typeof signatureRecord.signatureValue === "string" || typeof signatureRecord.jws === "string");
402
- };
403
- return Array.isArray(signature) ? signature.some(hasSignatureObject) : hasSignatureObject(signature);
404
- }
405
- /**
406
- * Checks if the given JSON-LD document has a Linked Data Signature.
407
- * @param jsonLd The JSON-LD document to check.
408
- * @returns `true` if the document has a signature; `false` otherwise.
409
- * @since 1.0.0
410
- */
411
- function hasSignature(jsonLd) {
412
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
413
- if ("signature" in jsonLd) {
414
- const signature = jsonLd.signature;
415
- if (typeof signature !== "object" || signature == null) return false;
416
- return "type" in signature && signature.type === "RsaSignature2017" && "creator" in signature && typeof signature.creator === "string" && "created" in signature && typeof signature.created === "string" && "signatureValue" in signature && typeof signature.signatureValue === "string";
417
- }
418
- return false;
419
- }
420
- /**
421
- * Detaches Linked Data Signatures from the given JSON-LD document.
422
- * @param jsonLd The JSON-LD document to modify.
423
- * @returns The modified JSON-LD document. If the input document does not
424
- * contain a signature, the original document is returned.
425
- * @since 1.0.0
426
- */
427
- function detachSignature(jsonLd) {
428
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
429
- const doc = { ...jsonLd };
430
- delete doc.signature;
431
- return doc;
432
- }
433
- /**
434
- * Verifies Linked Data Signatures of the given JSON-LD document.
435
- *
436
- * This is a low-level utility that only checks the cryptographic signature
437
- * and (optionally) the cached key. It does not run the JSON-LD parsing,
438
- * attribution, and owner checks that a complete inbound LD verification
439
- * needs. For incoming activities, prefer {@link verifyJsonLd}, which is
440
- * the public verification entry point and the one that emits the
441
- * `activitypub.signature.verification.duration` metric for the LD path.
442
- * `verifySignature` itself only emits
443
- * `activitypub.signature.key_fetch.duration`, since the rest of the work
444
- * that the verification-duration metric is meant to cover happens in
445
- * `verifyJsonLd`.
446
- * @param jsonLd The JSON-LD document to verify.
447
- * @param options Options for verifying the signature.
448
- * @returns The public key that signed the document or `null` if the signature
449
- * is invalid or the key is not found.
450
- * @since 1.0.0
451
- */
452
- async function verifySignature(jsonLd, options = {}) {
453
- if (!hasSignature(jsonLd)) return null;
454
- const sig = jsonLd.signature;
455
- let signature;
456
- try {
457
- signature = (0, byte_encodings_base64.decodeBase64)(sig.signatureValue);
458
- } catch (error) {
459
- logger$3.debug("Failed to verify; invalid base64 signatureValue: {signatureValue}", {
460
- ...sig,
461
- error
462
- });
463
- return null;
464
- }
465
- const { key, cached } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, options));
466
- if (key == null) return null;
467
- const sigOpts = {
468
- ...sig,
469
- "@context": "https://w3id.org/identity/v1"
470
- };
471
- delete sigOpts.type;
472
- delete sigOpts.id;
473
- delete sigOpts.signatureValue;
474
- let sigOptsHash;
475
- try {
476
- sigOptsHash = await hashJsonLd(sigOpts, options.contextLoader);
477
- } catch (error) {
478
- logger$3.warn("Failed to verify; failed to hash the signature options: {signatureOptions}\n{error}", {
479
- signatureOptions: sigOpts,
480
- error
481
- });
482
- return null;
483
- }
484
- const document = { ...jsonLd };
485
- delete document.signature;
486
- let docHash;
487
- try {
488
- docHash = await hashJsonLd(document, options.contextLoader);
489
- } catch (error) {
490
- logger$3.warn("Failed to verify; failed to hash the document: {document}\n{error}", {
491
- document,
492
- error
493
- });
494
- return null;
495
- }
496
- const encoder = new TextEncoder();
497
- const message = sigOptsHash + docHash;
498
- const messageBytes = encoder.encode(message);
499
- if (await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes)) return key;
500
- if (cached) {
501
- logger$3.debug("Failed to verify with the cached key {keyId}; signature {signatureValue} is invalid. Retrying with the freshly fetched key...", {
502
- keyId: sig.creator,
503
- ...sig
504
- });
505
- const { key } = await require_http.measureSignatureKeyFetch(options.meterProvider, "linked_data", () => require_http.fetchKey(new URL(sig.creator), _fedify_vocab.CryptographicKey, {
506
- ...options,
507
- keyCache: {
508
- get: () => Promise.resolve(void 0),
509
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
510
- }
511
- }));
512
- if (key == null) return null;
513
- return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key.publicKey, signature.slice(), messageBytes) ? key : null;
514
- }
515
- 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}", {
516
- keyId: sig.creator,
517
- ...sig,
518
- message
519
- });
520
- return null;
521
- }
522
- /**
523
- * Known Linked Data Signature `type` values, used to keep
524
- * `ld_signatures.type` on a bounded set of spec-defined string values.
525
- * Fedify only signs and verifies `RsaSignature2017`; other values come in
526
- * only from external documents and are dropped from the metric attribute to
527
- * avoid attacker-controlled cardinality.
528
- */
529
- const LD_KNOWN_SIGNATURE_TYPES = new Set(["RsaSignature2017"]);
530
- /**
531
- * Reports only whether a `signature` key is present on the document, with
532
- * no shape check on its value. This is intentionally looser than
533
- * {@link hasSignature} (which validates a full `RsaSignature2017` shape)
534
- * and {@link hasSignatureLike} (which structurally accepts several known
535
- * suites): `verifyJsonLd` needs to tell a document with a malformed or
536
- * unsupported signature payload (classified as `rejected`) apart from a
537
- * truly unsigned document (classified as `missing`), and only this
538
- * presence-only check captures both cases.
539
- */
540
- function hasLdSignatureProperty(jsonLd) {
541
- return typeof jsonLd === "object" && jsonLd != null && "signature" in jsonLd;
542
- }
543
- function getLdSignatureObject(jsonLd) {
544
- if (!hasLdSignatureProperty(jsonLd)) return void 0;
545
- const { signature } = jsonLd;
546
- if (typeof signature !== "object" || signature == null || Array.isArray(signature)) return;
547
- return signature;
548
- }
549
- /**
550
- * Verify the authenticity of the given JSON-LD document using Linked Data
551
- * Signatures. If the document is signed, this function verifies the signature
552
- * and checks if the document is attributed to the owner of the public key.
553
- * If the document is not signed, this function returns `false`.
554
- * @param jsonLd The JSON-LD document to verify.
555
- * @param options Options for verifying the document.
556
- * @returns `true` if the document is authentic; `false` otherwise.
557
- */
558
- async function verifyJsonLd(jsonLd, options = {}) {
559
- return await verifyJsonLdInternal(jsonLd, options, true);
560
- }
561
- /** @internal */
562
- async function verifyCompactJsonLd(jsonLd, options = {}) {
563
- return await verifyJsonLdInternal(jsonLd, options, false);
564
- }
565
- async function verifyJsonLdInternal(jsonLd, options, compact) {
566
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("ld_signatures.verify", async (span) => {
567
- const start = performance.now();
568
- let verified = false;
569
- let threw = false;
570
- let signatureType;
571
- try {
572
- const verificationOptions = hasSignature(jsonLd) ? {
573
- ...options,
574
- contextLoader: getNormalizationContextLoader(options.contextLoader)
575
- } : options;
576
- const compacted = compact ? hasSignature(jsonLd) ? await compactJsonLd(jsonLd, options.contextLoader) : jsonLd : jsonLd;
577
- const object = await _fedify_vocab.Object.fromJsonLd(compacted, verificationOptions);
578
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
579
- span.setAttribute("activitypub.object.type", (0, _fedify_vocab.getTypeId)(object).href);
580
- const sig = getLdSignatureObject(jsonLd);
581
- if (sig != null) {
582
- if (typeof sig.creator === "string") span.setAttribute("ld_signatures.key_id", sig.creator);
583
- if (typeof sig.signatureValue === "string") span.setAttribute("ld_signatures.signature", sig.signatureValue);
584
- if (typeof sig.type === "string") {
585
- span.setAttribute("ld_signatures.type", sig.type);
586
- if (LD_KNOWN_SIGNATURE_TYPES.has(sig.type)) signatureType = sig.type;
587
- }
588
- }
589
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
590
- if (object instanceof _fedify_vocab.Activity) for (const uri of object.actorIds) attributions.add(uri.href);
591
- const key = await verifySignature(compacted, verificationOptions);
592
- if (key == null) return false;
593
- if (key.ownerId == null) {
594
- logger$3.debug("Key {keyId} has no owner.", { keyId: key.id?.href });
595
- return false;
596
- }
597
- attributions.delete(key.ownerId.href);
598
- if (attributions.size > 0) {
599
- logger$3.debug("Some attributions are not authenticated by the Linked Data Signatures: {attributions}.", { attributions: [...attributions] });
600
- return false;
601
- }
602
- verified = true;
603
- return true;
604
- } catch (error) {
605
- threw = true;
606
- span.setStatus({
607
- code: _opentelemetry_api.SpanStatusCode.ERROR,
608
- message: String(error)
609
- });
610
- throw error;
611
- } finally {
612
- const classified = threw ? "error" : verified ? "verified" : hasLdSignatureProperty(jsonLd) ? "rejected" : "missing";
613
- require_http.getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(require_http.getDurationMs(start), "linked_data", classified, { ldType: signatureType });
614
- span.end();
615
- }
616
- });
617
- }
618
- async function hashJsonLd(jsonLd, contextLoader) {
619
- const canon = await _fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
620
- format: "application/n-quads",
621
- documentLoader: contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)()
622
- });
623
- const encoder = new TextEncoder();
624
- return (0, byte_encodings_hex.encodeHex)(await crypto.subtle.digest("SHA-256", encoder.encode(canon)));
625
- }
626
- //#endregion
627
- //#region src/sig/owner.ts
628
- /**
629
- * Checks if the actor of the given activity owns the specified key.
630
- * @param activity The activity to check.
631
- * @param key The public key to check.
632
- * @param options Options for checking the key ownership.
633
- * @returns Whether the actor is the owner of the key.
634
- */
635
- async function doesActorOwnKey(activity, key, options) {
636
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("activitypub.verify_key_ownership", {
637
- kind: _opentelemetry_api.SpanKind.INTERNAL,
638
- attributes: {
639
- "activitypub.actor.id": activity.actorId?.href ?? "",
640
- "activitypub.key.id": key.id?.href ?? ""
641
- }
642
- }, async (span) => {
643
- try {
644
- if (key.ownerId != null) {
645
- const owns = key.ownerId.href === activity.actorId?.href;
646
- span.setAttribute("activitypub.key_ownership.verified", owns);
647
- span.setAttribute("activitypub.key_ownership.method", "owner_id");
648
- return owns;
649
- }
650
- const actor = await activity.getActor(options);
651
- if (actor == null || !(0, _fedify_vocab.isActor)(actor)) {
652
- span.setAttribute("activitypub.key_ownership.verified", false);
653
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
654
- return false;
655
- }
656
- for (const publicKeyId of actor.publicKeyIds) if (key.id != null && publicKeyId.href === key.id.href) {
657
- span.setAttribute("activitypub.key_ownership.verified", true);
658
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
659
- return true;
660
- }
661
- span.setAttribute("activitypub.key_ownership.verified", false);
662
- span.setAttribute("activitypub.key_ownership.method", "actor_fetch");
663
- return false;
664
- } catch (error) {
665
- span.recordException(error);
666
- span.setStatus({
667
- code: _opentelemetry_api.SpanStatusCode.ERROR,
668
- message: String(error)
669
- });
670
- throw error;
671
- } finally {
672
- span.end();
673
- }
674
- });
675
- }
676
- /**
677
- * Gets the actor that owns the specified key. Returns `null` if the key has no
678
- * known owner.
679
- *
680
- * @param keyId The ID of the key to check, or the key itself.
681
- * @param options Options for getting the key owner.
682
- * @returns The actor that owns the key, or `null` if the key has no known
683
- * owner.
684
- * @since 0.7.0
685
- */
686
- async function getKeyOwner(keyId, options) {
687
- const tracerProvider = options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
688
- const documentLoader = options.documentLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
689
- const contextLoader = options.contextLoader ?? (0, _fedify_vocab_runtime.getDocumentLoader)();
690
- let object;
691
- if (keyId instanceof _fedify_vocab.CryptographicKey) {
692
- object = keyId;
693
- if (object.id == null) return null;
694
- keyId = object.id;
695
- } else {
696
- let keyDoc;
697
- try {
698
- const { document } = await documentLoader(keyId.href);
699
- keyDoc = document;
700
- } catch (_) {
701
- return null;
702
- }
703
- try {
704
- object = await _fedify_vocab.Object.fromJsonLd(keyDoc, {
705
- documentLoader,
706
- contextLoader,
707
- tracerProvider
708
- });
709
- } catch (e) {
710
- if (!(e instanceof TypeError)) throw e;
711
- try {
712
- object = await _fedify_vocab.CryptographicKey.fromJsonLd(keyDoc, {
713
- documentLoader,
714
- contextLoader,
715
- tracerProvider
716
- });
717
- } catch (e) {
718
- if (e instanceof TypeError) return null;
719
- throw e;
720
- }
721
- }
722
- }
723
- let owner = null;
724
- if (object instanceof _fedify_vocab.CryptographicKey) {
725
- if (object.ownerId == null) return null;
726
- owner = await object.getOwner({
727
- documentLoader,
728
- contextLoader,
729
- tracerProvider
730
- });
731
- } else if ((0, _fedify_vocab.isActor)(object)) owner = object;
732
- else return null;
733
- if (owner == null) return null;
734
- for (const kid of owner.publicKeyIds) if (kid.href === keyId.href) return owner;
735
- return null;
736
- }
737
- //#endregion
738
- //#region src/compat/preloaded-context-loader.ts
739
- /**
740
- * A restricted JSON-LD document loader that resolves only contexts bundled
741
- * with Fedify.
742
- *
743
- * This is intentionally narrower than `getDocumentLoader()`: normalization
744
- * helpers are also reached from verification paths that operate on inbound,
745
- * attacker-controlled JSON-LD, so the default fallback must never fetch
746
- * attacker-supplied context URLs.
747
- */
748
- const preloadedOnlyDocumentLoader = (url) => {
749
- if (Object.hasOwn(_fedify_vocab_runtime.preloadedContexts, url)) return Promise.resolve({
750
- contextUrl: null,
751
- documentUrl: url,
752
- document: _fedify_vocab_runtime.preloadedContexts[url]
753
- });
754
- return Promise.reject(/* @__PURE__ */ new Error("Refusing to fetch a non-preloaded JSON-LD context: " + url));
755
- };
756
- //#endregion
757
- //#region src/compat/public-audience.ts
758
- const logger$2 = (0, _logtape_logtape.getLogger)([
759
- "fedify",
760
- "compat",
761
- "public-audience"
762
- ]);
763
- const PUBLIC_ADDRESSING_FIELDS = new Set([
764
- "to",
765
- "cc",
766
- "bto",
767
- "bcc",
768
- "audience"
769
- ]);
770
- const AS_CONTEXT_URL$1 = "https://www.w3.org/ns/activitystreams";
771
- const MAX_TRAVERSAL_DEPTH$1 = 64;
772
- const KNOWN_SAFE_CONTEXT_URLS$1 = new Set(Object.keys(_fedify_vocab_runtime.preloadedContexts));
773
- function hasPublicCurieInAddressing(value, parentKey, depth = 0) {
774
- if (typeof value === "string") return parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public");
775
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return false;
776
- if (Array.isArray(value)) return value.some((item) => hasPublicCurieInAddressing(item, parentKey, depth + 1));
777
- if (typeof value !== "object" || value == null) return false;
778
- const record = value;
779
- for (const key of Object.keys(record)) {
780
- if (key === "@context") continue;
781
- if (hasPublicCurieInAddressing(record[key], key, depth + 1)) return true;
782
- }
783
- return false;
784
- }
785
- function rewritePublicAudience(value, parentKey, depth = 0) {
786
- if (typeof value === "string" && parentKey != null && PUBLIC_ADDRESSING_FIELDS.has(parentKey) && (value === "as:Public" || value === "Public")) return _fedify_vocab.PUBLIC_COLLECTION.href;
787
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return value;
788
- if (Array.isArray(value)) {
789
- let changed = false;
790
- const mapped = value.map((item) => {
791
- const rewritten = rewritePublicAudience(item, parentKey, depth + 1);
792
- if (rewritten !== item) changed = true;
793
- return rewritten;
794
- });
795
- return changed ? mapped : value;
796
- }
797
- if (typeof value !== "object" || value == null) return value;
798
- const record = value;
799
- let changed = false;
800
- const normalized = Object.create(null);
801
- for (const key of Object.keys(record)) {
802
- const rewritten = key === "@context" ? record[key] : rewritePublicAudience(record[key], key, depth + 1);
803
- if (rewritten !== record[key]) changed = true;
804
- normalized[key] = rewritten;
805
- }
806
- return changed ? normalized : value;
807
- }
808
- /**
809
- * Reports whether `value` carries an `@context` property anywhere inside
810
- * its subtree (not counting the value itself). A nested `@context` can
811
- * introduce a local term-definition scope that redefines `as:` or `Public`
812
- * even when the top-level `@context` is safe, so the fast path must defer
813
- * to the URDNA2015 equivalence check whenever one is present.
814
- */
815
- function hasNestedContext$1(value, depth = 0) {
816
- if (depth >= MAX_TRAVERSAL_DEPTH$1) return true;
817
- if (Array.isArray(value)) return value.some((item) => hasNestedContext$1(item, depth + 1));
818
- if (typeof value !== "object" || value == null) return false;
819
- const record = value;
820
- for (const key of Object.keys(record)) {
821
- if (key === "@context") return true;
822
- if (hasNestedContext$1(record[key], depth + 1)) return true;
823
- }
824
- return false;
825
- }
826
- /**
827
- * Checks whether the `@context` of a JSON-LD document is guaranteed not
828
- * to redefine the `as:` prefix or the bare `Public` term. Only documents
829
- * whose `@context` is a string, or an array of strings, drawn from Fedify's
830
- * preloaded context set AND including the ActivityStreams URL qualify,
831
- * AND no nested subtree carries its own `@context` that might redefine
832
- * those terms within a local scope. When all of that holds the rewrite
833
- * is provably semantics-preserving and the URDNA2015 equivalence check
834
- * can be skipped. Any other shape (unknown external URLs, inline
835
- * objects at the top level, nested `@context` blocks) is treated as
836
- * potentially unsafe.
837
- */
838
- function hasKnownSafeContext$1(jsonLd) {
839
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
840
- const record = jsonLd;
841
- if (!Object.hasOwn(record, "@context")) return false;
842
- const ctx = record["@context"];
843
- const entries = typeof ctx === "string" ? [ctx] : Array.isArray(ctx) ? ctx : null;
844
- if (entries == null || entries.length === 0) return false;
845
- let hasAs = false;
846
- for (const entry of entries) {
847
- if (typeof entry !== "string") return false;
848
- if (!KNOWN_SAFE_CONTEXT_URLS$1.has(entry)) return false;
849
- if (entry === AS_CONTEXT_URL$1) hasAs = true;
850
- }
851
- if (!hasAs) return false;
852
- for (const key of Object.keys(record)) {
853
- if (key === "@context") continue;
854
- if (hasNestedContext$1(record[key])) return false;
855
- }
856
- return true;
857
- }
858
- /**
859
- * Rewrites the compact `as:Public` / `Public` CURIE appearing in activity
860
- * addressing fields (`to`, `cc`, `bto`, `bcc`, `audience`) to the fully
861
- * expanded `https://www.w3.org/ns/activitystreams#Public` URI.
862
- *
863
- * Several ActivityPub implementations, Lemmy among them, match these
864
- * fields as plain URLs without running JSON-LD expansion, and silently
865
- * drop activities whose public addressing appears in CURIE form. This
866
- * helper works around that gap.
867
- *
868
- * For documents whose `@context` is drawn entirely from Fedify's
869
- * preloaded context set and includes the ActivityStreams URL, the
870
- * rewrite is applied directly: the content of every preloaded non-AS
871
- * context is known not to redefine the `as:` prefix or the bare `Public`
872
- * term, so the semantics are preserved by construction. Any other
873
- * shape (an inline object, an unknown external URL, and so on) is
874
- * treated as potentially unsafe and gated on a JSON-LD equivalence
875
- * check; both forms are canonicalized with URDNA2015 and the resulting
876
- * N-Quads are compared. When they differ, the original document is
877
- * returned unchanged. Canonicalization failures also fall back to the
878
- * original document.
879
- *
880
- * When no `contextLoader` is supplied the helper falls back to an
881
- * internal loader that resolves only the URLs in Fedify's
882
- * preloaded-contexts set and rejects every other URL without issuing a
883
- * network request. That behaviour is deliberately narrower than
884
- * `@fedify/vocab-runtime`'s `getDocumentLoader()`, which after its
885
- * `validatePublicUrl` check will happily fetch non-preloaded URLs: the
886
- * helper is reached from verification paths (`verifyProof()` /
887
- * `verifyObject()`) that operate on inbound, potentially adversarial
888
- * JSON-LD, and a default loader that fetches attacker-supplied
889
- * `@context` URLs on the caller's behalf would be an SSRF vector.
890
- * Canonicalization failures against the restricted loader fall back to
891
- * the original document, same as any other canonicalization error.
892
- * Callers that genuinely need the remote-fetch loader (for example
893
- * applications that sign local JSON-LD against a custom vocabulary)
894
- * should pass a `contextLoader` explicitly.
895
- *
896
- * Must be called before any signing step that canonicalizes the
897
- * compact form byte-for-byte (for example, Object Integrity Proofs
898
- * using the `eddsa-jcs-2022` cryptosuite), so the signed payload
899
- * matches what is sent on the wire.
900
- */
901
- async function normalizePublicAudience(jsonLd, contextLoader) {
902
- if (!hasPublicCurieInAddressing(jsonLd)) return jsonLd;
903
- const normalized = rewritePublicAudience(jsonLd);
904
- if (hasKnownSafeContext$1(jsonLd)) return normalized;
905
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
906
- try {
907
- const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
908
- format: "application/n-quads",
909
- documentLoader: loader
910
- }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
911
- format: "application/n-quads",
912
- documentLoader: loader
913
- })]);
914
- if (before === after) return normalized;
915
- logger$2.warn("Expanding the public audience CURIE to its full URI would change the canonical form of the activity; sending the activity as is. This usually means the active JSON-LD context redefines the `as:` prefix or the bare `Public` term.");
916
- } catch (error) {
917
- logger$2.debug("Failed to verify public audience normalization equivalence via JSON-LD canonicalization; sending the activity as is.\n{error}", { error });
918
- }
919
- return jsonLd;
920
- }
921
- //#endregion
922
- //#region src/compat/outgoing-jsonld.ts
923
- const logger$1 = (0, _logtape_logtape.getLogger)([
924
- "fedify",
925
- "compat",
926
- "outgoing-jsonld"
927
- ]);
928
- const ATTACHMENT_FIELDS = new Set(["attachment", "https://www.w3.org/ns/activitystreams#attachment"]);
929
- const AS_CONTEXT_URL = "https://www.w3.org/ns/activitystreams";
930
- const KNOWN_SAFE_CONTEXT_URLS = getKnownSafeContextUrls();
931
- const MAX_TRAVERSAL_DEPTH = 64;
932
- function isJsonLdListObject(value) {
933
- return typeof value === "object" && value != null && Object.hasOwn(value, "@list");
934
- }
935
- function isJsonLdValueObject(value) {
936
- return typeof value === "object" && value != null && Object.hasOwn(value, "@value");
937
- }
938
- function* getContextObjects(value, seen = /* @__PURE__ */ new WeakSet()) {
939
- if (Array.isArray(value)) {
940
- if (seen.has(value)) return;
941
- seen.add(value);
942
- for (const item of value) yield* getContextObjects(item, seen);
943
- return;
944
- }
945
- if (typeof value === "object" && value != null) {
946
- if (seen.has(value)) return;
947
- seen.add(value);
948
- const record = value;
949
- yield record;
950
- for (const definition of Object.values(record)) {
951
- if (typeof definition !== "object" || definition == null) continue;
952
- const nestedContext = definition["@context"];
953
- if (nestedContext == null) continue;
954
- yield* getContextObjects(nestedContext, seen);
955
- }
956
- }
957
- }
958
- function isActivityStreamsAttachmentTerm(value) {
959
- return typeof value === "object" && value != null && value["@id"] === "as:attachment" && value["@type"] === "@id";
960
- }
961
- /** @internal */
962
- function isPreloadedContextAttachmentSafe(document) {
963
- if (typeof document !== "object" || document == null) return true;
964
- const context = document["@context"];
965
- for (const contextObject of getContextObjects(context)) {
966
- if (!Object.hasOwn(contextObject, "attachment")) continue;
967
- if (isActivityStreamsAttachmentTerm(contextObject.attachment)) continue;
968
- return false;
969
- }
970
- return true;
971
- }
972
- function getKnownSafeContextUrls() {
973
- const urls = /* @__PURE__ */ new Set();
974
- for (const [url, document] of Object.entries(_fedify_vocab_runtime.preloadedContexts)) if (isPreloadedContextAttachmentSafe(document)) urls.add(url);
975
- else logger$1.warn("Preloaded JSON-LD context {contextUrl} redefines the `attachment` term incompatibly; attachment array normalization will require canonicalization for documents using it.", { contextUrl: url });
976
- return urls;
977
- }
978
- /**
979
- * Wraps scalar ActivityStreams attachment properties in arrays.
980
- */
981
- function wrapScalarAttachments(jsonLd, depth = 0) {
982
- if (depth >= MAX_TRAVERSAL_DEPTH) return jsonLd;
983
- if (Array.isArray(jsonLd)) {
984
- let normalized = null;
985
- for (let i = 0; i < jsonLd.length; i++) {
986
- const item = jsonLd[i];
987
- const next = wrapScalarAttachments(item, depth + 1);
988
- if (normalized == null && next !== item) normalized = jsonLd.slice(0, i);
989
- if (normalized != null) normalized[i] = next;
990
- }
991
- return normalized ?? jsonLd;
992
- }
993
- if (typeof jsonLd !== "object" || jsonLd == null) return jsonLd;
994
- const record = jsonLd;
995
- const keys = Object.keys(record);
996
- let normalized = null;
997
- for (let i = 0; i < keys.length; i++) {
998
- const key = keys[i];
999
- const value = record[key];
1000
- const next = key === "@context" || key === "@value" && isJsonLdValueObject(jsonLd) ? value : wrapScalarAttachments(value, depth + 1);
1001
- const output = ATTACHMENT_FIELDS.has(key) && next != null && !Array.isArray(next) && !isJsonLdListObject(next) ? [next] : next;
1002
- if (normalized == null && output !== value) {
1003
- const cloned = Object.create(null);
1004
- for (let j = 0; j < i; j++) {
1005
- const previousKey = keys[j];
1006
- cloned[previousKey] = record[previousKey];
1007
- }
1008
- normalized = cloned;
1009
- }
1010
- if (normalized != null) normalized[key] = output;
1011
- }
1012
- return normalized ?? jsonLd;
1013
- }
1014
- function hasNestedContext(value, depth = 0) {
1015
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
1016
- if (Array.isArray(value)) return value.some((item) => hasNestedContext(item, depth + 1));
1017
- if (typeof value !== "object" || value == null) return false;
1018
- const record = value;
1019
- for (const key of Object.keys(record)) {
1020
- if (key === "@context") return true;
1021
- if (key === "@value" && isJsonLdValueObject(value)) continue;
1022
- if (hasNestedContext(record[key], depth + 1)) return true;
1023
- }
1024
- return false;
1025
- }
1026
- function exceedsTraversalDepth(value, depth = 0) {
1027
- if (depth >= MAX_TRAVERSAL_DEPTH) return true;
1028
- if (Array.isArray(value)) return value.some((item) => exceedsTraversalDepth(item, depth + 1));
1029
- if (typeof value !== "object" || value == null) return false;
1030
- const record = value;
1031
- for (const key of Object.keys(record)) {
1032
- if (key === "@context" || key === "@value" && isJsonLdValueObject(value)) continue;
1033
- if (exceedsTraversalDepth(record[key], depth + 1)) return true;
1034
- }
1035
- return false;
1036
- }
1037
- function hasKnownSafeContext(jsonLd) {
1038
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
1039
- const record = jsonLd;
1040
- if (!Object.hasOwn(record, "@context")) return false;
1041
- const context = record["@context"];
1042
- const entries = typeof context === "string" ? [context] : Array.isArray(context) ? context : null;
1043
- if (entries == null || entries.length < 1) return false;
1044
- let hasActivityStreamsContext = false;
1045
- for (const entry of entries) {
1046
- if (typeof entry !== "string") return false;
1047
- if (!KNOWN_SAFE_CONTEXT_URLS.has(entry)) return false;
1048
- if (entry === AS_CONTEXT_URL) hasActivityStreamsContext = true;
1049
- }
1050
- if (!hasActivityStreamsContext) return false;
1051
- for (const key of Object.keys(record)) {
1052
- if (key === "@context") continue;
1053
- if (hasNestedContext(record[key])) return false;
1054
- }
1055
- return true;
1056
- }
1057
- function getLogSafeJsonLdMetadata(jsonLd) {
1058
- if (typeof jsonLd !== "object" || jsonLd == null) return {};
1059
- const record = jsonLd;
1060
- const context = record["@context"];
1061
- return {
1062
- id: typeof record.id === "string" ? record.id : typeof record["@id"] === "string" ? record["@id"] : void 0,
1063
- type: typeof record.type === "string" ? record.type : typeof record["@type"] === "string" ? record["@type"] : void 0,
1064
- context: typeof context === "string" ? context : Array.isArray(context) ? context.filter((entry) => typeof entry === "string").slice(0, 4) : context == null ? void 0 : "[inline context]"
1065
- };
1066
- }
1067
- /**
1068
- * Ensures ActivityStreams attachment properties are represented as arrays
1069
- * when doing so preserves the JSON-LD semantics.
1070
- *
1071
- * JSON-LD compaction collapses single-item arrays into scalar values by
1072
- * default. Some ActivityPub implementations, Pixelfed among them, parse
1073
- * `attachment` as a plain JSON array rather than a JSON-LD property and reject
1074
- * otherwise valid objects whose single attachment is emitted as a scalar.
1075
- *
1076
- * When no `contextLoader` is supplied, the helper falls back to a restricted
1077
- * loader that resolves only Fedify's preloaded JSON-LD contexts and rejects
1078
- * every other URL without network access. Documents with custom, inline, or
1079
- * otherwise uncached contexts should pass a real `contextLoader` if they need
1080
- * the semantic-preservation check to succeed; otherwise canonicalization
1081
- * failures leave the original document unchanged.
1082
- */
1083
- async function normalizeAttachmentArrays(jsonLd, contextLoader) {
1084
- const normalized = wrapScalarAttachments(jsonLd);
1085
- if (normalized === jsonLd) return jsonLd;
1086
- if (exceedsTraversalDepth(jsonLd)) {
1087
- logger$1.debug("Skipping attachment array normalization because the JSON-LD document exceeds the safe traversal depth; leaving it unchanged.");
1088
- return jsonLd;
1089
- }
1090
- if (hasKnownSafeContext(jsonLd)) return normalized;
1091
- const loader = contextLoader ?? preloadedOnlyDocumentLoader;
1092
- try {
1093
- const [before, after] = await Promise.all([_fedify_vocab_runtime_jsonld.default.canonize(jsonLd, {
1094
- format: "application/n-quads",
1095
- documentLoader: loader
1096
- }), _fedify_vocab_runtime_jsonld.default.canonize(normalized, {
1097
- format: "application/n-quads",
1098
- documentLoader: loader
1099
- })]);
1100
- if (before === after) return normalized;
1101
- logger$1.warn("Wrapping scalar attachment values in arrays would change the canonical form of the JSON-LD document; leaving it unchanged. This usually means the active JSON-LD context redefines the `attachment` term. Document: {id}; type: {type}; context: {context}.", getLogSafeJsonLdMetadata(jsonLd));
1102
- } catch (error) {
1103
- logger$1.debug("Failed to verify attachment array normalization equivalence via JSON-LD canonicalization; leaving the JSON-LD document unchanged.\n{error}", { error });
1104
- }
1105
- return jsonLd;
1106
- }
1107
- /**
1108
- * Applies Fedify's internal JSON-LD wire-format interoperability workarounds
1109
- * to locally generated outgoing activities before they are signed, enqueued,
1110
- * or sent.
1111
- */
1112
- async function normalizeOutgoingActivityJsonLd(jsonLd, contextLoader) {
1113
- jsonLd = await normalizePublicAudience(jsonLd, contextLoader);
1114
- return await normalizeAttachmentArrays(jsonLd, contextLoader);
1115
- }
1116
- //#endregion
1117
- //#region src/sig/proof.ts
1118
- const Temporal = require_temporal_polyfill.Temporal;
1119
- /**
1120
- * Known Object Integrity Proof `cryptosuite` values, used to keep
1121
- * `object_integrity_proofs.cryptosuite` on a bounded set of spec-defined
1122
- * string values. Fedify currently signs and verifies only
1123
- * `eddsa-jcs-2022`; other values come in only from external proofs and are
1124
- * dropped from the metric attribute to avoid attacker-controlled
1125
- * cardinality.
1126
- */
1127
- const OIP_KNOWN_CRYPTOSUITES = new Set(["eddsa-jcs-2022"]);
1128
- const logger = (0, _logtape_logtape.getLogger)([
1129
- "fedify",
1130
- "sig",
1131
- "proof"
1132
- ]);
1133
- /**
1134
- * Checks if the given JSON-LD document has a DataIntegrityProof-like object,
1135
- * without fully deserializing it into vocabulary classes.
1136
- * @param jsonLd The JSON-LD document to check.
1137
- * @returns `true` if the document has a proof-like object; `false` otherwise.
1138
- * @since 2.2.0
1139
- */
1140
- function hasProofLike(jsonLd) {
1141
- if (typeof jsonLd !== "object" || jsonLd == null) return false;
1142
- const record = jsonLd;
1143
- const proof = record.proof ?? record["https://w3id.org/security#proof"];
1144
- const getField = (source, compact, expanded) => source[compact] ?? source[expanded];
1145
- const isReference = (value) => {
1146
- if (typeof value === "string") return true;
1147
- if (Array.isArray(value)) return value.some(isReference);
1148
- 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");
1149
- };
1150
- const hasType = (value) => {
1151
- if (typeof value === "string") return value === "DataIntegrityProof" || value === "https://w3id.org/security#DataIntegrityProof";
1152
- if (Array.isArray(value)) return value.some(hasType);
1153
- return false;
1154
- };
1155
- const isProofLike = (value) => {
1156
- if (typeof value !== "object" || value == null) return false;
1157
- const proofRecord = value;
1158
- 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"));
1159
- };
1160
- return Array.isArray(proof) ? proof.some(isProofLike) : isProofLike(proof);
1161
- }
1162
- /**
1163
- * Creates a proof for the given object.
1164
- * @param object The object to create a proof for.
1165
- * @param privateKey The private key to sign the proof with.
1166
- * @param keyId The key ID to use in the proof. It will be used by the verifier.
1167
- * @param options Additional options. See also {@link CreateProofOptions}.
1168
- * @returns The created proof.
1169
- * @throws {TypeError} If the private key is invalid or unsupported.
1170
- * @since 0.10.0
1171
- */
1172
- async function createProof(object, privateKey, keyId, { contextLoader, context, created } = {}) {
1173
- require_http.validateCryptoKey(privateKey, "private");
1174
- if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
1175
- let compactMsg = await object.clone({ proofs: [] }).toJsonLd({
1176
- format: "compact",
1177
- contextLoader,
1178
- context
1179
- });
1180
- compactMsg = await normalizeOutgoingActivityJsonLd(compactMsg, contextLoader);
1181
- const msgCanon = (0, json_canon.default)(compactMsg);
1182
- const encoder = new TextEncoder();
1183
- const msgBytes = encoder.encode(msgCanon);
1184
- const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
1185
- created ??= Temporal.Now.instant();
1186
- const proofCanon = (0, json_canon.default)({
1187
- "@context": compactMsg["@context"],
1188
- type: "DataIntegrityProof",
1189
- cryptosuite: "eddsa-jcs-2022",
1190
- verificationMethod: keyId.href,
1191
- proofPurpose: "assertionMethod",
1192
- created: created.toString()
1193
- });
1194
- const proofBytes = encoder.encode(proofCanon);
1195
- const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
1196
- const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
1197
- digest.set(new Uint8Array(proofDigest), 0);
1198
- digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
1199
- const sig = await crypto.subtle.sign("Ed25519", privateKey, digest);
1200
- return new _fedify_vocab.DataIntegrityProof({
1201
- cryptosuite: "eddsa-jcs-2022",
1202
- verificationMethod: keyId,
1203
- proofPurpose: "assertionMethod",
1204
- created: created ?? Temporal.Now.instant(),
1205
- proofValue: new Uint8Array(sig)
1206
- });
1207
- }
1208
- /**
1209
- * Signs the given object with the private key and returns the signed object.
1210
- * @param object The object to create a proof for.
1211
- * @param privateKey The private key to sign the proof with.
1212
- * @param keyId The key ID to use in the proof. It will be used by the verifier.
1213
- * @param options Additional options. See also {@link SignObjectOptions}.
1214
- * @returns The signed object.
1215
- * @throws {TypeError} If the private key is invalid or unsupported.
1216
- * @since 0.10.0
1217
- */
1218
- async function signObject(object, privateKey, keyId, options = {}) {
1219
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": (0, _fedify_vocab.getTypeId)(object).href } }, async (span) => {
1220
- try {
1221
- if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
1222
- const existingProofs = [];
1223
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
1224
- const proof = await createProof(object, privateKey, keyId, options);
1225
- if (span.isRecording()) {
1226
- if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
1227
- if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
1228
- if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", (0, byte_encodings_hex.encodeHex)(proof.proofValue));
1229
- }
1230
- return object.clone({ proofs: [...existingProofs, proof] });
1231
- } catch (error) {
1232
- span.setStatus({
1233
- code: _opentelemetry_api.SpanStatusCode.ERROR,
1234
- message: String(error)
1235
- });
1236
- throw error;
1237
- } finally {
1238
- span.end();
1239
- }
1240
- });
1241
- }
1242
- /**
1243
- * Verifies the given proof for the object.
1244
- * @param jsonLd The JSON-LD object to verify the proof for. If it contains
1245
- * any proofs, they will be ignored.
1246
- * @param proof The proof to verify.
1247
- * @param options Additional options. See also {@link VerifyProofOptions}.
1248
- * @returns The public key that was used to sign the proof, or `null` if the
1249
- * proof is invalid.
1250
- * @since 0.10.0
1251
- */
1252
- async function verifyProof(jsonLd, proof, options = {}) {
1253
- return await (options.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider()).getTracer(require_http.name, require_http.version).startActiveSpan("object_integrity_proofs.verify", async (span) => {
1254
- const start = performance.now();
1255
- let verified = false;
1256
- let threw = false;
1257
- const cryptosuite = proof.cryptosuite != null && OIP_KNOWN_CRYPTOSUITES.has(proof.cryptosuite) ? proof.cryptosuite : void 0;
1258
- if (span.isRecording()) {
1259
- if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
1260
- if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
1261
- if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", (0, byte_encodings_hex.encodeHex)(proof.proofValue));
1262
- }
1263
- try {
1264
- const key = await verifyProofInternal(jsonLd, proof, options);
1265
- if (key == null) span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
1266
- else verified = true;
1267
- return key;
1268
- } catch (error) {
1269
- threw = true;
1270
- span.setStatus({
1271
- code: _opentelemetry_api.SpanStatusCode.ERROR,
1272
- message: String(error)
1273
- });
1274
- throw error;
1275
- } finally {
1276
- const classified = threw ? "error" : verified ? "verified" : "rejected";
1277
- require_http.getFederationMetrics(options.meterProvider).recordSignatureVerificationDuration(require_http.getDurationMs(start), "object_integrity", classified, { cryptosuite });
1278
- span.end();
1279
- }
1280
- });
1281
- }
1282
- async function verifyProofInternal(jsonLd, proof, options) {
1283
- if (typeof jsonLd !== "object" || jsonLd == null || Array.isArray(jsonLd) || proof.cryptosuite !== "eddsa-jcs-2022" || proof.verificationMethodId == null || proof.proofPurpose !== "assertionMethod" || proof.proofValue == null || proof.created == null) return null;
1284
- const publicKeyPromise = require_http.measureSignatureKeyFetch(options.meterProvider, "object_integrity", () => require_http.fetchKey(proof.verificationMethodId, _fedify_vocab.Multikey, options));
1285
- const proofConfig = {
1286
- "@context": jsonLd["@context"],
1287
- type: "DataIntegrityProof",
1288
- cryptosuite: proof.cryptosuite,
1289
- verificationMethod: proof.verificationMethodId.href,
1290
- proofPurpose: proof.proofPurpose,
1291
- created: proof.created.toString()
1292
- };
1293
- const encoder = new TextEncoder();
1294
- const proofBytes = encoder.encode((0, json_canon.default)(proofConfig));
1295
- const proofDigest = await crypto.subtle.digest("SHA-256", proofBytes);
1296
- const msg = { ...jsonLd };
1297
- if ("proof" in msg) delete msg.proof;
1298
- if ("https://w3id.org/security#proof" in msg) delete msg["https://w3id.org/security#proof"];
1299
- let fetchedKey;
1300
- try {
1301
- fetchedKey = await publicKeyPromise;
1302
- } catch (error) {
1303
- logger.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
1304
- proof,
1305
- keyId: proof.verificationMethodId.href,
1306
- error
1307
- });
1308
- return null;
1309
- }
1310
- const publicKey = fetchedKey.key;
1311
- if (publicKey == null) {
1312
- logger.debug("Failed to get the key (verificationMethod) for the proof:\n{proof}", {
1313
- proof,
1314
- keyId: proof.verificationMethodId.href
1315
- });
1316
- return null;
1317
- }
1318
- if (publicKey.publicKey.algorithm.name !== "Ed25519") {
1319
- if (fetchedKey.cached) {
1320
- logger.debug("The cached key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}; retrying with the freshly fetched key...", {
1321
- proof,
1322
- keyId: proof.verificationMethodId.href
1323
- });
1324
- return await verifyProofInternal(jsonLd, proof, {
1325
- ...options,
1326
- keyCache: {
1327
- get: () => Promise.resolve(void 0),
1328
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1329
- }
1330
- });
1331
- }
1332
- logger.debug("The fetched key (verificationMethod) for the proof is not a valid Ed25519 key:\n{keyId}", {
1333
- proof,
1334
- keyId: proof.verificationMethodId.href
1335
- });
1336
- return null;
1337
- }
1338
- const digest = new Uint8Array(proofDigest.byteLength + 32);
1339
- digest.set(new Uint8Array(proofDigest), 0);
1340
- const proofValue = proof.proofValue;
1341
- const verifyCandidate = async (candidate) => {
1342
- const msgBytes = encoder.encode((0, json_canon.default)(candidate));
1343
- const msgDigest = await crypto.subtle.digest("SHA-256", msgBytes);
1344
- digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
1345
- return await crypto.subtle.verify("Ed25519", publicKey.publicKey, proofValue.slice(), digest);
1346
- };
1347
- if (await verifyCandidate(msg)) return publicKey;
1348
- const normalized = await normalizeOutgoingActivityJsonLd(msg, preloadedOnlyDocumentLoader);
1349
- if (normalized !== msg && await verifyCandidate(normalized)) return publicKey;
1350
- if (fetchedKey.cached) {
1351
- logger.debug("Failed to verify the proof with the cached key {keyId}; retrying with the freshly fetched key...", {
1352
- keyId: proof.verificationMethodId.href,
1353
- proof
1354
- });
1355
- return await verifyProofInternal(jsonLd, proof, {
1356
- ...options,
1357
- keyCache: {
1358
- get: () => Promise.resolve(void 0),
1359
- set: async (keyId, key) => await options.keyCache?.set(keyId, key)
1360
- }
1361
- });
1362
- }
1363
- logger.debug("Failed to verify the proof with the fetched key {keyId}:\n{proof}", {
1364
- keyId: proof.verificationMethodId.href,
1365
- proof
1366
- });
1367
- return null;
1368
- }
1369
- /**
1370
- * Verifies the given object. It will verify all the proofs in the object,
1371
- * and succeed only if all the proofs are valid and all attributions and
1372
- * actors are authenticated by the proofs.
1373
- * @template T The type of the object to verify.
1374
- * @param cls The class of the object to verify. It must be a subclass of
1375
- * the {@link Object}.
1376
- * @param jsonLd The JSON-LD object to verify. It's assumed that the object
1377
- * is a compacted JSON-LD representation of a `T` with `@context`.
1378
- * @param options Additional options. See also {@link VerifyObjectOptions}.
1379
- * @returns The object if it's verified, or `null` if it's not.
1380
- * @throws {TypeError} If the object is invalid or unsupported.
1381
- * @since 0.10.0
1382
- */
1383
- async function verifyObject(cls, jsonLd, options = {}) {
1384
- const logger = (0, _logtape_logtape.getLogger)([
1385
- "fedify",
1386
- "sig",
1387
- "proof"
1388
- ]);
1389
- const object = await cls.fromJsonLd(jsonLd, options);
1390
- const attributions = new Set(object.attributionIds.map((uri) => uri.href));
1391
- if (object instanceof _fedify_vocab.Activity) for (const uri of object.actorIds) attributions.add(uri.href);
1392
- for await (const proof of object.getProofs(options)) {
1393
- const key = await verifyProof(jsonLd, proof, options);
1394
- if (key === null) return null;
1395
- if (proof.verificationMethodId == null) return null;
1396
- if (key.controllerId == null) {
1397
- logger.debug("Key {keyId} does not have a controller.", { keyId: key.id?.href });
1398
- continue;
1399
- }
1400
- deleteAuthenticatedAttribution(attributions, key.controllerId, proof.verificationMethodId);
1401
- }
1402
- if (attributions.size > 0) {
1403
- logger.debug("Some attributions are not authenticated by the proofs: {attributions}.", { attributions: [...attributions] });
1404
- return null;
1405
- }
1406
- return object;
1407
- }
1408
- function deleteAuthenticatedAttribution(attributions, controllerId, verificationMethodId) {
1409
- const controllerHasCryptographicOrigin = hasCryptographicOrigin(controllerId.href);
1410
- const verificationMethodMatchesController = controllerHasCryptographicOrigin && hasCryptographicOrigin(verificationMethodId.href) && (0, _fedify_vocab_runtime.haveSameFe34Origin)(controllerId, verificationMethodId);
1411
- if (!controllerHasCryptographicOrigin || verificationMethodMatchesController) attributions.delete(controllerId.href);
1412
- if (!verificationMethodMatchesController) return;
1413
- for (const attribution of [...attributions]) if (hasCryptographicOrigin(attribution) && (0, _fedify_vocab_runtime.haveSameFe34Origin)(controllerId, attribution)) attributions.delete(attribution);
1414
- }
1415
- function hasCryptographicOrigin(iri) {
1416
- return /^did:/i.test(iri) || /^ap(?:\+ef61)?:\/\//i.test(iri);
1417
- }
1418
- //#endregion
1419
- Object.defineProperty(exports, "InvalidContextReferenceError", {
1420
- enumerable: true,
1421
- get: function() {
1422
- return InvalidContextReferenceError;
1423
- }
1424
- });
1425
- Object.defineProperty(exports, "assertSafeJsonLd", {
1426
- enumerable: true,
1427
- get: function() {
1428
- return assertSafeJsonLd;
1429
- }
1430
- });
1431
- Object.defineProperty(exports, "attachSignature", {
1432
- enumerable: true,
1433
- get: function() {
1434
- return attachSignature;
1435
- }
1436
- });
1437
- Object.defineProperty(exports, "compactJsonLd", {
1438
- enumerable: true,
1439
- get: function() {
1440
- return compactJsonLd;
1441
- }
1442
- });
1443
- Object.defineProperty(exports, "createProof", {
1444
- enumerable: true,
1445
- get: function() {
1446
- return createProof;
1447
- }
1448
- });
1449
- Object.defineProperty(exports, "createSignature", {
1450
- enumerable: true,
1451
- get: function() {
1452
- return createSignature;
1453
- }
1454
- });
1455
- Object.defineProperty(exports, "detachSignature", {
1456
- enumerable: true,
1457
- get: function() {
1458
- return detachSignature;
1459
- }
1460
- });
1461
- Object.defineProperty(exports, "doesActorOwnKey", {
1462
- enumerable: true,
1463
- get: function() {
1464
- return doesActorOwnKey;
1465
- }
1466
- });
1467
- Object.defineProperty(exports, "getKeyOwner", {
1468
- enumerable: true,
1469
- get: function() {
1470
- return getKeyOwner;
1471
- }
1472
- });
1473
- Object.defineProperty(exports, "getNormalizationContextLoader", {
1474
- enumerable: true,
1475
- get: function() {
1476
- return getNormalizationContextLoader;
1477
- }
1478
- });
1479
- Object.defineProperty(exports, "hasProofLike", {
1480
- enumerable: true,
1481
- get: function() {
1482
- return hasProofLike;
1483
- }
1484
- });
1485
- Object.defineProperty(exports, "hasSignature", {
1486
- enumerable: true,
1487
- get: function() {
1488
- return hasSignature;
1489
- }
1490
- });
1491
- Object.defineProperty(exports, "hasSignatureLike", {
1492
- enumerable: true,
1493
- get: function() {
1494
- return hasSignatureLike;
1495
- }
1496
- });
1497
- Object.defineProperty(exports, "isClearlyMalformedContextReference", {
1498
- enumerable: true,
1499
- get: function() {
1500
- return isClearlyMalformedContextReference;
1501
- }
1502
- });
1503
- Object.defineProperty(exports, "isInvalidUrlTypeError", {
1504
- enumerable: true,
1505
- get: function() {
1506
- return isInvalidUrlTypeError;
1507
- }
1508
- });
1509
- Object.defineProperty(exports, "normalizeOutgoingActivityJsonLd", {
1510
- enumerable: true,
1511
- get: function() {
1512
- return normalizeOutgoingActivityJsonLd;
1513
- }
1514
- });
1515
- Object.defineProperty(exports, "signJsonLd", {
1516
- enumerable: true,
1517
- get: function() {
1518
- return signJsonLd;
1519
- }
1520
- });
1521
- Object.defineProperty(exports, "signObject", {
1522
- enumerable: true,
1523
- get: function() {
1524
- return signObject;
1525
- }
1526
- });
1527
- Object.defineProperty(exports, "verifyCompactJsonLd", {
1528
- enumerable: true,
1529
- get: function() {
1530
- return verifyCompactJsonLd;
1531
- }
1532
- });
1533
- Object.defineProperty(exports, "verifyJsonLd", {
1534
- enumerable: true,
1535
- get: function() {
1536
- return verifyJsonLd;
1537
- }
1538
- });
1539
- Object.defineProperty(exports, "verifyObject", {
1540
- enumerable: true,
1541
- get: function() {
1542
- return verifyObject;
1543
- }
1544
- });
1545
- Object.defineProperty(exports, "verifyProof", {
1546
- enumerable: true,
1547
- get: function() {
1548
- return verifyProof;
1549
- }
1550
- });
1551
- Object.defineProperty(exports, "verifySignature", {
1552
- enumerable: true,
1553
- get: function() {
1554
- return verifySignature;
1555
- }
1556
- });
1557
- Object.defineProperty(exports, "wrapContextLoaderForJsonLd", {
1558
- enumerable: true,
1559
- get: function() {
1560
- return wrapContextLoaderForJsonLd;
1561
- }
1562
- });