tenjin-cli 0.1.0-alpha.15 → 0.1.0-alpha.17

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 (278) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +43 -310
  3. package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
  5. package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
  6. package/dist/chunk-2BKS2FVE.js +93 -0
  7. package/dist/chunk-2BKS2FVE.js.map +1 -0
  8. package/dist/chunk-2G2WLVHB.js +102 -0
  9. package/dist/chunk-2G2WLVHB.js.map +1 -0
  10. package/dist/chunk-2I4QTOLB.js +11 -0
  11. package/dist/chunk-2I4QTOLB.js.map +1 -0
  12. package/dist/chunk-2JGT3KDW.js +172 -0
  13. package/dist/chunk-2JGT3KDW.js.map +1 -0
  14. package/dist/chunk-2QYORQBF.js +55 -0
  15. package/dist/chunk-2QYORQBF.js.map +1 -0
  16. package/dist/chunk-35M3VITA.js +102 -0
  17. package/dist/chunk-35M3VITA.js.map +1 -0
  18. package/dist/{chunk-KINZ23CV.js → chunk-3AUDA53C.js} +4740 -23
  19. package/dist/chunk-3AUDA53C.js.map +1 -0
  20. package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
  21. package/dist/chunk-56MOAIP5.js.map +1 -0
  22. package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
  23. package/dist/chunk-5QHHRMRA.js +227 -0
  24. package/dist/chunk-5QHHRMRA.js.map +1 -0
  25. package/dist/{chunk-JBIKAAT3.js → chunk-5UDD5VSY.js} +8 -8
  26. package/dist/chunk-5UDD5VSY.js.map +1 -0
  27. package/dist/chunk-7QKHZQKW.js +1680 -0
  28. package/dist/chunk-7QKHZQKW.js.map +1 -0
  29. package/dist/{chunk-ZFJJ3EXC.js → chunk-AR7U7BRG.js} +550 -182
  30. package/dist/chunk-AR7U7BRG.js.map +1 -0
  31. package/dist/chunk-AUKDYPPX.js +130 -0
  32. package/dist/chunk-AUKDYPPX.js.map +1 -0
  33. package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
  34. package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
  35. package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
  36. package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
  37. package/dist/chunk-EGELTSPU.js.map +1 -0
  38. package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-J5INH7WB.js +299 -0
  40. package/dist/chunk-J5INH7WB.js.map +1 -0
  41. package/dist/chunk-JLEF5WHM.js +132 -0
  42. package/dist/chunk-JLEF5WHM.js.map +1 -0
  43. package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
  44. package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
  45. package/dist/chunk-KK4YGYTV.js +808 -0
  46. package/dist/chunk-KK4YGYTV.js.map +1 -0
  47. package/dist/{chunk-CPCX67TI.js → chunk-KUBEYXSO.js} +1076 -1038
  48. package/dist/chunk-KUBEYXSO.js.map +1 -0
  49. package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
  50. package/dist/{chunk-NIKXHWOL.js → chunk-LJ4DMVFI.js} +16 -16
  51. package/dist/chunk-LJ4DMVFI.js.map +1 -0
  52. package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
  53. package/dist/chunk-MEFB5KHA.js.map +1 -0
  54. package/dist/{chunk-HPJGOLTN.js → chunk-MRGADYDD.js} +13 -8
  55. package/dist/chunk-MRGADYDD.js.map +1 -0
  56. package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
  57. package/dist/chunk-N35E6CM2.js.map +1 -0
  58. package/dist/chunk-O4ZNKFRU.js +366 -0
  59. package/dist/chunk-O4ZNKFRU.js.map +1 -0
  60. package/dist/chunk-PDA2BVFY.js +244 -0
  61. package/dist/chunk-PDA2BVFY.js.map +1 -0
  62. package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
  63. package/dist/chunk-QDD2RN7G.js +10238 -0
  64. package/dist/chunk-QDD2RN7G.js.map +1 -0
  65. package/dist/chunk-S2NRVRPF.js +171 -0
  66. package/dist/chunk-S2NRVRPF.js.map +1 -0
  67. package/dist/chunk-TGLKKLQG.js +11 -0
  68. package/dist/chunk-TGLKKLQG.js.map +1 -0
  69. package/dist/chunk-TP4D47BY.js +127 -0
  70. package/dist/chunk-TP4D47BY.js.map +1 -0
  71. package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
  72. package/dist/{chunk-UO22YNY4.js → chunk-U2DZISAH.js} +43 -1
  73. package/dist/chunk-U2DZISAH.js.map +1 -0
  74. package/dist/chunk-WGQVJM56.js +165 -0
  75. package/dist/chunk-WGQVJM56.js.map +1 -0
  76. package/dist/{chunk-OLWTRUTS.js → chunk-WLMJE3GJ.js} +35 -16
  77. package/dist/chunk-WLMJE3GJ.js.map +1 -0
  78. package/dist/chunk-WS4JA6TC.js +137 -0
  79. package/dist/chunk-WS4JA6TC.js.map +1 -0
  80. package/dist/chunk-WXC57XGG.js +29 -0
  81. package/dist/chunk-WXC57XGG.js.map +1 -0
  82. package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
  83. package/dist/chunk-XZOEUYMX.js +1784 -0
  84. package/dist/chunk-XZOEUYMX.js.map +1 -0
  85. package/dist/{cli-KKRKBU5T.js → cli-VHYYYYXM.js} +303 -374
  86. package/dist/cli-VHYYYYXM.js.map +1 -0
  87. package/dist/config-5ADBAAXU.js +42 -0
  88. package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
  89. package/dist/doctor-Q35VQW3S.js +436 -0
  90. package/dist/doctor-Q35VQW3S.js.map +1 -0
  91. package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  92. package/dist/{chunk-KAJZHIQ4.js → fund-GDDPL2BB.js} +81 -24
  93. package/dist/fund-GDDPL2BB.js.map +1 -0
  94. package/dist/hook-command-PBERPRE3.js +763 -0
  95. package/dist/hook-command-PBERPRE3.js.map +1 -0
  96. package/dist/index.js +8 -3
  97. package/dist/index.js.map +1 -1
  98. package/dist/install-OKDKGUXM.js +60 -0
  99. package/dist/install-wallet-SI4LZ73K.js +106 -0
  100. package/dist/install-wallet-SI4LZ73K.js.map +1 -0
  101. package/dist/{run-XYTQ5TWQ.js → mcp-XX3WRQEZ.js} +3766 -10677
  102. package/dist/mcp-XX3WRQEZ.js.map +1 -0
  103. package/dist/paths-P2N4JTDZ.js +49 -0
  104. package/dist/pay-3SYKHKWJ.js +39 -0
  105. package/dist/redact-6W23GGJC.js +15 -0
  106. package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
  107. package/dist/{send-G746D7PQ.js → send-LQRKTEJT.js} +29 -29
  108. package/dist/send-LQRKTEJT.js.map +1 -0
  109. package/dist/{chunk-QZ6ROAJU.js → skill-placement-JMDPSKE6.js} +155 -10
  110. package/dist/skill-placement-JMDPSKE6.js.map +1 -0
  111. package/dist/status-FFC6FO72.js +64 -0
  112. package/dist/status-FFC6FO72.js.map +1 -0
  113. package/dist/status-line-SAXSU6CR.js +87 -0
  114. package/dist/status-line-SAXSU6CR.js.map +1 -0
  115. package/dist/status-line-wiring-L2WYIYBM.js +29 -0
  116. package/dist/tenjin-daemon.mjs +20421 -0
  117. package/dist/tenjin-shim.mjs +251 -0
  118. package/dist/tenjin-vitest-reporter.mjs +49 -0
  119. package/dist/uninstall-OACH27UV.js +147 -0
  120. package/dist/uninstall-OACH27UV.js.map +1 -0
  121. package/dist/{update-R76LHOZW.js → update-4W6EKLGZ.js} +132 -16
  122. package/dist/update-4W6EKLGZ.js.map +1 -0
  123. package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  124. package/dist/wallet-BMEXRR3P.js +32 -0
  125. package/dist/wallet-kdf-worker.mjs +980 -0
  126. package/docs/agent-permissions.md +71 -352
  127. package/docs/safety-model.md +16 -6
  128. package/package.json +8 -7
  129. package/LICENSE +0 -21
  130. package/dist/buy-VIRNSYGN.js +0 -47
  131. package/dist/chunk-2MYQN7HM.js +0 -247
  132. package/dist/chunk-2MYQN7HM.js.map +0 -1
  133. package/dist/chunk-2RF2GIJQ.js +0 -1188
  134. package/dist/chunk-2RF2GIJQ.js.map +0 -1
  135. package/dist/chunk-3GL2Z5QK.js +0 -57
  136. package/dist/chunk-3GL2Z5QK.js.map +0 -1
  137. package/dist/chunk-47PP7TAG.js.map +0 -1
  138. package/dist/chunk-4CQIDQOT.js +0 -167
  139. package/dist/chunk-4CQIDQOT.js.map +0 -1
  140. package/dist/chunk-4KG27W2S.js +0 -614
  141. package/dist/chunk-4KG27W2S.js.map +0 -1
  142. package/dist/chunk-5QQTYWEU.js +0 -199
  143. package/dist/chunk-5QQTYWEU.js.map +0 -1
  144. package/dist/chunk-65DTCCJ7.js +0 -21
  145. package/dist/chunk-65DTCCJ7.js.map +0 -1
  146. package/dist/chunk-A5DKHMUN.js +0 -173
  147. package/dist/chunk-A5DKHMUN.js.map +0 -1
  148. package/dist/chunk-B63XPWQ4.js +0 -246
  149. package/dist/chunk-B63XPWQ4.js.map +0 -1
  150. package/dist/chunk-CAR6FHK6.js +0 -105
  151. package/dist/chunk-CAR6FHK6.js.map +0 -1
  152. package/dist/chunk-CPCX67TI.js.map +0 -1
  153. package/dist/chunk-CQBVCYI2.js +0 -162
  154. package/dist/chunk-CQBVCYI2.js.map +0 -1
  155. package/dist/chunk-DBU5CXBV.js +0 -4731
  156. package/dist/chunk-DBU5CXBV.js.map +0 -1
  157. package/dist/chunk-DHJD77OW.js +0 -81
  158. package/dist/chunk-DHJD77OW.js.map +0 -1
  159. package/dist/chunk-EDZSNPE5.js +0 -35
  160. package/dist/chunk-EDZSNPE5.js.map +0 -1
  161. package/dist/chunk-EFWZPUTC.js +0 -65
  162. package/dist/chunk-EFWZPUTC.js.map +0 -1
  163. package/dist/chunk-EPFL6CTE.js +0 -448
  164. package/dist/chunk-EPFL6CTE.js.map +0 -1
  165. package/dist/chunk-GHLVXVZD.js +0 -142
  166. package/dist/chunk-GHLVXVZD.js.map +0 -1
  167. package/dist/chunk-H3SOOJ2I.js +0 -580
  168. package/dist/chunk-H3SOOJ2I.js.map +0 -1
  169. package/dist/chunk-HPJGOLTN.js.map +0 -1
  170. package/dist/chunk-HRGBS2PA.js +0 -203
  171. package/dist/chunk-HRGBS2PA.js.map +0 -1
  172. package/dist/chunk-ITUXPJIS.js +0 -314
  173. package/dist/chunk-ITUXPJIS.js.map +0 -1
  174. package/dist/chunk-JBIKAAT3.js.map +0 -1
  175. package/dist/chunk-KAJZHIQ4.js.map +0 -1
  176. package/dist/chunk-KINZ23CV.js.map +0 -1
  177. package/dist/chunk-LRYV3SK7.js +0 -235
  178. package/dist/chunk-LRYV3SK7.js.map +0 -1
  179. package/dist/chunk-M2O56UK7.js.map +0 -1
  180. package/dist/chunk-MJZZTKCC.js.map +0 -1
  181. package/dist/chunk-NIKXHWOL.js.map +0 -1
  182. package/dist/chunk-OKDRDT74.js +0 -209
  183. package/dist/chunk-OKDRDT74.js.map +0 -1
  184. package/dist/chunk-OKYSNAS3.js +0 -2144
  185. package/dist/chunk-OKYSNAS3.js.map +0 -1
  186. package/dist/chunk-OLWTRUTS.js.map +0 -1
  187. package/dist/chunk-QQ6ELLSA.js +0 -143
  188. package/dist/chunk-QQ6ELLSA.js.map +0 -1
  189. package/dist/chunk-QZ6ROAJU.js.map +0 -1
  190. package/dist/chunk-R7RSCBI7.js +0 -794
  191. package/dist/chunk-R7RSCBI7.js.map +0 -1
  192. package/dist/chunk-SGK2B724.js +0 -67
  193. package/dist/chunk-SGK2B724.js.map +0 -1
  194. package/dist/chunk-U6VPKMGC.js +0 -390
  195. package/dist/chunk-U6VPKMGC.js.map +0 -1
  196. package/dist/chunk-UHTVXQ2O.js +0 -140
  197. package/dist/chunk-UHTVXQ2O.js.map +0 -1
  198. package/dist/chunk-UO22YNY4.js.map +0 -1
  199. package/dist/chunk-US456VUI.js +0 -149
  200. package/dist/chunk-US456VUI.js.map +0 -1
  201. package/dist/chunk-V44J2MXV.js +0 -400
  202. package/dist/chunk-V44J2MXV.js.map +0 -1
  203. package/dist/chunk-VJQKL3YH.js +0 -216
  204. package/dist/chunk-VJQKL3YH.js.map +0 -1
  205. package/dist/chunk-VJSQSLBM.js +0 -1442
  206. package/dist/chunk-VJSQSLBM.js.map +0 -1
  207. package/dist/chunk-VYOJOX4Z.js +0 -165
  208. package/dist/chunk-VYOJOX4Z.js.map +0 -1
  209. package/dist/chunk-WY2K35OL.js +0 -269
  210. package/dist/chunk-WY2K35OL.js.map +0 -1
  211. package/dist/chunk-ZFJJ3EXC.js.map +0 -1
  212. package/dist/chunk-ZOBNS7CX.js.map +0 -1
  213. package/dist/cli-KKRKBU5T.js.map +0 -1
  214. package/dist/config-JMRUNYE6.js +0 -37
  215. package/dist/discover-B5HF6SHM.js +0 -102
  216. package/dist/discover-B5HF6SHM.js.map +0 -1
  217. package/dist/doctor-ZBG7X66D.js +0 -32
  218. package/dist/edit-PZJIILQE.js +0 -40
  219. package/dist/fund-EUDH5KPA.js +0 -40
  220. package/dist/inspect-QC6WEQPN.js +0 -37
  221. package/dist/install-GNK2W3PI.js +0 -972
  222. package/dist/install-GNK2W3PI.js.map +0 -1
  223. package/dist/outcome-KSGWZHUS.js +0 -24
  224. package/dist/pay-BC4UICPA.js +0 -361
  225. package/dist/pay-BC4UICPA.js.map +0 -1
  226. package/dist/publish-LXWFDIKF.js +0 -42
  227. package/dist/read-JMNUQ56P.js +0 -160
  228. package/dist/read-JMNUQ56P.js.map +0 -1
  229. package/dist/run-XYTQ5TWQ.js.map +0 -1
  230. package/dist/search-TSQAB45E.js +0 -25
  231. package/dist/secp256k1-XRPVBC6V.js.map +0 -1
  232. package/dist/send-G746D7PQ.js.map +0 -1
  233. package/dist/session-JBKWMJ24.js +0 -89
  234. package/dist/session-JBKWMJ24.js.map +0 -1
  235. package/dist/skill-heal-WKD67SLJ.js +0 -92
  236. package/dist/skill-heal-WKD67SLJ.js.map +0 -1
  237. package/dist/skill-placement-RIU4AMC2.js +0 -20
  238. package/dist/skill-placement-RIU4AMC2.js.map +0 -1
  239. package/dist/uninstall-5E263VTS.js +0 -73
  240. package/dist/uninstall-5E263VTS.js.map +0 -1
  241. package/dist/update-R76LHOZW.js.map +0 -1
  242. package/dist/usdc-4VCDHFWX.js +0 -38
  243. package/dist/usdc-4VCDHFWX.js.map +0 -1
  244. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
  245. package/dist/wallet-TQ7D5EQ7.js +0 -41
  246. package/dist/wallet-TQ7D5EQ7.js.map +0 -1
  247. package/dist/wallet-ZAVXWLWP.js +0 -32
  248. package/dist/wallet-ZAVXWLWP.js.map +0 -1
  249. package/docs/command-reference.md +0 -303
  250. package/skills/tenjin/SKILL.md +0 -373
  251. package/skills/tenjin-pay/SKILL.md +0 -76
  252. package/skills/tenjin-publish/SKILL.md +0 -227
  253. package/skills/tenjin-publish/references/maintain.md +0 -39
  254. package/skills/tenjin-search/SKILL.md +0 -154
  255. package/skills/tenjin-search/references/permissions.md +0 -112
  256. /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
  257. /package/dist/{buy-VIRNSYGN.js.map → ccip-7RMRLAGV.js.map} +0 -0
  258. /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
  259. /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
  260. /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
  261. /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
  262. /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  263. /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
  264. /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
  265. /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
  266. /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
  267. /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
  268. /package/dist/{ccip-ZGGWQN4X.js.map → config-5ADBAAXU.js.map} +0 -0
  269. /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
  270. /package/dist/{config-JMRUNYE6.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  271. /package/dist/{doctor-ZBG7X66D.js.map → install-OKDKGUXM.js.map} +0 -0
  272. /package/dist/{edit-PZJIILQE.js.map → paths-P2N4JTDZ.js.map} +0 -0
  273. /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-3SYKHKWJ.js.map} +0 -0
  274. /package/dist/{fund-EUDH5KPA.js.map → redact-6W23GGJC.js.map} +0 -0
  275. /package/dist/{inspect-QC6WEQPN.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
  276. /package/dist/{outcome-KSGWZHUS.js.map → status-line-wiring-L2WYIYBM.js.map} +0 -0
  277. /package/dist/{publish-LXWFDIKF.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
  278. /package/dist/{search-TSQAB45E.js.map → wallet-BMEXRR3P.js.map} +0 -0
@@ -1,4 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ createLocalSpendAuthorizer
4
+ } from "./chunk-AUKDYPPX.js";
2
5
  import {
3
6
  hashAuthorization,
4
7
  hashMessage,
@@ -7,44 +10,16 @@ import {
7
10
  publicKeyToAddress,
8
11
  serializeSignature,
9
12
  serializeTransaction
10
- } from "./chunk-M2O56UK7.js";
11
- import {
12
- PRIVATE_KEY_RE,
13
- WALLET_SCHEMA_VERSION,
14
- readWalletRecord,
15
- walletFileMode,
16
- writeWalletRecord
17
- } from "./chunk-GHLVXVZD.js";
18
- import {
19
- emitNotice
20
- } from "./chunk-OLWTRUTS.js";
21
- import {
22
- evaluateSpendPolicy
23
- } from "./chunk-UO22YNY4.js";
24
- import {
25
- withFileLock
26
- } from "./chunk-ZOBNS7CX.js";
27
- import {
28
- CliError,
29
- archivedWalletPath,
30
- external_exports,
31
- fsyncDir,
32
- hasCode,
33
- passphraseBlobPath,
34
- passphraseBlobPathFor,
35
- spendLedgerPath,
36
- walletPath,
37
- writeFileAtomic
38
- } from "./chunk-ZFJJ3EXC.js";
13
+ } from "./chunk-N35E6CM2.js";
39
14
  import {
40
15
  hmac,
41
16
  secp256k1,
42
17
  sha256
43
- } from "./chunk-W6R3HAAG.js";
18
+ } from "./chunk-JRGFKVAZ.js";
44
19
  import {
45
20
  InvalidAddressError,
46
- concat2 as concat,
47
- from,
21
+ concat3 as concat,
22
+ from2 as from,
48
23
  hexToBytes,
49
24
  isAddress,
50
25
  isEqual,
@@ -52,10 +27,10 @@ import {
52
27
  keccak256,
53
28
  numberToHex,
54
29
  random,
55
- slice2 as slice,
30
+ slice3 as slice,
56
31
  toHex,
57
32
  toHex2
58
- } from "./chunk-47PP7TAG.js";
33
+ } from "./chunk-EGELTSPU.js";
59
34
  import {
60
35
  ahash,
61
36
  anumber,
@@ -67,386 +42,867 @@ import {
67
42
  rotl,
68
43
  swap32IfBE,
69
44
  u32
70
- } from "./chunk-KYQVEKP5.js";
71
-
72
- // src/lib/wallet/local.ts
73
- import { link, readdir, unlink as unlink2 } from "fs/promises";
45
+ } from "./chunk-BPMWXTFX.js";
46
+ import {
47
+ emitNotice
48
+ } from "./chunk-WLMJE3GJ.js";
49
+ import {
50
+ hasCode
51
+ } from "./chunk-2I4QTOLB.js";
52
+ import {
53
+ external_exports
54
+ } from "./chunk-AR7U7BRG.js";
55
+ import {
56
+ CliError,
57
+ fsyncDir,
58
+ writeFileAtomic,
59
+ writeFileAtomicExclusive
60
+ } from "./chunk-JLEF5WHM.js";
61
+ import {
62
+ archivedWalletPath,
63
+ passphraseBlobPath,
64
+ passphraseBlobPathFor,
65
+ spendLedgerPath,
66
+ walletPath
67
+ } from "./chunk-2BKS2FVE.js";
74
68
 
75
- // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
76
- function pbkdf2Init(hash, _password, _salt, _opts) {
77
- ahash(hash);
78
- const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
79
- const { c, dkLen, asyncTick } = opts;
80
- anumber(c);
81
- anumber(dkLen);
82
- anumber(asyncTick);
83
- if (c < 1)
84
- throw new Error("iterations (c) should be >= 1");
85
- const password = kdfInputToBytes(_password);
86
- const salt = kdfInputToBytes(_salt);
87
- const DK = new Uint8Array(dkLen);
88
- const PRF = hmac.create(hash, password);
89
- const PRFSalt = PRF._cloneInto().update(salt);
90
- return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
91
- }
92
- function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
93
- PRF.destroy();
94
- PRFSalt.destroy();
95
- if (prfW)
96
- prfW.destroy();
97
- clean(u);
98
- return DK;
69
+ // src/lib/wallet/store.ts
70
+ import { readFile, stat } from "node:fs/promises";
71
+ var PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;
72
+ var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
73
+ var KeystoreV3Schema = external_exports.object({
74
+ crypto: external_exports.object({
75
+ cipher: external_exports.literal("aes-128-ctr"),
76
+ ciphertext: external_exports.string(),
77
+ cipherparams: external_exports.object({ iv: external_exports.string() }),
78
+ kdf: external_exports.enum(["scrypt", "pbkdf2"]),
79
+ kdfparams: external_exports.record(external_exports.string(), external_exports.unknown()),
80
+ mac: external_exports.string()
81
+ }),
82
+ id: external_exports.string(),
83
+ version: external_exports.literal(3)
84
+ });
85
+ var WALLET_SCHEMA_VERSION = 2;
86
+ var WalletRecordSchema = external_exports.object({
87
+ schemaVersion: external_exports.literal(WALLET_SCHEMA_VERSION),
88
+ provider: external_exports.literal("local"),
89
+ address: external_exports.string().regex(ADDRESS_RE, "expected a 0x-prefixed 20-byte address"),
90
+ keystore: KeystoreV3Schema,
91
+ createdAt: external_exports.string()
92
+ });
93
+ async function walletFileExists(dir) {
94
+ return await walletFileMode(dir) !== null;
99
95
  }
100
- function pbkdf2(hash, password, salt, opts) {
101
- const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
102
- let prfW;
103
- const arr = new Uint8Array(4);
104
- const view = createView(arr);
105
- const u = new Uint8Array(PRF.outputLen);
106
- for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
107
- const Ti = DK.subarray(pos, pos + PRF.outputLen);
108
- view.setInt32(0, ti, false);
109
- (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
110
- Ti.set(u.subarray(0, Ti.length));
111
- for (let ui = 1; ui < c; ui++) {
112
- PRF._cloneInto(prfW).update(u).digestInto(u);
113
- for (let i = 0; i < Ti.length; i++)
114
- Ti[i] ^= u[i];
115
- }
96
+ async function walletFileMode(dir) {
97
+ try {
98
+ return (await stat(walletPath(dir))).mode & 511;
99
+ } catch (err) {
100
+ if (isNotFound(err)) return null;
101
+ throw err;
116
102
  }
117
- return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
118
- }
119
-
120
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/generatePrivateKey.js
121
- function generatePrivateKey() {
122
- return toHex(secp256k1.utils.randomPrivateKey());
123
103
  }
124
-
125
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/toAccount.js
126
- function toAccount(source) {
127
- if (typeof source === "string") {
128
- if (!isAddress(source, { strict: false }))
129
- throw new InvalidAddressError({ address: source });
130
- return {
131
- address: source,
132
- type: "json-rpc"
133
- };
104
+ async function readWalletRecord(dir) {
105
+ const path = walletPath(dir);
106
+ let raw;
107
+ try {
108
+ raw = await readFile(path, "utf8");
109
+ } catch (err) {
110
+ if (isNotFound(err)) return null;
111
+ throw new CliError("WALLET_INVALID_KEY", `Could not read the wallet file at ${path}.`, {
112
+ fix: `Check file permissions on ${path}.`,
113
+ cause: err
114
+ });
134
115
  }
135
- if (!isAddress(source.address, { strict: false }))
136
- throw new InvalidAddressError({ address: source.address });
137
- return {
138
- address: source.address,
139
- nonceManager: source.nonceManager,
140
- sign: source.sign,
141
- signAuthorization: source.signAuthorization,
142
- signMessage: source.signMessage,
143
- signTransaction: source.signTransaction,
144
- signTypedData: source.signTypedData,
145
- source: "custom",
146
- type: "local"
147
- };
116
+ let json;
117
+ try {
118
+ json = JSON.parse(raw);
119
+ } catch (err) {
120
+ throw new CliError("WALLET_INVALID_KEY", `The wallet file at ${path} is not valid JSON.`, {
121
+ fix: `Move ${path} aside, then run \`tenjin wallet create\`.`,
122
+ cause: err
123
+ });
124
+ }
125
+ if (isPreEncryptionRecord(json)) {
126
+ throw new CliError(
127
+ "WALLET_INVALID_KEY",
128
+ `The wallet file at ${path} predates encrypted storage.`,
129
+ {
130
+ fix: `Move ${path} aside and run \`tenjin wallet create\`; sweep any funds from the old address first.`
131
+ }
132
+ );
133
+ }
134
+ const newer = newerSchemaVersion(json);
135
+ if (newer !== null) {
136
+ throw new CliError(
137
+ "CONTRACT_MISMATCH",
138
+ `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,
139
+ {
140
+ fix: "Upgrade with `tenjin update`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds."
141
+ }
142
+ );
143
+ }
144
+ const parsed = WalletRecordSchema.safeParse(json);
145
+ if (!parsed.success) {
146
+ throw new CliError(
147
+ "WALLET_INVALID_KEY",
148
+ `The wallet file at ${path} is not a valid wallet record.`,
149
+ {
150
+ fix: `Move ${path} aside, then run \`tenjin wallet create\`.`,
151
+ details: parsed.error.issues
152
+ }
153
+ );
154
+ }
155
+ return parsed.data;
148
156
  }
149
-
150
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/sign.js
151
- var extraEntropy = false;
152
- async function sign({ hash, privateKey, to = "object" }) {
153
- const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), {
154
- lowS: true,
155
- extraEntropy: isHex(extraEntropy, { strict: false }) ? hexToBytes(extraEntropy) : extraEntropy
157
+ function walletExistsError(dir, cause) {
158
+ const path = walletPath(dir);
159
+ return new CliError("WALLET_EXISTS", `A wallet already exists at ${path}.`, {
160
+ fix: `Run \`tenjin wallet create --replace\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable \u2014 never delete the credential-store entry, or the wallet's funds are stranded.`,
161
+ ...cause !== void 0 ? { cause } : {}
156
162
  });
157
- const signature = {
158
- r: numberToHex(r, { size: 32 }),
159
- s: numberToHex(s, { size: 32 }),
160
- v: recovery ? 28n : 27n,
161
- yParity: recovery
162
- };
163
- return (() => {
164
- if (to === "bytes" || to === "hex")
165
- return serializeSignature({ ...signature, to });
166
- return signature;
167
- })();
168
163
  }
169
-
170
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signAuthorization.js
171
- async function signAuthorization(parameters) {
172
- const { chainId, nonce, privateKey, to = "object" } = parameters;
173
- const address = parameters.contractAddress ?? parameters.address;
174
- const signature = await sign({
175
- hash: hashAuthorization({ address, chainId, nonce }),
176
- privateKey,
177
- to
178
- });
179
- if (to === "object")
180
- return {
181
- address,
182
- chainId,
183
- nonce,
184
- ...signature
185
- };
186
- return signature;
164
+ async function writeWalletRecord(dir, record) {
165
+ const validated = WalletRecordSchema.parse(record);
166
+ const path = walletPath(dir);
167
+ try {
168
+ await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}
169
+ `, {
170
+ mode: 384,
171
+ dirMode: 448
172
+ });
173
+ } catch (err) {
174
+ if (hasCode(err, "EEXIST")) throw walletExistsError(dir, err);
175
+ throw err;
176
+ }
187
177
  }
188
-
189
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signMessage.js
190
- async function signMessage({ message, privateKey }) {
191
- return await sign({ hash: hashMessage(message), privateKey, to: "hex" });
178
+ function newerSchemaVersion(json) {
179
+ if (typeof json !== "object" || json === null) return null;
180
+ const v = json.schemaVersion;
181
+ return typeof v === "number" && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;
192
182
  }
193
-
194
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signTransaction.js
195
- async function signTransaction(parameters) {
196
- const { privateKey, transaction, serializer = serializeTransaction } = parameters;
197
- const signableTransaction = (() => {
198
- if (transaction.type === "eip4844")
199
- return {
200
- ...transaction,
201
- sidecars: false
202
- };
203
- return transaction;
204
- })();
205
- const signature = await sign({
206
- hash: keccak256(await serializer(signableTransaction)),
207
- privateKey
208
- });
209
- return await serializer(transaction, signature);
183
+ function isPreEncryptionRecord(json) {
184
+ if (typeof json !== "object" || json === null) return false;
185
+ const rec = json;
186
+ return rec.schemaVersion === 1 || "privateKey" in rec;
210
187
  }
211
-
212
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signTypedData.js
213
- async function signTypedData(parameters) {
214
- const { privateKey, ...typedData } = parameters;
215
- return await sign({
216
- hash: hashTypedData(typedData),
217
- privateKey,
218
- to: "hex"
219
- });
188
+ function isNotFound(err) {
189
+ return hasCode(err, "ENOENT");
220
190
  }
221
191
 
222
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/privateKeyToAccount.js
223
- function privateKeyToAccount(privateKey, options = {}) {
224
- const { nonceManager } = options;
225
- const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
226
- const address = publicKeyToAddress(publicKey);
227
- const account = toAccount({
228
- address,
229
- nonceManager,
230
- async sign({ hash }) {
231
- return sign({ hash, privateKey, to: "hex" });
232
- },
233
- async signAuthorization(authorization) {
234
- return signAuthorization({ ...authorization, privateKey });
235
- },
236
- async signMessage({ message }) {
237
- return signMessage({ message, privateKey });
238
- },
239
- async signTransaction(transaction, { serializer } = {}) {
240
- return signTransaction({ privateKey, transaction, serializer });
241
- },
242
- async signTypedData(typedData) {
243
- return signTypedData({ ...typedData, privateKey });
192
+ // src/lib/wallet/passphrase.ts
193
+ import { execFile } from "node:child_process";
194
+ import { randomBytes } from "node:crypto";
195
+ import { readFile as readFile2, unlink } from "node:fs/promises";
196
+ var KEYCHAIN_SERVICE = "tenjin-cli";
197
+ var LEGACY_ACCOUNT = "wallet";
198
+ var ACCOUNT_ADDRESS_RE = /^0x[0-9a-f]{40}$/;
199
+ var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
200
+ function walletStoreAccount(address) {
201
+ const account = address.toLowerCase();
202
+ if (!ACCOUNT_ADDRESS_RE.test(account)) {
203
+ throw new CliError("INTERNAL", `Not a valid wallet address for passphrase storage: ${address}`);
204
+ }
205
+ return account;
206
+ }
207
+ function defaultExecFor(timeoutMs) {
208
+ return (file, args, stdin) => new Promise((resolve, reject) => {
209
+ const child = execFile(
210
+ file,
211
+ args,
212
+ { encoding: "utf8", ...timeoutMs !== void 0 ? { timeout: timeoutMs } : {} },
213
+ (err, stdout, stderr) => {
214
+ if (err) reject(err);
215
+ else resolve({ stdout, stderr });
216
+ }
217
+ );
218
+ if (stdin !== void 0) {
219
+ child.stdin?.on("error", () => void 0);
220
+ child.stdin?.end(stdin);
244
221
  }
245
222
  });
246
- return {
247
- ...account,
248
- publicKey,
249
- source: "privateKey"
250
- };
251
223
  }
252
-
253
- // node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js
254
- function isBytes(a) {
255
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
256
- }
257
- function abytes(b, ...lengths) {
258
- if (!isBytes(b))
259
- throw new Error("Uint8Array expected");
260
- if (lengths.length > 0 && !lengths.includes(b.length))
261
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
262
- }
263
- function u8(arr) {
264
- return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
265
- }
266
- function u322(arr) {
267
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
268
- }
269
- function clean2(...arrays) {
270
- for (let i = 0; i < arrays.length; i++) {
271
- arrays[i].fill(0);
224
+ function storeFor(deps) {
225
+ switch (deps.platform ?? process.platform) {
226
+ case "darwin":
227
+ return keychainStore(deps);
228
+ case "win32":
229
+ return dpapiStore(deps);
230
+ case "linux":
231
+ return secretServiceStore(deps);
232
+ default:
233
+ return null;
272
234
  }
273
235
  }
274
- var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
275
- function overlapBytes(a, b) {
276
- return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
277
- a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
278
- b.byteOffset < a.byteOffset + a.byteLength;
279
- }
280
- function complexOverlapBytes(input, output) {
281
- if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
282
- throw new Error("complex overlap of input and output is not supported");
283
- }
284
- var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
285
- function wrappedCipher(key, ...args) {
286
- abytes(key);
287
- if (!isLE)
288
- throw new Error("Non little-endian hardware is not yet supported");
289
- if (params.nonceLength !== void 0) {
290
- const nonce = args[0];
291
- if (!nonce)
292
- throw new Error("nonce / iv required");
293
- if (params.varSizeNonce)
294
- abytes(nonce);
295
- else
296
- abytes(nonce, params.nonceLength);
297
- }
298
- const tagl = params.tagLength;
299
- if (tagl && args[1] !== void 0) {
300
- abytes(args[1]);
236
+ async function resolvePassphrase(deps, address) {
237
+ const fromEnv = envPassphrase(deps.env);
238
+ if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
239
+ const store = storeFor(deps);
240
+ if (store !== null) {
241
+ const account = walletStoreAccount(address);
242
+ const own = await store.read(account);
243
+ if (own !== null) return { passphrase: own, source: store.source };
244
+ const legacy = await store.read(LEGACY_ACCOUNT);
245
+ if (legacy !== null) {
246
+ return {
247
+ passphrase: legacy,
248
+ source: store.source,
249
+ migrateLegacy: () => migrateLegacyEntry(store, account, legacy)
250
+ };
301
251
  }
302
- const cipher = constructor(key, ...args);
303
- const checkOutput = (fnLength, output) => {
304
- if (output !== void 0) {
305
- if (fnLength !== 2)
306
- throw new Error("cipher output not supported");
307
- abytes(output);
308
- }
309
- };
310
- let called = false;
311
- const wrCipher = {
312
- encrypt(data, output) {
313
- if (called)
314
- throw new Error("cannot encrypt() twice with same key + nonce");
315
- called = true;
316
- abytes(data);
317
- checkOutput(cipher.encrypt.length, output);
318
- return cipher.encrypt(data, output);
319
- },
320
- decrypt(data, output) {
321
- abytes(data);
322
- if (tagl && data.length < tagl)
323
- throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
324
- checkOutput(cipher.decrypt.length, output);
325
- return cipher.decrypt(data, output);
326
- }
327
- };
328
- return wrCipher;
329
252
  }
330
- Object.assign(wrappedCipher, params);
331
- return wrappedCipher;
332
- };
333
- function getOutput(expectedLength, out, onlyAligned = true) {
334
- if (out === void 0)
335
- return new Uint8Array(expectedLength);
336
- if (out.length !== expectedLength)
337
- throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
338
- if (onlyAligned && !isAligned32(out))
339
- throw new Error("invalid output, must be aligned");
340
- return out;
341
- }
342
- function isAligned32(bytes) {
343
- return bytes.byteOffset % 4 === 0;
344
- }
345
- function copyBytes(bytes) {
346
- return Uint8Array.from(bytes);
253
+ if (canPrompt(deps)) {
254
+ const entered = await promptOf(deps)("Wallet passphrase: ");
255
+ if (entered.length === 0) throw noPassphraseError();
256
+ return { passphrase: entered, source: "prompt" };
257
+ }
258
+ throw noPassphraseError();
347
259
  }
348
-
349
- // node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js
350
- var BLOCK_SIZE = 16;
351
- var BLOCK_SIZE32 = 4;
352
- var POLY = 283;
353
- function mul2(n) {
354
- return n << 1 ^ POLY & -(n >> 7);
260
+ async function migrateLegacyEntry(store, account, passphrase) {
261
+ if (!await store.store(account, passphrase)) return false;
262
+ if (await store.read(account) !== passphrase) return false;
263
+ await store.remove(LEGACY_ACCOUNT);
264
+ return true;
355
265
  }
356
- function mul(a, b) {
357
- let res = 0;
358
- for (; b > 0; b >>= 1) {
359
- res ^= a & -(b & 1);
360
- a = mul2(a);
361
- }
362
- return res;
266
+ async function storePassphraseForWallet(deps, address, passphrase) {
267
+ const store = storeFor(deps);
268
+ if (store === null) return "no-store";
269
+ const account = walletStoreAccount(address);
270
+ if (await store.read(account) === passphrase) return "stored";
271
+ if (store.storable !== void 0 && !store.storable(passphrase)) return "rejected-characters";
272
+ if (!await store.store(account, passphrase)) return "store-failed";
273
+ return await store.read(account) === passphrase ? "stored" : "store-failed";
363
274
  }
364
- var sbox = /* @__PURE__ */ (() => {
365
- const t = new Uint8Array(256);
366
- for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
367
- t[i] = x;
368
- const box = new Uint8Array(256);
369
- box[0] = 99;
370
- for (let i = 0; i < 255; i++) {
371
- let x = t[255 - i];
372
- x |= x << 8;
373
- box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
374
- }
375
- clean2(t);
376
- return box;
377
- })();
378
- var rotr32_8 = (n) => n << 24 | n >>> 8;
379
- var rotl32_8 = (n) => n << 8 | n >>> 24;
380
- function genTtable(sbox2, fn) {
381
- if (sbox2.length !== 256)
382
- throw new Error("Wrong sbox length");
383
- const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
384
- const T1 = T0.map(rotl32_8);
385
- const T2 = T1.map(rotl32_8);
386
- const T3 = T2.map(rotl32_8);
387
- const T01 = new Uint32Array(256 * 256);
388
- const T23 = new Uint32Array(256 * 256);
389
- const sbox22 = new Uint16Array(256 * 256);
390
- for (let i = 0; i < 256; i++) {
391
- for (let j = 0; j < 256; j++) {
392
- const idx = i * 256 + j;
393
- T01[idx] = T0[i] ^ T1[j];
394
- T23[idx] = T2[i] ^ T3[j];
395
- sbox22[idx] = sbox2[i] << 8 | sbox2[j];
275
+ async function resolvePassphraseForCreate(deps, address) {
276
+ const fromEnv = envPassphrase(deps.env);
277
+ if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
278
+ const store = storeFor(deps);
279
+ if (store !== null) {
280
+ const account = walletStoreAccount(address);
281
+ const generated = randomBytes(32).toString("base64url");
282
+ if (await store.store(account, generated) && await store.read(account) === generated) {
283
+ return { passphrase: generated, source: store.source };
396
284
  }
397
285
  }
398
- return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
399
- }
400
- var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
401
- var xPowers = /* @__PURE__ */ (() => {
402
- const p = new Uint8Array(16);
403
- for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
404
- p[i] = x;
405
- return p;
406
- })();
407
- function expandKeyLE(key) {
408
- abytes(key);
409
- const len = key.length;
410
- if (![16, 24, 32].includes(len))
411
- throw new Error("aes: invalid key size, should be 16, 24 or 32, got " + len);
412
- const { sbox2 } = tableEncoding;
413
- const toClean = [];
414
- if (!isAligned32(key))
415
- toClean.push(key = copyBytes(key));
416
- const k32 = u322(key);
417
- const Nk = k32.length;
418
- const subByte = (n) => applySbox(sbox2, n, n, n, n);
419
- const xk = new Uint32Array(len + 28);
420
- xk.set(k32);
421
- for (let i = Nk; i < xk.length; i++) {
422
- let t = xk[i - 1];
423
- if (i % Nk === 0)
424
- t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
425
- else if (Nk > 6 && i % Nk === 4)
426
- t = subByte(t);
427
- xk[i] = xk[i - Nk] ^ t;
286
+ if (canPrompt(deps)) {
287
+ const prompt = promptOf(deps);
288
+ const first = await prompt("Set a wallet passphrase: ");
289
+ if (first.length === 0) {
290
+ throw new CliError("USAGE", "The wallet passphrase must not be empty.", {
291
+ fix: "Enter a non-empty passphrase, or set TENJIN_WALLET_PASSPHRASE."
292
+ });
293
+ }
294
+ const second = await prompt("Confirm passphrase: ");
295
+ if (first !== second) {
296
+ throw new CliError("USAGE", "The passphrases did not match.", {
297
+ fix: "Run `tenjin wallet create` again and enter the same passphrase both times."
298
+ });
299
+ }
300
+ return { passphrase: first, source: "prompt" };
428
301
  }
429
- clean2(...toClean);
430
- return xk;
431
- }
432
- function apply0123(T01, T23, s0, s1, s2, s3) {
433
- return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
434
- }
435
- function applySbox(sbox2, s0, s1, s2, s3) {
436
- return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
302
+ throw noPassphraseError();
437
303
  }
438
- function encrypt(xk, s0, s1, s2, s3) {
439
- const { sbox2, T01, T23 } = tableEncoding;
440
- let k = 0;
441
- s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
442
- const rounds = xk.length / 4 - 2;
443
- for (let i = 0; i < rounds; i++) {
444
- const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
445
- const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
446
- const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
447
- const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
448
- s0 = t02, s1 = t12, s2 = t22, s3 = t32;
449
- }
304
+ function keychainStore(deps) {
305
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
306
+ return {
307
+ source: "keychain",
308
+ async read(account) {
309
+ try {
310
+ const { stdout } = await exec("security", [
311
+ "find-generic-password",
312
+ "-s",
313
+ KEYCHAIN_SERVICE,
314
+ "-a",
315
+ account,
316
+ "-w"
317
+ ]);
318
+ return trimmedNonEmpty(stdout);
319
+ } catch {
320
+ return null;
321
+ }
322
+ },
323
+ // The one backend that interpolates into a command line, so only base64url
324
+ // values pass; escaping is NOT a safe alternative (backslash bites even
325
+ // inside single quotes there).
326
+ storable: (passphrase) => BASE64URL_RE.test(passphrase),
327
+ async store(account, passphrase) {
328
+ if (!BASE64URL_RE.test(passphrase) || !BASE64URL_RE.test(account)) return false;
329
+ try {
330
+ const command = `add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} -w '${passphrase}'
331
+ `;
332
+ await exec("security", ["-i"], command);
333
+ return true;
334
+ } catch {
335
+ return false;
336
+ }
337
+ },
338
+ async remove(account) {
339
+ try {
340
+ await exec("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account]);
341
+ return true;
342
+ } catch {
343
+ return false;
344
+ }
345
+ }
346
+ };
347
+ }
348
+ var DPAPI_PROTECT_SCRIPT = [
349
+ "Add-Type -AssemblyName System.Security;",
350
+ "$in = [Console]::In.ReadToEnd();",
351
+ "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in);",
352
+ "$prot = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser');",
353
+ "[Console]::Out.Write([Convert]::ToBase64String($prot));"
354
+ ].join(" ");
355
+ var DPAPI_UNPROTECT_SCRIPT = [
356
+ "Add-Type -AssemblyName System.Security;",
357
+ "$in = [Console]::In.ReadToEnd();",
358
+ "$blob = [Convert]::FromBase64String($in.Trim());",
359
+ "$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser');",
360
+ "[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain));"
361
+ ].join(" ");
362
+ function powershellArgs(script) {
363
+ return ["-NoProfile", "-NonInteractive", "-Command", script];
364
+ }
365
+ function dpapiStore(deps) {
366
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
367
+ const blobPathFor = (account) => account === LEGACY_ACCOUNT ? passphraseBlobPath(deps.dir) : passphraseBlobPathFor(account, deps.dir);
368
+ return {
369
+ source: "dpapi",
370
+ async read(account) {
371
+ let blob;
372
+ try {
373
+ blob = await readFile2(blobPathFor(account), "utf8");
374
+ } catch {
375
+ return null;
376
+ }
377
+ try {
378
+ const { stdout } = await exec(
379
+ "powershell.exe",
380
+ powershellArgs(DPAPI_UNPROTECT_SCRIPT),
381
+ blob
382
+ );
383
+ const passphrase = stdout.replace(/\r?\n$/, "");
384
+ return passphrase.length > 0 ? passphrase : null;
385
+ } catch {
386
+ return null;
387
+ }
388
+ },
389
+ async store(account, passphrase) {
390
+ try {
391
+ const { stdout } = await exec(
392
+ "powershell.exe",
393
+ powershellArgs(DPAPI_PROTECT_SCRIPT),
394
+ passphrase
395
+ );
396
+ const blob = stdout.replace(/\r?\n$/, "").trim();
397
+ if (blob.length === 0) return false;
398
+ await writeFileAtomic(blobPathFor(account), blob, { mode: 384 });
399
+ return true;
400
+ } catch {
401
+ return false;
402
+ }
403
+ },
404
+ async remove(account) {
405
+ try {
406
+ await unlink(blobPathFor(account));
407
+ return true;
408
+ } catch {
409
+ return false;
410
+ }
411
+ }
412
+ };
413
+ }
414
+ function secretServiceStore(deps) {
415
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
416
+ return {
417
+ source: "secret-service",
418
+ async read(account) {
419
+ try {
420
+ const { stdout } = await exec("secret-tool", [
421
+ "lookup",
422
+ "service",
423
+ KEYCHAIN_SERVICE,
424
+ "account",
425
+ account
426
+ ]);
427
+ return trimmedNonEmpty(stdout);
428
+ } catch {
429
+ return null;
430
+ }
431
+ },
432
+ async store(account, passphrase) {
433
+ try {
434
+ await exec(
435
+ "secret-tool",
436
+ [
437
+ "store",
438
+ `--label=tenjin-cli wallet ${account}`,
439
+ "service",
440
+ KEYCHAIN_SERVICE,
441
+ "account",
442
+ account
443
+ ],
444
+ passphrase
445
+ );
446
+ return true;
447
+ } catch {
448
+ return false;
449
+ }
450
+ },
451
+ async remove(account) {
452
+ try {
453
+ await exec("secret-tool", ["clear", "service", KEYCHAIN_SERVICE, "account", account]);
454
+ return true;
455
+ } catch {
456
+ return false;
457
+ }
458
+ }
459
+ };
460
+ }
461
+ function trimmedNonEmpty(stdout) {
462
+ const value = stdout.replace(/\r?\n$/, "");
463
+ return value.length > 0 ? value : null;
464
+ }
465
+ function envPassphrase(env) {
466
+ const value = env.TENJIN_WALLET_PASSPHRASE;
467
+ return value !== void 0 && value.length > 0 ? value : null;
468
+ }
469
+ function canPrompt(deps) {
470
+ return deps.isTTY ?? Boolean(process.stdin.isTTY);
471
+ }
472
+ function promptOf(deps) {
473
+ return deps.prompt ?? promptHidden;
474
+ }
475
+ function noPassphraseError() {
476
+ return new CliError("USAGE", "No wallet passphrase is available.", {
477
+ fix: "Set TENJIN_WALLET_PASSPHRASE (headless) or run in a terminal."
478
+ });
479
+ }
480
+ var CTRL_C = 3;
481
+ var CTRL_D = 4;
482
+ var BACKSPACE = 127;
483
+ var BACKSPACE_ALT = 8;
484
+ function promptHidden(label) {
485
+ return new Promise((resolve, reject) => {
486
+ const stdin = process.stdin;
487
+ const stderr = process.stderr;
488
+ const wasRaw = stdin.isRaw;
489
+ let value = "";
490
+ const cleanup = () => {
491
+ stdin.setRawMode?.(wasRaw ?? false);
492
+ stdin.pause();
493
+ stdin.removeListener("data", onData);
494
+ };
495
+ const onData = (chunk) => {
496
+ for (const ch of chunk.toString("utf8")) {
497
+ const code = ch.charCodeAt(0);
498
+ if (ch === "\n" || ch === "\r" || code === CTRL_D) {
499
+ cleanup();
500
+ stderr.write("\n");
501
+ resolve(value);
502
+ return;
503
+ }
504
+ if (code === CTRL_C) {
505
+ cleanup();
506
+ stderr.write("\n");
507
+ reject(
508
+ new CliError("USAGE", "Passphrase entry was cancelled.", {
509
+ fix: "Run the command again, or set TENJIN_WALLET_PASSPHRASE."
510
+ })
511
+ );
512
+ return;
513
+ }
514
+ if (code === BACKSPACE || code === BACKSPACE_ALT) {
515
+ value = value.slice(0, -1);
516
+ } else {
517
+ value += ch;
518
+ }
519
+ }
520
+ };
521
+ stderr.write(label);
522
+ stdin.setRawMode?.(true);
523
+ stdin.resume();
524
+ stdin.on("data", onData);
525
+ });
526
+ }
527
+
528
+ // src/lib/wallet/local.ts
529
+ import { link, readdir, unlink as unlink2 } from "node:fs/promises";
530
+
531
+ // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
532
+ function pbkdf2Init(hash, _password, _salt, _opts) {
533
+ ahash(hash);
534
+ const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
535
+ const { c, dkLen, asyncTick } = opts;
536
+ anumber(c);
537
+ anumber(dkLen);
538
+ anumber(asyncTick);
539
+ if (c < 1)
540
+ throw new Error("iterations (c) should be >= 1");
541
+ const password = kdfInputToBytes(_password);
542
+ const salt = kdfInputToBytes(_salt);
543
+ const DK = new Uint8Array(dkLen);
544
+ const PRF = hmac.create(hash, password);
545
+ const PRFSalt = PRF._cloneInto().update(salt);
546
+ return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
547
+ }
548
+ function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
549
+ PRF.destroy();
550
+ PRFSalt.destroy();
551
+ if (prfW)
552
+ prfW.destroy();
553
+ clean(u);
554
+ return DK;
555
+ }
556
+ function pbkdf2(hash, password, salt, opts) {
557
+ const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
558
+ let prfW;
559
+ const arr = new Uint8Array(4);
560
+ const view = createView(arr);
561
+ const u = new Uint8Array(PRF.outputLen);
562
+ for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
563
+ const Ti = DK.subarray(pos, pos + PRF.outputLen);
564
+ view.setInt32(0, ti, false);
565
+ (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
566
+ Ti.set(u.subarray(0, Ti.length));
567
+ for (let ui = 1; ui < c; ui++) {
568
+ PRF._cloneInto(prfW).update(u).digestInto(u);
569
+ for (let i = 0; i < Ti.length; i++)
570
+ Ti[i] ^= u[i];
571
+ }
572
+ }
573
+ return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
574
+ }
575
+
576
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/generatePrivateKey.js
577
+ function generatePrivateKey() {
578
+ return toHex(secp256k1.utils.randomPrivateKey());
579
+ }
580
+
581
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/toAccount.js
582
+ function toAccount(source) {
583
+ if (typeof source === "string") {
584
+ if (!isAddress(source, { strict: false }))
585
+ throw new InvalidAddressError({ address: source });
586
+ return {
587
+ address: source,
588
+ type: "json-rpc"
589
+ };
590
+ }
591
+ if (!isAddress(source.address, { strict: false }))
592
+ throw new InvalidAddressError({ address: source.address });
593
+ return {
594
+ address: source.address,
595
+ nonceManager: source.nonceManager,
596
+ sign: source.sign,
597
+ signAuthorization: source.signAuthorization,
598
+ signMessage: source.signMessage,
599
+ signTransaction: source.signTransaction,
600
+ signTypedData: source.signTypedData,
601
+ source: "custom",
602
+ type: "local"
603
+ };
604
+ }
605
+
606
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/sign.js
607
+ var extraEntropy = false;
608
+ async function sign({ hash, privateKey, to = "object" }) {
609
+ const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), {
610
+ lowS: true,
611
+ extraEntropy: isHex(extraEntropy, { strict: false }) ? hexToBytes(extraEntropy) : extraEntropy
612
+ });
613
+ const signature = {
614
+ r: numberToHex(r, { size: 32 }),
615
+ s: numberToHex(s, { size: 32 }),
616
+ v: recovery ? 28n : 27n,
617
+ yParity: recovery
618
+ };
619
+ return (() => {
620
+ if (to === "bytes" || to === "hex")
621
+ return serializeSignature({ ...signature, to });
622
+ return signature;
623
+ })();
624
+ }
625
+
626
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signAuthorization.js
627
+ async function signAuthorization(parameters) {
628
+ const { chainId, nonce, privateKey, to = "object" } = parameters;
629
+ const address = parameters.contractAddress ?? parameters.address;
630
+ const signature = await sign({
631
+ hash: hashAuthorization({ address, chainId, nonce }),
632
+ privateKey,
633
+ to
634
+ });
635
+ if (to === "object")
636
+ return {
637
+ address,
638
+ chainId,
639
+ nonce,
640
+ ...signature
641
+ };
642
+ return signature;
643
+ }
644
+
645
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signMessage.js
646
+ async function signMessage({ message, privateKey }) {
647
+ return await sign({ hash: hashMessage(message), privateKey, to: "hex" });
648
+ }
649
+
650
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signTransaction.js
651
+ async function signTransaction(parameters) {
652
+ const { privateKey, transaction, serializer = serializeTransaction } = parameters;
653
+ const signableTransaction = (() => {
654
+ if (transaction.type === "eip4844")
655
+ return {
656
+ ...transaction,
657
+ sidecars: false
658
+ };
659
+ return transaction;
660
+ })();
661
+ const signature = await sign({
662
+ hash: keccak256(await serializer(signableTransaction)),
663
+ privateKey
664
+ });
665
+ return await serializer(transaction, signature);
666
+ }
667
+
668
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signTypedData.js
669
+ async function signTypedData(parameters) {
670
+ const { privateKey, ...typedData } = parameters;
671
+ return await sign({
672
+ hash: hashTypedData(typedData),
673
+ privateKey,
674
+ to: "hex"
675
+ });
676
+ }
677
+
678
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/privateKeyToAccount.js
679
+ function privateKeyToAccount(privateKey, options = {}) {
680
+ const { nonceManager } = options;
681
+ const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
682
+ const address = publicKeyToAddress(publicKey);
683
+ const account = toAccount({
684
+ address,
685
+ nonceManager,
686
+ async sign({ hash }) {
687
+ return sign({ hash, privateKey, to: "hex" });
688
+ },
689
+ async signAuthorization(authorization) {
690
+ return signAuthorization({ ...authorization, privateKey });
691
+ },
692
+ async signMessage({ message }) {
693
+ return signMessage({ message, privateKey });
694
+ },
695
+ async signTransaction(transaction, { serializer } = {}) {
696
+ return signTransaction({ privateKey, transaction, serializer });
697
+ },
698
+ async signTypedData(typedData) {
699
+ return signTypedData({ ...typedData, privateKey });
700
+ }
701
+ });
702
+ return {
703
+ ...account,
704
+ publicKey,
705
+ source: "privateKey"
706
+ };
707
+ }
708
+
709
+ // node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js
710
+ function isBytes(a) {
711
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
712
+ }
713
+ function abytes(b, ...lengths) {
714
+ if (!isBytes(b))
715
+ throw new Error("Uint8Array expected");
716
+ if (lengths.length > 0 && !lengths.includes(b.length))
717
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
718
+ }
719
+ function u8(arr) {
720
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
721
+ }
722
+ function u322(arr) {
723
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
724
+ }
725
+ function clean2(...arrays) {
726
+ for (let i = 0; i < arrays.length; i++) {
727
+ arrays[i].fill(0);
728
+ }
729
+ }
730
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
731
+ function overlapBytes(a, b) {
732
+ return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
733
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
734
+ b.byteOffset < a.byteOffset + a.byteLength;
735
+ }
736
+ function complexOverlapBytes(input, output) {
737
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
738
+ throw new Error("complex overlap of input and output is not supported");
739
+ }
740
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
741
+ function wrappedCipher(key, ...args) {
742
+ abytes(key);
743
+ if (!isLE)
744
+ throw new Error("Non little-endian hardware is not yet supported");
745
+ if (params.nonceLength !== void 0) {
746
+ const nonce = args[0];
747
+ if (!nonce)
748
+ throw new Error("nonce / iv required");
749
+ if (params.varSizeNonce)
750
+ abytes(nonce);
751
+ else
752
+ abytes(nonce, params.nonceLength);
753
+ }
754
+ const tagl = params.tagLength;
755
+ if (tagl && args[1] !== void 0) {
756
+ abytes(args[1]);
757
+ }
758
+ const cipher = constructor(key, ...args);
759
+ const checkOutput = (fnLength, output) => {
760
+ if (output !== void 0) {
761
+ if (fnLength !== 2)
762
+ throw new Error("cipher output not supported");
763
+ abytes(output);
764
+ }
765
+ };
766
+ let called = false;
767
+ const wrCipher = {
768
+ encrypt(data, output) {
769
+ if (called)
770
+ throw new Error("cannot encrypt() twice with same key + nonce");
771
+ called = true;
772
+ abytes(data);
773
+ checkOutput(cipher.encrypt.length, output);
774
+ return cipher.encrypt(data, output);
775
+ },
776
+ decrypt(data, output) {
777
+ abytes(data);
778
+ if (tagl && data.length < tagl)
779
+ throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
780
+ checkOutput(cipher.decrypt.length, output);
781
+ return cipher.decrypt(data, output);
782
+ }
783
+ };
784
+ return wrCipher;
785
+ }
786
+ Object.assign(wrappedCipher, params);
787
+ return wrappedCipher;
788
+ };
789
+ function getOutput(expectedLength, out, onlyAligned = true) {
790
+ if (out === void 0)
791
+ return new Uint8Array(expectedLength);
792
+ if (out.length !== expectedLength)
793
+ throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
794
+ if (onlyAligned && !isAligned32(out))
795
+ throw new Error("invalid output, must be aligned");
796
+ return out;
797
+ }
798
+ function isAligned32(bytes) {
799
+ return bytes.byteOffset % 4 === 0;
800
+ }
801
+ function copyBytes(bytes) {
802
+ return Uint8Array.from(bytes);
803
+ }
804
+
805
+ // node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js
806
+ var BLOCK_SIZE = 16;
807
+ var BLOCK_SIZE32 = 4;
808
+ var POLY = 283;
809
+ function mul2(n) {
810
+ return n << 1 ^ POLY & -(n >> 7);
811
+ }
812
+ function mul(a, b) {
813
+ let res = 0;
814
+ for (; b > 0; b >>= 1) {
815
+ res ^= a & -(b & 1);
816
+ a = mul2(a);
817
+ }
818
+ return res;
819
+ }
820
+ var sbox = /* @__PURE__ */ (() => {
821
+ const t = new Uint8Array(256);
822
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
823
+ t[i] = x;
824
+ const box = new Uint8Array(256);
825
+ box[0] = 99;
826
+ for (let i = 0; i < 255; i++) {
827
+ let x = t[255 - i];
828
+ x |= x << 8;
829
+ box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
830
+ }
831
+ clean2(t);
832
+ return box;
833
+ })();
834
+ var rotr32_8 = (n) => n << 24 | n >>> 8;
835
+ var rotl32_8 = (n) => n << 8 | n >>> 24;
836
+ function genTtable(sbox2, fn) {
837
+ if (sbox2.length !== 256)
838
+ throw new Error("Wrong sbox length");
839
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
840
+ const T1 = T0.map(rotl32_8);
841
+ const T2 = T1.map(rotl32_8);
842
+ const T3 = T2.map(rotl32_8);
843
+ const T01 = new Uint32Array(256 * 256);
844
+ const T23 = new Uint32Array(256 * 256);
845
+ const sbox22 = new Uint16Array(256 * 256);
846
+ for (let i = 0; i < 256; i++) {
847
+ for (let j = 0; j < 256; j++) {
848
+ const idx = i * 256 + j;
849
+ T01[idx] = T0[i] ^ T1[j];
850
+ T23[idx] = T2[i] ^ T3[j];
851
+ sbox22[idx] = sbox2[i] << 8 | sbox2[j];
852
+ }
853
+ }
854
+ return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
855
+ }
856
+ var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
857
+ var xPowers = /* @__PURE__ */ (() => {
858
+ const p = new Uint8Array(16);
859
+ for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
860
+ p[i] = x;
861
+ return p;
862
+ })();
863
+ function expandKeyLE(key) {
864
+ abytes(key);
865
+ const len = key.length;
866
+ if (![16, 24, 32].includes(len))
867
+ throw new Error("aes: invalid key size, should be 16, 24 or 32, got " + len);
868
+ const { sbox2 } = tableEncoding;
869
+ const toClean = [];
870
+ if (!isAligned32(key))
871
+ toClean.push(key = copyBytes(key));
872
+ const k32 = u322(key);
873
+ const Nk = k32.length;
874
+ const subByte = (n) => applySbox(sbox2, n, n, n, n);
875
+ const xk = new Uint32Array(len + 28);
876
+ xk.set(k32);
877
+ for (let i = Nk; i < xk.length; i++) {
878
+ let t = xk[i - 1];
879
+ if (i % Nk === 0)
880
+ t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
881
+ else if (Nk > 6 && i % Nk === 4)
882
+ t = subByte(t);
883
+ xk[i] = xk[i - Nk] ^ t;
884
+ }
885
+ clean2(...toClean);
886
+ return xk;
887
+ }
888
+ function apply0123(T01, T23, s0, s1, s2, s3) {
889
+ return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
890
+ }
891
+ function applySbox(sbox2, s0, s1, s2, s3) {
892
+ return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
893
+ }
894
+ function encrypt(xk, s0, s1, s2, s3) {
895
+ const { sbox2, T01, T23 } = tableEncoding;
896
+ let k = 0;
897
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
898
+ const rounds = xk.length / 4 - 2;
899
+ for (let i = 0; i < rounds; i++) {
900
+ const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
901
+ const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
902
+ const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
903
+ const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
904
+ s0 = t02, s1 = t12, s2 = t22, s3 = t32;
905
+ }
450
906
  const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
451
907
  const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
452
908
  const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
@@ -570,539 +1026,251 @@ function XorAndSalsa(prev, pi, input, ii, out, oi) {
570
1026
  out[oi++] = y12 + x12 | 0;
571
1027
  out[oi++] = y13 + x13 | 0;
572
1028
  out[oi++] = y14 + x14 | 0;
573
- out[oi++] = y15 + x15 | 0;
574
- }
575
- function BlockMix(input, ii, out, oi, r) {
576
- let head = oi + 0;
577
- let tail = oi + 16 * r;
578
- for (let i = 0; i < 16; i++)
579
- out[tail + i] = input[ii + (2 * r - 1) * 16 + i];
580
- for (let i = 0; i < r; i++, head += 16, ii += 16) {
581
- XorAndSalsa(out, tail, input, ii, out, head);
582
- if (i > 0)
583
- tail += 16;
584
- XorAndSalsa(out, head, input, ii += 16, out, tail);
585
- }
586
- }
587
- function scryptInit(password, salt, _opts) {
588
- const opts = checkOpts({
589
- dkLen: 32,
590
- asyncTick: 10,
591
- maxmem: 1024 ** 3 + 1024
592
- }, _opts);
593
- const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
594
- anumber(N);
595
- anumber(r);
596
- anumber(p);
597
- anumber(dkLen);
598
- anumber(asyncTick);
599
- anumber(maxmem);
600
- if (onProgress !== void 0 && typeof onProgress !== "function")
601
- throw new Error("progressCb should be function");
602
- const blockSize = 128 * r;
603
- const blockSize32 = blockSize / 4;
604
- const pow32 = Math.pow(2, 32);
605
- if (N <= 1 || (N & N - 1) !== 0 || N > pow32) {
606
- throw new Error("Scrypt: N must be larger than 1, a power of 2, and less than 2^32");
607
- }
608
- if (p < 0 || p > (pow32 - 1) * 32 / blockSize) {
609
- throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");
610
- }
611
- if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
612
- throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");
613
- }
614
- const memUsed = blockSize * (N + p);
615
- if (memUsed > maxmem) {
616
- throw new Error("Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of " + maxmem);
617
- }
618
- const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
619
- const B32 = u32(B);
620
- const V = u32(new Uint8Array(blockSize * N));
621
- const tmp = u32(new Uint8Array(blockSize));
622
- let blockMixCb = () => {
623
- };
624
- if (onProgress) {
625
- const totalBlockMix = 2 * N * p;
626
- const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1);
627
- let blockMixCnt = 0;
628
- blockMixCb = () => {
629
- blockMixCnt++;
630
- if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
631
- onProgress(blockMixCnt / totalBlockMix);
632
- };
633
- }
634
- return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
635
- }
636
- function scryptOutput(password, dkLen, B, V, tmp) {
637
- const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
638
- clean(B, V, tmp);
639
- return res;
640
- }
641
- async function scryptAsync(password, salt, opts) {
642
- const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
643
- swap32IfBE(B32);
644
- for (let pi = 0; pi < p; pi++) {
645
- const Pi = blockSize32 * pi;
646
- for (let i = 0; i < blockSize32; i++)
647
- V[i] = B32[Pi + i];
648
- let pos = 0;
649
- await asyncLoop(N - 1, asyncTick, () => {
650
- BlockMix(V, pos, V, pos += blockSize32, r);
651
- blockMixCb();
652
- });
653
- BlockMix(V, (N - 1) * blockSize32, B32, Pi, r);
654
- blockMixCb();
655
- await asyncLoop(N, asyncTick, () => {
656
- const j = B32[Pi + blockSize32 - 16] % N;
657
- for (let k = 0; k < blockSize32; k++)
658
- tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];
659
- BlockMix(tmp, 0, B32, Pi, r);
660
- blockMixCb();
661
- });
662
- }
663
- swap32IfBE(B32);
664
- return scryptOutput(password, dkLen, B, V, tmp);
665
- }
666
-
667
- // node_modules/.pnpm/ox@0.14.30_typescript@6.0.3_zod@4.4.3/node_modules/ox/_esm/core/Keystore.js
668
- function decrypt(keystore, key, options = {}) {
669
- const { as = "Hex" } = options;
670
- const key_ = from(typeof key === "function" ? key() : key);
671
- const encKey = slice(key_, 0, 16);
672
- const macKey = slice(key_, 16, 32);
673
- const ciphertext = from(`0x${keystore.crypto.ciphertext}`);
674
- const mac = keccak2562(concat(macKey, ciphertext));
675
- if (!isEqual(mac, from(`0x${keystore.crypto.mac}`)))
676
- throw new Error("corrupt keystore");
677
- const data = ctr(encKey, from(`0x${keystore.crypto.cipherparams.iv}`)).decrypt(ciphertext);
678
- if (as === "Hex")
679
- return toHex2(data);
680
- return data;
681
- }
682
- function encrypt2(privateKey, key, options) {
683
- const { id = crypto.randomUUID(), kdf, kdfparams, iv } = options;
684
- const key_ = from(typeof key === "function" ? key() : key);
685
- const value_ = from(privateKey);
686
- const encKey = slice(key_, 0, 16);
687
- const macKey = slice(key_, 16, 32);
688
- const ciphertext = ctr(encKey, iv).encrypt(value_);
689
- const mac = keccak2562(concat(macKey, ciphertext));
690
- return {
691
- crypto: {
692
- cipher: "aes-128-ctr",
693
- ciphertext: toHex2(ciphertext).slice(2),
694
- cipherparams: { iv: toHex2(iv).slice(2) },
695
- kdf,
696
- kdfparams,
697
- mac: toHex2(mac).slice(2)
698
- },
699
- id,
700
- version: 3
701
- };
702
- }
703
- function pbkdf22(options) {
704
- const { iv, iterations = 262144, password } = options;
705
- const salt = options.salt ? from(options.salt) : random(32);
706
- const key = toHex2(pbkdf2(sha256, password, salt, { c: iterations, dkLen: 32 }));
707
- return defineKey(() => key, {
708
- iv,
709
- kdfparams: {
710
- c: iterations,
711
- dklen: 32,
712
- prf: "hmac-sha256",
713
- salt: toHex2(salt).slice(2)
714
- },
715
- kdf: "pbkdf2"
716
- });
717
- }
718
- async function scryptAsync2(options) {
719
- const { iv, n = 262144, password } = options;
720
- const p = 8;
721
- const r = 1;
722
- const salt = options.salt ? from(options.salt) : random(32);
723
- const key = toHex2(await scryptAsync(password, salt, { N: n, dkLen: 32, r, p }));
724
- return defineKey(() => key, {
725
- iv,
726
- kdfparams: {
727
- dklen: 32,
728
- n,
729
- p,
730
- r,
731
- salt: toHex2(salt).slice(2)
732
- },
733
- kdf: "scrypt"
734
- });
735
- }
736
- async function toKeyAsync(keystore, options) {
737
- const { crypto: crypto2 } = keystore;
738
- const { password } = options;
739
- const { cipherparams, kdf, kdfparams } = crypto2;
740
- const { iv } = cipherparams;
741
- const { c, n, p, r, salt } = kdfparams;
742
- const [key] = await (async () => {
743
- switch (kdf) {
744
- case "scrypt":
745
- return await scryptAsync2({
746
- iv: from(`0x${iv}`),
747
- n,
748
- p,
749
- r,
750
- salt: from(`0x${salt}`),
751
- password
752
- });
753
- case "pbkdf2":
754
- return await pbkdf22({
755
- iv: from(`0x${iv}`),
756
- iterations: c,
757
- password,
758
- salt: from(`0x${salt}`)
759
- });
760
- default:
761
- throw new Error("unsupported kdf");
762
- }
763
- })();
764
- return key;
765
- }
766
- function defineKey(key, options) {
767
- const iv = options.iv ? from(options.iv) : random(16);
768
- return [key, { ...options, iv }];
769
- }
770
-
771
- // src/lib/wallet/passphrase.ts
772
- import { execFile } from "child_process";
773
- import { randomBytes } from "crypto";
774
- import { readFile, unlink } from "fs/promises";
775
- var KEYCHAIN_SERVICE = "tenjin-cli";
776
- var LEGACY_ACCOUNT = "wallet";
777
- var ACCOUNT_ADDRESS_RE = /^0x[0-9a-f]{40}$/;
778
- var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
779
- function walletStoreAccount(address) {
780
- const account = address.toLowerCase();
781
- if (!ACCOUNT_ADDRESS_RE.test(account)) {
782
- throw new CliError("INTERNAL", `Not a valid wallet address for passphrase storage: ${address}`);
783
- }
784
- return account;
785
- }
786
- function defaultExecFor(timeoutMs) {
787
- return (file, args, stdin) => new Promise((resolve, reject) => {
788
- const child = execFile(
789
- file,
790
- args,
791
- { encoding: "utf8", ...timeoutMs !== void 0 ? { timeout: timeoutMs } : {} },
792
- (err, stdout, stderr) => {
793
- if (err) reject(err);
794
- else resolve({ stdout, stderr });
795
- }
796
- );
797
- if (stdin !== void 0) {
798
- child.stdin?.on("error", () => void 0);
799
- child.stdin?.end(stdin);
800
- }
801
- });
1029
+ out[oi++] = y15 + x15 | 0;
802
1030
  }
803
- function storeFor(deps) {
804
- switch (deps.platform ?? process.platform) {
805
- case "darwin":
806
- return keychainStore(deps);
807
- case "win32":
808
- return dpapiStore(deps);
809
- case "linux":
810
- return secretServiceStore(deps);
811
- default:
812
- return null;
1031
+ function BlockMix(input, ii, out, oi, r) {
1032
+ let head = oi + 0;
1033
+ let tail = oi + 16 * r;
1034
+ for (let i = 0; i < 16; i++)
1035
+ out[tail + i] = input[ii + (2 * r - 1) * 16 + i];
1036
+ for (let i = 0; i < r; i++, head += 16, ii += 16) {
1037
+ XorAndSalsa(out, tail, input, ii, out, head);
1038
+ if (i > 0)
1039
+ tail += 16;
1040
+ XorAndSalsa(out, head, input, ii += 16, out, tail);
813
1041
  }
814
1042
  }
815
- async function resolvePassphrase(deps, address) {
816
- const fromEnv = envPassphrase(deps.env);
817
- if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
818
- const store = storeFor(deps);
819
- if (store !== null) {
820
- const account = walletStoreAccount(address);
821
- const own = await store.read(account);
822
- if (own !== null) return { passphrase: own, source: store.source };
823
- const legacy = await store.read(LEGACY_ACCOUNT);
824
- if (legacy !== null) {
825
- return {
826
- passphrase: legacy,
827
- source: store.source,
828
- migrateLegacy: () => migrateLegacyEntry(store, account, legacy)
829
- };
830
- }
1043
+ function scryptInit(password, salt, _opts) {
1044
+ const opts = checkOpts({
1045
+ dkLen: 32,
1046
+ asyncTick: 10,
1047
+ maxmem: 1024 ** 3 + 1024
1048
+ }, _opts);
1049
+ const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
1050
+ anumber(N);
1051
+ anumber(r);
1052
+ anumber(p);
1053
+ anumber(dkLen);
1054
+ anumber(asyncTick);
1055
+ anumber(maxmem);
1056
+ if (onProgress !== void 0 && typeof onProgress !== "function")
1057
+ throw new Error("progressCb should be function");
1058
+ const blockSize = 128 * r;
1059
+ const blockSize32 = blockSize / 4;
1060
+ const pow32 = Math.pow(2, 32);
1061
+ if (N <= 1 || (N & N - 1) !== 0 || N > pow32) {
1062
+ throw new Error("Scrypt: N must be larger than 1, a power of 2, and less than 2^32");
831
1063
  }
832
- if (canPrompt(deps)) {
833
- const entered = await promptOf(deps)("Wallet passphrase: ");
834
- if (entered.length === 0) throw noPassphraseError();
835
- return { passphrase: entered, source: "prompt" };
1064
+ if (p < 0 || p > (pow32 - 1) * 32 / blockSize) {
1065
+ throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");
836
1066
  }
837
- throw noPassphraseError();
838
- }
839
- async function migrateLegacyEntry(store, account, passphrase) {
840
- if (!await store.store(account, passphrase)) return false;
841
- if (await store.read(account) !== passphrase) return false;
842
- await store.remove(LEGACY_ACCOUNT);
843
- return true;
844
- }
845
- async function storePassphraseForWallet(deps, address, passphrase) {
846
- const store = storeFor(deps);
847
- if (store === null) return "no-store";
848
- const account = walletStoreAccount(address);
849
- if (await store.read(account) === passphrase) return "stored";
850
- if (store.storable !== void 0 && !store.storable(passphrase)) return "rejected-characters";
851
- if (!await store.store(account, passphrase)) return "store-failed";
852
- return await store.read(account) === passphrase ? "stored" : "store-failed";
853
- }
854
- async function resolvePassphraseForCreate(deps, address) {
855
- const fromEnv = envPassphrase(deps.env);
856
- if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
857
- const store = storeFor(deps);
858
- if (store !== null) {
859
- const account = walletStoreAccount(address);
860
- const generated = randomBytes(32).toString("base64url");
861
- if (await store.store(account, generated) && await store.read(account) === generated) {
862
- return { passphrase: generated, source: store.source };
863
- }
1067
+ if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
1068
+ throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");
864
1069
  }
865
- if (canPrompt(deps)) {
866
- const prompt = promptOf(deps);
867
- const first = await prompt("Set a wallet passphrase: ");
868
- if (first.length === 0) {
869
- throw new CliError("USAGE", "The wallet passphrase must not be empty.", {
870
- fix: "Enter a non-empty passphrase, or set TENJIN_WALLET_PASSPHRASE."
871
- });
872
- }
873
- const second = await prompt("Confirm passphrase: ");
874
- if (first !== second) {
875
- throw new CliError("USAGE", "The passphrases did not match.", {
876
- fix: "Run `tenjin wallet create` again and enter the same passphrase both times."
877
- });
878
- }
879
- return { passphrase: first, source: "prompt" };
1070
+ const memUsed = blockSize * (N + p);
1071
+ if (memUsed > maxmem) {
1072
+ throw new Error("Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of " + maxmem);
880
1073
  }
881
- throw noPassphraseError();
882
- }
883
- function keychainStore(deps) {
884
- const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
885
- return {
886
- source: "keychain",
887
- async read(account) {
888
- try {
889
- const { stdout } = await exec("security", [
890
- "find-generic-password",
891
- "-s",
892
- KEYCHAIN_SERVICE,
893
- "-a",
894
- account,
895
- "-w"
896
- ]);
897
- return trimmedNonEmpty(stdout);
898
- } catch {
899
- return null;
900
- }
901
- },
902
- // The one backend that interpolates into a command line, so only base64url
903
- // values pass; escaping is NOT a safe alternative (backslash bites even
904
- // inside single quotes there).
905
- storable: (passphrase) => BASE64URL_RE.test(passphrase),
906
- async store(account, passphrase) {
907
- if (!BASE64URL_RE.test(passphrase) || !BASE64URL_RE.test(account)) return false;
908
- try {
909
- const command = `add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} -w '${passphrase}'
910
- `;
911
- await exec("security", ["-i"], command);
912
- return true;
913
- } catch {
914
- return false;
915
- }
916
- },
917
- async remove(account) {
918
- try {
919
- await exec("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account]);
920
- return true;
921
- } catch {
922
- return false;
923
- }
924
- }
1074
+ const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
1075
+ const B32 = u32(B);
1076
+ const V = u32(new Uint8Array(blockSize * N));
1077
+ const tmp = u32(new Uint8Array(blockSize));
1078
+ let blockMixCb = () => {
925
1079
  };
1080
+ if (onProgress) {
1081
+ const totalBlockMix = 2 * N * p;
1082
+ const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1);
1083
+ let blockMixCnt = 0;
1084
+ blockMixCb = () => {
1085
+ blockMixCnt++;
1086
+ if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
1087
+ onProgress(blockMixCnt / totalBlockMix);
1088
+ };
1089
+ }
1090
+ return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
926
1091
  }
927
- var DPAPI_PROTECT_SCRIPT = [
928
- "Add-Type -AssemblyName System.Security;",
929
- "$in = [Console]::In.ReadToEnd();",
930
- "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in);",
931
- "$prot = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser');",
932
- "[Console]::Out.Write([Convert]::ToBase64String($prot));"
933
- ].join(" ");
934
- var DPAPI_UNPROTECT_SCRIPT = [
935
- "Add-Type -AssemblyName System.Security;",
936
- "$in = [Console]::In.ReadToEnd();",
937
- "$blob = [Convert]::FromBase64String($in.Trim());",
938
- "$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser');",
939
- "[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain));"
940
- ].join(" ");
941
- function powershellArgs(script) {
942
- return ["-NoProfile", "-NonInteractive", "-Command", script];
1092
+ function scryptOutput(password, dkLen, B, V, tmp) {
1093
+ const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
1094
+ clean(B, V, tmp);
1095
+ return res;
943
1096
  }
944
- function dpapiStore(deps) {
945
- const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
946
- const blobPathFor = (account) => account === LEGACY_ACCOUNT ? passphraseBlobPath(deps.dir) : passphraseBlobPathFor(account, deps.dir);
947
- return {
948
- source: "dpapi",
949
- async read(account) {
950
- let blob;
951
- try {
952
- blob = await readFile(blobPathFor(account), "utf8");
953
- } catch {
954
- return null;
955
- }
956
- try {
957
- const { stdout } = await exec(
958
- "powershell.exe",
959
- powershellArgs(DPAPI_UNPROTECT_SCRIPT),
960
- blob
961
- );
962
- const passphrase = stdout.replace(/\r?\n$/, "");
963
- return passphrase.length > 0 ? passphrase : null;
964
- } catch {
965
- return null;
966
- }
967
- },
968
- async store(account, passphrase) {
969
- try {
970
- const { stdout } = await exec(
971
- "powershell.exe",
972
- powershellArgs(DPAPI_PROTECT_SCRIPT),
973
- passphrase
974
- );
975
- const blob = stdout.replace(/\r?\n$/, "").trim();
976
- if (blob.length === 0) return false;
977
- await writeFileAtomic(blobPathFor(account), blob, { mode: 384 });
978
- return true;
979
- } catch {
980
- return false;
981
- }
982
- },
983
- async remove(account) {
984
- try {
985
- await unlink(blobPathFor(account));
986
- return true;
987
- } catch {
988
- return false;
989
- }
990
- }
991
- };
1097
+ async function scryptAsync(password, salt, opts) {
1098
+ const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
1099
+ swap32IfBE(B32);
1100
+ for (let pi = 0; pi < p; pi++) {
1101
+ const Pi = blockSize32 * pi;
1102
+ for (let i = 0; i < blockSize32; i++)
1103
+ V[i] = B32[Pi + i];
1104
+ let pos = 0;
1105
+ await asyncLoop(N - 1, asyncTick, () => {
1106
+ BlockMix(V, pos, V, pos += blockSize32, r);
1107
+ blockMixCb();
1108
+ });
1109
+ BlockMix(V, (N - 1) * blockSize32, B32, Pi, r);
1110
+ blockMixCb();
1111
+ await asyncLoop(N, asyncTick, () => {
1112
+ const j = B32[Pi + blockSize32 - 16] % N;
1113
+ for (let k = 0; k < blockSize32; k++)
1114
+ tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];
1115
+ BlockMix(tmp, 0, B32, Pi, r);
1116
+ blockMixCb();
1117
+ });
1118
+ }
1119
+ swap32IfBE(B32);
1120
+ return scryptOutput(password, dkLen, B, V, tmp);
992
1121
  }
993
- function secretServiceStore(deps) {
994
- const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
1122
+
1123
+ // node_modules/.pnpm/ox@0.14.30_typescript@6.0.3_zod@4.4.3/node_modules/ox/_esm/core/Keystore.js
1124
+ function decrypt(keystore, key, options = {}) {
1125
+ const { as = "Hex" } = options;
1126
+ const key_ = from(typeof key === "function" ? key() : key);
1127
+ const encKey = slice(key_, 0, 16);
1128
+ const macKey = slice(key_, 16, 32);
1129
+ const ciphertext = from(`0x${keystore.crypto.ciphertext}`);
1130
+ const mac = keccak2562(concat(macKey, ciphertext));
1131
+ if (!isEqual(mac, from(`0x${keystore.crypto.mac}`)))
1132
+ throw new Error("corrupt keystore");
1133
+ const data = ctr(encKey, from(`0x${keystore.crypto.cipherparams.iv}`)).decrypt(ciphertext);
1134
+ if (as === "Hex")
1135
+ return toHex2(data);
1136
+ return data;
1137
+ }
1138
+ function encrypt2(privateKey, key, options) {
1139
+ const { id = crypto.randomUUID(), kdf, kdfparams, iv } = options;
1140
+ const key_ = from(typeof key === "function" ? key() : key);
1141
+ const value_ = from(privateKey);
1142
+ const encKey = slice(key_, 0, 16);
1143
+ const macKey = slice(key_, 16, 32);
1144
+ const ciphertext = ctr(encKey, iv).encrypt(value_);
1145
+ const mac = keccak2562(concat(macKey, ciphertext));
995
1146
  return {
996
- source: "secret-service",
997
- async read(account) {
998
- try {
999
- const { stdout } = await exec("secret-tool", [
1000
- "lookup",
1001
- "service",
1002
- KEYCHAIN_SERVICE,
1003
- "account",
1004
- account
1005
- ]);
1006
- return trimmedNonEmpty(stdout);
1007
- } catch {
1008
- return null;
1009
- }
1010
- },
1011
- async store(account, passphrase) {
1012
- try {
1013
- await exec(
1014
- "secret-tool",
1015
- [
1016
- "store",
1017
- `--label=tenjin-cli wallet ${account}`,
1018
- "service",
1019
- KEYCHAIN_SERVICE,
1020
- "account",
1021
- account
1022
- ],
1023
- passphrase
1024
- );
1025
- return true;
1026
- } catch {
1027
- return false;
1028
- }
1147
+ crypto: {
1148
+ cipher: "aes-128-ctr",
1149
+ ciphertext: toHex2(ciphertext).slice(2),
1150
+ cipherparams: { iv: toHex2(iv).slice(2) },
1151
+ kdf,
1152
+ kdfparams,
1153
+ mac: toHex2(mac).slice(2)
1029
1154
  },
1030
- async remove(account) {
1031
- try {
1032
- await exec("secret-tool", ["clear", "service", KEYCHAIN_SERVICE, "account", account]);
1033
- return true;
1034
- } catch {
1035
- return false;
1036
- }
1037
- }
1155
+ id,
1156
+ version: 3
1038
1157
  };
1039
1158
  }
1040
- function trimmedNonEmpty(stdout) {
1041
- const value = stdout.replace(/\r?\n$/, "");
1042
- return value.length > 0 ? value : null;
1043
- }
1044
- function envPassphrase(env) {
1045
- const value = env.TENJIN_WALLET_PASSPHRASE;
1046
- return value !== void 0 && value.length > 0 ? value : null;
1159
+ function pbkdf22(options) {
1160
+ const { iv, iterations = 262144, password } = options;
1161
+ const salt = options.salt ? from(options.salt) : random(32);
1162
+ const key = toHex2(pbkdf2(sha256, password, salt, { c: iterations, dkLen: 32 }));
1163
+ return defineKey(() => key, {
1164
+ iv,
1165
+ kdfparams: {
1166
+ c: iterations,
1167
+ dklen: 32,
1168
+ prf: "hmac-sha256",
1169
+ salt: toHex2(salt).slice(2)
1170
+ },
1171
+ kdf: "pbkdf2"
1172
+ });
1047
1173
  }
1048
- function canPrompt(deps) {
1049
- return deps.isTTY ?? Boolean(process.stdin.isTTY);
1174
+ async function scryptAsync2(options) {
1175
+ const { iv, n = 262144, password } = options;
1176
+ const p = 8;
1177
+ const r = 1;
1178
+ const salt = options.salt ? from(options.salt) : random(32);
1179
+ const key = toHex2(await scryptAsync(password, salt, { N: n, dkLen: 32, r, p }));
1180
+ return defineKey(() => key, {
1181
+ iv,
1182
+ kdfparams: {
1183
+ dklen: 32,
1184
+ n,
1185
+ p,
1186
+ r,
1187
+ salt: toHex2(salt).slice(2)
1188
+ },
1189
+ kdf: "scrypt"
1190
+ });
1050
1191
  }
1051
- function promptOf(deps) {
1052
- return deps.prompt ?? promptHidden;
1192
+ async function toKeyAsync(keystore, options) {
1193
+ const { crypto: crypto2 } = keystore;
1194
+ const { password } = options;
1195
+ const { cipherparams, kdf, kdfparams } = crypto2;
1196
+ const { iv } = cipherparams;
1197
+ const { c, n, p, r, salt } = kdfparams;
1198
+ const [key] = await (async () => {
1199
+ switch (kdf) {
1200
+ case "scrypt":
1201
+ return await scryptAsync2({
1202
+ iv: from(`0x${iv}`),
1203
+ n,
1204
+ p,
1205
+ r,
1206
+ salt: from(`0x${salt}`),
1207
+ password
1208
+ });
1209
+ case "pbkdf2":
1210
+ return await pbkdf22({
1211
+ iv: from(`0x${iv}`),
1212
+ iterations: c,
1213
+ password,
1214
+ salt: from(`0x${salt}`)
1215
+ });
1216
+ default:
1217
+ throw new Error("unsupported kdf");
1218
+ }
1219
+ })();
1220
+ return key;
1053
1221
  }
1054
- function noPassphraseError() {
1055
- return new CliError("USAGE", "No wallet passphrase is available.", {
1056
- fix: "Set TENJIN_WALLET_PASSPHRASE (headless) or run in a terminal."
1057
- });
1222
+ function defineKey(key, options) {
1223
+ const iv = options.iv ? from(options.iv) : random(16);
1224
+ return [key, { ...options, iv }];
1058
1225
  }
1059
- var CTRL_C = 3;
1060
- var CTRL_D = 4;
1061
- var BACKSPACE = 127;
1062
- var BACKSPACE_ALT = 8;
1063
- function promptHidden(label) {
1226
+
1227
+ // src/lib/wallet/keystore-kdf.ts
1228
+ import { Worker } from "node:worker_threads";
1229
+ async function deriveKeystoreKey(keystore, password, options = {}) {
1230
+ const timeoutMs = options.timeoutMs ?? 12e4;
1231
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 12e4)
1232
+ throw new Error("Keystore derivation timeout must be between 1 and 120000 milliseconds.");
1233
+ if (options.signal?.aborted) throw derivationError("AbortError");
1234
+ const url = new URL(
1235
+ import.meta.url.endsWith(".ts") ? "./keystore-kdf-worker.ts" : "./wallet-kdf-worker.mjs",
1236
+ import.meta.url
1237
+ );
1064
1238
  return new Promise((resolve, reject) => {
1065
- const stdin = process.stdin;
1066
- const stderr = process.stderr;
1067
- const wasRaw = stdin.isRaw;
1068
- let value = "";
1069
- const cleanup = () => {
1070
- stdin.setRawMode?.(wasRaw ?? false);
1071
- stdin.pause();
1072
- stdin.removeListener("data", onData);
1073
- };
1074
- const onData = (chunk) => {
1075
- for (const ch of chunk.toString("utf8")) {
1076
- const code = ch.charCodeAt(0);
1077
- if (ch === "\n" || ch === "\r" || code === CTRL_D) {
1078
- cleanup();
1079
- stderr.write("\n");
1080
- resolve(value);
1081
- return;
1082
- }
1083
- if (code === CTRL_C) {
1084
- cleanup();
1085
- stderr.write("\n");
1086
- reject(
1087
- new CliError("USAGE", "Passphrase entry was cancelled.", {
1088
- fix: "Run the command again, or set TENJIN_WALLET_PASSPHRASE."
1089
- })
1090
- );
1091
- return;
1092
- }
1093
- if (code === BACKSPACE || code === BACKSPACE_ALT) {
1094
- value = value.slice(0, -1);
1095
- } else {
1096
- value += ch;
1097
- }
1098
- }
1099
- };
1100
- stderr.write(label);
1101
- stdin.setRawMode?.(true);
1102
- stdin.resume();
1103
- stdin.on("data", onData);
1239
+ const worker = new Worker(url, { workerData: { keystore, password }, execArgv: [] });
1240
+ let settled = false;
1241
+ const onAbort = () => finish(derivationError("AbortError"));
1242
+ function finish(error, key) {
1243
+ if (settled) return;
1244
+ settled = true;
1245
+ clearTimeout(timer);
1246
+ options.signal?.removeEventListener("abort", onAbort);
1247
+ void worker.terminate().then(
1248
+ () => error ? reject(error) : resolve(key),
1249
+ () => reject(new Error("Keystore derivation worker could not terminate."))
1250
+ );
1251
+ }
1252
+ worker.once("message", (message) => {
1253
+ if (typeof message === "object" && message !== null && "key" in message && typeof message.key === "string" && /^0x[0-9a-fA-F]{64}$/.test(message.key)) {
1254
+ finish(void 0, message.key);
1255
+ } else finish(new Error("Keystore derivation failed."));
1256
+ });
1257
+ worker.once("error", () => finish(new Error("Keystore derivation worker failed.")));
1258
+ worker.once("exit", () => {
1259
+ if (!settled) finish(new Error("Keystore derivation worker exited without a result."));
1260
+ });
1261
+ const timer = setTimeout(() => finish(derivationError("TimeoutError")), timeoutMs);
1262
+ options.signal?.addEventListener("abort", onAbort, { once: true });
1263
+ if (options.signal?.aborted) onAbort();
1104
1264
  });
1105
1265
  }
1266
+ function derivationError(name) {
1267
+ return Object.assign(
1268
+ new Error(`Keystore derivation ${name === "AbortError" ? "aborted" : "timed out"}.`),
1269
+ {
1270
+ name
1271
+ }
1272
+ );
1273
+ }
1106
1274
 
1107
1275
  // src/lib/wallet/local.ts
1108
1276
  var isWindows = process.platform === "win32";
@@ -1170,9 +1338,12 @@ async function verifyLocalWallet(deps) {
1170
1338
  }
1171
1339
  let key;
1172
1340
  try {
1173
- const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1341
+ const derived = await deriveKeystoreKey(cred.keystore, resolved.passphrase, deps.derivation);
1174
1342
  key = decrypt(cred.keystore, derived);
1175
- } catch {
1343
+ } catch (error) {
1344
+ if (error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)) {
1345
+ return { status: "unverified", detail: "keystore verification was cancelled or timed out" };
1346
+ }
1176
1347
  if (resolved.migrateLegacy !== void 0) {
1177
1348
  return {
1178
1349
  status: "broken",
@@ -1387,9 +1558,10 @@ async function accountForSigning(cred, deps) {
1387
1558
  );
1388
1559
  let key;
1389
1560
  try {
1390
- const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1561
+ const derived = await deriveKeystoreKey(cred.keystore, resolved.passphrase, deps.derivation);
1391
1562
  key = decrypt(cred.keystore, derived);
1392
1563
  } catch (err) {
1564
+ if (err instanceof Error && ["AbortError", "TimeoutError"].includes(err.name)) throw err;
1393
1565
  if (resolved.migrateLegacy !== void 0) {
1394
1566
  throw new CliError(
1395
1567
  "WALLET_INVALID_KEY",
@@ -1453,140 +1625,6 @@ function walletRecord(address, keystore) {
1453
1625
  };
1454
1626
  }
1455
1627
 
1456
- // src/lib/wallet/spend.ts
1457
- import { mkdir, readFile as readFile2 } from "fs/promises";
1458
- import { randomUUID } from "crypto";
1459
- var DEFAULT_WINDOW_MS = 864e5;
1460
- var RESERVATION_TTL_MS = 6e5;
1461
- var ReservationSchema = external_exports.object({
1462
- id: external_exports.string(),
1463
- amountAtomic: external_exports.string().regex(/^\d+$/),
1464
- atMs: external_exports.number()
1465
- });
1466
- var LedgerSchema = external_exports.object({
1467
- schemaVersion: external_exports.literal(2),
1468
- windowStartMs: external_exports.number(),
1469
- committedAtomic: external_exports.string().regex(/^\d+$/),
1470
- reservations: external_exports.array(ReservationSchema)
1471
- });
1472
- function emptyLedger(nowMs) {
1473
- return { schemaVersion: 2, windowStartMs: nowMs, committedAtomic: "0", reservations: [] };
1474
- }
1475
- function createLocalSpendAuthorizer(deps) {
1476
- const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;
1477
- const now = deps.now ?? Date.now;
1478
- const path = spendLedgerPath(deps.dir);
1479
- const lockPath = `${path}.lock`;
1480
- let warnedCorrupt = false;
1481
- const freshen = (ledger, nowMs) => {
1482
- if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);
1483
- return {
1484
- ...ledger,
1485
- reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS)
1486
- };
1487
- };
1488
- const spentOf = (ledger) => ledger.reservations.reduce(
1489
- (sum, r) => sum + BigInt(r.amountAtomic),
1490
- BigInt(ledger.committedAtomic)
1491
- );
1492
- const persist = async (ledger) => {
1493
- await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}
1494
- `, {
1495
- mode: 384,
1496
- dirMode: 448
1497
- });
1498
- };
1499
- async function withLedger(fn) {
1500
- await mkdir(deps.dir, { recursive: true, mode: 448 });
1501
- return withFileLock(lockPath, async () => {
1502
- const nowMs = now();
1503
- const read = await readLedger(path);
1504
- if (read.corrupt !== void 0 && !warnedCorrupt) {
1505
- warnedCorrupt = true;
1506
- deps.onCorrupt?.(read.corrupt);
1507
- }
1508
- const ledger = freshen(read.ledger, nowMs);
1509
- return fn(ledger, nowMs);
1510
- });
1511
- }
1512
- return {
1513
- policyEnforcement: "client-only",
1514
- async authorize(req) {
1515
- return withLedger(async (ledger) => {
1516
- const sessionSpentAtomic = spentOf(ledger);
1517
- const evaluation = evaluateSpendPolicy(deps.policy, {
1518
- amountAtomic: req.amountAtomic,
1519
- creator: req.creator,
1520
- ...req.maxPriceAtomic !== void 0 ? { maxPriceAtomic: req.maxPriceAtomic } : {},
1521
- sessionSpentAtomic
1522
- });
1523
- const base = {
1524
- ...evaluation,
1525
- amountAtomic: req.amountAtomic,
1526
- sessionSpentAtomic,
1527
- sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,
1528
- policyEnforcement: "client-only"
1529
- };
1530
- if (evaluation.decision === "deny" || deps.policy.sessionBudgetAtomic === 0n) {
1531
- return base;
1532
- }
1533
- const reservation = {
1534
- id: randomUUID(),
1535
- amountAtomic: req.amountAtomic.toString(),
1536
- atMs: now()
1537
- };
1538
- await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });
1539
- return { ...base, reservationId: reservation.id };
1540
- });
1541
- },
1542
- async commit(reservationId, amountAtomic) {
1543
- await withLedger(async (ledger) => {
1544
- const reservation = reservationId !== void 0 ? ledger.reservations.find((r) => r.id === reservationId) : void 0;
1545
- const settled = reservation !== void 0 ? BigInt(reservation.amountAtomic) : amountAtomic;
1546
- await persist({
1547
- ...ledger,
1548
- committedAtomic: (BigInt(ledger.committedAtomic) + settled).toString(),
1549
- reservations: reservationId !== void 0 ? ledger.reservations.filter((r) => r.id !== reservationId) : ledger.reservations
1550
- });
1551
- });
1552
- },
1553
- async release(reservationId) {
1554
- if (reservationId === void 0) return;
1555
- await withLedger(async (ledger) => {
1556
- if (!ledger.reservations.some((r) => r.id === reservationId)) return;
1557
- await persist({
1558
- ...ledger,
1559
- reservations: ledger.reservations.filter((r) => r.id !== reservationId)
1560
- });
1561
- });
1562
- }
1563
- };
1564
- }
1565
- async function readLedger(path) {
1566
- let raw;
1567
- try {
1568
- raw = await readFile2(path, "utf8");
1569
- } catch (err) {
1570
- if (hasCode(err, "ENOENT")) return { ledger: null };
1571
- return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };
1572
- }
1573
- let json;
1574
- try {
1575
- json = JSON.parse(raw);
1576
- } catch {
1577
- return { ledger: null, corrupt: "not valid JSON" };
1578
- }
1579
- const parsed = LedgerSchema.safeParse(json);
1580
- if (parsed.success) return { ledger: parsed.data };
1581
- const issue = parsed.error.issues[0];
1582
- const field = issue?.path.join(".");
1583
- const message = issue?.message ?? "schema mismatch";
1584
- return {
1585
- ledger: null,
1586
- corrupt: field !== void 0 && field.length > 0 ? `${field}: ${message}` : message
1587
- };
1588
- }
1589
-
1590
1628
  // src/lib/wallet/index.ts
1591
1629
  function resolveWalletProvider(ctx, opts = {}) {
1592
1630
  if (opts.provider !== void 0) return opts.provider;
@@ -1622,15 +1660,15 @@ async function describeWallet(provider) {
1622
1660
  }
1623
1661
 
1624
1662
  export {
1663
+ walletFileExists,
1664
+ walletExistsError,
1625
1665
  resolvePassphraseForCreate,
1626
- verifyLocalWallet,
1627
1666
  prepareLocalWallet,
1628
1667
  commitLocalWallet,
1629
1668
  createLocalWallet,
1630
1669
  verifyAndPreserveOutgoingWallet,
1631
1670
  parkOutgoingWallet,
1632
1671
  restoreParkedWallet,
1633
- createLocalSpendAuthorizer,
1634
1672
  resolveWalletProvider,
1635
1673
  resolveSpendAuthorizer,
1636
1674
  describeWallet
@@ -1640,4 +1678,4 @@ export {
1640
1678
  @noble/ciphers/esm/utils.js:
1641
1679
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1642
1680
  */
1643
- //# sourceMappingURL=chunk-CPCX67TI.js.map
1681
+ //# sourceMappingURL=chunk-KUBEYXSO.js.map