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

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