@enbox/agent 0.0.1

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 (348) hide show
  1. package/dist/browser.js +2215 -0
  2. package/dist/browser.js.map +7 -0
  3. package/dist/browser.mjs +2215 -0
  4. package/dist/browser.mjs.map +7 -0
  5. package/dist/cjs/index.js +8530 -0
  6. package/dist/cjs/index.js.map +7 -0
  7. package/dist/cjs/package.json +1 -0
  8. package/dist/esm/agent-did-resolver-cache.js +87 -0
  9. package/dist/esm/agent-did-resolver-cache.js.map +1 -0
  10. package/dist/esm/bearer-identity.js +41 -0
  11. package/dist/esm/bearer-identity.js.map +1 -0
  12. package/dist/esm/connect.js +191 -0
  13. package/dist/esm/connect.js.map +1 -0
  14. package/dist/esm/crypto-api.js +346 -0
  15. package/dist/esm/crypto-api.js.map +1 -0
  16. package/dist/esm/did-api.js +278 -0
  17. package/dist/esm/did-api.js.map +1 -0
  18. package/dist/esm/dwn-api.js +336 -0
  19. package/dist/esm/dwn-api.js.map +1 -0
  20. package/dist/esm/dwn-registrar.js +120 -0
  21. package/dist/esm/dwn-registrar.js.map +1 -0
  22. package/dist/esm/hd-identity-vault.js +729 -0
  23. package/dist/esm/hd-identity-vault.js.map +1 -0
  24. package/dist/esm/identity-api.js +262 -0
  25. package/dist/esm/identity-api.js.map +1 -0
  26. package/dist/esm/index.js +23 -0
  27. package/dist/esm/index.js.map +1 -0
  28. package/dist/esm/local-key-manager.js +498 -0
  29. package/dist/esm/local-key-manager.js.map +1 -0
  30. package/dist/esm/oidc.js +507 -0
  31. package/dist/esm/oidc.js.map +1 -0
  32. package/dist/esm/permissions-api.js +322 -0
  33. package/dist/esm/permissions-api.js.map +1 -0
  34. package/dist/esm/prototyping/clients/dwn-rpc-types.js +2 -0
  35. package/dist/esm/prototyping/clients/dwn-rpc-types.js.map +1 -0
  36. package/dist/esm/prototyping/clients/dwn-server-info-cache-memory.js +74 -0
  37. package/dist/esm/prototyping/clients/dwn-server-info-cache-memory.js.map +1 -0
  38. package/dist/esm/prototyping/clients/http-dwn-rpc-client.js +105 -0
  39. package/dist/esm/prototyping/clients/http-dwn-rpc-client.js.map +1 -0
  40. package/dist/esm/prototyping/clients/json-rpc-socket.js +150 -0
  41. package/dist/esm/prototyping/clients/json-rpc-socket.js.map +1 -0
  42. package/dist/esm/prototyping/clients/json-rpc.js +58 -0
  43. package/dist/esm/prototyping/clients/json-rpc.js.map +1 -0
  44. package/dist/esm/prototyping/clients/server-info-types.js +2 -0
  45. package/dist/esm/prototyping/clients/server-info-types.js.map +1 -0
  46. package/dist/esm/prototyping/clients/web-socket-clients.js +90 -0
  47. package/dist/esm/prototyping/clients/web-socket-clients.js.map +1 -0
  48. package/dist/esm/prototyping/common/object.js +14 -0
  49. package/dist/esm/prototyping/common/object.js.map +1 -0
  50. package/dist/esm/prototyping/common/type-utils.js +2 -0
  51. package/dist/esm/prototyping/common/type-utils.js.map +1 -0
  52. package/dist/esm/prototyping/crypto/algorithms/aes-gcm.js +147 -0
  53. package/dist/esm/prototyping/crypto/algorithms/aes-gcm.js.map +1 -0
  54. package/dist/esm/prototyping/crypto/algorithms/aes-kw.js +137 -0
  55. package/dist/esm/prototyping/crypto/algorithms/aes-kw.js.map +1 -0
  56. package/dist/esm/prototyping/crypto/algorithms/ecdsa.js +307 -0
  57. package/dist/esm/prototyping/crypto/algorithms/ecdsa.js.map +1 -0
  58. package/dist/esm/prototyping/crypto/algorithms/eddsa.js +264 -0
  59. package/dist/esm/prototyping/crypto/algorithms/eddsa.js.map +1 -0
  60. package/dist/esm/prototyping/crypto/algorithms/hkdf.js +39 -0
  61. package/dist/esm/prototyping/crypto/algorithms/hkdf.js.map +1 -0
  62. package/dist/esm/prototyping/crypto/algorithms/pbkdf2.js +41 -0
  63. package/dist/esm/prototyping/crypto/algorithms/pbkdf2.js.map +1 -0
  64. package/dist/esm/prototyping/crypto/crypto-error.js +41 -0
  65. package/dist/esm/prototyping/crypto/crypto-error.js.map +1 -0
  66. package/dist/esm/prototyping/crypto/dsa.js +236 -0
  67. package/dist/esm/prototyping/crypto/dsa.js.map +1 -0
  68. package/dist/esm/prototyping/crypto/jose/jwe-compact.js +130 -0
  69. package/dist/esm/prototyping/crypto/jose/jwe-compact.js.map +1 -0
  70. package/dist/esm/prototyping/crypto/jose/jwe-flattened.js +294 -0
  71. package/dist/esm/prototyping/crypto/jose/jwe-flattened.js.map +1 -0
  72. package/dist/esm/prototyping/crypto/jose/jwe.js +308 -0
  73. package/dist/esm/prototyping/crypto/jose/jwe.js.map +1 -0
  74. package/dist/esm/prototyping/crypto/primitives/aes-gcm.js +352 -0
  75. package/dist/esm/prototyping/crypto/primitives/aes-gcm.js.map +1 -0
  76. package/dist/esm/prototyping/crypto/primitives/aes-kw.js +247 -0
  77. package/dist/esm/prototyping/crypto/primitives/aes-kw.js.map +1 -0
  78. package/dist/esm/prototyping/crypto/primitives/hkdf.js +80 -0
  79. package/dist/esm/prototyping/crypto/primitives/hkdf.js.map +1 -0
  80. package/dist/esm/prototyping/crypto/primitives/pbkdf2.js +85 -0
  81. package/dist/esm/prototyping/crypto/primitives/pbkdf2.js.map +1 -0
  82. package/dist/esm/prototyping/crypto/types/cipher.js +2 -0
  83. package/dist/esm/prototyping/crypto/types/cipher.js.map +1 -0
  84. package/dist/esm/prototyping/crypto/types/crypto-api.js +2 -0
  85. package/dist/esm/prototyping/crypto/types/crypto-api.js.map +1 -0
  86. package/dist/esm/prototyping/crypto/types/key-converter.js +2 -0
  87. package/dist/esm/prototyping/crypto/types/key-converter.js.map +1 -0
  88. package/dist/esm/prototyping/crypto/types/key-deriver.js +2 -0
  89. package/dist/esm/prototyping/crypto/types/key-deriver.js.map +1 -0
  90. package/dist/esm/prototyping/crypto/types/key-io.js +2 -0
  91. package/dist/esm/prototyping/crypto/types/key-io.js.map +1 -0
  92. package/dist/esm/prototyping/crypto/types/key-manager.js +2 -0
  93. package/dist/esm/prototyping/crypto/types/key-manager.js.map +1 -0
  94. package/dist/esm/prototyping/crypto/types/key-wrapper.js +2 -0
  95. package/dist/esm/prototyping/crypto/types/key-wrapper.js.map +1 -0
  96. package/dist/esm/prototyping/crypto/types/params-direct.js +2 -0
  97. package/dist/esm/prototyping/crypto/types/params-direct.js.map +1 -0
  98. package/dist/esm/prototyping/crypto/types/params-kms.js +2 -0
  99. package/dist/esm/prototyping/crypto/types/params-kms.js.map +1 -0
  100. package/dist/esm/prototyping/crypto/utils.js +19 -0
  101. package/dist/esm/prototyping/crypto/utils.js.map +1 -0
  102. package/dist/esm/prototyping/dids/resolver-cache-memory.js +77 -0
  103. package/dist/esm/prototyping/dids/resolver-cache-memory.js.map +1 -0
  104. package/dist/esm/prototyping/dids/utils.js +9 -0
  105. package/dist/esm/prototyping/dids/utils.js.map +1 -0
  106. package/dist/esm/rpc-client.js +123 -0
  107. package/dist/esm/rpc-client.js.map +1 -0
  108. package/dist/esm/store-data-protocols.js +38 -0
  109. package/dist/esm/store-data-protocols.js.map +1 -0
  110. package/dist/esm/store-data.js +320 -0
  111. package/dist/esm/store-data.js.map +1 -0
  112. package/dist/esm/store-did.js +136 -0
  113. package/dist/esm/store-did.js.map +1 -0
  114. package/dist/esm/store-identity.js +140 -0
  115. package/dist/esm/store-identity.js.map +1 -0
  116. package/dist/esm/store-key.js +136 -0
  117. package/dist/esm/store-key.js.map +1 -0
  118. package/dist/esm/sync-api.js +61 -0
  119. package/dist/esm/sync-api.js.map +1 -0
  120. package/dist/esm/sync-engine-level.js +618 -0
  121. package/dist/esm/sync-engine-level.js.map +1 -0
  122. package/dist/esm/test-harness.js +239 -0
  123. package/dist/esm/test-harness.js.map +1 -0
  124. package/dist/esm/types/agent.js +2 -0
  125. package/dist/esm/types/agent.js.map +1 -0
  126. package/dist/esm/types/dwn.js +31 -0
  127. package/dist/esm/types/dwn.js.map +1 -0
  128. package/dist/esm/types/identity-vault.js +2 -0
  129. package/dist/esm/types/identity-vault.js.map +1 -0
  130. package/dist/esm/types/identity.js +2 -0
  131. package/dist/esm/types/identity.js.map +1 -0
  132. package/dist/esm/types/key-manager.js +2 -0
  133. package/dist/esm/types/key-manager.js.map +1 -0
  134. package/dist/esm/types/permissions.js +2 -0
  135. package/dist/esm/types/permissions.js.map +1 -0
  136. package/dist/esm/types/sync.js +2 -0
  137. package/dist/esm/types/sync.js.map +1 -0
  138. package/dist/esm/types/vc.js +5 -0
  139. package/dist/esm/types/vc.js.map +1 -0
  140. package/dist/esm/utils-internal.js +147 -0
  141. package/dist/esm/utils-internal.js.map +1 -0
  142. package/dist/esm/utils.js +161 -0
  143. package/dist/esm/utils.js.map +1 -0
  144. package/dist/types/agent-did-resolver-cache.d.ts +30 -0
  145. package/dist/types/agent-did-resolver-cache.d.ts.map +1 -0
  146. package/dist/types/bearer-identity.d.ts +31 -0
  147. package/dist/types/bearer-identity.d.ts.map +1 -0
  148. package/dist/types/connect.d.ts +88 -0
  149. package/dist/types/connect.d.ts.map +1 -0
  150. package/dist/types/crypto-api.d.ts +286 -0
  151. package/dist/types/crypto-api.d.ts.map +1 -0
  152. package/dist/types/did-api.d.ts +119 -0
  153. package/dist/types/did-api.d.ts.map +1 -0
  154. package/dist/types/dwn-api.d.ts +66 -0
  155. package/dist/types/dwn-api.d.ts.map +1 -0
  156. package/dist/types/dwn-registrar.d.ts +29 -0
  157. package/dist/types/dwn-registrar.d.ts.map +1 -0
  158. package/dist/types/hd-identity-vault.d.ts +306 -0
  159. package/dist/types/hd-identity-vault.d.ts.map +1 -0
  160. package/dist/types/identity-api.d.ts +107 -0
  161. package/dist/types/identity-api.d.ts.map +1 -0
  162. package/dist/types/index.d.ts +30 -0
  163. package/dist/types/index.d.ts.map +1 -0
  164. package/dist/types/local-key-manager.d.ts +311 -0
  165. package/dist/types/local-key-manager.d.ts.map +1 -0
  166. package/dist/types/oidc.d.ts +247 -0
  167. package/dist/types/oidc.d.ts.map +1 -0
  168. package/dist/types/permissions-api.d.ts +35 -0
  169. package/dist/types/permissions-api.d.ts.map +1 -0
  170. package/dist/types/prototyping/clients/dwn-rpc-types.d.ts +45 -0
  171. package/dist/types/prototyping/clients/dwn-rpc-types.d.ts.map +1 -0
  172. package/dist/types/prototyping/clients/dwn-server-info-cache-memory.d.ts +57 -0
  173. package/dist/types/prototyping/clients/dwn-server-info-cache-memory.d.ts.map +1 -0
  174. package/dist/types/prototyping/clients/http-dwn-rpc-client.d.ts +13 -0
  175. package/dist/types/prototyping/clients/http-dwn-rpc-client.d.ts.map +1 -0
  176. package/dist/types/prototyping/clients/json-rpc-socket.d.ts +43 -0
  177. package/dist/types/prototyping/clients/json-rpc-socket.d.ts.map +1 -0
  178. package/dist/types/prototyping/clients/json-rpc.d.ts +49 -0
  179. package/dist/types/prototyping/clients/json-rpc.d.ts.map +1 -0
  180. package/dist/types/prototyping/clients/server-info-types.d.ts +20 -0
  181. package/dist/types/prototyping/clients/server-info-types.d.ts.map +1 -0
  182. package/dist/types/prototyping/clients/web-socket-clients.d.ts +10 -0
  183. package/dist/types/prototyping/clients/web-socket-clients.d.ts.map +1 -0
  184. package/dist/types/prototyping/common/object.d.ts +2 -0
  185. package/dist/types/prototyping/common/object.d.ts.map +1 -0
  186. package/dist/types/prototyping/common/type-utils.d.ts +7 -0
  187. package/dist/types/prototyping/common/type-utils.d.ts.map +1 -0
  188. package/dist/types/prototyping/crypto/algorithms/aes-gcm.d.ts +151 -0
  189. package/dist/types/prototyping/crypto/algorithms/aes-gcm.d.ts.map +1 -0
  190. package/dist/types/prototyping/crypto/algorithms/aes-kw.d.ts +109 -0
  191. package/dist/types/prototyping/crypto/algorithms/aes-kw.d.ts.map +1 -0
  192. package/dist/types/prototyping/crypto/algorithms/ecdsa.d.ts +160 -0
  193. package/dist/types/prototyping/crypto/algorithms/ecdsa.d.ts.map +1 -0
  194. package/dist/types/prototyping/crypto/algorithms/eddsa.d.ts +157 -0
  195. package/dist/types/prototyping/crypto/algorithms/eddsa.d.ts.map +1 -0
  196. package/dist/types/prototyping/crypto/algorithms/hkdf.d.ts +21 -0
  197. package/dist/types/prototyping/crypto/algorithms/hkdf.d.ts.map +1 -0
  198. package/dist/types/prototyping/crypto/algorithms/pbkdf2.d.ts +21 -0
  199. package/dist/types/prototyping/crypto/algorithms/pbkdf2.d.ts.map +1 -0
  200. package/dist/types/prototyping/crypto/crypto-error.d.ts +29 -0
  201. package/dist/types/prototyping/crypto/crypto-error.d.ts.map +1 -0
  202. package/dist/types/prototyping/crypto/dsa.d.ts +169 -0
  203. package/dist/types/prototyping/crypto/dsa.d.ts.map +1 -0
  204. package/dist/types/prototyping/crypto/jose/jwe-compact.d.ts +135 -0
  205. package/dist/types/prototyping/crypto/jose/jwe-compact.d.ts.map +1 -0
  206. package/dist/types/prototyping/crypto/jose/jwe-flattened.d.ts +134 -0
  207. package/dist/types/prototyping/crypto/jose/jwe-flattened.d.ts.map +1 -0
  208. package/dist/types/prototyping/crypto/jose/jwe.d.ts +378 -0
  209. package/dist/types/prototyping/crypto/jose/jwe.d.ts.map +1 -0
  210. package/dist/types/prototyping/crypto/primitives/aes-gcm.d.ts +245 -0
  211. package/dist/types/prototyping/crypto/primitives/aes-gcm.d.ts.map +1 -0
  212. package/dist/types/prototyping/crypto/primitives/aes-kw.d.ts +103 -0
  213. package/dist/types/prototyping/crypto/primitives/aes-kw.d.ts.map +1 -0
  214. package/dist/types/prototyping/crypto/primitives/hkdf.d.ts +90 -0
  215. package/dist/types/prototyping/crypto/primitives/hkdf.d.ts.map +1 -0
  216. package/dist/types/prototyping/crypto/primitives/pbkdf2.d.ts +84 -0
  217. package/dist/types/prototyping/crypto/primitives/pbkdf2.d.ts.map +1 -0
  218. package/dist/types/prototyping/crypto/types/cipher.d.ts +14 -0
  219. package/dist/types/prototyping/crypto/types/cipher.d.ts.map +1 -0
  220. package/dist/types/prototyping/crypto/types/crypto-api.d.ts +35 -0
  221. package/dist/types/prototyping/crypto/types/crypto-api.d.ts.map +1 -0
  222. package/dist/types/prototyping/crypto/types/key-converter.d.ts +49 -0
  223. package/dist/types/prototyping/crypto/types/key-converter.d.ts.map +1 -0
  224. package/dist/types/prototyping/crypto/types/key-deriver.d.ts +50 -0
  225. package/dist/types/prototyping/crypto/types/key-deriver.d.ts.map +1 -0
  226. package/dist/types/prototyping/crypto/types/key-io.d.ts +49 -0
  227. package/dist/types/prototyping/crypto/types/key-io.d.ts.map +1 -0
  228. package/dist/types/prototyping/crypto/types/key-manager.d.ts +69 -0
  229. package/dist/types/prototyping/crypto/types/key-manager.d.ts.map +1 -0
  230. package/dist/types/prototyping/crypto/types/key-wrapper.d.ts +14 -0
  231. package/dist/types/prototyping/crypto/types/key-wrapper.d.ts.map +1 -0
  232. package/dist/types/prototyping/crypto/types/params-direct.d.ts +75 -0
  233. package/dist/types/prototyping/crypto/types/params-direct.d.ts.map +1 -0
  234. package/dist/types/prototyping/crypto/types/params-kms.d.ts +63 -0
  235. package/dist/types/prototyping/crypto/types/params-kms.d.ts.map +1 -0
  236. package/dist/types/prototyping/crypto/utils.d.ts +7 -0
  237. package/dist/types/prototyping/crypto/utils.d.ts.map +1 -0
  238. package/dist/types/prototyping/dids/resolver-cache-memory.d.ts +57 -0
  239. package/dist/types/prototyping/dids/resolver-cache-memory.d.ts.map +1 -0
  240. package/dist/types/prototyping/dids/utils.d.ts +3 -0
  241. package/dist/types/prototyping/dids/utils.d.ts.map +1 -0
  242. package/dist/types/rpc-client.d.ts +51 -0
  243. package/dist/types/rpc-client.d.ts.map +1 -0
  244. package/dist/types/store-data-protocols.d.ts +4 -0
  245. package/dist/types/store-data-protocols.d.ts.map +1 -0
  246. package/dist/types/store-data.d.ts +95 -0
  247. package/dist/types/store-data.d.ts.map +1 -0
  248. package/dist/types/store-did.d.ts +33 -0
  249. package/dist/types/store-did.d.ts.map +1 -0
  250. package/dist/types/store-identity.d.ts +34 -0
  251. package/dist/types/store-identity.d.ts.map +1 -0
  252. package/dist/types/store-key.d.ts +32 -0
  253. package/dist/types/store-key.d.ts.map +1 -0
  254. package/dist/types/sync-api.d.ts +41 -0
  255. package/dist/types/sync-api.d.ts.map +1 -0
  256. package/dist/types/sync-engine-level.d.ts +85 -0
  257. package/dist/types/sync-engine-level.d.ts.map +1 -0
  258. package/dist/types/test-harness.d.ts +69 -0
  259. package/dist/types/test-harness.d.ts.map +1 -0
  260. package/dist/types/types/agent.d.ts +172 -0
  261. package/dist/types/types/agent.d.ts.map +1 -0
  262. package/dist/types/types/dwn.d.ts +178 -0
  263. package/dist/types/types/dwn.d.ts.map +1 -0
  264. package/dist/types/types/identity-vault.d.ts +129 -0
  265. package/dist/types/types/identity-vault.d.ts.map +1 -0
  266. package/dist/types/types/identity.d.ts +16 -0
  267. package/dist/types/types/identity.d.ts.map +1 -0
  268. package/dist/types/types/key-manager.d.ts +9 -0
  269. package/dist/types/types/key-manager.d.ts.map +1 -0
  270. package/dist/types/types/permissions.d.ts +98 -0
  271. package/dist/types/types/permissions.d.ts.map +1 -0
  272. package/dist/types/types/sync.d.ts +66 -0
  273. package/dist/types/types/sync.d.ts.map +1 -0
  274. package/dist/types/types/vc.d.ts +7 -0
  275. package/dist/types/types/vc.d.ts.map +1 -0
  276. package/dist/types/utils-internal.d.ts +50 -0
  277. package/dist/types/utils-internal.d.ts.map +1 -0
  278. package/dist/types/utils.d.ts +37 -0
  279. package/dist/types/utils.d.ts.map +1 -0
  280. package/package.json +112 -0
  281. package/src/agent-did-resolver-cache.ts +95 -0
  282. package/src/bearer-identity.ts +42 -0
  283. package/src/connect.ts +296 -0
  284. package/src/crypto-api.ts +593 -0
  285. package/src/did-api.ts +429 -0
  286. package/src/dwn-api.ts +462 -0
  287. package/src/dwn-registrar.ts +127 -0
  288. package/src/hd-identity-vault.ts +853 -0
  289. package/src/identity-api.ts +324 -0
  290. package/src/index.ts +30 -0
  291. package/src/local-key-manager.ts +672 -0
  292. package/src/oidc.ts +857 -0
  293. package/src/permissions-api.ts +408 -0
  294. package/src/prototyping/clients/dwn-rpc-types.ts +55 -0
  295. package/src/prototyping/clients/dwn-server-info-cache-memory.ts +79 -0
  296. package/src/prototyping/clients/http-dwn-rpc-client.ts +110 -0
  297. package/src/prototyping/clients/json-rpc-socket.ts +169 -0
  298. package/src/prototyping/clients/json-rpc.ts +113 -0
  299. package/src/prototyping/clients/server-info-types.ts +21 -0
  300. package/src/prototyping/clients/web-socket-clients.ts +100 -0
  301. package/src/prototyping/common/object.ts +15 -0
  302. package/src/prototyping/common/type-utils.ts +6 -0
  303. package/src/prototyping/crypto/algorithms/aes-gcm.ts +211 -0
  304. package/src/prototyping/crypto/algorithms/aes-kw.ts +164 -0
  305. package/src/prototyping/crypto/algorithms/ecdsa.ts +365 -0
  306. package/src/prototyping/crypto/algorithms/eddsa.ts +310 -0
  307. package/src/prototyping/crypto/algorithms/hkdf.ts +40 -0
  308. package/src/prototyping/crypto/algorithms/pbkdf2.ts +44 -0
  309. package/src/prototyping/crypto/crypto-error.ts +45 -0
  310. package/src/prototyping/crypto/dsa.ts +367 -0
  311. package/src/prototyping/crypto/jose/jwe-compact.ts +225 -0
  312. package/src/prototyping/crypto/jose/jwe-flattened.ts +459 -0
  313. package/src/prototyping/crypto/jose/jwe.ts +653 -0
  314. package/src/prototyping/crypto/primitives/aes-gcm.ts +374 -0
  315. package/src/prototyping/crypto/primitives/aes-kw.ts +271 -0
  316. package/src/prototyping/crypto/primitives/hkdf.ts +121 -0
  317. package/src/prototyping/crypto/primitives/pbkdf2.ts +116 -0
  318. package/src/prototyping/crypto/types/cipher.ts +17 -0
  319. package/src/prototyping/crypto/types/crypto-api.ts +78 -0
  320. package/src/prototyping/crypto/types/key-converter.ts +53 -0
  321. package/src/prototyping/crypto/types/key-deriver.ts +56 -0
  322. package/src/prototyping/crypto/types/key-io.ts +51 -0
  323. package/src/prototyping/crypto/types/key-manager.ts +83 -0
  324. package/src/prototyping/crypto/types/key-wrapper.ts +17 -0
  325. package/src/prototyping/crypto/types/params-direct.ts +95 -0
  326. package/src/prototyping/crypto/types/params-kms.ts +76 -0
  327. package/src/prototyping/crypto/utils.ts +41 -0
  328. package/src/prototyping/dids/resolver-cache-memory.ts +83 -0
  329. package/src/prototyping/dids/utils.ts +10 -0
  330. package/src/rpc-client.ts +162 -0
  331. package/src/store-data-protocols.ts +40 -0
  332. package/src/store-data.ts +400 -0
  333. package/src/store-did.ts +105 -0
  334. package/src/store-identity.ts +109 -0
  335. package/src/store-key.ts +104 -0
  336. package/src/sync-api.ts +71 -0
  337. package/src/sync-engine-level.ts +714 -0
  338. package/src/test-harness.ts +330 -0
  339. package/src/types/agent.ts +195 -0
  340. package/src/types/dwn.ts +278 -0
  341. package/src/types/identity-vault.ts +137 -0
  342. package/src/types/identity.ts +18 -0
  343. package/src/types/key-manager.ts +15 -0
  344. package/src/types/permissions.ts +115 -0
  345. package/src/types/sync.ts +58 -0
  346. package/src/types/vc.ts +7 -0
  347. package/src/utils-internal.ts +157 -0
  348. package/src/utils.ts +181 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.ts", "../../src/types/dwn.ts", "../../src/agent-did-resolver-cache.ts", "../../src/bearer-identity.ts", "../../src/crypto-api.ts", "../../src/prototyping/crypto/algorithms/hkdf.ts", "../../src/prototyping/crypto/primitives/hkdf.ts", "../../src/prototyping/crypto/algorithms/ecdsa.ts", "../../src/prototyping/crypto/crypto-error.ts", "../../src/prototyping/crypto/algorithms/eddsa.ts", "../../src/prototyping/crypto/algorithms/aes-kw.ts", "../../src/prototyping/crypto/primitives/aes-kw.ts", "../../src/prototyping/crypto/algorithms/pbkdf2.ts", "../../src/prototyping/crypto/primitives/pbkdf2.ts", "../../src/prototyping/crypto/algorithms/aes-gcm.ts", "../../src/did-api.ts", "../../src/store-did.ts", "../../src/store-data-protocols.ts", "../../src/prototyping/dids/utils.ts", "../../src/utils-internal.ts", "../../src/store-data.ts", "../../src/dwn-api.ts", "../../src/utils.ts", "../../src/dwn-registrar.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_assert.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/cryptoNode.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/utils.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_sha2.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_u64.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/sha512.ts", "../../../../node_modules/.pnpm/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/utils.ts", "../../../../node_modules/.pnpm/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/modular.ts", "../../../../node_modules/.pnpm/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/curve.ts", "../../../../node_modules/.pnpm/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/edwards.ts", "../../../../node_modules/.pnpm/@noble+curves@1.3.0/node_modules/@noble/curves/src/ed25519.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/hmac.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/ripemd160.ts", "../../../../node_modules/.pnpm/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/sha256.ts", "../../../../node_modules/.pnpm/ed25519-keygen@0.4.11/node_modules/ed25519-keygen/hdkey.js", "../../src/hd-identity-vault.ts", "../../src/local-key-manager.ts", "../../src/store-key.ts", "../../src/prototyping/crypto/jose/jwe-compact.ts", "../../src/prototyping/crypto/jose/jwe.ts", "../../src/prototyping/crypto/jose/jwe-flattened.ts", "../../src/prototyping/crypto/utils.ts", "../../src/prototyping/common/object.ts", "../../src/store-identity.ts", "../../src/identity-api.ts", "../../src/permissions-api.ts", "../../src/rpc-client.ts", "../../src/prototyping/clients/json-rpc.ts", "../../src/prototyping/clients/http-dwn-rpc-client.ts", "../../src/prototyping/clients/dwn-server-info-cache-memory.ts", "../../src/prototyping/clients/web-socket-clients.ts", "../../src/prototyping/clients/json-rpc-socket.ts", "../../src/sync-api.ts", "../../src/sync-engine-level.ts", "../../src/test-harness.ts", "../../src/prototyping/dids/resolver-cache-memory.ts", "../../src/oidc.ts", "../../src/connect.ts"],
4
+ "sourcesContent": ["export type * from './types/agent.js';\nexport * from './types/dwn.js';\nexport type * from './types/identity.js';\nexport type * from './types/identity-vault.js';\nexport type * from './types/key-manager.js';\nexport type * from './types/permissions.js';\nexport type * from './types/sync.js';\nexport type * from './types/vc.js';\n\nexport * from './agent-did-resolver-cache.js';\nexport * from './bearer-identity.js';\nexport * from './crypto-api.js';\nexport * from './did-api.js';\nexport * from './dwn-api.js';\nexport * from './dwn-registrar.js';\nexport * from './hd-identity-vault.js';\nexport * from './identity-api.js';\nexport * from './local-key-manager.js';\nexport * from './permissions-api.js';\nexport * from './rpc-client.js';\nexport * from './store-data.js';\nexport * from './store-did.js';\nexport * from './store-identity.js';\nexport * from './store-key.js';\nexport * from './sync-api.js';\nexport * from './sync-engine-level.js';\nexport * from './test-harness.js';\nexport * from './utils.js';\nexport * from './connect.js';\nexport * from './oidc.js';", "import type { DidService } from '@enbox/dids';\nimport type { Readable, RequireOnly } from '@enbox/common';\nimport type {\n RecordsReadReply,\n RecordsQueryReply,\n RecordsReadMessage,\n RecordsReadOptions,\n GenericMessageReply,\n ProtocolsQueryReply,\n RecordsQueryMessage,\n RecordsQueryOptions,\n RecordsWriteMessage,\n RecordsWriteOptions,\n RecordsDeleteMessage,\n RecordsDeleteOptions,\n ProtocolsQueryMessage,\n ProtocolsQueryOptions,\n ProtocolsConfigureMessage,\n ProtocolsConfigureOptions,\n RecordsSubscribeMessage,\n RecordsSubscribeOptions,\n RecordsSubscribeReply,\n MessageSubscriptionHandler,\n RecordSubscriptionHandler,\n MessagesQueryMessage,\n MessagesReadMessage,\n MessagesSubscribeMessage,\n MessagesQueryOptions,\n MessagesReadOptions,\n MessagesSubscribeOptions,\n MessagesQueryReply,\n MessagesReadReply,\n MessagesSubscribeReply,\n} from '@enbox/dwn-sdk-js';\n\nimport {\n RecordsRead,\n RecordsQuery,\n RecordsWrite,\n DwnMethodName,\n RecordsDelete,\n ProtocolsQuery,\n DwnInterfaceName,\n ProtocolsConfigure,\n RecordsSubscribe,\n MessagesQuery,\n MessagesRead,\n MessagesSubscribe,\n} from '@enbox/dwn-sdk-js';\n\n/**\n * Represents a Decentralized Web Node (DWN) service in a DID Document.\n *\n * A DWN DID service is a specialized type of DID service with the `type` set to\n * `DecentralizedWebNode`. It includes specific properties `enc` and `sig` that are used to identify\n * the public keys that can be used to interact with the DID Subject. The values of these properties\n * are strings or arrays of strings containing one or more verification method `id` values present in\n * the same DID document. If the `enc` and/or `sig` properties are an array of strings, an entity\n * interacting with the DID subject is expected to use the verification methods in the order they\n * are listed.\n *\n * @example\n * ```ts\n * const service: DwnDidService = {\n * id: 'did:example:123#dwn',\n * type: 'DecentralizedWebNode',\n * serviceEndpoint: 'https://enbox-production.up.railway.app',\n * enc: 'did:example:123#key-1',\n * sig: 'did:example:123#key-2'\n * }\n * ```\n *\n * @see {@link https://identity.foundation/decentralized-web-node/spec/ | DIF Decentralized Web Node (DWN) Specification}\n */\nexport interface DwnDidService extends DidService {\n /**\n * One or more verification method `id` values that can be used to encrypt information\n * intended for the DID subject.\n */\n enc?: string | string[];\n\n /**\n * One or more verification method `id` values that will be used by the DID subject to sign data\n * or by another entity to verify signatures created by the DID subject.\n */\n sig: string | string[];\n}\n\nexport enum DwnInterface {\n MessagesQuery = DwnInterfaceName.Messages + DwnMethodName.Query,\n MessagesRead = DwnInterfaceName.Messages + DwnMethodName.Read,\n MessagesSubscribe = DwnInterfaceName.Messages + DwnMethodName.Subscribe,\n ProtocolsConfigure = DwnInterfaceName.Protocols + DwnMethodName.Configure,\n ProtocolsQuery = DwnInterfaceName.Protocols + DwnMethodName.Query,\n RecordsDelete = DwnInterfaceName.Records + DwnMethodName.Delete,\n RecordsQuery = DwnInterfaceName.Records + DwnMethodName.Query,\n RecordsRead = DwnInterfaceName.Records + DwnMethodName.Read,\n RecordsSubscribe = DwnInterfaceName.Records + DwnMethodName.Subscribe,\n RecordsWrite = DwnInterfaceName.Records + DwnMethodName.Write\n}\n\nexport type DwnRecordsInterfaces = DwnInterface.RecordsDelete | DwnInterface.RecordsQuery | DwnInterface.RecordsRead | DwnInterface.RecordsSubscribe | DwnInterface.RecordsWrite;\nexport type DwnMessageInterfaces = DwnInterface.MessagesQuery | DwnInterface.MessagesRead | DwnInterface.MessagesSubscribe;\nexport type DwnProtocolInterfaces = DwnInterface.ProtocolsConfigure | DwnInterface.ProtocolsQuery;\n\nexport interface DwnMessage {\n [DwnInterface.MessagesQuery] : MessagesQueryMessage;\n [DwnInterface.MessagesRead] : MessagesReadMessage;\n [DwnInterface.MessagesSubscribe] : MessagesSubscribeMessage;\n [DwnInterface.ProtocolsConfigure] : ProtocolsConfigureMessage;\n [DwnInterface.ProtocolsQuery] : ProtocolsQueryMessage;\n [DwnInterface.RecordsDelete] : RecordsDeleteMessage;\n [DwnInterface.RecordsQuery] : RecordsQueryMessage;\n [DwnInterface.RecordsRead] : RecordsReadMessage;\n [DwnInterface.RecordsSubscribe] : RecordsSubscribeMessage;\n [DwnInterface.RecordsWrite] : RecordsWriteMessage;\n}\n\nexport interface DwnMessageDescriptor {\n [DwnInterface.MessagesQuery] : MessagesQueryMessage['descriptor'];\n [DwnInterface.MessagesRead] : MessagesReadMessage['descriptor'];\n [DwnInterface.MessagesSubscribe] : MessagesSubscribeMessage['descriptor'];\n [DwnInterface.ProtocolsConfigure] : ProtocolsConfigureMessage['descriptor'];\n [DwnInterface.ProtocolsQuery] : ProtocolsQueryMessage['descriptor'];\n [DwnInterface.RecordsDelete] : RecordsDeleteMessage['descriptor'];\n [DwnInterface.RecordsQuery] : RecordsQueryMessage['descriptor'];\n [DwnInterface.RecordsRead] : RecordsReadMessage['descriptor'];\n [DwnInterface.RecordsSubscribe] : RecordsSubscribeMessage['descriptor'];\n [DwnInterface.RecordsWrite] : RecordsWriteMessage['descriptor'];\n}\n\nexport interface DwnMessageParams {\n [DwnInterface.MessagesQuery] : RequireOnly<MessagesQueryOptions, 'filters'>;\n [DwnInterface.MessagesRead] : RequireOnly<MessagesReadOptions, 'messageCid'>;\n [DwnInterface.MessagesSubscribe] : Partial<MessagesSubscribeOptions>;\n [DwnInterface.ProtocolsConfigure] : RequireOnly<ProtocolsConfigureOptions, 'definition'>;\n [DwnInterface.ProtocolsQuery] : ProtocolsQueryOptions;\n [DwnInterface.RecordsDelete] : RequireOnly<RecordsDeleteOptions, 'recordId'>;\n [DwnInterface.RecordsQuery] : RecordsQueryOptions;\n [DwnInterface.RecordsRead] : RecordsReadOptions;\n [DwnInterface.RecordsSubscribe] : RecordsSubscribeOptions;\n [DwnInterface.RecordsWrite] : RecordsWriteOptions;\n}\n\nexport interface DwnMessageReply {\n [DwnInterface.MessagesQuery] : MessagesQueryReply;\n [DwnInterface.MessagesRead] : MessagesReadReply;\n [DwnInterface.MessagesSubscribe] : MessagesSubscribeReply;\n [DwnInterface.ProtocolsConfigure] : GenericMessageReply;\n [DwnInterface.ProtocolsQuery] : ProtocolsQueryReply;\n [DwnInterface.RecordsDelete] : GenericMessageReply;\n [DwnInterface.RecordsQuery] : RecordsQueryReply;\n [DwnInterface.RecordsRead] : RecordsReadReply;\n [DwnInterface.RecordsSubscribe] : RecordsSubscribeReply;\n [DwnInterface.RecordsWrite] : GenericMessageReply;\n}\n\nexport interface MessageHandler {\n [DwnInterface.MessagesSubscribe] : MessageSubscriptionHandler;\n [DwnInterface.RecordsSubscribe] : RecordSubscriptionHandler;\n\n // define all of them individually as undefined\n [DwnInterface.MessagesQuery] : undefined;\n [DwnInterface.MessagesRead] : undefined;\n [DwnInterface.ProtocolsConfigure] : undefined;\n [DwnInterface.ProtocolsQuery] : undefined;\n [DwnInterface.RecordsDelete] : undefined;\n [DwnInterface.RecordsQuery] : undefined;\n [DwnInterface.RecordsRead] : undefined;\n [DwnInterface.RecordsWrite] : undefined;\n}\n\nexport type DwnRequest<T extends DwnInterface> = {\n author: string;\n target: string;\n messageType: T;\n}\n\n/**\n * Defines the structure for response status, including a status code and detail message.\n */\nexport type DwnResponseStatus = {\n /** Encapsulates the outcome of an operation, providing both a numeric status code and a descriptive message. */\n status: {\n /** Numeric status code representing the outcome of the operation. */\n code: number;\n\n /** Descriptive detail about the status or error. */\n detail: string;\n };\n};\n\nexport type ProcessDwnRequest<T extends DwnInterface> = DwnRequest<T> & {\n dataStream?: Blob | ReadableStream | Readable;\n rawMessage?: DwnMessage[T];\n messageParams?: DwnMessageParams[T];\n store?: boolean;\n signAsOwner?: boolean;\n signAsOwnerDelegate?: boolean;\n granteeDid?: string;\n subscriptionHandler?: MessageHandler[T];\n}\n\nexport type SendDwnRequest<T extends DwnInterface> = DwnRequest<T> & (ProcessDwnRequest<T> | { messageCid: string })\n\nexport type DwnResponse<T extends DwnInterface> = {\n message?: DwnMessage[T];\n messageCid: string;\n reply: DwnMessageReply[T];\n}\n\nexport interface DwnMessageConstructor<T extends DwnInterface> {\n new (): DwnMessageInstance[T];\n create(params: DwnMessageParams[T]): Promise<DwnMessageInstance[T]>;\n parse(rawMessage: DwnMessage[T]): Promise<DwnMessageInstance[T]>;\n}\n\nexport const dwnMessageConstructors: { [T in DwnInterface]: DwnMessageConstructor<T> } = {\n [DwnInterface.MessagesQuery] : MessagesQuery as any,\n [DwnInterface.MessagesRead] : MessagesRead as any,\n [DwnInterface.MessagesSubscribe] : MessagesSubscribe as any,\n [DwnInterface.ProtocolsConfigure] : ProtocolsConfigure as any,\n [DwnInterface.ProtocolsQuery] : ProtocolsQuery as any,\n [DwnInterface.RecordsDelete] : RecordsDelete as any,\n [DwnInterface.RecordsQuery] : RecordsQuery as any,\n [DwnInterface.RecordsRead] : RecordsRead as any,\n [DwnInterface.RecordsSubscribe] : RecordsSubscribe as any,\n [DwnInterface.RecordsWrite] : RecordsWrite as any,\n} as const;\n\nexport type DwnMessageConstructors = typeof dwnMessageConstructors;\n\nexport interface DwnMessageInstance {\n [DwnInterface.MessagesQuery] : MessagesQuery;\n [DwnInterface.MessagesRead] : MessagesRead;\n [DwnInterface.MessagesSubscribe] : MessagesSubscribe;\n [DwnInterface.ProtocolsConfigure] : ProtocolsConfigure;\n [DwnInterface.ProtocolsQuery] : ProtocolsQuery;\n [DwnInterface.RecordsDelete] : RecordsDelete;\n [DwnInterface.RecordsQuery] : RecordsQuery;\n [DwnInterface.RecordsRead] : RecordsRead;\n [DwnInterface.RecordsSubscribe] : RecordsSubscribe;\n [DwnInterface.RecordsWrite] : RecordsWrite;\n}\n\nexport type DwnMessageWithData<T extends DwnInterface> = {\n message: DwnMessage[T];\n dataStream?: Readable;\n}\n\n// The following types are exported by the DWN SDK and are re-exported here so that dependent\n// packages do not need to import the DWN SDK directly. This ensures that downstream packages are\n// always using the same version of the DWN SDK as the agent package.\n\nexport {\n DwnConstant,\n Signer as DwnSigner,\n DateSort as DwnDateSort,\n DataEncodedRecordsWriteMessage as DwnDataEncodedRecordsWriteMessage,\n PublicJwk as DwnPublicKeyJwk, // TODO: Remove once DWN SDK switches to Jwk from @enbox/crypto\n PaginationCursor as DwnPaginationCursor,\n MessageSubscriptionHandler as DwnMessageSubscriptionHandler,\n RecordSubscriptionHandler as DwnRecordSubscriptionHandler,\n MessageSubscription as DwnMessageSubscription,\n MessagesPermissionScope as DwnMessagesPermissionScope,\n EncryptionAlgorithm as DwnEncryptionAlgorithm,\n KeyDerivationScheme as DwnKeyDerivationScheme,\n PermissionGrant as DwnPermissionGrant,\n PermissionGrantData as DwnPermissionGrantData,\n PermissionRequest as DwnPermissionRequest,\n PermissionRequestData as DwnPermissionRequestData,\n PermissionsProtocol as DwnPermissionsProtocol,\n ProtocolDefinition as DwnProtocolDefinition,\n ProtocolPermissionScope as DwnProtocolPermissionScope,\n RecordsPermissionScope as DwnRecordsPermissionScope,\n PermissionConditions as DwnPermissionConditions,\n PermissionScope as DwnPermissionScope,\n} from '@enbox/dwn-sdk-js';", "import { DidResolutionResult, DidResolverCache, DidResolverCacheLevel, DidResolverCacheLevelParams } from '@enbox/dids';\nimport { Web5PlatformAgent } from './types/agent.js';\nimport { logger } from '@enbox/common';\n\n\n/**\n * AgentDidResolverCache keeps a stale copy of the Agent's managed Identity DIDs and only evicts and refreshes upon a successful resolution.\n * This allows for quick and offline access to the internal DIDs used by the agent.\n */\nexport class AgentDidResolverCache extends DidResolverCacheLevel implements DidResolverCache {\n\n /**\n * Holds the instance of a `Web5PlatformAgent` that represents the current execution context for\n * the `AgentDidApi`. This agent is used to interact with other Web5 agent components. It's vital\n * to ensure this instance is set to correctly contextualize operations within the broader Web5\n * Agent framework.\n */\n private _agent?: Web5PlatformAgent;\n\n /** A map of DIDs that are currently in-flight. This helps avoid going into an infinite loop */\n private _resolving: Map<string, boolean> = new Map();\n\n constructor({ agent, db, location, ttl }: DidResolverCacheLevelParams & { agent?: Web5PlatformAgent }) {\n super ({ db, location, ttl });\n this._agent = agent;\n }\n\n get agent() {\n if (!this._agent) {\n throw new Error('Agent not initialized');\n }\n return this._agent;\n }\n\n set agent(agent: Web5PlatformAgent) {\n this._agent = agent;\n }\n\n /**\n * Get the DID resolution result from the cache for the given DID.\n *\n * If the DID is managed by the agent, or is the agent's own DID, it will not evict it from the cache until a new resolution is successful.\n * This is done to achieve quick and offline access to the agent's own managed DIDs.\n */\n async get(did: string): Promise<DidResolutionResult | void> {\n try {\n const str = await this.cache.get(did);\n const cachedResult = JSON.parse(str);\n if (!this._resolving.has(did) && Date.now() >= cachedResult.ttlMillis) {\n this._resolving.set(did, true);\n\n // if a DID is stored in the DID Store, then we don't want to evict it from the cache until we have a successful resolution\n // upon a successful resolution, we will update both the storage and the cache with the newly resolved Document.\n const storedDid = await this.agent.did.get({ didUri: did, tenant: this.agent.agentDid.uri });\n if ('undefined' !== typeof storedDid) {\n try {\n const result = await this.agent.did.resolve(did);\n\n // if the resolution was successful, update the stored DID with the new Document\n if (!result.didResolutionMetadata.error && result.didDocument) {\n\n const portableDid = {\n ...storedDid,\n document : result.didDocument,\n metadata : result.didDocumentMetadata,\n };\n\n try {\n // this will throw an error if the DID is not managed by the agent, or there is no difference between the stored and resolved DID\n // We don't publish the DID in this case, as it was received by the resolver.\n await this.agent.did.update({ portableDid, tenant: this.agent.agentDid.uri, publish: false });\n } catch(error: any) {\n // if the error is not due to no changes detected, log the error\n if (error.message && !error.message.includes('No changes detected, update aborted')) {\n logger.error(`Error updating DID: ${error.message}`);\n }\n }\n }\n } finally {\n this._resolving.delete(did);\n }\n } else {\n this._resolving.delete(did);\n this.cache.nextTick(() => this.cache.del(did));\n }\n }\n return cachedResult.value;\n } catch(error: any) {\n if (error.notFound) {\n return;\n }\n throw error;\n }\n }\n}", "import { BearerDid } from '@enbox/dids';\nimport { IdentityMetadata, PortableIdentity } from './types/identity.js';\n\n/**\n * Represents a Web5 Identity with its DID and metadata.\n */\nexport class BearerIdentity {\n /** {@inheritDoc BearerDid} */\n public did: BearerDid;\n\n /** {@inheritDoc DidMetadata} */\n public metadata: IdentityMetadata;\n\n constructor({ did, metadata }: {\n did: BearerDid;\n metadata: IdentityMetadata;\n }) {\n this.did = did;\n this.metadata = metadata;\n }\n\n /**\n * Converts a `BearerIdentity` object to a portable format containing the DID and metadata\n * associated with the Identity.\n *\n * @example\n * ```ts\n * // Assuming `identity` is an instance of BearerIdentity.\n * const portableIdentity = await identity.export();\n * // portableIdentity now contains the and metadata.\n * ```\n *\n * @returns A `PortableIdentity` containing the DID and metadata associated with the\n * `BearerIdentity`.\n */\n public async export(): Promise<PortableIdentity> {\n return {\n portableDid : await this.did.export(),\n metadata : { ...this.metadata },\n };\n }\n}", "import type {\n Jwk,\n Cipher,\n Hasher,\n Signer,\n KeyWrapper,\n SignParams,\n AesGcmParams,\n DigestParams,\n VerifyParams,\n GenerateKeyParams,\n GetPublicKeyParams,\n KmsGetKeyUriParams,\n AsymmetricKeyGenerator,\n} from '@enbox/crypto';\n\nimport { CryptoAlgorithm, Sha2Algorithm, computeJwkThumbprint } from '@enbox/crypto';\n\nimport type { CryptoApi } from './prototyping/crypto/types/crypto-api.js';\nimport type { HkdfParams } from './prototyping/crypto/primitives/hkdf.js';\nimport type { Pbkdf2Params } from './prototyping/crypto/primitives/pbkdf2.js';\nimport type { KeyBytesDeriver } from './prototyping/crypto/types/key-deriver.js';\nimport type { AsymmetricKeyConverter, KeyConverter } from './prototyping/crypto/types/key-converter.js';\nimport type { BytesToPrivateKeyParams, BytesToPublicKeyParams, CipherParams, DeriveKeyBytesParams, DeriveKeyParams, PrivateKeyToBytesParams, PublicKeyToBytesParams, UnwrapKeyParams, WrapKeyParams } from './prototyping/crypto/types/params-direct.js';\n\nimport { HkdfAlgorithm } from './prototyping/crypto/algorithms/hkdf.js';\nimport { EcdsaAlgorithm } from './prototyping/crypto/algorithms/ecdsa.js';\nimport { EdDsaAlgorithm } from './prototyping/crypto/algorithms/eddsa.js';\nimport { AesKwAlgorithm } from './prototyping/crypto/algorithms/aes-kw.js';\nimport { Pbkdf2Algorithm } from './prototyping/crypto/algorithms/pbkdf2.js';\nimport { AesGcmAlgorithm } from './prototyping/crypto/algorithms/aes-gcm.js';\nimport { CryptoError, CryptoErrorCode } from './prototyping/crypto/crypto-error.js';\n\nexport interface CryptoApiBytesToPrivateKeyParams extends BytesToPrivateKeyParams {\n algorithm: KeyConversionAlgorithm;\n}\n\nexport interface CryptoApiBytesToPublicKeyParams extends BytesToPublicKeyParams {\n algorithm: AsymmetricKeyConversionAlgorithm;\n}\n\n/**\n * The `CryptoApiCipherParams` interface defines the algorithm-specific parameters that should\n * be passed into the {@link AgentCryptoApi.encrypt | `AgentCryptoApi.encrypt()`} or\n * {@link AgentCryptoApi.decrypt | `AgentCryptoApi.decrypt()`} method.\n */\nexport interface CryptoApiCipherParams extends CipherParams, AesGcmParams {}\n\n/**\n * The `CryptoApiDigestParams` interface defines the algorithm-specific parameters that should\n * be passed into the {@link AgentCryptoApi.digest | `AgentCryptoApi.digest()`} method.\n */\nexport interface CryptoApiDigestParams extends DigestParams {\n /**\n * A string defining the name of hash function to use. The value must be one of the following:\n * - `\"SHA-256\"`: Generates a 256-bit digest.\n */\n algorithm: DigestAlgorithm;\n}\n\nexport interface CryptoApiDeriveKeyOptions {\n 'HKDF-256': Omit<HkdfParams, 'hash'> & { derivedKeyAlgorithm: CipherAlgorithm | KeyWrappingAlgorithm};\n 'HKDF-384': Omit<HkdfParams, 'hash'> & { derivedKeyAlgorithm: CipherAlgorithm | KeyWrappingAlgorithm};\n 'HKDF-512': Omit<HkdfParams, 'hash'> & { derivedKeyAlgorithm: CipherAlgorithm | KeyWrappingAlgorithm};\n 'PBES2-HS256+A128KW': Omit<Pbkdf2Params, 'hash'> & { derivedKeyAlgorithm?: never };\n 'PBES2-HS384+A192KW': Omit<Pbkdf2Params, 'hash'> & { derivedKeyAlgorithm?: never };\n 'PBES2-HS512+A256KW': Omit<Pbkdf2Params, 'hash'> & { derivedKeyAlgorithm?: never };\n}\n\nexport interface CryptoApiDeriveKeyBytesOptions {\n 'HKDF-256': Omit<HkdfParams, 'hash'>;\n 'HKDF-384': Omit<HkdfParams, 'hash'>;\n 'HKDF-512': Omit<HkdfParams, 'hash'>;\n 'PBES2-HS256+A128KW': Omit<Pbkdf2Params, 'hash'>;\n 'PBES2-HS384+A192KW': Omit<Pbkdf2Params, 'hash'>;\n 'PBES2-HS512+A256KW': Omit<Pbkdf2Params, 'hash'>;\n}\n\n/**\n * The `CryptoApiDeriveKeyParams` interface defines the algorithm-specific parameters that\n * should be passed into the {@link AgentCryptoApi.deriveKey | `AgentCryptoApi.deriveKey()`} method.\n */\nexport type CryptoApiDeriveKeyParams<T extends DeriveKeyAlgorithm> = DeriveKeyParams & {\n /**\n * A string defining the name of key derivation function to use. The value must be one of the\n * following:\n * - `\"HKDF-256\"`: HKDF with SHA-256.\n * - `\"HKDF-384\"`: HKDF with SHA-384.\n * - `\"HKDF-512\"`: HKDF with SHA-512.\n * - `\"PBKDF2-HS256+A128KW\"`: PBKDF2 with HMAC SHA-256 and A128KW key wrapping.\n * - `\"PBKDF2-HS384+A192KW\"`: PBKDF2 with HMAC SHA-384 and A192KW key wrapping.\n * - `\"PBKDF2-HS512+A256KW\"`: PBKDF2 with HMAC SHA-512 and A256KW key wrapping.\n */\n algorithm: T;\n} & CryptoApiDeriveKeyOptions[T];\n\n/**\n * The `CryptoApiDeriveKeyBytesParams` interface defines the algorithm-specific parameters that\n * should be passed into the {@link AgentCryptoApi.deriveKeyBytes | `AgentCryptoApi.deriveKeyBytes()`} method.\n */\nexport type CryptoApiDeriveKeyBytesParams<T extends DeriveKeyByteAlgorithm> = DeriveKeyBytesParams & {\n /**\n * A string defining the name of key derivation function to use. The value must be one of the\n * following:\n * - `\"HKDF-256\"`: HKDF with SHA-256.\n * - `\"HKDF-384\"`: HKDF with SHA-384.\n * - `\"HKDF-512\"`: HKDF with SHA-512.\n * - `\"PBKDF2-HS256+A128KW\"`: PBKDF2 with HMAC SHA-256 and A128KW key wrapping.\n * - `\"PBKDF2-HS384+A192KW\"`: PBKDF2 with HMAC SHA-384 and A192KW key wrapping.\n * - `\"PBKDF2-HS512+A256KW\"`: PBKDF2 with HMAC SHA-512 and A256KW key wrapping.\n */\n algorithm: T;\n} & CryptoApiDeriveKeyBytesOptions[T];\n\nexport interface CryptoApiGenerateKeyParams extends GenerateKeyParams {\n algorithm: KeyGenerationAlgorithm;\n}\n\n/**\n * `supportedAlgorithms` is an object mapping algorithm names to their respective implementations\n * Each entry in this map specifies the algorithm name and its associated properties, including the\n * implementation class and any relevant names or identifiers for the algorithm. This structure\n * allows for easy retrieval and instantiation of algorithm implementations based on the algorithm\n * name or key specification. It facilitates the support of multiple algorithms within the\n * `LocalKeyManager` class.\n */\nconst supportedAlgorithms = {\n 'AES-GCM': {\n implementation : AesGcmAlgorithm,\n names : ['A128GCM', 'A192GCM', 'A256GCM'],\n operations : ['bytesToPrivateKey', 'decrypt', 'encrypt', 'generateKey'],\n },\n 'AES-KW': {\n implementation : AesKwAlgorithm,\n names : ['A128KW', 'A192KW', 'A256KW'],\n operations : ['bytesToPrivateKey', 'generateKey', 'privateKeyToBytes', 'wrapKey', 'unwrapKey'],\n },\n 'Ed25519': {\n implementation : EdDsaAlgorithm,\n names : ['Ed25519'],\n operations : ['bytesToPrivateKey', 'bytesToPublicKey', 'generateKey', 'sign', 'verify'],\n },\n 'HKDF': {\n implementation : HkdfAlgorithm,\n names : ['HKDF-256', 'HKDF-384', 'HKDF-512'],\n operations : ['deriveKey', 'deriveKeyBytes'],\n },\n 'PBKDF2': {\n implementation : Pbkdf2Algorithm,\n names : ['PBES2-HS256+A128KW', 'PBES2-HS384+A192KW', 'PBES2-HS512+A256KW'],\n operations : ['deriveKey', 'deriveKeyBytes'],\n },\n 'secp256k1': {\n implementation : EcdsaAlgorithm,\n names : ['ES256K', 'secp256k1'],\n operations : ['bytesToPrivateKey', 'bytesToPublicKey', 'generateKey', 'sign', 'verify'],\n },\n 'secp256r1': {\n implementation : EcdsaAlgorithm,\n names : ['ES256', 'secp256r1'],\n operations : ['bytesToPrivateKey', 'bytesToPublicKey', 'generateKey', 'sign', 'verify'],\n },\n 'SHA-256': {\n implementation : Sha2Algorithm,\n names : ['SHA-256'],\n operations : ['digest'],\n }\n} as const;\n\n/* Helper types for `supportedAlgorithms`. */\ntype SupportedAlgorithm = keyof typeof supportedAlgorithms;\ntype SupportedAlgorithms = typeof supportedAlgorithms;\n\n/* Helper type for `supportedAlgorithms` implementations. */\ntype AlgorithmConstructor = typeof supportedAlgorithms[SupportedAlgorithm]['implementation'];\n\ntype CipherAlgorithms = {\n [K in keyof SupportedAlgorithms]: 'encrypt' extends SupportedAlgorithms[K]['operations'][number] ? K : never\n}[keyof SupportedAlgorithms];\n\ntype CipherAlgorithm = typeof supportedAlgorithms[CipherAlgorithms]['names'][number];\n\ntype DeriveKeyAlgorithms = {\n [K in keyof SupportedAlgorithms]: 'deriveKey' extends SupportedAlgorithms[K]['operations'][number] ? K : never\n}[keyof SupportedAlgorithms];\n\ntype DeriveKeyAlgorithm = typeof supportedAlgorithms[DeriveKeyAlgorithms]['names'][number];\n\ntype DeriveKeyBytesAlgorithms = {\n [K in keyof SupportedAlgorithms]: 'deriveKeyBytes' extends SupportedAlgorithms[K]['operations'][number] ? K : never\n}[keyof SupportedAlgorithms];\n\ntype DeriveKeyByteAlgorithm = typeof supportedAlgorithms[DeriveKeyBytesAlgorithms]['names'][number];\n\ntype DigestAlgorithms = {\n [K in keyof SupportedAlgorithms]: 'digest' extends SupportedAlgorithms[K]['operations'][number] ? K : never\n}[keyof SupportedAlgorithms];\n\ntype DigestAlgorithm = typeof supportedAlgorithms[DigestAlgorithms]['names'][number];\n\ntype KeyConversionAlgorithms = {\n [K in keyof SupportedAlgorithms]: 'bytesToPrivateKey' extends SupportedAlgorithms[K]['operations'][number] ? K : never\n}[keyof SupportedAlgorithms];\n\ntype KeyConversionAlgorithm = typeof supportedAlgorithms[KeyConversionAlgorithms]['names'][number];\n\ntype AsymmetricKeyConversionAlgorithms = {\n [K in keyof SupportedAlgorithms]: 'bytesToPublicKey' extends SupportedAlgorithms[K]['operations'][number] ? K : never\n}[keyof SupportedAlgorithms];\n\ntype AsymmetricKeyConversionAlgorithm = typeof supportedAlgorithms[AsymmetricKeyConversionAlgorithms]['names'][number];\n\ntype KeyWrappingAlgorithms = {\n [K in keyof SupportedAlgorithms]: 'wrapKey' extends SupportedAlgorithms[K]['operations'][number] ? K : never\n}[keyof SupportedAlgorithms];\n\ntype KeyWrappingAlgorithm = typeof supportedAlgorithms[KeyWrappingAlgorithms]['names'][number];\n\ntype KeyGenerationAlgorithms = {\n [K in keyof SupportedAlgorithms]: 'generateKey' extends SupportedAlgorithms[K]['operations'][number] ? K : never\n}[keyof SupportedAlgorithms];\n\ntype KeyGenerationAlgorithm = typeof supportedAlgorithms[KeyGenerationAlgorithms]['names'][number];\n\nexport class AgentCryptoApi implements CryptoApi<\n CryptoApiGenerateKeyParams, Jwk, GetPublicKeyParams,\n CryptoApiDigestParams,\n SignParams, VerifyParams,\n CryptoApiCipherParams, CryptoApiCipherParams,\n CryptoApiBytesToPublicKeyParams, PublicKeyToBytesParams,\n CryptoApiBytesToPrivateKeyParams, PrivateKeyToBytesParams,\n CryptoApiDeriveKeyParams<DeriveKeyAlgorithm>, Jwk,\n CryptoApiDeriveKeyBytesParams<DeriveKeyAlgorithm>, Uint8Array,\n WrapKeyParams, UnwrapKeyParams\n> {\n\n /**\n * A private map that stores instances of cryptographic algorithm implementations. Each key in\n * this map is an `AlgorithmConstructor`, and its corresponding value is an instance of a class\n * that implements a specific cryptographic algorithm. This map is used to cache and reuse\n * instances for performance optimization, ensuring that each algorithm is instantiated only once.\n */\n private _algorithmInstances: Map<AlgorithmConstructor, InstanceType<typeof CryptoAlgorithm>> = new Map();\n\n public async bytesToPrivateKey({ algorithm: algorithmIdentifier, privateKeyBytes }:\n CryptoApiBytesToPrivateKeyParams\n ): Promise<Jwk> {\n // Determine the algorithm name based on the given algorithm identifier.\n const algorithm = this.getAlgorithmName({ algorithm: algorithmIdentifier });\n\n // Get the key converter based on the algorithm name.\n const keyConverter = this.getAlgorithm({ algorithm }) as KeyConverter<CryptoApiBytesToPrivateKeyParams, PrivateKeyToBytesParams>;\n\n // Convert the byte array to a JWK.\n const privateKey = await keyConverter.bytesToPrivateKey({ algorithm: algorithmIdentifier, privateKeyBytes });\n\n return privateKey;\n }\n\n public async bytesToPublicKey({ algorithm: algorithmIdentifier, publicKeyBytes }:\n CryptoApiBytesToPublicKeyParams\n ): Promise<Jwk> {\n // Determine the algorithm name based on the given algorithm identifier.\n const algorithm = this.getAlgorithmName({ algorithm: algorithmIdentifier });\n\n // Get the key converter based on the algorithm name.\n const keyConverter = this.getAlgorithm({ algorithm }) as AsymmetricKeyConverter<CryptoApiBytesToPublicKeyParams, PublicKeyToBytesParams>;\n\n // Convert the byte array to a JWK.\n const publicKey = await keyConverter.bytesToPublicKey({ algorithm: algorithmIdentifier, publicKeyBytes });\n\n return publicKey;\n }\n\n public async decrypt(params: CryptoApiCipherParams): Promise<Uint8Array> {\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: params.key });\n\n // Get the cipher algorithm based on the algorithm name.\n const cipher = this.getAlgorithm({ algorithm }) as Cipher<CipherParams, CipherParams>;\n\n // Decrypt the data.\n return await cipher.decrypt(params);\n }\n\n public async deriveKey<T extends DeriveKeyAlgorithm>(\n params: CryptoApiDeriveKeyParams<T>\n ): Promise<Jwk> {\n // Determine the algorithm name based on the given algorithm identifier.\n const algorithm = this.getAlgorithmName({ algorithm: params.algorithm });\n\n // Get the key derivation function based on the algorithm name.\n const kdf = this.getAlgorithm({ algorithm }) as KeyBytesDeriver<DeriveKeyBytesParams, Uint8Array>;\n\n let derivedKeyAlgorithm: CipherAlgorithm | KeyWrappingAlgorithm;\n\n switch (params.algorithm) {\n case 'HKDF-256':\n case 'HKDF-384':\n case 'HKDF-512': {\n derivedKeyAlgorithm = params.derivedKeyAlgorithm as CipherAlgorithm | KeyWrappingAlgorithm;\n break;\n }\n\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n derivedKeyAlgorithm = params.algorithm.split(/[-+]/)[2] as 'A128KW' | 'A192KW' | 'A256KW';\n break;\n }\n\n default:\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The specified \"algorithm\" is not supported: ${params.algorithm}`);\n }\n\n // Determine the bit length of the derived key based on the given algorithm.\n const length = +(derivedKeyAlgorithm.match(/\\d+/)?.[0] ?? -1);\n\n if (length === -1) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The derived key algorithm\" is not supported: ${derivedKeyAlgorithm}`);\n }\n\n // Derive the byte array.\n const privateKeyBytes = await kdf.deriveKeyBytes({ ...params, length });\n\n return await this.bytesToPrivateKey({ algorithm: derivedKeyAlgorithm, privateKeyBytes });\n }\n\n public async deriveKeyBytes<T extends DeriveKeyAlgorithm>(\n params: CryptoApiDeriveKeyBytesParams<T>\n ): Promise<Uint8Array> {\n // Determine the algorithm name based on the given algorithm identifier.\n const algorithm = this.getAlgorithmName({ algorithm: params.algorithm });\n\n // Get the key derivation function based on the algorithm name.\n const kdf = this.getAlgorithm({ algorithm }) as KeyBytesDeriver<DeriveKeyBytesParams, Uint8Array>;\n\n // Derive the byte array.\n const derivedKeyBytes = await kdf.deriveKeyBytes(params);\n\n return derivedKeyBytes;\n }\n\n /**\n * Generates a hash digest of the provided data.\n *\n * @remarks\n * A digest is the output of the hash function. It's a fixed-size string of bytes that uniquely\n * represents the data input into the hash function. The digest is often used for data integrity\n * checks, as any alteration in the input data results in a significantly different digest.\n *\n * It takes the algorithm identifier of the hash function and data to digest as input and returns\n * the digest of the data.\n *\n * @example\n * ```ts\n * const cryptoApi = new AgentCryptoApi();\n * const data = new Uint8Array([...]);\n * const digest = await cryptoApi.digest({ algorithm: 'SHA-256', data });\n * ```\n *\n * @param params - The parameters for the digest operation.\n * @param params.algorithm - The name of hash function to use.\n * @param params.data - The data to digest.\n *\n * @returns A Promise which will be fulfilled with the hash digest.\n */\n public async digest({ algorithm, data }:\n CryptoApiDigestParams\n ): Promise<Uint8Array> {\n // Get the hash function implementation based on the specified `algorithm` parameter.\n const hasher = this.getAlgorithm({ algorithm }) as Hasher<CryptoApiDigestParams>;\n\n // Compute the hash.\n const hash = await hasher.digest({ algorithm, data });\n\n return hash;\n }\n\n public async encrypt(params: CryptoApiCipherParams): Promise<Uint8Array> {\n // If th\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: params.key });\n\n // Get the cipher algorithm based on the algorithm name.\n const cipher = this.getAlgorithm({ algorithm }) as Cipher<CipherParams, CipherParams>;\n\n // Encrypt the data and return the ciphertext.\n return await cipher.encrypt(params);\n }\n\n public async generateKey(params: CryptoApiGenerateKeyParams): Promise<Jwk> {\n // Determine the algorithm name based on the given algorithm identifier.\n const algorithm = this.getAlgorithmName({ algorithm: params.algorithm });\n\n // Get the key generator implementation based on the algorithm.\n const keyGenerator = this.getAlgorithm({ algorithm }) as AsymmetricKeyGenerator<CryptoApiGenerateKeyParams, Jwk, GetPublicKeyParams>;\n\n // Generate the key.\n const privateKey = await keyGenerator.generateKey({ algorithm: params.algorithm });\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n privateKey.kid ??= await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n // ! TODO: Remove this once the `Dsa` interface is updated in @enbox/crypto to remove KMS-specific methods.\n public async getKeyUri(_params: KmsGetKeyUriParams): Promise<string> {\n throw new Error('Method not implemented.');\n }\n\n public async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key });\n\n // Get the key generator based on the algorithm name.\n const keyGenerator = this.getAlgorithm({ algorithm }) as AsymmetricKeyGenerator<CryptoApiGenerateKeyParams, Jwk, GetPublicKeyParams>;\n\n // Get the public key properties from the private JWK.\n const publicKey = await keyGenerator.getPublicKey({ key });\n\n return publicKey;\n }\n\n public async privateKeyToBytes({ privateKey }: { privateKey: Jwk; }): Promise<Uint8Array> {\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the key converter based on the algorithm name.\n const keyConverter = this.getAlgorithm({ algorithm }) as KeyConverter<CryptoApiBytesToPrivateKeyParams, PrivateKeyToBytesParams>;\n\n // Convert the JWK to a byte array.\n const privateKeyBytes = await keyConverter.privateKeyToBytes({ privateKey });\n\n return privateKeyBytes;\n }\n\n public async publicKeyToBytes({ publicKey }: { publicKey: Jwk; }): Promise<Uint8Array> {\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: publicKey });\n\n // Get the key converter based on the algorithm name.\n const keyConverter = this.getAlgorithm({ algorithm }) as AsymmetricKeyConverter<CryptoApiBytesToPublicKeyParams, PublicKeyToBytesParams>;\n\n // Convert the JWK to a byte array.\n const publicKeyBytes = await keyConverter.publicKeyToBytes({ publicKey });\n\n return publicKeyBytes;\n }\n\n public async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key });\n\n // Get the signature algorithm based on the algorithm name.\n const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n // Sign the data.\n const signature = signer.sign({ data, key });\n\n return signature;\n }\n\n public async unwrapKey(params: UnwrapKeyParams): Promise<Jwk> {\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: params.decryptionKey });\n\n // Get the key wrapping algorithm based on the algorithm name.\n const keyWrapper = this.getAlgorithm({ algorithm }) as KeyWrapper<WrapKeyParams, UnwrapKeyParams>;\n\n // decrypt the key and return the ciphertext.\n return await keyWrapper.unwrapKey(params);\n }\n\n public async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key });\n\n // Get the signature algorithm based on the algorithm name.\n const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n // Verify the signature.\n const isSignatureValid = signer.verify({ key, signature, data });\n\n return isSignatureValid;\n }\n\n public async wrapKey(params: WrapKeyParams): Promise<Uint8Array> {\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: params.encryptionKey });\n\n // Get the key wrapping algorithm based on the algorithm name.\n const keyWrapper = this.getAlgorithm({ algorithm }) as KeyWrapper<WrapKeyParams, UnwrapKeyParams>;\n\n // Encrypt the key and return the ciphertext.\n return await keyWrapper.wrapKey(params);\n }\n\n /**\n * Retrieves an algorithm implementation instance based on the provided algorithm name.\n *\n * @remarks\n * This method checks if the requested algorithm is supported and returns a cached instance\n * if available. If an instance does not exist, it creates and caches a new one. This approach\n * optimizes performance by reusing algorithm instances across cryptographic operations.\n *\n * @example\n * ```ts\n * const signer = this.getAlgorithm({ algorithm: 'Ed25519' });\n * ```\n *\n * @param params - The parameters for retrieving the algorithm implementation.\n * @param params.algorithm - The name of the algorithm to retrieve.\n *\n * @returns An instance of the requested algorithm implementation.\n *\n * @throws Error if the requested algorithm is not supported.\n */\n private getAlgorithm({ algorithm }: {\n algorithm: SupportedAlgorithm;\n }): InstanceType<typeof CryptoAlgorithm> {\n // Check if algorithm is supported.\n const AlgorithmImplementation = supportedAlgorithms[algorithm]?.['implementation'];\n if (!AlgorithmImplementation) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n }\n\n // Check if instance already exists for the `AlgorithmImplementation`.\n if (!this._algorithmInstances.has(AlgorithmImplementation)) {\n // If not, create a new instance and store it in the cache\n this._algorithmInstances.set(AlgorithmImplementation, new AlgorithmImplementation());\n }\n\n // Return the cached instance\n return this._algorithmInstances.get(AlgorithmImplementation)!;\n }\n\n /**\n * Determines the algorithm name based on the key's properties.\n *\n * @remarks\n * This method facilitates the identification of the correct algorithm for cryptographic\n * operations based on the `alg` or `crv` properties of a {@link Jwk | JWK}.\n *\n * @example\n * ```ts\n * const key = { ... }; // Public key in JWK format\n * const algorithm = this.getAlgorithmName({ key });\n * ```\n *\n * @example\n * ```ts\n * const algorithm = this.getAlgorithmName({ algorithm: 'ES256' });\n * ```\n *\n * @param params - The parameters for determining the algorithm name.\n * @param params.key - A JWK containing the `alg` or `crv` properties.\n *\n * @returns The algorithm name associated with the key.\n *\n * @throws Error if the algorithm name cannot be determined from the provided input.\n */\n private getAlgorithmName({ key }: { key: Jwk }): SupportedAlgorithm;\n private getAlgorithmName({ algorithm }: { algorithm: string }): SupportedAlgorithm;\n private getAlgorithmName({ algorithm, key }: {\n algorithm?: string;\n key?: { alg?: string, crv?: string };\n }): SupportedAlgorithm {\n const algProperty = key?.alg ?? algorithm;\n const crvProperty = key?.crv;\n\n for (const algorithmIdentifier of Object.keys(supportedAlgorithms) as SupportedAlgorithm[]) {\n const algorithmNames = supportedAlgorithms[algorithmIdentifier].names as readonly string[];\n if (algProperty && algorithmNames.includes(algProperty)) {\n return algorithmIdentifier;\n } else if (crvProperty && algorithmNames.includes(crvProperty)) {\n return algorithmIdentifier;\n }\n }\n\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported,\n `Algorithm not supported based on provided input: alg=${algProperty}, crv=${crvProperty}. ` +\n 'Please check the documentation for the list of supported algorithms.'\n );\n }\n}", "import { CryptoAlgorithm } from '@enbox/crypto';\n\nimport type { DeriveKeyBytesParams } from '../types/params-direct.js';\n\nimport { Hkdf, HkdfParams } from '../primitives/hkdf.js';\nimport { KeyBytesDeriver } from '../types/key-deriver.js';\n\n/**\n * The `HkdfDeriveKeyBytesParams` interface defines the algorithm-specific parameters that should be\n * passed into the `deriveKeyBytes()` method when using the HKDF algorithm.\n */\nexport interface HkdfDeriveKeyBytesParams extends DeriveKeyBytesParams {\n /** Specifies the algorithm variant for HKDF key derivation.\n * The value determines the hash function that will be used and must be one of the following:\n * - `\"HKDF-256\"`: HKDF with SHA-256.\n * - `\"HKDF-384\"`: HKDF with SHA-384.\n * - `\"HKDF-512\"`: HKDF with SHA-512.\n */\n algorithm: 'HKDF-256' | 'HKDF-384' | 'HKDF-512';\n}\n\nexport class HkdfAlgorithm extends CryptoAlgorithm\n implements KeyBytesDeriver<HkdfDeriveKeyBytesParams, Uint8Array> {\n\n public async deriveKeyBytes({ algorithm, ...params }:\n HkdfDeriveKeyBytesParams & Omit<HkdfParams, 'hash'>\n ): Promise<Uint8Array> {\n // Map algorithm name to hash function.\n const hash = {\n 'HKDF-256' : 'SHA-256' as const,\n 'HKDF-384' : 'SHA-384' as const,\n 'HKDF-512' : 'SHA-512' as const\n }[algorithm];\n\n // Derive a cryptographic byte array using HKDF.\n const derivedKeyBytes = await Hkdf.deriveKeyBytes({ ...params, hash });\n\n return derivedKeyBytes;\n }\n}", "// ! TODO : Make sure I remove `@noble/ciphers` from the Agent package.json once this is moved to the `@enbox/crypto` package.\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\n\nimport { Convert } from '@enbox/common';\nimport { DeriveKeyBytesParams } from '../types/params-direct.js';\n\n/**\n * The object that should be passed into `Hkdf.deriveKey()`, when using the HKDF algorithm.\n */\nexport type HkdfParams = {\n /**\n * A string representing the digest algorithm to use. This may be one of:\n * - 'SHA-256'\n * - 'SHA-384'\n * - 'SHA-512'\n */\n hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n /**\n * The salt value to use in the derivation process.\n *\n * Ideally, the salt is a random or pseudo-random value with the same length as the output of the\n * digest function. Unlike the input key material passed into deriveKey(), salt does not need to\n * be kept secret.\n *\n * Note: The {@link https://datatracker.ietf.org/doc/html/rfc5869 | HKDF specification} states\n * that adding salt \"adds significantly to the strength of HKDF\".\n */\n salt: string | Uint8Array;\n\n /**\n * Optional application-specific information to use in the HKDF.\n *\n * If given, this value is used to bind the derived key to application-specific contextual\n * information. This makes it possible to derive different keys for different contexts while using\n * the same input key material.\n *\n * If not provided, the `info` value is set to an empty array.\n *\n * Note: It is important that the `info` value be independent and unrelated to the input key\n * material.\n */\n info?: string | Uint8Array,\n};\n\n/**\n * The `Hkdf` class provides an interface for HMAC-based Extract-and-Expand Key Derivation Function (HKDF)\n * as defined in RFC 5869.\n *\n * Note: The `baseKeyBytes` that will be the input key material for HKDF should be a high-entropy secret\n * value, such as a cryptographic key. It should be kept confidential and not be derived from a\n * low-entropy value, such as a password.\n *\n * @example\n * ```ts\n * const info = new Uint8Array([...]);\n * const derivedKeyBytes = await Hkdf.deriveKeyBytes({\n * baseKeyBytes: new Uint8Array([...]), // Input keying material\n * hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n * salt: new Uint8Array([...]), // The salt value\n * info: new Uint8Array([...]), // Optional application-specific information\n * length: 256 // The length of the derived key in bits\n * });\n * ```\n */\nexport class Hkdf {\n /**\n * Derives a key using the HMAC-based Extract-and-Expand Key Derivation Function (HKDF).\n *\n * This method generates a derived key using a hash function from input keying material given as\n * `baseKeyBytes`. The length of the derived key can be specified. Optionally, it can also use a salt\n * and info for the derivation process.\n *\n * HKDF is useful in various cryptographic applications and protocols, especially when\n * there's a need to derive multiple keys from a single source of key material.\n *\n * Note: The `baseKeyBytes` that will be the input key material for HKDF should be a high-entropy\n * secret value, such as a cryptographic key. It should be kept confidential and not be derived\n * from a low-entropy value, such as a password.\n *\n * @example\n * ```ts\n * const info = new Uint8Array([...]);\n * const derivedKeyBytes = await Hkdf.deriveKeyBytes({\n * baseKeyBytes: new Uint8Array([...]), // Input keying material\n * hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n * salt: new Uint8Array([...]), // The salt value\n * info: new Uint8Array([...]), // Optional application-specific information\n * length: 256 // The length of the derived key in bits\n * });\n * ```\n *\n * @param params - The parameters for key derivation.\n * @returns A Promise that resolves to the derived key as a byte array.\n */\n public static async deriveKeyBytes({ baseKeyBytes, length, hash, salt, info = new Uint8Array() }:\n DeriveKeyBytesParams & HkdfParams\n ): Promise<Uint8Array> {\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Import the baseKeyBytes into the Web Crypto API to use for the key derivation operation.\n const webCryptoKey = await webCrypto.importKey('raw', baseKeyBytes, { name: 'HKDF' }, false, ['deriveBits']);\n\n // Convert the salt and info to Uint8Array if they are provided as strings.\n salt = typeof salt === 'string' ? Convert.string(salt).toUint8Array() : salt;\n info = typeof info === 'string' ? Convert.string(info).toUint8Array() : info;\n\n // Derive the bytes using the Web Crypto API.\n const derivedKeyBuffer = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash, salt, info },\n webCryptoKey,\n length\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const derivedKeyBytes = new Uint8Array(derivedKeyBuffer);\n\n return derivedKeyBytes;\n }\n}", "import type {\n Jwk,\n Signer,\n SignParams,\n KeyConverter,\n VerifyParams,\n GenerateKeyParams,\n GetPublicKeyParams,\n AsymmetricKeyConverter,\n AsymmetricKeyGenerator,\n ComputePublicKeyParams,\n} from '@enbox/crypto';\n\nimport { CryptoAlgorithm, isEcPrivateJwk, isEcPublicJwk, Secp256k1, Secp256r1 } from '@enbox/crypto';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\nimport { BytesToPrivateKeyParams, BytesToPublicKeyParams, PrivateKeyToBytesParams, PublicKeyToBytesParams } from '../types/params-direct.js';\n\n/**\n * The `EcdsaGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the ECDSA algorithm.\n */\nexport interface EcdsaGenerateKeyParams extends GenerateKeyParams {\n /**\n * A string defining the type of key to generate. The value must be one of the following:\n * - `\"ES256\"`: ECDSA using the secp256r1 (P-256) curve and SHA-256.\n * - `\"ES256K\"`: ECDSA using the secp256k1 curve and SHA-256.\n * - `\"secp256k1\"`: ECDSA using the secp256k1 curve and SHA-256.\n * - `\"secp256r1\"`: ECDSA using the secp256r1 (P-256) curve and SHA-256.\n */\n algorithm: 'ES256' | 'ES256K' | 'secp256k1' | 'secp256r1';\n}\n\n/**\n * The `EcdsaAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the Elliptic Curve Digital Signature Algorithm (ECDSA). This class implements both\n * {@link Signer | `Signer`} and { @link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`}\n * interfaces, providing private key generation, public key derivation, and creation/verification\n * of signatures.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class EcdsaAlgorithm extends CryptoAlgorithm\n implements AsymmetricKeyGenerator<EcdsaGenerateKeyParams, Jwk, GetPublicKeyParams>,\n KeyConverter, AsymmetricKeyConverter,\n Signer<SignParams, VerifyParams> {\n\n public async bytesToPrivateKey({ algorithm, privateKeyBytes }:\n BytesToPrivateKeyParams & { algorithm: 'ES256' | 'ES256K' | 'secp256k1' | 'secp256r1' }\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'ES256K':\n case 'secp256k1': {\n const privateKey = await Secp256k1.bytesToPrivateKey({ privateKeyBytes });\n privateKey.alg = 'EdDSA';\n return privateKey;\n }\n\n case 'ES256':\n case 'secp256r1': {\n const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });\n privateKey.alg = 'EdDSA';\n return privateKey;\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n }\n }\n }\n\n public async bytesToPublicKey({ algorithm, publicKeyBytes }:\n BytesToPublicKeyParams & { algorithm: 'ES256' | 'ES256K' | 'secp256k1' | 'secp256r1' }\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'ES256K':\n case 'secp256k1': {\n const publicKey = await Secp256k1.bytesToPublicKey({ publicKeyBytes });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n case 'ES256':\n case 'secp256r1': {\n const publicKey = await Secp256r1.bytesToPublicKey({ publicKeyBytes });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n }\n }\n }\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The process ensures that the derived public key correctly corresponds to\n * the given private key.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await ecdsa.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n if (!isEcPrivateJwk(key)) throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');\n\n switch (key.crv) {\n\n case 'secp256k1': {\n const publicKey = await Secp256k1.computePublicKey({ key });\n publicKey.alg = 'ES256K';\n return publicKey;\n }\n\n case 'P-256': {\n const publicKey = await Secp256r1.computePublicKey({ key });\n publicKey.alg = 'ES256';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates a new private key with the specified algorithm in JSON Web Key (JWK) format.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = await ecdsa.generateKey({ algorithm: 'ES256K' });\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation.\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public async generateKey({ algorithm }:\n EcdsaGenerateKeyParams\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'ES256K':\n case 'secp256k1': {\n const privateKey = await Secp256k1.generateKey();\n privateKey.alg = 'ES256K';\n return privateKey;\n }\n\n case 'ES256':\n case 'secp256r1': {\n const privateKey = await Secp256r1.generateKey();\n privateKey.alg = 'ES256';\n return privateKey;\n }\n }\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an ECDSA private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key.\n *\n * Note: This method offers a significant performance advantage, being about 200 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await ecdsa.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n if (!isEcPrivateJwk(key)) throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');\n\n switch (key.crv) {\n\n case 'secp256k1': {\n const publicKey = await Secp256k1.getPublicKey({ key });\n publicKey.alg = 'ES256K';\n return publicKey;\n }\n\n case 'P-256': {\n const publicKey = await Secp256r1.getPublicKey({ key });\n publicKey.alg = 'ES256';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n public async privateKeyToBytes({ privateKey }:\n PrivateKeyToBytesParams\n ): Promise<Uint8Array> {\n switch (privateKey.crv) {\n\n case 'secp256k1': {\n return await Secp256k1.privateKeyToBytes({ privateKey });\n }\n\n case 'P-256': {\n return await Secp256r1.privateKeyToBytes({ privateKey });\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${privateKey.crv}`);\n }\n }\n }\n\n public async publicKeyToBytes({ publicKey }:\n PublicKeyToBytesParams\n ): Promise<Uint8Array> {\n switch (publicKey.crv) {\n\n case 'secp256k1': {\n return await Secp256k1.publicKeyToBytes({ publicKey });\n }\n\n case 'P-256': {\n return await Secp256r1.publicKeyToBytes({ publicKey });\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${publicKey.crv}`);\n }\n }\n }\n\n /**\n * Generates an ECDSA signature of given data using a private key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the given `algorithm` to sign the\n * provided data.\n *\n * The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const data = new TextEncoder().encode('Message');\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const signature = await ecdsa.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n if (!isEcPrivateJwk(key)) throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');\n\n switch (key.crv) {\n\n case 'secp256k1': {\n return await Secp256k1.sign({ key, data });\n }\n\n case 'P-256': {\n return await Secp256r1.sign({ key, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Verifies an ECDSA signature associated with the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `crv` property of the provided key\n * to check the validity of a digital signature against the original data. It confirms whether the\n * signature was created by the holder of the corresponding private key and that the data has not\n * been tampered with.\n *s\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const data = new TextEncoder().encode('Message');\n * const isValid = await ecdsa.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n if (!isEcPublicJwk(key)) throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) public key.');\n\n switch (key.crv) {\n\n case 'secp256k1': {\n return await Secp256k1.verify({ key, signature, data });\n }\n\n case 'P-256': {\n return await Secp256r1.verify({ key, signature, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n}", "/**\n * A custom error class for Crypto-related errors.\n */\nexport class CryptoError extends Error {\n /**\n * Constructs an instance of CryptoError, a custom error class for handling Crypto-related errors.\n *\n * @param code - A {@link CryptoErrorCode} representing the specific type of error encountered.\n * @param message - A human-readable description of the error.\n */\n constructor(public code: CryptoErrorCode, message: string) {\n super(message);\n this.name = 'CryptoError';\n\n // Ensures that instanceof works properly, the correct prototype chain when using inheritance,\n // and that V8 stack traces (like Chrome, Edge, and Node.js) are more readable and relevant.\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Captures the stack trace in V8 engines (like Chrome, Edge, and Node.js).\n // In non-V8 environments, the stack trace will still be captured.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CryptoError);\n }\n }\n}\n\n/**\n * An enumeration of possible Crypto error codes.\n */\nexport enum CryptoErrorCode {\n /** The supplied algorithm identifier is not supported by the implementation. */\n AlgorithmNotSupported = 'algorithmNotSupported',\n\n /** The encoding operation (either encoding or decoding) failed. */\n EncodingError = 'encodingError',\n\n /** The JWE supplied does not conform to valid syntax. */\n InvalidJwe = 'invalidJwe',\n\n /** The JWK supplied does not conform to valid syntax. */\n InvalidJwk = 'invalidJwk',\n\n /** The requested operation is not supported by the implementation. */\n OperationNotSupported = 'operationNotSupported',\n}", "import type {\n Jwk,\n Signer,\n SignParams,\n KeyConverter,\n VerifyParams,\n GenerateKeyParams,\n GetPublicKeyParams,\n AsymmetricKeyConverter,\n AsymmetricKeyGenerator,\n ComputePublicKeyParams,\n} from '@enbox/crypto';\n\nimport { CryptoAlgorithm, Ed25519, isOkpPrivateJwk, isOkpPublicJwk } from '@enbox/crypto';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\nimport { BytesToPrivateKeyParams, BytesToPublicKeyParams, PrivateKeyToBytesParams, PublicKeyToBytesParams } from '../types/params-direct.js';\n\n/**\n * The `EdDsaGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the EdDSA algorithm.\n */\nexport interface EdDsaGenerateKeyParams extends GenerateKeyParams {\n /**\n * A string defining the type of key to generate. The value must be one of the following:\n * - `\"Ed25519\"`: EdDSA using the Ed25519 curve.\n */\n algorithm: 'Ed25519';\n}\n\n/**\n * The `EdDsaAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the Edwards-curve Digital Signature Algorithm (EdDSA). This class implements both\n * {@link Signer | `Signer`} and { @link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`}\n * interfaces, providing private key generation, public key derivation, and creation/verification\n * of signatures.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class EdDsaAlgorithm extends CryptoAlgorithm\n implements AsymmetricKeyGenerator<EdDsaGenerateKeyParams, Jwk, GetPublicKeyParams>,\n KeyConverter, AsymmetricKeyConverter,\n Signer<SignParams, VerifyParams> {\n\n public async bytesToPrivateKey({ algorithm, privateKeyBytes }:\n BytesToPrivateKeyParams & { algorithm: 'Ed25519' }\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'Ed25519': {\n const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });\n privateKey.alg = 'EdDSA';\n return privateKey;\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n }\n }\n }\n\n public async bytesToPublicKey({ algorithm, publicKeyBytes }:\n BytesToPublicKeyParams & { algorithm: 'Ed25519' }\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'Ed25519': {\n const publicKey = await Ed25519.bytesToPublicKey({ publicKeyBytes });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n }\n }\n }\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The process ensures that the derived public key correctly corresponds to\n * the given private key.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await eddsa.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n if (!isOkpPrivateJwk(key)) throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');\n\n switch (key.crv) {\n\n case 'Ed25519': {\n const publicKey = await Ed25519.computePublicKey({ key });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates a new private key with the specified algorithm in JSON Web Key (JWK) format.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = await eddsa.generateKey({ algorithm: 'Ed25519' });\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation.\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n async generateKey({ algorithm }:\n EdDsaGenerateKeyParams\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'Ed25519': {\n const privateKey = await Ed25519.generateKey();\n privateKey.alg = 'EdDSA';\n return privateKey;\n }\n }\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an EdDSA private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key.\n *\n * Note: This method offers a significant performance advantage, being about 100 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await eddsa.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n if (!isOkpPrivateJwk(key)) throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');\n\n switch (key.crv) {\n\n case 'Ed25519': {\n const publicKey = await Ed25519.getPublicKey({ key });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n public async privateKeyToBytes({ privateKey }:\n PrivateKeyToBytesParams\n ): Promise<Uint8Array> {\n switch (privateKey.crv) {\n\n case 'Ed25519': {\n return await Ed25519.privateKeyToBytes({ privateKey });\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${privateKey.crv}`);\n }\n }\n }\n\n public async publicKeyToBytes({ publicKey }:\n PublicKeyToBytesParams\n ): Promise<Uint8Array> {\n switch (publicKey.crv) {\n\n case 'Ed25519': {\n return await Ed25519.publicKeyToBytes({ publicKey });\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${publicKey.crv}`);\n }\n }\n }\n\n /**\n * Generates an EdDSA signature of given data using a private key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the given `algorithm` to sign the\n * provided data.\n *\n * The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const data = new TextEncoder().encode('Message');\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const signature = await eddsa.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n if (!isOkpPrivateJwk(key)) throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');\n\n switch (key.crv) {\n\n case 'Ed25519': {\n return await Ed25519.sign({ key, data });\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${key.crv}`);\n }\n }\n }\n\n /**\n * Verifies an EdDSA signature associated with the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `crv` property of the provided key\n * to check the validity of a digital signature against the original data. It confirms whether the\n * signature was created by the holder of the corresponding private key and that the data has not\n * been tampered with.\n *s\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const data = new TextEncoder().encode('Message');\n * const isValid = await eddsa.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n if (!isOkpPublicJwk(key)) throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) public key.');\n\n switch (key.crv) {\n\n case 'Ed25519': {\n return await Ed25519.verify({ key, signature, data });\n }\n\n default: {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Curve not supported: ${key.crv}`);\n }\n }\n }\n}", "import type { GenerateKeyParams, Jwk, KeyConverter, KeyGenerator, KeyWrapper } from '@enbox/crypto';\n\nimport { CryptoAlgorithm } from '@enbox/crypto';\n\nimport type { BytesToPrivateKeyParams, PrivateKeyToBytesParams, UnwrapKeyParams, WrapKeyParams } from '../types/params-direct.js';\n\nimport { AesKw } from '../primitives/aes-kw.js';\nimport { RequireOnly } from '@enbox/common';\n\n/**\n * The `AesKwGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the AES-KW algorithm.\n */\nexport interface AesKwGenerateKeyParams extends GenerateKeyParams {\n /** Specifies the algorithm variant for key generation in AES-KW mode.\n * The value determines the length of the key to be generated and must be one of the following:\n * - `\"A128KW\"`: AES Key Wrap using a 128-bit key.\n * - `\"A192KW\"`: AES Key Wrap using a 192-bit key.\n * - `\"A256KW\"`: AES Key Wrap using a 256-bit key.\n */\n algorithm: 'A128KW' | 'A192KW' | 'A256KW';\n}\n\n/**\n * The `AesKwAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the AES algorithm for key wrapping. This class implements both\n * {@link KeyGenerator | `KeyGenerator`} and {@link KeyWrapper | `KeyWrapper`} interfaces, providing\n * key generation, key wrapping, and key unwrapping features.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class AesKwAlgorithm extends CryptoAlgorithm\n implements KeyConverter,\n KeyGenerator<AesKwGenerateKeyParams, Jwk>,\n KeyWrapper<WrapKeyParams, UnwrapKeyParams> {\n\n public async bytesToPrivateKey({ privateKeyBytes }:\n RequireOnly<BytesToPrivateKeyParams, 'privateKeyBytes'>\n ): Promise<Jwk> {\n // Convert the byte array to a JWK.\n const privateKey = await AesKw.bytesToPrivateKey({ privateKeyBytes });\n\n // Set the `alg` property based on the key length.\n privateKey.alg = { 16: 'A128KW', 24: 'A192KW', 32: 'A256KW' }[privateKeyBytes.length];\n\n return privateKey;\n }\n\n /**\n * Generates a symmetric key for AES for key wrapping in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method generates a symmetric AES key for use in key wrapping mode, based on the specified\n * `algorithm` parameter which determines the key length. It uses cryptographically secure random\n * number generation to ensure the uniqueness and security of the key. The key is returned in JWK\n * format.\n *\n * The generated key includes the following components:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n * - `alg`: Algorithm, set to 'A128KW', 'A192KW', or 'A256KW' for AES Key Wrap with the\n * specified key length.\n *\n * @example\n * ```ts\n * const aesKw = new AesKwAlgorithm();\n * const privateKey = await aesKw.generateKey({ algorithm: 'A256KW' });\n * ```\n *\n * @param params - The parameters for the key generation.\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public async generateKey({ algorithm }:\n AesKwGenerateKeyParams\n ): Promise<Jwk> {\n // Map algorithm name to key length.\n const length = { A128KW: 128, A192KW: 192, A256KW: 256 }[algorithm] as 128 | 192 | 256;\n\n // Generate a random private key.\n const privateKey = await AesKw.generateKey({ length });\n\n // Set the `alg` property based on the specified algorithm.\n privateKey.alg = algorithm;\n\n return privateKey;\n }\n\n public async privateKeyToBytes({ privateKey }:\n PrivateKeyToBytesParams\n ): Promise<Uint8Array> {\n // Convert the JWK to a byte array.\n const privateKeyBytes = await AesKw.privateKeyToBytes({ privateKey });\n\n return privateKeyBytes;\n }\n\n /**\n * Decrypts a wrapped key using the AES Key Wrap algorithm.\n *\n * @remarks\n * This method unwraps a previously wrapped cryptographic key using the AES Key Wrap algorithm.\n * The wrapped key, provided as a byte array, is unwrapped using the decryption key specified in\n * the parameters.\n *\n * This operation is useful for securely receiving keys transmitted over untrusted mediums. The\n * method returns the unwrapped key as a JSON Web Key (JWK).\n *\n * @example\n * ```ts\n * const aesKw = new AesKwAlgorithm();\n * const wrappedKeyBytes = new Uint8Array([...]); // Byte array of a wrapped AES-256 GCM key\n * const decryptionKey = { ... }; // A Jwk object representing the AES unwrapping key\n * const unwrappedKey = await aesKw.unwrapKey({\n * wrappedKeyBytes,\n * wrappedKeyAlgorithm: 'A256GCM',\n * decryptionKey\n * });\n * ```\n *\n * @param params - The parameters for the key unwrapping operation.\n *\n * @returns A Promise that resolves to the unwrapped key in JWK format.\n */\n public async unwrapKey(params:\n UnwrapKeyParams\n ): Promise<Jwk> {\n const unwrappedKey = await AesKw.unwrapKey(params);\n\n return unwrappedKey;\n }\n\n /**\n * Encrypts a given key using the AES Key Wrap algorithm.\n *\n * @remarks\n * This method wraps a given cryptographic key using the AES Key Wrap algorithm. The private key\n * to be wrapped is provided in the form of a JSON Web Key (JWK).\n *\n * This operation is useful for securely transmitting keys over untrusted mediums. The method\n * returns the wrapped key as a byte array.\n *\n * @example\n * ```ts\n * const aesKw = new AesKwAlgorithm();\n * const unwrappedKey = { ... }; // A Jwk object representing the key to be wrapped\n * const encryptionKey = { ... }; // A Jwk object representing the AES wrapping key\n * const wrappedKeyBytes = await aesKw.wrapKey({ unwrappedKey, encryptionKey });\n * ```\n *\n * @param params - The parameters for the key wrapping operation.\n *\n * @returns A Promise that resolves to the wrapped key as a Uint8Array.\n */\n public async wrapKey(params:\n WrapKeyParams\n ): Promise<Uint8Array> {\n const wrappedKeyBytes = AesKw.wrapKey(params);\n\n return wrappedKeyBytes;\n }\n}", "// ! TODO : Make sure I remove `@noble/ciphers` from the Agent package.json once this is moved to the `@enbox/crypto` package.\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\n\nimport type { Jwk } from '@enbox/crypto';\n\nimport { Convert } from '@enbox/common';\nimport { computeJwkThumbprint, isOctPrivateJwk } from '@enbox/crypto';\n\nimport type { UnwrapKeyParams, WrapKeyParams } from '../types/params-direct.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * Constant defining the AES key length values in bits.\n *\n * @remarks\n * NIST publication FIPS 197 states:\n * > The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt\n * > and decrypt data in blocks of 128 bits.\n *\n * This implementation does not support key lengths that are different from the three values\n * defined by this constant.\n *\n * @see {@link https://doi.org/10.6028/NIST.FIPS.197-upd1 | NIST FIPS 197}\n */\nconst AES_KEY_LENGTHS = [128, 192, 256] as const;\n\nexport class AesKw {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a symmetric key represented as a byte array (Uint8Array) and\n * converts it into a JWK object for use with AES (Advanced Encryption Standard)\n * for key wrapping. The conversion process involves encoding the key into\n * base64url format and setting the appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).\n * - `k`: The symmetric key, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes\n * const privateKey = await AesKw.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.\n *\n * @returns A Promise that resolves to the symmetric key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n k : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n kty : 'oct'\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n // Add algorithm identifier based on key length.\n const lengthInBits = privateKeyBytes.length * 8;\n privateKey.alg = { 128: 'A128KW', 192: 'A192KW', 256: 'A256KW' }[lengthInBits];\n\n return privateKey;\n }\n\n /**\n * Generates a symmetric key for AES for key wrapping in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new symmetric key of a specified length suitable for use with\n * AES key wrapping. It uses cryptographically secure random number generation to\n * ensure the uniqueness and security of the key. The generated key adheres to the JWK\n * format, making it compatible with common cryptographic standards and easy to use in\n * various cryptographic processes.\n *\n * The generated key includes the following components:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n * - `alg`: Algorithm, set to 'A128KW', 'A192KW', or 'A256KW' for AES Key Wrap with the\n * specified key length.\n *\n * @example\n * ```ts\n * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)\n * const privateKey = await AesKw.generateKey({ length });\n * ```\n *\n * @param params - The parameters for the key generation.\n * @param params.length - The length of the key in bits. Common lengths are 128, 192, and 256 bits.\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public static async generateKey({ length }: {\n length: typeof AES_KEY_LENGTHS[number];\n }): Promise<Jwk> {\n // Validate the key length.\n if (!AES_KEY_LENGTHS.includes(length as any)) {\n throw new RangeError(`The key length is invalid: Must be ${AES_KEY_LENGTHS.join(', ')} bits`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Generate a random private key.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for\n // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().\n const webCryptoKey = await webCrypto.generateKey( { name: 'AES-KW', length }, true, ['wrapKey', 'unwrapKey']);\n\n // Export the private key in JWK format.\n const { ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey) as Jwk;\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a symmetric key in JWK format and extracts its raw byte representation.\n * It decodes the 'k' parameter of the JWK value, which represents the symmetric key in base64url\n * encoding, into a byte array.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A symmetric key in JWK format\n * const privateKeyBytes = await AesKw.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the symmetric key conversion.\n * @param params.privateKey - The symmetric key in JWK format.\n *\n * @returns A Promise that resolves to the symmetric key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid oct private key.\n if (!isOctPrivateJwk(privateKey)) {\n throw new Error(`AesKw: The provided key is not a valid oct private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();\n\n return privateKeyBytes;\n }\n\n public static async unwrapKey({ wrappedKeyBytes, wrappedKeyAlgorithm, decryptionKey }:\n UnwrapKeyParams\n ): Promise<Jwk> {\n if (!('alg' in decryptionKey && decryptionKey.alg)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwk, `The decryption key is missing the 'alg' property.`);\n }\n\n if (!['A128KW', 'A192KW', 'A256KW'].includes(decryptionKey.alg)) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'decryptionKey' algorithm is not supported: ${decryptionKey.alg}`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Import the decryption key for use with the Web Crypto API.\n const decryptionCryptoKey = await webCrypto.importKey(\n 'jwk', // key format\n decryptionKey as JsonWebKey, // key data\n { name: 'AES-KW' }, // algorithm identifier\n true, // key is extractable\n ['unwrapKey'] // key usages\n );\n\n // Map the private key's JOSE algorithm name to the Web Crypto API algorithm identifier.\n const webCryptoAlgorithm = {\n A128KW : 'AES-KW', A192KW : 'AES-KW', A256KW : 'AES-KW',\n A128GCM : 'AES-GCM', A192GCM : 'AES-GCM', A256GCM : 'AES-GCM',\n }[wrappedKeyAlgorithm];\n\n if (!webCryptoAlgorithm) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'wrappedKeyAlgorithm' is not supported: ${wrappedKeyAlgorithm}`);\n }\n\n // Unwrap the key using the Web Crypto API.\n const unwrappedCryptoKey = await webCrypto.unwrapKey(\n 'raw', // output format\n wrappedKeyBytes.buffer, // key to unwrap\n decryptionCryptoKey, // unwrapping key\n 'AES-KW', // algorithm identifier\n { name: webCryptoAlgorithm }, // unwrapped key algorithm identifier\n true, // key is extractable\n ['unwrapKey'] // key usages\n );\n\n // Export the unwrapped key in JWK format.\n const { ext, key_ops, ...unwrappedJsonWebKey } = await webCrypto.exportKey('jwk', unwrappedCryptoKey);\n const unwrappedKey = unwrappedJsonWebKey as Jwk;\n\n // Compute the JWK thumbprint and set as the key ID.\n unwrappedKey.kid = await computeJwkThumbprint({ jwk: unwrappedKey });\n\n return unwrappedKey;\n }\n\n public static async wrapKey({ unwrappedKey, encryptionKey }:\n WrapKeyParams\n ): Promise<Uint8Array> {\n if (!('alg' in encryptionKey && encryptionKey.alg)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwk, `The encryption key is missing the 'alg' property.`);\n }\n\n if (!['A128KW', 'A192KW', 'A256KW'].includes(encryptionKey.alg)) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'encryptionKey' algorithm is not supported: ${encryptionKey.alg}`);\n }\n\n if (!('alg' in unwrappedKey && unwrappedKey.alg)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwk, `The private key to wrap is missing the 'alg' property.`);\n }\n\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Import the encryption key for use with the Web Crypto API.\n const encryptionCryptoKey = await webCrypto.importKey(\n 'jwk', // key format\n encryptionKey as JsonWebKey, // key data\n { name: 'AES-KW' }, // algorithm identifier\n true, // key is extractable\n ['wrapKey'] // key usages\n );\n\n // Map the private key's JOSE algorithm name to the Web Crypto API algorithm identifier.\n const webCryptoAlgorithm = {\n A128KW : 'AES-KW', A192KW : 'AES-KW', A256KW : 'AES-KW',\n A128GCM : 'AES-GCM', A192GCM : 'AES-GCM', A256GCM : 'AES-GCM',\n }[unwrappedKey.alg];\n\n if (!webCryptoAlgorithm) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `The 'unwrappedKey' algorithm is not supported: ${unwrappedKey.alg}`);\n }\n\n // Import the private key to wrap for use with the Web Crypto API.\n const unwrappedCryptoKey = await webCrypto.importKey(\n 'jwk', // key format\n unwrappedKey as JsonWebKey, // key data\n { name: webCryptoAlgorithm }, // algorithm identifier\n true, // key is extractable\n ['unwrapKey'] // key usages\n );\n\n // Wrap the key using the Web Crypto API.\n const wrappedKeyBuffer = await webCrypto.wrapKey(\n 'raw', // output format\n unwrappedCryptoKey, // key to wrap\n encryptionCryptoKey, // wrapping key\n 'AES-KW' // algorithm identifier\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const wrappedKeyBytes = new Uint8Array(wrappedKeyBuffer);\n\n return wrappedKeyBytes;\n }\n}", "import { CryptoAlgorithm } from '@enbox/crypto';\n\nimport type { Pbkdf2Params } from '../primitives/pbkdf2.js';\nimport type { KeyBytesDeriver } from '../types/key-deriver.js';\nimport type { DeriveKeyBytesParams } from '../types/params-direct.js';\n\nimport { Pbkdf2 } from '../primitives/pbkdf2.js';\n\n/**\n * The `Pbkdf2DeriveKeyBytesParams` interface defines the algorithm-specific parameters that\n * should be passed into the `deriveKeyBytes()` method when using the PBKDF2 algorithm.\n */\nexport interface Pbkdf2DeriveKeyBytesParams extends DeriveKeyBytesParams {\n /** Specifies the algorithm variant for PBKDF2 key derivation.\n * The value determines the hash function that will be used and must be one of the following:\n * - `\"PBKDF2-HS256+A128KW\"`: PBKDF2 with HMAC SHA-256 and A128KW key wrapping.\n * - `\"PBKDF2-HS384+A192KW\"`: PBKDF2 with HMAC SHA-384 and A192KW key wrapping.\n * - `\"PBKDF2-HS512+A256KW\"`: PBKDF2 with HMAC SHA-512 and A256KW key wrapping.\n */\n algorithm: 'PBES2-HS256+A128KW' | 'PBES2-HS384+A192KW' | 'PBES2-HS512+A256KW';\n}\n\nexport class Pbkdf2Algorithm extends CryptoAlgorithm\n implements KeyBytesDeriver<Pbkdf2DeriveKeyBytesParams, Uint8Array> {\n\n public async deriveKeyBytes({ algorithm, ...params }:\n Pbkdf2DeriveKeyBytesParams & Omit<Pbkdf2Params, 'hash'>\n ): Promise<Uint8Array> {\n // Extract the hash function component of the `algorithm` parameter.\n const [, hashFunction] = algorithm.split(/[-+]/);\n\n // Map from JOSE algorithm name to \"SHA\" hash function identifier.\n const hash = {\n 'HS256' : 'SHA-256' as const,\n 'HS384' : 'SHA-384' as const,\n 'HS512' : 'SHA-512' as const\n }[hashFunction]!;\n\n // Derive a cryptographic byte array using PBKDF2.\n const derivedKeyBytes = await Pbkdf2.deriveKeyBytes({ ...params, hash });\n\n return derivedKeyBytes;\n }\n}", "// ! TODO : Make sure I remove `@noble/ciphers` from the Agent package.json once this is moved to the `@enbox/crypto` package.\nimport { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';\n\nimport type { DeriveKeyBytesParams } from '../types/params-direct.js';\n\n/**\n * The object that should be passed into `Pbkdf2.deriveKeyBytes()`, when using the PBKDF2 algorithm.\n */\nexport interface Pbkdf2Params {\n /**\n * A string representing the digest algorithm to use. This may be one of:\n * - 'SHA-256'\n * - 'SHA-384'\n * - 'SHA-512'\n */\n hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n /**\n * The salt value to use in the derivation process, as a Uint8Array. This should be a random or\n * pseudo-random value of at least 16 bytes. Unlike the `password`, `salt` does not need to be\n * kept secret.\n */\n salt: Uint8Array;\n\n /**\n * A `Number` representing the number of iterations the hash function will be executed in\n * `deriveKey()`. This impacts the computational cost of the `deriveKey()` operation, making it\n * more resistant to dictionary attacks. The higher the number, the more secure, but also slower,\n * the operation. Choose a value that balances security needs and performance for your\n * application.\n */\n iterations: number;\n}\n\n/**\n * The `Pbkdf2` class provides a secure way to derive cryptographic keys from a password\n * using the PBKDF2 (Password-Based Key Derivation Function 2) algorithm.\n *\n * The PBKDF2 algorithm is widely used for generating keys from passwords, as it applies\n * a pseudorandom function to the input password along with a salt value and iterates the\n * process multiple times to increase the key's resistance to brute-force attacks.\n *\n * Notes:\n * - The `baseKeyBytes` that will be the input key material for PBKDF2 is expected to be a low-entropy\n * value, such as a password or passphrase. It should be kept confidential.\n * - In 2023, {@link https://web.archive.org/web/20230123232056/https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2 | OWASP recommended}\n * a minimum of 600,000 iterations for PBKDF2-HMAC-SHA256 and 210,000 for PBKDF2-HMAC-SHA512.\n *\n * @example\n * ```ts\n * // Key Derivation\n * const derivedKeyBytes = await Pbkdf2.deriveKeyBytes({\n * baseKeyBytes: new TextEncoder().encode('password'), // The password as a Uint8Array\n * hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n * salt: new Uint8Array([...]), // The salt value\n * iterations: 600_000, // The number of iterations\n * length: 256 // The length of the derived key in bits\n * });\n * ```\n *\n * @remarks\n * This class relies on the availability of the Web Crypto API.\n */\nexport class Pbkdf2 {\n /**\n * Derives a cryptographic key from a password using the PBKDF2 algorithm.\n *\n * @remarks\n * This method applies the PBKDF2 algorithm to the provided password along with\n * a salt value and iterates the process a specified number of times. It uses\n * a cryptographic hash function to enhance security and produce a key of the\n * desired length. The method is capable of utilizing either the Web Crypto API\n * or the Node.js Crypto module, depending on the environment's support.\n *\n * @example\n * ```ts\n * const derivedKeyBytes = await Pbkdf2.deriveKeyBytes({\n * baseKeyBytes: new TextEncoder().encode('password'), // The password as a Uint8Array\n * hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')\n * salt: new Uint8Array([...]), // The salt value\n * iterations: 600_000, // The number of iterations\n * length: 256 // The length of the derived key in bits\n * });\n * ```\n *\n * @param params - The parameters for key derivation.\n * @returns A Promise that resolves to the derived key as a byte array.\n */\n public static async deriveKeyBytes({ baseKeyBytes, hash, salt, iterations, length }:\n DeriveKeyBytesParams & Pbkdf2Params\n ): Promise<Uint8Array> {\n // Get the Web Crypto API interface.\n const webCrypto = getWebcryptoSubtle() as SubtleCrypto;\n\n // Import the password as a raw key for use with the Web Crypto API.\n const webCryptoKey = await webCrypto.importKey(\n 'raw', // key format is raw bytes\n baseKeyBytes, // key data to import\n { name: 'PBKDF2' }, // algorithm identifier\n false, // key is not extractable\n ['deriveBits'] // key usages\n );\n\n // Derive the bytes using the Web Crypto API.\n const derivedKeyBuffer = await webCrypto.deriveBits(\n { name: 'PBKDF2', hash, salt, iterations },\n webCryptoKey,\n length\n );\n\n // Convert from ArrayBuffer to Uint8Array.\n const derivedKeyBytes = new Uint8Array(derivedKeyBuffer);\n\n return derivedKeyBytes;\n }\n}", "import type {\n Jwk,\n Cipher,\n KeyConverter,\n KeyGenerator,\n DecryptParams,\n EncryptParams,\n GenerateKeyParams,\n} from '@enbox/crypto';\n\nimport { AesGcm, AES_GCM_TAG_LENGTHS, CryptoAlgorithm } from '@enbox/crypto';\n\nimport type { BytesToPrivateKeyParams, PrivateKeyToBytesParams } from '../types/params-direct.js';\n\n/**\n * The `AesGcmGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the AES-GCM algorithm.\n */\nexport interface AesGcmGenerateKeyParams extends GenerateKeyParams {\n /** Specifies the algorithm variant for key generation in AES-GCM mode.\n * The value determines the length of the key to be generated and must be one of the following:\n * - `\"A128GCM\"`: Generates a 128-bit key.\n * - `\"A192GCM\"`: Generates a 192-bit key.\n * - `\"A256GCM\"`: Generates a 256-bit key.\n */\n algorithm: 'A128GCM' | 'A192GCM' | 'A256GCM';\n}\n\n/**\n * The `AesGcmParams` interface defines the algorithm-specific parameters that should be passed\n * into the `encrypt()` and `decrypt()` methods when using the AES-GCM algorithm.\n */\nexport interface AesGcmParams {\n /**\n * The `additionalData` property is used for authentication alongside encrypted data but isn't\n * encrypted itself. It must match in both encryption and decryption; a mismatch will cause\n * decryption to fail. This feature allows for the authentication of data without encrypting it.\n *\n * The `additionalData` property is optional and omitting it does not compromise encryption\n * security.\n */\n additionalData?: Uint8Array;\n\n /**\n * The initialization vector (IV) must be unique for every encryption operation carried out with a\n * given key. The IV need not be secret, but it must be unpredictable: that is, the IV must not be\n * reused with the same key. The IV must be 12 bytes (96 bits) in length in accordance with the\n * AES-GCM specification recommendedation to promote interoperability and efficiency.\n *\n * Note: It is OK to transmit the IV in the clear with the encrypted message.\n */\n iv: Uint8Array;\n\n /**\n * This property determines the size in bits of the authentication tag generated in the encryption\n * operation and used for authentication in the corresponding decryption. In accordance with the\n * AES-GCM specification, the tag length must be 96, 104, 112, 120 or 128.\n *\n * The `tagLength` property is optional and defaults to 128 bits if omitted.\n */\n tagLength?: typeof AES_GCM_TAG_LENGTHS[number];\n}\n\n/**\n * The `AesGcmAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the AES algorithm in Galois/Counter Mode (GCM). This class implements both\n * {@link Cipher | `Cipher`} and { @link KeyGenerator | `KeyGenerator`} interfaces, providing\n * key generation, encryption, and decryption features.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class AesGcmAlgorithm extends CryptoAlgorithm\n implements Cipher<AesGcmParams, AesGcmParams>,\n KeyConverter,\n KeyGenerator<AesGcmGenerateKeyParams, Jwk> {\n\n public async bytesToPrivateKey({ privateKeyBytes }: BytesToPrivateKeyParams): Promise<Jwk> {\n // Convert the byte array to a JWK.\n const privateKey = await AesGcm.bytesToPrivateKey({ privateKeyBytes });\n\n // Set the `alg` property based on the key length.\n privateKey.alg = { 16: 'A128GCM', 24: 'A192GCM', 32: 'A256GCM' }[privateKeyBytes.length];\n\n return privateKey;\n }\n\n /**\n * Decrypts the provided data using AES-GCM.\n *\n * @remarks\n * This method performs AES-GCM decryption on the given encrypted data using the specified key.\n * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n * and optionally, additional authenticated data (AAD). The method returns the decrypted data as a\n * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n * tag used when encrypting the data. If not specified, the default tag length of 128 bits is\n * used.\n *\n * @example\n * ```ts\n * const aesGcm = new AesGcmAlgorithm();\n * const encryptedData = new Uint8Array([...]); // Encrypted data\n * const iv = new Uint8Array([...]); // Initialization vector used during encryption\n * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n * const key = { ... }; // A Jwk object representing the AES key\n * const decryptedData = await aesGcm.decrypt({\n * data: encryptedData,\n * iv,\n * additionalData,\n * key,\n * tagLength: 128 // Optional tag length in bits\n * });\n * ```\n *\n * @param params - The parameters for the decryption operation.\n *\n * @returns A Promise that resolves to the decrypted data as a Uint8Array.\n */\n public async decrypt(params:\n DecryptParams & AesGcmParams\n ): Promise<Uint8Array> {\n const plaintext = AesGcm.decrypt(params);\n\n return plaintext;\n }\n\n /**\n * Encrypts the provided data using AES-GCM.\n *\n * @remarks\n * This method performs AES-GCM encryption on the given data using the specified key.\n * It requires an initialization vector (IV), the encrypted data along with the decryption key,\n * and optionally, additional authenticated data (AAD). The method returns the encrypted data as a\n * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication\n * tag generated in the encryption operation and used for authentication in the corresponding\n * decryption. If not specified, the default tag length of 128 bits is used.\n *\n * @example\n * ```ts\n * const aesGcm = new AesGcmAlgorithm();\n * const data = new TextEncoder().encode('Messsage');\n * const iv = new Uint8Array([...]); // Initialization vector\n * const additionalData = new Uint8Array([...]); // Optional additional authenticated data\n * const key = { ... }; // A Jwk object representing an AES key\n * const encryptedData = await aesGcm.encrypt({\n * data,\n * iv,\n * additionalData,\n * key,\n * tagLength: 128 // Optional tag length in bits\n * });\n * ```\n *\n * @param params - The parameters for the encryption operation.\n *\n * @returns A Promise that resolves to the encrypted data as a Uint8Array.\n */\n public async encrypt(params:\n EncryptParams & AesGcmParams\n ): Promise<Uint8Array> {\n const ciphertext = AesGcm.encrypt(params);\n\n return ciphertext;\n }\n\n /**\n * Generates a symmetric key for AES in Galois/Counter Mode (GCM) in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method generates a symmetric AES key for use in GCM mode, based on the specified\n * `algorithm` parameter which determines the key length. It uses cryptographically secure random\n * number generation to ensure the uniqueness and security of the key. The key is returned in JWK\n * format.\n *\n * The generated key includes the following components:\n * - `kty`: Key Type, set to 'oct' for Octet Sequence.\n * - `k`: The symmetric key component, base64url-encoded.\n * - `kid`: Key ID, generated based on the JWK thumbprint.\n *\n * @example\n * ```ts\n * const aesGcm = new AesGcmAlgorithm();\n * const privateKey = await aesGcm.generateKey({ algorithm: 'A256GCM' });\n * ```\n *\n * @param params - The parameters for the key generation.\n *\n * @returns A Promise that resolves to the generated symmetric key in JWK format.\n */\n public async generateKey({ algorithm }:\n AesGcmGenerateKeyParams\n ): Promise<Jwk> {\n // Map algorithm name to key length.\n const length = { A128GCM: 128, A192GCM: 192, A256GCM: 256 }[algorithm] as 128 | 192 | 256;\n\n // Generate a random private key.\n const privateKey = await AesGcm.generateKey({ length });\n\n // Set the `alg` property based on the specified algorithm.\n privateKey.alg = algorithm;\n\n return privateKey;\n }\n\n public async privateKeyToBytes({ privateKey }: PrivateKeyToBytesParams): Promise<Uint8Array> {\n // Convert the JWK to a byte array.\n const privateKeyBytes = await AesGcm.privateKeyToBytes({ privateKey });\n\n return privateKeyBytes;\n }\n}", "import type {\n DidDocument,\n DidMetadata,\n PortableDid,\n DidMethodApi,\n DidDhtCreateOptions,\n DidJwkCreateOptions,\n DidResolutionResult,\n DidResolutionOptions,\n DidVerificationMethod,\n DidResolverCache,\n} from '@enbox/dids';\n\nimport { BearerDid, Did, DidDht, UniversalResolver } from '@enbox/dids';\n\nimport type { AgentDataStore } from './store-data.js';\nimport type { AgentKeyManager } from './types/key-manager.js';\nimport type { ResponseStatus, Web5PlatformAgent } from './types/agent.js';\n\nimport { InMemoryDidStore } from './store-did.js';\nimport { AgentDidResolverCache } from './agent-did-resolver-cache.js';\nimport { canonicalize } from '@enbox/crypto';\n\nexport enum DidInterface {\n Create = 'Create',\n // Deactivate = 'Deactivate',\n Resolve = 'Resolve',\n // Update = 'Update'\n}\n\nexport interface DidMessageParams {\n [DidInterface.Create]: DidCreateParams;\n // [DidInterface.Deactivate]: DidDeactivateParams;\n [DidInterface.Resolve]: DidResolveParams;\n // [DidInterface.Update]: DidUpdateParams;\n}\n\nexport interface DidMessageResult {\n [DidInterface.Create]: DidCreateResult;\n // [DidInterface.Deactivate]: DidDeactivateResult;\n [DidInterface.Resolve]: DidResolveResult;\n // [DidInterface.Update]: DidUpdateResult;\n}\n\nexport type DidCreateResult = {\n uri: string;\n document: DidDocument;\n metadata: DidMetadata;\n}\n\nexport type DidResolveResult = DidResolutionResult\n\nexport type DidRequest<T extends DidInterface> = {\n messageType: T;\n messageParams: DidMessageParams[T];\n}\n\nexport type DidResolveParams = {\n didUri: string;\n options?: DidResolutionOptions;\n}\n\nexport type DidResponse<T extends DidInterface> = ResponseStatus & {\n result?: DidMessageResult[T];\n};\n\nexport interface DidCreateParams<\n TKeyManager = AgentKeyManager,\n TMethod extends keyof DidMethodCreateOptions<TKeyManager> = keyof DidMethodCreateOptions<TKeyManager>\n> {\n method: TMethod;\n options?: DidMethodCreateOptions<TKeyManager>[TMethod];\n store?: boolean;\n tenant?: string;\n}\n\nexport interface DidMethodCreateOptions<TKeyManager> {\n dht: DidDhtCreateOptions<TKeyManager>;\n jwk: DidJwkCreateOptions<TKeyManager>;\n}\n\nexport interface DidApiParams {\n didMethods: DidMethodApi[];\n\n agent?: Web5PlatformAgent;\n\n /**\n * An optional `DidResolverCache` instance used for caching resolved DID documents.\n *\n * Providing a cache implementation can significantly enhance resolution performance by avoiding\n * redundant resolutions for previously resolved DIDs. If omitted, the default is an instance of `AgentDidResolverCache`.\n *\n * `AgentDidResolverCache` keeps a stale copy of the Agent's managed Identity DIDs and only refreshes upon a successful resolution.\n * This allows for quick and offline access to the internal DIDs used by the agent.\n */\n resolverCache?: DidResolverCache;\n\n store?: AgentDataStore<PortableDid>;\n}\n\nexport function isDidRequest<T extends DidInterface>(\n didRequest: DidRequest<DidInterface>, messageType: T\n): didRequest is DidRequest<T> {\n return didRequest.messageType === messageType;\n}\n\n/**\n * This API is used to manage and interact with DIDs within the Web5 Agent framework.\n *\n * If a DWN Data Store is used, the DID information is stored under DID's own tenant by default.\n * If a tenant property is passed, that tenant will be used to store the DID information.\n */\nexport class AgentDidApi<TKeyManager extends AgentKeyManager = AgentKeyManager> extends UniversalResolver {\n /**\n * Holds the instance of a `Web5PlatformAgent` that represents the current execution context for\n * the `AgentDidApi`. This agent is used to interact with other Web5 agent components. It's vital\n * to ensure this instance is set to correctly contextualize operations within the broader Web5\n * Agent framework.\n */\n private _agent?: Web5PlatformAgent;\n\n private _didMethods: Map<string, DidMethodApi> = new Map();\n\n private _store: AgentDataStore<PortableDid>;\n\n constructor({ agent, didMethods, resolverCache, store }: DidApiParams) {\n if (!didMethods) {\n throw new TypeError(`AgentDidApi: Required parameter missing: 'didMethods'`);\n }\n\n // Initialize the DID resolver with the given DID methods and resolver cache, or use a default\n // AgentDidResolverCache if none is provided.\n super({\n didResolvers : didMethods,\n cache : resolverCache ?? new AgentDidResolverCache({ agent, location: 'DATA/AGENT/DID_CACHE' })\n });\n\n this._agent = agent;\n\n // If `store` is not given, use an in-memory store by default.\n this._store = store ?? new InMemoryDidStore();\n\n for (const didMethod of didMethods) {\n this._didMethods.set(didMethod.methodName, didMethod);\n }\n }\n\n /**\n * Retrieves the `Web5PlatformAgent` execution context.\n *\n * @returns The `Web5PlatformAgent` instance that represents the current execution context.\n * @throws Will throw an error if the `agent` instance property is undefined.\n */\n get agent(): Web5PlatformAgent {\n if (this._agent === undefined) {\n throw new Error('AgentDidApi: Unable to determine agent execution context.');\n }\n\n return this._agent;\n }\n\n set agent(agent: Web5PlatformAgent) {\n this._agent = agent;\n\n // AgentDidResolverCache should set the agent if it is the type of cache being used\n if ('agent' in this.cache) {\n this.cache.agent = agent;\n }\n }\n\n public async create({\n method, tenant, options, store\n }: DidCreateParams<TKeyManager>): Promise<BearerDid> {\n // Get the DID method implementation, which also verifies the method is supported.\n const didMethod = this.getMethod(method);\n\n // Create the DID and store the generated keys in the Agent's key manager.\n const bearerDid = await didMethod.create({ keyManager: this.agent.keyManager, options });\n\n // pre-populate the resolution cache with the document and metadata\n await this.cache.set(bearerDid.uri, { didDocument: bearerDid.document, didResolutionMetadata: { }, didDocumentMetadata: bearerDid.metadata });\n\n // Persist the DID to the store, by default, unless the `store` option is set to false.\n if (store ?? true) {\n // Data stored in the Agent's DID store must be in PortableDid format.\n const { uri, document, metadata } = bearerDid;\n const portableDid: PortableDid = { uri, document, metadata };\n\n // Unless an existing `tenant` is specified, a record that includes the DID's URI, document,\n // and metadata will be stored under a new tenant controlled by the newly created DID.\n await this._store.set({\n id : portableDid.uri,\n data : portableDid,\n agent : this.agent,\n tenant : tenant ?? portableDid.uri,\n preventDuplicates : false,\n useCache : true\n });\n }\n\n return bearerDid;\n }\n\n public async export({ didUri, tenant }: {\n didUri: string;\n tenant?: string;\n }): Promise<PortableDid> {\n // Attempt to retrieve the DID from the agent's DID store.\n const bearerDid = await this.get({ didUri, tenant });\n\n if (!bearerDid) {\n throw new Error(`AgentDidApi: Failed to export due to DID not found: ${didUri}`);\n }\n\n // If the DID was found, return the DID in a portable format, and if supported by the Agent's\n // key manager, the private key material.\n const portableDid = await bearerDid.export();\n\n return portableDid;\n }\n\n public async get({ didUri, tenant }: {\n didUri: string,\n tenant?: string\n }): Promise<BearerDid | undefined> {\n const portableDid = await this._store.get({ id: didUri, agent: this.agent, tenant, useCache: true });\n\n if (!portableDid) return undefined;\n\n const bearerDid = await BearerDid.import({ portableDid, keyManager: this.agent.keyManager });\n\n return bearerDid;\n }\n\n public async getSigningMethod({ didUri, methodId }: {\n didUri: string;\n methodId?: string;\n }): Promise<DidVerificationMethod> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(didUri);\n if (!parsedDid) {\n throw new Error(`Invalid DID URI: ${didUri}`);\n }\n\n // Get the DID method implementation, which also verifies the method is supported.\n const didMethod = this.getMethod(parsedDid.method);\n\n // Resolve the DID document.\n const { didDocument, didResolutionMetadata } = await this.resolve(didUri);\n if (!didDocument) {\n throw new Error(`DID resolution failed for '${didUri}': ${JSON.stringify(didResolutionMetadata)}`);\n }\n\n // Retrieve the method-specific verification method to be used for signing operations.\n const verificationMethod = await didMethod.getSigningMethod({ didDocument, methodId });\n\n return verificationMethod;\n }\n\n public async update({ tenant, portableDid, publish = true }: {\n tenant?: string;\n portableDid: PortableDid;\n publish?: boolean;\n }): Promise<BearerDid> {\n\n // Check if the DID exists in the store.\n const existingDid = await this.get({ didUri: portableDid.uri, tenant: tenant ?? portableDid.uri });\n if (!existingDid) {\n throw new Error(`AgentDidApi: Could not update, DID not found: ${portableDid.uri}`);\n }\n\n // If the document has not changed, abort the update.\n if (canonicalize(portableDid.document) === canonicalize(existingDid.document)) {\n throw new Error('AgentDidApi: No changes detected, update aborted');\n }\n\n // If private keys are present in the PortableDid, import the key material into the Agent's key\n // manager. Validate that the key material for every verification method in the DID document is\n // present in the key manager. If no keys are present, this will fail.\n // NOTE: We currently do not delete the previous keys from the document.\n // TODO: Add support for deleting the keys no longer present in the document.\n const bearerDid = await BearerDid.import({ keyManager: this.agent.keyManager, portableDid });\n\n // Only the DID URI, document, and metadata are stored in the Agent's DID store.\n const { uri, document, metadata } = bearerDid;\n const portableDidWithoutKeys: PortableDid = { uri, document, metadata };\n\n // pre-populate the resolution cache with the document and metadata\n await this.cache.set(uri, { didDocument: document, didResolutionMetadata: { }, didDocumentMetadata: metadata });\n\n await this._store.set({\n id : uri,\n data : portableDidWithoutKeys,\n agent : this.agent,\n tenant : tenant ?? uri,\n updateExisting : true,\n useCache : true\n });\n\n if (publish) {\n const parsedDid = Did.parse(uri);\n // currently only supporting DHT as a publishable method.\n // TODO: abstract this into the didMethod class so that other publishable methods can be supported.\n if (parsedDid && parsedDid.method === 'dht') {\n await DidDht.publish({ did: bearerDid });\n }\n }\n\n return bearerDid;\n }\n\n public async import({ portableDid, tenant }: {\n portableDid: PortableDid;\n tenant?: string;\n }): Promise<BearerDid> {\n // If private keys are present in the PortableDid, import the key material into the Agent's key\n // manager. Validate that the key material for every verification method in the DID document is\n // present in the key manager.\n const bearerDid = await BearerDid.import({ keyManager: this.agent.keyManager, portableDid });\n\n // Only the DID URI, document, and metadata are stored in the Agent's DID store.\n const { uri, document, metadata } = bearerDid;\n const portableDidWithoutKeys: PortableDid = { uri, document, metadata };\n\n // pre-populate the resolution cache with the document and metadata\n await this.cache.set(uri, { didDocument: document, didResolutionMetadata: { }, didDocumentMetadata: metadata });\n\n // Store the DID in the agent's DID store.\n // Unless an existing `tenant` is specified, a record that includes the DID's URI, document,\n // and metadata will be stored under a new tenant controlled by the imported DID.\n await this._store.set({\n id : portableDidWithoutKeys.uri,\n data : portableDidWithoutKeys,\n agent : this.agent,\n tenant : tenant ?? portableDidWithoutKeys.uri,\n preventDuplicates : true,\n useCache : true\n });\n\n return bearerDid;\n }\n\n public async delete({ didUri, tenant, deleteKey = true }: {\n didUri: string;\n tenant?: string;\n deleteKey?: boolean;\n }): Promise<void> {\n const portableDid = await this._store.get({ id: didUri, agent: this.agent, tenant, useCache: false });\n if(!portableDid) {\n throw new Error('AgentDidApi: Could not delete, DID not found');\n }\n\n // delete from the cache\n await this.cache.delete(didUri);\n\n // Delete the data before deleting the associated keys.\n await this._store.delete({ id: didUri, agent: this.agent, tenant });\n\n if (deleteKey) {\n // Delete the keys associated with the DID\n // TODO: this could be made a static method on `BearerDid` class\n await this.deleteKeys({ portableDid });\n }\n }\n\n public async deleteKeys({ portableDid }: {\n portableDid: PortableDid;\n }): Promise<void> {\n for (const verificationMethod of portableDid.document.verificationMethod || []) {\n if (!verificationMethod.publicKeyJwk) {\n continue;\n }\n // Compute the key URI of the verification method's public key.\n const keyUri = await this.agent.keyManager.getKeyUri({ key: verificationMethod.publicKeyJwk });\n await this.agent.keyManager.deleteKey({ keyUri });\n }\n }\n\n public async processRequest<T extends DidInterface>(\n request: DidRequest<T>\n ): Promise<DidResponse<T>> {\n // Process Create DID request.\n if (isDidRequest(request, DidInterface.Create)) {\n try {\n const bearerDid = await this.create({ ...request.messageParams });\n const response: DidResponse<typeof request.messageType> = {\n result: {\n uri : bearerDid.uri,\n document : bearerDid.document,\n metadata : bearerDid.metadata,\n },\n ok : true,\n status : { code: 201, message: 'Created' }\n };\n return response;\n\n } catch (error: any) {\n return {\n ok : false,\n status : { code: 500, message: error.message ?? 'Unknown error occurred' }\n };\n }\n }\n\n // Process Resolve DID request.\n if (isDidRequest(request, DidInterface.Resolve)) {\n const { didUri, options } = request.messageParams;\n const resolutionResult = await this.resolve(didUri, options);\n const response: DidResponse<typeof request.messageType> = {\n result : resolutionResult,\n ok : true,\n status : { code: 200, message: 'OK' }\n };\n return response;\n }\n\n throw new Error(`AgentDidApi: Unsupported request type: ${request.messageType}`);\n }\n\n private getMethod(methodName: string): DidMethodApi {\n const didMethodApi = this._didMethods.get(methodName);\n\n if (didMethodApi === undefined) {\n throw new Error(`DID Method not supported: ${methodName}`);\n }\n\n return didMethodApi;\n }\n}", "import type { PortableDid } from '@enbox/dids';\n\nimport { Convert } from '@enbox/common';\n\nimport type { Web5PlatformAgent } from './types/agent.js';\nimport type { AgentDataStore, DataStoreDeleteParams, DataStoreGetParams, DataStoreListParams, DataStoreSetParams } from './store-data.js';\n\nimport { DwnInterface } from './types/dwn.js';\nimport { IdentityProtocolDefinition } from './store-data-protocols.js';\nimport { isPortableDid } from './prototyping/dids/utils.js';\nimport { TENANT_SEPARATOR } from './utils-internal.js';\nimport { DwnDataStore, InMemoryDataStore } from './store-data.js';\n\nexport class DwnDidStore extends DwnDataStore<PortableDid> implements AgentDataStore<PortableDid> {\n protected name = 'DwnDidStore';\n\n protected _recordProtocolDefinition = IdentityProtocolDefinition;\n\n /**\n * Properties to use when writing and querying DID records with the DWN store.\n */\n protected _recordProperties = {\n dataFormat : 'application/json',\n protocol : this._recordProtocolDefinition.protocol,\n protocolPath : 'portableDid',\n schema : this._recordProtocolDefinition.types.portableDid.schema,\n };\n\n public async delete(params: DataStoreDeleteParams): Promise<boolean> {\n return await super.delete(params);\n }\n\n public async get(params: DataStoreGetParams): Promise<PortableDid | undefined> {\n return await super.get(params);\n }\n\n public async list(params: DataStoreListParams): Promise<PortableDid[]> {\n return await super.list(params);\n }\n\n public async set(params: DataStoreSetParams<PortableDid>): Promise<void> {\n return await super.set(params);\n }\n\n protected async getAllRecords({ agent, tenantDid }: {\n agent: Web5PlatformAgent;\n tenantDid: string;\n }): Promise<PortableDid[]> {\n // Clear the index since it will be rebuilt from the query results.\n this._index.clear();\n\n // Query the DWN for all stored PortableDid objects.\n const { reply: queryReply } = await agent.dwn.processRequest({\n author : tenantDid,\n target : tenantDid,\n messageType : DwnInterface.RecordsQuery,\n messageParams : { filter: { ...this._recordProperties } }\n });\n\n // Loop through all of the stored DID records and accumulate the DID objects.\n let storedDids: PortableDid[] = [];\n for (const record of queryReply.entries ?? []) {\n // All DID records are expected to be small enough such that the data is returned with the\n // query results. If a record is returned without `encodedData` this is unexpected so throw\n // an error.\n if (!record.encodedData) {\n throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);\n }\n\n const storedDid = Convert.base64Url(record.encodedData).toObject() as PortableDid;\n if (isPortableDid(storedDid)) {\n // Update the index with the matching record ID.\n const indexKey = `${tenantDid}${TENANT_SEPARATOR}${storedDid.uri}`;\n this._index.set(indexKey, record.recordId);\n\n // Add the stored DID to the cache.\n this._cache.set(record.recordId, storedDid);\n\n storedDids.push(storedDid);\n }\n }\n\n return storedDids;\n }\n}\n\nexport class InMemoryDidStore extends InMemoryDataStore<PortableDid> implements AgentDataStore<PortableDid> {\n protected name = 'InMemoryDidStore';\n\n public async delete(params: DataStoreDeleteParams): Promise<boolean> {\n return await super.delete(params);\n }\n\n public async get(params: DataStoreGetParams): Promise<PortableDid | undefined> {\n return await super.get(params);\n }\n\n public async list(params: DataStoreListParams): Promise<PortableDid[]> {\n return await super.list(params);\n }\n\n public async set(params: DataStoreSetParams<PortableDid>): Promise<void> {\n return await super.set(params);\n }\n}", "import type { ProtocolDefinition } from '@enbox/dwn-sdk-js';\n\nexport const IdentityProtocolDefinition: ProtocolDefinition = {\n protocol : 'http://identity.foundation/protocols/web5/identity-store',\n published : false,\n types : {\n portableDid: {\n schema : 'https://identity.foundation/schemas/web5/portable-did',\n dataFormats : [\n 'application/json'\n ]\n },\n identityMetadata: {\n schema : 'https://identity.foundation/schemas/web5/identity-metadata',\n dataFormats : [\n 'application/json'\n ]\n }\n },\n structure: {\n portableDid : {},\n identityMetadata : {}\n }\n};\n\nexport const JwkProtocolDefinition: ProtocolDefinition = {\n protocol : 'http://identity.foundation/protocols/web5/jwk-store',\n published : false,\n types : {\n privateJwk: {\n schema : 'https://identity.foundation/schemas/web5/private-jwk',\n dataFormats : [\n 'application/json'\n ]\n },\n },\n structure: {\n privateJwk: {}\n }\n};", "import type { PortableDid } from '@enbox/dids';\n\nexport function isPortableDid(obj: unknown): obj is PortableDid {\n // Validate that the given value is an object that has the necessary properties of PortableDid.\n return !(!obj || typeof obj !== 'object' || obj === null)\n && 'uri' in obj\n && 'document' in obj\n && 'metadata' in obj\n && (!('keyManager' in obj) || obj.keyManager === undefined);\n}", "import type { Jwk, KeyIdentifier, KmsExportKeyParams, KmsGetPublicKeyParams, KmsSignParams } from '@enbox/crypto';\n\nimport { Ed25519, LocalKeyManager, computeJwkThumbprint } from '@enbox/crypto';\n\nimport type { Web5PlatformAgent } from './types/agent.js';\n\n/**\n * Internal utility functions used by the Web5 platform agent that are not intended for public use\n * and are not exported in the public API.\n */\n\n/**\n * Separator used to join the tenant DID and the DID URI that is used to prefix all lookups in the\n * Agent data stores, including the DWN-backed store's index and the in-memory store's map.\n */\nexport const TENANT_SEPARATOR = '^';\n\nexport class DeterministicKeyGenerator extends LocalKeyManager {\n private _predefinedKeys: Map<KeyIdentifier, Jwk>;\n private _keyGenerator: IterableIterator<KeyIdentifier>;\n\n constructor() {\n super();\n this._predefinedKeys = new Map();\n this._keyGenerator = this._predefinedKeys.keys();\n }\n\n public async addPredefinedKeys({ privateKeys }: { privateKeys: Jwk[] }): Promise<void> {\n const predefinedKeys: { [keyUri: KeyIdentifier]: Jwk } = {};\n\n for (const key of privateKeys) {\n // If the key ID is undefined, set it to the JWK thumbprint.\n key.kid ??= await computeJwkThumbprint({ jwk: key });\n\n // Compute the key URI for the key.\n const keyUri = await this.getKeyUri({ key });\n\n // Store the key.\n predefinedKeys[keyUri] = key;\n }\n\n // Store the keys.\n this._predefinedKeys = new Map(Object.entries(predefinedKeys));\n\n // Reset the key generator to use the new keys.\n this._keyGenerator = this._predefinedKeys.keys();\n }\n\n public async exportKey({ keyUri }:\n KmsExportKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = this._predefinedKeys.get(keyUri);\n\n // Throw an error if the key is not found.\n if (!privateKey) {\n throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${keyUri}`);\n }\n\n return privateKey;\n }\n\n public async generateKey(_params: {\n algorithm: 'Ed25519' | 'secp256k1' | 'secp256r1'\n }): Promise<KeyIdentifier> {\n // Get the next key from the array of predefined keys.\n const { value: keyUri, done } = this._keyGenerator.next();\n\n // Throw an error if the generator is empty and there are no more keys to return.\n if (done) {\n throw new Error('Ran out of predefined keys');\n }\n\n return keyUri;\n }\n\n public async getPublicKey({ keyUri }:\n KmsGetPublicKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = this._predefinedKeys.get(keyUri);\n\n // Throw an error if the key is not found.\n if (!privateKey) {\n throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${keyUri}`);\n }\n\n // Get the public key properties from the private JWK.\n const { d, ...publicKey } = privateKey;\n\n return publicKey;\n }\n\n public async sign({ keyUri, data }:\n KmsSignParams\n ): Promise<Uint8Array> {\n // Get the private key from the key store.\n const privateKey = this._predefinedKeys.get(keyUri);\n\n // Throw an error if the key is not found.\n if (!privateKey) {\n throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${keyUri}`);\n }\n\n // Sign the data.\n const signature = await Ed25519.sign({ data, key: privateKey });\n\n return signature;\n }\n}\n\n/**\n * Determines the tenant identifier (DID) for data store operations based on the provided\n * parameters.\n *\n * The function identifies the tenant using a priority order:\n * 1. directly provided tenant DID,\n * 2. the agent's DID,\n * 3. or a specified DID URI.\n *\n * This approach ensures operations are isolated by DID, supporting multi-tenancy.\n *\n * @param params - The parameters for determining the tenant.\n * @param params.agent - The Web5 platform agent instance.\n * @param [params.tenant] - An optional tenant DID. If provided, it takes precedence.\n * @param [params.didUri] - An optional DID URI to use if no tenant DID or agent DID is available.\n * @returns A promise that resolves to the tenant DID.\n * @throws Throws an error if it fails to determine the tenant from the provided inputs.\n */\nexport async function getDataStoreTenant({ agent, tenant, didUri }: {\n agent: Web5PlatformAgent;\n tenant?: string;\n didUri?: string;\n}): Promise<string> {\n // Check if a tenant identifier (DID) is explicitly provided and return it immediately if so.\n // This is the highest priority to ensure explicit tenant isolation.\n if (tenant) return tenant;\n\n // If the agent's DID is available, return it as the tenant identifier.\n // This allows using the agent's own identity as a fallback tenant.\n if (agent.agentDid) return agent.agentDid.uri;\n\n // Throw an error if neither tenant, agent.agentDid, nor didUri are provided,\n // as it's not possible to determine the tenant identifier without any of these.\n if (!didUri) {\n throw new Error(`Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined`);\n }\n\n // Return the DID URI as the tenant identifier if both `tenant` and `agent.agentDid` are undefined\n // but a `didUri` is provided. This assumes the agent has the necessary permissions and keys\n // associated with the provided DID for data store operations.\n //\n // Note: This assumes the Agent's key manager has the private key for the given DID URI. No\n // explicit check is made here for performance reasons, relying on downstream processes to\n // validate access rights.\n return didUri;\n}", "import type { Jwk } from '@enbox/crypto';\n\nimport ms from 'ms';\nimport { Convert, NodeStream, TtlCache } from '@enbox/common';\n\nimport type { Web5PlatformAgent } from './types/agent.js';\n\nimport { TENANT_SEPARATOR } from './utils-internal.js';\nimport { getDataStoreTenant } from './utils-internal.js';\nimport { DwnInterface, DwnMessageParams } from './types/dwn.js';\nimport { ProtocolDefinition, RecordsReadReplyEntry } from '@enbox/dwn-sdk-js';\n\nexport type DataStoreTenantParams = {\n agent: Web5PlatformAgent;\n tenant?: string;\n}\n\nexport type DataStoreListParams = DataStoreTenantParams;\n\nexport type DataStoreGetParams = DataStoreTenantParams & {\n id: string;\n useCache?: boolean;\n}\n\nexport type DataStoreSetParams<TStoreObject> = DataStoreTenantParams & {\n id: string;\n data: TStoreObject;\n preventDuplicates?: boolean;\n updateExisting?: boolean;\n useCache?: boolean;\n}\n\nexport type DataStoreDeleteParams = DataStoreTenantParams & {\n id: string;\n}\n\nexport interface AgentDataStore<TStoreObject> {\n delete(params: DataStoreDeleteParams): Promise<boolean>;\n\n get(params: DataStoreGetParams): Promise<TStoreObject | undefined>;\n\n list(params: DataStoreTenantParams): Promise<TStoreObject[]>;\n\n set(params: DataStoreSetParams<TStoreObject>): Promise<void>;\n}\n\nexport class DwnDataStore<TStoreObject extends Record<string, any> = Jwk> implements AgentDataStore<TStoreObject> {\n protected name = 'DwnDataStore';\n\n /**\n * Cache of Store Objects referenced by DWN record ID to Store Objects.\n *\n * Up to 100 entries are retained for 15 minutes.\n */\n protected _cache = new TtlCache<string, TStoreObject>({ ttl: ms('15 minutes'), max: 100 });\n\n /**\n * Index for mappings from Store Identifier to DWN record ID.\n * Since these values don't change, we can use a long TTL.\n *\n * Up to 1,000 entries are retained for 21 days.\n * NOTE: The maximum number for the ttl is 2^31 - 1 milliseconds (24.8 days), setting to 21 days to be safe.\n */\n protected _index = new TtlCache<string, string>({ ttl: ms('21 days'), max: 1000 });\n\n /**\n * Cache of tenant DIDs that have been initialized with the protocol.\n * This is used to avoid redundant protocol initialization requests.\n *\n * Since these are default protocols and unlikely to change, we can use a long TTL.\n */\n protected _protocolInitializedCache: TtlCache<string, boolean> = new TtlCache({ ttl: ms('21 days'), max: 1000 });\n\n /**\n * The protocol assigned to this storage instance.\n */\n protected _recordProtocolDefinition!: ProtocolDefinition;\n\n /**\n * Properties to use when writing and querying records with the DWN store.\n */\n protected _recordProperties = {\n dataFormat: 'application/json',\n };\n\n public async delete({ id, agent, tenant }: DataStoreDeleteParams): Promise<boolean> {\n // Determine the tenant identifier (DID) for the delete operation.\n const tenantDid = await getDataStoreTenant({ agent, tenant, didUri: id });\n\n // Look up the DWN record ID of the object in the store with the given `id`.\n let matchingRecordId = await this.lookupRecordId({ id, tenantDid, agent });\n\n // Return false if the given ID was not found in the store.\n if (!matchingRecordId) return false;\n\n // If a record for the given ID was found, attempt to delete it.\n const { reply: { status } } = await agent.dwn.processRequest({\n author : tenantDid,\n target : tenantDid,\n messageType : DwnInterface.RecordsDelete,\n messageParams : { recordId: matchingRecordId }\n });\n\n // If the record was successfully deleted, update the index/cache and return true;\n if (status.code === 202) {\n this._index.delete(`${tenantDid}${TENANT_SEPARATOR}${id}`);\n this._cache.delete(matchingRecordId);\n return true;\n }\n\n // If the Delete operation failed, throw an error.\n throw new Error(`${this.name}: Failed to delete '${id}' from store: (${status.code}) ${status.detail}`);\n }\n\n public async get({ id, agent, tenant, useCache = false }:\n DataStoreGetParams\n ): Promise<TStoreObject | undefined> {\n // Determine the tenant identifier (DID) for the list operation.\n const tenantDid = await getDataStoreTenant({ agent, tenant, didUri: id });\n\n // Look up the DWN record ID of the object in the store with the given `id`.\n let matchingRecordId = await this.lookupRecordId({ id, tenantDid, agent });\n\n // Return undefined if no matches were found.\n if (!matchingRecordId) return undefined;\n\n // Retrieve and return the stored object.\n return await this.getRecord({ recordId: matchingRecordId, tenantDid, agent, useCache });\n }\n\n public async list({ agent, tenant}: DataStoreListParams): Promise<TStoreObject[]> {\n // Determine the tenant identifier (DID) for the list operation.\n const tenantDid = await getDataStoreTenant({ tenant, agent });\n\n // Query the DWN for all stored record objects.\n const storedRecords = await this.getAllRecords({ agent, tenantDid });\n\n return storedRecords;\n }\n\n public async set({ id, data, tenant, agent, preventDuplicates = true, updateExisting = false, useCache = false }:\n DataStoreSetParams<TStoreObject>\n ): Promise<void> {\n // Determine the tenant identifier (DID) for the set operation.\n const tenantDid = await getDataStoreTenant({ agent, tenant, didUri: id });\n\n // initialize the storage protocol if not already done\n await this.initialize({ tenant: tenantDid, agent });\n\n const messageParams: DwnMessageParams[DwnInterface.RecordsWrite] = { ...this._recordProperties };\n\n if (updateExisting) {\n // Look up the DWN record ID of the object in the store with the given `id`.\n const matchingRecordEntry = await this.getExistingRecordEntry({ id, tenantDid, agent });\n if (!matchingRecordEntry) {\n throw new Error(`${this.name}: Update failed due to missing entry for: ${id}`);\n }\n\n // set the recordId in the messageParams to update the existing record\n // set the dateCreated to the existing dateCreated as this is an immutable property\n messageParams.recordId = matchingRecordEntry.recordsWrite!.recordId;\n messageParams.dateCreated = matchingRecordEntry.recordsWrite!.descriptor.dateCreated;\n } else if (preventDuplicates) {\n // Look up the DWN record ID of the object in the store with the given `id`.\n const matchingRecordId = await this.lookupRecordId({ id, tenantDid, agent });\n if (matchingRecordId) {\n throw new Error(`${this.name}: Import failed due to duplicate entry for: ${id}`);\n }\n }\n\n\n // Convert the store object to a byte array, which will be the data payload of the DWN record.\n const dataBytes = Convert.object(data).toUint8Array();\n\n // Store the record in the DWN.\n const { message, reply: { status } } = await agent.dwn.processRequest({\n author : tenantDid,\n target : tenantDid,\n messageType : DwnInterface.RecordsWrite,\n messageParams : { ...this._recordProperties, ...messageParams },\n dataStream : new Blob([dataBytes], { type: 'application/json' })\n });\n\n // If the write fails, throw an error.\n if (!(message && status.code === 202)) {\n throw new Error(`${this.name}: Failed to write data to store for ${id}: ${status.detail}`);\n }\n\n // Add the ID of the newly created record to the index.\n this._index.set(`${tenantDid}${TENANT_SEPARATOR}${id}`, message.recordId);\n\n // If caching is enabled, add the store object to the cache.\n if (useCache) {\n this._cache.set(message.recordId, data);\n }\n }\n\n /**\n * Initialize the relevant protocol for the given tenant.\n * This confirms that the storage protocol is configured, otherwise it will be installed.\n */\n public async initialize({ tenant, agent }: DataStoreTenantParams) {\n const tenantDid = await getDataStoreTenant({ agent, tenant });\n if (this._protocolInitializedCache.has(tenantDid)) {\n return;\n }\n\n const { reply: { status, entries }} = await agent.dwn.processRequest({\n author : tenantDid,\n target : tenantDid,\n messageType : DwnInterface.ProtocolsQuery,\n messageParams : {\n filter: {\n protocol: this._recordProtocolDefinition.protocol\n }\n },\n });\n\n if (status.code !== 200) {\n throw new Error(`Failed to query for protocols: ${status.code} - ${status.detail}`);\n }\n\n if (entries?.length === 0) {\n // protocol is not installed, install it\n await this.installProtocol(tenantDid, agent);\n }\n\n this._protocolInitializedCache.set(tenantDid, true);\n }\n\n protected async getAllRecords(_params: {\n agent: Web5PlatformAgent;\n tenantDid: string;\n }): Promise<TStoreObject[]> {\n throw new Error('Not implemented: Classes extending DwnDataStore must implement getAllRecords()');\n }\n\n private async getRecord({ recordId, tenantDid, agent, useCache }: {\n recordId: string;\n tenantDid: string;\n agent: Web5PlatformAgent;\n useCache: boolean;\n }): Promise<TStoreObject | undefined> {\n // If caching is enabled, check the cache for the record ID.\n if (useCache) {\n const record = this._cache.get(recordId);\n // If the record ID was present in the cache, return the associated store object.\n if (record) return record;\n // Otherwise, continue to read from the store.\n }\n\n // Read the record from the store.\n const { reply: readReply } = await agent.dwn.processRequest({\n author : tenantDid,\n target : tenantDid,\n messageType : DwnInterface.RecordsRead,\n messageParams : { filter: { recordId } }\n });\n\n if (!readReply.entry?.data) {\n throw new Error(`${this.name}: Failed to read data from DWN for: ${recordId}`);\n }\n\n // If the record was found, convert back to store object format.\n const storeObject = await NodeStream.consumeToJson({ readable: readReply.entry.data }) as TStoreObject;\n\n // If caching is enabled, add the store object to the cache.\n if (useCache) {\n this._cache.set(recordId, storeObject);\n }\n\n return storeObject;\n }\n\n /**\n * Install the protocol for the given tenant using a `ProtocolsConfigure` message.\n */\n private async installProtocol(tenant: string, agent: Web5PlatformAgent) {\n const { reply : { status } } = await agent.dwn.processRequest({\n author : tenant,\n target : tenant,\n messageType : DwnInterface.ProtocolsConfigure,\n messageParams : {\n definition: this._recordProtocolDefinition\n },\n });\n\n if (status.code !== 202) {\n throw new Error(`Failed to install protocol: ${status.code} - ${status.detail}`);\n }\n }\n\n private async lookupRecordId({ id, tenantDid, agent }: {\n id: string;\n tenantDid: string;\n agent: Web5PlatformAgent;\n }): Promise<string | undefined> {\n // Check the index for a matching ID and extend the index TTL.\n let recordId = this._index.get(`${tenantDid}${TENANT_SEPARATOR}${id}`, { updateAgeOnGet: true });\n\n // If no matching record ID was found in the index...\n if (!recordId) {\n // Query the DWN for all stored objects, which rebuilds the index.\n await this.getAllRecords({ agent, tenantDid });\n\n // Check the index again for a matching ID.\n recordId = this._index.get(`${tenantDid}${TENANT_SEPARATOR}${id}`);\n }\n\n return recordId;\n }\n\n private async getExistingRecordEntry({ id, tenantDid, agent }: {\n id: string;\n tenantDid: string;\n agent: Web5PlatformAgent;\n }): Promise<RecordsReadReplyEntry | undefined> {\n // Look up the DWN record ID of the object in the store with the given `id`.\n const recordId = await this.lookupRecordId({ id, tenantDid, agent });\n if (recordId) {\n // Read the record from the store.\n const { reply: readReply } = await agent.dwn.processRequest({\n author : tenantDid,\n target : tenantDid,\n messageType : DwnInterface.RecordsRead,\n messageParams : { filter: { recordId } }\n });\n\n return readReply.entry;\n }\n }\n}\n\nexport class InMemoryDataStore<TStoreObject extends Record<string, any> = Jwk> implements AgentDataStore<TStoreObject> {\n protected name = 'InMemoryDataStore';\n\n /**\n * A private field that contains the Map used as the in-memory data store.\n */\n private store: Map<string, TStoreObject> = new Map();\n\n public async delete({ id, agent, tenant }: DataStoreDeleteParams): Promise<boolean> {\n // Determine the tenant identifier (DID) for the delete operation.\n const tenantDid = await getDataStoreTenant({ agent, tenant, didUri: id });\n\n if (this.store.has(`${tenantDid}${TENANT_SEPARATOR}${id}`)) {\n // Record with given identifier exists so proceed with delete.\n this.store.delete(`${tenantDid}${TENANT_SEPARATOR}${id}`);\n return true;\n }\n\n // Record with given identifier not present so delete operation not possible.\n return false;\n }\n\n public async get({ id, agent, tenant }: DataStoreGetParams): Promise<TStoreObject | undefined> {\n // Determine the tenant identifier (DID) for the get operation.\n const tenantDid = await getDataStoreTenant({ agent, tenant, didUri: id });\n\n return this.store.get(`${tenantDid}${TENANT_SEPARATOR}${id}`);\n }\n\n public async list({ agent, tenant}: DataStoreListParams): Promise<TStoreObject[]> {\n // Determine the tenant identifier (DID) for the list operation.\n const tenantDid = await getDataStoreTenant({ tenant, agent });\n\n const result: TStoreObject[] = [];\n for (const [key, storedRecord] of this.store.entries()) {\n if (key.startsWith(`${tenantDid}${TENANT_SEPARATOR}`)) {\n result.push(storedRecord);\n }\n }\n\n return result;\n }\n\n public async set({ id, data, tenant, agent, preventDuplicates, updateExisting }: DataStoreSetParams<TStoreObject>): Promise<void> {\n // Determine the tenant identifier (DID) for the set operation.\n const tenantDid = await getDataStoreTenant({ agent, tenant, didUri: id });\n\n // If enabled, check if a record with the given `id` is already present in the store.\n if (updateExisting) {\n // Look up the DWN record ID of the object in the store with the given `id`.\n if (!this.store.has(`${tenantDid}${TENANT_SEPARATOR}${id}`)) {\n throw new Error(`${this.name}: Update failed due to missing entry for: ${id}`);\n }\n\n // set the recordId in the messageParams to update the existing record\n } else if (preventDuplicates) {\n const duplicateFound = this.store.has(`${tenantDid}${TENANT_SEPARATOR}${id}`);\n if (duplicateFound) {\n throw new Error(`${this.name}: Import failed due to duplicate entry for: ${id}`);\n }\n }\n\n // Make a deep copy so that the object stored does not share the same references as the input.\n const clonedData = structuredClone(data);\n this.store.set(`${tenantDid}${TENANT_SEPARATOR}${id}`, clonedData);\n }\n}", "import type { Readable } from '@enbox/common';\n\nimport {\n Cid,\n DataStoreLevel,\n Dwn,\n DwnConfig,\n DwnInterfaceName,\n DwnMethodName,\n EventEmitterStream,\n EventLogLevel,\n GenericMessage,\n Message,\n MessageStoreLevel,\n ResumableTaskStoreLevel\n} from '@enbox/dwn-sdk-js';\n\nimport { NodeStream } from '@enbox/common';\nimport { CryptoUtils } from '@enbox/crypto';\nimport { DidDht, DidJwk, DidResolverCacheLevel, UniversalResolver } from '@enbox/dids';\n\nimport type { Web5PlatformAgent } from './types/agent.js';\nimport type {\n DwnMessage,\n DwnMessageInstance,\n DwnMessageParams,\n DwnMessageReply,\n DwnMessagesPermissionScope,\n DwnMessageWithData,\n DwnPermissionScope,\n DwnRecordsInterfaces,\n DwnRecordsPermissionScope,\n DwnResponse,\n DwnSigner,\n MessageHandler,\n ProcessDwnRequest,\n SendDwnRequest\n} from './types/dwn.js';\n\nimport { DwnInterface, dwnMessageConstructors } from './types/dwn.js';\nimport { blobToIsomorphicNodeReadable, getDwnServiceEndpointUrls, isRecordsWrite, webReadableToIsomorphicNodeReadable } from './utils.js';\n\nexport type DwnMessageWithBlob<T extends DwnInterface> = {\n message: DwnMessage[T];\n data?: Blob;\n}\n\nexport type DwnApiParams = {\n agent?: Web5PlatformAgent;\n dwn: Dwn;\n}\n\nexport interface DwnApiCreateDwnParams extends Partial<DwnConfig> {\n dataPath?: string;\n}\n\nexport function isDwnRequest<T extends DwnInterface>(\n dwnRequest: ProcessDwnRequest<DwnInterface>, messageType: T\n): dwnRequest is ProcessDwnRequest<T> {\n return dwnRequest.messageType === messageType;\n}\n\nexport function isDwnMessage<T extends DwnInterface>(\n messageType: T, message: GenericMessage\n): message is DwnMessage[T] {\n const incomingMessageInterfaceName = message.descriptor.interface + message.descriptor.method;\n return incomingMessageInterfaceName === messageType;\n}\n\nexport function isRecordsType(messageType: DwnInterface): messageType is DwnRecordsInterfaces {\n return messageType === DwnInterface.RecordsDelete ||\n messageType === DwnInterface.RecordsQuery ||\n messageType === DwnInterface.RecordsRead ||\n messageType === DwnInterface.RecordsSubscribe ||\n messageType === DwnInterface.RecordsWrite;\n}\n\nexport function isRecordPermissionScope(scope: DwnPermissionScope): scope is DwnRecordsPermissionScope {\n return scope.interface === DwnInterfaceName.Records;\n}\n\nexport function isMessagesPermissionScope(scope: DwnPermissionScope): scope is DwnMessagesPermissionScope {\n return scope.interface === DwnInterfaceName.Messages;\n}\n\nexport class AgentDwnApi {\n /**\n * Holds the instance of a `Web5PlatformAgent` that represents the current execution context for\n * the `AgentDwnApi`. This agent is used to interact with other Web5 agent components. It's vital\n * to ensure this instance is set to correctly contextualize operations within the broader Web5\n * Agent framework.\n */\n private _agent?: Web5PlatformAgent;\n\n /**\n * The DWN instance to use for this API.\n */\n private _dwn: Dwn;\n\n constructor({ agent, dwn }: DwnApiParams) {\n // If an agent is provided, set it as the execution context for this API.\n this._agent = agent;\n\n // Set the DWN instance for this API.\n this._dwn = dwn;\n }\n\n /**\n * Retrieves the `Web5PlatformAgent` execution context.\n *\n * @returns The `Web5PlatformAgent` instance that represents the current execution context.\n * @throws Will throw an error if the `agent` instance property is undefined.\n */\n get agent(): Web5PlatformAgent {\n if (this._agent === undefined) {\n throw new Error('AgentDwnApi: Unable to determine agent execution context.');\n }\n\n return this._agent;\n }\n\n set agent(agent: Web5PlatformAgent) {\n this._agent = agent;\n }\n\n /**\n * Public getter for the DWN instance used by this API.\n *\n * Notes:\n * - This getter is public to allow advanced developers to access the DWN instance directly.\n * However, it is recommended to use the `processRequest` method to interact with the DWN\n * instance to ensure that the DWN message is constructed correctly.\n * - The getter is named `node` to avoid confusion with the `dwn` property of the\n * `Web5PlatformAgent`. In other words, so that a developer can call `agent.dwn.node` to access\n * the DWN instance and not `agent.dwn.dwn`.\n */\n get node(): Dwn {\n return this._dwn;\n }\n\n public static async createDwn({\n dataPath, dataStore, didResolver, eventLog, eventStream, messageStore, tenantGate, resumableTaskStore\n }: DwnApiCreateDwnParams): Promise<Dwn> {\n dataStore ??= new DataStoreLevel({ blockstoreLocation: `${dataPath}/DWN_DATASTORE` });\n\n didResolver ??= new UniversalResolver({\n didResolvers : [DidDht, DidJwk],\n cache : new DidResolverCacheLevel({ location: `${dataPath}/DID_RESOLVERCACHE` }),\n });\n\n eventLog ??= new EventLogLevel({ location: `${dataPath}/DWN_EVENTLOG` });\n\n messageStore ??= new MessageStoreLevel(({\n blockstoreLocation : `${dataPath}/DWN_MESSAGESTORE`,\n indexLocation : `${dataPath}/DWN_MESSAGEINDEX`\n }));\n\n resumableTaskStore ??= new ResumableTaskStoreLevel({ location: `${dataPath}/DWN_RESUMABLETASKSTORE` });\n\n eventStream ??= new EventEmitterStream();\n\n return await Dwn.create({ dataStore, didResolver, eventLog, eventStream, messageStore, tenantGate, resumableTaskStore });\n }\n\n public async processRequest<T extends DwnInterface>(\n request: ProcessDwnRequest<T>\n ): Promise<DwnResponse<T>> {\n // Constructs a DWN message. and if there is a data payload, transforms the data to a Node\n // Readable stream.\n const { message, dataStream } = await this.constructDwnMessage({ request });\n\n // Extracts the optional subscription handler from the request to pass into `processMessage.\n const { subscriptionHandler } = request;\n\n // Conditionally processes the message with the DWN instance:\n // - If `store` is not explicitly set to false, it sends the message to the DWN node for\n // processing, passing along the target DID, the message, and any associated data stream.\n // - If `store` is set to false, it immediately returns a simulated 'accepted' status without\n // storing the message/data in the DWN node.\n const reply: DwnMessageReply[T] = (request.store !== false)\n ? await this._dwn.processMessage(request.target, message, { dataStream: dataStream as any, subscriptionHandler })\n : { status: { code: 202, detail: 'Accepted' } };\n\n // Returns an object containing the reply from processing the message, the original message,\n // and the content identifier (CID) of the message.\n return {\n reply,\n message,\n messageCid: await Message.getCid(message),\n };\n }\n\n public async sendRequest<T extends DwnInterface>(\n request: SendDwnRequest<T>\n ): Promise<DwnResponse<T>> {\n // First, confirm the target DID can be dereferenced and extract the DWN service endpoint URLs.\n const dwnEndpointUrls = await getDwnServiceEndpointUrls(request.target, this.agent.did);\n if (dwnEndpointUrls.length === 0) {\n throw new Error(`AgentDwnApi: DID Service is missing or malformed: ${request.target}#dwn`);\n }\n\n let messageCid: string | undefined;\n let message: DwnMessage[T];\n let data: Blob | undefined;\n let subscriptionHandler: MessageHandler[T] | undefined;\n\n // If `messageCid` is given, retrieve message and data, if any.\n if ('messageCid' in request) {\n ({ message, data } = await this.getDwnMessage({\n author : request.author,\n messageCid : request.messageCid,\n messageType : request.messageType\n }));\n messageCid = request.messageCid;\n\n } else {\n // Otherwise, construct a new message.\n ({ message } = await this.constructDwnMessage({ request }));\n if (request.dataStream && !(request.dataStream instanceof Blob)) {\n throw new Error('AgentDwnApi: DataStream must be provided as a Blob');\n }\n data = request.dataStream;\n subscriptionHandler = request.subscriptionHandler;\n }\n\n // Send the RPC request to the target DID's DWN service endpoint using the Agent's RPC client.\n const reply = await this.sendDwnRpcRequest({\n targetDid: request.target,\n dwnEndpointUrls,\n message,\n data,\n subscriptionHandler\n });\n\n // If the message CID was not given in the `request`, compute it.\n messageCid ??= await Message.getCid(message);\n\n // Returns an object containing the reply from processing the message, the original message,\n // and the content identifier (CID) of the message.\n return { reply, message, messageCid };\n }\n\n private async sendDwnRpcRequest<T extends DwnInterface>({\n targetDid, dwnEndpointUrls, message, data, subscriptionHandler\n }: {\n targetDid: string;\n dwnEndpointUrls: string[];\n message: DwnMessage[T];\n data?: Blob;\n subscriptionHandler?: MessageHandler[T];\n }\n ): Promise<DwnMessageReply[T]> {\n const errorMessages: { url: string, message: string }[] = [];\n\n if (message.descriptor.method === DwnMethodName.Subscribe && subscriptionHandler === undefined) {\n throw new Error('AgentDwnApi: Subscription handler is required for subscription requests.');\n }\n\n // Try sending to author's publicly addressable DWNs until the first request succeeds.\n for (let dwnUrl of dwnEndpointUrls) {\n try {\n if (subscriptionHandler !== undefined) {\n // we get the server info to check if the server supports WebSocket for subscription requests\n const serverInfo = await this.agent.rpc.getServerInfo(dwnUrl);\n if (!serverInfo.webSocketSupport) {\n // If the server does not support WebSocket, add an error message and continue to the next URL.\n errorMessages.push({\n url : dwnUrl,\n message : 'WebSocket support is not enabled on the server.'\n });\n continue;\n }\n\n // If the server supports WebSocket, replace the subscription URL with a socket transport.\n // For `http` we use the unsecured `ws` protocol, and for `https` we use the secured `wss` protocol.\n const parsedUrl = new URL(dwnUrl);\n parsedUrl.protocol = parsedUrl.protocol === 'http:' ? 'ws:' : 'wss:';\n dwnUrl = parsedUrl.toString();\n }\n\n const dwnReply = await this.agent.rpc.sendDwnRequest({\n dwnUrl,\n targetDid,\n message,\n data,\n subscriptionHandler\n });\n\n return dwnReply;\n } catch(error: any) {\n errorMessages.push({\n url : dwnUrl,\n message : (error instanceof Error) ? error.message : 'Unknown error',\n });\n }\n }\n\n throw new Error(`Failed to send DWN RPC request: ${JSON.stringify(errorMessages)}`);\n }\n\n private async constructDwnMessage<T extends DwnInterface>({ request }: {\n request: ProcessDwnRequest<T>\n }): Promise<DwnMessageWithData<T>> {\n // if the request has a granteeDid, ensure the messageParams include the proper grant parameters\n if (request.granteeDid && !this.hasGrantParams(request.messageParams)) {\n throw new Error('AgentDwnApi: Requested to sign with a permission but no grant messageParams were provided in the request');\n }\n\n const rawMessage = request.rawMessage;\n let readableStream: Readable | undefined;\n // TODO: Consider refactoring to move data transformations imposed by fetch() limitations to the HTTP transport-related methods.\n // if the request is a RecordsWrite message, we need to handle the data stream and update the messageParams accordingly\n if (isDwnRequest(request, DwnInterface.RecordsWrite)) {\n const messageParams = request.messageParams;\n\n if (request.dataStream && !messageParams?.data) {\n const { dataStream } = request;\n let isomorphicNodeReadable: Readable;\n\n if (dataStream instanceof Blob) {\n isomorphicNodeReadable = blobToIsomorphicNodeReadable(dataStream);\n readableStream = blobToIsomorphicNodeReadable(dataStream);\n\n } else if (dataStream instanceof ReadableStream) {\n const [ forCid, forProcessMessage ] = dataStream.tee();\n isomorphicNodeReadable = webReadableToIsomorphicNodeReadable(forCid);\n readableStream = webReadableToIsomorphicNodeReadable(forProcessMessage);\n }\n\n if (!rawMessage) {\n // @ts-ignore\n messageParams.dataCid = await Cid.computeDagPbCidFromStream(isomorphicNodeReadable);\n // @ts-ignore\n messageParams.dataSize ??= isomorphicNodeReadable['bytesRead'];\n }\n }\n }\n\n let dwnMessage: DwnMessageInstance[T];\n const dwnMessageConstructor = dwnMessageConstructors[request.messageType];\n\n // if there is no raw message provided, we need to create the dwn message\n if (!rawMessage) {\n\n // If we need to sign as an author delegate or with permissions we need to get the grantee's signer\n // The messageParams should include either a permissionGrantId, or a delegatedGrant message\n const signer = request.granteeDid ?\n await this.getSigner(request.granteeDid) :\n await this.getSigner(request.author);\n\n dwnMessage = await dwnMessageConstructor.create({\n // TODO: Implement alternative to type assertion.\n ...request.messageParams!,\n signer\n });\n\n } else {\n dwnMessage = await dwnMessageConstructor.parse(rawMessage);\n if (isRecordsWrite(dwnMessage) && request.signAsOwner) {\n // if we are signing as owner, we use the author's signer\n const signer = await this.getSigner(request.author);\n await dwnMessage.signAsOwner(signer);\n } else if (request.granteeDid && isRecordsWrite(dwnMessage) && request.signAsOwnerDelegate) {\n // if we are signing as owner delegate, we use the grantee's signer and the provided delegated grant\n const signer = await this.getSigner(request.granteeDid);\n\n //if we have reached here, the presence of the grant params has already been checked\n const messageParams = request.messageParams as DwnMessageParams[DwnInterface.RecordsWrite];\n await dwnMessage.signAsOwnerDelegate(signer, messageParams.delegatedGrant!);\n }\n }\n\n return { message: dwnMessage.message as DwnMessage[T], dataStream: readableStream };\n }\n\n private hasGrantParams<T extends DwnInterface>(params?: DwnMessageParams[T]): boolean {\n return params !== undefined &&\n (('permissionGrantId' in params && params.permissionGrantId !== undefined) ||\n ('delegatedGrant' in params && params.delegatedGrant !== undefined));\n }\n\n private async getSigner(author: string): Promise<DwnSigner> {\n // If the author is the Agent's DID, use the Agent's signer.\n if (author === this.agent.agentDid.uri) {\n const signer = await this.agent.agentDid.getSigner();\n\n return {\n algorithm : signer.algorithm,\n keyId : signer.keyId,\n sign : async (data: Uint8Array) => {\n return await signer.sign({ data });\n }\n };\n\n } else {\n // Otherwise, use the author's DID to determine the signing method.\n try {\n const signingMethod = await this.agent.did.getSigningMethod({ didUri: author });\n\n if (!signingMethod.publicKeyJwk) {\n throw new Error(`Verification method '${signingMethod.id}' does not contain a public key in JWK format`);\n }\n\n // Compute the key URI of the verification method's public key.\n const keyUri = await this.agent.keyManager.getKeyUri({ key: signingMethod.publicKeyJwk });\n\n // Verify that the key is present in the key manager. If not, an error is thrown.\n const publicKey = await this.agent.keyManager.getPublicKey({ keyUri });\n\n // Bind the Agent's Key Manager to the signer.\n const keyManager = this.agent.keyManager;\n\n return {\n algorithm : CryptoUtils.getJoseSignatureAlgorithmFromPublicKey(publicKey),\n keyId : signingMethod.id,\n sign : async (data: Uint8Array) => {\n return await keyManager.sign({ data, keyUri: keyUri! });\n }\n };\n } catch (error: any) {\n throw new Error(`AgentDwnApi: Unable to get signer for author '${author}': ${error.message}`);\n }\n }\n }\n\n /**\n * FURTHER REFACTORING NEEDED BELOW THIS LINE\n */\n\n private async getDwnMessage<T extends DwnInterface>({ author, messageCid }: {\n author: string;\n messageType: T;\n messageCid: string;\n }): Promise<DwnMessageWithBlob<T>> {\n const signer = await this.getSigner(author);\n\n // Construct a MessagesRead message to fetch the message.\n const messagesRead = await dwnMessageConstructors[DwnInterface.MessagesRead].create({\n messageCid: messageCid,\n signer\n });\n\n const result = await this._dwn.processMessage(author, messagesRead.message);\n\n if (result.status.code !== 200) {\n throw new Error(`AgentDwnApi: Failed to read message, response status: ${result.status.code} - ${result.status.detail}`);\n }\n\n const messageEntry = result.entry!;\n const message = messageEntry.message as DwnMessage[T];\n\n let dwnMessageWithBlob: DwnMessageWithBlob<T> = { message };\n // If the message is a RecordsWrite, data will be present in the form of a stream\n\n if (isRecordsWrite(messageEntry) && messageEntry.data) {\n const dataBytes = await NodeStream.consumeToBytes({ readable: messageEntry.data });\n dwnMessageWithBlob.data = new Blob([ dataBytes ], { type: messageEntry.message.descriptor.dataFormat });\n }\n\n return dwnMessageWithBlob;\n }\n}", "import type { DidUrlDereferencer } from '@enbox/dids';\nimport { Jws, PaginationCursor, RecordsDeleteMessage, RecordsWriteMessage } from '@enbox/dwn-sdk-js';\n\nimport { Readable } from '@enbox/common';\nimport { utils as didUtils } from '@enbox/dids';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { DateSort, DwnInterfaceName, DwnMethodName, Message, RecordsWrite } from '@enbox/dwn-sdk-js';\n\nexport function blobToIsomorphicNodeReadable(blob: Blob): Readable {\n return webReadableToIsomorphicNodeReadable(blob.stream() as ReadableStream<any>);\n}\n\nexport async function getDwnServiceEndpointUrls(didUri: string, dereferencer: DidUrlDereferencer): Promise<string[]> {\n // Attempt to dereference the DID service with ID fragment #dwn.\n const dereferencingResult = await dereferencer.dereference(`${didUri}#dwn`);\n\n if (dereferencingResult.dereferencingMetadata.error) {\n throw new Error(`Failed to dereference '${didUri}#dwn': ${dereferencingResult.dereferencingMetadata.error}`);\n }\n\n if (didUtils.isDwnDidService(dereferencingResult.contentStream)) {\n const { serviceEndpoint } = dereferencingResult.contentStream;\n const serviceEndpointUrls = typeof serviceEndpoint === 'string'\n // If the service endpoint is a string, format it as a single-element array.\n ? [serviceEndpoint]\n : Array.isArray(serviceEndpoint) && serviceEndpoint.every(endpoint => typeof endpoint === 'string')\n // If the service endpoint is an array of strings, use it as is.\n ? serviceEndpoint as string[]\n // If the service endpoint is neither a string nor an array of strings, return an empty array.\n : [];\n\n if (serviceEndpointUrls.length > 0) {\n return serviceEndpointUrls;\n }\n }\n\n // If the DID service with ID fragment #dwn was not found or is not valid, return an empty array.\n return [];\n}\n\nexport function getRecordAuthor(record: RecordsWriteMessage | RecordsDeleteMessage): string | undefined {\n return Message.getAuthor(record);\n}\n\n/**\n * Get the `protocolRole` string from the signature payload of the given RecordsWriteMessage or RecordsDeleteMessage.\n */\nexport function getRecordProtocolRole(message: RecordsWriteMessage | RecordsDeleteMessage): string | undefined {\n const signaturePayload = Jws.decodePlainObjectPayload(message.authorization.signature);\n return signaturePayload?.protocolRole;\n}\n\nexport function isRecordsWrite(obj: unknown): obj is RecordsWrite {\n // Validate that the given value is an object.\n if (!obj || typeof obj !== 'object' || obj === null) return false;\n\n // Validate that the object has the necessary properties of RecordsWrite.\n return (\n 'message' in obj && typeof obj.message === 'object' && obj.message !== null &&\n 'descriptor' in obj.message && typeof obj.message.descriptor === 'object' && obj.message.descriptor !== null &&\n 'interface' in obj.message.descriptor && obj.message.descriptor.interface === DwnInterfaceName.Records &&\n 'method' in obj.message.descriptor && obj.message.descriptor.method === DwnMethodName.Write\n );\n}\n\n/**\n * Get the CID of the given RecordsWriteMessage.\n */\nexport function getRecordMessageCid(message: RecordsWriteMessage): Promise<string> {\n return Message.getCid(message);\n}\n\n/**\n * Get the pagination cursor for the given RecordsWriteMessage and DateSort.\n *\n * @param message The RecordsWriteMessage for which to get the pagination cursor.\n * @param dateSort The date sort that will be used in the query or subscription to which the cursor will be applied.\n */\nexport async function getPaginationCursor(message: RecordsWriteMessage, dateSort: DateSort): Promise<PaginationCursor> {\n const value = dateSort === DateSort.CreatedAscending || dateSort === DateSort.CreatedDescending ?\n message.descriptor.dateCreated : message.descriptor.datePublished;\n\n if (value === undefined) {\n throw new Error('The dateCreated or datePublished property is missing from the record descriptor.');\n }\n\n return {\n messageCid: await getRecordMessageCid(message),\n value\n };\n}\n\nexport function webReadableToIsomorphicNodeReadable(webReadable: ReadableStream<any>) {\n return new ReadableWebToNodeStream(webReadable);\n}\n\n/**\n * Polling function with interval, TTL accepting a custom fetch function\n * @template T - the return you expect from the fetcher\n * @param fetchFunction an http fetch function\n * @param [interval=3000] how frequently to poll\n * @param [ttl=300_000] how long until polling stops\n * @returns T - the result of fetch\n */\nexport function pollWithTtl(\n fetchFunction: () => Promise<Response>,\n interval = 3000,\n ttl = 300_000,\n abortSignal?: AbortSignal\n): Promise<Response | null> {\n const endTime = Date.now() + ttl;\n let timeoutId: NodeJS.Timeout | null = null;\n let isPolling = true;\n return new Promise((resolve, reject) => {\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n isPolling = false;\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n }\n console.log('Polling aborted by user');\n resolve(null);\n });\n }\n\n async function poll() {\n if (!isPolling) return;\n\n const remainingTime = endTime - Date.now();\n\n if (remainingTime <= 0) {\n isPolling = false;\n console.log('Polling stopped: TTL reached');\n resolve(null);\n return;\n }\n\n console.log(`Polling... (Remaining time: ${Math.ceil(remainingTime / 1000)}s)`);\n\n try {\n const response = await fetchFunction();\n\n if (response.ok) {\n isPolling = false;\n\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n }\n\n console.log('Polling stopped: Success condition met');\n resolve(response);\n return;\n }\n } catch (error) {\n console.error('Error fetching data:', error);\n reject(error);\n }\n\n if (isPolling) {\n timeoutId = setTimeout(poll, interval);\n }\n }\n\n poll();\n });\n}\n\n/** Concatenates a base URL and a path ensuring that there is exactly one slash between them */\nexport function concatenateUrl(baseUrl: string, path: string): string {\n // Remove trailing slash from baseUrl if it exists\n if (baseUrl.endsWith('/')) {\n baseUrl = baseUrl.slice(0, -1);\n }\n\n // Remove leading slash from path if it exists\n if (path.startsWith('/')) {\n path = path.slice(1);\n }\n\n return `${baseUrl}/${path}`;\n}", "import { Sha256, CryptoUtils } from '@enbox/crypto';\nimport { concatenateUrl } from './utils.js';\nimport { Convert } from '@enbox/common';\n\n/**\n * A client for registering tenants with a DWN.\n */\nexport class DwnRegistrar {\n /**\n * Registers a new tenant with the given DWN.\n * NOTE: Assumes the user has already accepted the terms of service.\n * NOTE: Currently the DWN Server from `dwn-server` does not require user signature.\n * TODO: bring in types from `dwn-server`.\n */\n public static async registerTenant(dwnEndpoint: string, did: string): Promise<void> {\n\n const registrationEndpoint = concatenateUrl(dwnEndpoint, 'registration');\n const termsOfUseEndpoint = concatenateUrl(registrationEndpoint, 'terms-of-service');\n const proofOfWorkEndpoint = concatenateUrl(registrationEndpoint, 'proof-of-work');\n\n // fetch the terms-of-service\n const termsOfServiceGetResponse = await fetch(termsOfUseEndpoint, {\n method: 'GET',\n });\n\n if (termsOfServiceGetResponse.status !== 200) {\n const statusCode = termsOfServiceGetResponse.status;\n const statusText = termsOfServiceGetResponse.statusText;\n const errorText = await termsOfServiceGetResponse.text();\n throw new Error(`Failed fetching terms-of-service: ${statusCode} ${statusText}: ${errorText}`);\n }\n const termsOfServiceFetched = await termsOfServiceGetResponse.text();\n\n // fetch the proof-of-work challenge\n const proofOfWorkChallengeGetResponse = await fetch(proofOfWorkEndpoint, {\n method: 'GET',\n });\n const { challengeNonce, maximumAllowedHashValue} = await proofOfWorkChallengeGetResponse.json();\n\n // create registration data based on the hash of the terms-of-service and the DID\n const registrationData = {\n did,\n termsOfServiceHash: await DwnRegistrar.hashAsHexString(termsOfServiceFetched),\n };\n\n // compute the proof-of-work response nonce based on the the proof-of-work challenge and the registration data.\n const responseNonce = await DwnRegistrar.findQualifiedResponseNonce({\n challengeNonce,\n maximumAllowedHashValue,\n requestData: JSON.stringify(registrationData),\n });\n\n // send the registration request to the server\n const registrationRequest = {\n registrationData,\n proofOfWork: {\n challengeNonce,\n responseNonce,\n },\n };\n\n const registrationResponse = await fetch(registrationEndpoint, {\n method : 'POST',\n headers : { 'Content-Type': 'application/json' },\n body : JSON.stringify(registrationRequest),\n });\n\n if (registrationResponse.status !== 200) {\n const statusCode = registrationResponse.status;\n const statusText = registrationResponse.statusText;\n const errorText = await registrationResponse.text();\n throw new Error(`Registration failed: ${statusCode} ${statusText}: ${errorText}`);\n }\n }\n\n /**\n * Computes the SHA-256 hash of the given array of strings.\n */\n public static async hashAsHexString(input: string): Promise<string> {\n const hashAsBytes = await Sha256.digest({ data: Convert.string(input).toUint8Array()});\n const hashAsHex = Convert.uint8Array(hashAsBytes).toHex();\n return hashAsHex;\n }\n\n /**\n * Finds a response nonce that qualifies the difficulty requirement for the given proof-of-work challenge and request data.\n */\n public static async findQualifiedResponseNonce(input: {\n maximumAllowedHashValue: string;\n challengeNonce: string;\n requestData: string;\n }): Promise<string> {\n const startTime = Date.now();\n\n const { maximumAllowedHashValue, challengeNonce, requestData } = input;\n const maximumAllowedHashValueAsBigInt = BigInt(`0x${maximumAllowedHashValue}`);\n\n let iterations = 1;\n let responseNonce;\n let qualifiedSolutionNonceFound = false;\n do {\n responseNonce = await this.generateNonce();\n const computedHash = await DwnRegistrar.hashAsHexString(challengeNonce + responseNonce + requestData);\n const computedHashAsBigInt = BigInt(`0x${computedHash}`);\n\n qualifiedSolutionNonceFound = computedHashAsBigInt <= maximumAllowedHashValueAsBigInt;\n\n iterations++;\n } while (!qualifiedSolutionNonceFound);\n\n // Log final/successful iteration.\n console.log(\n `iterations: ${iterations}, time lapsed: ${Date.now() - startTime} ms`,\n );\n\n return responseNonce;\n }\n\n /**\n * Generates 32 random bytes expressed as a HEX string.\n */\n public static async generateNonce(): Promise<string> {\n const randomBytes = CryptoUtils.randomBytes(32);\n const hexString = Convert.uint8Array(randomBytes).toHex().toUpperCase();\n return hexString;\n }\n}", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\n// The file will throw on node.js 14 and earlier.\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto =\n nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\n// Other libraries would silently corrupt the data instead of throwing an error,\n// when they don't support it.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!isBytes(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a)) throw new Error('Uint8Array expected');\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2<T extends SHA2<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "import { SHA2 } from './_sha2.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends SHA2<SHA512> {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x6a09e667 | 0;\n Al = 0xf3bcc908 | 0;\n Bh = 0xbb67ae85 | 0;\n Bl = 0x84caa73b | 0;\n Ch = 0x3c6ef372 | 0;\n Cl = 0xfe94f82b | 0;\n Dh = 0xa54ff53a | 0;\n Dl = 0x5f1d36f1 | 0;\n Eh = 0x510e527f | 0;\n El = 0xade682d1 | 0;\n Fh = 0x9b05688c | 0;\n Fl = 0x2b3e6c1f | 0;\n Gh = 0x1f83d9ab | 0;\n Gl = 0xfb41bd6b | 0;\n Hh = 0x5be0cd19 | 0;\n Hl = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nclass SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x8c3d37c8 | 0;\n Al = 0x19544da2 | 0;\n Bh = 0x73e19966 | 0;\n Bl = 0x89dcd4d6 | 0;\n Ch = 0x1dfab7ae | 0;\n Cl = 0x32ff9c82 | 0;\n Dh = 0x679dd514 | 0;\n Dl = 0x582f9fcf | 0;\n Eh = 0x0f6d2b69 | 0;\n El = 0x7bd44da8 | 0;\n Fh = 0x77e36f73 | 0;\n Fl = 0x04c48942 | 0;\n Gh = 0x3f9d85a8 | 0;\n Gl = 0x6a1d36c8 | 0;\n Hh = 0x1112e6ad | 0;\n Hl = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nclass SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x22312194 | 0;\n Al = 0xfc2bf72c | 0;\n Bh = 0x9f555fa3 | 0;\n Bl = 0xc84c64c2 | 0;\n Ch = 0x2393b86b | 0;\n Cl = 0x6f53b151 | 0;\n Dh = 0x96387719 | 0;\n Dl = 0x5940eabd | 0;\n Eh = 0x96283ee2 | 0;\n El = 0xa88effe3 | 0;\n Fh = 0xbe5e1e25 | 0;\n Fl = 0x53863992 | 0;\n Gh = 0x2b0199fc | 0;\n Gl = 0x2c85b8aa | 0;\n Hh = 0x0eb72ddc | 0;\n Hl = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nclass SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0xcbbb9d5d | 0;\n Al = 0xc1059ed8 | 0;\n Bh = 0x629a292a | 0;\n Bl = 0x367cd507 | 0;\n Ch = 0x9159015a | 0;\n Cl = 0x3070dd17 | 0;\n Dh = 0x152fecd8 | 0;\n Dl = 0xf70e5939 | 0;\n Eh = 0x67332667 | 0;\n El = 0xffc00b31 | 0;\n Fh = 0x8eb44a87 | 0;\n Fl = 0x68581511 | 0;\n Gh = 0xdb0c2e0d | 0;\n Gl = 0x64f98fa7 | 0;\n Hh = 0x47b5481d | 0;\n Hl = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a)) throw new Error('Uint8Array expected');\n sum += a.length;\n }\n let res = new Uint8Array(sum);\n let pad = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n: bigint, pos: number, value: boolean) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n numberToBytesBE,\n numberToBytesLE,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) \u2261 1 if a is a square (mod p)\n // (a | p) \u2261 -1 if a is not a square (mod p)\n // (a | p) \u2261 0 if a \u2261 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) \u2261 -1 and set c \u2261 zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be \u2261 -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P \u2261 3 (mod 4)\n // \u221An = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q \u2261 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P \u2261 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField<T> {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(f: IField<T>, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('Expected power > 0');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch<T>(f: IField<T>, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv<T>(f: IField<T>, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(f: IField<T>) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x: T): boolean => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number) {\n const constTimeNegate = (condition: boolean, item: T): T => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W: number) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint) {\n let p = c.ZERO;\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = opts(W);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n wNAFCached(P: T, precomputesMap: Map<T, T[]>, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n // @ts-ignore\n const W: number = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(curve: BasicCurve<FP> & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, FHash, Hex } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n// Edwards curves must declare params a & d.\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n// Instance of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n };\n};\n\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n: bigint, max: bigint) {\n // n in [1..max-1]\n if (inRange(n, max)) return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n: bigint) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map<Point, Point[]>();\n function isPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n if (!in0MaskRange(ex)) throw new Error('x required');\n if (!in0MaskRange(ey)) throw new Error('y required');\n if (!in0MaskRange(ez)) throw new Error('z required');\n if (!in0MaskRange(et)) throw new Error('t required');\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n const { a, d } = CURVE;\n if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n protected is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar: bigint): Point {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n) return I;\n if (this.equals(I) || n === _1n) return this;\n if (this.equals(G)) return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n } else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215) assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\nimport { createHasher, htfBasicOpts, expand_message_xmd } from './abstract/hash-to-curve.js';\nimport { AffinePoint, Group } from './abstract/curve.js';\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);\n// prettier-ignore\nconst _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = Field(ED25519_P, undefined, true);\n\nconst ed25519Defaults = {\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field \uD835\uDD3Dp over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: BigInt(8),\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n} as const;\n\nexport const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n});\nexport const ed25519ph = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n prehash: sha512,\n});\n\nexport const x25519 = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic\n\nconst ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1\nconst ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)\nconst ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic\nconst ELL2_J = BigInt(486662);\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint<bigint>) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n", "import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n", "import { SHA2 } from './_sha2.js';\nimport { wrapConstructor } from './utils.js';\n\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i);\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++) for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k]));\n\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// The rotate left (circular left shift) operation for uint32\nconst rotl = (word: number, shift: number) => (word << shift) | (word >>> (32 - shift));\n// It's called f() in spec.\nfunction f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n else if (group === 1) return (x & y) | (~x & z);\n else if (group === 2) return (x | ~y) ^ z;\n else if (group === 3) return (x & z) | (y & ~z);\n else return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends SHA2<RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean() {\n BUF.fill(0);\n }\n destroy() {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a hash function from 1990s.\n * @param message - msg that would be hashed\n */\nexport const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n", "import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = IV[0] | 0;\n B = IV[1] | 0;\n C = IV[2] | 0;\n D = IV[3] | 0;\n E = IV[4] | 0;\n F = IV[5] | 0;\n G = IV[6] | 0;\n H = IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n", "/*! micro-ed25519-hdkey - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { hmac } from '@noble/hashes/hmac';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, createView, hexToBytes, utf8ToBytes, bytesToHex } from '@noble/hashes/utils';\nimport { bytes as assertBytes } from '@noble/hashes/_assert';\nexport const MASTER_SECRET = utf8ToBytes('ed25519 seed');\nexport const HARDENED_OFFSET = 0x80000000;\nconst ZERO = new Uint8Array([0]);\nfunction ensureBytes(b, ...lengths) {\n if (typeof b === 'string')\n b = hexToBytes(b);\n assertBytes(b, ...lengths);\n return b;\n}\nconst hash160 = (data) => ripemd160(sha256(data));\nconst fromU32 = (data) => createView(data).getUint32(0, false);\nconst toU32 = (n) => {\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {\n throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`);\n }\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\nexport class HDKey {\n get publicKeyRaw() {\n return ed25519.getPublicKey(this.privateKey);\n }\n get publicKey() {\n return concatBytes(ZERO, this.publicKeyRaw);\n }\n get pubHash() {\n return hash160(this.publicKey);\n }\n get fingerprint() {\n return fromU32(this.pubHash);\n }\n get fingerprintHex() {\n return bytesToHex(toU32(this.fingerprint));\n }\n get parentFingerprintHex() {\n return bytesToHex(toU32(this.parentFingerprint));\n }\n static fromMasterSeed(seed) {\n seed = ensureBytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new Error(`HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`);\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n return new HDKey({\n privateKey: I.slice(0, 32),\n chainCode: I.slice(32),\n });\n }\n constructor(opt) {\n this.depth = 0;\n this.index = 0;\n this.parentFingerprint = 0;\n if (!opt || typeof opt !== 'object')\n throw new Error('HDKey.constructor must not be called directly');\n assertBytes(opt.privateKey, 32);\n assertBytes(opt.chainCode, 32);\n this.depth = opt.depth || 0;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index)\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n this.chainCode = opt.chainCode;\n this.privateKey = opt.privateKey;\n }\n derive(path, forceHardened = false) {\n if (!/^[mM]'?/.test(path))\n throw new Error('Path must start with \"m\" or \"M\"');\n if (/^[mM]'?$/.test(path))\n return this;\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n if (!m || m.length !== 3)\n throw new Error(`Invalid child index: ${c}`);\n let idx = +m[1];\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET)\n throw new Error('Invalid index');\n // hardened key\n if (forceHardened || m[2] === \"'\")\n idx += HARDENED_OFFSET;\n child = child.deriveChild(idx);\n }\n return child;\n }\n deriveChild(index) {\n if (index < HARDENED_OFFSET)\n throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${index})`);\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n const data = concatBytes(ZERO, this.privateKey, toU32(index));\n const I = hmac(sha512, this.chainCode, data);\n return new HDKey({\n chainCode: I.slice(32),\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n privateKey: I.slice(0, 32),\n });\n }\n sign(message) {\n return ed25519.sign(message, this.privateKey);\n }\n verify(message, signature) {\n signature = ensureBytes(signature, 64);\n return ed25519.verify(signature, message, this.publicKeyRaw);\n }\n}\n", "import type { Jwk } from '@enbox/crypto';\nimport type { KeyValueStore } from '@enbox/common';\nimport { DidDhtCreateOptions } from '@enbox/dids';\n\nimport { HDKey } from 'ed25519-keygen/hdkey';\nimport { BearerDid, DidDht } from '@enbox/dids';\nimport { Convert, MemoryStore } from '@enbox/common';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nimport { generateMnemonic, mnemonicToSeed, validateMnemonic } from '@scure/bip39';\n\nimport type { JweHeaderParams } from './prototyping/crypto/jose/jwe.js';\nimport type { IdentityVaultBackup, IdentityVaultBackupData, IdentityVaultStatus, IdentityVaultParams, IdentityVault } from './types/identity-vault.js';\n\nimport { AgentCryptoApi } from './crypto-api.js';\nimport { LocalKeyManager } from './local-key-manager.js';\nimport { isPortableDid } from './prototyping/dids/utils.js';\nimport { DeterministicKeyGenerator } from './utils-internal.js';\nimport { CompactJwe } from './prototyping/crypto/jose/jwe-compact.js';\n\n/**\n * Extended initialization parameters for HdIdentityVault, including an optional recovery phrase\n * that can be used to derive keys to encrypt the vault and generate a DID.\n */\nexport type HdIdentityVaultInitializeParams = {\n /**\n * The password used to secure the vault.\n *\n * The password selected should be strong and securely managed to prevent unauthorized access.\n */\n password: string;\n\n /**\n * An optional recovery phrase used to derive the cryptographic keys for the vault.\n *\n * Providing a recovery phrase can be used to recover the vault's content or establish a\n * deterministic key generation scheme. If not provided, a new recovery phrase will be generated\n * during the initialization process.\n */\n recoveryPhrase?: string;\n\n /**\n * Optional dwnEndpoints to register didService endpoints during HdIdentityVault initialization\n *\n * The dwnEndpoints are used to register a DWN endpoint during DidDht.create(). This allows the\n * agent to properly recover connectedDids from DWN. Also, this pattern can be used on the server\n * side in place of the agentDid-->connectedDids pattern.\n */\n dwnEndpoints?: string[];\n };\n\n/**\n * Type guard function to check if a given object is an empty string or a string containing only\n * whitespace.\n *\n * This is an internal utility function used to validate password inputs, ensuring they are not\n * empty or filled with only whitespace characters, which are considered invalid for password\n * purposes.\n *\n * @param obj - The object to be checked, typically expected to be a password string.\n * @returns A boolean value indicating whether the object is an empty string or a string with only\n * whitespace.\n */\nfunction isEmptyString(obj: unknown): obj is string {\n return typeof obj !== 'string' || obj.trim().length === 0;\n}\n\n/**\n * Type guard function to check if a given object conforms to the {@link IdentityVaultBackup}\n * interface.\n *\n * This function is an internal utility meant to ensure the integrity and structure of the data\n * assumed to be an {@link IdentityVaultBackup}. It verifies the presence and types of the\n * `dateCreated`, `size`, and `data` properties, aligning with the expected structure of a backup\n * object in the context of an {@link IdentityVault}.\n *\n * @param obj - The object to be verified against the {@link IdentityVaultBackup} interface.\n * @returns A boolean value indicating whether the object is a valid {@link IdentityVaultBackup}.\n */\nfunction isIdentityVaultBackup(obj: unknown): obj is IdentityVaultBackup {\n return typeof obj === 'object' && obj !== null\n && 'dateCreated' in obj && typeof obj.dateCreated === 'string'\n && 'size' in obj && typeof obj.size === 'number'\n && 'data' in obj && typeof obj.data === 'string';\n}\n\n/**\n * Internal-only type guard function that checks if a given object conforms to the\n * {@link IdentityVaultStatus} interface.\n *\n * This function is utilized within the {@link HdIdentityVault} implementation to ensure the\n * integrity of the object representing the vault's status, verifying the presence and types of\n * required properties. It aasserts the presence and correct types of `initialized`, `lastBackup`,\n * and `lastRestore` properties, ensuring they align with the expected structure of an identity\n * vault's status.\n *\n * @param obj - The object to be checked against the {{@link IdentityVaultStatus} interface.\n * @returns A boolean indicating whether the object is an instance of {@link IdentityVaultStatus}.\n */\nfunction isIdentityVaultStatus(obj: unknown): obj is IdentityVaultStatus {\n return typeof obj === 'object' && obj !== null\n && 'initialized' in obj && typeof obj.initialized === 'boolean'\n && 'lastBackup' in obj\n && 'lastRestore' in obj;\n}\n\n/**\n * The `HdIdentityVault` class provides secure storage and management of identity data.\n *\n * The `HdIdentityVault` class implements the `IdentityVault` interface, providing secure storage\n * and management of identity data with an added layer of security using Hierarchical Deterministic\n * (HD) key derivation based on the SLIP-0010 standard for Ed25519 keys. It enhances identity\n * protection by generating and securing the identity using a derived HD key, allowing for the\n * deterministic regeneration of keys from a recovery phrase.\n *\n * The vault is capable of:\n * - Secure initialization with a password and an optional recovery phrase, employing HD key\n * derivation.\n * - Encrypting the identity data using a derived content encryption key (CEK) which is securely\n * encrypted and stored, accessible only by the correct password.\n * - Securely backing up and restoring the vault\u2019s contents, including the HD-derived keys and\n * associated DID.\n * - Locking and unlocking the vault, which encrypts and decrypts the CEK for secure access to the\n * vault's contents.\n * - Managing the DID associated with the identity, providing a secure identity layer for\n * applications.\n *\n * Usage involves initializing the vault with a secure password (and optionally a recovery phrase),\n * which then allows for the secure storage, backup, and retrieval of the identity data.\n *\n * Note: Ensure the password is strong and securely managed, as it is crucial for the security of the\n * vault's encrypted contents.\n *\n * @example\n * ```typescript\n * const vault = new HdIdentityVault();\n * await vault.initialize({ password: 'secure-unique-phrase', recoveryPhrase: 'twelve words ...' });\n * const backup = await vault.backup();\n * await vault.restore({ backup, password: 'secure-unique-phrase' });\n * ```\n */\nexport class HdIdentityVault implements IdentityVault<{ InitializeResult: string }> {\n /** Provides cryptographic functions needed for secure storage and management of the vault. */\n public crypto = new AgentCryptoApi();\n\n /** Determines the computational intensity of the key derivation process. */\n private _keyDerivationWorkFactor: number;\n\n /** The underlying key-value store for the vault's encrypted content. */\n private _store: KeyValueStore<string, string>;\n\n /** The cryptographic key used to encrypt and decrypt the vault's content securely. */\n private _contentEncryptionKey: Jwk | undefined;\n\n /**\n * Constructs an instance of `HdIdentityVault`, initializing the key derivation factor and data\n * store. It sets the default key derivation work factor and initializes the internal data store,\n * either with the provided store or a default in-memory store. It also establishes the initial\n * status of the vault as uninitialized and locked.\n *\n * @param params - Optional parameters when constructing a vault instance.\n * @param params.keyDerivationWorkFactor - Optionally set the computational effort for key derivation.\n * @param params.store - Optionally specify a custom key-value store for vault data.\n */\n constructor({ keyDerivationWorkFactor, store }: IdentityVaultParams = {}) {\n this._keyDerivationWorkFactor = keyDerivationWorkFactor ?? 210_000;\n this._store = store ?? new MemoryStore<string, string>();\n }\n\n /**\n * Creates a backup of the vault's current state, including the encrypted DID and content\n * encryption key, and returns it as an `IdentityVaultBackup` object. The backup includes a\n * Base64Url-encoded string representing the vault's encrypted data, encapsulating the\n * {@link PortableDid}, the content encryption key, and the vault's status.\n *\n * This method ensures that the vault is initialized and unlocked before proceeding with the\n * backup operation.\n *\n * @throws Error if the vault is not initialized or is locked, preventing the backup.\n * @returns A promise that resolves to the `IdentityVaultBackup` object containing the vault's\n * encrypted backup data.\n */\n public async backup(): Promise<IdentityVaultBackup> {\n // Verify the identity vault has already been initialized and unlocked.\n if (this.isLocked() || await this.isInitialized() === false) {\n throw new Error(\n 'HdIdentityVault: Unable to proceed with the backup operation because the identity vault ' +\n 'has not been initialized and unlocked. Please ensure the vault is properly initialized ' +\n 'with a secure password before attempting to backup its contents.'\n );\n }\n\n // Encode the encrypted CEK and DID as a single Base64Url string.\n const backupData: IdentityVaultBackupData = {\n did : await this.getStoredDid(),\n contentEncryptionKey : await this.getStoredContentEncryptionKey(),\n status : await this.getStatus()\n };\n const backupDataString = Convert.object(backupData).toBase64Url();\n\n // Create a backup object containing the encrypted vault contents.\n const backup: IdentityVaultBackup = {\n data : backupDataString,\n dateCreated : new Date().toISOString(),\n size : backupDataString.length\n };\n\n // Update the last backup timestamp in the data store.\n await this.setStatus({ lastBackup: backup.dateCreated });\n\n return backup;\n }\n\n /**\n * Changes the password used to secure the vault.\n *\n * This method decrypts the existing content encryption key (CEK) with the old password, then\n * re-encrypts it with the new password, updating the vault's stored encrypted CEK. It ensures\n * that the vault is initialized and unlocks the vault if the password is successfully changed.\n *\n * @param params - Parameters required for changing the vault password.\n * @param params.oldPassword - The current password used to unlock the vault.\n * @param params.newPassword - The new password to replace the existing one.\n * @throws Error if the vault is not initialized or the old password is incorrect.\n * @returns A promise that resolves when the password change is complete.\n */\n public async changePassword({ oldPassword, newPassword }: {\n oldPassword: string;\n newPassword: string;\n }): Promise<void> {\n // Verify the identity vault has already been initialized.\n if (await this.isInitialized() === false) {\n throw new Error(\n 'HdIdentityVault: Unable to proceed with the change password operation because the ' +\n 'identity vault has not been initialized. Please ensure the vault is properly ' +\n 'initialized with a secure password before trying again.'\n );\n }\n\n // Lock the vault.\n await this.lock();\n\n // Retrieve the content encryption key (CEK) record as a compact JWE from the data store.\n const cekJwe = await this.getStoredContentEncryptionKey();\n\n // Decrypt the compact JWE using the given `oldPassword` to verify it is correct.\n let protectedHeader: JweHeaderParams;\n let contentEncryptionKey: Jwk;\n try {\n let contentEncryptionKeyBytes: Uint8Array;\n ({ plaintext: contentEncryptionKeyBytes, protectedHeader } = await CompactJwe.decrypt({\n jwe : cekJwe,\n key : Convert.string(oldPassword).toUint8Array(),\n crypto : this.crypto,\n keyManager : new LocalKeyManager()\n }));\n contentEncryptionKey = Convert.uint8Array(contentEncryptionKeyBytes).toObject() as Jwk;\n\n } catch (error: any) {\n throw new Error(`HdIdentityVault: Unable to change the vault password due to an incorrectly entered old password.`);\n }\n\n // Re-encrypt the vault content encryption key (CEK) using the new password.\n const newCekJwe = await CompactJwe.encrypt({\n key : Convert.string(newPassword).toUint8Array(),\n protectedHeader, // Re-use the protected header from the original JWE.\n plaintext : Convert.object(contentEncryptionKey).toUint8Array(),\n crypto : this.crypto,\n keyManager : new LocalKeyManager()\n });\n\n // Update the vault with the new CEK JWE.\n await this._store.set('contentEncryptionKey', newCekJwe);\n\n // Update the vault CEK in memory, effectively unlocking the vault.\n this._contentEncryptionKey = contentEncryptionKey;\n }\n\n /**\n * Retrieves the DID (Decentralized Identifier) associated with the vault.\n *\n * This method ensures the vault is initialized and unlocked before decrypting and returning the\n * DID. The DID is stored encrypted and is decrypted using the vault's content encryption key.\n *\n * @throws Error if the vault is not initialized, is locked, or the DID cannot be decrypted.\n * @returns A promise that resolves with a {@link BearerDid}.\n */\n public async getDid(): Promise<BearerDid> {\n // Verify the identity vault is unlocked.\n if (this.isLocked()) {\n throw new Error(`HdIdentityVault: Vault has not been initialized and unlocked.`);\n }\n\n // Retrieve the encrypted DID record as compact JWE from the vault store.\n const didJwe = await this.getStoredDid();\n\n // Decrypt the compact JWE to obtain the PortableDid as a byte array.\n const { plaintext: portableDidBytes } = await CompactJwe.decrypt({\n jwe : didJwe,\n key : this._contentEncryptionKey!,\n crypto : this.crypto,\n keyManager : new LocalKeyManager()\n });\n\n // Convert the DID from a byte array to PortableDid format.\n const portableDid = Convert.uint8Array(portableDidBytes).toObject();\n if (!isPortableDid(portableDid)) {\n throw new Error('HdIdentityVault: Unable to decode malformed DID in identity vault');\n }\n\n // Return the DID in Bearer DID format.\n return await BearerDid.import({ portableDid });\n }\n\n /**\n * Fetches the current status of the `HdIdentityVault`, providing details on whether it's\n * initialized and the timestamps of the last backup and restore operations.\n *\n * @returns A promise that resolves with the current status of the `HdIdentityVault`, detailing\n * its initialization, lock state, and the timestamps of the last backup and restore.\n */\n public async getStatus(): Promise<IdentityVaultStatus> {\n const storedStatus = await this._store.get('vaultStatus');\n\n // On the first run, the store will not contain an IdentityVaultStatus object yet, so return an\n // uninitialized status.\n if (!storedStatus) {\n return {\n initialized : false,\n lastBackup : null,\n lastRestore : null\n };\n }\n\n const vaultStatus = Convert.string(storedStatus).toObject();\n if (!isIdentityVaultStatus(vaultStatus)) {\n throw new Error('HdIdentityVault: Invalid IdentityVaultStatus object in store');\n }\n\n return vaultStatus;\n }\n\n /**\n * Initializes the `HdIdentityVault` with a password and an optional recovery phrase.\n *\n * If a recovery phrase is not provided, a new one is generated. This process sets up the vault,\n * deriving the necessary cryptographic keys and preparing the vault for use. It ensures the vault\n * is ready to securely store and manage identity data.\n *\n * @example\n * ```ts\n * const identityVault = new HdIdentityVault();\n * const recoveryPhrase = await identityVault.initialize({\n * password: 'your-secure-phrase'\n * });\n * console.log('Vault initialized. Recovery phrase:', recoveryPhrase);\n * ```\n *\n * @param params - The initialization parameters.\n * @param params.password - The password used to secure the vault.\n * @param params.recoveryPhrase - An optional 12-word recovery phrase for key derivation. If\n * omitted, a new recovery is generated.\n * @returns A promise that resolves with the recovery phrase used during the initialization, which\n * should be securely stored by the user.\n */\n public async initialize({ password, recoveryPhrase, dwnEndpoints }:\n HdIdentityVaultInitializeParams\n ): Promise<string> {\n /**\n * STEP 0: Validate the input parameters and verify the identity vault is not already\n * initialized.\n */\n\n // Verify that the identity vault was not previously initialized.\n if (await this.isInitialized()) {\n throw new Error(`HdIdentityVault: Vault has already been initialized.`);\n }\n\n // Verify that the password is not empty.\n if (isEmptyString(password)) {\n throw new Error(\n `HdIdentityVault: The password is required and cannot be blank. Please provide a ' +\n 'valid, non-empty password.`\n );\n }\n\n // If provided, verify that the recovery phrase is not empty.\n if (recoveryPhrase && isEmptyString(recoveryPhrase)) {\n throw new Error(\n `HdIdentityVault: The password is required and cannot be blank. Please provide a ' +\n 'valid, non-empty password.`\n );\n }\n\n /**\n * STEP 1: Derive a Hierarchical Deterministic (HD) key pair from the given (or generated)\n * recoveryPhrase.\n */\n\n // Generate a 12-word (128-bit) mnemonic, if one was not provided.\n recoveryPhrase ??= generateMnemonic(wordlist, 128);\n\n // Validate the mnemonic for being 12-24 words contained in `wordlist`.\n if (!validateMnemonic(recoveryPhrase, wordlist)) {\n throw new Error(\n 'HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the ' +\n 'recovery phrase is a correctly formatted series of 12 words.'\n );\n }\n\n // Derive a root seed from the mnemonic.\n const rootSeed = await mnemonicToSeed(recoveryPhrase);\n\n // Derive a root key for the DID from the root seed.\n const rootHdKey = HDKey.fromMasterSeed(rootSeed);\n\n /**\n * STEP 2: Derive the vault HD key pair from the root key.\n */\n\n // The vault HD key is derived using account 0 and index 0 so that it can be\n // deterministically re-derived. The vault key pair serves as input keying material for:\n // - deriving the vault content encryption key (CEK)\n // - deriving the salt that serves as input to derive the key that encrypts the vault CEK\n const vaultHdKey = rootHdKey.derive(`m/44'/0'/0'/0'/0'`);\n\n /**\n * STEP 3: Derive the vault Content Encryption Key (CEK) from the vault private\n * key and a non-secret static info value.\n */\n\n // A non-secret static info value is combined with the vault private key as input to HKDF\n // (Hash-based Key Derivation Function) to derive a 32-byte content encryption key (CEK).\n const contentEncryptionKey = await this.crypto.deriveKey({\n algorithm : 'HKDF-512', // key derivation function\n baseKeyBytes : vaultHdKey.privateKey, // input keying material\n salt : '', // empty salt because private key is sufficiently random\n info : 'vault_cek', // non-secret application specific information\n derivedKeyAlgorithm : 'A256GCM' // derived key algorithm\n });\n\n /**\n * STEP 4: Using the given `password` and a `salt` derived from the vault public key, encrypt\n * the vault CEK and store it in the data store as a compact JWE.\n */\n\n // A non-secret static info value is combined with the vault public key as input to HKDF\n // (Hash-based Key Derivation Function) to derive a new 32-byte salt.\n const saltInput = await this.crypto.deriveKeyBytes({\n algorithm : 'HKDF-512', // key derivation function\n baseKeyBytes : vaultHdKey.publicKey, // input keying material\n salt : '', // empty salt because public key is sufficiently random\n info : 'vault_unlock_salt', // non-secret application specific information\n length : 256, // derived key length, in bits\n });\n\n // Construct the JWE header.\n const cekJweProtectedHeader: JweHeaderParams = {\n alg : 'PBES2-HS512+A256KW',\n enc : 'A256GCM',\n cty : 'text/plain',\n p2c : this._keyDerivationWorkFactor,\n p2s : Convert.uint8Array(saltInput).toBase64Url()\n };\n\n // Encrypt the vault content encryption key (CEK) to compact JWE format.\n const cekJwe = await CompactJwe.encrypt({\n key : Convert.string(password).toUint8Array(),\n protectedHeader : cekJweProtectedHeader,\n plaintext : Convert.object(contentEncryptionKey).toUint8Array(),\n crypto : this.crypto,\n keyManager : new LocalKeyManager()\n });\n\n // Store the compact JWE in the data store.\n await this._store.set('contentEncryptionKey', cekJwe);\n\n /**\n * STEP 5: Create a DID using identity, signing, and encryption keys derived from the root key.\n */\n\n // Derive the identity key pair using index 0 and convert to JWK format.\n // Note: The account is set to Unix epoch time so that in the future, the keys for a DID DHT\n // document can be deterministically derived based on the versionId returned in a DID\n // resolution result.\n const identityHdKey = rootHdKey.derive(`m/44'/0'/1708523827'/0'/0'`);\n const identityPrivateKey = await this.crypto.bytesToPrivateKey({\n algorithm : 'Ed25519',\n privateKeyBytes : identityHdKey.privateKey\n });\n\n // Derive the signing key using index 1 and convert to JWK format.\n let signingHdKey = rootHdKey.derive(`m/44'/0'/1708523827'/0'/1'`);\n const signingPrivateKey = await this.crypto.bytesToPrivateKey({\n algorithm : 'Ed25519',\n privateKeyBytes : signingHdKey.privateKey\n });\n\n // TODO: Enable this once DID DHT supports X25519 keys.\n // Derive the encryption key using index 1 and convert to JWK format.\n // const encryptionHdKey = rootHdKey.derive(`m/44'/0'/1708523827'/0'/1'`);\n // const encryptionKeyEd25519 = await this.crypto.bytesToPrivateKey({\n // algorithm : 'Ed25519',\n // privateKeyBytes : encryptionHdKey.privateKey\n // });\n // const encryptionPrivateKey = await Ed25519.convertPrivateKeyToX25519({ privateKey: encryptionKeyEd25519 });\n\n // Add the identity and signing keys to the deterministic key generator so that when the DID is\n // created it will use the derived keys.\n const deterministicKeyGenerator = new DeterministicKeyGenerator();\n await deterministicKeyGenerator.addPredefinedKeys({\n privateKeys: [identityPrivateKey, signingPrivateKey]\n });\n\n // Create the DID using the derived identity, signing, and encryption keys.\n const options = {\n verificationMethods: [\n {\n algorithm : 'Ed25519',\n id : 'sig',\n purposes : ['assertionMethod', 'authentication']\n },\n ]\n } as DidDhtCreateOptions<DeterministicKeyGenerator>;\n\n if(dwnEndpoints && !!dwnEndpoints.length) {\n options.services = [\n {\n id : 'dwn',\n type : 'DecentralizedWebNode',\n serviceEndpoint : dwnEndpoints,\n enc : '#enc',\n sig : '#sig',\n }\n ];\n }\n\n const did = await DidDht.create({ keyManager: deterministicKeyGenerator, options });\n\n /**\n * STEP 6: Convert the DID to portable format and store it in the data store as a\n * compact JWE.\n */\n\n // Convert the DID to a portable format.\n const portableDid = await did.export();\n\n // Construct the JWE header.\n const didJweProtectedHeader: JweHeaderParams = {\n alg : 'dir',\n enc : 'A256GCM',\n cty : 'json'\n };\n\n // Encrypt the DID to compact JWE format.\n const didJwe = await CompactJwe.encrypt({\n key : contentEncryptionKey,\n plaintext : Convert.object(portableDid).toUint8Array(),\n protectedHeader : didJweProtectedHeader,\n crypto : this.crypto,\n keyManager : new LocalKeyManager()\n });\n\n // Store the compact JWE in the data store.\n await this._store.set('did', didJwe);\n\n /**\n * STEP 7: Set the vault CEK (effectively unlocking the vault), set the status to initialized,\n * and return the mnemonic used to generate the vault key.\n */\n\n this._contentEncryptionKey = contentEncryptionKey;\n\n await this.setStatus({ initialized: true });\n\n // Return the recovery phrase in case it was generated so that it can be displayed to the user\n // for safekeeping.\n return recoveryPhrase;\n }\n\n /**\n * Determines whether the vault has been initialized.\n *\n * This method checks the vault's current status to determine if it has been\n * initialized. Initialization is a prerequisite for most operations on the vault,\n * ensuring that it is ready for use.\n *\n * @example\n * ```ts\n * const isInitialized = await identityVault.isInitialized();\n * console.log('Is the vault initialized?', isInitialized);\n * ```\n *\n * @returns A promise that resolves to `true` if the vault has been initialized, otherwise `false`.\n */\n public async isInitialized(): Promise<boolean> {\n return this.getStatus().then(({ initialized }) => initialized);\n }\n\n /**\n * Checks if the vault is currently locked.\n *\n * This method assesses the vault's current state to determine if it is locked.\n * A locked vault restricts access to its contents, requiring the correct password\n * to unlock and access the stored identity data. The vault must be unlocked to\n * perform operations that access or modify its contents.\n *\n * @example\n * ```ts\n * const isLocked = await identityVault.isLocked();\n * console.log('Is the vault locked?', isLocked);\n * ```\n *\n * @returns `true` if the vault is locked, otherwise `false`.\n */\n public isLocked(): boolean {\n return !this._contentEncryptionKey;\n }\n\n /**\n * Locks the `HdIdentityVault`, securing its contents by clearing the in-memory encryption key.\n *\n * This method ensures that the vault's sensitive data cannot be accessed without unlocking the\n * vault again with the correct password. It's an essential security feature for safeguarding\n * the vault's contents against unauthorized access.\n *\n * @example\n * ```ts\n * const identityVault = new HdIdentityVault();\n * await identityVault.lock();\n * console.log('Vault is now locked.');\n * ```\n * @throws An error if the identity vault has not been initialized.\n * @returns A promise that resolves when the vault is successfully locked.\n */\n public async lock(): Promise<void> {\n // Verify the identity vault has already been initialized.\n if (await this.isInitialized() === false) {\n throw new Error(`HdIdentityVault: Lock operation failed. Vault has not been initialized.`);\n }\n\n // Clear the vault content encryption key (CEK), effectively locking the vault.\n if (this._contentEncryptionKey) this._contentEncryptionKey.k = '';\n this._contentEncryptionKey = undefined;\n }\n\n /**\n * Restores the vault's data from a backup object, decrypting and reinitializing the vault's\n * content with the provided backup data.\n *\n * This operation is crucial for data recovery scenarios, allowing users to regain access to their\n * encrypted data using a previously saved backup and their password.\n *\n * @example\n * ```ts\n * const identityVault = new HdIdentityVault();\n * await identityVault.initialize({ password: 'your-secure-phrase' });\n * // Create a backup of the vault's contents.\n * const backup = await identityVault.backup();\n * // Restore the vault with the same password.\n * await identityVault.restore({ backup: backup, password: 'your-secure-phrase' });\n * console.log('Vault restored successfully.');\n * ```\n *\n * @param params - The parameters required for the restore operation.\n * @param params.backup - The backup object containing the encrypted vault data.\n * @param params.password - The password used to encrypt the backup, necessary for decryption.\n * @returns A promise that resolves when the vault has been successfully restored.\n * @throws An error if the backup object is invalid or if the password is incorrect.\n */\n public async restore({ backup, password }: {\n backup: IdentityVaultBackup;\n password: string;\n }): Promise<void> {\n // Validate the backup object.\n if (!isIdentityVaultBackup(backup)) {\n throw new Error(`HdIdentityVault: Restore operation failed due to invalid backup object.`);\n }\n\n // Temporarily save the status and contents of the data store while attempting to restore the\n // backup so that they are not lost in case the restore operation fails.\n let previousStatus: IdentityVaultStatus;\n let previousContentEncryptionKey: string;\n let previousDid: string;\n try {\n previousDid = await this.getStoredDid();\n previousContentEncryptionKey = await this.getStoredContentEncryptionKey();\n previousStatus = await this.getStatus();\n } catch {\n throw new Error(\n 'HdIdentityVault: The restore operation cannot proceed because the existing vault ' +\n 'contents are missing or inaccessible. If the problem persists consider re-initializing ' +\n 'the vault and retrying the restore.'\n );\n }\n\n try {\n // Convert the backup data to a JSON object.\n const backupData = Convert.base64Url(backup.data).toObject() as IdentityVaultBackupData;\n\n // Restore the backup to the data store.\n await this._store.set('did', backupData.did);\n await this._store.set('contentEncryptionKey', backupData.contentEncryptionKey);\n await this.setStatus(backupData.status);\n\n // Attempt to unlock the vault with the given `password`.\n await this.unlock({ password });\n\n } catch (error: any) {\n // If the restore operation fails, revert the data store to the status and contents that were\n // saved before the restore operation was attempted.\n await this.setStatus(previousStatus);\n await this._store.set('contentEncryptionKey', previousContentEncryptionKey);\n await this._store.set('did', previousDid);\n\n throw new Error(\n 'HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect ' +\n 'password. Please verify the password is correct for the provided backup and try again.'\n );\n }\n\n // Update the last restore timestamp in the data store.\n await this.setStatus({ lastRestore: new Date().toISOString() });\n }\n\n /**\n * Unlocks the vault by decrypting the stored content encryption key (CEK) using the provided\n * password.\n *\n * This method is essential for accessing the vault's encrypted contents, enabling the decryption\n * of stored data and the execution of further operations requiring the vault to be unlocked.\n *\n * @example\n * ```ts\n * const identityVault = new HdIdentityVault();\n * await identityVault.initialize({ password: 'your-initial-phrase' });\n * // Unlock the vault with the correct password before accessing its contents\n * await identityVault.unlock({ password: 'your-initial-phrase' });\n * console.log('Vault unlocked successfully.');\n * ```\n *\n *\n * @param params - The parameters required for the unlock operation.\n * @param params.password - The password used to encrypt the vault's CEK, necessary for\n * decryption.\n * @returns A promise that resolves when the vault has been successfully unlocked.\n * @throws An error if the vault has not been initialized or if the provided password is\n * incorrect.\n */\n public async unlock({ password }: { password: string }): Promise<void> {\n // Lock the vault.\n await this.lock();\n\n // Retrieve the content encryption key (CEK) record as a compact JWE from the data store.\n const cekJwe = await this.getStoredContentEncryptionKey();\n\n // Decrypt the compact JWE.\n try {\n const { plaintext: contentEncryptionKeyBytes } = await CompactJwe.decrypt({\n jwe : cekJwe,\n key : Convert.string(password).toUint8Array(),\n crypto : this.crypto,\n keyManager : new LocalKeyManager()\n });\n const contentEncryptionKey = Convert.uint8Array(contentEncryptionKeyBytes).toObject() as Jwk;\n\n // Save the content encryption key in memory, thereby unlocking the vault.\n this._contentEncryptionKey = contentEncryptionKey;\n\n } catch (error: any) {\n throw new Error(`HdIdentityVault: Unable to unlock the vault due to an incorrect password.`);\n }\n }\n\n /**\n * Retrieves the Decentralized Identifier (DID) associated with the identity vault from the vault\n * store.\n *\n * This DID is encrypted in compact JWE format and needs to be decrypted after the vault is\n * unlocked. The method is intended to be used internally within the HdIdentityVault class to access\n * the encrypted PortableDid.\n *\n * @returns A promise that resolves to the encrypted DID stored in the vault as a compact JWE.\n * @throws Will throw an error if the DID cannot be retrieved from the vault.\n */\n private async getStoredDid(): Promise<string> {\n // Retrieve the DID record as a compact JWE from the data store.\n const didJwe = await this._store.get('did');\n\n if (!didJwe) {\n throw new Error(\n 'HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the ' +\n 'vault status and if the problem persists consider re-initializing the vault and ' +\n 'restoring the contents from a previous backup.'\n );\n }\n\n return didJwe;\n }\n\n /**\n * Retrieves the encrypted Content Encryption Key (CEK) from the vault's storage.\n *\n * This CEK is used for encrypting and decrypting the vault's contents. It is stored as a\n * compact JWE and should be decrypted with the user's password to be used for further\n * cryptographic operations.\n *\n * @returns A promise that resolves to the stored CEK as a string in compact JWE format.\n * @throws Will throw an error if the CEK cannot be retrieved, indicating potential issues with\n * the vault's integrity or state.\n */\n private async getStoredContentEncryptionKey(): Promise<string> {\n // Retrieve the content encryption key (CEK) record as a compact JWE from the data store.\n const cekJwe = await this._store.get('contentEncryptionKey');\n\n if (!cekJwe) {\n throw new Error(\n 'HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. ' +\n 'Please check the vault status and if the problem persists consider re-initializing the ' +\n 'vault and restoring the contents from a previous backup.'\n );\n }\n\n return cekJwe;\n }\n\n /**\n * Updates the status of the `HdIdentityVault`, reflecting changes in its initialization, lock\n * state, and the timestamps of the last backup and restore operations.\n *\n * This method directly manipulates the internal state stored in the vault's key-value store.\n *\n * @param params - The status properties to be updated.\n * @param params.initialized - Updates the initialization state of the vault.\n * @param params.lastBackup - Updates the timestamp of the last successful backup.\n * @param params.lastRestore - Updates the timestamp of the last successful restore.\n * @returns A promise that resolves to a boolean indicating successful status update.\n * @throws Will throw an error if the status cannot be updated in the key-value store.\n */\n private async setStatus({ initialized, lastBackup, lastRestore }: Partial<IdentityVaultStatus>): Promise<boolean> {\n // Get the current status values from the store, if any.\n let vaultStatus = await this.getStatus();\n\n // Update the status properties with new values specified, if any.\n vaultStatus.initialized = initialized ?? vaultStatus.initialized;\n vaultStatus.lastBackup = lastBackup ?? vaultStatus.lastBackup;\n vaultStatus.lastRestore = lastRestore ?? vaultStatus.lastRestore;\n\n // Write the changes to the store.\n await this._store.set('vaultStatus', JSON.stringify(vaultStatus));\n\n return true;\n }\n}", "import type {\n Jwk,\n Cipher,\n Signer,\n KeyWrapper,\n SignParams,\n AesGcmParams,\n KeyGenerator,\n VerifyParams,\n KeyIdentifier,\n KmsSignParams,\n KmsDigestParams,\n KmsVerifyParams,\n GetPublicKeyParams,\n KmsExportKeyParams,\n KmsGetKeyUriParams,\n KmsImportKeyParams,\n KmsGenerateKeyParams,\n KmsGetPublicKeyParams,\n AsymmetricKeyGenerator,\n} from '@enbox/crypto';\n\nimport {\n isPrivateJwk,\n Sha2Algorithm,\n EcdsaAlgorithm,\n EdDsaAlgorithm,\n AesGcmAlgorithm,\n CryptoAlgorithm,\n KEY_URI_PREFIX_JWK,\n computeJwkThumbprint,\n} from '@enbox/crypto';\n\nimport type { AgentDataStore } from './store-data.js';\nimport type { Web5PlatformAgent } from './types/agent.js';\nimport type { AgentKeyManager } from './types/key-manager.js';\nimport type { InferType } from './prototyping/common/type-utils.js';\nimport type { CipherParams, UnwrapKeyParams, WrapKeyParams } from './prototyping/crypto/types/params-direct.js';\nimport type { KmsCipherParams, KmsUnwrapKeyParams, KmsWrapKeyParams } from './prototyping/crypto/types/params-kms.js';\n\nimport { InMemoryKeyStore } from './store-key.js';\nimport { AesKwAlgorithm } from './prototyping/crypto/algorithms/aes-kw.js';\nimport { CryptoError, CryptoErrorCode } from './prototyping/crypto/crypto-error.js';\n\n/**\n * `supportedAlgorithms` is an object mapping algorithm names to their respective implementations\n * Each entry in this map specifies the algorithm name and its associated properties, including the\n * implementation class and any relevant names or identifiers for the algorithm. This structure\n * allows for easy retrieval and instantiation of algorithm implementations based on the algorithm\n * name or key specification. It facilitates the support of multiple algorithms within the\n * `LocalKeyManager` class.\n */\nconst supportedAlgorithms = {\n 'AES-GCM': {\n implementation : AesGcmAlgorithm,\n names : ['A128GCM', 'A192GCM', 'A256GCM'] as const,\n },\n 'AES-KW': {\n implementation : AesKwAlgorithm,\n names : ['A128KW', 'A192KW', 'A256KW'] as const,\n },\n 'Ed25519': {\n implementation : EdDsaAlgorithm,\n names : ['Ed25519'] as const,\n },\n 'secp256k1': {\n implementation : EcdsaAlgorithm,\n names : ['ES256K', 'secp256k1'] as const,\n },\n 'secp256r1': {\n implementation : EcdsaAlgorithm,\n names : ['ES256', 'secp256r1'] as const,\n },\n 'SHA-256': {\n implementation : Sha2Algorithm,\n names : ['SHA-256'] as const\n }\n} satisfies {\n [key: string]: {\n implementation : typeof CryptoAlgorithm;\n names : readonly string[];\n }\n};\n\n/* Helper type for `supportedAlgorithms`. */\ntype SupportedAlgorithm = keyof typeof supportedAlgorithms;\n\n/* Helper type for `supportedAlgorithms` implementations. */\ntype AlgorithmConstructor = typeof supportedAlgorithms[SupportedAlgorithm]['implementation'];\n\n/* Commented out but retaining in case it ends up being useful. */\n// type AlgorithmNames = typeof supportedAlgorithms[SupportedAlgorithm]['names'][number];\n\n/* Helper type for supported key generator algorithms. */\ntype SupportedKeyGeneratorAlgorithm =\n | 'Ed25519' // Edwards Curve Digital Signature Algorithm (EdDSA)\n | 'secp256k1' | 'ES256K' | 'secp256r1' | 'ES256' // Elliptic Curve Digital Signature Algorithm (ECDSA)\n | 'A128GCM' | 'A192GCM' | 'A256GCM' // AES GCM with a 128-bit, 192-bit, or 256-bit key\n | 'A128KW' | 'A192KW' | 'A256KW'; // AES Key Wrap with a 128-bit, 192-bit, or 256-bit key\n\n/**\n * The `LocalKmsParams` interface specifies the parameters for initializing an instance of\n * {@link LocalKeyManager}. It allows the optional inclusion of a {@link AgentDataStore} instance\n * for key management. If not provided, a default {@link InMemoryKeyStore} instance will be used for\n * storing keys. Note that the {@link InMemoryKeyStore} is not persistent and will be cleared when\n * the application exits.\n */\nexport type LocalKmsParams = {\n agent?: Web5PlatformAgent;\n\n /**\n * An optional property to specify a custom {@link AgentDataStore} instance for key management. If\n * not provided, {@link LocalKeyManager} uses a default {@link InMemoryKeyStore} instance. This\n * store is responsible for managing cryptographic keys, allowing them to be retrieved, stored,\n * and managed during cryptographic operations.\n */\n keyStore?: AgentDataStore<Jwk>;\n};\n\n/**\n * The `LocalKmsGenerateKeyParams` interface defines the algorithm-specific parameters that\n * should be passed into the {@link LocalKeyManager.generateKey | `LocalKeyManager.generateKey()`}\n * method when generating a key in the local KMS.\n */\nexport interface LocalKmsGenerateKeyParams extends KmsGenerateKeyParams {\n /**\n * A string defining the type of key to generate.\n */\n algorithm: InferType<SupportedKeyGeneratorAlgorithm>\n}\n\n/**\n * The `LocalKmsUnwrapKeyParams` interface defines the algorithm-specific parameters that\n * should be passed into the {@link LocalKeyManager.wrapKey} method when wrapping a key using a\n * key stored in the local KMS to encrypt the key material.\n */\nexport interface LocalKmsUnwrapKeyParams extends KmsUnwrapKeyParams {\n /**\n * A string defining the type of wrapped key. The value must be one of the following:\n * - `\"A128GCM\"`: AES GCM using a 128-bit key.\n * - `\"A192GCM\"`: AES GCM using a 192-bit key.\n * - `\"A256GCM\"`: AES GCM using a 256-bit key.\n * - `\"A128KW\"`: AES Key Wrap using a 128-bit key.\n * - `\"A192KW\"`: AES Key Wrap using a 192-bit key.\n * - `\"A256KW\"`: AES Key Wrap using a 256-bit key.\n */\n wrappedKeyAlgorithm: 'A128GCM' | 'A192GCM' | 'A256GCM' | 'A128KW' | 'A192KW' | 'A256KW';\n}\n\nexport class LocalKeyManager implements AgentKeyManager {\n /**\n * Holds the instance of a `Web5PlatformAgent` that represents the current execution context for\n * the `LocalKeyManager`. This agent is used to interact with other Web5 agent components. It's\n * vital to ensure this instance is set to correctly contextualize operations within the broader\n * Web5 Agent framework.\n */\n private _agent?: Web5PlatformAgent;\n\n /**\n * A private map that stores instances of cryptographic algorithm implementations. Each key in\n * this map is an `AlgorithmConstructor`, and its corresponding value is an instance of a class\n * that implements a specific cryptographic algorithm. This map is used to cache and reuse\n * instances for performance optimization, ensuring that each algorithm is instantiated only once.\n */\n private _algorithmInstances: Map<AlgorithmConstructor, InstanceType<typeof CryptoAlgorithm>> = new Map();\n\n /**\n * The `_keyStore` private variable in `LocalKeyManager` is a {@link AgentDataStore} instance used\n * for storing and managing cryptographic keys. It allows the `LocalKeyManager` class to save,\n * retrieve, and handle keys efficiently within the local Key Management System (KMS) context.\n * This variable can be configured to use different storage backends, like in-memory storage or\n * persistent storage, providing flexibility in key management according to the application's\n * requirements.\n */\n private _keyStore: AgentDataStore<Jwk>;\n\n constructor({ agent, keyStore }: LocalKmsParams = {}) {\n this._agent = agent;\n\n this._keyStore = keyStore ?? new InMemoryKeyStore();\n }\n\n /**\n * Retrieves the `Web5PlatformAgent` execution context.\n *\n * @returns The `Web5PlatformAgent` instance that represents the current execution context.\n * @throws Will throw an error if the `agent` instance property is undefined.\n */\n get agent(): Web5PlatformAgent {\n if (this._agent === undefined) {\n throw new Error('LocalKeyManager: Unable to determine agent execution context.');\n }\n\n return this._agent;\n }\n\n set agent(agent: Web5PlatformAgent) {\n this._agent = agent;\n }\n\n public async decrypt({ keyUri, ...params }:\n KmsCipherParams & AesGcmParams\n ): Promise<Uint8Array> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the cipher algorithm based on the algorithm name.\n const cipher = this.getAlgorithm({ algorithm }) as Cipher<CipherParams, CipherParams>;\n\n // Encrypt the data.\n const ciphertext = await cipher.decrypt({ key: privateKey, ...params });\n\n return ciphertext;\n }\n\n digest(_params: KmsDigestParams): Promise<Uint8Array> {\n throw new Error('Method not implemented.');\n }\n\n public async encrypt({ keyUri, ...params }:\n KmsCipherParams & AesGcmParams\n ): Promise<Uint8Array> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the cipher algorithm based on the algorithm name.\n const cipher = this.getAlgorithm({ algorithm }) as Cipher<CipherParams, CipherParams>;\n\n // Encrypt the data.\n const ciphertext = await cipher.encrypt({ key: privateKey, ...params });\n\n return ciphertext;\n }\n\n /**\n * Exports a private key identified by the provided key URI from the local KMS.\n *\n * @remarks\n * This method retrieves the key from the key store and returns it. It is primarily used\n * for extracting keys for backup or transfer purposes.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const privateKey = await keyManager.exportKey({ keyUri });\n * ```\n *\n * @param params - Parameters for exporting the key.\n * @param params.keyUri - The key URI identifying the key to export.\n *\n * @returns A Promise resolving to the JWK representation of the exported key.\n */\n public async exportKey({ keyUri }:\n KmsExportKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n return privateKey;\n }\n\n /**\n * Generates a new cryptographic key in the local KMS with the specified algorithm and returns a\n * unique key URI which can be used to reference the key in subsequent operations.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * console.log(keyUri); // Outputs the key URI\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation, defined in `SupportedAlgorithm`.\n *\n * @returns A Promise that resolves to the key URI, a unique identifier for the generated key.\n */\n public async generateKey({ algorithm: algorithmIdentifier }:\n LocalKmsGenerateKeyParams\n ): Promise<KeyIdentifier> {\n // Determine the algorithm name based on the given algorithm identifier.\n const algorithm = this.getAlgorithmName({ key: { alg: algorithmIdentifier } });\n\n // Get the key generator implementation based on the algorithm.\n const keyGenerator = this.getAlgorithm({ algorithm }) as KeyGenerator<LocalKmsGenerateKeyParams, Jwk>;\n\n // Generate the key.\n const privateKey = await keyGenerator.generateKey({ algorithm: algorithmIdentifier });\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n privateKey.kid ??= await computeJwkThumbprint({ jwk: privateKey });\n\n // Compute the key URI for the key.\n const keyUri = await this.getKeyUri({ key: privateKey });\n\n // Store the key in the key store.\n await this._keyStore.set({\n id : keyUri,\n data : privateKey,\n agent : this.agent,\n preventDuplicates : false,\n useCache : true\n });\n\n return keyUri;\n }\n\n /**\n * Computes the Key URI for a given public JWK (JSON Web Key).\n *\n * @remarks\n * This method generates a {@link https://datatracker.ietf.org/doc/html/rfc3986 | URI}\n * (Uniform Resource Identifier) for the given JWK, which uniquely identifies the key across all\n * `CryptoApi` implementations. The key URI is constructed by appending the\n * {@link https://datatracker.ietf.org/doc/html/rfc7638 | JWK thumbprint} to the prefix\n * `urn:jwk:`. The JWK thumbprint is deterministically computed from the JWK and is consistent\n * regardless of property order or optional property inclusion in the JWK. This ensures that the\n * same key material represented as a JWK will always yield the same thumbprint, and therefore,\n * the same key URI.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const publicKey = await keyManager.getPublicKey({ keyUri });\n * const keyUriFromPublicKey = await keyManager.getKeyUri({ key: publicKey });\n * console.log(keyUri === keyUriFromPublicKey); // Outputs `true`\n * ```\n *\n * @param params - The parameters for getting the key URI.\n * @param params.key - The JWK for which to compute the key URI.\n *\n * @returns A Promise that resolves to the key URI as a string.\n */\n public async getKeyUri({ key }:\n KmsGetKeyUriParams\n ): Promise<KeyIdentifier> {\n // Compute the JWK thumbprint.\n const jwkThumbprint = await computeJwkThumbprint({ jwk: key });\n\n // Construct the key URI by appending the JWK thumbprint to the key URI prefix.\n const keyUri = `${KEY_URI_PREFIX_JWK}${jwkThumbprint}`;\n\n return keyUri;\n }\n\n /**\n * Retrieves the public key associated with a previously generated private key, identified by\n * the provided key URI.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const publicKey = await keyManager.getPublicKey({ keyUri });\n * ```\n *\n * @param params - The parameters for retrieving the public key.\n * @param params.keyUri - The key URI of the private key to retrieve the public key for.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ keyUri }:\n KmsGetPublicKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the key generator based on the algorithm name.\n const keyGenerator = this.getAlgorithm({ algorithm }) as AsymmetricKeyGenerator<LocalKmsGenerateKeyParams, Jwk, GetPublicKeyParams>;\n\n // Get the public key properties from the private JWK.\n const publicKey = await keyGenerator.getPublicKey({ key: privateKey });\n\n return publicKey;\n }\n\n /**\n * Imports a private key into the local KMS.\n *\n * @remarks\n * This method stores the provided JWK in the key store, making it available for subsequent\n * cryptographic operations. It is particularly useful for initializing the KMS with pre-existing\n * keys or for restoring keys from backups.\n *\n * Note that, if defined, the `kid` (key ID) property of the JWK is used as the key URI for the\n * imported key. If the `kid` property is not provided, the key URI is computed from the JWK\n * thumbprint of the key.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const privateKey = { ... } // A private key in JWK format\n * const keyUri = await keyManager.importKey({ key: privateKey });\n * ```\n *\n * @param params - Parameters for importing the key.\n * @param params.key - The private key to import to in JWK format.\n *\n * @returns A Promise resolving to the key URI, uniquely identifying the imported key.\n */\n public async importKey({ key }:\n KmsImportKeyParams\n ): Promise<KeyIdentifier> {\n if (!isPrivateJwk(key)) throw new TypeError('Invalid key provided. Must be a private key in JWK format.');\n\n // Make a deep copy of the key to avoid mutating the original.\n const privateKey = structuredClone(key);\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n privateKey.kid ??= await computeJwkThumbprint({ jwk: privateKey });\n\n // Compute the key URI for the key.\n const keyUri = await this.getKeyUri({ key: privateKey });\n\n // Store the key in the key store.\n await this._keyStore.set({\n id : keyUri,\n data : privateKey,\n agent : this.agent,\n preventDuplicates : true,\n useCache : true\n });\n\n return keyUri;\n }\n\n /**\n * Signs the provided data using the private key identified by the provided key URI.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `alg` and/or `crv` properties of the\n * private key identified by the provided key URI to sign the provided data. The signature can\n * later be verified by parties with access to the corresponding public key, ensuring that the\n * data has not been tampered with and was indeed signed by the holder of the private key.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const data = new TextEncoder().encode('Message to sign');\n * const signature = await keyManager.sign({ keyUri, data });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.keyUri - The key URI of the private key to use for signing.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ keyUri, data }:\n KmsSignParams\n ): Promise<Uint8Array> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the signature algorithm based on the algorithm name.\n const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n // Sign the data.\n const signature = signer.sign({ data, key: privateKey });\n\n return signature;\n }\n\n public async unwrapKey({ wrappedKeyBytes, wrappedKeyAlgorithm, decryptionKeyUri }:\n LocalKmsUnwrapKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const decryptionKey = await this.getPrivateKey({ keyUri: decryptionKeyUri });\n\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: decryptionKey });\n\n // Get the key wrapping algorithm based on the algorithm name.\n const keyWrapper = this.getAlgorithm({ algorithm }) as KeyWrapper<WrapKeyParams, UnwrapKeyParams>;\n\n // Decrypt the key.\n const unwrappedKey = await keyWrapper.unwrapKey({ wrappedKeyBytes, wrappedKeyAlgorithm, decryptionKey });\n\n return unwrappedKey;\n }\n\n /**\n * Verifies a digital signature associated the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `alg` and/or `crv` properties of the\n * provided key to check the validity of a digital signature against the original data. It\n * confirms whether the signature was created by the holder of the corresponding private key and\n * that the data has not been tampered with.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const data = new TextEncoder().encode('Message to sign');\n * const signature = await keyManager.sign({ keyUri, data });\n * const isSignatureValid = await keyManager.verify({ keyUri, data, signature });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n KmsVerifyParams\n ): Promise<boolean> {\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key });\n\n // Get the signature algorithm based on the algorithm name.\n const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n // Verify the signature.\n const isSignatureValid = signer.verify({ key, signature, data });\n\n return isSignatureValid;\n }\n\n public async wrapKey({ unwrappedKey, encryptionKeyUri }:\n KmsWrapKeyParams\n ): Promise<Uint8Array> {\n // Get the private key from the key store.\n const encryptionKey = await this.getPrivateKey({ keyUri: encryptionKeyUri });\n\n // Determine the algorithm name based on the JWK's `alg` property.\n const algorithm = this.getAlgorithmName({ key: encryptionKey });\n\n // Get the key wrapping algorithm based on the algorithm name.\n const keyWrapper = this.getAlgorithm({ algorithm }) as KeyWrapper<WrapKeyParams, UnwrapKeyParams>;\n\n // Encrypt the key.\n const wrappedKeyBytes = await keyWrapper.wrapKey({ unwrappedKey, encryptionKey });\n\n return wrappedKeyBytes;\n }\n\n public async deleteKey({ keyUri }:{ keyUri: KeyIdentifier }): Promise<void> {\n // Get the private key from the key store.\n const jwk = await this._keyStore.get({ id: keyUri, agent: this.agent, useCache: true });\n if (!jwk) {\n throw new Error(`Key not found: ${keyUri}`);\n }\n\n await this._keyStore.delete({ id: keyUri, agent: this.agent });\n }\n\n /**\n * Retrieves an algorithm implementation instance based on the provided algorithm name.\n *\n * @remarks\n * This method checks if the requested algorithm is supported and returns a cached instance\n * if available. If an instance does not exist, it creates and caches a new one. This approach\n * optimizes performance by reusing algorithm instances across cryptographic operations.\n *\n * @example\n * ```ts\n * const signer = this.getAlgorithm({ algorithm: 'Ed25519' });\n * ```\n *\n * @param params - The parameters for retrieving the algorithm implementation.\n * @param params.algorithm - The name of the algorithm to retrieve.\n *\n * @returns An instance of the requested algorithm implementation.\n *\n * @throws Error if the requested algorithm is not supported.\n */\n private getAlgorithm({ algorithm }: {\n algorithm: SupportedAlgorithm;\n }): InstanceType<typeof CryptoAlgorithm> {\n // Check if algorithm is supported.\n const AlgorithmImplementation = supportedAlgorithms[algorithm]?.['implementation'];\n if (!AlgorithmImplementation) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Algorithm not supported: ${algorithm}`);\n }\n\n // Check if instance already exists for the `AlgorithmImplementation`.\n if (!this._algorithmInstances.has(AlgorithmImplementation)) {\n // If not, create a new instance and store it in the cache\n this._algorithmInstances.set(AlgorithmImplementation, new AlgorithmImplementation());\n }\n\n // Return the cached instance\n return this._algorithmInstances.get(AlgorithmImplementation)!;\n }\n\n /**\n * Determines the algorithm name based on the key's properties.\n *\n * @remarks\n * This method facilitates the identification of the correct algorithm for cryptographic\n * operations based on the `alg` or `crv` properties of a {@link Jwk | JWK}.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // Public key in JWK format\n * const algorithm = this.getAlgorithmName({ key: publicKey });\n * ```\n *\n * @param params - The parameters for determining the algorithm name.\n * @param params.key - A JWK containing the `alg` or `crv` properties.\n *\n * @returns The algorithm name associated with the key.\n *\n * @throws Error if the algorithm name cannot be determined from the provided input.\n */\n private getAlgorithmName({ key }: {\n key: { alg?: string, crv?: string };\n }): SupportedAlgorithm {\n const algProperty = key.alg;\n const crvProperty = key.crv;\n\n for (const algorithmIdentifier of Object.keys(supportedAlgorithms) as SupportedAlgorithm[]) {\n const algorithmNames = supportedAlgorithms[algorithmIdentifier].names as readonly string[];\n if (algProperty && algorithmNames.includes(algProperty)) {\n return algorithmIdentifier;\n } else if (crvProperty && algorithmNames.includes(crvProperty)) {\n return algorithmIdentifier;\n }\n }\n\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported,\n `Algorithm not supported based on provided input: alg=${algProperty}, crv=${crvProperty}. ` +\n 'Please check the documentation for the list of supported algorithms.'\n );\n }\n\n /**\n * Retrieves a private key from the key store based on the provided key URI.\n *\n * @example\n * ```ts\n * const privateKey = this.getPrivateKey({ keyUri: 'urn:jwk:...' });\n * ```\n *\n * @param params - Parameters for retrieving the private key.\n * @param params.keyUri - The key URI identifying the private key to retrieve.\n *\n * @returns A Promise resolving to the JWK representation of the private key.\n *\n * @throws Error if the key is not found in the key store.\n */\n private async getPrivateKey({ keyUri }: {\n keyUri: KeyIdentifier;\n }): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this._keyStore.get({ id: keyUri, agent: this.agent, useCache: true });\n\n if (!privateKey) {\n throw new Error(`Key not found: ${keyUri}`);\n }\n\n return privateKey;\n }\n}", "import type { Jwk } from '@enbox/crypto';\n\nimport { KEY_URI_PREFIX_JWK, isPrivateJwk } from '@enbox/crypto';\nimport { Convert } from '@enbox/common';\n\nimport type { Web5PlatformAgent } from './types/agent.js';\n\nimport { DwnInterface } from './types/dwn.js';\nimport { JwkProtocolDefinition } from './store-data-protocols.js';\nimport { TENANT_SEPARATOR } from './utils-internal.js';\nimport { AgentDataStore, DataStoreDeleteParams, DataStoreGetParams, DataStoreListParams, DataStoreSetParams, DwnDataStore, InMemoryDataStore } from './store-data.js';\n\nexport class DwnKeyStore extends DwnDataStore<Jwk> implements AgentDataStore<Jwk> {\n protected name = 'DwnKeyStore';\n\n protected _recordProtocolDefinition = JwkProtocolDefinition;\n\n /**\n * Properties to use when writing and querying Private Key records with the DWN store.\n */\n protected _recordProperties = {\n dataFormat : 'application/json',\n protocol : this._recordProtocolDefinition.protocol,\n protocolPath : 'privateJwk',\n schema : this._recordProtocolDefinition.types.privateJwk.schema,\n };\n\n public async delete(params: DataStoreDeleteParams): Promise<boolean> {\n return await super.delete(params);\n }\n\n public async get(params: DataStoreGetParams): Promise<Jwk | undefined> {\n return await super.get(params);\n }\n\n public async set(params: DataStoreSetParams<Jwk>): Promise<void> {\n await super.set(params);\n }\n\n public async list(params: DataStoreListParams): Promise<Jwk[]> {\n return await super.list(params);\n }\n\n protected async getAllRecords({ agent, tenantDid }: {\n agent: Web5PlatformAgent;\n tenantDid: string;\n }): Promise<Jwk[]> {\n // Clear the index since it will be rebuilt from the query results.\n this._index.clear();\n\n // Query the DWN for all stored Jwk objects.\n const { reply: queryReply } = await agent.dwn.processRequest({\n author : tenantDid,\n target : tenantDid,\n messageType : DwnInterface.RecordsQuery,\n messageParams : { filter: { ...this._recordProperties } }\n });\n\n // Loop through all of the stored Jwk records and accumulate the objects.\n let storedKeys: Jwk[] = [];\n for (const record of queryReply.entries ?? []) {\n // All Jwk records are expected to be small enough such that the data is returned\n // with the query results. If a record is returned without `encodedData` this is unexpected so\n // throw an error.\n if (!record.encodedData) {\n throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);\n }\n\n const storedKey = Convert.base64Url(record.encodedData).toObject() as Jwk;\n if (isPrivateJwk(storedKey)) {\n // Update the index with the matching record ID.\n const indexKey = `${tenantDid}${TENANT_SEPARATOR}${KEY_URI_PREFIX_JWK}${storedKey.kid}`;\n this._index.set(indexKey, record.recordId);\n\n // Add the stored key to the cache.\n this._cache.set(record.recordId, storedKey);\n\n storedKeys.push(storedKey);\n }\n }\n\n return storedKeys;\n }\n}\n\nexport class InMemoryKeyStore extends InMemoryDataStore<Jwk> implements AgentDataStore<Jwk> {\n protected name = 'InMemoryKeyStore';\n\n public async delete(params: DataStoreDeleteParams): Promise<boolean> {\n return await super.delete(params);\n }\n\n public async get(params: DataStoreGetParams): Promise<Jwk | undefined> {\n return await super.get(params);\n }\n\n public async list(params: DataStoreListParams): Promise<Jwk[]> {\n return await super.list(params);\n }\n\n public async set(params: DataStoreSetParams<Jwk>): Promise<void> {\n return await super.set(params);\n }\n}", "import type { Jwk, KeyIdentifier } from '@enbox/crypto';\n\nimport { LocalKeyManager } from '@enbox/crypto';\n\nimport type { CryptoApi } from '../types/crypto-api.js';\nimport type { KeyManager } from '../types/key-manager.js';\nimport type { JweDecryptOptions, JweEncryptOptions, JweHeaderParams } from './jwe.js';\n\nimport { isValidJweHeader } from './jwe.js';\nimport { FlattenedJwe } from './jwe-flattened.js';\nimport { AgentCryptoApi } from '../../../crypto-api.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * Parameters required for decrypting a JWE in Compact Serialization format.\n *\n * @typeParam TKeyManager - The Key Manager used to manage cryptographic keys.\n * @typeParam TCrypto - The Crypto API used to perform cryptographic operations.\n */\nexport interface CompactJweDecryptParams<TKeyManager, TCrypto> {\n /** The JWE string in Compact Serialization format. */\n jwe: string;\n\n /**\n * The decryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n * or raw key material represented as a byte array.\n */\n key: KeyIdentifier | Jwk | Uint8Array;\n\n /** Key Manager instance\u00DF responsible for managing cryptographic keys. */\n keyManager?: TKeyManager;\n\n /** Crypto API instance that provides the necessary cryptographic operations. */\n crypto?: TCrypto;\n\n /** {@inheritDoc JweDecryptOptions} */\n options?: JweDecryptOptions;\n}\n\n/**\n * Result of decrypting a JWE in Compact Serialization format.\n */\nexport interface CompactJweDecryptResult {\n /** Decrypted plaintext as a byte array. */\n plaintext: Uint8Array;\n\n /** The protected header of the JWE. */\n protectedHeader: JweHeaderParams;\n}\n\n/**\n * Parameters required for encrypting data into a JWE in Compact Serialization format.\n *\n * @typeParam TKeyManager - The Key Manager used to manage cryptographic keys.\n * @typeParam TCrypto - The Crypto API used to perform cryptographic operations.\n */\nexport interface CompactJweEncryptParams<TKeyManager, TCrypto> {\n /** The plaintext data to be encrypted as a byte array. */\n plaintext: Uint8Array;\n\n /** JWE Protected Header containing encryption algorithm details. */\n protectedHeader: JweHeaderParams;\n\n /**\n * The encryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n * or raw key material represented as a byte array.\n */\n key: KeyIdentifier | Jwk | Uint8Array;\n\n /** Key Manager instance\u00DF responsible for managing cryptographic keys. */\n keyManager?: TKeyManager;\n\n /** Crypto API instance that provides the necessary cryptographic operations. */\n crypto?: TCrypto;\n\n /** {@inheritDoc JweEncryptOptions} */\n options?: JweEncryptOptions;\n}\n\n/**\n * The `CompactJwe` class facilitates encryption and decryption processes using the JSON Web\n * Encryption (JWE) Compact Serialization format. This class adheres to the specifications\n * outlined in {@link https://datatracker.ietf.org/doc/html/rfc7516 | RFC 7516}, enabling secure\n * data encapsulation through various cryptographic algorithms.\n *\n * Compact Serialization is a space-efficient representation of JWE, suitable for contexts\n * where verbose data structures are impractical, such as HTTP headers. It provides mechanisms to\n * encrypt content and protect its integrity with authenticated encryption, ensuring\n * confidentiality, authenticity, and non-repudiation.\n *\n * This class supports the following operations:\n * - Decrypting data from a compact serialized JWE string.\n * - Encrypting data and producing a compact serialized JWE string.\n *\n * Usage involves specifying the cryptographic details, such as keys and algorithms, and the class\n * handles the complexities of the JWE processing, including parsing, validating, and applying the\n * cryptographic operations defined in the JWE specification.\n *\n * @example\n * ```ts\n * // Example usage of encrypt method\n * const plaintext = new TextEncoder().encode(\"Secret Message\");\n * const key = { kty: \"oct\", k: \"your-secret-key\" }; // Example symmetric key\n * const protectedHeader = { alg: \"dir\", enc: \"A256GCM\" };\n * const encryptedJweString = await CompactJwe.encrypt({\n * plaintext,\n * protectedHeader,\n * key,\n * });\n * console.log(encryptedJweString); // Outputs the JWE string in Compact Serialization format\n * ```\n *\n * @example\n * ```ts\n * // Example usage of decrypt method\n * const jweString = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"; // A JWE in Compact Serialization\n * const decryptionKey = { kty: \"oct\", k: \"your-secret-key\" }; // The key must match the one used for encryption\n * const { plaintext, protectedHeader } = await CompactJwe.decrypt({\n * jwe: jweString,\n * key: decryptionKey,\n * });\n * console.log(new TextDecoder().decode(plaintext)); // Outputs the decrypted message\n * ```\n */\nexport class CompactJwe {\n /**\n * Decrypts a JWE string in Compact Serialization format, extracting the plaintext and\n * reconstructing the JWE Protected Header.\n *\n * This method parses the compact JWE, validates its structure, and applies the appropriate\n * decryption algorithm as specified in the JWE Protected Header. It returns the decrypted\n * plaintext along with the reconstructed protected header, ensuring the data's authenticity\n * and integrity.\n *\n * @param params - The decryption parameters including the JWE string, cryptographic key, and\n * optional instances of Key Manager and Crypto API.\n * @returns A promise resolving to the decrypted content and the JWE Protected Header.\n * @throws {@link CryptoError} if the JWE format is invalid or decryption fails.\n */\n public static async decrypt<\n TKeyManager extends KeyManager | undefined = KeyManager,\n TCrypto extends CryptoApi | undefined = CryptoApi\n >({\n jwe,\n key,\n keyManager = new LocalKeyManager(),\n crypto = new AgentCryptoApi(),\n options = {}\n }: CompactJweDecryptParams<TKeyManager, TCrypto>\n ): Promise<CompactJweDecryptResult> {\n if (typeof jwe !== 'string') {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Invalid JWE format. JWE must be a string.');\n }\n\n // Split the JWE into its constituent parts.\n const {\n 0: protectedHeader,\n 1: encryptedKey,\n 2: initializationVector,\n 3: ciphertext,\n 4: authenticationTag,\n length,\n } = jwe.split('.');\n\n // Ensure that the JWE has the required number of parts.\n if (length !== 5) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Invalid JWE format. JWE must have 5 parts.');\n }\n\n // Decrypt the JWE using the provided Key URI.\n const flattenedJwe = await FlattenedJwe.decrypt({\n jwe: {\n ciphertext,\n encrypted_key : encryptedKey || undefined,\n iv : initializationVector || undefined,\n protected : protectedHeader,\n tag : authenticationTag || undefined,\n },\n key,\n keyManager,\n crypto,\n options\n });\n\n if (!isValidJweHeader(flattenedJwe.protectedHeader)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Decrypt operation failed due to missing or malformed JWE Protected Header');\n }\n\n return { plaintext: flattenedJwe.plaintext, protectedHeader: flattenedJwe.protectedHeader };\n }\n\n /**\n * Encrypts plaintext to a JWE string in Compact Serialization format, encapsulating the content\n * with the specified cryptographic protections.\n *\n * It constructs the JWE by encrypting the plaintext, then serializing the output to the\n * compact format, which includes concatenating various components like the protected header,\n * encrypted key, initialization vector, ciphertext, and authentication tag.\n *\n * @param params - The encryption parameters, including plaintext, JWE Protected Header,\n * cryptographic key, and optional Key Manager and Crypto API instances.\n * @returns A promise that resolves to a string representing the JWE in Compact Serialization\n * format.\n * @throws {@link CryptoError} if encryption fails or the input parameters are invalid.\n */\n public static async encrypt<\n TKeyManager extends KeyManager | undefined = KeyManager,\n TCrypto extends CryptoApi | undefined = CryptoApi\n >({\n plaintext,\n protectedHeader,\n key,\n keyManager = new LocalKeyManager(),\n crypto = new AgentCryptoApi(),\n options = {}\n }: CompactJweEncryptParams<TKeyManager, TCrypto>\n ): Promise<string> {\n const jwe = await FlattenedJwe.encrypt({ plaintext, protectedHeader, key, keyManager, crypto, options });\n\n // Create the Compact Serialization, which is the string BASE64URL(UTF8(JWE Protected Header))\n // || '.' || BASE64URL(JWE Encrypted Key) || '.' || BASE64URL(JWE Initialization Vector)\n // || '.' || BASE64URL(JWE Ciphertext) || '.' || BASE64URL(JWE Authentication Tag).\n return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');\n }\n}", "import type { JoseHeaderParams, Jwk, KeyIdentifier } from '@enbox/crypto';\n\nimport { Convert } from '@enbox/common';\n\nimport type { CryptoApi } from '../types/crypto-api.js';\nimport type { KeyManager } from '../types/key-manager.js';\n\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * Specifies options for decrypting a JWE, allowing the caller to define constraints on the JWE\n * decryption process, particularly regarding the algorithms used.\n *\n * These options ensure that only expected and permitted algorithms are utilized during the\n * decryption, enhancing security by preventing unexpected algorithm usage.\n */\nexport interface JweDecryptOptions {\n /**\n * The allowed \"alg\" (Algorithm) Header Parameter values.\n *\n * These values specify the cryptographic algorithms that are permissible for decrypting\n * the Content Encryption Key (CEK) or for key agreement to determine the CEK.\n *\n * Note: If not specified, all algorithm values are considered allowed, which might not be\n * desirable in all contexts.\n */\n allowedAlgValues?: string[];\n\n /**\n * The allowed \"enc\" (Encryption) Header Parameter values.\n *\n * These values determine the cryptographic algorithms that can be used for decrypting the\n * ciphertext and protecting the integrity of the plaintext and Additional Authenticated Data.\n *\n * Note: If left unspecified, it implies that all encryption algorithms are acceptable, which may\n * not be secure in every scenario.\n *\n */\n allowedEncValues?: string[];\n}\n\n/**\n * Placeholder for specifying options during the JWE encryption process. Currently, this interface\n * does not define any specific options but can be extended in the future to include parameters\n * that control various aspects of the JWE encryption workflow.\n */\nexport interface JweEncryptOptions {}\n\n/**\n * JSON Web Encryption (JWE) Header Parameters\n *\n * The Header Parameter names for use in JWEs are registered in the IANA \"JSON Web Signature and\n * Encryption Header Parameters\" registry.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7516#section-4.1 | RFC 7516, Section 4.1}\n */\nexport interface JweHeaderParams extends JoseHeaderParams {\n /**\n * Algorithm Header Parameter\n *\n * Identifies the cryptographic algorithm used to encrypt or determine the value of the Content\n * Encryption Key (CEK). The encrypted content is not usable if the \"alg\" value does not represent\n * a supported algorithm, or if the recipient does not have a key that can be used with that\n * algorithm.\n *\n * \"alg\" values should either be registered in the IANA \"JSON Web Signature and Encryption\n * Algorithms\" registry or be a value that contains a Collision-Resistant Name. The \"alg\" value is\n * a case-sensitive ASCII string. This Header Parameter MUST be present and MUST be understood\n * and processed by implementations.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7516#section-4.1.1 | RFC 7516, Section 4.1.1}\n */\n alg:\n // AES Key Wrap with default initial value using 128-bit key\n | 'A128KW'\n // AES Key Wrap with default initial value using 192-bit key\n | 'A192KW'\n // AES Key Wrap with default initial value using 256-bit key\n | 'A256KW'\n // Direct use of a shared symmetric key as the CEK\n | 'dir'\n // Elliptic Curve Diffie-Hellman Ephemeral Static key agreement using Concat KDF\n | 'ECDH-ES'\n // ECDH-ES using Concat KDF and CEK wrapped with \"A128KW\"\n | 'ECDH-ES+A128KW'\n // ECDH-ES using Concat KDF and CEK wrapped with \"A192KW\"\n | 'ECDH-ES+A192KW'\n // ECDH-ES using Concat KDF and CEK wrapped with \"A256KW\"\n | 'ECDH-ES+A256KW'\n // Key wrapping with AES GCM using 128-bit key\n | 'A128GCMKW'\n // Key wrapping with AES GCM using 192-bit key\n | 'A192GCMKW'\n // Key wrapping with AES GCM using 256-bit key\n | 'A256GCMKW'\n // PBES2 with HMAC SHA-256 and \"A128KW\" wrapping\n | 'PBES2-HS256+A128KW'\n // PBES2 with HMAC SHA-384 and \"A192KW\" wrapping\n | 'PBES2-HS384+A192KW'\n // PBES2 with HMAC SHA-512 and \"A256KW\" wrapping\n | 'PBES2-HS512+A256KW'\n // PBES2 with HMAC SHA-512 and \"XC20PKW\" wrapping\n | 'PBES2-HS512+XC20PKW'\n // an unregistered, case-sensitive, collision-resistant string\n | string;\n\n /**\n * Agreement PartyUInfo Header Parameter\n *\n * The \"apu\" (agreement PartyUInfo) value is a base64url-encoded octet sequence containing\n * information about the producer of the JWE. This information is used by the recipient to\n * determine the key agreement algorithm and key encryption algorithm to use to decrypt the JWE.\n *\n * Note: This parameter is intended only for use when the recipient is a key agreement algorithm\n * that uses public key cryptography.\n */\n apu?: string;\n\n /**\n * Agreement PartyVInfo Header Parameter\n *\n * The \"apv\" (agreement PartyVInfo) value is a base64url-encoded octet sequence containing\n * information about the recipient of the JWE. This information is used by the recipient to\n * determine the key agreement algorithm and key encryption algorithm to use to decrypt the JWE.\n *\n * Note: This parameter is intended only for use when the recipient is a key agreement algorithm\n * that uses public key cryptography.\n */\n apv?: string;\n\n /**\n * Critical Header Parameter\n *\n * Indicates that extensions to JOSE RFCs are being used that MUST be understood and processed.\n */\n crit?: string[];\n\n /**\n * Encryption Algorithm Header Parameter\n *\n * Identifies the content encryption algorithm used to encrypt and integrity-protect (also\n * known as \"authenticated encryption\") the plaintext and to integrity-protect the Additional\n * Authenticated Data (AAD), if any. This algorithm MUST be an AEAD algorithm with a specified\n * key length.\n *\n * The encrypted content is not usable if the \"enc\" value does not represent a supported\n * algorithm. \"enc\" values should either be registered in the IANA \"JSON Web Signature and\n * Encryption Algorithms\" registry or be a value that contains a Collision-Resistant Name. The\n * \"enc\" value is a case-sensitive ASCII string containing a StringOrURI value. This Header\n * Parameter MUST be present and MUST be understood and processed by implementations.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7516#section-4.1.2 | RFC 7516, Section 4.1.2}\n */\n enc:\n // AES_128_CBC_HMAC_SHA_256 authenticated encryption algorithm,\n // as defined in RFC 7518, Section 5.2.3\n | 'A128CBC-HS256'\n // AES_192_CBC_HMAC_SHA_384 authenticated encryption algorithm,\n // as defined in RFC 7518, Section 5.2.4\n | 'A192CBC-HS384'\n // AES_256_CBC_HMAC_SHA_512 authenticated encryption algorithm,\n // as defined in RFC 7518, Section 5.2.5\n | 'A256CBC-HS512'\n // AES GCM using 128-bit key\n | 'A128GCM'\n // AES GCM using 192-bit key\n | 'A192GCM'\n // AES GCM using 256-bit key\n | 'A256GCM'\n // XChaCha20-Poly1305 authenticated encryption algorithm\n | 'XC20P'\n // an unregistered, case-sensitive, collision-resistant string\n | string;\n\n /**\n * Ephemeral Public Key Header Parameter\n *\n * The \"epk\" (ephemeral public key) value created by the originator for the use in key agreement\n * algorithms. It is the ephemeral public key that corresponds to the key used to encrypt the\n * JWE. This value is represented as a JSON Web Key (JWK).\n *\n * Note: This parameter is intended only for use when the recipient is a key agreement algorithm\n * that uses public key cryptography.\n */\n epk?: Jwk;\n\n /**\n * Initialization Vector Header Parameter\n *\n * The \"iv\" (initialization vector) value is a base64url-encoded octet sequence used by the\n * specified \"enc\" algorithm. The length of this Initialization Vector value MUST be exactly\n * equal to the value that would be produced by the \"enc\" algorithm.\n *\n * Note: With symmetric encryption algorithms such as AES GCM, this Header Parameter MUST\n * be present and MUST be understood and processed by implementations.\n */\n iv?: string;\n\n /**\n * PBES2 Count Header Parameter\n *\n * The \"p2c\" (PBES2 count) value is an integer indicating the number of iterations of the PBKDF2\n * algorithm performed during key derivation.\n *\n * Note: The iteration count adds computational expense, ideally compounded by the possible range\n * of keys introduced by the salt. A minimum iteration count of 1000 is RECOMMENDED.\n */\n p2c?: number;\n\n /**\n * PBES2 Salt Input Header Parameter\n *\n * The \"p2s\" (PBES2 salt) value is a base64url-encoded octet sequence used as the salt value\n * input to the PBKDF2 algorithm during key derivation.\n *\n * The salt value used is (UTF8(Alg) || 0x00 || Salt Input), where Alg is the \"alg\" (algorithm)\n * Header Parameter value.\n *\n * Note: The salt value is used to ensure that each key derived from the master key is\n * independent of every other key. A suitable source of salt value is a sequence of\n * cryptographically random bytes containing 8 or more octets.\n */\n p2s?: string;\n\n /**\n * Authentication Tag Header Parameter\n *\n * The \"tag\" value is a base64url-encoded octet sequence containing the value of the\n * Authentication Tag output by the specified \"enc\" algorithm. The length of this\n * Authentication Tag value MUST be exactly equal to the value that would be produced by the\n * \"enc\" algorithm.\n *\n * Note: With authenticated encryption algorithms such as AES GCM, this Header Parameter MUST\n * be present and MUST be understood and processed by implementations.\n */\n tag?: string;\n\n /**\n * Additional Public or Private Header Parameter names.\n */\n [key: string]: unknown;\n}\n\n/**\n * Represents the result of the JWE key management encryption process, encapsulating the Content\n * Encryption Key (CEK) and optionally the encrypted CEK.\n */\nexport interface JweKeyManagementEncryptResult {\n /**\n * The Content Encryption Key (CEK) used for encrypting the JWE payload. It can be a Key\n * Identifier such as a KMS URI or a JSON Web Key (JWK).\n */\n cek: KeyIdentifier | Jwk;\n\n /**\n * The encrypted version of the CEK, provided as a byte array. The encrypted version of the CEK\n * is returned for all key management modes other than \"dir\" (Direct Encryption Mode).\n */\n encryptedKey?: Uint8Array;\n}\n\n/**\n * Defines the parameters required to decrypt a JWE encrypted key, including the key management\n * details.\n *\n * @typeParam TKeyManager - The Key Manager used to manage cryptographic keys.\n * @typeParam TCrypto - The Crypto API used to perform cryptographic operations.\n */\nexport interface JweKeyManagementDecryptParams<TKeyManager, TCrypto> {\n /**\n * The decryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n * or raw key material represented as a byte array.\n */\n key: KeyIdentifier | Jwk | Uint8Array;\n\n /**\n * The encrypted key extracted from the JWE, represented as a byte array. This parameter is\n * optional and is used when the key is wrapped.\n */\n encryptedKey?: Uint8Array;\n\n /**\n * The JWE header parameters that define the characteristics of the decryption process, specifying\n * the algorithm and encryption method among other settings.\n */\n joseHeader: JweHeaderParams;\n\n /** Key Manager instance\u00DF responsible for managing cryptographic keys. */\n keyManager: TKeyManager;\n\n /** Crypto API instance that provides the necessary cryptographic operations. */\n crypto: TCrypto;\n}\n\n/**\n * Defines the parameters required for encrypting a JWE CEK, including the key management details.\n *\n * @typeParam TKeyManager - The Key Manager used to manage cryptographic keys.\n * @typeParam TCrypto - The Crypto API used to perform cryptographic operations.\n */\nexport interface JweKeyManagementEncryptParams<TKeyManager, TCrypto> {\n /**\n * The encryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n * or raw key material represented as a byte array.\n */\n key: KeyIdentifier | Jwk | Uint8Array;\n\n /**\n * The JWE header parameters that define the characteristics of the encryption process, specifying\n * the algorithm and encryption method among other settings.\n */\n joseHeader: JweHeaderParams;\n\n /** Key Manager instance\u00DF responsible for managing cryptographic keys. */\n keyManager: TKeyManager;\n\n /** Crypto API instance that provides the necessary cryptographic operations. */\n crypto: TCrypto;\n}\n\n/**\n * Checks if the provided object is a valid JWE (JSON Web Encryption) header.\n *\n * This function evaluates whether the given object adheres to the structure expected for\n * a JWE header, specifically looking for the presence and proper format of the \"alg\" (algorithm)\n * and \"enc\" (encryption algorithm) properties, which are essential for defining the JWE's\n * cryptographic operations.\n *\n * @example\n * ```ts\n * const header = {\n * alg: 'dir',\n * enc: 'A256GCM'\n * };\n *\n * if (isValidJweHeader(header)) {\n * console.log('The object is a valid JWE header.');\n * } else {\n * console.log('The object is not a valid JWE header.');\n * }\n * ```\n *\n * @param obj - The object to be validated as a JWE header.\n * @returns Returns `true` if the object is a valid JWE header, otherwise `false`.\n */\nexport function isValidJweHeader(obj: unknown): obj is JweHeaderParams {\n return typeof obj === 'object' && obj !== null\n && 'alg' in obj && obj.alg !== undefined\n && 'enc' in obj && obj.enc !== undefined;\n}\n\n/**\n * The `JweKeyManagement` class implements the key management aspects of JSON Web Encryption (JWE)\n * as specified in {@link https://datatracker.ietf.org/doc/html/rfc7516 | RFC 7516}.\n *\n * It supports algorithms for encrypting and decrypting keys, thereby enabling the secure\n * transmission of information where the payload is encrypted, and the encryption key is also\n * encrypted or agreed upon using key agreement techniques.\n *\n * The choice of algorithm is determined by the \"alg\" parameter in the JWE\n * header, and the class is designed to handle the intricacies associated with each algorithm,\n * ensuring the secure handling of the encryption keys.\n *\n * Supported algorithms include:\n * - `\"dir\"`: Direct Encryption Mode\n * - `\"PBES2-HS256+A128KW\"`, `\"PBES2-HS384+A192KW\"`, `\"PBES2-HS512+A256KW\"`: Password-Based\n * Encryption Mode with Key Wrapping (PBES2) using HMAC-SHA and AES Key Wrap algorithms for key\n * wrapping and encryption.\n *\n * @example\n * // To encrypt a key:\n * const keyEncryptionKey = Convert.string(passphrase).toUint8Array()\n * const { cek, encryptedKey: encryptedCek } = await JweKeyManagement.encrypt({\n * key: keyEncryptionKey,\n * joseHeader: {\n * alg: 'PBES2-HS512+A256KW',\n * enc: 'A256GCM',\n * p2c : 210_000,\n p2s : Convert.uint8Array(saltInput).toBase64Url()\n * },\n * crypto: new AgentCryptoApi(),\n * });\n *\n * // To decrypt a key:\n * const cek = await JweKeyManagement.decrypt({\n * key: keyEncryptionKey,\n * encryptedKey: encryptedCek,\n * joseHeader: {\n * alg: 'PBES2-HS512+A256KW',\n * enc: 'A256GCM',\n * p2c : 210_000,\n p2s : Convert.uint8Array(saltInput).toBase64Url()\n * },\n * crypto: new AgentCryptoApi(),\n * });\n */\nexport class JweKeyManagement {\n /**\n * Decrypts the encrypted key (JWE Encrypted Key) using the specified key encryption algorithm\n * defined in the JWE Header's \"alg\" parameter.\n *\n * This method supports multiple key management algorithms, including Direct Encryption (dir) and\n * PBES2 schemes with key wrapping.\n *\n * The method takes a key, which can be a Key Identifier, JWK, or raw byte array, and the\n * encrypted key along with the JWE header. It returns the decrypted Content Encryption Key (CEK)\n * which can then be used to decrypt the JWE ciphertext.\n *\n * @example\n * ```ts\n * // Decrypting the CEK with the PBES2-HS512+A256KW algorithm\n * const cek = await JweKeyManagement.decrypt({\n * key: Convert.string(passphrase).toUint8Array(),\n * encryptedKey: encryptedCek,\n * joseHeader: {\n * alg: 'PBES2-HS512+A256KW',\n * enc: 'A256GCM',\n * p2c: 210_000,\n * p2s: Convert.uint8Array(saltInput).toBase64Url(),\n * },\n * crypto: new AgentCryptoApi()\n * });\n * ```\n *\n * @param params - The decryption parameters.\n * @throws Throws an error if the key management algorithm is not supported or if required\n * parameters are missing or invalid.\n */\n public static async decrypt<TKeyManager extends KeyManager, TCrypto extends CryptoApi>({\n key, encryptedKey, joseHeader, crypto\n }: JweKeyManagementDecryptParams<TKeyManager, TCrypto>\n ): Promise<KeyIdentifier | Jwk> {\n // Determine the Key Management Mode employed by the algorithm specified by the \"alg\"\n // (algorithm) Header Parameter.\n switch (joseHeader.alg) {\n case 'dir': {\n // In Direct Encryption mode, a JWE \"Encrypted Key\" is not provided. Instead, the\n // provided key management `key` is directly used as the Content Encryption Key (CEK) to\n // decrypt the JWE payload.\n\n // Verify that the JWE Encrypted Key value is empty.\n if (encryptedKey !== undefined) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JWE \"encrypted_key\" is not allowed when using \"dir\" (Direct Encryption Mode).');\n }\n\n // Verify the key management `key` is a Key Identifier or JWK.\n if (key instanceof Uint8Array) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Key management \"key\" must be a Key URI or JWK when using \"dir\" (Direct Encryption Mode).');\n }\n\n // return the key management `key` as the CEK.\n return key;\n }\n\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n // In Key Encryption mode (PBES2) with key wrapping (A128KW, A192KW, A256KW), the given\n // passphrase, salt (p2s), and iteration count (p2c) are used with the PBKDF2 key derivation\n // function to derive the Key Encryption Key (KEK). The KEK is then used to decrypt the JWE\n // Encrypted Key to obtain the Content Encryption Key (CEK).\n\n if (typeof joseHeader.p2c !== 'number') {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"p2c\" (PBES2 Count) is missing or not a number.');\n }\n\n if (typeof joseHeader.p2s !== 'string') {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"p2s\" (PBES2 salt) is missing or not a string.');\n }\n\n // Throw an error if the key management `key` is not a byte array. For PBES2, the key is\n // expected to be a low-entropy passphrase as a byte array.\n if (!(key instanceof Uint8Array)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Key management \"key\" must be a Uint8Array when using \"PBES2\" (Key Encryption Mode).');\n }\n\n // Verify that the JWE Encrypted Key value is present.\n if (encryptedKey === undefined) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JWE \"encrypted_key\" is required when using \"PBES2\" (Key Encryption Mode).');\n }\n\n // Per {@link https://www.rfc-editor.org/rfc/rfc7518.html#section-4.8.1.1 | RFC 7518, Section 4.8.1.1},\n // the salt value used with PBES2 should be of the format (UTF8(Alg) || 0x00 || Salt Input),\n // where Alg is the \"alg\" (algorithm) Header Parameter value. This reduces the potential for\n // a precomputed dictionary attack (also known as a rainbow table attack).\n let salt: Uint8Array;\n try {\n salt = new Uint8Array([\n ...Convert.string(joseHeader.alg).toUint8Array(),\n 0x00,\n ...Convert.base64Url(joseHeader.p2s).toUint8Array()\n ]);\n } catch {\n throw new CryptoError(CryptoErrorCode.EncodingError, 'Failed to decode the JOSE Header \"p2s\" (PBES2 salt) value.');\n }\n\n // Derive the Key Encryption Key (KEK) from the given passphrase, salt, and iteration count.\n const kek = await crypto.deriveKey({\n algorithm : joseHeader.alg,\n baseKeyBytes : key,\n iterations : joseHeader.p2c,\n salt\n });\n\n if (!(kek.alg && ['A128KW', 'A192KW', 'A256KW'].includes(kek.alg))) {\n throw new CryptoError(CryptoErrorCode.AlgorithmNotSupported, `Unsupported Key Encryption Algorithm (alg) value: ${kek.alg}`);\n }\n\n // Decrypt the Content Encryption Key (CEK) with the derived KEK.\n return await crypto.unwrapKey({\n decryptionKey : kek,\n wrappedKeyBytes : encryptedKey,\n wrappedKeyAlgorithm : joseHeader.enc\n });\n }\n\n default: {\n throw new CryptoError(\n CryptoErrorCode.AlgorithmNotSupported,\n `Unsupported \"alg\" (Algorithm) Header Parameter value: ${joseHeader.alg}`\n );\n }\n }\n }\n\n /**\n * Encrypts a Content Encryption Key (CEK) using the key management algorithm specified in the\n * JWE Header's \"alg\" parameter.\n *\n * This method supports various key management algorithms, including Direct Encryption (dir) and\n * PBES2 with key wrapping.\n *\n * It generates a random CEK for the specified encryption algorithm in the JWE header, which\n * can then be used to encrypt the actual payload. For algorithms that require an encrypted key,\n * it returns the CEK along with the encrypted key.\n *\n * @example\n * ```ts\n * // Encrypting the CEK with the PBES2-HS512+A256KW algorithm\n * const { cek, encryptedKey } = await JweKeyManagement.encrypt({\n * key: Convert.string(passphrase).toUint8Array(),\n * joseHeader: {\n * alg: 'PBES2-HS512+A256KW',\n * enc: 'A256GCM',\n * p2c: 210_000,\n * p2s: Convert.uint8Array(saltInput).toBase64Url(),\n * },\n * crypto: crypto: new AgentCryptoApi()\n * });\n * ```\n *\n * @param params - The encryption parameters.\n * @returns The encrypted key result containing the CEK and optionally the encrypted CEK\n * (JWE Encrypted Key).\n * @throws Throws an error if the key management algorithm is not supported or if required\n * parameters are missing or invalid.\n */\n public static async encrypt<TKeyManager extends KeyManager, TCrypto extends CryptoApi>({\n key, joseHeader, crypto\n }: JweKeyManagementEncryptParams<TKeyManager, TCrypto>\n ): Promise<JweKeyManagementEncryptResult> {\n let cek: KeyIdentifier | Jwk;\n let encryptedKey: Uint8Array | undefined;\n\n // Determine the Key Management Mode employed by the algorithm specified by the \"alg\"\n // (algorithm) Header Parameter.\n switch (joseHeader.alg) {\n case 'dir': {\n // In Direct Encryption mode (dir), a JWE \"Encrypted Key\" is not provided. Instead, the\n // provided key management `key` is directly used as the Content Encryption Key (CEK) to\n // decrypt the JWE payload.\n\n // Verify that the JWE Encrypted Key value is empty.\n if (encryptedKey !== undefined) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JWE \"encrypted_key\" is not allowed when using \"dir\" (Direct Encryption Mode).');\n }\n\n // Verify the key management `key` is a Key Identifier or JWK.\n if (key instanceof Uint8Array) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Key management \"key\" must be a Key URI or JWK when using \"dir\" (Direct Encryption Mode).');\n }\n\n // Set the CEK to the key management `key`.\n cek = key;\n\n break;\n }\n\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n // In Key Encryption mode (PBES2) with key wrapping (A128KW, A192KW, A256KW), a randomly\n // generated Content Encryption Key (CEK) is encrypted with a Key Encryption Key (KEK)\n // derived from the given passphrase, salt (p2s), and iteration count (p2c) using the\n // PBKDF2 key derivation function.\n\n if (typeof joseHeader.p2c !== 'number') {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"p2c\" (PBES2 Count) is missing or not a number.');\n }\n\n if (typeof joseHeader.p2s !== 'string') {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JOSE Header \"p2s\" (PBES2 salt) is missing or not a string.');\n }\n\n // Throw an error if the key management `key` is not a byte array.\n if (!(key instanceof Uint8Array)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Key management \"key\" must be a Uint8Array when using \"PBES2\" (Key Encryption Mode).');\n }\n\n // Generate a random Content Encryption Key (CEK) using the algorithm specified by the \"enc\"\n // (encryption) Header Parameter.\n cek = await crypto.generateKey({ algorithm: joseHeader.enc });\n\n // Per {@link https://www.rfc-editor.org/rfc/rfc7518.html#section-4.8.1.1 | RFC 7518, Section 4.8.1.1},\n // the salt value used with PBES2 should be of the format (UTF8(Alg) || 0x00 || Salt Input),\n // where Alg is the \"alg\" (algorithm) Header Parameter value. This reduces the potential for\n // a precomputed dictionary attack (also known as a rainbow table attack).\n let salt: Uint8Array;\n try {\n salt = new Uint8Array([\n ...Convert.string(joseHeader.alg).toUint8Array(),\n 0x00,\n ...Convert.base64Url(joseHeader.p2s).toUint8Array()\n ]);\n } catch {\n throw new CryptoError(CryptoErrorCode.EncodingError, 'Failed to decode the JOSE Header \"p2s\" (PBES2 salt) value.');\n }\n\n // Derive a Key Encryption Key (KEK) from the given passphrase, salt, and iteration count.\n const kek = await crypto.deriveKey({\n algorithm : joseHeader.alg,\n baseKeyBytes : key,\n iterations : joseHeader.p2c,\n salt\n });\n\n // Encrypt the randomly generated CEK with the derived Key Encryption Key (KEK).\n encryptedKey = await crypto.wrapKey({ encryptionKey: kek, unwrappedKey: cek });\n\n break;\n }\n\n default: {\n throw new CryptoError(\n CryptoErrorCode.AlgorithmNotSupported,\n `Unsupported \"alg\" (Algorithm) Header Parameter value: ${joseHeader.alg}`\n );\n }\n }\n\n return { cek, encryptedKey };\n }\n}", "import type { Jwk, KeyIdentifier } from '@enbox/crypto';\n\nimport { Convert } from '@enbox/common';\nimport { LocalKeyManager, CryptoUtils } from '@enbox/crypto';\n\nimport type { CryptoApi } from '../types/crypto-api.js';\nimport type { KeyManager } from '../types/key-manager.js';\nimport type { JweDecryptOptions, JweEncryptOptions, JweHeaderParams } from './jwe.js';\n\nimport { isCipher } from '../utils.js';\nimport { AgentCryptoApi } from '../../../crypto-api.js';\nimport { JweKeyManagement, isValidJweHeader } from './jwe.js';\nimport { hasDuplicateProperties } from '../../common/object.js';\nimport { CryptoError, CryptoErrorCode } from '../crypto-error.js';\n\n/**\n * Parameters required for decrypting a flattened JWE.\n *\n * @typeParam TKeyManager - The Key Manager used to manage cryptographic keys.\n * @typeParam TCrypto - The Crypto API used to perform cryptographic operations.\n */\nexport interface FlattenedJweDecryptParams<TKeyManager, TCrypto> {\n /** The flattened JWE. */\n jwe: FlattenedJweParams | FlattenedJwe;\n\n /**\n * The decryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n * or raw key material represented as a byte array.\n */\n key: KeyIdentifier | Jwk | Uint8Array;\n\n /** Key Manager instance\u00DF responsible for managing cryptographic keys. */\n keyManager?: TKeyManager;\n\n /** Crypto API instance that provides the necessary cryptographic operations. */\n crypto?: TCrypto;\n\n /** {@inheritDoc JweDecryptOptions} */\n options?: JweDecryptOptions;\n}\n\n/**\n * Result of decrypting a flattened JWE, containing the plaintext and related information.\n */\nexport interface FlattenedJweDecryptResult {\n /** JWE Additional Authenticated Data (AAD). */\n additionalAuthenticatedData?: Uint8Array;\n\n /** Plaintext. */\n plaintext: Uint8Array;\n\n /** JWE Protected Header. */\n protectedHeader?: Partial<JweHeaderParams>;\n\n /** JWE Shared Unprotected Header. */\n sharedUnprotectedHeader?: Partial<JweHeaderParams>;\n\n /** JWE Per-Recipient Unprotected Header. */\n unprotectedHeader?: Partial<JweHeaderParams>;\n}\n\n/**\n * Parameters for encrypting data into a flattened JWE format.\n *\n * @typeParam TKeyManager - The Key Manager used to manage cryptographic keys.\n * @typeParam TCrypto - The Crypto API used to perform cryptographic operations.\n */\nexport interface FlattenedJweEncryptParams<TKeyManager, TCrypto> extends FlattenedJweDecryptResult {\n /**\n * The encryption key which can be a Key Identifier such as a KMS key URI, a JSON Web Key (JWK),\n * or raw key material represented as a byte array.\n */\n key: KeyIdentifier | Jwk | Uint8Array;\n\n /** Key Manager instance\u00DF responsible for managing cryptographic keys. */\n keyManager?: TKeyManager;\n\n /** Crypto API instance that provides the necessary cryptographic operations. */\n crypto?: TCrypto;\n\n /** {@inheritDoc JweEncryptOptions} */\n options?: JweEncryptOptions;\n}\n\n/**\n * Represents the parameters for a flattened JWE object, typically used in single-recipient\n * scenarios.\n */\nexport interface FlattenedJweParams {\n /** Base64URL encoded additional authenticated data. */\n aad?: string;\n\n /** Base64URL encoded ciphertext. */\n ciphertext: string;\n\n /** Base64URL encoded encrypted key. */\n encrypted_key?: string;\n\n /** Per-Recipient Unprotected Header parameters. */\n header?: Partial<JweHeaderParams>;\n\n /** Base64URL encoded initialization vector. */\n iv?: string;\n\n /** Base64URL encoded string of the Protected Header. */\n protected?: string;\n\n /** Base64URL encoded authentication tag. */\n tag?: string;\n\n /** Shared Unprotected Header parameters. */\n unprotected?: Partial<JweHeaderParams>;\n}\n\n/**\n * A helper utility function used internally to decode a JWE header parameter from a Base64 URL\n * encoded string to a Uint8Array. It's designed to process individual JWE header parameter values,\n * ensuring they are correctly formatted and decoded.\n *\n * @param param - The name of the JWE header parameter being decoded; used for error messaging.\n * @param value - The Base64 URL encoded string value of the header parameter to decode.\n * @returns The decoded parameter as a Uint8Array, or undefined if the input value is undefined.\n * @throws {@link CryptoError} if the value is not a properly encoded Base64 URL string or if it's\n * not a string.\n */\nfunction decodeHeaderParam(param: string, value?: string): Uint8Array | undefined {\n // If the parameter value is not present, return undefined.\n if (value === undefined) return undefined;\n\n try {\n if (typeof value !== 'string') throw new Error();\n return Convert.base64Url(value).toUint8Array();\n } catch {\n throw new CryptoError(CryptoErrorCode.InvalidJwe,\n `Failed to decode the JWE Header parameter '${param}' from Base64 URL format to ` +\n 'Uint8Array. Ensure the value is properly encoded in Base64 URL format without padding.'\n );\n }\n}\n\n/**\n * The `FlattenedJwe` class handles the encryption and decryption of JSON Web Encryption (JWE)\n * objects in the flattened serialization format. This format is a compact, URL-safe means of\n * representing encrypted content, typically used when dealing with a single recipient or when\n * bandwidth efficiency is important.\n *\n * This class provides methods to encrypt plaintext to a flattened JWE and decrypt a flattened JWE\n * back to plaintext, utilizing a variety of supported cryptographic algorithms as specified in the\n * JWE header parameters.\n *\n * @example\n * ```ts\n * // Example usage of encrypt method\n * const plaintext = new TextEncoder().encode(\"Secret Message\");\n * const key = { kty: \"oct\", k: \"your-secret-key\" }; // Example symmetric key\n * const protectedHeader = { alg: \"dir\", enc: \"A256GCM\" };\n * const encryptedJwe = await FlattenedJwe.encrypt({\n * plaintext,\n * protectedHeader,\n * key,\n * });\n * ```\n *\n * @example\n * // Decryption example\n * const { plaintext, protectedHeader } = await FlattenedJwe.decrypt({\n * jwe: yourFlattenedJweObject,\n * key: yourDecryptionKey,\n * crypto: new YourCryptoApi(),\n * });\n */\nexport class FlattenedJwe {\n /** Base64URL encoded additional authenticated data. */\n public aad?: string;\n\n /** Base64URL encoded ciphertext. */\n public ciphertext: string = '';\n\n /** Base64URL encoded encrypted key. */\n public encrypted_key?: string;\n\n /** Per-Recipient Unprotected Header parameters. */\n public header?: Partial<JweHeaderParams>;\n\n /** Base64URL encoded initialization vector. */\n public iv?: string;\n\n /** Base64URL encoded string of the Protected Header. */\n public protected?: string;\n\n /** Base64URL encoded authentication tag. */\n public tag?: string;\n\n /** Shared Unprotected Header parameters. */\n public unprotected?: Partial<JweHeaderParams>;\n\n constructor(params: FlattenedJweParams) {\n Object.assign(this, params);\n }\n\n public static async decrypt<\n TKeyManager extends KeyManager | undefined = KeyManager,\n TCrypto extends CryptoApi | undefined = CryptoApi\n >({\n jwe,\n key,\n keyManager = new LocalKeyManager(),\n crypto = new AgentCryptoApi(),\n options = {}\n }: FlattenedJweDecryptParams<TKeyManager, TCrypto>): Promise<FlattenedJweDecryptResult> {\n // Verify that the provided Crypto API supports the decrypt operation before proceeding.\n if (!isCipher(crypto)) {\n throw new CryptoError(CryptoErrorCode.OperationNotSupported, 'Crypto API does not support the \"encrypt\" operation.');\n }\n // Verify that the provided Key Manager supports the decrypt operation before proceeding.\n if (!isCipher(keyManager)) {\n throw new CryptoError(CryptoErrorCode.OperationNotSupported, 'Key Manager does not support the \"decrypt\" operation.');\n }\n\n // Verify that at least one of the JOSE header objects is present.\n if (!jwe.protected && !jwe.header && !jwe.unprotected) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe,\n 'JWE is missing the required JOSE header parameters. ' +\n 'Please provide at least one of the following: \"protected\", \"header\", or \"unprotected\"'\n );\n }\n\n // Verify that the JWE Ciphertext is present.\n if (typeof jwe.ciphertext !== 'string') {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'JWE Ciphertext is missing or not a string.');\n }\n\n // Parse the JWE Protected Header, if present.\n let parsedProtectedHeader: Partial<JweHeaderParams> | undefined;\n if (jwe.protected) {\n try {\n parsedProtectedHeader = Convert.base64Url(jwe.protected).toObject();\n } catch {\n throw new Error('JWE Protected Header is invalid');\n }\n }\n\n // Per {@link https://www.rfc-editor.org/rfc/rfc7516#section-5.2 | RFC7516 Section 5.2}\n // the resulting JOSE Header MUST NOT contain duplicate Header Parameter names. In other words,\n // the same Header Parameter name MUST NOT occur in the `header`, `protected`, and\n // `unprotected` JSON object values that together comprise the JOSE Header.\n if (hasDuplicateProperties(parsedProtectedHeader, jwe.header, jwe.unprotected)){\n throw new Error(\n 'Duplicate properties detected. Please ensure that each parameter is defined only once ' +\n 'across the JWE \"header\", \"protected\", and \"unprotected\" objects.'\n );\n }\n\n // The JOSE Header is the union of the members of the JWE Protected Header (`protected`), the\n // JWE Shared Unprotected Header (`unprotected`), and the corresponding JWE Per-Recipient\n // Unprotected Header (`header`).\n const joseHeader = { ...parsedProtectedHeader, ...jwe.header, ...jwe.unprotected };\n\n if (!isValidJweHeader(joseHeader)) {\n throw new Error('JWE Header is missing required \"alg\" (Algorithm) and/or \"enc\" (Encryption) Header Parameters');\n }\n\n if (Array.isArray(options.allowedAlgValues)\n && !options.allowedAlgValues.includes(joseHeader.alg)) {\n throw new Error(`\"alg\" (Algorithm) Header Parameter value not allowed: ${joseHeader.alg}`);\n }\n\n if (Array.isArray(options.allowedEncValues)\n && !options.allowedEncValues.includes(joseHeader.enc)) {\n throw new Error(`\"enc\" (Encryption Algorithm) Header Parameter value not allowed: ${joseHeader.enc}`);\n }\n\n let cek: KeyIdentifier | Jwk;\n try {\n const encryptedKey = jwe.encrypted_key\n ? Convert.base64Url(jwe.encrypted_key).toUint8Array()\n : undefined;\n\n cek = await JweKeyManagement.decrypt({ key, encryptedKey, joseHeader, keyManager, crypto });\n\n } catch (error: any) {\n // If the error is a CryptoError with code \"InvalidJwe\" or \"AlgorithmNotSupported\", re-throw.\n if (error instanceof CryptoError\n && (error.code === CryptoErrorCode.InvalidJwe || error.code === CryptoErrorCode.AlgorithmNotSupported)) {\n throw error;\n }\n\n // Otherwise, generate a random CEK and proceed to the next step.\n // As noted in\n // {@link https://datatracker.ietf.org/doc/html/rfc7516#section-11.5 | RFC 7516 Section 11.5},\n // to mitigate the attacks described in\n // {@link https://datatracker.ietf.org/doc/html/rfc3218 | RFC 3218}, the recipient MUST NOT\n // distinguish between format, padding, and length errors of encrypted keys. It is strongly\n // recommended, in the event of receiving an improperly formatted key, that the recipient\n // substitute a randomly generated CEK and proceed to the next step, to mitigate timing\n // attacks.\n cek = typeof key === 'string'\n ? await keyManager.generateKey({ algorithm: joseHeader.enc })\n : await crypto.generateKey({ algorithm: joseHeader.enc });\n }\n\n // If present, decode the JWE Initialization Vector (IV) and Authentication Tag.\n const iv = decodeHeaderParam('iv', jwe.iv);\n const tag = decodeHeaderParam('tag', jwe.tag);\n\n // Decode the JWE Ciphertext to a byte array, and if present, append the Authentication Tag.\n const ciphertext = tag !== undefined\n ? new Uint8Array([\n ...Convert.base64Url(jwe.ciphertext).toUint8Array(),\n ...(tag ?? [])\n ])\n : Convert.base64Url(jwe.ciphertext).toUint8Array();\n\n // If the JWE Additional Authenticated Data (AAD) is present, the Additional Authenticated Data\n // input to the Content Encryption Algorithm is\n // ASCII(Encoded Protected Header || '.' || BASE64URL(JWE AAD)). If the JWE AAD is absent, the\n // Additional Authenticated Data is ASCII(BASE64URL(UTF8(JWE Protected Header))).\n const additionalData = jwe.aad !== undefined\n ? new Uint8Array([\n ...Convert.string(jwe.protected ?? '').toUint8Array(),\n ...Convert.string('.').toUint8Array(),\n ...Convert.string(jwe.aad).toUint8Array()\n ])\n : Convert.string(jwe.protected ?? '').toUint8Array();\n\n // Decrypt the JWE using the Content Encryption Key (CEK) with:\n // - Key Manager: If the CEK is a Key Identifier.\n // - Crypto API: If the CEK is a JWK.\n const plaintext = typeof cek === 'string'\n ? await keyManager.decrypt({ keyUri: cek, data: ciphertext, iv, additionalData })\n : await crypto.decrypt({ key: cek, data: ciphertext, iv, additionalData });\n\n return {\n plaintext,\n protectedHeader : parsedProtectedHeader,\n additionalAuthenticatedData : decodeHeaderParam('aad', jwe.aad),\n sharedUnprotectedHeader : jwe.unprotected,\n unprotectedHeader : jwe.header\n };\n }\n\n public static async encrypt<\n TKeyManager extends KeyManager | undefined = KeyManager,\n TCrypto extends CryptoApi | undefined = CryptoApi\n >({\n key,\n plaintext,\n additionalAuthenticatedData,\n protectedHeader,\n sharedUnprotectedHeader,\n unprotectedHeader,\n keyManager = new LocalKeyManager(),\n crypto = new AgentCryptoApi(),\n }: FlattenedJweEncryptParams<TKeyManager, TCrypto>): Promise<FlattenedJwe> {\n // Verify that the provided Crypto API supports the decrypt operation before proceeding.\n if (!isCipher(crypto)) {\n throw new CryptoError(CryptoErrorCode.OperationNotSupported, 'Crypto API does not support the \"encrypt\" operation.');\n }\n // Verify that the provided Key Manager supports the decrypt operation before proceeding.\n if (!isCipher(keyManager)) {\n throw new CryptoError(CryptoErrorCode.OperationNotSupported, 'Key Manager does not support the \"decrypt\" operation.');\n }\n\n // Verify that at least one of the JOSE header objects is present.\n if (!protectedHeader && !sharedUnprotectedHeader && !unprotectedHeader) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe,\n 'JWE is missing the required JOSE header parameters. ' +\n 'Please provide at least one of the following: \"protectedHeader\", \"sharedUnprotectedHeader\", or \"unprotectedHeader\"'\n );\n }\n\n // Verify that the Plaintext is present.\n if (!(plaintext instanceof Uint8Array)) {\n throw new CryptoError(CryptoErrorCode.InvalidJwe, 'Plaintext is missing or not a byte array.');\n }\n\n // Per {@link https://www.rfc-editor.org/rfc/rfc7516#section-5.2 | RFC7516 Section 5.2}\n // the resulting JOSE Header MUST NOT contain duplicate Header Parameter names. In other words,\n // the same Header Parameter name MUST NOT occur in the `header`, `protected`, and\n // `unprotected` JSON object values that together comprise the JOSE Header.\n if (hasDuplicateProperties(protectedHeader, sharedUnprotectedHeader, unprotectedHeader)){\n throw new Error(\n 'Duplicate properties detected. Please ensure that each parameter is defined only once ' +\n 'across the JWE \"protectedHeader\", \"sharedUnprotectedHeader\", and \"unprotectedHeader\" objects.'\n );\n }\n\n // The JOSE Header is the union of the members of the JWE Protected Header (`protectedHeader`),\n // the JWE Shared Unprotected Header (`sharedUnprotectedHeader`), and the corresponding JWE\n // Per-Recipient Unprotected Header (`unprotectedHeader`).\n const joseHeader = { ...protectedHeader, ...sharedUnprotectedHeader, ...unprotectedHeader };\n\n if (!isValidJweHeader(joseHeader)) {\n throw new Error('JWE Header is missing required \"alg\" (Algorithm) and/or \"enc\" (Encryption) Header Parameters');\n }\n\n const { cek, encryptedKey } = await JweKeyManagement.encrypt({ key, joseHeader, keyManager, crypto });\n\n // If required for the Content Encryption Algorithm, generate a random JWE Initialization\n // Vector (IV) of the correct size; otherwise, let the JWE Initialization Vector be the empty\n // octet sequence.\n let iv: Uint8Array;\n switch (joseHeader.enc) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM':\n iv = CryptoUtils.randomBytes(12);\n break;\n default:\n iv = new Uint8Array(0);\n }\n\n // Compute the Encoded Protected Header value BASE64URL(UTF8(JWE Protected Header)). If the JWE\n // Protected Header is not present, let this value be the empty string.\n const encodedProtectedHeader = protectedHeader\n ? Convert.object(protectedHeader).toBase64Url()\n : '';\n\n // If the JWE Additional Authenticated Data (AAD) is present, the Additional Authenticated Data\n // input to the Content Encryption Algorithm is\n // ASCII(Encoded Protected Header || '.' || BASE64URL(JWE AAD)). If the JWE AAD is absent, the\n // Additional Authenticated Data is ASCII(BASE64URL(UTF8(JWE Protected Header))).\n let additionalData: Uint8Array;\n let encodedAad: string | undefined;\n if (additionalAuthenticatedData) {\n encodedAad = Convert.uint8Array(additionalAuthenticatedData).toBase64Url();\n additionalData = Convert.string(encodedProtectedHeader + '.' + encodedAad).toUint8Array();\n } else {\n additionalData = Convert.string(encodedProtectedHeader).toUint8Array();\n }\n\n // Encrypt the plaintext using the CEK, the JWE Initialization Vector, and the Additional\n // Authenticated Data value using the specified content encryption algorithm to create the JWE\n // Ciphertext value and the JWE Authentication Tag.\n const ciphertextWithTag = typeof cek === 'string'\n ? await keyManager.encrypt({ keyUri: cek, data: plaintext, iv, additionalData })\n : await crypto.encrypt({ key: cek, data: plaintext, iv, additionalData });\n const ciphertext = ciphertextWithTag.slice(0, -16);\n const authenticationTag = ciphertextWithTag.slice(-16);\n\n // Create the Flattened JWE JSON Serialization output, which is based upon the General syntax,\n // but flattens it, optimizing it for the single-recipient case. It flattens it by removing the\n // \"recipients\" member and instead placing those members defined for use in the \"recipients\"\n // array (the \"header\" and \"encrypted_key\" members) in the top-level JSON object (at the same\n // level as the \"ciphertext\" member).\n const jwe = new FlattenedJwe({\n ciphertext: Convert.uint8Array(ciphertext).toBase64Url(),\n });\n if (encryptedKey) jwe.encrypted_key = Convert.uint8Array(encryptedKey).toBase64Url();\n if (protectedHeader) jwe.protected = encodedProtectedHeader;\n if (sharedUnprotectedHeader) jwe.unprotected = sharedUnprotectedHeader;\n if (unprotectedHeader) jwe.header = unprotectedHeader;\n if (iv) jwe.iv = Convert.uint8Array(iv).toBase64Url();\n if (encodedAad) jwe.aad = encodedAad;\n if (authenticationTag) jwe.tag = Convert.uint8Array(authenticationTag).toBase64Url();\n\n return jwe;\n }\n}", "import type { Cipher, KeyWrapper } from '@enbox/crypto';\n\nimport type { KeyExporter, KeyImporter } from './types/key-io.js';\n\nexport function isCipher<EncryptInput, DecryptInput>(\n obj: unknown\n): obj is Cipher<EncryptInput, DecryptInput> {\n return (\n obj !== null && typeof obj === 'object'\n && 'encrypt' in obj && typeof obj.encrypt === 'function'\n && 'decrypt' in obj && typeof obj.decrypt === 'function'\n );\n}\n\nexport function isKeyExporter<ExportKeyInput, ExportKeyOutput>(\n obj: unknown\n): obj is KeyExporter<ExportKeyInput, ExportKeyOutput> {\n return (\n obj !== null && typeof obj === 'object'\n && 'exportKey' in obj && typeof obj.exportKey === 'function'\n );\n}\n\nexport function isKeyImporter<ImportKeyInput, ImportKeyExport>(\n obj: unknown\n): obj is KeyImporter<ImportKeyInput, ImportKeyExport> {\n return (\n obj !== null && typeof obj === 'object'\n && 'importKey' in obj && typeof obj.importKey === 'function'\n );\n}\n\nexport function isKeyWrapper<WrapKeyInput, UnwrapKeyInput>(\n obj: unknown\n): obj is KeyWrapper<WrapKeyInput, UnwrapKeyInput> {\n return (\n obj !== null && typeof obj === 'object'\n && 'wrapKey' in obj && typeof obj.wrapKey === 'function'\n && 'unwrapKey' in obj && typeof obj.unwrapKey === 'function'\n );\n}", "export function hasDuplicateProperties(...objects: Array<Record<string, any> | undefined>): boolean {\n const propertySet = new Set<string>();\n const objectsWithoutUndefined = objects.filter(Boolean); // Remove any undefined values\n\n for (const obj of objectsWithoutUndefined) {\n for (const key in obj) {\n if (propertySet.has(key)) {\n return true; // Return true if a duplicate property is found\n }\n propertySet.add(key);\n }\n }\n\n return false; // Return false if no duplicates are found\n}", "import { Convert } from '@enbox/common';\n\nimport type { Web5PlatformAgent } from './types/agent.js';\nimport type { IdentityMetadata } from './types/identity.js';\nimport type { AgentDataStore, DataStoreDeleteParams, DataStoreGetParams, DataStoreListParams, DataStoreSetParams } from './store-data.js';\n\nimport { DwnInterface } from './types/dwn.js';\nimport { IdentityProtocolDefinition } from './store-data-protocols.js';\nimport { TENANT_SEPARATOR } from './utils-internal.js';\nimport { DwnDataStore, InMemoryDataStore } from './store-data.js';\n\nexport function isIdentityMetadata(obj: unknown): obj is IdentityMetadata {\n // Validate that the given value is an object that has the necessary properties of IdentityMetadata.\n return !(!obj || typeof obj !== 'object' || obj === null)\n && 'name' in obj;\n}\n\nexport class DwnIdentityStore extends DwnDataStore<IdentityMetadata> implements AgentDataStore<IdentityMetadata> {\n protected name = 'DwnIdentityStore';\n\n protected _recordProtocolDefinition = IdentityProtocolDefinition;\n\n /**\n * Properties to use when writing and querying Identity records with the DWN store.\n */\n protected _recordProperties = {\n dataFormat : 'application/json',\n protocol : this._recordProtocolDefinition.protocol,\n protocolPath : 'identityMetadata',\n schema : this._recordProtocolDefinition.types.identityMetadata.schema,\n };\n\n public async delete(params: DataStoreDeleteParams): Promise<boolean> {\n return await super.delete(params);\n }\n\n public async get(params: DataStoreGetParams): Promise<IdentityMetadata | undefined> {\n return await super.get(params);\n }\n\n public async set(params: DataStoreSetParams<IdentityMetadata>): Promise<void> {\n return await super.set(params);\n }\n\n public async list(params: DataStoreListParams): Promise<IdentityMetadata[]> {\n return await super.list(params);\n }\n\n protected async getAllRecords({ agent, tenantDid }: {\n agent: Web5PlatformAgent;\n tenantDid: string;\n }): Promise<IdentityMetadata[]> {\n // Clear the index since it will be rebuilt from the query results.\n this._index.clear();\n\n // Query the DWN for all stored IdentityMetadata objects.\n const { reply: queryReply } = await agent.dwn.processRequest({\n author : tenantDid,\n target : tenantDid,\n messageType : DwnInterface.RecordsQuery,\n messageParams : { filter: { ...this._recordProperties } }\n });\n\n // Loop through all of the stored IdentityMetadata records and accumulate the objects.\n let storedIdentities: IdentityMetadata[] = [];\n for (const record of queryReply.entries ?? []) {\n // All IdentityMetadata records are expected to be small enough such that the data is returned\n // with the query results. If a record is returned without `encodedData` this is unexpected so\n // throw an error.\n if (!record.encodedData) {\n throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);\n }\n\n const storedIdentity = Convert.base64Url(record.encodedData).toObject() as IdentityMetadata;\n if (isIdentityMetadata(storedIdentity)) {\n // Update the index with the matching record ID.\n const indexKey = `${tenantDid}${TENANT_SEPARATOR}${storedIdentity.uri}`;\n this._index.set(indexKey, record.recordId);\n\n // Add the stored Identity to the cache.\n this._cache.set(record.recordId, storedIdentity);\n\n storedIdentities.push(storedIdentity);\n }\n }\n\n return storedIdentities;\n }\n}\n\nexport class InMemoryIdentityStore extends InMemoryDataStore<IdentityMetadata> implements AgentDataStore<IdentityMetadata> {\n protected name = 'InMemoryIdentityStore';\n\n public async delete(params: DataStoreDeleteParams): Promise<boolean> {\n return await super.delete(params);\n }\n\n public async get(params: DataStoreGetParams): Promise<IdentityMetadata | undefined> {\n return await super.get(params);\n }\n\n public async list(params: DataStoreListParams): Promise<IdentityMetadata[]> {\n return await super.list(params);\n }\n\n public async set(params: DataStoreSetParams<IdentityMetadata>): Promise<void> {\n return await super.set(params);\n }\n}", "import type { RequireOnly } from '@enbox/common';\n\nimport type { AgentDataStore } from './store-data.js';\nimport type { Web5PlatformAgent } from './types/agent.js';\nimport type { DidMethodCreateOptions } from './did-api.js';\nimport type { AgentKeyManager } from './types/key-manager.js';\nimport type { IdentityMetadata, PortableIdentity } from './types/identity.js';\n\nimport { BearerIdentity } from './bearer-identity.js';\nimport { isPortableDid } from './prototyping/dids/utils.js';\nimport { InMemoryIdentityStore } from './store-identity.js';\nimport { getDwnServiceEndpointUrls } from './utils.js';\nimport { PortableDid } from '@enbox/dids';\n\nexport interface IdentityApiParams<TKeyManager extends AgentKeyManager> {\n agent?: Web5PlatformAgent<TKeyManager>;\n\n store?: AgentDataStore<IdentityMetadata>;\n}\n\nexport interface IdentityCreateParams<\n TKeyManager = AgentKeyManager,\n TMethod extends keyof DidMethodCreateOptions<TKeyManager> = keyof DidMethodCreateOptions<TKeyManager>\n> {\n metadata: RequireOnly<IdentityMetadata, 'name'>;\n didMethod?: TMethod;\n didOptions?: DidMethodCreateOptions<TKeyManager>[TMethod];\n store?: boolean;\n}\n\nexport function isPortableIdentity(obj: unknown): obj is PortableIdentity {\n // Validate that the given value is an object that has the necessary properties of PortableIdentity.\n return !(!obj || typeof obj !== 'object' || obj === null)\n && 'did' in obj\n && 'metadata' in obj\n && isPortableDid(obj.did);\n}\n\n/**\n * This API is used to manage and interact with Identities within the Web5 Agent framework.\n * An Identity is a DID that is associated with metadata that describes the Identity.\n * Metadata includes A name(label), and whether or not the Identity is connected (delegated to act on the behalf of another DID).\n *\n * A KeyManager is used to manage the cryptographic keys associated with the Identities.\n *\n * The `DidApi` is used internally to create, store, and manage DIDs.\n * When a DWN Data Store is used, the Identity and DID information are stored under the Agent DID's tenant.\n */\nexport class AgentIdentityApi<TKeyManager extends AgentKeyManager = AgentKeyManager> {\n /**\n * Holds the instance of a `Web5PlatformAgent` that represents the current execution context for\n * the `AgentIdentityApi`. This agent is used to interact with other Web5 agent components. It's\n * vital to ensure this instance is set to correctly contextualize operations within the broader\n * Web5 Agent framework.\n */\n private _agent?: Web5PlatformAgent<TKeyManager>;\n\n private _store: AgentDataStore<IdentityMetadata>;\n\n constructor({ agent, store }: IdentityApiParams<TKeyManager> = {}) {\n this._agent = agent;\n\n // If `store` is not given, use an in-memory store by default.\n this._store = store ?? new InMemoryIdentityStore();\n }\n\n /**\n * Retrieves the `Web5PlatformAgent` execution context.\n *\n * @returns The `Web5PlatformAgent` instance that represents the current execution context.\n * @throws Will throw an error if the `agent` instance property is undefined.\n */\n get agent(): Web5PlatformAgent<TKeyManager> {\n if (this._agent === undefined) {\n throw new Error('AgentIdentityApi: Unable to determine agent execution context.');\n }\n\n return this._agent;\n }\n\n set agent(agent: Web5PlatformAgent<TKeyManager>) {\n this._agent = agent;\n }\n\n get tenant(): string {\n if (!this._agent) {\n throw new Error('AgentIdentityApi: The agent must be set to perform tenant specific actions.');\n }\n\n return this._agent.agentDid.uri;\n }\n\n public async create({ metadata, didMethod = 'dht', didOptions, store }:\n IdentityCreateParams<TKeyManager>\n ): Promise<BearerIdentity> {\n\n const bearerDid = await this.agent.did.create({\n method : didMethod,\n options : didOptions,\n tenant : this.tenant,\n store,\n });\n\n // Create the BearerIdentity object.\n const identity = new BearerIdentity({\n did : bearerDid,\n metadata : { ...metadata, uri: bearerDid.uri, tenant: this.tenant }\n });\n\n // Persist the Identity to the store, by default, unless the `store` option is set to false.\n if (store ?? true) {\n await this._store.set({\n id : identity.did.uri,\n data : identity.metadata,\n agent : this.agent,\n tenant : identity.metadata.tenant,\n preventDuplicates : false,\n useCache : true\n });\n }\n\n return identity;\n }\n\n public async export({ didUri }: {\n didUri: string;\n }): Promise<PortableIdentity> {\n const bearerIdentity = await this.get({ didUri });\n\n if (!bearerIdentity) {\n throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${didUri}`);\n }\n\n // If the Identity was found, return the Identity in a portable format, and if supported by the\n // Agent's key manager, the private key material.\n const portableIdentity = await bearerIdentity.export();\n\n return portableIdentity;\n }\n\n public async get({ didUri }: {\n didUri: string;\n }): Promise<BearerIdentity | undefined> {\n const storedIdentity = await this._store.get({ id: didUri, agent: this.agent, useCache: true });\n\n // If the Identity is not found in the store, return undefined.\n if (!storedIdentity) return undefined;\n\n // Retrieve the DID from the Agent's DID store using the tenant value from the stored\n // Identity's metadata.\n const storedDid = await this.agent.did.get({ didUri, tenant: storedIdentity.tenant });\n\n // If the Identity is present but the DID is not found, throw an error.\n if (!storedDid) {\n throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${didUri}`);\n }\n\n // Create the BearerIdentity object.\n const identity = new BearerIdentity({ did: storedDid, metadata: storedIdentity });\n\n return identity;\n }\n\n public async import({ portableIdentity }: {\n portableIdentity: PortableIdentity;\n }): Promise<BearerIdentity> {\n\n // set the tenant of the portable identity to the agent's tenant\n portableIdentity.metadata.tenant = this.tenant;\n\n // Import the PortableDid to the Agent's DID store.\n const storedDid = await this.agent.did.import({\n portableDid : portableIdentity.portableDid,\n tenant : portableIdentity.metadata.tenant\n });\n\n // Verify the DID is present in the Agent's DID store.\n if (!storedDid) {\n throw new Error(`AgentIdentityApi: Failed to import Identity: ${portableIdentity.metadata.uri}`);\n }\n\n // Create the BearerIdentity object.\n const identity = new BearerIdentity({ did: storedDid, metadata: portableIdentity.metadata });\n\n // Store the Identity metadata in the Agent's Identity store.\n await this._store.set({\n id : identity.did.uri,\n data : identity.metadata,\n agent : this.agent,\n tenant : identity.metadata.tenant,\n preventDuplicates : true,\n useCache : true\n });\n\n return identity;\n }\n\n public async list({ tenant }: {\n tenant?: string;\n } = {}): Promise<BearerIdentity[]> {\n // Retrieve the list of Identities from the Agent's Identity store.\n const storedIdentities = await this._store.list({ agent: this.agent, tenant });\n\n const identities = await Promise.all(storedIdentities.map(metadata => this.get({ didUri: metadata.uri })));\n\n return identities.filter(identity => typeof identity !== 'undefined') as BearerIdentity[];\n }\n\n public async delete({ didUri }:{\n didUri: string;\n }): Promise<void> {\n const storedIdentity = await this._store.get({ id: didUri, agent: this.agent, useCache: true });\n if (!storedIdentity) {\n throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${didUri}`);\n }\n\n // Delete the Identity from the Agent's Identity store.\n await this._store.delete({ id: didUri, agent: this.agent });\n }\n\n /**\n * Returns the DWN endpoints for the given DID.\n *\n * @param didUri - The DID URI to get the DWN endpoints for.\n * @returns An array of DWN endpoints.\n * @throws An error if the DID is not found, or no DWN service exists.\n */\n public getDwnEndpoints({ didUri }: { didUri: string; }): Promise<string[]> {\n return getDwnServiceEndpointUrls(didUri, this.agent.did);\n }\n\n /**\n * Sets the DWN endpoints for the given DID.\n *\n * @param didUri - The DID URI to set the DWN endpoints for.\n * @param endpoints - The array of DWN endpoints to set.\n * @throws An error if the DID is not found, or if an update cannot be performed.\n */\n public async setDwnEndpoints({ didUri, endpoints }: { didUri: string; endpoints: string[] }): Promise<void> {\n const bearerDid = await this.agent.did.get({ didUri });\n if (!bearerDid) {\n throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${didUri}`);\n }\n\n const portableDid = await bearerDid.export();\n const dwnService = portableDid.document.service?.find(service => service.id.endsWith('dwn'));\n if (dwnService) {\n // Update the existing DWN Service with the provided endpoints\n dwnService.serviceEndpoint = endpoints;\n } else {\n\n // create a DWN Service to add to the DID document\n const newDwnService = {\n id : 'dwn',\n type : 'DecentralizedWebNode',\n serviceEndpoint : endpoints,\n enc : '#enc',\n sig : '#sig'\n };\n\n // if no other services exist, create a new array with the DWN service\n if (!portableDid.document.service) {\n portableDid.document.service = [newDwnService];\n } else {\n // otherwise, push the new DWN service to the existing services\n portableDid.document.service.push(newDwnService);\n }\n }\n\n await this.agent.did.update({ portableDid, tenant: this.agent.agentDid.uri });\n }\n\n /**\n * Updates the Identity's metadata name field.\n *\n * @param didUri - The DID URI of the Identity to update.\n * @param name - The new name to set for the Identity.\n *\n * @throws An error if the Identity is not found, name is not provided, or no changes are detected.\n */\n public async setMetadataName({ didUri, name }: { didUri: string; name: string }): Promise<void> {\n if (!name) {\n throw new Error('AgentIdentityApi: Failed to set metadata name due to missing name value.');\n }\n\n const identity = await this.get({ didUri });\n if (!identity) {\n throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${didUri}`);\n }\n\n if (identity.metadata.name === name) {\n throw new Error('AgentIdentityApi: No changes detected.');\n }\n\n // Update the name in the Identity's metadata and store it\n await this._store.set({\n id : identity.did.uri,\n data : { ...identity.metadata, name },\n agent : this.agent,\n tenant : identity.metadata.tenant,\n updateExisting : true,\n useCache : true\n });\n }\n\n /**\n * Returns the connected Identity, if one is available.\n *\n * Accepts optional `connectedDid` parameter to filter the a specific connected identity,\n * if none is provided the first connected identity is returned.\n */\n public async connectedIdentity({ connectedDid }:{ connectedDid?: string } = {}): Promise<BearerIdentity | undefined> {\n const identities = await this.list();\n if (identities.length < 1) {\n return undefined;\n }\n\n // If a specific connected DID is provided, return the first identity that matches it.\n // Otherwise, return the first connected identity.\n return connectedDid ?\n identities.find(identity => identity.metadata.connectedDid === connectedDid) :\n identities.find(identity => identity.metadata.connectedDid !== undefined);\n }\n}", "import { PermissionGrant, PermissionGrantData, PermissionRequestData, PermissionRevocationData, PermissionsProtocol } from '@enbox/dwn-sdk-js';\nimport { Web5Agent } from './types/agent.js';\nimport { DwnDataEncodedRecordsWriteMessage, DwnInterface, DwnMessageParams, DwnMessagesPermissionScope, DwnPermissionGrant, DwnPermissionRequest, DwnPermissionScope, DwnProtocolPermissionScope, DwnRecordsPermissionScope, ProcessDwnRequest } from './types/dwn.js';\nimport { Convert, TtlCache } from '@enbox/common';\nimport { CreateGrantParams, CreateRequestParams, CreateRevocationParams, FetchPermissionRequestParams, FetchPermissionsParams, GetPermissionParams, IsGrantRevokedParams, PermissionGrantEntry, PermissionRequestEntry, PermissionRevocationEntry, PermissionsApi } from './types/permissions.js';\nimport { isRecordsType } from './dwn-api.js';\n\nexport class AgentPermissionsApi implements PermissionsApi {\n\n /** cache for fetching a permission {@link PermissionGrant}, keyed by a specific MessageType and protocol */\n private _cachedPermissions: TtlCache<string, PermissionGrantEntry> = new TtlCache({ ttl: 60 * 1000 });\n\n private _agent?: Web5Agent;\n\n get agent(): Web5Agent {\n if (!this._agent) {\n throw new Error('AgentPermissionsApi: Agent is not set');\n }\n return this._agent;\n }\n\n set agent(agent:Web5Agent) {\n this._agent = agent;\n }\n\n constructor({ agent }: { agent?: Web5Agent } = {}) {\n this._agent = agent;\n }\n\n async getPermissionForRequest({\n connectedDid,\n delegateDid,\n delegate,\n messageType,\n protocol,\n cached = false\n }: GetPermissionParams): Promise<PermissionGrantEntry> {\n // Currently we only support finding grants based on protocols\n // A different approach may be necessary when we introduce `protocolPath` and `contextId` specific impersonation\n const cacheKey = [ connectedDid, delegateDid, messageType, protocol ].join('~');\n const cachedGrant = cached ? this._cachedPermissions.get(cacheKey) : undefined;\n if (cachedGrant) {\n return cachedGrant;\n }\n\n const permissionGrants = await this.fetchGrants({\n author : delegateDid,\n target : delegateDid,\n grantor : connectedDid,\n grantee : delegateDid,\n });\n\n // get the delegate grants that match the messageParams and are associated with the connectedDid as the grantor\n const grant = await AgentPermissionsApi.matchGrantFromArray(\n connectedDid,\n delegateDid,\n { messageType, protocol },\n permissionGrants,\n delegate\n );\n\n if (!grant) {\n throw new Error(`CachedPermissions: No permissions found for ${messageType}: ${protocol}`);\n }\n\n this._cachedPermissions.set(cacheKey, grant);\n return grant;\n }\n\n async fetchGrants({\n author,\n target,\n grantee,\n grantor,\n protocol,\n remote = false\n }: FetchPermissionsParams): Promise<PermissionGrantEntry[]> {\n\n // filter by a protocol using tags if provided\n const tags = protocol ? { protocol } : undefined;\n\n const params: ProcessDwnRequest<DwnInterface.RecordsQuery> = {\n author : author,\n target : target,\n messageType : DwnInterface.RecordsQuery,\n messageParams : {\n filter: {\n author : grantor, // the author of the grant would be the grantor\n recipient : grantee, // the recipient of the grant would be the grantee\n protocol : PermissionsProtocol.uri,\n protocolPath : PermissionsProtocol.grantPath,\n tags\n }\n }\n };\n\n const { reply } = remote ? await this.agent.sendDwnRequest(params) : await this.agent.processDwnRequest(params);\n if (reply.status.code !== 200) {\n throw new Error(`PermissionsApi: Failed to fetch grants: ${reply.status.detail}`);\n }\n\n const grants:PermissionGrantEntry[] = [];\n for (const entry of reply.entries! as DwnDataEncodedRecordsWriteMessage[]) {\n // TODO: Check for revocation status based on a request parameter and filter out revoked grants\n const grant = await DwnPermissionGrant.parse(entry);\n grants.push({ grant, message: entry });\n }\n\n return grants;\n }\n\n async fetchRequests({\n author,\n target,\n protocol,\n remote = false\n }:FetchPermissionRequestParams):Promise<PermissionRequestEntry[]> {\n // filter by a protocol using tags if provided\n const tags = protocol ? { protocol } : undefined;\n\n const params: ProcessDwnRequest<DwnInterface.RecordsQuery> = {\n author : author,\n target : target,\n messageType : DwnInterface.RecordsQuery,\n messageParams : {\n filter: {\n protocol : PermissionsProtocol.uri,\n protocolPath : PermissionsProtocol.requestPath,\n tags\n }\n }\n };\n\n const { reply } = remote ? await this.agent.sendDwnRequest(params) : await this.agent.processDwnRequest(params);\n if (reply.status.code !== 200) {\n throw new Error(`PermissionsApi: Failed to fetch requests: ${reply.status.detail}`);\n }\n\n const requests: PermissionRequestEntry[] = [];\n for (const entry of reply.entries! as DwnDataEncodedRecordsWriteMessage[]) {\n const request = await DwnPermissionRequest.parse(entry);\n requests.push({ request, message: entry });\n }\n\n return requests;\n }\n\n async isGrantRevoked({\n author,\n target,\n grantRecordId,\n remote = false\n }: IsGrantRevokedParams): Promise<boolean> {\n const params: ProcessDwnRequest<DwnInterface.RecordsRead> = {\n author,\n target,\n messageType : DwnInterface.RecordsRead,\n messageParams : {\n filter: {\n parentId : grantRecordId,\n protocol : PermissionsProtocol.uri,\n protocolPath : PermissionsProtocol.revocationPath,\n }\n }\n };\n\n const { reply: revocationReply } = remote ? await this.agent.sendDwnRequest(params) : await this.agent.processDwnRequest(params);\n if (revocationReply.status.code === 404) {\n // no revocation found, the grant is not revoked\n return false;\n } else if (revocationReply.status.code === 200) {\n // a revocation was found, the grant is revoked\n return true;\n }\n\n throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${revocationReply.status.detail}`);\n }\n\n async createGrant(params: CreateGrantParams): Promise<PermissionGrantEntry> {\n const { author, store = false, delegated = false, ...createGrantParams } = params;\n\n let tags = undefined;\n if (PermissionsProtocol.hasProtocolScope(createGrantParams.scope)) {\n tags = { protocol: createGrantParams.scope.protocol };\n }\n\n const permissionGrantData: PermissionGrantData = {\n dateExpires : createGrantParams.dateExpires,\n requestId : createGrantParams.requestId,\n description : createGrantParams.description,\n delegated,\n scope : createGrantParams.scope\n };\n\n const permissionsGrantBytes = Convert.object(permissionGrantData).toUint8Array();\n\n const messageParams: DwnMessageParams[DwnInterface.RecordsWrite] = {\n recipient : createGrantParams.grantedTo,\n protocol : PermissionsProtocol.uri,\n protocolPath : PermissionsProtocol.grantPath,\n dataFormat : 'application/json',\n tags\n };\n\n const { reply, message } = await this.agent.processDwnRequest({\n store,\n author,\n target : author,\n messageType : DwnInterface.RecordsWrite,\n messageParams,\n dataStream : new Blob([ permissionsGrantBytes ])\n });\n\n if (reply.status.code !== 202) {\n throw new Error(`PermissionsApi: Failed to create grant: ${reply.status.detail}`);\n }\n\n const dataEncodedMessage: DwnDataEncodedRecordsWriteMessage = {\n ...message!,\n encodedData: Convert.uint8Array(permissionsGrantBytes).toBase64Url()\n };\n\n const grant = await DwnPermissionGrant.parse(dataEncodedMessage);\n\n return { grant, message: dataEncodedMessage };\n }\n\n async createRequest(params: CreateRequestParams): Promise<PermissionRequestEntry> {\n const { author, store = false, delegated = false, ...createGrantParams } = params;\n\n let tags = undefined;\n if (PermissionsProtocol.hasProtocolScope(createGrantParams.scope)) {\n tags = { protocol: createGrantParams.scope.protocol };\n }\n\n const permissionRequestData: PermissionRequestData = {\n description : createGrantParams.description,\n delegated,\n scope : createGrantParams.scope\n };\n\n const permissionRequestBytes = Convert.object(permissionRequestData).toUint8Array();\n\n const messageParams: DwnMessageParams[DwnInterface.RecordsWrite] = {\n protocol : PermissionsProtocol.uri,\n protocolPath : PermissionsProtocol.requestPath,\n dataFormat : 'application/json',\n tags\n };\n\n const { reply, message } = await this.agent.processDwnRequest({\n store,\n author,\n target : author,\n messageType : DwnInterface.RecordsWrite,\n messageParams,\n dataStream : new Blob([ permissionRequestBytes ])\n });\n\n if (reply.status.code !== 202) {\n throw new Error(`PermissionsApi: Failed to create request: ${reply.status.detail}`);\n }\n\n const dataEncodedMessage: DwnDataEncodedRecordsWriteMessage = {\n ...message!,\n encodedData: Convert.uint8Array(permissionRequestBytes).toBase64Url()\n };\n\n const request = await DwnPermissionRequest.parse(dataEncodedMessage);\n\n return { request, message: dataEncodedMessage };\n }\n\n async createRevocation(params: CreateRevocationParams): Promise<PermissionRevocationEntry> {\n const { author, store = false, grant, description } = params;\n\n const revokeData: PermissionRevocationData = { description };\n\n const permissionRevocationBytes = Convert.object(revokeData).toUint8Array();\n\n let tags = undefined;\n if (PermissionsProtocol.hasProtocolScope(grant.scope)) {\n tags = { protocol: grant.scope.protocol };\n }\n\n const messageParams: DwnMessageParams[DwnInterface.RecordsWrite] = {\n parentContextId : grant.id,\n protocol : PermissionsProtocol.uri,\n protocolPath : PermissionsProtocol.revocationPath,\n dataFormat : 'application/json',\n tags\n };\n\n const { reply, message } = await this.agent.processDwnRequest({\n store,\n author,\n target : author,\n messageType : DwnInterface.RecordsWrite,\n messageParams,\n dataStream : new Blob([ permissionRevocationBytes ])\n });\n\n if (reply.status.code !== 202) {\n throw new Error(`PermissionsApi: Failed to create revocation: ${reply.status.detail}`);\n }\n\n const dataEncodedMessage: DwnDataEncodedRecordsWriteMessage = {\n ...message!,\n encodedData: Convert.uint8Array(permissionRevocationBytes).toBase64Url()\n };\n\n return { message: dataEncodedMessage };\n }\n\n async clear():Promise<void> {\n this._cachedPermissions.clear();\n }\n\n /**\n * Matches the appropriate grant from an array of grants based on the provided parameters.\n *\n * @param delegated if true, only delegated grants are turned, if false all grants are returned including delegated ones.\n */\n static async matchGrantFromArray<T extends DwnInterface>(\n grantor: string,\n grantee: string,\n messageParams: {\n messageType: T,\n protocol?: string,\n protocolPath?: string,\n contextId?: string,\n },\n grants: PermissionGrantEntry[],\n delegated: boolean = false\n ): Promise<PermissionGrantEntry | undefined> {\n for (const entry of grants) {\n const { grant, message } = entry;\n if (delegated === true && grant.delegated !== true) {\n continue;\n }\n const { messageType, protocol, protocolPath, contextId } = messageParams;\n\n if (this.matchScopeFromGrant(grantor, grantee, messageType, grant, protocol, protocolPath, contextId)) {\n return { grant, message };\n }\n }\n }\n\n private static matchScopeFromGrant<T extends DwnInterface>(\n grantor: string,\n grantee: string,\n messageType: T,\n grant: PermissionGrant,\n protocol?: string,\n protocolPath?: string,\n contextId?: string\n ): boolean {\n // Check if the grant matches the provided parameters\n if (grant.grantee !== grantee || grant.grantor !== grantor) {\n return false;\n }\n\n const scope = grant.scope;\n const scopeMessageType = scope.interface + scope.method;\n if (scopeMessageType === messageType) {\n if (isRecordsType(messageType)) {\n const recordScope = scope as DwnRecordsPermissionScope;\n if (recordScope.protocol !== protocol) {\n return false;\n }\n\n // If the grant scope is not restricted to a specific context or protocol path, it is unrestricted and can be used\n if (this.isUnrestrictedProtocolScope(recordScope)) {\n return true;\n }\n\n // protocolPath and contextId are mutually exclusive\n // If the permission is scoped to a protocolPath and the permissionParams matches that path, this grant can be used\n if (recordScope.protocolPath !== undefined && recordScope.protocolPath === protocolPath) {\n return true;\n }\n\n // If the permission is scoped to a contextId and the permissionParams starts with that contextId, this grant can be used\n if (recordScope.contextId !== undefined && contextId?.startsWith(recordScope.contextId)) {\n return true;\n }\n } else {\n const messagesScope = scope as DwnMessagesPermissionScope | DwnProtocolPermissionScope;\n // Checks for unrestricted protocol scope, if no protocol is defined in the scope it is unrestricted\n if (messagesScope.protocol === undefined) {\n return true;\n }\n\n if (messagesScope.protocol !== protocol) {\n return false;\n }\n\n return this.isUnrestrictedProtocolScope(messagesScope);\n }\n }\n\n return false;\n }\n\n private static isUnrestrictedProtocolScope(scope: DwnPermissionScope & { contextId?: string, protocolPath?: string }): boolean {\n return scope.contextId === undefined && scope.protocolPath === undefined;\n }\n}", "import { CryptoUtils } from '@enbox/crypto';\n\n\nimport type { DwnRpc, DwnRpcRequest, DwnRpcResponse } from './prototyping/clients/dwn-rpc-types.js';\nimport type { DwnServerInfoRpc, ServerInfo } from './prototyping/clients/server-info-types.js';\nimport type { JsonRpcResponse } from './prototyping/clients/json-rpc.js';\n\nimport { createJsonRpcRequest } from './prototyping/clients/json-rpc.js';\nimport { HttpDwnRpcClient } from './prototyping/clients/http-dwn-rpc-client.js';\nimport { WebSocketDwnRpcClient } from './prototyping/clients/web-socket-clients.js';\n\n/**\n * Interface that can be implemented to communicate with {@link Web5Agent | Web5 Agent}\n * implementations via JSON-RPC.\n */\nexport interface DidRpc {\n get transportProtocols(): string[]\n sendDidRequest(request: DidRpcRequest): Promise<DidRpcResponse>\n}\n\nexport enum DidRpcMethod {\n Create = 'did.create',\n Resolve = 'did.resolve'\n}\n\nexport type DidRpcRequest = {\n data: string;\n method: DidRpcMethod;\n url: string;\n}\n\nexport type DidRpcResponse = {\n data?: string;\n ok: boolean;\n status: RpcStatus;\n}\n\nexport type RpcStatus = {\n code: number;\n message: string;\n};\n\nexport interface Web5Rpc extends DwnRpc, DidRpc, DwnServerInfoRpc {}\n\n/**\n * Client used to communicate with Dwn Servers\n */\nexport class Web5RpcClient implements Web5Rpc {\n private transportClients: Map<string, Web5Rpc>;\n\n constructor(clients: Web5Rpc[] = []) {\n this.transportClients = new Map();\n\n // include http and socket clients as default.\n // can be overwritten for 'http:', 'https:', 'ws: or ':wss' if instantiated with other clients.\n clients = [new HttpWeb5RpcClient(), new WebSocketWeb5RpcClient(), ...clients];\n\n for (let client of clients) {\n for (let transportScheme of client.transportProtocols) {\n this.transportClients.set(transportScheme, client);\n }\n }\n }\n\n get transportProtocols(): string[] {\n return Array.from(this.transportClients.keys());\n }\n\n async sendDidRequest(request: DidRpcRequest): Promise<DidRpcResponse> {\n // URL() will throw if provided `url` is invalid.\n const url = new URL(request.url);\n\n const transportClient = this.transportClients.get(url.protocol);\n if (!transportClient) {\n const error = new Error(`no ${url.protocol} transport client available`);\n error.name = 'NO_TRANSPORT_CLIENT';\n\n throw error;\n }\n\n return transportClient.sendDidRequest(request);\n }\n\n sendDwnRequest(request: DwnRpcRequest): Promise<DwnRpcResponse> {\n // will throw if url is invalid\n const url = new URL(request.dwnUrl);\n\n const transportClient = this.transportClients.get(url.protocol);\n if (!transportClient) {\n const error = new Error(`no ${url.protocol} transport client available`);\n error.name = 'NO_TRANSPORT_CLIENT';\n\n throw error;\n }\n\n return transportClient.sendDwnRequest(request);\n }\n\n async getServerInfo(dwnUrl: string): Promise<ServerInfo> {\n // will throw if url is invalid\n const url = new URL(dwnUrl);\n\n const transportClient = this.transportClients.get(url.protocol);\n if(!transportClient) {\n const error = new Error(`no ${url.protocol} transport client available`);\n error.name = 'NO_TRANSPORT_CLIENT';\n\n throw error;\n }\n\n return transportClient.getServerInfo(dwnUrl);\n }\n}\n\nexport class HttpWeb5RpcClient extends HttpDwnRpcClient implements Web5Rpc {\n async sendDidRequest(request: DidRpcRequest): Promise<DidRpcResponse> {\n const requestId = CryptoUtils.randomUuid();\n const jsonRpcRequest = createJsonRpcRequest(requestId, request.method, {\n data: request.data\n });\n\n const httpRequest = new Request(request.url, {\n method : 'POST',\n headers : {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(jsonRpcRequest),\n });\n\n let jsonRpcResponse: JsonRpcResponse;\n\n try {\n const response = await fetch(httpRequest);\n\n if (response.ok) {\n jsonRpcResponse = await response.json();\n\n // If the response is an error, throw an error.\n if (jsonRpcResponse.error) {\n const { code, message } = jsonRpcResponse.error;\n throw new Error(`JSON RPC (${code}) - ${message}`);\n }\n } else {\n throw new Error(`HTTP (${response.status}) - ${response.statusText}`);\n }\n } catch (error: any) {\n throw new Error(`Error encountered while processing response from ${request.url}: ${error.message}`);\n }\n\n return jsonRpcResponse.result as DidRpcResponse;\n }\n}\n\nexport class WebSocketWeb5RpcClient extends WebSocketDwnRpcClient implements Web5Rpc {\n async sendDidRequest(_request: DidRpcRequest): Promise<DidRpcResponse> {\n throw new Error(`not implemented for transports [${this.transportProtocols.join(', ')}]`);\n }\n\n async getServerInfo(_dwnUrl: string): Promise<ServerInfo> {\n throw new Error(`not implemented for transports [${this.transportProtocols.join(', ')}]`);\n }\n}", "export type JsonRpcId = string | number | null;\nexport type JsonRpcParams = any;\nexport type JsonRpcVersion = '2.0';\n\nexport interface JsonRpcRequest {\n jsonrpc: JsonRpcVersion;\n id?: JsonRpcId;\n /** JSON RPC Subscription Extension Parameters */\n subscription?: { id: JsonRpcId }\n method: string;\n params?: any;\n}\n\nexport interface JsonRpcError {\n code: JsonRpcErrorCodes;\n message: string;\n data?: any;\n}\n\nexport enum JsonRpcErrorCodes {\n // JSON-RPC 2.0 pre-defined errors\n InvalidRequest = -32600,\n MethodNotFound = -32601,\n InvalidParams = -32602,\n InternalError = -32603,\n ParseError = -32700,\n TransportError = -32300,\n\n // App defined errors\n BadRequest = -50400, // equivalent to HTTP Status 400\n Unauthorized = -50401, // equivalent to HTTP Status 401\n Forbidden = -50403, // equivalent to HTTP Status 403,\n Conflict = -50409, // equivalent to HTTP Status 409\n}\n\nexport type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;\n\nexport interface JsonRpcSuccessResponse {\n jsonrpc: JsonRpcVersion;\n id: JsonRpcId;\n result: any;\n error?: never;\n}\n\nexport interface JsonRpcErrorResponse {\n jsonrpc: JsonRpcVersion;\n id: JsonRpcId;\n result?: never;\n error: JsonRpcError;\n}\n\nexport const createJsonRpcErrorResponse = (\n id: JsonRpcId,\n code: JsonRpcErrorCodes,\n message: string,\n data?: any,\n): JsonRpcErrorResponse => {\n const error: JsonRpcError = { code, message, data };\n return {\n jsonrpc: '2.0',\n id,\n error,\n };\n};\n\nexport const createJsonRpcRequest = (\n id: JsonRpcId,\n method: string,\n params?: JsonRpcParams,\n): JsonRpcRequest => {\n return {\n jsonrpc: '2.0',\n id,\n method,\n params,\n };\n};\n\nexport const createJsonRpcSubscriptionRequest = (\n id: JsonRpcId,\n method: string,\n subscriptionId: JsonRpcId,\n params?: any\n): JsonRpcRequest => {\n return {\n jsonrpc : '2.0',\n id,\n method : `rpc.subscribe.${method}`,\n params,\n subscription : {\n id: subscriptionId,\n }\n };\n};\n\nexport const createJsonRpcSuccessResponse = (\n id: JsonRpcId,\n result: any,\n): JsonRpcSuccessResponse => {\n return {\n jsonrpc: '2.0',\n id,\n result,\n };\n};\n\nexport function parseJson(text: string): object | null {\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}", "import type { JsonRpcResponse } from './json-rpc.js';\nimport type { DwnRpc, DwnRpcRequest, DwnRpcResponse } from './dwn-rpc-types.js';\n\nimport { createJsonRpcRequest, parseJson } from './json-rpc.js';\nimport { CryptoUtils } from '@enbox/crypto';\nimport { DwnServerInfoCache, ServerInfo } from './server-info-types.js';\nimport { DwnServerInfoCacheMemory } from './dwn-server-info-cache-memory.js';\n\n/**\n * HTTP client that can be used to communicate with Dwn Servers\n */\nexport class HttpDwnRpcClient implements DwnRpc {\n private serverInfoCache: DwnServerInfoCache;\n constructor(serverInfoCache?: DwnServerInfoCache) {\n this.serverInfoCache = serverInfoCache ?? new DwnServerInfoCacheMemory();\n }\n\n get transportProtocols() { return ['http:', 'https:']; }\n\n async sendDwnRequest(request: DwnRpcRequest): Promise<DwnRpcResponse> {\n const requestId = CryptoUtils.randomUuid();\n const jsonRpcRequest = createJsonRpcRequest(requestId, 'dwn.processMessage', {\n target : request.targetDid,\n message : request.message\n });\n\n const fetchOpts = {\n method : 'POST',\n headers : {\n 'dwn-request': JSON.stringify(jsonRpcRequest)\n }\n };\n\n if (request.data) {\n // @ts-expect-error TODO: REMOVE\n fetchOpts.headers['content-type'] = 'application/octet-stream';\n // @ts-expect-error TODO: REMOVE\n fetchOpts['body'] = request.data;\n }\n\n const resp = await fetch(request.dwnUrl, fetchOpts);\n let dwnRpcResponse: JsonRpcResponse;\n\n // check to see if response is in header first. if it is, that means the response is a ReadableStream\n let dataStream;\n const { headers } = resp;\n if (headers.has('dwn-response')) {\n // @ts-expect-error TODO: REMOVE\n const jsonRpcResponse = parseJson(headers.get('dwn-response')) as JsonRpcResponse;\n\n if (jsonRpcResponse == null) {\n throw new Error(`failed to parse json rpc response. dwn url: ${request.dwnUrl}`);\n }\n\n dataStream = resp.body;\n dwnRpcResponse = jsonRpcResponse;\n } else {\n // TODO: wonder if i need to try/catch this?\n const responseBody = await resp.text();\n dwnRpcResponse = JSON.parse(responseBody);\n }\n\n if (dwnRpcResponse.error) {\n const { code, message } = dwnRpcResponse.error;\n throw new Error(`(${code}) - ${message}`);\n }\n\n const { reply } = dwnRpcResponse.result;\n if (dataStream && reply.record) {\n reply.record.data = dataStream;\n } else if (dataStream && reply.entry) {\n reply.entry.data = dataStream;\n }\n\n return reply as DwnRpcResponse;\n }\n\n async getServerInfo(dwnUrl: string): Promise<ServerInfo> {\n const serverInfo = await this.serverInfoCache.get(dwnUrl);\n if (serverInfo) {\n return serverInfo;\n }\n\n const url = new URL(dwnUrl);\n\n // add `/info` to the dwn server url path\n url.pathname.endsWith('/') ? url.pathname += 'info' : url.pathname += '/info';\n\n try {\n const response = await fetch(url.toString());\n if(response.ok) {\n const results = await response.json() as ServerInfo;\n\n // explicitly return and cache only the desired properties.\n const serverInfo = {\n registrationRequirements : results.registrationRequirements,\n maxFileSize : results.maxFileSize,\n webSocketSupport : results.webSocketSupport,\n };\n this.serverInfoCache.set(dwnUrl, serverInfo);\n\n return serverInfo;\n } else {\n throw new Error(`HTTP (${response.status}) - ${response.statusText}`);\n }\n } catch(error: any) {\n throw new Error(`Error encountered while processing response from ${url.toString()}: ${error.message}`);\n }\n }\n}\n", "\nimport ms from 'ms';\nimport { TtlCache } from '@enbox/common';\nimport { DwnServerInfoCache, ServerInfo } from './server-info-types.js';\n\n/**\n * Configuration parameters for creating an in-memory cache for DWN ServerInfo entries.\n *\n * Allows customization of the cache time-to-live (TTL) setting.\n */\nexport type DwnServerInfoCacheMemoryParams = {\n /**\n * Optional. The time-to-live for cache entries, expressed as a string (e.g., '1h', '15m').\n * Determines how long a cache entry should remain valid before being considered expired.\n *\n * Defaults to '15m' if not specified.\n */\n ttl?: string;\n}\n\nexport class DwnServerInfoCacheMemory implements DwnServerInfoCache {\n private cache: TtlCache<string, ServerInfo>;\n\n constructor({ ttl = '15m' }: DwnServerInfoCacheMemoryParams= {}) {\n this.cache = new TtlCache({ ttl: ms(ttl) });\n }\n\n /**\n * Retrieves a DWN ServerInfo entry from the cache.\n *\n * If the cached item has exceeded its TTL, it's scheduled for deletion and undefined is returned.\n *\n * @param dwnUrl - The DWN URL endpoint string used as the key for getting the entry.\n * @returns The cached DWN ServerInfo entry or undefined if not found or expired.\n */\n public async get(dwnUrl: string): Promise<ServerInfo| undefined> {\n return this.cache.get(dwnUrl);\n }\n\n /**\n * Stores a DWN ServerInfo entry in the cache with a TTL.\n *\n * @param dwnUrl - The DWN URL endpoint string used as the key for storing the entry.\n * @param value - The DWN ServerInfo entry to be cached.\n * @returns A promise that resolves when the operation is complete.\n */\n public async set(dwnUrl: string, value: ServerInfo): Promise<void> {\n this.cache.set(dwnUrl, value);\n }\n\n /**\n * Deletes a DWN ServerInfo entry from the cache.\n *\n * @param dwnUrl - The DWN URL endpoint string used as the key for deletion.\n * @returns A promise that resolves when the operation is complete.\n */\n public async delete(dwnUrl: string): Promise<void> {\n this.cache.delete(dwnUrl);\n }\n\n /**\n * Clears all entries from the cache.\n *\n * @returns A promise that resolves when the operation is complete.\n */\n public async clear(): Promise<void> {\n this.cache.clear();\n }\n\n /**\n * This method is a no-op but exists to be consistent with other DWN ServerInfo Cache\n * implementations.\n *\n * @returns A promise that resolves immediately.\n */\n public async close(): Promise<void> {\n // No-op since there is no underlying store to close.\n }\n}", "import type { DwnRpc, DwnRpcRequest, DwnRpcResponse, DwnSubscriptionHandler } from './dwn-rpc-types.js';\nimport type { GenericMessage, MessageSubscription, UnionMessageReply } from '@enbox/dwn-sdk-js';\n\nimport { CryptoUtils } from '@enbox/crypto';\nimport { createJsonRpcRequest, createJsonRpcSubscriptionRequest } from './json-rpc.js';\nimport { JsonRpcSocket, JsonRpcSocketOptions } from './json-rpc-socket.js';\n\ninterface SocketConnection {\n socket: JsonRpcSocket;\n subscriptions: Map<string, MessageSubscription>;\n}\n\nexport class WebSocketDwnRpcClient implements DwnRpc {\n public get transportProtocols() { return ['ws:', 'wss:']; }\n // a map of dwn host to WebSocket connection\n private static connections = new Map<string, SocketConnection>();\n\n async sendDwnRequest(request: DwnRpcRequest, jsonRpcSocketOptions?: JsonRpcSocketOptions): Promise<DwnRpcResponse> {\n\n // validate that the dwn URL provided is a valid WebSocket URL\n const url = new URL(request.dwnUrl);\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n throw new Error(`Invalid websocket protocol ${url.protocol}`);\n }\n\n // check if there is already a connection to this host, if it does not exist, initiate a new connection\n const hasConnection = WebSocketDwnRpcClient.connections.has(url.host);\n if (!hasConnection) {\n try {\n const socket = await JsonRpcSocket.connect(url.toString(), jsonRpcSocketOptions);\n const subscriptions = new Map();\n WebSocketDwnRpcClient.connections.set(url.host, { socket, subscriptions });\n } catch(error) {\n throw new Error(`Error connecting to ${url.host}: ${(error as Error).message}`);\n }\n }\n\n const connection = WebSocketDwnRpcClient.connections.get(url.host)!;\n const { targetDid, message, subscriptionHandler } = request;\n\n if (subscriptionHandler) {\n return WebSocketDwnRpcClient.subscriptionRequest(connection, targetDid, message, subscriptionHandler);\n }\n\n return WebSocketDwnRpcClient.processMessage(connection, targetDid, message);\n }\n\n private static async processMessage(connection: SocketConnection, target: string, message: GenericMessage): Promise<DwnRpcResponse> {\n const requestId = CryptoUtils.randomUuid();\n const request = createJsonRpcRequest(requestId, 'dwn.processMessage', { target, message });\n\n const { socket } = connection;\n const response = await socket.request(request);\n\n const { error, result } = response;\n if (error !== undefined) {\n throw new Error(`error sending DWN request: ${error.message}`);\n }\n\n return result.reply as DwnRpcResponse;\n }\n\n private static async subscriptionRequest(connection: SocketConnection, target:string, message: GenericMessage, messageHandler: DwnSubscriptionHandler): Promise<DwnRpcResponse> {\n const requestId = CryptoUtils.randomUuid();\n const subscriptionId = CryptoUtils.randomUuid();\n const request = createJsonRpcSubscriptionRequest(requestId, 'dwn.processMessage', subscriptionId, { target, message });\n\n const { socket, subscriptions } = connection;\n const { response, close } = await socket.subscribe(request, (response) => {\n const { result, error } = response;\n if (error) {\n\n // if there is an error, close the subscription and delete it from the connection\n const subscription = subscriptions.get(subscriptionId);\n if (subscription) {\n subscription.close();\n }\n\n subscriptions.delete(subscriptionId);\n return;\n }\n\n const { event } = result;\n messageHandler(event);\n });\n\n const { error, result } = response;\n if (error) {\n throw new Error(`could not subscribe via jsonrpc socket: ${error.message}`);\n }\n\n const { reply } = result as { reply: UnionMessageReply };\n if (reply.subscription && close) {\n subscriptions.set(subscriptionId, { ...reply.subscription, close });\n reply.subscription.close = close;\n }\n\n return reply;\n }\n}", "import { CryptoUtils } from '@enbox/crypto';\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport { JsonRpcId, JsonRpcRequest, JsonRpcResponse, createJsonRpcSubscriptionRequest, parseJson } from './json-rpc.js';\n\n// These were arbitrarily chosen, but can be modified via connect options\nconst CONNECT_TIMEOUT = 3_000;\nconst RESPONSE_TIMEOUT = 30_000;\n\nexport interface JsonRpcSocketOptions {\n /** socket connection timeout in milliseconds */\n connectTimeout?: number;\n /** response timeout for rpc requests in milliseconds */\n responseTimeout?: number;\n /** optional connection close handler */\n onclose?: () => void;\n /** optional socket error handler */\n onerror?: (error?: any) => void;\n}\n\n/**\n * JSON RPC Socket Client for WebSocket request/response and long-running subscriptions.\n *\n * NOTE: This is temporarily copied over from https://github.com/TBD54566975/dwn-server/blob/main/src/json-rpc-socket.ts\n * This was done in order to avoid taking a dependency on the `dwn-server`, until a future time when there will be a `clients` package.\n */\nexport class JsonRpcSocket {\n private messageHandlers: Map<JsonRpcId, (event: { data: any }) => void> = new Map();\n\n private constructor(private socket: IsomorphicWebSocket, private responseTimeout: number) {}\n\n static async connect(url: string, options: JsonRpcSocketOptions = {}): Promise<JsonRpcSocket> {\n const { connectTimeout = CONNECT_TIMEOUT, responseTimeout = RESPONSE_TIMEOUT, onclose, onerror } = options;\n\n const socket = new IsomorphicWebSocket(url);\n\n if (!onclose) {\n socket.onclose = ():void => {\n console.info(`JSON RPC Socket close ${url}`);\n };\n } else {\n socket.onclose = onclose;\n }\n\n if (!onerror) {\n socket.onerror = (error?: any):void => {\n console.error(`JSON RPC Socket error ${url}`, error);\n };\n } else {\n socket.onerror = onerror;\n }\n\n return new Promise<JsonRpcSocket>((resolve, reject) => {\n socket.addEventListener('open', () => {\n const jsonRpcSocket = new JsonRpcSocket(socket, responseTimeout);\n\n socket.addEventListener('message', (event: { data: any }) => {\n const jsonRpcResponse = parseJson(event.data) as JsonRpcResponse;\n const handler = jsonRpcSocket.messageHandlers.get(jsonRpcResponse.id);\n if (handler) {\n handler(event);\n }\n });\n\n resolve(jsonRpcSocket);\n });\n\n socket.addEventListener('error', (error: any) => {\n reject(error);\n });\n\n setTimeout(() => reject, connectTimeout);\n });\n }\n\n close(): void {\n this.socket.close();\n }\n\n /**\n * Sends a JSON-RPC request through the socket and waits for a single response.\n */\n async request(request: JsonRpcRequest): Promise<JsonRpcResponse> {\n return new Promise((resolve, reject) => {\n request.id ??= CryptoUtils.randomUuid();\n\n const handleResponse = (event: { data: any }):void => {\n const jsonRpsResponse = parseJson(event.data) as JsonRpcResponse;\n if (jsonRpsResponse.id === request.id) {\n // if the incoming response id matches the request id, we will remove the listener and resolve the response\n this.messageHandlers.delete(request.id);\n return resolve(jsonRpsResponse);\n }\n };\n\n // add the listener to the map of message handlers\n this.messageHandlers.set(request.id, handleResponse);\n this.send(request);\n\n // reject this promise if we don't receive any response back within the timeout period\n setTimeout(() => {\n this.messageHandlers.delete(request.id!);\n reject(new Error('request timed out'));\n }, this.responseTimeout);\n });\n }\n\n /**\n * Sends a JSON-RPC request through the socket and keeps a listener open to read associated responses as they arrive.\n * Returns a close method to clean up the listener.\n */\n async subscribe(request: JsonRpcRequest, listener: (response: JsonRpcResponse) => void): Promise<{\n response: JsonRpcResponse;\n close?: () => Promise<void>;\n }> {\n\n if (!request.method.startsWith('rpc.subscribe.')) {\n throw new Error('subscribe rpc requests must include the `rpc.subscribe` prefix');\n }\n\n if (!request.subscription) {\n throw new Error('subscribe rpc requests must include subscribe options');\n }\n\n const subscriptionId = request.subscription.id;\n const socketEventListener = (event: { data: any }):void => {\n const jsonRpcResponse = parseJson(event.data.toString()) as JsonRpcResponse;\n if (jsonRpcResponse.id === subscriptionId) {\n if (jsonRpcResponse.error !== undefined) {\n // remove the event listener upon receipt of a JSON RPC Error.\n this.messageHandlers.delete(subscriptionId);\n this.closeSubscription(subscriptionId);\n }\n listener(jsonRpcResponse);\n }\n };\n\n this.messageHandlers.set(subscriptionId, socketEventListener);\n\n const response = await this.request(request);\n if (response.error) {\n this.messageHandlers.delete(subscriptionId);\n return { response };\n }\n\n // clean up listener and create a `rpc.subscribe.close` message to use when closing this JSON RPC subscription\n const close = async (): Promise<void> => {\n this.messageHandlers.delete(subscriptionId);\n await this.closeSubscription(subscriptionId);\n };\n\n return {\n response,\n close\n };\n }\n\n private closeSubscription(id: JsonRpcId): Promise<JsonRpcResponse> {\n const requestId = CryptoUtils.randomUuid();\n const request = createJsonRpcSubscriptionRequest(requestId, 'close', id, {});\n return this.request(request);\n }\n\n /**\n * Sends a JSON-RPC request through the socket. You must subscribe to a message listener separately to capture the response.\n */\n send(request: JsonRpcRequest):void {\n this.socket.send(JSON.stringify(request));\n }\n}", "import type { SyncEngine, SyncIdentityOptions } from './types/sync.js';\nimport type { Web5PlatformAgent } from './types/agent.js';\n\nexport type SyncApiParams = {\n agent?: Web5PlatformAgent;\n syncEngine: SyncEngine;\n}\n\nexport class AgentSyncApi implements SyncEngine {\n /**\n * Holds the instance of a `Web5PlatformAgent` that represents the current execution context for\n * the `AgentSyncApi`. This agent is used to interact with other Web5 agent components. It's vital\n * to ensure this instance is set to correctly contextualize operations within the broader Web5\n * Agent framework.\n */\n private _agent?: Web5PlatformAgent;\n\n private _syncEngine: SyncEngine;\n\n constructor({ agent, syncEngine }: SyncApiParams) {\n this._syncEngine = syncEngine;\n this._agent = agent;\n }\n\n /**\n * Retrieves the `Web5PlatformAgent` execution context.\n *\n * @returns The `Web5PlatformAgent` instance that represents the current execution context.\n * @throws Will throw an error if the `agent` instance property is undefined.\n */\n get agent(): Web5PlatformAgent {\n if (this._agent === undefined) {\n throw new Error('AgentSyncApi: Unable to determine agent execution context.');\n }\n\n return this._agent;\n }\n\n set agent(agent: Web5PlatformAgent) {\n this._agent = agent;\n this._syncEngine.agent = agent;\n }\n\n public async registerIdentity(params: { did: string; options?: SyncIdentityOptions }): Promise<void> {\n await this._syncEngine.registerIdentity(params);\n }\n\n public async unregisterIdentity(did: string): Promise<void> {\n await this._syncEngine.unregisterIdentity(did);\n }\n\n public async getIdentityOptions(did: string): Promise<SyncIdentityOptions | undefined> {\n return await this._syncEngine.getIdentityOptions(did);\n }\n\n public async updateIdentityOptions(params: { did: string, options: SyncIdentityOptions }): Promise<void> {\n await this._syncEngine.updateIdentityOptions(params);\n }\n\n public sync(direction?: 'push' | 'pull'): Promise<void> {\n return this._syncEngine.sync(direction);\n }\n\n public startSync(params: { interval: string; }): Promise<void> {\n return this._syncEngine.startSync(params);\n }\n\n public stopSync(timeout?: number): Promise<void> {\n return this._syncEngine.stopSync(timeout);\n }\n}", "import type { ULIDFactory } from 'ulidx';\nimport type { AbstractBatchOperation, AbstractLevel } from 'abstract-level';\nimport type {\n GenericMessage,\n MessagesQueryReply,\n MessagesReadReply,\n PaginationCursor,\n UnionMessageReply,\n} from '@enbox/dwn-sdk-js';\n\nimport ms from 'ms';\nimport { Level } from 'level';\nimport { monotonicFactory } from 'ulidx';\nimport { NodeStream } from '@enbox/common';\nimport {\n DwnInterfaceName,\n DwnMethodName,\n} from '@enbox/dwn-sdk-js';\n\nimport type { SyncEngine, SyncIdentityOptions } from './types/sync.js';\nimport type { Web5Agent, Web5PlatformAgent } from './types/agent.js';\n\nimport { DwnInterface } from './types/dwn.js';\nimport { getDwnServiceEndpointUrls, isRecordsWrite } from './utils.js';\nimport { PermissionsApi } from './types/permissions.js';\nimport { AgentPermissionsApi } from './permissions-api.js';\n\nexport type SyncEngineLevelParams = {\n agent?: Web5PlatformAgent;\n dataPath?: string;\n db?: AbstractLevel<string | Buffer | Uint8Array>;\n}\n\ntype LevelBatchOperation = AbstractBatchOperation<AbstractLevel<string | Buffer | Uint8Array>, string, string>;\n\ntype SyncDirection = 'push' | 'pull';\n\ntype SyncState = {\n did: string;\n delegateDid?: string;\n dwnUrl: string;\n cursor?: PaginationCursor,\n protocol?: string;\n}\n\ntype SyncMessageParams = {\n did: string;\n messageCid: string;\n watermark: string;\n dwnUrl: string;\n delegateDid?: string;\n cursor?: PaginationCursor,\n protocol?: string;\n}\n\nexport class SyncEngineLevel implements SyncEngine {\n /**\n * Holds the instance of a `Web5PlatformAgent` that represents the current execution context for\n * the `SyncEngineLevel`. This agent is used to interact with other Web5 agent components. It's\n * vital to ensure this instance is set to correctly contextualize operations within the broader\n * Web5 Agent framework.\n */\n private _agent?: Web5PlatformAgent;\n\n /**\n * An instance of the `AgentPermissionsApi` that is used to interact with permissions grants used during sync\n */\n private _permissionsApi: PermissionsApi;;\n\n private _db: AbstractLevel<string | Buffer | Uint8Array>;\n private _syncIntervalId?: ReturnType<typeof setInterval>;\n private _syncLock = false;\n private _ulidFactory: ULIDFactory;\n\n constructor({ agent, dataPath, db }: SyncEngineLevelParams) {\n this._agent = agent;\n this._permissionsApi = new AgentPermissionsApi({ agent: agent as Web5Agent });\n this._db = (db) ? db : new Level<string, string>(dataPath ?? 'DATA/AGENT/SYNC_STORE');\n this._ulidFactory = monotonicFactory();\n }\n\n /**\n * Retrieves the `Web5PlatformAgent` execution context.\n *\n * @returns The `Web5PlatformAgent` instance that represents the current execution context.\n * @throws Will throw an error if the `agent` instance property is undefined.\n */\n get agent(): Web5PlatformAgent {\n if (this._agent === undefined) {\n throw new Error('SyncEngineLevel: Unable to determine agent execution context.');\n }\n\n return this._agent;\n }\n\n set agent(agent: Web5PlatformAgent) {\n this._agent = agent;\n this._permissionsApi = new AgentPermissionsApi({ agent: agent as Web5Agent });\n }\n\n public async clear(): Promise<void> {\n await this._permissionsApi.clear();\n await this._db.clear();\n }\n\n public async close(): Promise<void> {\n await this._db.close();\n }\n\n private async pull(): Promise<void> {\n const syncPeerState = await this.getSyncPeerState({ syncDirection: 'pull' });\n await this.enqueueOperations({ syncDirection: 'pull', syncPeerState });\n\n const pullQueue = this.getPullQueue();\n const pullJobs = await pullQueue.iterator().all();\n\n const deleteOperations: LevelBatchOperation[] = [];\n const errored: Set<string> = new Set();\n\n for (let job of pullJobs) {\n const [key] = job;\n const { did, dwnUrl, messageCid, delegateDid, protocol } = SyncEngineLevel.parseSyncMessageParamsKey(key);\n // If a particular DWN service endpoint is unreachable, skip subsequent pull operations.\n if (errored.has(dwnUrl)) {\n continue;\n }\n\n const messageExists = await this.messageExists(did, messageCid);\n if (messageExists) {\n deleteOperations.push({ type: 'del', key: key });\n continue;\n }\n\n let permissionGrantId: string | undefined;\n let granteeDid: string | undefined;\n if (delegateDid) {\n try {\n const messagesReadGrant = await this._permissionsApi.getPermissionForRequest({\n connectedDid : did,\n messageType : DwnInterface.MessagesRead,\n delegateDid,\n protocol,\n cached : true\n });\n\n permissionGrantId = messagesReadGrant.grant.id;\n granteeDid = delegateDid;\n } catch(error:any) {\n console.error('SyncEngineLevel: pull - Error fetching MessagesRead permission grant for delegate DID', error);\n continue;\n }\n }\n\n const messagesRead = await this.agent.processDwnRequest({\n store : false,\n author : did,\n target : did,\n messageType : DwnInterface.MessagesRead,\n granteeDid,\n messageParams : {\n messageCid,\n permissionGrantId\n }\n });\n\n let reply: MessagesReadReply;\n\n try {\n reply = await this.agent.rpc.sendDwnRequest({\n dwnUrl, targetDid : did,\n message : messagesRead.message,\n }) as MessagesReadReply;\n } catch(e) {\n errored.add(dwnUrl);\n continue;\n }\n\n if (reply.status.code !== 200 || !reply.entry?.message) {\n await this.addMessage(did, messageCid);\n deleteOperations.push({ type: 'del', key: key });\n continue;\n }\n\n const replyEntry = reply.entry;\n const message = replyEntry.message;\n // if the message includes data we convert it to a Node readable stream\n // otherwise we set it as undefined, as the message does not include data\n // this occurs when the message is a RecordsWrite message that has been updated\n const dataStream = isRecordsWrite(replyEntry) && replyEntry.data ?\n NodeStream.fromWebReadable({ readableStream: replyEntry.data as unknown as ReadableStream })\n : undefined;\n\n const pullReply = await this.agent.dwn.node.processMessage(did, message, { dataStream: dataStream as any });\n if (SyncEngineLevel.syncMessageReplyIsSuccessful(pullReply)) {\n await this.addMessage(did, messageCid);\n deleteOperations.push({ type: 'del', key: key });\n }\n }\n\n await pullQueue.batch(deleteOperations as any);\n }\n\n private async push(): Promise<void> {\n const syncPeerState = await this.getSyncPeerState({ syncDirection: 'push' });\n await this.enqueueOperations({ syncDirection: 'push', syncPeerState });\n\n const pushQueue = this.getPushQueue();\n const pushJobs = await pushQueue.iterator().all();\n\n const deleteOperations: LevelBatchOperation[] = [];\n const errored: Set<string> = new Set();\n\n for (let job of pushJobs) {\n const [key] = job;\n const { did, delegateDid, protocol, dwnUrl, messageCid } = SyncEngineLevel.parseSyncMessageParamsKey(key);\n // If a particular DWN service endpoint is unreachable, skip subsequent push operations.\n if (errored.has(dwnUrl)) {\n continue;\n }\n\n // Attempt to retrieve the message from the local DWN.\n const dwnMessage = await this.getDwnMessage({ author: did, messageCid, delegateDid, protocol });\n\n // If the message does not exist on the local DWN, remove the sync operation from the\n // push queue, update the push watermark for this DID/DWN endpoint combination, add the\n // message to the local message store, and continue to the next job.\n if (!dwnMessage) {\n deleteOperations.push({ type: 'del', key: key });\n await this.addMessage(did, messageCid);\n\n continue;\n }\n\n try {\n const reply = await this.agent.rpc.sendDwnRequest({\n dwnUrl,\n targetDid : did,\n data : dwnMessage.data,\n message : dwnMessage.message\n });\n\n // Update the watermark and add the messageCid to the Sync Message Store if either:\n if (SyncEngineLevel.syncMessageReplyIsSuccessful(reply)) {\n await this.addMessage(did, messageCid);\n deleteOperations.push({ type: 'del', key: key });\n }\n } catch {\n // Error is intentionally ignored; 'errored' set is updated with 'dwnUrl'.\n errored.add(dwnUrl);\n }\n }\n\n await pushQueue.batch(deleteOperations as any);\n }\n\n public async registerIdentity({ did, options }: { did: string; options?: SyncIdentityOptions }): Promise<void> {\n // Get a reference to the `registeredIdentities` sublevel.\n const registeredIdentities = this._db.sublevel('registeredIdentities');\n\n const existing = await this.getIdentityOptions(did);\n if (existing) {\n throw new Error(`SyncEngineLevel: Identity with DID ${did} is already registered.`);\n }\n\n // if no options are provided, we default to no delegateDid and all protocols (empty array)\n options ??= { protocols: [] };\n\n // Add (or overwrite, if present) the Identity's DID as a registered identity.\n await registeredIdentities.put(did, JSON.stringify(options));\n }\n\n public async unregisterIdentity(did: string): Promise<void> {\n const registeredIdentities = this._db.sublevel('registeredIdentities');\n const existing = await this.getIdentityOptions(did);\n if (!existing) {\n throw new Error(`SyncEngineLevel: Identity with DID ${did} is not registered.`);\n }\n\n await registeredIdentities.del(did);\n }\n\n public async getIdentityOptions(did: string): Promise<SyncIdentityOptions | undefined> {\n const registeredIdentities = this._db.sublevel('registeredIdentities');\n try {\n const options = await registeredIdentities.get(did);\n if (options) {\n return JSON.parse(options) as SyncIdentityOptions;\n }\n } catch(error) {\n const e = error as { code: string };\n // `Level`` throws an error if the key is not present. Return `undefined` in this case.\n if (e.code === 'LEVEL_NOT_FOUND') {\n return;\n } else {\n throw new Error(`SyncEngineLevel: Error reading level: ${e.code}.`);\n }\n }\n }\n\n public async updateIdentityOptions({ did, options }: { did: string, options: SyncIdentityOptions }): Promise<void> {\n const registeredIdentities = this._db.sublevel('registeredIdentities');\n const existingOptions = await this.getIdentityOptions(did);\n if (!existingOptions) {\n throw new Error(`SyncEngineLevel: Identity with DID ${did} is not registered.`);\n }\n\n await registeredIdentities.put(did, JSON.stringify(options));\n }\n\n public async sync(direction?: 'push' | 'pull'): Promise<void> {\n if (this._syncLock) {\n throw new Error('SyncEngineLevel: Sync operation is already in progress.');\n }\n\n this._syncLock = true;\n try {\n if (!direction || direction === 'push') {\n await this.push();\n }\n if (!direction || direction === 'pull') {\n await this.pull();\n }\n } finally {\n this._syncLock = false;\n }\n }\n\n public async startSync({ interval }: {\n interval: string\n }): Promise<void> {\n // Convert the interval string to milliseconds.\n const intervalMilliseconds = ms(interval);\n\n const intervalSync = async () => {\n if (this._syncLock) {\n return;\n }\n\n clearInterval(this._syncIntervalId);\n this._syncIntervalId = undefined;\n\n try {\n await this.sync();\n } catch (error) {\n console.error('SyncEngineLevel: Error during sync operation', error);\n }\n\n if (!this._syncIntervalId) {\n this._syncIntervalId = setInterval(intervalSync, intervalMilliseconds);\n }\n };\n\n if (this._syncIntervalId) {\n clearInterval(this._syncIntervalId);\n }\n\n // Set up a new interval.\n this._syncIntervalId = setInterval(intervalSync, intervalMilliseconds);\n\n // initiate an immediate sync\n if (!this._syncLock) {\n await this.sync();\n }\n }\n\n /**\n * stopSync currently awaits the completion of the current sync operation before stopping the sync interval.\n * TODO: implement a signal to gracefully stop sync immediately https://github.com/TBD54566975/web5-js/issues/890\n */\n public async stopSync(timeout: number = 2000): Promise<void> {\n let elapsedTimeout = 0;\n\n while(this._syncLock) {\n if (elapsedTimeout >= timeout) {\n throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${timeout} milliseconds.`);\n }\n\n elapsedTimeout += 100;\n await new Promise((resolve) => setTimeout(resolve, timeout < 100 ? timeout : 100));\n }\n\n if (this._syncIntervalId) {\n clearInterval(this._syncIntervalId);\n this._syncIntervalId = undefined;\n }\n }\n\n /**\n * 202: message was successfully written to the remote DWN\n * 204: an initial write message was written without any data, cannot yet be read until a subsequent message is written with data\n * 409: message was already present on the remote DWN\n * RecordsDelete and the status code is 404: the initial write message was not found or the message was already deleted\n */\n private static syncMessageReplyIsSuccessful(reply: UnionMessageReply): boolean {\n return reply.status.code === 202 ||\n // a 204 status code is returned when the message was accepted without any data.\n // This is the case for an initial RecordsWrite messages for records that have been updated.\n // For context: https://github.com/TBD54566975/dwn-sdk-js/issues/695\n reply.status.code === 204 ||\n reply.status.code === 409 ||\n (\n // If the message is a RecordsDelete and the status code is 404, the initial write message was not found or the message was already deleted\n reply.entry?.message.descriptor.interface === DwnInterfaceName.Records &&\n reply.entry?.message.descriptor.method === DwnMethodName.Delete &&\n reply.status.code === 404\n );\n }\n\n private async enqueueOperations({ syncDirection, syncPeerState }: {\n syncDirection: SyncDirection,\n syncPeerState: SyncState[]\n }) {\n const enqueueOps = await Promise.allSettled(syncPeerState.map(async (syncState) => {\n // Get the event log from the remote DWN if pull sync, or local DWN if push sync.\n const eventLog = await this.getDwnEventLog({\n did : syncState.did,\n delegateDid : syncState.delegateDid,\n dwnUrl : syncState.dwnUrl,\n cursor : syncState.cursor,\n protocol : syncState.protocol,\n syncDirection\n });\n\n const syncOperations: LevelBatchOperation[] = [];\n\n for (let messageCid of eventLog) {\n const watermark = this._ulidFactory();\n const operationKey = SyncEngineLevel.generateSyncMessageParamsKey({\n ...syncState,\n watermark,\n messageCid\n });\n\n syncOperations.push({ type: 'put', key: operationKey, value: '' });\n }\n\n if (syncOperations.length > 0) {\n const syncQueue = (syncDirection === 'pull')\n ? this.getPullQueue()\n : this.getPushQueue();\n await syncQueue.batch(syncOperations as any);\n }\n }));\n\n // log any errors that occurred during the enqueuing process\n enqueueOps.forEach((result, index) => {\n if (result.status === 'rejected') {\n const peerState = syncPeerState[index];\n console.error(`SyncEngineLevel: Error enqueuing sync operation for peerState: ${JSON.stringify(peerState)}`, result.reason);\n }\n });\n }\n\n private static generateSyncMessageParamsKey({ did, delegateDid, dwnUrl, protocol, watermark, messageCid }:SyncMessageParams): string {\n // Use \"did~dwnUrl~watermark~messageCid\" as the key in the sync queue.\n // Note: It is critical that `watermark` precedes `messageCid` to ensure that when the sync\n // jobs are pulled off the queue, they are lexographically sorted oldest to newest.\n //\n // `protocol` and `delegateDid` may be undefined, which is fine, its part of the key will be stored as an empty string.\n // Later, when parsing the key, we will handle this case and return an actual undefined.\n // This is information useful for subset and delegated sync.\n return [did, delegateDid, dwnUrl, protocol, watermark, messageCid ].join('~');\n }\n\n private static parseSyncMessageParamsKey(key: string): SyncMessageParams {\n // The order is import here, see `generateKey` for more information.\n const [did, delegateDidString, dwnUrl, protocolString, watermark, messageCid] = key.split('~');\n\n // `protocol` or `delegateDid` may be parsed as an empty string, so we need to handle that case and returned an actual undefined.\n const protocol = protocolString === '' ? undefined : protocolString;\n const delegateDid = delegateDidString === '' ? undefined : delegateDidString;\n return { did, delegateDid, dwnUrl, watermark, messageCid, protocol };\n }\n\n private async getDwnEventLog({ did, delegateDid, dwnUrl, syncDirection, cursor, protocol }: {\n did: string,\n delegateDid?: string,\n dwnUrl: string,\n syncDirection: SyncDirection,\n cursor?: PaginationCursor\n protocol?: string\n }) {\n let messagesReply = {} as MessagesQueryReply;\n let permissionGrantId: string | undefined;\n if (delegateDid) {\n // fetch the grants for the delegate DID\n try {\n const messagesQueryGrant = await this._permissionsApi.getPermissionForRequest({\n connectedDid : did,\n messageType : DwnInterface.MessagesQuery,\n delegateDid,\n protocol,\n cached : true\n });\n\n permissionGrantId = messagesQueryGrant.grant.id;\n } catch(error:any) {\n console.error('SyncEngineLevel: Error fetching MessagesQuery permission grant for delegate DID', error);\n return [];\n }\n }\n\n if (syncDirection === 'pull') {\n // filter for a specific protocol if one is provided\n const filters = protocol ? [{ protocol }] : [];\n // When sync is a pull, get the event log from the remote DWN.\n const messagesQueryMessage = await this.agent.dwn.processRequest({\n store : false,\n target : did,\n author : did,\n messageType : DwnInterface.MessagesQuery,\n granteeDid : delegateDid,\n messageParams : { filters, cursor, permissionGrantId }\n });\n\n try {\n messagesReply = await this.agent.rpc.sendDwnRequest({\n dwnUrl : dwnUrl,\n targetDid : did,\n message : messagesQueryMessage.message,\n }) as MessagesQueryReply;\n } catch {\n // If a particular DWN service endpoint is unreachable, silently ignore.\n }\n\n } else if (syncDirection === 'push') {\n const filters = protocol ? [{ protocol }] : [];\n // When sync is a push, get the event log from the local DWN.\n const messagesQueryDwnResponse = await this.agent.dwn.processRequest({\n author : did,\n target : did,\n messageType : DwnInterface.MessagesQuery,\n granteeDid : delegateDid,\n messageParams : { filters, cursor, permissionGrantId }\n });\n messagesReply = messagesQueryDwnResponse.reply as MessagesQueryReply;\n }\n\n const eventLog = messagesReply.entries ?? [];\n if (messagesReply.cursor) {\n this.setCursor(did, dwnUrl, syncDirection, messagesReply.cursor, protocol);\n }\n\n return eventLog;\n }\n\n private async getDwnMessage({ author, delegateDid, protocol, messageCid }: {\n author: string;\n delegateDid?: string;\n protocol?: string;\n messageCid: string;\n }): Promise<{ message: GenericMessage, data?: Blob } | undefined> {\n let permissionGrantId: string | undefined;\n if (delegateDid) {\n try {\n const messagesReadGrant = await this._permissionsApi.getPermissionForRequest({\n connectedDid : author,\n messageType : DwnInterface.MessagesRead,\n delegateDid,\n protocol,\n cached : true\n });\n\n permissionGrantId = messagesReadGrant.grant.id;\n } catch(error:any) {\n console.error('SyncEngineLevel: push - Error fetching MessagesRead permission grant for delegate DID', error);\n return;\n }\n }\n\n let { reply } = await this.agent.dwn.processRequest({\n author : author,\n target : author,\n messageType : DwnInterface.MessagesRead,\n granteeDid : delegateDid,\n messageParams : { messageCid, permissionGrantId }\n });\n\n\n // Absence of a messageEntry or message within messageEntry can happen because updating a\n // Record creates another RecordsWrite with the same recordId. Only the first and\n // most recent RecordsWrite messages are kept for a given recordId. Any RecordsWrite messages\n // that aren't the first or most recent are discarded by the DWN.\n if (reply.status.code !== 200 || !reply.entry) {\n return undefined;\n }\n const messageEntry = reply.entry!;\n\n let dwnMessageWithBlob: { message: GenericMessage, data?: Blob } = { message: messageEntry.message };\n\n // If the message is a RecordsWrite, either data will be present,\n // OR we have to fetch it using a RecordsRead.\n if (isRecordsWrite(messageEntry) && messageEntry.data) {\n const dataBytes = await NodeStream.consumeToBytes({ readable: messageEntry.data });\n dwnMessageWithBlob.data = new Blob([ dataBytes ], { type: messageEntry.message.descriptor.dataFormat });\n }\n\n return dwnMessageWithBlob;\n }\n\n private async getSyncPeerState({ syncDirection }: {\n syncDirection: SyncDirection;\n }): Promise<SyncState[]> {\n\n // Array to accumulate the list of sync peers for each DID.\n const syncPeerState: SyncState[] = [];\n\n // iterate over all registered identities\n for await (const [ did, options ] of this._db.sublevel('registeredIdentities').iterator()) {\n\n const { protocols, delegateDid } = await new Promise<SyncIdentityOptions>((resolve) => {\n try {\n const { protocols, delegateDid } = JSON.parse(options) as SyncIdentityOptions;\n resolve({ protocols, delegateDid });\n } catch(error: any) {\n resolve({ protocols: [] });\n }\n });\n\n // First, confirm the DID can be resolved and extract the DWN service endpoint URLs.\n const dwnEndpointUrls = await getDwnServiceEndpointUrls(did, this.agent.did);\n if (dwnEndpointUrls.length === 0) {\n // Silently ignore and do not try to perform Sync for any DID that does not have a DWN\n // service endpoint published in its DID document.\n continue;\n }\n\n // Get the cursor (or undefined) for each (DID, DWN service endpoint, sync direction)\n // combination and add it to the sync peer state array.\n for (let dwnUrl of dwnEndpointUrls) {\n if (protocols.length === 0) {\n const cursor = await this.getCursor(did, dwnUrl, syncDirection);\n syncPeerState.push({ did, delegateDid, dwnUrl, cursor });\n } else {\n for (const protocol of protocols) {\n const cursor = await this.getCursor(did, dwnUrl, syncDirection, protocol);\n syncPeerState.push({ did, delegateDid, dwnUrl, cursor, protocol });\n }\n }\n }\n }\n\n return syncPeerState;\n }\n\n private async getCursor(did: string, dwnUrl: string, direction: SyncDirection, protocol?: string): Promise<PaginationCursor | undefined> {\n\n // if a protocol is provided, we append it to the key\n const cursorKey = protocol ? `${did}~${dwnUrl}~${direction}-${protocol}` :\n `${did}~${dwnUrl}~${direction}`;\n\n const cursorsStore = this.getCursorStore();\n try {\n const cursorValue = await cursorsStore.get(cursorKey);\n if (cursorValue) {\n return JSON.parse(cursorValue) as PaginationCursor;\n }\n } catch(error: any) {\n // Don't throw when a key wasn't found.\n if (error.notFound) {\n return undefined;\n }\n }\n }\n\n private async setCursor(did: string, dwnUrl: string, direction: SyncDirection, cursor: PaginationCursor, protocol?: string) {\n const cursorKey = protocol ? `${did}~${dwnUrl}~${direction}-${protocol}` :\n `${did}~${dwnUrl}~${direction}`;\n const cursorsStore = this.getCursorStore();\n await cursorsStore.put(cursorKey, JSON.stringify(cursor));\n }\n\n /**\n * The message store is used to prevent \"echoes\" that occur during a sync pull operation.\n * After a message is confirmed to already be synchronized on the local DWN, its CID is added\n * to the message store to ensure that any subsequent pull attempts are skipped.\n */\n private async messageExists(did: string, messageCid: string) {\n const messageStore = this.getMessageStore(did);\n\n // If the `messageCid` exists in this DID's store, return true. Otherwise, return false.\n try {\n await messageStore.get(messageCid);\n return true;\n } catch (error: any) {\n if (error.notFound) {\n return false;\n }\n throw error;\n }\n }\n\n private async addMessage(did: string, messageCid: string) {\n const messageStore = this.getMessageStore(did);\n\n return await messageStore.put(messageCid, '');\n }\n\n private getMessageStore(did: string) {\n return this._db.sublevel('history').sublevel(did).sublevel('messages');\n }\n\n private getCursorStore() {\n return this._db.sublevel('cursors');\n }\n\n private getPushQueue() {\n return this._db.sublevel('pushQueue');\n }\n\n private getPullQueue() {\n return this._db.sublevel('pullQueue');\n }\n}", "import type { KeyValueStore } from '@enbox/common';\nimport type { AbstractLevel } from 'abstract-level';\n\nimport { Level } from 'level';\nimport { LevelStore, MemoryStore } from '@enbox/common';\nimport { DataStoreLevel, Dwn, EventEmitterStream, EventLogLevel, MessageStoreLevel, ResumableTaskStoreLevel } from '@enbox/dwn-sdk-js';\nimport { DidDht, DidJwk, DidResolutionResult, DidResolverCache } from '@enbox/dids';\n\nimport type { Web5PlatformAgent } from './types/agent.js';\n\nimport { AgentDidApi } from './did-api.js';\nimport { AgentDidResolverCache } from './agent-did-resolver-cache.js';\nimport { AgentDwnApi } from './dwn-api.js';\nimport { AgentSyncApi } from './sync-api.js';\nimport { Web5RpcClient } from './rpc-client.js';\nimport { AgentCryptoApi } from './crypto-api.js';\nimport { AgentIdentityApi } from './identity-api.js';\nimport { BearerIdentity } from './bearer-identity.js';\nimport { HdIdentityVault } from './hd-identity-vault.js';\nimport { LocalKeyManager } from './local-key-manager.js';\nimport { SyncEngineLevel } from './sync-engine-level.js';\nimport { DwnDidStore, InMemoryDidStore } from './store-did.js';\nimport { DwnKeyStore, InMemoryKeyStore } from './store-key.js';\nimport { DwnIdentityStore, InMemoryIdentityStore } from './store-identity.js';\nimport { DidResolverCacheMemory } from './prototyping/dids/resolver-cache-memory.js';\nimport { AgentPermissionsApi } from './permissions-api.js';\n\ntype PlatformAgentTestHarnessParams = {\n agent: Web5PlatformAgent<LocalKeyManager>\n\n agentStores: 'dwn' | 'memory';\n didResolverCache: DidResolverCache;\n dwn: Dwn;\n dwnDataStore: DataStoreLevel;\n dwnEventLog: EventLogLevel;\n dwnMessageStore: MessageStoreLevel;\n dwnResumableTaskStore: ResumableTaskStoreLevel;\n syncStore: AbstractLevel<string | Buffer | Uint8Array>;\n vaultStore: KeyValueStore<string, string>;\n dwnStores: {\n keyStore: DwnKeyStore;\n identityStore: DwnIdentityStore;\n didStore: DwnDidStore;\n clear: () => void;\n }\n}\n\nexport class PlatformAgentTestHarness {\n public agent: Web5PlatformAgent<LocalKeyManager>;\n\n public agentStores: 'dwn' | 'memory';\n public didResolverCache: DidResolverCache;\n public dwn: Dwn;\n public dwnDataStore: DataStoreLevel;\n public dwnEventLog: EventLogLevel;\n public dwnMessageStore: MessageStoreLevel;\n public dwnResumableTaskStore: ResumableTaskStoreLevel;\n public syncStore: AbstractLevel<string | Buffer | Uint8Array>;\n public vaultStore: KeyValueStore<string, string>;\n\n /**\n * Custom DWN Stores for `keyStore`, `identityStore` and `didStore`.\n * This allows us to clear the store cache between tests\n */\n public dwnStores: {\n keyStore: DwnKeyStore;\n identityStore: DwnIdentityStore;\n didStore: DwnDidStore;\n /** clears the protocol initialization caches */\n clear: () => void;\n };\n\n constructor(params: PlatformAgentTestHarnessParams) {\n this.agent = params.agent;\n this.agentStores = params.agentStores;\n this.didResolverCache = params.didResolverCache;\n this.dwn = params.dwn;\n this.dwnDataStore = params.dwnDataStore;\n this.dwnEventLog = params.dwnEventLog;\n this.dwnMessageStore = params.dwnMessageStore;\n this.syncStore = params.syncStore;\n this.vaultStore = params.vaultStore;\n this.dwnResumableTaskStore = params.dwnResumableTaskStore;\n this.dwnStores = params.dwnStores;\n }\n\n public async clearStorage(): Promise<void> {\n // first stop any ongoing sync operations\n await this.agent.sync.stopSync();\n\n // @ts-expect-error since normally this property shouldn't be set to undefined.\n this.agent.agentDid = undefined;\n await this.didResolverCache.clear();\n await this.dwnDataStore.clear();\n await this.dwnEventLog.clear();\n await this.dwnMessageStore.clear();\n await this.dwnResumableTaskStore.clear();\n await this.syncStore.clear();\n await this.vaultStore.clear();\n await this.agent.permissions.clear();\n this.dwnStores.clear();\n\n // Reset the indexes and caches for the Agent's DWN data stores.\n // if (this.agentStores === 'dwn') {\n // const { didApi, identityApi } = PlatformAgentTestHarness.useDiskStores({ testDataLocation: '__TESTDATA__', agent: this.agent });\n // this.agent.crypto = cryptoApi;\n // this.agent.did = didApi;\n // this.agent.identity = identityApi;\n // }\n\n // Easiest way to start with fresh in-memory stores is to re-instantiate Agent components.\n if (this.agentStores === 'memory') {\n const { didApi, identityApi, permissionsApi, keyManager } = PlatformAgentTestHarness.useMemoryStores({ agent: this.agent });\n this.agent.did = didApi;\n this.agent.identity = identityApi;\n this.agent.keyManager = keyManager;\n this.agent.permissions = permissionsApi;\n }\n }\n\n public async closeStorage(): Promise<void> {\n await this.didResolverCache.close();\n await this.dwnDataStore.close();\n await this.dwnEventLog.close();\n await this.dwnMessageStore.close();\n await this.dwnResumableTaskStore.close();\n await this.syncStore.close();\n await this.vaultStore.close();\n }\n\n public async createAgentDid(): Promise<void> {\n // Create a DID for the Agent.\n this.agent.agentDid = await DidJwk.create({\n options: { algorithm: 'Ed25519' }\n });\n }\n\n public async createIdentity({ name, testDwnUrls }: {\n name: string;\n testDwnUrls: string[];\n }): Promise<BearerIdentity> {\n const bearerIdentity = await this.agent.identity.create({\n didMethod : 'dht',\n didOptions : {\n services: [\n {\n id : 'dwn',\n type : 'DecentralizedWebNode',\n serviceEndpoint : testDwnUrls,\n enc : '#enc',\n sig : '#sig',\n }\n ],\n verificationMethods: [\n {\n algorithm : 'Ed25519',\n id : 'sig',\n purposes : ['assertionMethod', 'authentication']\n },\n {\n algorithm : 'secp256k1',\n id : 'enc',\n purposes : ['keyAgreement']\n }\n ]\n },\n metadata: { name }\n });\n\n return bearerIdentity;\n }\n\n public static async setup({ agentClass, agentStores, testDataLocation }: {\n agentClass: new (params: any) => Web5PlatformAgent<LocalKeyManager>\n agentStores?: 'dwn' | 'memory';\n testDataLocation?: string;\n }): Promise<PlatformAgentTestHarness> {\n agentStores ??= 'memory';\n testDataLocation ??= '__TESTDATA__';\n\n const testDataPath = (path: string) => `${testDataLocation}/${path}`;\n\n // Instantiate Agent's Crypto API.\n const cryptoApi = new AgentCryptoApi();\n\n // Instantiate Agent's RPC Client.\n const rpcClient = new Web5RpcClient();\n\n const dwnStores = {\n keyStore : new DwnKeyStore(),\n identityStore : new DwnIdentityStore(),\n didStore : new DwnDidStore(),\n clear : ():void => {\n dwnStores.keyStore['_protocolInitializedCache']?.clear();\n dwnStores.identityStore['_protocolInitializedCache']?.clear();\n dwnStores.didStore['_protocolInitializedCache']?.clear();\n }\n };\n\n const {\n agentVault,\n didApi,\n identityApi,\n keyManager,\n didResolverCache,\n vaultStore,\n permissionsApi\n } = (agentStores === 'memory')\n ? PlatformAgentTestHarness.useMemoryStores()\n : PlatformAgentTestHarness.useDiskStores({ testDataLocation, stores: dwnStores });\n\n // Instantiate custom stores to use with DWN instance.\n // Note: There is no in-memory store for DWN, so we always use LevelDB-based disk stores.\n const dwnDataStore = new DataStoreLevel({ blockstoreLocation: testDataPath('DWN_DATASTORE') });\n const dwnEventLog = new EventLogLevel({ location: testDataPath('DWN_EVENTLOG') });\n const dwnEventStream = new EventEmitterStream();\n const dwnResumableTaskStore = new ResumableTaskStoreLevel({ location: testDataPath('DWN_RESUMABLETASKSTORE') });\n\n const dwnMessageStore = new MessageStoreLevel({\n blockstoreLocation : testDataPath('DWN_MESSAGESTORE'),\n indexLocation : testDataPath('DWN_MESSAGEINDEX')\n });\n\n // Instantiate DWN instance using the custom stores.\n const dwn = await AgentDwnApi.createDwn({\n dataPath : testDataLocation,\n dataStore : dwnDataStore,\n didResolver : didApi,\n eventLog : dwnEventLog,\n eventStream : dwnEventStream,\n messageStore : dwnMessageStore,\n resumableTaskStore : dwnResumableTaskStore\n });\n\n // Instantiate Agent's DWN API using the custom DWN instance.\n const dwnApi = new AgentDwnApi({ dwn });\n\n // Instantiate Agent's Sync API using a custom LevelDB-backed store.\n const syncStore = new Level(testDataPath('SYNC_STORE'));\n const syncEngine = new SyncEngineLevel({ db: syncStore });\n const syncApi = new AgentSyncApi({ syncEngine });\n\n // Create Web5PlatformAgent instance\n const agent = new agentClass({\n agentVault,\n cryptoApi,\n didApi,\n dwnApi,\n identityApi,\n keyManager,\n permissionsApi,\n rpcClient,\n syncApi,\n });\n\n return new PlatformAgentTestHarness({\n agent,\n agentStores,\n didResolverCache,\n dwn,\n dwnDataStore,\n dwnEventLog,\n dwnMessageStore,\n dwnResumableTaskStore,\n dwnStores,\n syncStore,\n vaultStore\n });\n }\n\n private static useDiskStores({ agent, testDataLocation, stores }: {\n agent?: Web5PlatformAgent;\n stores: {\n keyStore: DwnKeyStore;\n identityStore: DwnIdentityStore;\n didStore: DwnDidStore;\n }\n testDataLocation: string;\n }) {\n const testDataPath = (path: string) => `${testDataLocation}/${path}`;\n\n const vaultStore = new LevelStore<string, string>({ location: testDataPath('VAULT_STORE') });\n const agentVault = new HdIdentityVault({ keyDerivationWorkFactor: 1, store: vaultStore });\n\n const { didStore, identityStore, keyStore } = stores;\n\n // Setup DID Resolver Cache\n const didResolverCache = new AgentDidResolverCache({\n location: testDataPath('DID_RESOLVERCACHE')\n });\n\n const didApi = new AgentDidApi({\n agent : agent,\n didMethods : [DidDht, DidJwk],\n resolverCache : didResolverCache,\n store : didStore\n });\n\n const identityApi = new AgentIdentityApi({ agent, store: identityStore });\n\n const keyManager = new LocalKeyManager({ agent, keyStore: keyStore });\n\n const permissionsApi = new AgentPermissionsApi({ agent });\n\n return { agentVault, didApi, didResolverCache, identityApi, keyManager, permissionsApi, vaultStore };\n }\n\n private static useMemoryStores({ agent }: { agent?: Web5PlatformAgent<LocalKeyManager> } = {}) {\n const vaultStore = new MemoryStore<string, string>();\n const agentVault = new HdIdentityVault({ keyDerivationWorkFactor: 1, store: vaultStore });\n\n // Setup DID Resolver Cache\n const didResolverCache = new DidResolverCacheMemory();\n\n const didApi = new AgentDidApi({\n agent : agent,\n didMethods : [DidDht, DidJwk],\n resolverCache : didResolverCache,\n store : new InMemoryDidStore()\n });\n\n const keyManager = new LocalKeyManager({ agent, keyStore: new InMemoryKeyStore() });\n\n const identityApi = new AgentIdentityApi<LocalKeyManager>({ agent, store: new InMemoryIdentityStore() });\n\n const permissionsApi = new AgentPermissionsApi({ agent });\n\n return { agentVault, didApi, didResolverCache, identityApi, keyManager, permissionsApi, vaultStore };\n }\n}", "import type { DidResolverCache, DidResolutionResult } from '@enbox/dids';\n\nimport ms from 'ms';\nimport { TtlCache } from '@enbox/common';\n\n/**\n * Configuration parameters for creating an in-memory cache for DID resolution results.\n *\n * Allows customization of the cache time-to-live (TTL) setting.\n */\nexport type DidResolverCacheMemoryParams = {\n /**\n * Optional. The time-to-live for cache entries, expressed as a string (e.g., '1h', '15m').\n * Determines how long a cache entry should remain valid before being considered expired.\n *\n * Defaults to '15m' if not specified.\n */\n ttl?: string;\n}\n\nexport class DidResolverCacheMemory implements DidResolverCache {\n private cache: TtlCache<string, DidResolutionResult>;\n\n constructor({ ttl = '15m' }: DidResolverCacheMemoryParams = {}) {\n this.cache = new TtlCache({ ttl: ms(ttl) });\n }\n\n /**\n * Retrieves a DID resolution result from the cache.\n *\n * If the cached item has exceeded its TTL, it's scheduled for deletion and undefined is returned.\n *\n * @param didUri - The DID string used as the key for retrieving the cached result.\n * @returns The cached DID resolution result or undefined if not found or expired.\n */\n public async get(didUri: string): Promise<DidResolutionResult | void> {\n if (!didUri) {\n throw new Error('Key cannot be null or undefined');\n }\n\n return this.cache.get(didUri);\n }\n\n /**\n * Stores a DID resolution result in the cache with a TTL.\n *\n * @param didUri - The DID string used as the key for storing the result.\n * @param resolutionResult - The DID resolution result to be cached.\n * @returns A promise that resolves when the operation is complete.\n */\n public async set(didUri: string, resolutionResult: DidResolutionResult): Promise<void> {\n this.cache.set(didUri, resolutionResult);\n }\n\n /**\n * Deletes a DID resolution result from the cache.\n *\n * @param didUri - The DID string used as the key for deletion.\n * @returns A promise that resolves when the operation is complete.\n */\n public async delete(didUri: string): Promise<void> {\n this.cache.delete(didUri);\n }\n\n /**\n * Clears all entries from the cache.\n *\n * @returns A promise that resolves when the operation is complete.\n */\n public async clear(): Promise<void> {\n this.cache.clear();\n }\n\n /**\n * This method is a no-op but exists to be consistent with other DID Resolver Cache\n * implementations.\n *\n * @returns A promise that resolves immediately.\n */\n public async close(): Promise<void> {\n // No-op since there is no underlying store to close.\n }\n}", "import { Convert, logger, RequireOnly } from '@enbox/common';\nimport {\n Ed25519,\n EdDsaAlgorithm,\n JoseHeaderParams,\n Jwk,\n Sha256,\n X25519,\n CryptoUtils,\n} from '@enbox/crypto';\nimport { concatenateUrl } from './utils.js';\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha';\nimport type { ConnectPermissionRequest } from './connect.js';\nimport { DidDocument, DidJwk, PortableDid, type BearerDid } from '@enbox/dids';\nimport { DwnDataEncodedRecordsWriteMessage, DwnInterface, DwnPermissionScope, DwnProtocolDefinition } from './types/dwn.js';\nimport { AgentPermissionsApi } from './permissions-api.js';\nimport type { Web5Agent } from './types/agent.js';\nimport { isRecordPermissionScope } from './dwn-api.js';\nimport { DwnInterfaceName, DwnMethodName } from '@enbox/dwn-sdk-js';\n\n/**\n * Sent to an OIDC server to authorize a client. Allows clients\n * to securely send authorization request parameters directly to\n * the server via POST. This avoids exposing sensitive data in URLs\n * and ensures the server validates the request before user interaction.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9126.html | OAuth 2.0 Pushed Authorization Requests}\n */\nexport type PushedAuthRequest = {\n /** The JWT which contains the {@link Web5ConnectAuthRequest} */\n request: string;\n};\n\n/**\n * Sent back by OIDC server in response to {@link PushedAuthRequest}\n * The server generates a TTL and a unique request_uri. The request_uri can be shared\n * with the Provider using a link or a QR code along with additional params\n * to access the url and decrypt the payload.\n */\nexport type PushedAuthResponse = {\n request_uri: string;\n expires_in: number;\n};\n\n/**\n * Used in decentralized apps. The SIOPv2 Auth Request is created by a client relying party (RP)\n * often a web service or an app who wants to obtain information from a provider\n * The contents of this are inserted into a JWT inside of the {@link PushedAuthRequest}.\n * @see {@link https://github.com/TBD54566975/known-customer-credential | TBD OIDC Documentation for SIOPv2 }\n */\nexport type SIOPv2AuthRequest = {\n /** The DID of the client (RP) */\n client_id: string;\n\n /** The scope of the access request (e.g., `openid profile`). */\n scope: string;\n\n /** The type of response desired (e.g. `id_token`) */\n response_type: string;\n\n /** the URL to which the Identity Provider will post the Authorization Response */\n redirect_uri: string;\n\n /** The URI to which the SIOPv2 Authorization Response will be sent (Tim's note: not used with encrypted request JWT)*/\n response_uri?: string;\n\n /**\n * An opaque value used to maintain state between the request and the callback.\n * Recommended for security to prevent CSRF attacks.\n */\n state: string;\n\n /**\n * A string value used to associate a client session with an ID token to mitigate replay attacks.\n * Recommended when requesting ID tokens.\n */\n nonce: string;\n\n /**\n * The PKCE code challenge.\n * Required if `code_challenge_method` is used. Enhances security for public clients (e.g., single-page apps,\n * mobile apps) by requiring an additional verification step during token exchange.\n */\n code_challenge?: string;\n\n /** The method used for the PKCE challenge (typically `S256`). Must be present if `code_challenge` is included. */\n code_challenge_method?: 'S256';\n\n /**\n * An ID token previously issued to the client, passed as a hint about the end-user\u2019s current or past authenticated\n * session with the client. Can streamline user experience if already logged in.\n */\n id_token_hint?: string;\n\n /** A hint to the authorization server about the login identifier the user might use. Useful for pre-filling login information. */\n login_hint?: string;\n\n /** Requested Authentication Context Class Reference values. Specifies the authentication context requirements. */\n acr_values?: string;\n\n /** When using a PAR for secure cross device flows we use a \"form_post\" rather than a \"direct_post\" */\n response_mode: 'direct_post';\n\n /** Used by PFI to request VCs as input to IDV process. If present, `response_type: \"vp_token\"\"` MUST also be present */\n presentation_definition?: any;\n\n /** A JSON object containing the Verifier metadata values (Tim's note: from TBD KCC Repo) */\n client_metadata?: {\n /** Array of strings, each a DID method supported for the subject of ID Token\t*/\n subject_syntax_types_supported: string[];\n /** Human-readable string name of the client to be presented to the end-user during authorization */\n client_name?: string;\n /** URI of a web page providing information about the client */\n client_uri?: string;\n /** URI of an image logo for the client */\n logo_uri?: string;\n /** Array of strings representing ways to contact people responsible for this client, typically email addresses */\n contacts?: string[];\n /** URI that points to a terms of service document for the client */\n tos_uri?: string;\n /** URI that points to a privacy policy document */\n policy_uri?: string;\n };\n};\n\n/**\n * An auth request that is compatible with both Web5 Connect and (hopefully, WIP) OIDC SIOPv2\n * The contents of this are inserted into a JWT inside of the {@link PushedAuthRequest}.\n */\nexport type Web5ConnectAuthRequest = {\n /** The user friendly name of the client/app to be displayed when prompting end-user with permission requests. */\n displayName: string;\n\n /** PermissionGrants that are to be sent to the provider */\n permissionRequests: ConnectPermissionRequest[];\n} & SIOPv2AuthRequest;\n\n/** The fields for an OIDC SIOPv2 Auth Repsonse */\nexport type SIOPv2AuthResponse = {\n /** Issuer MUST match the value of sub (Applicant's DID) */\n iss: string;\n /** Subject Identifier. A locally unique and never reassigned identifier\n * within the Issuer for the End-User, which is intended to be consumed\n * by the Client. */\n sub: string;\n /** Audience(s) that this ID Token is intended for. It MUST contain the\n * OAuth 2.0 client_id of the Relying Party as an audience value. */\n aud: string;\n /** Time at which the JWT was issued. */\n iat: number;\n /** Expiration time on or after which the ID Token MUST NOT be accepted\n * for processing. */\n exp: number;\n /** Time when the End-User authentication occurred. */\n auth_time?: number;\n /** b64url encoded nonce used to associate a Client session with an ID Token, and to\n * mitigate replay attacks. */\n nonce?: string;\n /** Custom claims. */\n [key: string]: any;\n};\n\n/** An auth response that is compatible with both Web5 Connect and (hopefully, WIP) OIDC SIOPv2 */\nexport type Web5ConnectAuthResponse = {\n delegateGrants: DwnDataEncodedRecordsWriteMessage[];\n delegatePortableDid: PortableDid;\n} & SIOPv2AuthResponse;\n\n/** Represents the different OIDC endpoint types.\n * 1. `pushedAuthorizationRequest`: client sends {@link PushedAuthRequest} receives {@link PushedAuthResponse}\n * 2. `authorize`: provider gets the {@link Web5ConnectAuthRequest} JWT that was stored by the PAR\n * 3. `callback`: provider sends {@link Web5ConnectAuthResponse} to this endpoint\n * 4. `token`: client gets {@link Web5ConnectAuthResponse} from this endpoint\n */\ntype OidcEndpoint =\n | 'pushedAuthorizationRequest'\n | 'authorize'\n | 'callback'\n | 'token';\n\n/**\n * Gets the correct OIDC endpoint out of the {@link OidcEndpoint} options provided.\n * Handles a trailing slash on baseURL\n *\n * @param {Object} options the options object\n * @param {string} options.baseURL for example `http://foo.com/connect/\n * @param {OidcEndpoint} options.endpoint the OIDC endpoint desired\n * @param {string} options.authParam this is the unique id which must be provided when getting the `authorize` endpoint\n * @param {string} options.tokenParam this is the random state as b64url which must be provided with the `token` endpoint\n */\nfunction buildOidcUrl({\n baseURL,\n endpoint,\n authParam,\n tokenParam,\n}: {\n baseURL: string;\n endpoint: OidcEndpoint;\n authParam?: string;\n tokenParam?: string;\n}) {\n switch (endpoint) {\n /** 1. client sends {@link PushedAuthRequest} & client receives {@link PushedAuthResponse} */\n case 'pushedAuthorizationRequest':\n return concatenateUrl(baseURL, 'par');\n /** 2. provider gets {@link Web5ConnectAuthRequest} */\n case 'authorize':\n if (!authParam)\n throw new Error(\n `authParam must be providied when building a token URL`\n );\n return concatenateUrl(baseURL, `authorize/${authParam}.jwt`);\n /** 3. provider sends {@link Web5ConnectAuthResponse} */\n case 'callback':\n return concatenateUrl(baseURL, `callback`);\n /** 4. client gets {@link Web5ConnectAuthResponse */\n case 'token':\n if (!tokenParam)\n throw new Error(\n `tokenParam must be providied when building a token URL`\n );\n return concatenateUrl(baseURL, `token/${tokenParam}.jwt`);\n // TODO: metadata endpoints?\n default:\n throw new Error(`No matches for endpoint specified: ${endpoint}`);\n }\n}\n\n/**\n * Generates a cryptographically random \"code challenge\" in\n * accordance with the RFC 7636 PKCE specification.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 | RFC 7636 }\n */\nasync function generateCodeChallenge() {\n const codeVerifierBytes = CryptoUtils.randomBytes(32);\n const codeChallengeBytes = await Sha256.digest({ data: codeVerifierBytes });\n const codeChallengeBase64Url =\n Convert.uint8Array(codeChallengeBytes).toBase64Url();\n\n return { codeChallengeBytes, codeChallengeBase64Url };\n}\n\n/** Client creates the {@link Web5ConnectAuthRequest} */\nasync function createAuthRequest(\n options: RequireOnly<\n Web5ConnectAuthRequest,\n 'client_id' | 'scope' | 'redirect_uri' | 'permissionRequests' | 'displayName'\n >\n) {\n // Generate a random state value to associate the authorization request with the response.\n const stateBytes = CryptoUtils.randomBytes(16);\n\n // Generate a random nonce value to associate the ID Token with the authorization request.\n const nonceBytes = CryptoUtils.randomBytes(16);\n\n const requestObject: Web5ConnectAuthRequest = {\n ...options,\n nonce : Convert.uint8Array(nonceBytes).toBase64Url(),\n response_type : 'id_token',\n response_mode : 'direct_post',\n state : Convert.uint8Array(stateBytes).toBase64Url(),\n client_metadata : {\n subject_syntax_types_supported: ['did:dht', 'did:jwk'],\n },\n };\n\n return requestObject;\n}\n\n/** Encrypts the auth request with the key which will be passed through QR code */\nasync function encryptAuthRequest({\n jwt,\n encryptionKey,\n}: {\n jwt: string;\n encryptionKey: Uint8Array;\n}) {\n const protectedHeader = {\n alg : 'dir',\n cty : 'JWT',\n enc : 'XC20P',\n typ : 'JWT',\n };\n const nonce = CryptoUtils.randomBytes(24);\n const additionalData = Convert.object(protectedHeader).toUint8Array();\n const jwtBytes = Convert.string(jwt).toUint8Array();\n const chacha = xchacha20poly1305(encryptionKey, nonce, additionalData);\n const ciphertextAndTag = chacha.encrypt(jwtBytes);\n\n /** The cipher output concatenates the encrypted data and tag\n * so we need to extract the values for use in the JWE. */\n const ciphertext = ciphertextAndTag.subarray(0, -16);\n const authenticationTag = ciphertextAndTag.subarray(-16);\n\n const compactJwe = [\n Convert.object(protectedHeader).toBase64Url(),\n '', // Empty string since there is no wrapped key.\n Convert.uint8Array(nonce).toBase64Url(),\n Convert.uint8Array(ciphertext).toBase64Url(),\n Convert.uint8Array(authenticationTag).toBase64Url(),\n ].join('.');\n\n return compactJwe;\n}\n\n/** Create a response object compatible with Web5 Connect and OIDC SIOPv2 */\nasync function createResponseObject(\n options: RequireOnly<\n Web5ConnectAuthResponse,\n 'iss' | 'sub' | 'aud' | 'delegateGrants' | 'delegatePortableDid'\n >\n) {\n const currentTimeInSeconds = Math.floor(Date.now() / 1000);\n\n const responseObject: Web5ConnectAuthResponse = {\n ...options,\n iat : currentTimeInSeconds,\n exp : currentTimeInSeconds + 600, // Expires in 10 minutes.\n };\n\n return responseObject;\n}\n\n/** sign an object and transform it into a jwt using a did */\nasync function signJwt({\n did,\n data,\n}: {\n did: BearerDid;\n data: Record<string, unknown>;\n}) {\n const header = Convert.object({\n alg : 'EdDSA',\n kid : did.document.verificationMethod![0].id,\n typ : 'JWT',\n }).toBase64Url();\n\n const payload = Convert.object(data).toBase64Url();\n\n // signs using ed25519 EdDSA\n const signer = await did.getSigner();\n const signature = await signer.sign({\n data: Convert.string(`${header}.${payload}`).toUint8Array(),\n });\n\n const signatureBase64Url = Convert.uint8Array(signature).toBase64Url();\n\n const jwt = `${header}.${payload}.${signatureBase64Url}`;\n\n return jwt;\n}\n\n/** Take the decrypted JWT and verify it was signed by its public DID. Return parsed object. */\nasync function verifyJwt({ jwt }: { jwt: string }) {\n const [headerB64U, payloadB64U, signatureB64U] = jwt.split('.');\n\n // Convert the header back to a JOSE object and verify that the 'kid' header value is present.\n const header: JoseHeaderParams = Convert.base64Url(headerB64U).toObject();\n\n if (!header.kid)\n throw new Error(\n `OIDC: Object could not be verified due to missing 'kid' header value.`\n );\n\n // Resolve the Client DID document.\n const { didDocument } = await DidJwk.resolve(header.kid.split('#')[0]);\n\n if (!didDocument)\n throw new Error(\n 'OIDC: Object could not be verified due to Client DID resolution issue.'\n );\n\n // Get the public key used to sign the Object from the DID document.\n const { publicKeyJwk } =\n didDocument.verificationMethod?.find((method: any) => {\n return method.id === header.kid;\n }) ?? {};\n\n if (!publicKeyJwk)\n throw new Error(\n 'OIDC: Object could not be verified due to missing public key in DID document.'\n );\n\n const EdDsa = new EdDsaAlgorithm();\n const isValid = await EdDsa.verify({\n key : publicKeyJwk,\n signature : Convert.base64Url(signatureB64U).toUint8Array(),\n data : Convert.string(`${headerB64U}.${payloadB64U}`).toUint8Array(),\n });\n\n if (!isValid)\n throw new Error(\n 'OIDC: Object failed verification due to invalid signature.'\n );\n\n const object = Convert.base64Url(payloadB64U).toObject();\n\n return object;\n}\n\n/**\n * Fetches the {@Web5ConnectAuthRequest} from the authorize endpoint and decrypts it\n * using the encryption key passed via QR code.\n */\nconst getAuthRequest = async (request_uri: string, encryption_key: string) => {\n const authRequest = await fetch(request_uri);\n const jwe = await authRequest.text();\n const jwt = decryptAuthRequest({\n jwe,\n encryption_key,\n });\n const web5ConnectAuthRequest = (await verifyJwt({\n jwt,\n })) as Web5ConnectAuthRequest;\n\n return web5ConnectAuthRequest;\n};\n\n/** Take the encrypted JWE, decrypt using the code challenge and return a JWT string which will need to be verified */\nfunction decryptAuthRequest({\n jwe,\n encryption_key,\n}: {\n jwe: string;\n encryption_key: string;\n}) {\n const [\n protectedHeaderB64U,\n ,\n nonceB64U,\n ciphertextB64U,\n authenticationTagB64U,\n ] = jwe.split('.');\n\n const encryptionKeyBytes = Convert.base64Url(encryption_key).toUint8Array();\n const protectedHeader = Convert.base64Url(protectedHeaderB64U).toUint8Array();\n const additionalData = protectedHeader;\n const nonce = Convert.base64Url(nonceB64U).toUint8Array();\n const ciphertext = Convert.base64Url(ciphertextB64U).toUint8Array();\n const authenticationTag = Convert.base64Url(\n authenticationTagB64U\n ).toUint8Array();\n\n // The cipher expects the encrypted data and tag to be concatenated.\n const ciphertextAndTag = new Uint8Array([\n ...ciphertext,\n ...authenticationTag,\n ]);\n const chacha = xchacha20poly1305(encryptionKeyBytes, nonce, additionalData);\n const decryptedJwtBytes = chacha.decrypt(ciphertextAndTag);\n const jwt = Convert.uint8Array(decryptedJwtBytes).toString();\n\n return jwt;\n}\n\n/**\n * The client uses to decrypt the jwe obtained from the auth server which contains\n * the {@link Web5ConnectAuthResponse} that was sent by the provider to the auth server.\n *\n * @async\n * @param {BearerDid} clientDid - The did that was initially used by the client for ECDH at connect init.\n * @param {string} jwe - The encrypted data as a jwe.\n * @param {string} pin - The pin that was obtained from the user.\n */\nasync function decryptAuthResponse(\n clientDid: BearerDid,\n jwe: string,\n pin: string\n) {\n const [\n protectedHeaderB64U,\n ,\n nonceB64U,\n ciphertextB64U,\n authenticationTagB64U,\n ] = jwe.split('.');\n\n // get the delegatedid public key from the header\n const header = Convert.base64Url(protectedHeaderB64U).toObject() as Jwk;\n const delegateResolvedDid = await DidJwk.resolve(header.kid!.split('#')[0]);\n\n // derive ECDH shared key using the provider's public key and our clientDid private key\n const sharedKey = await Oidc.deriveSharedKey(\n clientDid,\n delegateResolvedDid.didDocument!\n );\n\n // add the pin to the AAD\n const additionalData = { ...header, pin: pin };\n const AAD = Convert.object(additionalData).toUint8Array();\n\n const nonce = Convert.base64Url(nonceB64U).toUint8Array();\n const ciphertext = Convert.base64Url(ciphertextB64U).toUint8Array();\n const authenticationTag = Convert.base64Url(\n authenticationTagB64U\n ).toUint8Array();\n\n // The cipher expects the encrypted data and tag to be concatenated.\n const ciphertextAndTag = new Uint8Array([\n ...ciphertext,\n ...authenticationTag,\n ]);\n\n // decrypt using the sharedKey\n const chacha = xchacha20poly1305(sharedKey, nonce, AAD);\n const decryptedJwtBytes = chacha.decrypt(ciphertextAndTag);\n const jwt = Convert.uint8Array(decryptedJwtBytes).toString();\n\n return jwt;\n}\n\n/** Derives a shared ECDH private key in order to encrypt the {@link Web5ConnectAuthResponse} */\nasync function deriveSharedKey(\n privateKeyDid: BearerDid,\n publicKeyDid: DidDocument\n) {\n const privatePortableDid = await privateKeyDid.export();\n\n const publicJwk = publicKeyDid.verificationMethod?.[0].publicKeyJwk!;\n const privateJwk = privatePortableDid.privateKeys?.[0]!;\n publicJwk.alg = 'EdDSA';\n\n const publicX25519 = await Ed25519.convertPublicKeyToX25519({\n publicKey: publicJwk,\n });\n const privateX25519 = await Ed25519.convertPrivateKeyToX25519({\n privateKey: privateJwk,\n });\n\n const sharedKey = await X25519.sharedSecret({\n privateKeyA : privateX25519,\n publicKeyB : publicX25519,\n });\n\n const derivedKey = await crypto.subtle.importKey(\n 'raw',\n sharedKey,\n { name: 'HKDF' },\n false,\n ['deriveBits']\n );\n const derivedKeyBits = await crypto.subtle.deriveBits(\n {\n name : 'HKDF',\n hash : 'SHA-256',\n info : new Uint8Array(),\n salt : new Uint8Array(),\n },\n derivedKey,\n 256\n );\n const sharedEncryptionKey = new Uint8Array(derivedKeyBits);\n return sharedEncryptionKey;\n}\n\n/**\n * Encrypts the auth response jwt. Requires a randomPin is added to the AAD of the\n * encryption algorithm in order to prevent man in the middle and eavesdropping attacks.\n * The keyid of the delegate did is used to pass the public key to the client in order\n * for the client to derive the shared ECDH private key.\n */\nfunction encryptAuthResponse({\n jwt,\n encryptionKey,\n delegateDidKeyId,\n randomPin,\n}: {\n jwt: string;\n encryptionKey: Uint8Array;\n delegateDidKeyId: string;\n randomPin: string;\n}) {\n const protectedHeader = {\n alg : 'dir',\n cty : 'JWT',\n enc : 'XC20P',\n typ : 'JWT',\n kid : delegateDidKeyId,\n };\n const nonce = CryptoUtils.randomBytes(24);\n const additionalData = Convert.object({\n ...protectedHeader,\n pin: randomPin,\n }).toUint8Array();\n\n const jwtBytes = Convert.string(jwt).toUint8Array();\n const chacha = xchacha20poly1305(encryptionKey, nonce, additionalData);\n const ciphertextAndTag = chacha.encrypt(jwtBytes);\n\n /** The cipher output concatenates the encrypted data and tag\n * so we need to extract the values for use in the JWE. */\n const ciphertext = ciphertextAndTag.subarray(0, -16);\n const authenticationTag = ciphertextAndTag.subarray(-16);\n\n const compactJwe = [\n Convert.object(protectedHeader).toBase64Url(),\n '', // Empty string since there is no wrapped key.\n Convert.uint8Array(nonce).toBase64Url(),\n Convert.uint8Array(ciphertext).toBase64Url(),\n Convert.uint8Array(authenticationTag).toBase64Url(),\n ].join('.');\n\n return compactJwe;\n}\n\nfunction shouldUseDelegatePermission(scope: DwnPermissionScope): boolean {\n // Currently all record permissions are treated as delegated permissions\n // In the future only methods that modify state will be delegated and the rest will be normal permissions\n if (isRecordPermissionScope(scope)) {\n return true;\n } else if (scope.interface === DwnInterfaceName.Protocols && scope.method === DwnMethodName.Configure) {\n // ProtocolConfigure messages are also delegated, as they modify state\n return true;\n }\n\n // All other permissions are not treated as delegated\n return false;\n}\n\n/**\n * Creates the permission grants that assign to the selectedDid the level of\n * permissions that the web app requested in the {@link Web5ConnectAuthRequest}\n */\nasync function createPermissionGrants(\n selectedDid: string,\n delegateBearerDid: BearerDid,\n agent: Web5Agent,\n scopes: DwnPermissionScope[],\n) {\n const permissionsApi = new AgentPermissionsApi({ agent });\n\n // TODO: cleanup all grants if one fails by deleting them from the DWN: https://github.com/TBD54566975/web5-js/issues/849\n logger.log(`Creating permission grants for ${scopes.length} scopes given...`);\n const permissionGrants = await Promise.all(\n scopes.map((scope) => {\n // check if the scope is a records permission scope, or a protocol configure scope, if so it should use a delegated permission.\n const delegated = shouldUseDelegatePermission(scope);\n return permissionsApi.createGrant({\n delegated,\n store : true,\n grantedTo : delegateBearerDid.uri,\n scope,\n dateExpires : '2040-06-25T16:09:16.693356Z', // TODO: make dateExpires optional\n author : selectedDid,\n });\n })\n );\n\n logger.log(`Sending ${permissionGrants.length} permission grants to remote DWN...`);\n const messagePromises = permissionGrants.map(async (grant) => {\n // Quirk: we have to pull out encodedData out of the message the schema validator doesn't want it there\n const { encodedData, ...rawMessage } = grant.message;\n\n const data = Convert.base64Url(encodedData).toUint8Array();\n const { reply } = await agent.sendDwnRequest({\n author : selectedDid,\n target : selectedDid,\n messageType : DwnInterface.RecordsWrite,\n dataStream : new Blob([data]),\n rawMessage,\n });\n\n // check if the message was sent successfully, if the remote returns 409 the message may have come through already via sync\n if (reply.status.code !== 202 && reply.status.code !== 409) {\n logger.error(`Error sending RecordsWrite: ${reply.status.detail}`);\n logger.error(`RecordsWrite message: ${rawMessage}`);\n throw new Error(\n `Could not send the message. Error details: ${reply.status.detail}`\n );\n }\n\n return grant.message;\n });\n\n try {\n const messages = await Promise.all(messagePromises);\n return messages;\n } catch (error) {\n logger.error(`Error during batch-send of permission grants: ${error}`);\n throw error;\n }\n}\n\n/**\n * Installs the protocol required by the Client on the Provider if it doesn't already exist.\n */\nasync function prepareProtocol(\n selectedDid: string,\n agent: Web5Agent,\n protocolDefinition: DwnProtocolDefinition\n): Promise<void> {\n\n const queryMessage = await agent.processDwnRequest({\n author : selectedDid,\n messageType : DwnInterface.ProtocolsQuery,\n target : selectedDid,\n messageParams : { filter: { protocol: protocolDefinition.protocol } },\n });\n\n if ( queryMessage.reply.status.code !== 200) {\n // if the query failed, throw an error\n throw new Error(\n `Could not fetch protocol: ${queryMessage.reply.status.detail}`\n );\n } else if (queryMessage.reply.entries === undefined || queryMessage.reply.entries.length === 0) {\n logger.log(`Protocol does not exist, creating: ${protocolDefinition.protocol}`);\n\n // send the protocol definition to the remote DWN first, if it passes we can process it locally\n const { reply: sendReply, message: configureMessage } = await agent.sendDwnRequest({\n author : selectedDid,\n target : selectedDid,\n messageType : DwnInterface.ProtocolsConfigure,\n messageParams : { definition: protocolDefinition },\n });\n\n // check if the message was sent successfully, if the remote returns 409 the message may have come through already via sync\n if (sendReply.status.code !== 202 && sendReply.status.code !== 409) {\n throw new Error(`Could not send protocol: ${sendReply.status.detail}`);\n }\n\n // process the protocol locally, we don't have to check if it exists as this is just a convenience over waiting for sync.\n await agent.processDwnRequest({\n author : selectedDid,\n target : selectedDid,\n messageType : DwnInterface.ProtocolsConfigure,\n rawMessage : configureMessage\n });\n\n } else {\n logger.log(`Protocol already exists: ${protocolDefinition.protocol}`);\n\n // the protocol already exists, let's make sure it exists on the remote DWN as the requesting app will need it\n const configureMessage = queryMessage.reply.entries![0];\n const { reply: sendReply } = await agent.sendDwnRequest({\n author : selectedDid,\n target : selectedDid,\n messageType : DwnInterface.ProtocolsConfigure,\n rawMessage : configureMessage,\n });\n\n if (sendReply.status.code !== 202 && sendReply.status.code !== 409) {\n throw new Error(`Could not send protocol: ${sendReply.status.detail}`);\n }\n }\n}\n\n/**\n * Creates a delegate did which the web app will use as its future indentity.\n * Assigns to that DID the level of permissions that the web app requested in\n * the {@link Web5ConnectAuthRequest}. Encrypts via ECDH key that the web app\n * will have access to because the web app has the public key which it provided\n * in the {@link Web5ConnectAuthRequest}. Then sends the ciphertext of this\n * {@link Web5ConnectAuthResponse} to the callback endpoint. Which the\n * web app will need to retrieve from the token endpoint and decrypt with the pin to access.\n */\nasync function submitAuthResponse(\n selectedDid: string,\n authRequest: Web5ConnectAuthRequest,\n randomPin: string,\n agent: Web5Agent\n) {\n const delegateBearerDid = await DidJwk.create();\n const delegatePortableDid = await delegateBearerDid.export();\n\n // TODO: roll back permissions and protocol configurations if an error occurs. Need a way to delete protocols to achieve this.\n const delegateGrantPromises = authRequest.permissionRequests.map(\n async (permissionRequest) => {\n const { protocolDefinition, permissionScopes } = permissionRequest;\n\n // We validate that all permission scopes match the protocol uri of the protocol definition they are provided with.\n const grantsMatchProtocolUri = permissionScopes.every(scope => 'protocol' in scope && scope.protocol === protocolDefinition.protocol);\n if (!grantsMatchProtocolUri) {\n throw new Error('All permission scopes must match the protocol uri they are provided with.');\n }\n\n await prepareProtocol(selectedDid, agent, protocolDefinition);\n\n const permissionGrants = await Oidc.createPermissionGrants(\n selectedDid,\n delegateBearerDid,\n agent,\n permissionScopes\n );\n\n return permissionGrants;\n }\n );\n\n const delegateGrants = (await Promise.all(delegateGrantPromises)).flat();\n\n logger.log('Generating auth response object...');\n const responseObject = await Oidc.createResponseObject({\n //* the IDP's did that was selected to be connected\n iss : selectedDid,\n //* the client's new identity\n sub : delegateBearerDid.uri,\n //* the client's temporary ephemeral did used for connect\n aud : authRequest.client_id,\n //* the nonce of the original auth request\n nonce : authRequest.nonce,\n delegateGrants,\n delegatePortableDid,\n });\n\n // Sign the Response Object using the ephemeral DID's signing key.\n logger.log('Signing auth response object...');\n const responseObjectJwt = await Oidc.signJwt({\n did : delegateBearerDid,\n data : responseObject,\n });\n const clientDid = await DidJwk.resolve(authRequest.client_id);\n\n const sharedKey = await Oidc.deriveSharedKey(\n delegateBearerDid,\n clientDid?.didDocument!\n );\n\n logger.log('Encrypting auth response object...');\n const encryptedResponse = Oidc.encryptAuthResponse({\n jwt : responseObjectJwt!,\n encryptionKey : sharedKey,\n delegateDidKeyId : delegateBearerDid.document.verificationMethod![0].id,\n randomPin,\n });\n\n const formEncodedRequest = new URLSearchParams({\n id_token : encryptedResponse,\n state : authRequest.state,\n }).toString();\n\n logger.log(`Sending auth response object to Web5 Connect server: ${authRequest.redirect_uri}`);\n await fetch(authRequest.redirect_uri, {\n body : formEncodedRequest,\n method : 'POST',\n headers : {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n });\n}\n\nexport const Oidc = {\n createAuthRequest,\n encryptAuthRequest,\n getAuthRequest,\n decryptAuthRequest,\n createPermissionGrants,\n createResponseObject,\n encryptAuthResponse,\n decryptAuthResponse,\n deriveSharedKey,\n signJwt,\n verifyJwt,\n buildOidcUrl,\n generateCodeChallenge,\n submitAuthResponse,\n};\n", "\nimport type { PushedAuthResponse } from './oidc.js';\nimport type { DwnPermissionScope, DwnProtocolDefinition, Web5Agent, Web5ConnectAuthResponse } from './index.js';\n\nimport {\n Oidc,\n} from './oidc.js';\nimport { pollWithTtl } from './utils.js';\n\nimport { Convert, logger } from '@enbox/common';\nimport { CryptoUtils } from '@enbox/crypto';\nimport { DidJwk } from '@enbox/dids';\nimport { DwnInterfaceName, DwnMethodName } from '@enbox/dwn-sdk-js';\n\n/**\n * Initiates the wallet connect process. Used when a client wants to obtain\n * a did from a provider.\n */\nasync function initClient({\n displayName,\n connectServerUrl,\n walletUri,\n permissionRequests,\n onWalletUriReady,\n validatePin,\n}: WalletConnectOptions) {\n // ephemeral client did for ECDH, signing, verification\n // TODO: use separate keys for ECDH vs. sign/verify. could maybe use secp256k1.\n const clientDid = await DidJwk.create();\n\n // TODO: properly implement PKCE. this implementation is lacking server side validations and more.\n // https://github.com/TBD54566975/web5-js/issues/829\n // Derive the code challenge based on the code verifier\n // const { codeChallengeBytes, codeChallengeBase64Url } =\n // await Oidc.generateCodeChallenge();\n const encryptionKey = CryptoUtils.randomBytes(32);\n\n // build callback URL to pass into the auth request\n const callbackEndpoint = Oidc.buildOidcUrl({\n baseURL : connectServerUrl,\n endpoint : 'callback',\n });\n\n // build the PAR request\n const request = await Oidc.createAuthRequest({\n client_id : clientDid.uri,\n scope : 'openid did:jwk',\n redirect_uri : callbackEndpoint,\n // custom properties:\n // code_challenge : codeChallengeBase64Url,\n // code_challenge_method : 'S256',\n permissionRequests : permissionRequests,\n displayName,\n });\n\n // Sign the Request Object using the Client DID's signing key.\n const requestJwt = await Oidc.signJwt({\n did : clientDid,\n data : request,\n });\n\n if (!requestJwt) {\n throw new Error('Unable to sign requestObject');\n }\n // Encrypt the Request Object JWT using the code challenge.\n const requestObjectJwe = await Oidc.encryptAuthRequest({\n jwt: requestJwt,\n encryptionKey,\n });\n\n // Convert the encrypted Request Object to URLSearchParams for form encoding.\n const formEncodedRequest = new URLSearchParams({\n request: requestObjectJwe,\n });\n\n const pushedAuthorizationRequestEndpoint = Oidc.buildOidcUrl({\n baseURL : connectServerUrl,\n endpoint : 'pushedAuthorizationRequest',\n });\n\n const parResponse = await fetch(pushedAuthorizationRequestEndpoint, {\n body : formEncodedRequest,\n method : 'POST',\n headers : {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n });\n\n if (!parResponse.ok) {\n throw new Error(`${parResponse.status}: ${parResponse.statusText}`);\n }\n\n const parData: PushedAuthResponse = await parResponse.json();\n\n // a deeplink to a web5 compatible wallet. if the wallet scans this link it should receive\n // a route to its web5 connect provider flow and the params of where to fetch the auth request.\n logger.log(`Wallet URI: ${walletUri}`);\n const generatedWalletUri = new URL(walletUri);\n generatedWalletUri.searchParams.set('request_uri', parData.request_uri);\n generatedWalletUri.searchParams.set(\n 'encryption_key',\n Convert.uint8Array(encryptionKey).toBase64Url()\n );\n\n // call user's callback so they can send the URI to the wallet as they see fit\n onWalletUriReady(generatedWalletUri.toString());\n\n const tokenUrl = Oidc.buildOidcUrl({\n baseURL : connectServerUrl,\n endpoint : 'token',\n tokenParam : request.state,\n });\n\n // subscribe to receiving a response from the wallet with default TTL. receive ciphertext of {@link Web5ConnectAuthResponse}\n const authResponse = await pollWithTtl(() => fetch(tokenUrl));\n\n if (authResponse) {\n const jwe = await authResponse?.text();\n\n // get the pin from the user and use it as AAD to decrypt\n const pin = await validatePin();\n const jwt = await Oidc.decryptAuthResponse(clientDid, jwe, pin);\n const verifiedAuthResponse = (await Oidc.verifyJwt({\n jwt,\n })) as Web5ConnectAuthResponse;\n\n return {\n delegateGrants : verifiedAuthResponse.delegateGrants,\n delegatePortableDid : verifiedAuthResponse.delegatePortableDid,\n connectedDid : verifiedAuthResponse.iss,\n };\n }\n}\n\n/**\n * Initiates the wallet connect process. Used when a client wants to obtain\n * a did from a provider.\n */\nexport type WalletConnectOptions = {\n /** The user friendly name of the client/app to be displayed when prompting end-user with permission requests. */\n displayName: string;\n\n /** The URL of the intermediary server which relays messages between the client and provider. */\n connectServerUrl: string;\n\n /**\n * The URI of the Provider (wallet).The `onWalletUriReady` will take this wallet\n * uri and add a payload to it which will be used to obtain and decrypt from the `request_uri`.\n * @example `web5://` or `http://localhost:3000/`.\n */\n walletUri: string;\n\n /**\n * The protocols of permissions requested, along with the definition and\n * permission scopes for each protocol. The key is the protocol URL and\n * the value is an object with the protocol definition and the permission scopes.\n */\n permissionRequests: ConnectPermissionRequest[];\n\n /**\n * The Web5 API provides a URI to the wallet based on the `walletUri` plus a query params payload valid for 5 minutes.\n * The link can either be used as a deep link on the same device or a QR code for cross device or both.\n * The query params are `{ request_uri: string; encryption_key: string; }`\n * The wallet will use the `request_uri to contact the intermediary server's `authorize` endpoint\n * and pull down the {@link Web5ConnectAuthRequest} and use the `encryption_key` to decrypt it.\n *\n * @param uri - The URI returned by the web5 connect API to be passed to a provider.\n */\n onWalletUriReady: (uri: string) => void;\n\n /**\n * Function that must be provided to submit the pin entered by the user on the client.\n * The pin is used to decrypt the {@link Web5ConnectAuthResponse} that was retrieved from the\n * token endpoint by the client inside of web5 connect.\n *\n * @returns A promise that resolves to the PIN as a string.\n */\n validatePin: () => Promise<string>;\n};\n\n/**\n * The protocols of permissions requested, along with the definition and permission scopes for each protocol.\n */\nexport type ConnectPermissionRequest = {\n /**\n * The definition of the protocol the permissions are being requested for.\n * In the event that the protocol is not already installed, the wallet will install this given protocol definition.\n */\n protocolDefinition: DwnProtocolDefinition;\n\n /** The scope of the permissions being requested for the given protocol */\n permissionScopes: DwnPermissionScope[];\n};\n\n/**\n * Shorthand for the types of permissions that can be requested.\n */\nexport type Permission = 'write' | 'read' | 'delete' | 'query' | 'subscribe' | 'configure';\n\n/**\n * The options for creating a permission request for a given protocol.\n */\nexport type ProtocolPermissionOptions = {\n /** The protocol definition for the protocol being requested */\n definition: DwnProtocolDefinition;\n\n /** The permissions being requested for the protocol */\n permissions: Permission[];\n};\n\n/**\n * Creates a set of Dwn Permission Scopes to request for a given protocol.\n *\n * If no permissions are provided, the default is to request all relevant record permissions (write, read, delete, query, subscribe).\n * 'configure' is not included by default, as this gives the application a lot of control over the protocol.\n */\nfunction createPermissionRequestForProtocol({ definition, permissions }: ProtocolPermissionOptions): ConnectPermissionRequest {\n const requests: DwnPermissionScope[] = [];\n\n // Add the ability to query for the specific protocol\n requests.push({\n protocol : definition.protocol,\n interface : DwnInterfaceName.Protocols,\n method : DwnMethodName.Query,\n });\n\n // In order to enable sync, we must request permissions for `MessagesQuery`, `MessagesRead` and `MessagesSubscribe`\n requests.push({\n protocol : definition.protocol,\n interface : DwnInterfaceName.Messages,\n method : DwnMethodName.Read,\n }, {\n protocol : definition.protocol,\n interface : DwnInterfaceName.Messages,\n method : DwnMethodName.Query,\n }, {\n protocol : definition.protocol,\n interface : DwnInterfaceName.Messages,\n method : DwnMethodName.Subscribe,\n });\n\n // We also request any additional permissions the user has requested for this protocol\n for (const permission of permissions) {\n switch (permission) {\n case 'write':\n requests.push({\n protocol : definition.protocol,\n interface : DwnInterfaceName.Records,\n method : DwnMethodName.Write,\n });\n break;\n case 'read':\n requests.push({\n protocol : definition.protocol,\n interface : DwnInterfaceName.Records,\n method : DwnMethodName.Read,\n });\n break;\n case 'delete':\n requests.push({\n protocol : definition.protocol,\n interface : DwnInterfaceName.Records,\n method : DwnMethodName.Delete,\n });\n break;\n case 'query':\n requests.push({\n protocol : definition.protocol,\n interface : DwnInterfaceName.Records,\n method : DwnMethodName.Query,\n });\n break;\n case 'subscribe':\n requests.push({\n protocol : definition.protocol,\n interface : DwnInterfaceName.Records,\n method : DwnMethodName.Subscribe,\n });\n break;\n case 'configure':\n requests.push({\n protocol : definition.protocol,\n interface : DwnInterfaceName.Protocols,\n method : DwnMethodName.Configure,\n });\n break;\n }\n }\n\n return {\n protocolDefinition : definition,\n permissionScopes : requests,\n };\n}\n\nexport const WalletConnect = { initClient, createPermissionRequestForProtocol };\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmCA,wBAaO;AA8MP,IAAAC,qBAuBO;AA7LA,IAAK,gBAAL,CAAKC,kBAAL;AACL,EAAAA,4BAAA,mBAAsB,mCAAiB,WAAW,gCAAc,SAAhE;AACA,EAAAA,4BAAA,kBAAsB,mCAAiB,WAAW,gCAAc,QAAhE;AACA,EAAAA,4BAAA,uBAAsB,mCAAiB,WAAW,gCAAc,aAAhE;AACA,EAAAA,4BAAA,wBAAsB,mCAAiB,YAAY,gCAAc,aAAjE;AACA,EAAAA,4BAAA,oBAAsB,mCAAiB,YAAY,gCAAc,SAAjE;AACA,EAAAA,4BAAA,mBAAsB,mCAAiB,UAAU,gCAAc,UAA/D;AACA,EAAAA,4BAAA,kBAAsB,mCAAiB,UAAU,gCAAc,SAA/D;AACA,EAAAA,4BAAA,iBAAsB,mCAAiB,UA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KAAK;AACH,iBAAS,KAAK;AAAA,UACZ,UAAY,WAAW;AAAA,UACvB,WAAY,qCAAiB;AAAA,UAC7B,QAAY,kCAAc;AAAA,QAC5B,CAAC;AACD;AAAA,IACJ;AAAA,EACF;AAEA,SAAO;AAAA,IACL,oBAAqB;AAAA,IACrB,kBAAqB;AAAA,EACvB;AACF;AAEO,IAAM,gBAAgB,EAAE,YAAY,mCAAmC;",
6
+ "names": ["LocalKeyManager", "import_dwn_sdk_js", "DwnInterface", "import_crypto", "import_common", "hash", "hash", "import_crypto", "import_crypto", "import_crypto", "import_webcrypto", "import_common", "import_crypto", "import_crypto", "import_webcrypto", "hash", "hash", "import_crypto", "hash", "import_dids", "import_common", "import_crypto", "import_common", "ms", "import_crypto", "DidInterface", "import_dwn_sdk_js", "import_common", "import_crypto", "import_dids", "import_dwn_sdk_js", "import_dids", "didUtils", "import_crypto", "import_common", "randomBytes", "hash", "crypto", "isBytes", "bytes", "isBytes", "crypto", "isLE", "_32n", "isBytes", "hexes", "bytesToHex", "bytes", "asciis", "asciiToBase16", "hexToBytes", "bytes", "bytesToHex", "isBytes", "hexToBytes", "isBytes", "concatBytes", "isBytes", "_0n", "_1n", "_2n", "number", "Fp", "f", "isLE", "_0n", "f", "_1n", "bytes", "Fp", "_0n", "_1n", "f", "_0n", "_1n", "_2n", "_8n", "Fp", "randomBytes", "uvRatio", "adjustScalarBytes", "bytes", "G", "A", "B", "F", "C", "D", "E", "H", "X3", "Y3", "T3", "Z3", "f", "cofactor", "bytesToHex", "hash", "concatBytes", "_0n", "_1n", "_2n", "_5n", "bytes", "pow", "_2n", "hash", "ensureBytes", "import_dids", "import_common", "import_crypto", "import_crypto", "import_common", "supportedAlgorithms", "LocalKeyManager", "import_crypto", "import_common", "crypto", "import_common", "import_crypto", "crypto", "crypto", "LocalKeyManager", "import_common", "import_dwn_sdk_js", "import_common", "import_crypto", "import_crypto", "import_ms", "import_common", "ms", "serverInfo", "import_crypto", "import_crypto", "IsomorphicWebSocket", "response", "result", "error", "DidRpcMethod", "import_ms", "import_common", "import_dwn_sdk_js", "ms", "protocols", "delegateDid", "import_level", "import_common", "import_dwn_sdk_js", "import_dids", "import_ms", "import_common", "ms", "LocalKeyManager", "import_common", "import_crypto", "import_dids", "import_dwn_sdk_js", "import_common", "import_crypto", "import_dids", "import_dwn_sdk_js"]
7
+ }