tenjin-cli 0.1.0-alpha.3 → 0.1.0-alpha.31

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 (284) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +100 -266
  3. package/dist/{_esm-FEASBWRP.js → _esm-MEXZI5DL.js} +9 -10
  4. package/dist/alive-J64H46HI.js +31 -0
  5. package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
  6. package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
  7. package/dist/chunk-27EPWVOY.js +108 -0
  8. package/dist/chunk-27EPWVOY.js.map +1 -0
  9. package/dist/chunk-2SNUOHAT.js +75 -0
  10. package/dist/chunk-2SNUOHAT.js.map +1 -0
  11. package/dist/{chunk-Z6MFJV5Z.js → chunk-2XLC3AEX.js} +857 -504
  12. package/dist/chunk-2XLC3AEX.js.map +1 -0
  13. package/dist/chunk-3623BLPV.js +184 -0
  14. package/dist/chunk-3623BLPV.js.map +1 -0
  15. package/dist/chunk-3UCIG4TG.js +65 -0
  16. package/dist/chunk-3UCIG4TG.js.map +1 -0
  17. package/dist/chunk-4ZZO6ULA.js +151 -0
  18. package/dist/chunk-4ZZO6ULA.js.map +1 -0
  19. package/dist/chunk-5C32RLTA.js +115 -0
  20. package/dist/chunk-5C32RLTA.js.map +1 -0
  21. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  22. package/dist/chunk-5K5W4S66.js +105 -0
  23. package/dist/chunk-5K5W4S66.js.map +1 -0
  24. package/dist/chunk-5MARFNSB.js +2018 -0
  25. package/dist/chunk-5MARFNSB.js.map +1 -0
  26. package/dist/{chunk-CYOF7ROH.js → chunk-6E5R45ZO.js} +3 -3
  27. package/dist/chunk-77TCKDEC.js +1987 -0
  28. package/dist/chunk-77TCKDEC.js.map +1 -0
  29. package/dist/chunk-7EKYXMUO.js +7536 -0
  30. package/dist/chunk-7EKYXMUO.js.map +1 -0
  31. package/dist/chunk-7Q5FDF65.js +159 -0
  32. package/dist/chunk-7Q5FDF65.js.map +1 -0
  33. package/dist/chunk-7QKHZQKW.js +1680 -0
  34. package/dist/chunk-7QKHZQKW.js.map +1 -0
  35. package/dist/{chunk-MUBUQVC3.js → chunk-7WEQQJLG.js} +6 -5
  36. package/dist/{chunk-MUBUQVC3.js.map → chunk-7WEQQJLG.js.map} +1 -1
  37. package/dist/chunk-7WU4OPLP.js +244 -0
  38. package/dist/chunk-7WU4OPLP.js.map +1 -0
  39. package/dist/chunk-7ZRL2LBQ.js +192 -0
  40. package/dist/chunk-7ZRL2LBQ.js.map +1 -0
  41. package/dist/chunk-A36LQPHV.js +29 -0
  42. package/dist/chunk-A36LQPHV.js.map +1 -0
  43. package/dist/chunk-AGZ7PJKY.js +326 -0
  44. package/dist/chunk-AGZ7PJKY.js.map +1 -0
  45. package/dist/chunk-AKWGE6JQ.js +49 -0
  46. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  47. package/dist/chunk-B7HUUJOK.js +29 -0
  48. package/dist/chunk-B7HUUJOK.js.map +1 -0
  49. package/dist/{chunk-S3IGX57D.js → chunk-BL3332HQ.js} +290 -7361
  50. package/dist/chunk-BL3332HQ.js.map +1 -0
  51. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  52. package/dist/chunk-D65GNPS3.js +12708 -0
  53. package/dist/chunk-D65GNPS3.js.map +1 -0
  54. package/dist/chunk-DOQGNFHM.js +121 -0
  55. package/dist/chunk-DOQGNFHM.js.map +1 -0
  56. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  57. package/dist/chunk-FW75G2W4.js +406 -0
  58. package/dist/chunk-FW75G2W4.js.map +1 -0
  59. package/dist/chunk-GA7JETVM.js +150 -0
  60. package/dist/chunk-GA7JETVM.js.map +1 -0
  61. package/dist/chunk-I3EQFHCD.js +175 -0
  62. package/dist/chunk-I3EQFHCD.js.map +1 -0
  63. package/dist/chunk-JKKAIPTU.js +108 -0
  64. package/dist/chunk-JKKAIPTU.js.map +1 -0
  65. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  66. package/dist/{chunk-NCE5NSN6.js → chunk-K3I7C2MO.js} +142 -12
  67. package/dist/chunk-K3I7C2MO.js.map +1 -0
  68. package/dist/chunk-K72RURN3.js +239 -0
  69. package/dist/chunk-K72RURN3.js.map +1 -0
  70. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  71. package/dist/chunk-KOGZDMHO.js +21 -0
  72. package/dist/chunk-KOGZDMHO.js.map +1 -0
  73. package/dist/chunk-KXQ4UIP7.js +228 -0
  74. package/dist/chunk-KXQ4UIP7.js.map +1 -0
  75. package/dist/chunk-KXVP2VKA.js +194 -0
  76. package/dist/chunk-KXVP2VKA.js.map +1 -0
  77. package/dist/chunk-LEFIX6RS.js +100 -0
  78. package/dist/chunk-LEFIX6RS.js.map +1 -0
  79. package/dist/chunk-LHHMV4GU.js +27 -0
  80. package/dist/chunk-LHHMV4GU.js.map +1 -0
  81. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  82. package/dist/chunk-MEFB5KHA.js.map +1 -0
  83. package/dist/chunk-MNXS2U45.js +1768 -0
  84. package/dist/chunk-MNXS2U45.js.map +1 -0
  85. package/dist/{chunk-UGX7YPX2.js → chunk-NEFNKLBE.js} +9 -11
  86. package/dist/{chunk-UGX7YPX2.js.map → chunk-NEFNKLBE.js.map} +1 -1
  87. package/dist/chunk-OHRR5OYM.js +63 -0
  88. package/dist/chunk-OHRR5OYM.js.map +1 -0
  89. package/dist/chunk-ORWL5BSN.js +269 -0
  90. package/dist/chunk-ORWL5BSN.js.map +1 -0
  91. package/dist/chunk-P4NH7OUK.js +398 -0
  92. package/dist/chunk-P4NH7OUK.js.map +1 -0
  93. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  94. package/dist/chunk-QSCPK4F5.js +145 -0
  95. package/dist/chunk-QSCPK4F5.js.map +1 -0
  96. package/dist/chunk-QXP3Z3JN.js +131 -0
  97. package/dist/chunk-QXP3Z3JN.js.map +1 -0
  98. package/dist/{chunk-XJIW7USF.js → chunk-R5LCN54M.js} +118 -9
  99. package/dist/chunk-R5LCN54M.js.map +1 -0
  100. package/dist/chunk-S4SAZ7OD.js +30 -0
  101. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  102. package/dist/chunk-SJLTEINJ.js +117 -0
  103. package/dist/chunk-SJLTEINJ.js.map +1 -0
  104. package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
  105. package/dist/chunk-UKY4CHNC.js +498 -0
  106. package/dist/chunk-UKY4CHNC.js.map +1 -0
  107. package/dist/chunk-UQUOVWBG.js +114 -0
  108. package/dist/chunk-UQUOVWBG.js.map +1 -0
  109. package/dist/chunk-V6BSF6OC.js +260 -0
  110. package/dist/chunk-V6BSF6OC.js.map +1 -0
  111. package/dist/chunk-WJXLQXJY.js +43 -0
  112. package/dist/chunk-WJXLQXJY.js.map +1 -0
  113. package/dist/chunk-WK7F3B2E.js +114 -0
  114. package/dist/chunk-WK7F3B2E.js.map +1 -0
  115. package/dist/chunk-XKESD27X.js +10 -0
  116. package/dist/chunk-XKESD27X.js.map +1 -0
  117. package/dist/chunk-XQJXNMSB.js +23 -0
  118. package/dist/chunk-XQJXNMSB.js.map +1 -0
  119. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  120. package/dist/chunk-Y527D4TV.js +56 -0
  121. package/dist/chunk-Y527D4TV.js.map +1 -0
  122. package/dist/chunk-YFPY4ONH.js +127 -0
  123. package/dist/chunk-YFPY4ONH.js.map +1 -0
  124. package/dist/{chunk-OYMYCW7J.js → chunk-YVFXE7RR.js} +606 -97
  125. package/dist/chunk-YVFXE7RR.js.map +1 -0
  126. package/dist/clack-EZ7TDWQU.js +19 -0
  127. package/dist/claude-cli-2YKABJJZ.js +31 -0
  128. package/dist/{cli-SBXI5AMS.js → cli-D5OE3URZ.js} +458 -218
  129. package/dist/cli-D5OE3URZ.js.map +1 -0
  130. package/dist/codex-event-PPNVRRDH.js +16 -0
  131. package/dist/codex-host-2RJOJW2B.js +28 -0
  132. package/dist/codex-install-UUZ6QMBQ.js +221 -0
  133. package/dist/codex-install-UUZ6QMBQ.js.map +1 -0
  134. package/dist/config-ZD4OB2DO.js +51 -0
  135. package/dist/dist-3LOO6M4U.js +2842 -0
  136. package/dist/dist-3LOO6M4U.js.map +1 -0
  137. package/dist/doctor-KBR34Q4B.js +601 -0
  138. package/dist/doctor-KBR34Q4B.js.map +1 -0
  139. package/dist/env-proxy-XL4P73MZ.js +15 -0
  140. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  141. package/dist/ethersCompat-Df4a6QIZ-THAVUGIJ.js.map +1 -0
  142. package/dist/fund-5ITKQGYF.js +372 -0
  143. package/dist/fund-5ITKQGYF.js.map +1 -0
  144. package/dist/hook-command-4TYCHHRL.js +39 -0
  145. package/dist/hook-command-4TYCHHRL.js.map +1 -0
  146. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  147. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +15 -0
  148. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  149. package/dist/hosts/claude/tenjin/hooks/hooks.json +224 -0
  150. package/dist/hosts/claude/tenjin/hooks/register.tsx +589 -0
  151. package/dist/hosts/claude/tenjin/types/index.d.ts +41 -0
  152. package/dist/hosts/codex/.agents/plugins/marketplace.json +20 -0
  153. package/dist/hosts/codex/tenjin/.codex-plugin/plugin.json +16 -0
  154. package/dist/hosts/codex/tenjin/.mcp.json +12 -0
  155. package/dist/hosts/codex/tenjin/hooks/hooks.json +52 -0
  156. package/dist/hosts-FWZOV26H.js +216 -0
  157. package/dist/hosts-FWZOV26H.js.map +1 -0
  158. package/dist/index.js +21 -2
  159. package/dist/index.js.map +1 -1
  160. package/dist/install-XWGE4Q7L.js +77 -0
  161. package/dist/install-XWGE4Q7L.js.map +1 -0
  162. package/dist/install-identity-K7EJIQFP.js +30 -0
  163. package/dist/install-identity-K7EJIQFP.js.map +1 -0
  164. package/dist/install-wallet-XQ6XFZV4.js +117 -0
  165. package/dist/install-wallet-XQ6XFZV4.js.map +1 -0
  166. package/dist/mcp-3LIJSSJB.js +13553 -0
  167. package/dist/mcp-3LIJSSJB.js.map +1 -0
  168. package/dist/package-ZKQFDWLE.js +37 -0
  169. package/dist/package-ZKQFDWLE.js.map +1 -0
  170. package/dist/paths-POPTXJO6.js +61 -0
  171. package/dist/paths-POPTXJO6.js.map +1 -0
  172. package/dist/pay-WHBERZ3W.js +55 -0
  173. package/dist/pay-WHBERZ3W.js.map +1 -0
  174. package/dist/payments-KVICEKD2.js +110 -0
  175. package/dist/payments-KVICEKD2.js.map +1 -0
  176. package/dist/plugin-registration-5TIA564H.js +54 -0
  177. package/dist/plugin-registration-5TIA564H.js.map +1 -0
  178. package/dist/redact-6W23GGJC.js +15 -0
  179. package/dist/redact-6W23GGJC.js.map +1 -0
  180. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  181. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  182. package/dist/send-7G7Y7DLN.js +228 -0
  183. package/dist/send-7G7Y7DLN.js.map +1 -0
  184. package/dist/status-OF7RH5HM.js +120 -0
  185. package/dist/status-OF7RH5HM.js.map +1 -0
  186. package/dist/status-line-XOUE6MPL.js +90 -0
  187. package/dist/status-line-XOUE6MPL.js.map +1 -0
  188. package/dist/uninstall-JXUAFNDB.js +158 -0
  189. package/dist/uninstall-JXUAFNDB.js.map +1 -0
  190. package/dist/update-ZKUERSO2.js +44 -0
  191. package/dist/update-ZKUERSO2.js.map +1 -0
  192. package/dist/usdc-OGOGEHV2.js +40 -0
  193. package/dist/usdc-OGOGEHV2.js.map +1 -0
  194. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-S3DA7DFW.js} +5 -5
  195. package/dist/viemAdapter-By13KInL-S3DA7DFW.js.map +1 -0
  196. package/dist/wallet-2HA6W4R4.js +43 -0
  197. package/dist/wallet-2HA6W4R4.js.map +1 -0
  198. package/dist/wallet-kdf-worker.mjs +980 -0
  199. package/docs/agent-permissions.md +196 -0
  200. package/docs/safety-model.md +59 -0
  201. package/docs/troubleshooting.md +13 -0
  202. package/package.json +28 -19
  203. package/LICENSE +0 -21
  204. package/dist/buy-EE6SEXP6.js +0 -1598
  205. package/dist/buy-EE6SEXP6.js.map +0 -1
  206. package/dist/candidate-ERMSYYQZ.js +0 -127
  207. package/dist/candidate-ERMSYYQZ.js.map +0 -1
  208. package/dist/chunk-3OV7E5G5.js +0 -18
  209. package/dist/chunk-3OV7E5G5.js.map +0 -1
  210. package/dist/chunk-4ONXEEQL.js +0 -152
  211. package/dist/chunk-4ONXEEQL.js.map +0 -1
  212. package/dist/chunk-662MSGZB.js +0 -286
  213. package/dist/chunk-662MSGZB.js.map +0 -1
  214. package/dist/chunk-7KUW4MJD.js +0 -59
  215. package/dist/chunk-7KUW4MJD.js.map +0 -1
  216. package/dist/chunk-AWPAWHNX.js +0 -333
  217. package/dist/chunk-AWPAWHNX.js.map +0 -1
  218. package/dist/chunk-DXTQ3CSI.js +0 -171
  219. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  220. package/dist/chunk-ESPNTPQ2.js +0 -207
  221. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  222. package/dist/chunk-FJPLRISB.js +0 -79
  223. package/dist/chunk-FJPLRISB.js.map +0 -1
  224. package/dist/chunk-GO75V3NZ.js +0 -160
  225. package/dist/chunk-GO75V3NZ.js.map +0 -1
  226. package/dist/chunk-JPHG2JW3.js +0 -96
  227. package/dist/chunk-JPHG2JW3.js.map +0 -1
  228. package/dist/chunk-NCE5NSN6.js.map +0 -1
  229. package/dist/chunk-OYMYCW7J.js.map +0 -1
  230. package/dist/chunk-RY4XKNV3.js +0 -140
  231. package/dist/chunk-RY4XKNV3.js.map +0 -1
  232. package/dist/chunk-S3IGX57D.js.map +0 -1
  233. package/dist/chunk-TLCMMYLY.js +0 -126
  234. package/dist/chunk-TLCMMYLY.js.map +0 -1
  235. package/dist/chunk-UO22YNY4.js +0 -69
  236. package/dist/chunk-UO22YNY4.js.map +0 -1
  237. package/dist/chunk-XHC6FCGZ.js +0 -261
  238. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  239. package/dist/chunk-XJIW7USF.js.map +0 -1
  240. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  241. package/dist/chunk-YN5SHIXQ.js +0 -126
  242. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  243. package/dist/chunk-Z52RA3NC.js +0 -137
  244. package/dist/chunk-Z52RA3NC.js.map +0 -1
  245. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  246. package/dist/cli-SBXI5AMS.js.map +0 -1
  247. package/dist/config-VELDKLHY.js +0 -21
  248. package/dist/doctor-T3KWNNP2.js +0 -20
  249. package/dist/inspect-LMKOXE4Y.js +0 -96
  250. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  251. package/dist/install-LEX3ENQ6.js +0 -387
  252. package/dist/install-LEX3ENQ6.js.map +0 -1
  253. package/dist/lookup-ZPN2Q67N.js +0 -129
  254. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  255. package/dist/outcome-N7TAK6WR.js +0 -66
  256. package/dist/outcome-N7TAK6WR.js.map +0 -1
  257. package/dist/publish-BKBQQAW4.js +0 -1478
  258. package/dist/publish-BKBQQAW4.js.map +0 -1
  259. package/dist/usdc-JIAJW4SV.js +0 -22
  260. package/dist/wallet-CWEMYVIH.js +0 -179
  261. package/dist/wallet-CWEMYVIH.js.map +0 -1
  262. package/dist/wallet-PA54CRBL.js +0 -30
  263. package/skills/tenjin/SKILL.md +0 -199
  264. package/skills/tenjin-publish/SKILL.md +0 -111
  265. package/skills/tenjin-search/SKILL.md +0 -133
  266. /package/dist/{_esm-FEASBWRP.js.map → _esm-MEXZI5DL.js.map} +0 -0
  267. /package/dist/{ccip-NQXCEK2U.js.map → alive-J64H46HI.js.map} +0 -0
  268. /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
  269. /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
  270. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  271. /package/dist/{chunk-CYOF7ROH.js.map → chunk-6E5R45ZO.js.map} +0 -0
  272. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  273. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  274. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  275. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  276. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  277. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  278. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  279. /package/dist/{doctor-T3KWNNP2.js.map → clack-EZ7TDWQU.js.map} +0 -0
  280. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → claude-cli-2YKABJJZ.js.map} +0 -0
  281. /package/dist/{secp256k1-N3ZHU7LB.js.map → codex-event-PPNVRRDH.js.map} +0 -0
  282. /package/dist/{usdc-JIAJW4SV.js.map → codex-host-2RJOJW2B.js.map} +0 -0
  283. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → config-ZD4OB2DO.js.map} +0 -0
  284. /package/dist/{wallet-PA54CRBL.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
@@ -1,25 +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
- readWalletRecord,
5
- walletFileMode,
6
- writeWalletRecord
7
- } from "./chunk-YN5SHIXQ.js";
8
- import {
9
- withFileLock
10
- } from "./chunk-YBMMV4Y4.js";
11
- import {
12
- evaluateSpendPolicy
13
- } from "./chunk-UO22YNY4.js";
14
- import {
15
- writeFileAtomic
16
- } from "./chunk-MUBUQVC3.js";
17
- import {
18
- CliError,
19
- external_exports,
20
- passphraseBlobPath,
21
- walletPath
22
- } from "./chunk-OYMYCW7J.js";
3
+ createLocalSpendAuthorizer
4
+ } from "./chunk-7ZRL2LBQ.js";
23
5
  import {
24
6
  hashAuthorization,
25
7
  hashMessage,
@@ -28,12 +10,7 @@ import {
28
10
  publicKeyToAddress,
29
11
  serializeSignature,
30
12
  serializeTransaction
31
- } from "./chunk-NCE5NSN6.js";
32
- import {
33
- hmac,
34
- secp256k1,
35
- sha256
36
- } from "./chunk-QVX5MWJZ.js";
13
+ } from "./chunk-K3I7C2MO.js";
37
14
  import {
38
15
  InvalidAddressError,
39
16
  concat3 as concat,
@@ -48,7 +25,12 @@ import {
48
25
  slice3 as slice,
49
26
  toHex,
50
27
  toHex2
51
- } from "./chunk-YALGASEU.js";
28
+ } from "./chunk-EGELTSPU.js";
29
+ import {
30
+ hmac,
31
+ secp256k1,
32
+ sha256
33
+ } from "./chunk-JRGFKVAZ.js";
52
34
  import {
53
35
  ahash,
54
36
  anumber,
@@ -60,7 +42,493 @@ import {
60
42
  rotl,
61
43
  swap32IfBE,
62
44
  u32
63
- } from "./chunk-5CLSD5YN.js";
45
+ } from "./chunk-BPMWXTFX.js";
46
+ import {
47
+ emitNotice
48
+ } from "./chunk-K72RURN3.js";
49
+ import {
50
+ hasCode
51
+ } from "./chunk-2I4QTOLB.js";
52
+ import {
53
+ external_exports
54
+ } from "./chunk-YVFXE7RR.js";
55
+ import {
56
+ CliError
57
+ } from "./chunk-3UCIG4TG.js";
58
+ import {
59
+ fsyncDir,
60
+ writeFileAtomic,
61
+ writeFileAtomicExclusive
62
+ } from "./chunk-7WEQQJLG.js";
63
+ import {
64
+ archivedWalletPath,
65
+ passphraseBlobPath,
66
+ passphraseBlobPathFor,
67
+ spendLedgerPath,
68
+ walletPath
69
+ } from "./chunk-SJLTEINJ.js";
70
+
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;
97
+ }
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;
104
+ }
105
+ }
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
+ });
117
+ }
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;
158
+ }
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 } : {}
164
+ });
165
+ }
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
+ }
179
+ }
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;
184
+ }
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;
189
+ }
190
+ function isNotFound(err) {
191
+ return hasCode(err, "ENOENT");
192
+ }
193
+
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);
223
+ }
224
+ });
225
+ }
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;
236
+ }
237
+ }
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
+ };
253
+ }
254
+ }
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();
261
+ }
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;
267
+ }
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";
276
+ }
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 };
286
+ }
287
+ }
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" };
303
+ }
304
+ throw noPassphraseError();
305
+ }
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";
64
532
 
65
533
  // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
66
534
  function pbkdf2Init(hash, _password, _salt, _opts) {
@@ -685,356 +1153,137 @@ function encrypt2(privateKey, key, options) {
685
1153
  kdf,
686
1154
  kdfparams,
687
1155
  mac: toHex2(mac).slice(2)
688
- },
689
- id,
690
- version: 3
691
- };
692
- }
693
- function pbkdf22(options) {
694
- const { iv, iterations = 262144, password } = options;
695
- const salt = options.salt ? from(options.salt) : random(32);
696
- const key = toHex2(pbkdf2(sha256, password, salt, { c: iterations, dkLen: 32 }));
697
- return defineKey(() => key, {
698
- iv,
699
- kdfparams: {
700
- c: iterations,
701
- dklen: 32,
702
- prf: "hmac-sha256",
703
- salt: toHex2(salt).slice(2)
704
- },
705
- kdf: "pbkdf2"
706
- });
707
- }
708
- async function scryptAsync2(options) {
709
- const { iv, n = 262144, password } = options;
710
- const p = 8;
711
- const r = 1;
712
- const salt = options.salt ? from(options.salt) : random(32);
713
- const key = toHex2(await scryptAsync(password, salt, { N: n, dkLen: 32, r, p }));
714
- return defineKey(() => key, {
715
- iv,
716
- kdfparams: {
717
- dklen: 32,
718
- n,
719
- p,
720
- r,
721
- salt: toHex2(salt).slice(2)
722
- },
723
- kdf: "scrypt"
724
- });
725
- }
726
- async function toKeyAsync(keystore, options) {
727
- const { crypto: crypto2 } = keystore;
728
- const { password } = options;
729
- const { cipherparams, kdf, kdfparams } = crypto2;
730
- const { iv } = cipherparams;
731
- const { c, n, p, r, salt } = kdfparams;
732
- const [key] = await (async () => {
733
- switch (kdf) {
734
- case "scrypt":
735
- return await scryptAsync2({
736
- iv: from(`0x${iv}`),
737
- n,
738
- p,
739
- r,
740
- salt: from(`0x${salt}`),
741
- password
742
- });
743
- case "pbkdf2":
744
- return await pbkdf22({
745
- iv: from(`0x${iv}`),
746
- iterations: c,
747
- password,
748
- salt: from(`0x${salt}`)
749
- });
750
- default:
751
- throw new Error("unsupported kdf");
752
- }
753
- })();
754
- return key;
755
- }
756
- function defineKey(key, options) {
757
- const iv = options.iv ? from(options.iv) : random(16);
758
- return [key, { ...options, iv }];
759
- }
760
-
761
- // src/lib/wallet/passphrase.ts
762
- import { execFile } from "child_process";
763
- import { randomBytes } from "crypto";
764
- import { readFile } from "fs/promises";
765
- var KEYCHAIN_SERVICE = "tenjin-cli";
766
- var KEYCHAIN_ACCOUNT = "wallet";
767
- var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
768
- var defaultExec = (file, args, stdin) => new Promise((resolve, reject) => {
769
- const child = execFile(file, args, { encoding: "utf8" }, (err, stdout, stderr) => {
770
- if (err) reject(err);
771
- else resolve({ stdout, stderr });
772
- });
773
- if (stdin !== void 0) {
774
- child.stdin?.on("error", () => void 0);
775
- child.stdin?.end(stdin);
776
- }
777
- });
778
- function storeFor(deps) {
779
- switch (deps.platform ?? process.platform) {
780
- case "darwin":
781
- return keychainStore(deps);
782
- case "win32":
783
- return dpapiStore(deps);
784
- case "linux":
785
- return secretServiceStore(deps);
786
- default:
787
- return null;
788
- }
789
- }
790
- async function resolvePassphrase(deps) {
791
- const fromEnv = envPassphrase(deps.env);
792
- if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
793
- const store = storeFor(deps);
794
- if (store !== null) {
795
- const fromStore = await store.read();
796
- if (fromStore !== null) return { passphrase: fromStore, source: store.source };
797
- }
798
- if (canPrompt(deps)) {
799
- const entered = await promptOf(deps)("Wallet passphrase: ");
800
- if (entered.length === 0) throw noPassphraseError();
801
- return { passphrase: entered, source: "prompt" };
802
- }
803
- throw noPassphraseError();
804
- }
805
- async function resolvePassphraseForCreate(deps) {
806
- const fromEnv = envPassphrase(deps.env);
807
- if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
808
- const store = storeFor(deps);
809
- if (store !== null) {
810
- const generated = randomBytes(32).toString("base64url");
811
- if (await store.store(generated)) {
812
- return { passphrase: generated, source: store.source };
813
- }
814
- }
815
- if (canPrompt(deps)) {
816
- const prompt = promptOf(deps);
817
- const first = await prompt("Set a wallet passphrase: ");
818
- if (first.length === 0) {
819
- throw new CliError("USAGE", "The wallet passphrase must not be empty.", {
820
- fix: "Enter a non-empty passphrase, or set TENJIN_WALLET_PASSPHRASE."
821
- });
822
- }
823
- const second = await prompt("Confirm passphrase: ");
824
- if (first !== second) {
825
- throw new CliError("USAGE", "The passphrases did not match.", {
826
- fix: "Run `tenjin wallet create` again and enter the same passphrase both times."
827
- });
828
- }
829
- return { passphrase: first, source: "prompt" };
830
- }
831
- throw noPassphraseError();
832
- }
833
- function keychainStore(deps) {
834
- const exec = deps.exec ?? defaultExec;
835
- return {
836
- source: "keychain",
837
- async read() {
838
- try {
839
- const { stdout } = await exec("security", [
840
- "find-generic-password",
841
- "-s",
842
- KEYCHAIN_SERVICE,
843
- "-a",
844
- KEYCHAIN_ACCOUNT,
845
- "-w"
846
- ]);
847
- return trimmedNonEmpty(stdout);
848
- } catch {
849
- return null;
850
- }
851
- },
852
- async store(passphrase) {
853
- if (!BASE64URL_RE.test(passphrase)) return false;
854
- try {
855
- const command = `add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${KEYCHAIN_ACCOUNT} -w '${passphrase}'
856
- `;
857
- await exec("security", ["-i"], command);
858
- return true;
859
- } catch {
860
- return false;
861
- }
862
- }
863
- };
864
- }
865
- var DPAPI_PROTECT_SCRIPT = [
866
- "Add-Type -AssemblyName System.Security;",
867
- "$in = [Console]::In.ReadToEnd();",
868
- "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in);",
869
- "$prot = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser');",
870
- "[Console]::Out.Write([Convert]::ToBase64String($prot));"
871
- ].join(" ");
872
- var DPAPI_UNPROTECT_SCRIPT = [
873
- "Add-Type -AssemblyName System.Security;",
874
- "$in = [Console]::In.ReadToEnd();",
875
- "$blob = [Convert]::FromBase64String($in.Trim());",
876
- "$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser');",
877
- "[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain));"
878
- ].join(" ");
879
- function powershellArgs(script) {
880
- return ["-NoProfile", "-NonInteractive", "-Command", script];
881
- }
882
- function dpapiStore(deps) {
883
- const exec = deps.exec ?? defaultExec;
884
- const blobPath = passphraseBlobPath(deps.dir);
885
- return {
886
- source: "dpapi",
887
- async read() {
888
- let blob;
889
- try {
890
- blob = await readFile(blobPath, "utf8");
891
- } catch {
892
- return null;
893
- }
894
- try {
895
- const { stdout } = await exec(
896
- "powershell.exe",
897
- powershellArgs(DPAPI_UNPROTECT_SCRIPT),
898
- blob
899
- );
900
- const passphrase = stdout.replace(/\r?\n$/, "");
901
- return passphrase.length > 0 ? passphrase : null;
902
- } catch {
903
- return null;
904
- }
905
- },
906
- async store(passphrase) {
907
- try {
908
- const { stdout } = await exec(
909
- "powershell.exe",
910
- powershellArgs(DPAPI_PROTECT_SCRIPT),
911
- passphrase
912
- );
913
- const blob = stdout.replace(/\r?\n$/, "").trim();
914
- if (blob.length === 0) return false;
915
- await writeFileAtomic(blobPath, blob, { mode: 384 });
916
- return true;
917
- } catch {
918
- return false;
919
- }
920
- }
921
- };
922
- }
923
- function secretServiceStore(deps) {
924
- const exec = deps.exec ?? defaultExec;
925
- return {
926
- source: "secret-service",
927
- async read() {
928
- try {
929
- const { stdout } = await exec("secret-tool", [
930
- "lookup",
931
- "service",
932
- KEYCHAIN_SERVICE,
933
- "account",
934
- KEYCHAIN_ACCOUNT
935
- ]);
936
- return trimmedNonEmpty(stdout);
937
- } catch {
938
- return null;
939
- }
940
- },
941
- async store(passphrase) {
942
- try {
943
- await exec(
944
- "secret-tool",
945
- [
946
- "store",
947
- "--label=tenjin-cli-wallet",
948
- "service",
949
- KEYCHAIN_SERVICE,
950
- "account",
951
- KEYCHAIN_ACCOUNT
952
- ],
953
- passphrase
954
- );
955
- return true;
956
- } catch {
957
- return false;
958
- }
959
- }
1156
+ },
1157
+ id,
1158
+ version: 3
960
1159
  };
961
1160
  }
962
- function trimmedNonEmpty(stdout) {
963
- const value = stdout.replace(/\r?\n$/, "");
964
- return value.length > 0 ? value : null;
965
- }
966
- function envPassphrase(env) {
967
- const value = env.TENJIN_WALLET_PASSPHRASE;
968
- 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
+ });
969
1175
  }
970
- function canPrompt(deps) {
971
- 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
+ });
972
1193
  }
973
- function promptOf(deps) {
974
- 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;
975
1223
  }
976
- function noPassphraseError() {
977
- return new CliError("USAGE", "No wallet passphrase is available.", {
978
- fix: "Set TENJIN_WALLET_PASSPHRASE (headless) or run in a terminal."
979
- });
1224
+ function defineKey(key, options) {
1225
+ const iv = options.iv ? from(options.iv) : random(16);
1226
+ return [key, { ...options, iv }];
980
1227
  }
981
- var CTRL_C = 3;
982
- var CTRL_D = 4;
983
- var BACKSPACE = 127;
984
- var BACKSPACE_ALT = 8;
985
- 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
+ );
986
1240
  return new Promise((resolve, reject) => {
987
- const stdin = process.stdin;
988
- const stderr = process.stderr;
989
- const wasRaw = stdin.isRaw;
990
- let value = "";
991
- const cleanup = () => {
992
- stdin.setRawMode?.(wasRaw ?? false);
993
- stdin.pause();
994
- stdin.removeListener("data", onData);
995
- };
996
- const onData = (chunk) => {
997
- for (const ch of chunk.toString("utf8")) {
998
- const code = ch.charCodeAt(0);
999
- if (ch === "\n" || ch === "\r" || code === CTRL_D) {
1000
- cleanup();
1001
- stderr.write("\n");
1002
- resolve(value);
1003
- return;
1004
- }
1005
- if (code === CTRL_C) {
1006
- cleanup();
1007
- stderr.write("\n");
1008
- reject(
1009
- new CliError("USAGE", "Passphrase entry was cancelled.", {
1010
- fix: "Run the command again, or set TENJIN_WALLET_PASSPHRASE."
1011
- })
1012
- );
1013
- return;
1014
- }
1015
- if (code === BACKSPACE || code === BACKSPACE_ALT) {
1016
- value = value.slice(0, -1);
1017
- } else {
1018
- value += ch;
1019
- }
1020
- }
1021
- };
1022
- stderr.write(label);
1023
- stdin.setRawMode?.(true);
1024
- stdin.resume();
1025
- 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();
1026
1266
  });
1027
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
+ }
1028
1276
 
1029
1277
  // src/lib/wallet/local.ts
1030
1278
  var isWindows = process.platform === "win32";
1031
1279
  var KEY_STORAGE = "encrypted (keystore v3, scrypt)";
1280
+ var STORE_READ_TIMEOUT_MS = 5e3;
1032
1281
  var signerCache = /* @__PURE__ */ new Map();
1033
1282
  function createLocalProvider(deps) {
1034
1283
  return {
1035
1284
  id: "local",
1036
1285
  async describe() {
1037
- const cred = resolveCredentialOrThrow(await loadCredential(deps));
1286
+ const cred = await credentialOrThrow(deps);
1038
1287
  return {
1039
1288
  // A file credential's address is stored cleartext and returned as-is —
1040
1289
  // no decryption. An env credential derives (and thereby validates) its
@@ -1046,19 +1295,92 @@ function createLocalProvider(deps) {
1046
1295
  };
1047
1296
  },
1048
1297
  async getSigner() {
1049
- const cred = resolveCredentialOrThrow(await loadCredential(deps));
1298
+ const cred = await credentialOrThrow(deps);
1050
1299
  const account = await accountForSigning(cred, deps);
1051
1300
  return {
1052
1301
  address: account.address,
1053
1302
  signMessage: (args) => account.signMessage({ message: args.message }),
1054
- signTypedData: (args) => account.signTypedData(args)
1303
+ signTypedData: (args) => account.signTypedData(args),
1304
+ signTransaction: (tx) => account.signTransaction(tx)
1055
1305
  };
1056
1306
  },
1057
1307
  diagnostics() {
1058
1308
  return localWalletDiagnostics(deps);
1309
+ },
1310
+ verify() {
1311
+ return verifyLocalWallet(deps);
1312
+ }
1313
+ };
1314
+ }
1315
+ async function verifyLocalWallet(deps) {
1316
+ const cred = await loadCredential(deps);
1317
+ if (cred === null) return { status: "unverified", detail: "there is no credential to verify" };
1318
+ if (cred.source === "env") {
1319
+ accountFromKey(cred.key, "env");
1320
+ return { status: "verified", detail: "TENJIN_WALLET_KEY derives a valid signing key" };
1321
+ }
1322
+ const account = walletStoreAccount(cred.address);
1323
+ let resolved;
1324
+ try {
1325
+ resolved = await resolvePassphrase(
1326
+ {
1327
+ env: deps.env,
1328
+ dir: deps.dir,
1329
+ ...deps.passphrase,
1330
+ isTTY: false,
1331
+ timeoutMs: STORE_READ_TIMEOUT_MS
1332
+ },
1333
+ cred.address
1334
+ );
1335
+ } catch {
1336
+ return {
1337
+ status: "unverified",
1338
+ detail: "no passphrase is reachable without prompting, so the keystore was not opened"
1339
+ };
1340
+ }
1341
+ let key;
1342
+ try {
1343
+ const derived = await deriveKeystoreKey(cred.keystore, resolved.passphrase, deps.derivation);
1344
+ key = decrypt(cred.keystore, derived);
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
+ }
1349
+ if (resolved.migrateLegacy !== void 0) {
1350
+ return {
1351
+ status: "broken",
1352
+ detail: `the keystore cannot be decrypted: the only stored passphrase is ${legacyOrigin(resolved.source)}, which does not open it`,
1353
+ fix: `That passphrase likely belongs to a wallet created later. Set TENJIN_WALLET_PASSPHRASE to this wallet's own passphrase, or restore ${passphraseOrigin(resolved.source, account)}.`
1354
+ };
1059
1355
  }
1356
+ const escape = resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not open it; set it to the correct passphrase" : `The passphrase from ${passphraseOrigin(resolved.source, account)} does not open it; set TENJIN_WALLET_PASSPHRASE to the correct passphrase`;
1357
+ return {
1358
+ status: "broken",
1359
+ detail: `the keystore cannot be decrypted with the passphrase from ${passphraseOrigin(resolved.source, account)}`,
1360
+ fix: `${escape}. Without it the key is unrecoverable and this address can no longer sign or publish.`
1361
+ };
1362
+ }
1363
+ if (privateKeyToAccount(key).address.toLowerCase() !== account) {
1364
+ return {
1365
+ status: "broken",
1366
+ detail: `the decrypted key does not derive the wallet file's stored address ${cred.address}`,
1367
+ fix: "The wallet file may be tampered. Move it aside, then run `tenjin wallet create` for a fresh key or set TENJIN_WALLET_KEY to use the intended one."
1368
+ };
1369
+ }
1370
+ return {
1371
+ status: "verified",
1372
+ detail: `keystore decrypts with the passphrase from ${passphraseOrigin(resolved.source, account)}`
1060
1373
  };
1061
1374
  }
1375
+ function passphraseOrigin(source, account) {
1376
+ if (source === "env") return "TENJIN_WALLET_PASSPHRASE";
1377
+ if (source === "prompt") return "the prompt";
1378
+ if (source === "dpapi") return `the DPAPI-protected passphrase file for ${account}`;
1379
+ return `the OS credential store (service tenjin-cli, account ${account})`;
1380
+ }
1381
+ function legacyOrigin(source) {
1382
+ return source === "dpapi" ? "the legacy shared DPAPI passphrase file (passphrase.dpapi)" : 'the legacy shared entry (service tenjin-cli, account "wallet")';
1383
+ }
1062
1384
  async function localWalletDiagnostics(deps) {
1063
1385
  const mode = await walletFileMode(deps.dir);
1064
1386
  const fileExists = mode !== null;
@@ -1079,18 +1401,133 @@ async function localWalletDiagnostics(deps) {
1079
1401
  }
1080
1402
  }
1081
1403
  const passphraseSource = deps.env.TENJIN_WALLET_PASSPHRASE !== void 0 && deps.env.TENJIN_WALLET_PASSPHRASE.length > 0 ? "TENJIN_WALLET_PASSPHRASE" : void 0;
1404
+ const archivedWallets = await listArchivedWallets(deps.dir);
1082
1405
  return {
1083
1406
  ...fileExists ? { walletPath: path, keyStorage: KEY_STORAGE } : {},
1084
1407
  ...fileExists && passphraseSource !== void 0 ? { passphraseSource } : {},
1408
+ ...archivedWallets.length > 0 ? { archivedWallets } : {},
1085
1409
  warnings
1086
1410
  };
1087
1411
  }
1088
- async function createLocalWallet(dir, passphrase) {
1412
+ var ARCHIVED_WALLET_RE = /^wallet\.(0x[0-9a-f]{40})\.json\.bak$/;
1413
+ async function listArchivedWallets(dir) {
1414
+ let names;
1415
+ try {
1416
+ names = await readdir(dir);
1417
+ } catch {
1418
+ return [];
1419
+ }
1420
+ return names.map((name) => ARCHIVED_WALLET_RE.exec(name)?.[1]).filter((address) => address !== void 0).sort();
1421
+ }
1422
+ async function prepareLocalWallet(passphrase) {
1089
1423
  const key = generatePrivateKey();
1090
1424
  const address = privateKeyToAccount(key).address;
1091
- const keystore = await encryptToKeystore(key, passphrase);
1092
- await writeWalletRecord(dir, walletRecord(address, keystore));
1093
- return { address, walletPath: walletPath(dir) };
1425
+ const resolved = typeof passphrase === "string" ? passphrase : await passphrase(address);
1426
+ const keystore = await encryptToKeystore(key, resolved);
1427
+ return { address, record: walletRecord(address, keystore) };
1428
+ }
1429
+ async function commitLocalWallet(dir, prepared) {
1430
+ await writeWalletRecord(dir, prepared.record);
1431
+ return { address: prepared.address, walletPath: walletPath(dir) };
1432
+ }
1433
+ async function createLocalWallet(dir, passphrase) {
1434
+ return commitLocalWallet(dir, await prepareLocalWallet(passphrase));
1435
+ }
1436
+ async function verifyAndPreserveOutgoingWallet(deps) {
1437
+ const record = await readWalletRecord(deps.dir);
1438
+ if (record === null) {
1439
+ throw new CliError("WALLET_MISSING", "No wallet found to archive.", {
1440
+ fix: "Run `tenjin wallet create` without --replace."
1441
+ });
1442
+ }
1443
+ const address = record.address;
1444
+ const account = walletStoreAccount(address);
1445
+ const passphraseDeps = { env: deps.env, dir: deps.dir, ...deps.passphrase };
1446
+ const resolved = await resolvePassphrase(passphraseDeps, address);
1447
+ let key;
1448
+ try {
1449
+ const derived = await toKeyAsync(record.keystore, { password: resolved.passphrase });
1450
+ key = decrypt(record.keystore, derived);
1451
+ } catch (err) {
1452
+ const escape = resolved.source === "prompt" ? "Retry and enter that wallet's correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it" : resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase" : `Set TENJIN_WALLET_PASSPHRASE to its passphrase, or fix its OS credential store entry (service tenjin-cli, account ${account})`;
1453
+ throw new CliError(
1454
+ "REFUSED",
1455
+ `Cannot verify the passphrase of the existing wallet ${address}; --replace refused.`,
1456
+ {
1457
+ fix: `Replacing now could strand that wallet's funds. ${escape}, then retry.`,
1458
+ cause: err
1459
+ }
1460
+ );
1461
+ }
1462
+ if (privateKeyToAccount(key).address.toLowerCase() !== account) {
1463
+ throw new CliError(
1464
+ "REFUSED",
1465
+ `The wallet file's stored address ${address} does not match its key; --replace refused.`,
1466
+ { fix: "The wallet file may be tampered. Resolve that before replacing it." }
1467
+ );
1468
+ }
1469
+ if (resolved.source === "env") {
1470
+ return { address, account, passphraseLocation: "env" };
1471
+ }
1472
+ if (resolved.migrateLegacy !== void 0) {
1473
+ if (!await resolved.migrateLegacy()) {
1474
+ throw new CliError(
1475
+ "REFUSED",
1476
+ `Could not archive the existing wallet's passphrase under its own address; --replace refused.`,
1477
+ {
1478
+ fix: `The passphrase currently lives only in the legacy shared slot (service tenjin-cli, account "wallet"), and copying it to account ${account} failed. Retry, or check OS credential store access.`
1479
+ }
1480
+ );
1481
+ }
1482
+ return { address, account, passphraseLocation: "store" };
1483
+ }
1484
+ if (resolved.source === "prompt") {
1485
+ const outcome = await storePassphraseForWallet(passphraseDeps, address, resolved.passphrase);
1486
+ return outcome === "stored" ? { address, account, passphraseLocation: "store" } : { address, account, passphraseLocation: "unarchived", unarchivedReason: outcome };
1487
+ }
1488
+ return { address, account, passphraseLocation: "store" };
1489
+ }
1490
+ async function parkOutgoingWallet(dir, account) {
1491
+ const src = walletPath(dir);
1492
+ const dst = archivedWalletPath(account, dir);
1493
+ try {
1494
+ await link(src, dst);
1495
+ } catch (err) {
1496
+ if (hasCode(err, "EEXIST")) {
1497
+ throw new CliError("REFUSED", `An archived wallet already exists at ${dst}.`, {
1498
+ fix: `Move ${dst} aside, then retry \`tenjin wallet create --replace\`. Nothing has moved; the current wallet is still active.`,
1499
+ cause: err
1500
+ });
1501
+ }
1502
+ throw new CliError("INTERNAL", `Could not park the outgoing keystore at ${dst}.`, {
1503
+ fix: `Nothing has moved; the current wallet is still active at ${src}. Fix the underlying filesystem error and retry.`,
1504
+ cause: err
1505
+ });
1506
+ }
1507
+ try {
1508
+ await unlink2(src);
1509
+ } catch (err) {
1510
+ await unlink2(dst).catch(() => void 0);
1511
+ throw new CliError(
1512
+ "INTERNAL",
1513
+ `Could not clear the active wallet slot ${src} while parking the outgoing wallet.`,
1514
+ {
1515
+ fix: "The previous wallet is still active and nothing was lost. Fix the underlying filesystem error (on Windows, close any process holding the wallet file open) and retry.",
1516
+ cause: err
1517
+ }
1518
+ );
1519
+ }
1520
+ await syncWalletDir(dir);
1521
+ return dst;
1522
+ }
1523
+ async function restoreParkedWallet(dir, archivedPath) {
1524
+ await link(archivedPath, walletPath(dir));
1525
+ await unlink2(archivedPath).catch(() => void 0);
1526
+ await syncWalletDir(dir);
1527
+ }
1528
+ async function syncWalletDir(dir) {
1529
+ if (isWindows) return;
1530
+ await fsyncDir(dir);
1094
1531
  }
1095
1532
  async function loadCredential(deps) {
1096
1533
  const envKey = deps.env.TENJIN_WALLET_KEY;
@@ -1113,18 +1550,33 @@ async function accountForSigning(cred, deps) {
1113
1550
  if (cred.source === "env") return accountFromKey(cred.key, "env");
1114
1551
  const cached = signerCache.get(cred.keystore.id);
1115
1552
  if (cached !== void 0) return cached;
1116
- const { passphrase } = await resolvePassphrase({
1117
- env: deps.env,
1118
- dir: deps.dir,
1119
- ...deps.passphrase
1120
- });
1553
+ const resolved = await resolvePassphrase(
1554
+ {
1555
+ env: deps.env,
1556
+ dir: deps.dir,
1557
+ ...deps.passphrase
1558
+ },
1559
+ cred.address
1560
+ );
1121
1561
  let key;
1122
1562
  try {
1123
- const derived = await toKeyAsync(cred.keystore, { password: passphrase });
1563
+ const derived = await deriveKeystoreKey(cred.keystore, resolved.passphrase, deps.derivation);
1124
1564
  key = decrypt(cred.keystore, derived);
1125
1565
  } catch (err) {
1566
+ if (err instanceof Error && ["AbortError", "TimeoutError"].includes(err.name)) throw err;
1567
+ if (resolved.migrateLegacy !== void 0) {
1568
+ throw new CliError(
1569
+ "WALLET_INVALID_KEY",
1570
+ 'The legacy shared passphrase entry (service tenjin-cli, account "wallet") does not decrypt this wallet.',
1571
+ {
1572
+ fix: "That entry likely belongs to a different wallet created later and was left untouched. If you know this wallet's passphrase, set TENJIN_WALLET_PASSPHRASE to it (a store-served passphrase is never re-asked at a prompt).",
1573
+ cause: err
1574
+ }
1575
+ );
1576
+ }
1577
+ const escape = resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase" : resolved.source === "prompt" ? "Retry and enter the correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it" : `The OS credential store entry (service tenjin-cli, account ${cred.address.toLowerCase()}) does not decrypt it; set TENJIN_WALLET_PASSPHRASE to the correct passphrase`;
1126
1578
  throw new CliError("WALLET_INVALID_KEY", "Could not decrypt the wallet keystore.", {
1127
- fix: "Check the passphrase: TENJIN_WALLET_PASSPHRASE, the macOS keychain (service tenjin-cli), or the one you enter when prompted.",
1579
+ fix: `${escape}.`,
1128
1580
  cause: err
1129
1581
  });
1130
1582
  }
@@ -1138,6 +1590,7 @@ async function accountForSigning(cred, deps) {
1138
1590
  }
1139
1591
  );
1140
1592
  }
1593
+ if (resolved.migrateLegacy !== void 0) await resolved.migrateLegacy();
1141
1594
  signerCache.set(cred.keystore.id, account);
1142
1595
  return account;
1143
1596
  }
@@ -1155,17 +1608,18 @@ async function encryptToKeystore(key, passphrase) {
1155
1608
  const [derivedKey, opts] = await scryptAsync2({ password: passphrase });
1156
1609
  return encrypt2(key, derivedKey, opts);
1157
1610
  }
1158
- function resolveCredentialOrThrow(cred) {
1159
- if (cred === null) {
1160
- throw new CliError("WALLET_MISSING", "No wallet found.", {
1161
- fix: "Run `tenjin wallet create` to create one."
1162
- });
1163
- }
1164
- return cred;
1611
+ async function credentialOrThrow(deps) {
1612
+ const cred = await loadCredential(deps);
1613
+ if (cred !== null) return cred;
1614
+ const archived = await listArchivedWallets(deps.dir);
1615
+ const hint = archived.length > 0 ? ` Archived wallets exist (${archived.join(", ")}); restore one with \`mv ${archivedWalletPath("<address>", deps.dir)} ${walletPath(deps.dir)}\`.` : "";
1616
+ throw new CliError("WALLET_MISSING", "No wallet found.", {
1617
+ fix: `Run \`tenjin wallet create\` to create one.${hint}`
1618
+ });
1165
1619
  }
1166
1620
  function walletRecord(address, keystore) {
1167
1621
  return {
1168
- schemaVersion: 2,
1622
+ schemaVersion: WALLET_SCHEMA_VERSION,
1169
1623
  provider: "local",
1170
1624
  address,
1171
1625
  keystore,
@@ -1173,133 +1627,26 @@ function walletRecord(address, keystore) {
1173
1627
  };
1174
1628
  }
1175
1629
 
1176
- // src/lib/wallet/spend.ts
1177
- import { mkdir, readFile as readFile2 } from "fs/promises";
1178
- import { randomUUID } from "crypto";
1179
- import { join } from "path";
1180
- var DEFAULT_WINDOW_MS = 864e5;
1181
- var RESERVATION_TTL_MS = 6e5;
1182
- var ReservationSchema = external_exports.object({
1183
- id: external_exports.string(),
1184
- amountAtomic: external_exports.string().regex(/^\d+$/),
1185
- atMs: external_exports.number()
1186
- });
1187
- var LedgerSchema = external_exports.object({
1188
- schemaVersion: external_exports.literal(2),
1189
- windowStartMs: external_exports.number(),
1190
- committedAtomic: external_exports.string().regex(/^\d+$/),
1191
- reservations: external_exports.array(ReservationSchema)
1192
- });
1193
- function emptyLedger(nowMs) {
1194
- return { schemaVersion: 2, windowStartMs: nowMs, committedAtomic: "0", reservations: [] };
1195
- }
1196
- function createLocalSpendAuthorizer(deps) {
1197
- const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;
1198
- const now = deps.now ?? Date.now;
1199
- const path = join(deps.dir, "session.json");
1200
- const lockPath = `${path}.lock`;
1201
- const freshen = (ledger, nowMs) => {
1202
- if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);
1203
- return {
1204
- ...ledger,
1205
- reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS)
1206
- };
1207
- };
1208
- const spentOf = (ledger) => ledger.reservations.reduce(
1209
- (sum, r) => sum + BigInt(r.amountAtomic),
1210
- BigInt(ledger.committedAtomic)
1211
- );
1212
- const persist = async (ledger) => {
1213
- await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}
1214
- `, {
1215
- mode: 384,
1216
- dirMode: 448
1217
- });
1218
- };
1219
- async function withLedger(fn) {
1220
- await mkdir(deps.dir, { recursive: true, mode: 448 });
1221
- return withFileLock(lockPath, async () => {
1222
- const nowMs = now();
1223
- const ledger = freshen(await readLedger(path), nowMs);
1224
- return fn(ledger, nowMs);
1225
- });
1226
- }
1227
- return {
1228
- policyEnforcement: "client-only",
1229
- async authorize(req) {
1230
- return withLedger(async (ledger) => {
1231
- const sessionSpentAtomic = spentOf(ledger);
1232
- const evaluation = evaluateSpendPolicy(deps.policy, {
1233
- amountAtomic: req.amountAtomic,
1234
- creator: req.creator,
1235
- ...req.maxPriceAtomic !== void 0 ? { maxPriceAtomic: req.maxPriceAtomic } : {},
1236
- sessionSpentAtomic
1237
- });
1238
- const base = {
1239
- ...evaluation,
1240
- amountAtomic: req.amountAtomic,
1241
- sessionSpentAtomic,
1242
- sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,
1243
- policyEnforcement: "client-only"
1244
- };
1245
- if (evaluation.decision === "deny" || deps.policy.sessionBudgetAtomic === 0n) {
1246
- return base;
1247
- }
1248
- const reservation = {
1249
- id: randomUUID(),
1250
- amountAtomic: req.amountAtomic.toString(),
1251
- atMs: now()
1252
- };
1253
- await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });
1254
- return { ...base, reservationId: reservation.id };
1255
- });
1256
- },
1257
- async commit(reservationId, amountAtomic) {
1258
- await withLedger(async (ledger) => {
1259
- const reservation = reservationId !== void 0 ? ledger.reservations.find((r) => r.id === reservationId) : void 0;
1260
- const settled = reservation !== void 0 ? BigInt(reservation.amountAtomic) : amountAtomic;
1261
- await persist({
1262
- ...ledger,
1263
- committedAtomic: (BigInt(ledger.committedAtomic) + settled).toString(),
1264
- reservations: reservationId !== void 0 ? ledger.reservations.filter((r) => r.id !== reservationId) : ledger.reservations
1265
- });
1266
- });
1267
- },
1268
- async release(reservationId) {
1269
- if (reservationId === void 0) return;
1270
- await withLedger(async (ledger) => {
1271
- if (!ledger.reservations.some((r) => r.id === reservationId)) return;
1272
- await persist({
1273
- ...ledger,
1274
- reservations: ledger.reservations.filter((r) => r.id !== reservationId)
1275
- });
1276
- });
1277
- }
1278
- };
1279
- }
1280
- async function readLedger(path) {
1281
- let raw;
1282
- try {
1283
- raw = await readFile2(path, "utf8");
1284
- } catch {
1285
- return null;
1286
- }
1287
- try {
1288
- const parsed = LedgerSchema.safeParse(JSON.parse(raw));
1289
- return parsed.success ? parsed.data : null;
1290
- } catch {
1291
- return null;
1292
- }
1293
- }
1294
-
1295
1630
  // src/lib/wallet/index.ts
1296
1631
  function resolveWalletProvider(ctx, opts = {}) {
1297
1632
  if (opts.provider !== void 0) return opts.provider;
1298
- return createLocalProvider({ dir: ctx.dataDir, env: process.env });
1633
+ return createLocalProvider({
1634
+ dir: ctx.dataDir,
1635
+ env: process.env,
1636
+ passphrase: { ...opts.passphrase, isTTY: ctx.io.isTTY ? void 0 : false }
1637
+ });
1299
1638
  }
1300
1639
  function resolveSpendAuthorizer(ctx, policy, opts = {}) {
1301
1640
  if (opts.authorizer !== void 0) return opts.authorizer;
1302
- return createLocalSpendAuthorizer({ dir: ctx.dataDir, policy });
1641
+ return createLocalSpendAuthorizer({
1642
+ dir: ctx.dataDir,
1643
+ policy,
1644
+ onCorrupt: (reason) => emitNotice(
1645
+ ctx.io,
1646
+ `spend ledger at ${spendLedgerPath(ctx.dataDir)} was unreadable (${reason}); spending window restarted`,
1647
+ { json: ctx.flags.json }
1648
+ )
1649
+ });
1303
1650
  }
1304
1651
  async function describeWallet(provider) {
1305
1652
  try {
@@ -1315,9 +1662,15 @@ async function describeWallet(provider) {
1315
1662
  }
1316
1663
 
1317
1664
  export {
1665
+ walletFileExists,
1666
+ walletExistsError,
1318
1667
  resolvePassphraseForCreate,
1668
+ prepareLocalWallet,
1669
+ commitLocalWallet,
1319
1670
  createLocalWallet,
1320
- createLocalSpendAuthorizer,
1671
+ verifyAndPreserveOutgoingWallet,
1672
+ parkOutgoingWallet,
1673
+ restoreParkedWallet,
1321
1674
  resolveWalletProvider,
1322
1675
  resolveSpendAuthorizer,
1323
1676
  describeWallet
@@ -1327,4 +1680,4 @@ export {
1327
1680
  @noble/ciphers/esm/utils.js:
1328
1681
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1329
1682
  */
1330
- //# sourceMappingURL=chunk-Z6MFJV5Z.js.map
1683
+ //# sourceMappingURL=chunk-2XLC3AEX.js.map