tenjin-cli 0.1.0-alpha.14 → 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 (253) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +41 -295
  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-ACBEHJAH.js → chunk-2U5ZVEV3.js} +14 -16
  13. package/dist/chunk-2U5ZVEV3.js.map +1 -0
  14. package/dist/{chunk-MJSXP4LW.js → chunk-3AJS6LLN.js} +11 -8
  15. package/dist/chunk-3AJS6LLN.js.map +1 -0
  16. package/dist/{chunk-OWVVI4VQ.js → chunk-3AUDA53C.js} +7650 -7361
  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-PAOVPSP6.js → chunk-BBVUVBUO.js} +517 -138
  28. package/dist/chunk-BBVUVBUO.js.map +1 -0
  29. package/dist/{chunk-ETKZWJ4B.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-PKW3H26Z.js → chunk-OJLYNM4Z.js} +56 -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-QWBUKIP2.js → chunk-U5DXNFJC.js} +23 -94
  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-7GJQ5RGA.js → chunk-YEETV6IW.js} +1077 -1039
  72. package/dist/chunk-YEETV6IW.js.map +1 -0
  73. package/dist/{chunk-B676GPS2.js → chunk-YJHHCWM3.js} +39 -16
  74. package/dist/chunk-YJHHCWM3.js.map +1 -0
  75. package/dist/{cli-U2BEUA55.js → cli-M3XCSOU6.js} +295 -349
  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-3ZW7HPY5.js → fund-A54P2QFK.js} +81 -22
  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-CJWPGMIQ.js → mcp-HJC2PLRV.js} +3725 -10661
  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-C5EOKXOU.js → send-ASD2ZXJD.js} +28 -30
  98. package/dist/send-ASD2ZXJD.js.map +1 -0
  99. package/dist/{chunk-NAAMHWSI.js → skill-placement-NFVHY6A3.js} +159 -12
  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-24Y2CQTT.js → update-ANJ2AOTN.js} +133 -17
  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 +68 -342
  117. package/docs/safety-model.md +25 -6
  118. package/package.json +8 -7
  119. package/LICENSE +0 -21
  120. package/dist/buy-2JBYPHAI.js +0 -46
  121. package/dist/chunk-3P3ES4XU.js +0 -144
  122. package/dist/chunk-3P3ES4XU.js.map +0 -1
  123. package/dist/chunk-3ZW7HPY5.js.map +0 -1
  124. package/dist/chunk-47PP7TAG.js.map +0 -1
  125. package/dist/chunk-4UHNXY6B.js +0 -786
  126. package/dist/chunk-4UHNXY6B.js.map +0 -1
  127. package/dist/chunk-4Y53PDH6.js +0 -213
  128. package/dist/chunk-4Y53PDH6.js.map +0 -1
  129. package/dist/chunk-54AJIO3E.js +0 -198
  130. package/dist/chunk-54AJIO3E.js.map +0 -1
  131. package/dist/chunk-736DW4V3.js +0 -65
  132. package/dist/chunk-736DW4V3.js.map +0 -1
  133. package/dist/chunk-7GJQ5RGA.js.map +0 -1
  134. package/dist/chunk-7NADDA2V.js +0 -161
  135. package/dist/chunk-7NADDA2V.js.map +0 -1
  136. package/dist/chunk-ACBEHJAH.js.map +0 -1
  137. package/dist/chunk-B676GPS2.js.map +0 -1
  138. package/dist/chunk-DAZAXFSF.js +0 -1357
  139. package/dist/chunk-DAZAXFSF.js.map +0 -1
  140. package/dist/chunk-DTCXO7HS.js +0 -791
  141. package/dist/chunk-DTCXO7HS.js.map +0 -1
  142. package/dist/chunk-ETKZWJ4B.js.map +0 -1
  143. package/dist/chunk-FDUD3W5V.js +0 -317
  144. package/dist/chunk-FDUD3W5V.js.map +0 -1
  145. package/dist/chunk-GEHL43VE.js +0 -711
  146. package/dist/chunk-GEHL43VE.js.map +0 -1
  147. package/dist/chunk-IU2HVT3Y.js +0 -313
  148. package/dist/chunk-IU2HVT3Y.js.map +0 -1
  149. package/dist/chunk-IUQZ4Z7M.js +0 -162
  150. package/dist/chunk-IUQZ4Z7M.js.map +0 -1
  151. package/dist/chunk-IXZJ3JOO.js +0 -614
  152. package/dist/chunk-IXZJ3JOO.js.map +0 -1
  153. package/dist/chunk-J6FUAIRR.js +0 -205
  154. package/dist/chunk-J6FUAIRR.js.map +0 -1
  155. package/dist/chunk-L6G35FU5.js +0 -105
  156. package/dist/chunk-L6G35FU5.js.map +0 -1
  157. package/dist/chunk-LSWP7MU2.js +0 -290
  158. package/dist/chunk-LSWP7MU2.js.map +0 -1
  159. package/dist/chunk-M2O56UK7.js.map +0 -1
  160. package/dist/chunk-MJSXP4LW.js.map +0 -1
  161. package/dist/chunk-MJZZTKCC.js.map +0 -1
  162. package/dist/chunk-NAAMHWSI.js.map +0 -1
  163. package/dist/chunk-O75FOHXS.js +0 -372
  164. package/dist/chunk-O75FOHXS.js.map +0 -1
  165. package/dist/chunk-OWVVI4VQ.js.map +0 -1
  166. package/dist/chunk-PAOVPSP6.js.map +0 -1
  167. package/dist/chunk-PCX2JQ2J.js +0 -233
  168. package/dist/chunk-PCX2JQ2J.js.map +0 -1
  169. package/dist/chunk-PKW3H26Z.js.map +0 -1
  170. package/dist/chunk-PQZVDCCA.js +0 -125
  171. package/dist/chunk-PQZVDCCA.js.map +0 -1
  172. package/dist/chunk-QWBUKIP2.js.map +0 -1
  173. package/dist/chunk-SGK2B724.js +0 -67
  174. package/dist/chunk-SGK2B724.js.map +0 -1
  175. package/dist/chunk-UHTVXQ2O.js +0 -140
  176. package/dist/chunk-UHTVXQ2O.js.map +0 -1
  177. package/dist/chunk-UO22YNY4.js.map +0 -1
  178. package/dist/chunk-VEAERJVJ.js +0 -43
  179. package/dist/chunk-VEAERJVJ.js.map +0 -1
  180. package/dist/chunk-VRPLZERE.js +0 -1421
  181. package/dist/chunk-VRPLZERE.js.map +0 -1
  182. package/dist/chunk-W4VW5XYB.js +0 -149
  183. package/dist/chunk-W4VW5XYB.js.map +0 -1
  184. package/dist/chunk-WU5CZPLD.js +0 -145
  185. package/dist/chunk-WU5CZPLD.js.map +0 -1
  186. package/dist/chunk-WYLMJQVH.js +0 -240
  187. package/dist/chunk-WYLMJQVH.js.map +0 -1
  188. package/dist/chunk-XGZ5EVMB.js +0 -35
  189. package/dist/chunk-XGZ5EVMB.js.map +0 -1
  190. package/dist/chunk-XVPQGCH4.js +0 -176
  191. package/dist/chunk-XVPQGCH4.js.map +0 -1
  192. package/dist/chunk-ZOBNS7CX.js.map +0 -1
  193. package/dist/chunk-ZQIQ55KK.js +0 -51
  194. package/dist/chunk-ZQIQ55KK.js.map +0 -1
  195. package/dist/cli-U2BEUA55.js.map +0 -1
  196. package/dist/config-CNUIX23Q.js +0 -32
  197. package/dist/doctor-QJJXRWTO.js +0 -31
  198. package/dist/edit-HJ44P44P.js +0 -40
  199. package/dist/fund-Y5IAHZ5D.js +0 -40
  200. package/dist/inspect-NFQ6SQQQ.js +0 -37
  201. package/dist/install-DXX7PVUP.js +0 -854
  202. package/dist/install-DXX7PVUP.js.map +0 -1
  203. package/dist/outcome-ANV4QIED.js +0 -24
  204. package/dist/publish-PCBTCXCZ.js +0 -42
  205. package/dist/read-W7QVRBVD.js +0 -160
  206. package/dist/read-W7QVRBVD.js.map +0 -1
  207. package/dist/run-CJWPGMIQ.js.map +0 -1
  208. package/dist/search-JGAVKTYJ.js +0 -25
  209. package/dist/secp256k1-XRPVBC6V.js.map +0 -1
  210. package/dist/send-C5EOKXOU.js.map +0 -1
  211. package/dist/session-OBCUUIFX.js +0 -89
  212. package/dist/session-OBCUUIFX.js.map +0 -1
  213. package/dist/skill-heal-D6EPLPS6.js +0 -84
  214. package/dist/skill-heal-D6EPLPS6.js.map +0 -1
  215. package/dist/uninstall-OWJNJ5LI.js +0 -73
  216. package/dist/uninstall-OWJNJ5LI.js.map +0 -1
  217. package/dist/update-24Y2CQTT.js.map +0 -1
  218. package/dist/usdc-4VCDHFWX.js +0 -38
  219. package/dist/usdc-4VCDHFWX.js.map +0 -1
  220. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
  221. package/dist/wallet-OFXDIIGP.js +0 -33
  222. package/dist/wallet-OFXDIIGP.js.map +0 -1
  223. package/dist/wallet-SLRIYJ2U.js +0 -42
  224. package/dist/wallet-SLRIYJ2U.js.map +0 -1
  225. package/docs/command-reference.md +0 -261
  226. package/skills/tenjin/SKILL.md +0 -364
  227. package/skills/tenjin-publish/SKILL.md +0 -224
  228. package/skills/tenjin-publish/references/maintain.md +0 -39
  229. package/skills/tenjin-search/SKILL.md +0 -149
  230. package/skills/tenjin-search/references/permissions.md +0 -106
  231. /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
  232. /package/dist/{buy-2JBYPHAI.js.map → ccip-7RMRLAGV.js.map} +0 -0
  233. /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
  234. /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
  235. /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
  236. /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
  237. /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  238. /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
  239. /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
  240. /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
  241. /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
  242. /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
  243. /package/dist/{ccip-ZGGWQN4X.js.map → config-MXOX7XDR.js.map} +0 -0
  244. /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
  245. /package/dist/{config-CNUIX23Q.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  246. /package/dist/{doctor-QJJXRWTO.js.map → install-XUM2XSHW.js.map} +0 -0
  247. /package/dist/{edit-HJ44P44P.js.map → paths-P2N4JTDZ.js.map} +0 -0
  248. /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-SBXZEPEP.js.map} +0 -0
  249. /package/dist/{fund-Y5IAHZ5D.js.map → redact-46ZHF2NH.js.map} +0 -0
  250. /package/dist/{inspect-NFQ6SQQQ.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
  251. /package/dist/{outcome-ANV4QIED.js.map → status-line-wiring-BYPHTYZE.js.map} +0 -0
  252. /package/dist/{publish-PCBTCXCZ.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
  253. /package/dist/{search-JGAVKTYJ.js.map → wallet-PWAHVKWW.js.map} +0 -0
@@ -1,34 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
- PRIVATE_KEY_RE,
4
- WALLET_SCHEMA_VERSION,
5
- readWalletRecord,
6
- walletFileMode,
7
- writeWalletRecord
8
- } from "./chunk-3P3ES4XU.js";
9
- import {
10
- emitNotice
11
- } from "./chunk-B676GPS2.js";
12
- import {
13
- withFileLock
14
- } from "./chunk-ZOBNS7CX.js";
15
- import {
16
- evaluateSpendPolicy
17
- } from "./chunk-UO22YNY4.js";
18
- import {
19
- archivedWalletPath,
20
- passphraseBlobPath,
21
- passphraseBlobPathFor,
22
- spendLedgerPath,
23
- walletPath
24
- } from "./chunk-ZQIQ55KK.js";
25
- import {
26
- CliError,
27
- external_exports,
28
- fsyncDir,
29
- hasCode,
30
- writeFileAtomic
31
- } from "./chunk-PAOVPSP6.js";
3
+ createLocalSpendAuthorizer
4
+ } from "./chunk-DMZZLPZN.js";
32
5
  import {
33
6
  hashAuthorization,
34
7
  hashMessage,
@@ -37,16 +10,16 @@ import {
37
10
  publicKeyToAddress,
38
11
  serializeSignature,
39
12
  serializeTransaction
40
- } from "./chunk-M2O56UK7.js";
13
+ } from "./chunk-N35E6CM2.js";
41
14
  import {
42
15
  hmac,
43
16
  secp256k1,
44
17
  sha256
45
- } from "./chunk-W6R3HAAG.js";
18
+ } from "./chunk-JRGFKVAZ.js";
46
19
  import {
47
20
  InvalidAddressError,
48
- concat2 as concat,
49
- from,
21
+ concat3 as concat,
22
+ from2 as from,
50
23
  hexToBytes,
51
24
  isAddress,
52
25
  isEqual,
@@ -54,10 +27,10 @@ import {
54
27
  keccak256,
55
28
  numberToHex,
56
29
  random,
57
- slice2 as slice,
30
+ slice3 as slice,
58
31
  toHex,
59
32
  toHex2
60
- } from "./chunk-47PP7TAG.js";
33
+ } from "./chunk-EGELTSPU.js";
61
34
  import {
62
35
  ahash,
63
36
  anumber,
@@ -69,386 +42,869 @@ import {
69
42
  rotl,
70
43
  swap32IfBE,
71
44
  u32
72
- } from "./chunk-KYQVEKP5.js";
73
-
74
- // src/lib/wallet/local.ts
75
- 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";
76
70
 
77
- // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
78
- function pbkdf2Init(hash, _password, _salt, _opts) {
79
- ahash(hash);
80
- const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
81
- const { c, dkLen, asyncTick } = opts;
82
- anumber(c);
83
- anumber(dkLen);
84
- anumber(asyncTick);
85
- if (c < 1)
86
- throw new Error("iterations (c) should be >= 1");
87
- const password = kdfInputToBytes(_password);
88
- const salt = kdfInputToBytes(_salt);
89
- const DK = new Uint8Array(dkLen);
90
- const PRF = hmac.create(hash, password);
91
- const PRFSalt = PRF._cloneInto().update(salt);
92
- return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
93
- }
94
- function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
95
- PRF.destroy();
96
- PRFSalt.destroy();
97
- if (prfW)
98
- prfW.destroy();
99
- clean(u);
100
- 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;
101
97
  }
102
- function pbkdf2(hash, password, salt, opts) {
103
- const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
104
- let prfW;
105
- const arr = new Uint8Array(4);
106
- const view = createView(arr);
107
- const u = new Uint8Array(PRF.outputLen);
108
- for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
109
- const Ti = DK.subarray(pos, pos + PRF.outputLen);
110
- view.setInt32(0, ti, false);
111
- (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
112
- Ti.set(u.subarray(0, Ti.length));
113
- for (let ui = 1; ui < c; ui++) {
114
- PRF._cloneInto(prfW).update(u).digestInto(u);
115
- for (let i = 0; i < Ti.length; i++)
116
- Ti[i] ^= u[i];
117
- }
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;
118
104
  }
119
- return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
120
- }
121
-
122
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/generatePrivateKey.js
123
- function generatePrivateKey() {
124
- return toHex(secp256k1.utils.randomPrivateKey());
125
105
  }
126
-
127
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/toAccount.js
128
- function toAccount(source) {
129
- if (typeof source === "string") {
130
- if (!isAddress(source, { strict: false }))
131
- throw new InvalidAddressError({ address: source });
132
- return {
133
- address: source,
134
- type: "json-rpc"
135
- };
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
+ });
136
117
  }
137
- if (!isAddress(source.address, { strict: false }))
138
- throw new InvalidAddressError({ address: source.address });
139
- return {
140
- address: source.address,
141
- nonceManager: source.nonceManager,
142
- sign: source.sign,
143
- signAuthorization: source.signAuthorization,
144
- signMessage: source.signMessage,
145
- signTransaction: source.signTransaction,
146
- signTypedData: source.signTypedData,
147
- source: "custom",
148
- type: "local"
149
- };
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;
150
158
  }
151
-
152
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/sign.js
153
- var extraEntropy = false;
154
- async function sign({ hash, privateKey, to = "object" }) {
155
- const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), {
156
- lowS: true,
157
- 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 } : {}
158
164
  });
159
- const signature = {
160
- r: numberToHex(r, { size: 32 }),
161
- s: numberToHex(s, { size: 32 }),
162
- v: recovery ? 28n : 27n,
163
- yParity: recovery
164
- };
165
- return (() => {
166
- if (to === "bytes" || to === "hex")
167
- return serializeSignature({ ...signature, to });
168
- return signature;
169
- })();
170
165
  }
171
-
172
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signAuthorization.js
173
- async function signAuthorization(parameters) {
174
- const { chainId, nonce, privateKey, to = "object" } = parameters;
175
- const address = parameters.contractAddress ?? parameters.address;
176
- const signature = await sign({
177
- hash: hashAuthorization({ address, chainId, nonce }),
178
- privateKey,
179
- to
180
- });
181
- if (to === "object")
182
- return {
183
- address,
184
- chainId,
185
- nonce,
186
- ...signature
187
- };
188
- 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
+ }
189
179
  }
190
-
191
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signMessage.js
192
- async function signMessage({ message, privateKey }) {
193
- 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;
194
184
  }
195
-
196
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signTransaction.js
197
- async function signTransaction(parameters) {
198
- const { privateKey, transaction, serializer = serializeTransaction } = parameters;
199
- const signableTransaction = (() => {
200
- if (transaction.type === "eip4844")
201
- return {
202
- ...transaction,
203
- sidecars: false
204
- };
205
- return transaction;
206
- })();
207
- const signature = await sign({
208
- hash: keccak256(await serializer(signableTransaction)),
209
- privateKey
210
- });
211
- 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;
212
189
  }
213
-
214
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signTypedData.js
215
- async function signTypedData(parameters) {
216
- const { privateKey, ...typedData } = parameters;
217
- return await sign({
218
- hash: hashTypedData(typedData),
219
- privateKey,
220
- to: "hex"
221
- });
190
+ function isNotFound(err) {
191
+ return hasCode(err, "ENOENT");
222
192
  }
223
193
 
224
- // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/privateKeyToAccount.js
225
- function privateKeyToAccount(privateKey, options = {}) {
226
- const { nonceManager } = options;
227
- const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
228
- const address = publicKeyToAddress(publicKey);
229
- const account = toAccount({
230
- address,
231
- nonceManager,
232
- async sign({ hash }) {
233
- return sign({ hash, privateKey, to: "hex" });
234
- },
235
- async signAuthorization(authorization) {
236
- return signAuthorization({ ...authorization, privateKey });
237
- },
238
- async signMessage({ message }) {
239
- return signMessage({ message, privateKey });
240
- },
241
- async signTransaction(transaction, { serializer } = {}) {
242
- return signTransaction({ privateKey, transaction, serializer });
243
- },
244
- async signTypedData(typedData) {
245
- 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);
246
223
  }
247
224
  });
248
- return {
249
- ...account,
250
- publicKey,
251
- source: "privateKey"
252
- };
253
225
  }
254
-
255
- // node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js
256
- function isBytes(a) {
257
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
258
- }
259
- function abytes(b, ...lengths) {
260
- if (!isBytes(b))
261
- throw new Error("Uint8Array expected");
262
- if (lengths.length > 0 && !lengths.includes(b.length))
263
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
264
- }
265
- function u8(arr) {
266
- return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
267
- }
268
- function u322(arr) {
269
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
270
- }
271
- function clean2(...arrays) {
272
- for (let i = 0; i < arrays.length; i++) {
273
- 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;
274
236
  }
275
237
  }
276
- var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
277
- function overlapBytes(a, b) {
278
- return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
279
- a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
280
- b.byteOffset < a.byteOffset + a.byteLength;
281
- }
282
- function complexOverlapBytes(input, output) {
283
- if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
284
- throw new Error("complex overlap of input and output is not supported");
285
- }
286
- var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
287
- function wrappedCipher(key, ...args) {
288
- abytes(key);
289
- if (!isLE)
290
- throw new Error("Non little-endian hardware is not yet supported");
291
- if (params.nonceLength !== void 0) {
292
- const nonce = args[0];
293
- if (!nonce)
294
- throw new Error("nonce / iv required");
295
- if (params.varSizeNonce)
296
- abytes(nonce);
297
- else
298
- abytes(nonce, params.nonceLength);
299
- }
300
- const tagl = params.tagLength;
301
- if (tagl && args[1] !== void 0) {
302
- 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
+ };
303
253
  }
304
- const cipher = constructor(key, ...args);
305
- const checkOutput = (fnLength, output) => {
306
- if (output !== void 0) {
307
- if (fnLength !== 2)
308
- throw new Error("cipher output not supported");
309
- abytes(output);
310
- }
311
- };
312
- let called = false;
313
- const wrCipher = {
314
- encrypt(data, output) {
315
- if (called)
316
- throw new Error("cannot encrypt() twice with same key + nonce");
317
- called = true;
318
- abytes(data);
319
- checkOutput(cipher.encrypt.length, output);
320
- return cipher.encrypt(data, output);
321
- },
322
- decrypt(data, output) {
323
- abytes(data);
324
- if (tagl && data.length < tagl)
325
- throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
326
- checkOutput(cipher.decrypt.length, output);
327
- return cipher.decrypt(data, output);
328
- }
329
- };
330
- return wrCipher;
331
254
  }
332
- Object.assign(wrappedCipher, params);
333
- return wrappedCipher;
334
- };
335
- function getOutput(expectedLength, out, onlyAligned = true) {
336
- if (out === void 0)
337
- return new Uint8Array(expectedLength);
338
- if (out.length !== expectedLength)
339
- throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
340
- if (onlyAligned && !isAligned32(out))
341
- throw new Error("invalid output, must be aligned");
342
- return out;
343
- }
344
- function isAligned32(bytes) {
345
- return bytes.byteOffset % 4 === 0;
346
- }
347
- function copyBytes(bytes) {
348
- 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();
349
261
  }
350
-
351
- // node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js
352
- var BLOCK_SIZE = 16;
353
- var BLOCK_SIZE32 = 4;
354
- var POLY = 283;
355
- function mul2(n) {
356
- 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;
357
267
  }
358
- function mul(a, b) {
359
- let res = 0;
360
- for (; b > 0; b >>= 1) {
361
- res ^= a & -(b & 1);
362
- a = mul2(a);
363
- }
364
- 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";
365
276
  }
366
- var sbox = /* @__PURE__ */ (() => {
367
- const t = new Uint8Array(256);
368
- for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
369
- t[i] = x;
370
- const box = new Uint8Array(256);
371
- box[0] = 99;
372
- for (let i = 0; i < 255; i++) {
373
- let x = t[255 - i];
374
- x |= x << 8;
375
- box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
376
- }
377
- clean2(t);
378
- return box;
379
- })();
380
- var rotr32_8 = (n) => n << 24 | n >>> 8;
381
- var rotl32_8 = (n) => n << 8 | n >>> 24;
382
- function genTtable(sbox2, fn) {
383
- if (sbox2.length !== 256)
384
- throw new Error("Wrong sbox length");
385
- const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
386
- const T1 = T0.map(rotl32_8);
387
- const T2 = T1.map(rotl32_8);
388
- const T3 = T2.map(rotl32_8);
389
- const T01 = new Uint32Array(256 * 256);
390
- const T23 = new Uint32Array(256 * 256);
391
- const sbox22 = new Uint16Array(256 * 256);
392
- for (let i = 0; i < 256; i++) {
393
- for (let j = 0; j < 256; j++) {
394
- const idx = i * 256 + j;
395
- T01[idx] = T0[i] ^ T1[j];
396
- T23[idx] = T2[i] ^ T3[j];
397
- 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 };
398
286
  }
399
287
  }
400
- return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
401
- }
402
- var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
403
- var xPowers = /* @__PURE__ */ (() => {
404
- const p = new Uint8Array(16);
405
- for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
406
- p[i] = x;
407
- return p;
408
- })();
409
- function expandKeyLE(key) {
410
- abytes(key);
411
- const len = key.length;
412
- if (![16, 24, 32].includes(len))
413
- throw new Error("aes: invalid key size, should be 16, 24 or 32, got " + len);
414
- const { sbox2 } = tableEncoding;
415
- const toClean = [];
416
- if (!isAligned32(key))
417
- toClean.push(key = copyBytes(key));
418
- const k32 = u322(key);
419
- const Nk = k32.length;
420
- const subByte = (n) => applySbox(sbox2, n, n, n, n);
421
- const xk = new Uint32Array(len + 28);
422
- xk.set(k32);
423
- for (let i = Nk; i < xk.length; i++) {
424
- let t = xk[i - 1];
425
- if (i % Nk === 0)
426
- t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
427
- else if (Nk > 6 && i % Nk === 4)
428
- t = subByte(t);
429
- 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" };
430
303
  }
431
- clean2(...toClean);
432
- return xk;
433
- }
434
- function apply0123(T01, T23, s0, s1, s2, s3) {
435
- return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
436
- }
437
- function applySbox(sbox2, s0, s1, s2, s3) {
438
- return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
304
+ throw noPassphraseError();
439
305
  }
440
- function encrypt(xk, s0, s1, s2, s3) {
441
- const { sbox2, T01, T23 } = tableEncoding;
442
- let k = 0;
443
- s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
444
- const rounds = xk.length / 4 - 2;
445
- for (let i = 0; i < rounds; i++) {
446
- const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
447
- const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
448
- const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
449
- const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
450
- s0 = t02, s1 = t12, s2 = t22, s3 = t32;
451
- }
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
+ }
452
908
  const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
453
909
  const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
454
910
  const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
@@ -572,539 +1028,251 @@ function XorAndSalsa(prev, pi, input, ii, out, oi) {
572
1028
  out[oi++] = y12 + x12 | 0;
573
1029
  out[oi++] = y13 + x13 | 0;
574
1030
  out[oi++] = y14 + x14 | 0;
575
- out[oi++] = y15 + x15 | 0;
576
- }
577
- function BlockMix(input, ii, out, oi, r) {
578
- let head = oi + 0;
579
- let tail = oi + 16 * r;
580
- for (let i = 0; i < 16; i++)
581
- out[tail + i] = input[ii + (2 * r - 1) * 16 + i];
582
- for (let i = 0; i < r; i++, head += 16, ii += 16) {
583
- XorAndSalsa(out, tail, input, ii, out, head);
584
- if (i > 0)
585
- tail += 16;
586
- XorAndSalsa(out, head, input, ii += 16, out, tail);
587
- }
588
- }
589
- function scryptInit(password, salt, _opts) {
590
- const opts = checkOpts({
591
- dkLen: 32,
592
- asyncTick: 10,
593
- maxmem: 1024 ** 3 + 1024
594
- }, _opts);
595
- const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
596
- anumber(N);
597
- anumber(r);
598
- anumber(p);
599
- anumber(dkLen);
600
- anumber(asyncTick);
601
- anumber(maxmem);
602
- if (onProgress !== void 0 && typeof onProgress !== "function")
603
- throw new Error("progressCb should be function");
604
- const blockSize = 128 * r;
605
- const blockSize32 = blockSize / 4;
606
- const pow32 = Math.pow(2, 32);
607
- if (N <= 1 || (N & N - 1) !== 0 || N > pow32) {
608
- throw new Error("Scrypt: N must be larger than 1, a power of 2, and less than 2^32");
609
- }
610
- if (p < 0 || p > (pow32 - 1) * 32 / blockSize) {
611
- throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");
612
- }
613
- if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
614
- throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");
615
- }
616
- const memUsed = blockSize * (N + p);
617
- if (memUsed > maxmem) {
618
- throw new Error("Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of " + maxmem);
619
- }
620
- const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
621
- const B32 = u32(B);
622
- const V = u32(new Uint8Array(blockSize * N));
623
- const tmp = u32(new Uint8Array(blockSize));
624
- let blockMixCb = () => {
625
- };
626
- if (onProgress) {
627
- const totalBlockMix = 2 * N * p;
628
- const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1);
629
- let blockMixCnt = 0;
630
- blockMixCb = () => {
631
- blockMixCnt++;
632
- if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
633
- onProgress(blockMixCnt / totalBlockMix);
634
- };
635
- }
636
- return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
637
- }
638
- function scryptOutput(password, dkLen, B, V, tmp) {
639
- const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
640
- clean(B, V, tmp);
641
- return res;
642
- }
643
- async function scryptAsync(password, salt, opts) {
644
- const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
645
- swap32IfBE(B32);
646
- for (let pi = 0; pi < p; pi++) {
647
- const Pi = blockSize32 * pi;
648
- for (let i = 0; i < blockSize32; i++)
649
- V[i] = B32[Pi + i];
650
- let pos = 0;
651
- await asyncLoop(N - 1, asyncTick, () => {
652
- BlockMix(V, pos, V, pos += blockSize32, r);
653
- blockMixCb();
654
- });
655
- BlockMix(V, (N - 1) * blockSize32, B32, Pi, r);
656
- blockMixCb();
657
- await asyncLoop(N, asyncTick, () => {
658
- const j = B32[Pi + blockSize32 - 16] % N;
659
- for (let k = 0; k < blockSize32; k++)
660
- tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];
661
- BlockMix(tmp, 0, B32, Pi, r);
662
- blockMixCb();
663
- });
664
- }
665
- swap32IfBE(B32);
666
- return scryptOutput(password, dkLen, B, V, tmp);
667
- }
668
-
669
- // node_modules/.pnpm/ox@0.14.30_typescript@6.0.3_zod@4.4.3/node_modules/ox/_esm/core/Keystore.js
670
- function decrypt(keystore, key, options = {}) {
671
- const { as = "Hex" } = options;
672
- const key_ = from(typeof key === "function" ? key() : key);
673
- const encKey = slice(key_, 0, 16);
674
- const macKey = slice(key_, 16, 32);
675
- const ciphertext = from(`0x${keystore.crypto.ciphertext}`);
676
- const mac = keccak2562(concat(macKey, ciphertext));
677
- if (!isEqual(mac, from(`0x${keystore.crypto.mac}`)))
678
- throw new Error("corrupt keystore");
679
- const data = ctr(encKey, from(`0x${keystore.crypto.cipherparams.iv}`)).decrypt(ciphertext);
680
- if (as === "Hex")
681
- return toHex2(data);
682
- return data;
683
- }
684
- function encrypt2(privateKey, key, options) {
685
- const { id = crypto.randomUUID(), kdf, kdfparams, iv } = options;
686
- const key_ = from(typeof key === "function" ? key() : key);
687
- const value_ = from(privateKey);
688
- const encKey = slice(key_, 0, 16);
689
- const macKey = slice(key_, 16, 32);
690
- const ciphertext = ctr(encKey, iv).encrypt(value_);
691
- const mac = keccak2562(concat(macKey, ciphertext));
692
- return {
693
- crypto: {
694
- cipher: "aes-128-ctr",
695
- ciphertext: toHex2(ciphertext).slice(2),
696
- cipherparams: { iv: toHex2(iv).slice(2) },
697
- kdf,
698
- kdfparams,
699
- mac: toHex2(mac).slice(2)
700
- },
701
- id,
702
- version: 3
703
- };
704
- }
705
- function pbkdf22(options) {
706
- const { iv, iterations = 262144, password } = options;
707
- const salt = options.salt ? from(options.salt) : random(32);
708
- const key = toHex2(pbkdf2(sha256, password, salt, { c: iterations, dkLen: 32 }));
709
- return defineKey(() => key, {
710
- iv,
711
- kdfparams: {
712
- c: iterations,
713
- dklen: 32,
714
- prf: "hmac-sha256",
715
- salt: toHex2(salt).slice(2)
716
- },
717
- kdf: "pbkdf2"
718
- });
719
- }
720
- async function scryptAsync2(options) {
721
- const { iv, n = 262144, password } = options;
722
- const p = 8;
723
- const r = 1;
724
- const salt = options.salt ? from(options.salt) : random(32);
725
- const key = toHex2(await scryptAsync(password, salt, { N: n, dkLen: 32, r, p }));
726
- return defineKey(() => key, {
727
- iv,
728
- kdfparams: {
729
- dklen: 32,
730
- n,
731
- p,
732
- r,
733
- salt: toHex2(salt).slice(2)
734
- },
735
- kdf: "scrypt"
736
- });
737
- }
738
- async function toKeyAsync(keystore, options) {
739
- const { crypto: crypto2 } = keystore;
740
- const { password } = options;
741
- const { cipherparams, kdf, kdfparams } = crypto2;
742
- const { iv } = cipherparams;
743
- const { c, n, p, r, salt } = kdfparams;
744
- const [key] = await (async () => {
745
- switch (kdf) {
746
- case "scrypt":
747
- return await scryptAsync2({
748
- iv: from(`0x${iv}`),
749
- n,
750
- p,
751
- r,
752
- salt: from(`0x${salt}`),
753
- password
754
- });
755
- case "pbkdf2":
756
- return await pbkdf22({
757
- iv: from(`0x${iv}`),
758
- iterations: c,
759
- password,
760
- salt: from(`0x${salt}`)
761
- });
762
- default:
763
- throw new Error("unsupported kdf");
764
- }
765
- })();
766
- return key;
767
- }
768
- function defineKey(key, options) {
769
- const iv = options.iv ? from(options.iv) : random(16);
770
- return [key, { ...options, iv }];
771
- }
772
-
773
- // src/lib/wallet/passphrase.ts
774
- import { execFile } from "child_process";
775
- import { randomBytes } from "crypto";
776
- import { readFile, unlink } from "fs/promises";
777
- var KEYCHAIN_SERVICE = "tenjin-cli";
778
- var LEGACY_ACCOUNT = "wallet";
779
- var ACCOUNT_ADDRESS_RE = /^0x[0-9a-f]{40}$/;
780
- var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
781
- function walletStoreAccount(address) {
782
- const account = address.toLowerCase();
783
- if (!ACCOUNT_ADDRESS_RE.test(account)) {
784
- throw new CliError("INTERNAL", `Not a valid wallet address for passphrase storage: ${address}`);
785
- }
786
- return account;
787
- }
788
- function defaultExecFor(timeoutMs) {
789
- return (file, args, stdin) => new Promise((resolve, reject) => {
790
- const child = execFile(
791
- file,
792
- args,
793
- { encoding: "utf8", ...timeoutMs !== void 0 ? { timeout: timeoutMs } : {} },
794
- (err, stdout, stderr) => {
795
- if (err) reject(err);
796
- else resolve({ stdout, stderr });
797
- }
798
- );
799
- if (stdin !== void 0) {
800
- child.stdin?.on("error", () => void 0);
801
- child.stdin?.end(stdin);
802
- }
803
- });
1031
+ out[oi++] = y15 + x15 | 0;
804
1032
  }
805
- function storeFor(deps) {
806
- switch (deps.platform ?? process.platform) {
807
- case "darwin":
808
- return keychainStore(deps);
809
- case "win32":
810
- return dpapiStore(deps);
811
- case "linux":
812
- return secretServiceStore(deps);
813
- default:
814
- 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);
815
1043
  }
816
1044
  }
817
- async function resolvePassphrase(deps, address) {
818
- const fromEnv = envPassphrase(deps.env);
819
- if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
820
- const store = storeFor(deps);
821
- if (store !== null) {
822
- const account = walletStoreAccount(address);
823
- const own = await store.read(account);
824
- if (own !== null) return { passphrase: own, source: store.source };
825
- const legacy = await store.read(LEGACY_ACCOUNT);
826
- if (legacy !== null) {
827
- return {
828
- passphrase: legacy,
829
- source: store.source,
830
- migrateLegacy: () => migrateLegacyEntry(store, account, legacy)
831
- };
832
- }
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");
833
1065
  }
834
- if (canPrompt(deps)) {
835
- const entered = await promptOf(deps)("Wallet passphrase: ");
836
- if (entered.length === 0) throw noPassphraseError();
837
- 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)");
838
1068
  }
839
- throw noPassphraseError();
840
- }
841
- async function migrateLegacyEntry(store, account, passphrase) {
842
- if (!await store.store(account, passphrase)) return false;
843
- if (await store.read(account) !== passphrase) return false;
844
- await store.remove(LEGACY_ACCOUNT);
845
- return true;
846
- }
847
- async function storePassphraseForWallet(deps, address, passphrase) {
848
- const store = storeFor(deps);
849
- if (store === null) return "no-store";
850
- const account = walletStoreAccount(address);
851
- if (await store.read(account) === passphrase) return "stored";
852
- if (store.storable !== void 0 && !store.storable(passphrase)) return "rejected-characters";
853
- if (!await store.store(account, passphrase)) return "store-failed";
854
- return await store.read(account) === passphrase ? "stored" : "store-failed";
855
- }
856
- async function resolvePassphraseForCreate(deps, address) {
857
- const fromEnv = envPassphrase(deps.env);
858
- if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
859
- const store = storeFor(deps);
860
- if (store !== null) {
861
- const account = walletStoreAccount(address);
862
- const generated = randomBytes(32).toString("base64url");
863
- if (await store.store(account, generated) && await store.read(account) === generated) {
864
- return { passphrase: generated, source: store.source };
865
- }
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");
866
1071
  }
867
- if (canPrompt(deps)) {
868
- const prompt = promptOf(deps);
869
- const first = await prompt("Set a wallet passphrase: ");
870
- if (first.length === 0) {
871
- throw new CliError("USAGE", "The wallet passphrase must not be empty.", {
872
- fix: "Enter a non-empty passphrase, or set TENJIN_WALLET_PASSPHRASE."
873
- });
874
- }
875
- const second = await prompt("Confirm passphrase: ");
876
- if (first !== second) {
877
- throw new CliError("USAGE", "The passphrases did not match.", {
878
- fix: "Run `tenjin wallet create` again and enter the same passphrase both times."
879
- });
880
- }
881
- 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);
882
1075
  }
883
- throw noPassphraseError();
884
- }
885
- function keychainStore(deps) {
886
- const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
887
- return {
888
- source: "keychain",
889
- async read(account) {
890
- try {
891
- const { stdout } = await exec("security", [
892
- "find-generic-password",
893
- "-s",
894
- KEYCHAIN_SERVICE,
895
- "-a",
896
- account,
897
- "-w"
898
- ]);
899
- return trimmedNonEmpty(stdout);
900
- } catch {
901
- return null;
902
- }
903
- },
904
- // The one backend that interpolates into a command line, so only base64url
905
- // values pass; escaping is NOT a safe alternative (backslash bites even
906
- // inside single quotes there).
907
- storable: (passphrase) => BASE64URL_RE.test(passphrase),
908
- async store(account, passphrase) {
909
- if (!BASE64URL_RE.test(passphrase) || !BASE64URL_RE.test(account)) return false;
910
- try {
911
- const command = `add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} -w '${passphrase}'
912
- `;
913
- await exec("security", ["-i"], command);
914
- return true;
915
- } catch {
916
- return false;
917
- }
918
- },
919
- async remove(account) {
920
- try {
921
- await exec("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account]);
922
- return true;
923
- } catch {
924
- return false;
925
- }
926
- }
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 = () => {
927
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 };
928
1093
  }
929
- var DPAPI_PROTECT_SCRIPT = [
930
- "Add-Type -AssemblyName System.Security;",
931
- "$in = [Console]::In.ReadToEnd();",
932
- "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in);",
933
- "$prot = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser');",
934
- "[Console]::Out.Write([Convert]::ToBase64String($prot));"
935
- ].join(" ");
936
- var DPAPI_UNPROTECT_SCRIPT = [
937
- "Add-Type -AssemblyName System.Security;",
938
- "$in = [Console]::In.ReadToEnd();",
939
- "$blob = [Convert]::FromBase64String($in.Trim());",
940
- "$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser');",
941
- "[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain));"
942
- ].join(" ");
943
- function powershellArgs(script) {
944
- 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;
945
1098
  }
946
- function dpapiStore(deps) {
947
- const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
948
- const blobPathFor = (account) => account === LEGACY_ACCOUNT ? passphraseBlobPath(deps.dir) : passphraseBlobPathFor(account, deps.dir);
949
- return {
950
- source: "dpapi",
951
- async read(account) {
952
- let blob;
953
- try {
954
- blob = await readFile(blobPathFor(account), "utf8");
955
- } catch {
956
- return null;
957
- }
958
- try {
959
- const { stdout } = await exec(
960
- "powershell.exe",
961
- powershellArgs(DPAPI_UNPROTECT_SCRIPT),
962
- blob
963
- );
964
- const passphrase = stdout.replace(/\r?\n$/, "");
965
- return passphrase.length > 0 ? passphrase : null;
966
- } catch {
967
- return null;
968
- }
969
- },
970
- async store(account, passphrase) {
971
- try {
972
- const { stdout } = await exec(
973
- "powershell.exe",
974
- powershellArgs(DPAPI_PROTECT_SCRIPT),
975
- passphrase
976
- );
977
- const blob = stdout.replace(/\r?\n$/, "").trim();
978
- if (blob.length === 0) return false;
979
- await writeFileAtomic(blobPathFor(account), blob, { mode: 384 });
980
- return true;
981
- } catch {
982
- return false;
983
- }
984
- },
985
- async remove(account) {
986
- try {
987
- await unlink(blobPathFor(account));
988
- return true;
989
- } catch {
990
- return false;
991
- }
992
- }
993
- };
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);
994
1123
  }
995
- function secretServiceStore(deps) {
996
- 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));
997
1148
  return {
998
- source: "secret-service",
999
- async read(account) {
1000
- try {
1001
- const { stdout } = await exec("secret-tool", [
1002
- "lookup",
1003
- "service",
1004
- KEYCHAIN_SERVICE,
1005
- "account",
1006
- account
1007
- ]);
1008
- return trimmedNonEmpty(stdout);
1009
- } catch {
1010
- return null;
1011
- }
1012
- },
1013
- async store(account, passphrase) {
1014
- try {
1015
- await exec(
1016
- "secret-tool",
1017
- [
1018
- "store",
1019
- `--label=tenjin-cli wallet ${account}`,
1020
- "service",
1021
- KEYCHAIN_SERVICE,
1022
- "account",
1023
- account
1024
- ],
1025
- passphrase
1026
- );
1027
- return true;
1028
- } catch {
1029
- return false;
1030
- }
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)
1031
1156
  },
1032
- async remove(account) {
1033
- try {
1034
- await exec("secret-tool", ["clear", "service", KEYCHAIN_SERVICE, "account", account]);
1035
- return true;
1036
- } catch {
1037
- return false;
1038
- }
1039
- }
1157
+ id,
1158
+ version: 3
1040
1159
  };
1041
1160
  }
1042
- function trimmedNonEmpty(stdout) {
1043
- const value = stdout.replace(/\r?\n$/, "");
1044
- return value.length > 0 ? value : null;
1045
- }
1046
- function envPassphrase(env) {
1047
- const value = env.TENJIN_WALLET_PASSPHRASE;
1048
- 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
+ });
1049
1175
  }
1050
- function canPrompt(deps) {
1051
- 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
+ });
1052
1193
  }
1053
- function promptOf(deps) {
1054
- 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;
1055
1223
  }
1056
- function noPassphraseError() {
1057
- return new CliError("USAGE", "No wallet passphrase is available.", {
1058
- fix: "Set TENJIN_WALLET_PASSPHRASE (headless) or run in a terminal."
1059
- });
1224
+ function defineKey(key, options) {
1225
+ const iv = options.iv ? from(options.iv) : random(16);
1226
+ return [key, { ...options, iv }];
1060
1227
  }
1061
- var CTRL_C = 3;
1062
- var CTRL_D = 4;
1063
- var BACKSPACE = 127;
1064
- var BACKSPACE_ALT = 8;
1065
- 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
+ );
1066
1240
  return new Promise((resolve, reject) => {
1067
- const stdin = process.stdin;
1068
- const stderr = process.stderr;
1069
- const wasRaw = stdin.isRaw;
1070
- let value = "";
1071
- const cleanup = () => {
1072
- stdin.setRawMode?.(wasRaw ?? false);
1073
- stdin.pause();
1074
- stdin.removeListener("data", onData);
1075
- };
1076
- const onData = (chunk) => {
1077
- for (const ch of chunk.toString("utf8")) {
1078
- const code = ch.charCodeAt(0);
1079
- if (ch === "\n" || ch === "\r" || code === CTRL_D) {
1080
- cleanup();
1081
- stderr.write("\n");
1082
- resolve(value);
1083
- return;
1084
- }
1085
- if (code === CTRL_C) {
1086
- cleanup();
1087
- stderr.write("\n");
1088
- reject(
1089
- new CliError("USAGE", "Passphrase entry was cancelled.", {
1090
- fix: "Run the command again, or set TENJIN_WALLET_PASSPHRASE."
1091
- })
1092
- );
1093
- return;
1094
- }
1095
- if (code === BACKSPACE || code === BACKSPACE_ALT) {
1096
- value = value.slice(0, -1);
1097
- } else {
1098
- value += ch;
1099
- }
1100
- }
1101
- };
1102
- stderr.write(label);
1103
- stdin.setRawMode?.(true);
1104
- stdin.resume();
1105
- 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();
1106
1266
  });
1107
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
+ }
1108
1276
 
1109
1277
  // src/lib/wallet/local.ts
1110
1278
  var isWindows = process.platform === "win32";
@@ -1172,9 +1340,12 @@ async function verifyLocalWallet(deps) {
1172
1340
  }
1173
1341
  let key;
1174
1342
  try {
1175
- const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1343
+ const derived = await deriveKeystoreKey(cred.keystore, resolved.passphrase, deps.derivation);
1176
1344
  key = decrypt(cred.keystore, derived);
1177
- } 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
+ }
1178
1349
  if (resolved.migrateLegacy !== void 0) {
1179
1350
  return {
1180
1351
  status: "broken",
@@ -1389,9 +1560,10 @@ async function accountForSigning(cred, deps) {
1389
1560
  );
1390
1561
  let key;
1391
1562
  try {
1392
- const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1563
+ const derived = await deriveKeystoreKey(cred.keystore, resolved.passphrase, deps.derivation);
1393
1564
  key = decrypt(cred.keystore, derived);
1394
1565
  } catch (err) {
1566
+ if (err instanceof Error && ["AbortError", "TimeoutError"].includes(err.name)) throw err;
1395
1567
  if (resolved.migrateLegacy !== void 0) {
1396
1568
  throw new CliError(
1397
1569
  "WALLET_INVALID_KEY",
@@ -1455,140 +1627,6 @@ function walletRecord(address, keystore) {
1455
1627
  };
1456
1628
  }
1457
1629
 
1458
- // src/lib/wallet/spend.ts
1459
- import { mkdir, readFile as readFile2 } from "fs/promises";
1460
- import { randomUUID } from "crypto";
1461
- var DEFAULT_WINDOW_MS = 864e5;
1462
- var RESERVATION_TTL_MS = 6e5;
1463
- var ReservationSchema = external_exports.object({
1464
- id: external_exports.string(),
1465
- amountAtomic: external_exports.string().regex(/^\d+$/),
1466
- atMs: external_exports.number()
1467
- });
1468
- var LedgerSchema = external_exports.object({
1469
- schemaVersion: external_exports.literal(2),
1470
- windowStartMs: external_exports.number(),
1471
- committedAtomic: external_exports.string().regex(/^\d+$/),
1472
- reservations: external_exports.array(ReservationSchema)
1473
- });
1474
- function emptyLedger(nowMs) {
1475
- return { schemaVersion: 2, windowStartMs: nowMs, committedAtomic: "0", reservations: [] };
1476
- }
1477
- function createLocalSpendAuthorizer(deps) {
1478
- const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;
1479
- const now = deps.now ?? Date.now;
1480
- const path = spendLedgerPath(deps.dir);
1481
- const lockPath = `${path}.lock`;
1482
- let warnedCorrupt = false;
1483
- const freshen = (ledger, nowMs) => {
1484
- if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);
1485
- return {
1486
- ...ledger,
1487
- reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS)
1488
- };
1489
- };
1490
- const spentOf = (ledger) => ledger.reservations.reduce(
1491
- (sum, r) => sum + BigInt(r.amountAtomic),
1492
- BigInt(ledger.committedAtomic)
1493
- );
1494
- const persist = async (ledger) => {
1495
- await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}
1496
- `, {
1497
- mode: 384,
1498
- dirMode: 448
1499
- });
1500
- };
1501
- async function withLedger(fn) {
1502
- await mkdir(deps.dir, { recursive: true, mode: 448 });
1503
- return withFileLock(lockPath, async () => {
1504
- const nowMs = now();
1505
- const read = await readLedger(path);
1506
- if (read.corrupt !== void 0 && !warnedCorrupt) {
1507
- warnedCorrupt = true;
1508
- deps.onCorrupt?.(read.corrupt);
1509
- }
1510
- const ledger = freshen(read.ledger, nowMs);
1511
- return fn(ledger, nowMs);
1512
- });
1513
- }
1514
- return {
1515
- policyEnforcement: "client-only",
1516
- async authorize(req) {
1517
- return withLedger(async (ledger) => {
1518
- const sessionSpentAtomic = spentOf(ledger);
1519
- const evaluation = evaluateSpendPolicy(deps.policy, {
1520
- amountAtomic: req.amountAtomic,
1521
- creator: req.creator,
1522
- ...req.maxPriceAtomic !== void 0 ? { maxPriceAtomic: req.maxPriceAtomic } : {},
1523
- sessionSpentAtomic
1524
- });
1525
- const base = {
1526
- ...evaluation,
1527
- amountAtomic: req.amountAtomic,
1528
- sessionSpentAtomic,
1529
- sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,
1530
- policyEnforcement: "client-only"
1531
- };
1532
- if (evaluation.decision === "deny" || deps.policy.sessionBudgetAtomic === 0n) {
1533
- return base;
1534
- }
1535
- const reservation = {
1536
- id: randomUUID(),
1537
- amountAtomic: req.amountAtomic.toString(),
1538
- atMs: now()
1539
- };
1540
- await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });
1541
- return { ...base, reservationId: reservation.id };
1542
- });
1543
- },
1544
- async commit(reservationId, amountAtomic) {
1545
- await withLedger(async (ledger) => {
1546
- const reservation = reservationId !== void 0 ? ledger.reservations.find((r) => r.id === reservationId) : void 0;
1547
- const settled = reservation !== void 0 ? BigInt(reservation.amountAtomic) : amountAtomic;
1548
- await persist({
1549
- ...ledger,
1550
- committedAtomic: (BigInt(ledger.committedAtomic) + settled).toString(),
1551
- reservations: reservationId !== void 0 ? ledger.reservations.filter((r) => r.id !== reservationId) : ledger.reservations
1552
- });
1553
- });
1554
- },
1555
- async release(reservationId) {
1556
- if (reservationId === void 0) return;
1557
- await withLedger(async (ledger) => {
1558
- if (!ledger.reservations.some((r) => r.id === reservationId)) return;
1559
- await persist({
1560
- ...ledger,
1561
- reservations: ledger.reservations.filter((r) => r.id !== reservationId)
1562
- });
1563
- });
1564
- }
1565
- };
1566
- }
1567
- async function readLedger(path) {
1568
- let raw;
1569
- try {
1570
- raw = await readFile2(path, "utf8");
1571
- } catch (err) {
1572
- if (hasCode(err, "ENOENT")) return { ledger: null };
1573
- return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };
1574
- }
1575
- let json;
1576
- try {
1577
- json = JSON.parse(raw);
1578
- } catch {
1579
- return { ledger: null, corrupt: "not valid JSON" };
1580
- }
1581
- const parsed = LedgerSchema.safeParse(json);
1582
- if (parsed.success) return { ledger: parsed.data };
1583
- const issue = parsed.error.issues[0];
1584
- const field = issue?.path.join(".");
1585
- const message = issue?.message ?? "schema mismatch";
1586
- return {
1587
- ledger: null,
1588
- corrupt: field !== void 0 && field.length > 0 ? `${field}: ${message}` : message
1589
- };
1590
- }
1591
-
1592
1630
  // src/lib/wallet/index.ts
1593
1631
  function resolveWalletProvider(ctx, opts = {}) {
1594
1632
  if (opts.provider !== void 0) return opts.provider;
@@ -1624,15 +1662,15 @@ async function describeWallet(provider) {
1624
1662
  }
1625
1663
 
1626
1664
  export {
1665
+ walletFileExists,
1666
+ walletExistsError,
1627
1667
  resolvePassphraseForCreate,
1628
- verifyLocalWallet,
1629
1668
  prepareLocalWallet,
1630
1669
  commitLocalWallet,
1631
1670
  createLocalWallet,
1632
1671
  verifyAndPreserveOutgoingWallet,
1633
1672
  parkOutgoingWallet,
1634
1673
  restoreParkedWallet,
1635
- createLocalSpendAuthorizer,
1636
1674
  resolveWalletProvider,
1637
1675
  resolveSpendAuthorizer,
1638
1676
  describeWallet
@@ -1642,4 +1680,4 @@ export {
1642
1680
  @noble/ciphers/esm/utils.js:
1643
1681
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1644
1682
  */
1645
- //# sourceMappingURL=chunk-7GJQ5RGA.js.map
1683
+ //# sourceMappingURL=chunk-YEETV6IW.js.map