tenjin-cli 0.1.0-alpha.30 → 0.1.0-alpha.32

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 (280) hide show
  1. package/README.md +65 -116
  2. package/dist/{_esm-CE7KNONL.js → _esm-RLLC72MS.js} +127 -131
  3. package/dist/alive-MROUMFH3.js +38 -0
  4. package/dist/auto-update-OPWMRZLS.js +22 -0
  5. package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
  6. package/dist/chunk-2GNOFONN.js +560 -0
  7. package/dist/chunk-2GNOFONN.js.map +1 -0
  8. package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
  9. package/dist/chunk-2GP3HRYK.js.map +1 -0
  10. package/dist/chunk-3623BLPV.js +184 -0
  11. package/dist/chunk-3623BLPV.js.map +1 -0
  12. package/dist/chunk-3AIHRXKO.js +72 -0
  13. package/dist/chunk-3AIHRXKO.js.map +1 -0
  14. package/dist/chunk-3DIL66VX.js +120 -0
  15. package/dist/chunk-3DIL66VX.js.map +1 -0
  16. package/dist/{chunk-S4SAZ7OD.js → chunk-3FMZGI7I.js} +12 -2
  17. package/dist/{chunk-S4SAZ7OD.js.map → chunk-3FMZGI7I.js.map} +1 -1
  18. package/dist/chunk-3UCIG4TG.js +65 -0
  19. package/dist/chunk-3UCIG4TG.js.map +1 -0
  20. package/dist/{chunk-LFZJM56J.js → chunk-445VQTVM.js} +3 -3
  21. package/dist/{chunk-A36LQPHV.js → chunk-4LMUQMBH.js} +1 -1
  22. package/dist/{chunk-A36LQPHV.js.map → chunk-4LMUQMBH.js.map} +1 -1
  23. package/dist/{chunk-RAULEAZ6.js → chunk-4USCZ2NI.js} +3 -3
  24. package/dist/chunk-62KNUYWD.js +111 -0
  25. package/dist/chunk-62KNUYWD.js.map +1 -0
  26. package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
  27. package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
  28. package/dist/chunk-7WEQQJLG.js +68 -0
  29. package/dist/chunk-7WEQQJLG.js.map +1 -0
  30. package/dist/{chunk-3O2BQIF6.js → chunk-AD226HDR.js} +344 -534
  31. package/dist/chunk-AD226HDR.js.map +1 -0
  32. package/dist/chunk-ADV4LDTB.js +106 -0
  33. package/dist/chunk-ADV4LDTB.js.map +1 -0
  34. package/dist/{chunk-AWFUPKTM.js → chunk-AV5NZMYO.js} +15 -7
  35. package/dist/{chunk-AWFUPKTM.js.map → chunk-AV5NZMYO.js.map} +1 -1
  36. package/dist/chunk-B7EM4GGF.js +198 -0
  37. package/dist/chunk-B7EM4GGF.js.map +1 -0
  38. package/dist/chunk-BFDQ4WNW.js +119 -0
  39. package/dist/chunk-BFDQ4WNW.js.map +1 -0
  40. package/dist/{chunk-OSYTBCUC.js → chunk-BI673VEJ.js} +531 -503
  41. package/dist/chunk-BI673VEJ.js.map +1 -0
  42. package/dist/chunk-CEXSOI5R.js +808 -0
  43. package/dist/chunk-CEXSOI5R.js.map +1 -0
  44. package/dist/{chunk-OK2TDZQU.js → chunk-CISYM4EO.js} +9 -7
  45. package/dist/chunk-CISYM4EO.js.map +1 -0
  46. package/dist/{chunk-VFMQTSXG.js → chunk-D3ZURCG7.js} +3 -3
  47. package/dist/chunk-D5TOQSO4.js +474 -0
  48. package/dist/chunk-D5TOQSO4.js.map +1 -0
  49. package/dist/{chunk-P7LABKCW.js → chunk-DOQGNFHM.js} +33 -2
  50. package/dist/{chunk-P7LABKCW.js.map → chunk-DOQGNFHM.js.map} +1 -1
  51. package/dist/{chunk-QUVVWYJW.js → chunk-DRDUIZIA.js} +11 -9
  52. package/dist/{chunk-QUVVWYJW.js.map → chunk-DRDUIZIA.js.map} +1 -1
  53. package/dist/{chunk-O2FRQ2L2.js → chunk-DW4YTVR3.js} +5 -65
  54. package/dist/chunk-DW4YTVR3.js.map +1 -0
  55. package/dist/chunk-E7LGOMH6.js +449 -0
  56. package/dist/chunk-E7LGOMH6.js.map +1 -0
  57. package/dist/chunk-E7SW44LM.js +138 -0
  58. package/dist/chunk-E7SW44LM.js.map +1 -0
  59. package/dist/chunk-EDJWHDDL.js +33 -0
  60. package/dist/chunk-EDJWHDDL.js.map +1 -0
  61. package/dist/chunk-F3ED5WTR.js +13 -0
  62. package/dist/chunk-F3ED5WTR.js.map +1 -0
  63. package/dist/chunk-G75OPGAK.js +111 -0
  64. package/dist/chunk-G75OPGAK.js.map +1 -0
  65. package/dist/{chunk-YFQOA5AU.js → chunk-GAKUQHKA.js} +13 -17
  66. package/dist/{chunk-YFQOA5AU.js.map → chunk-GAKUQHKA.js.map} +1 -1
  67. package/dist/{chunk-PAYV4XUA.js → chunk-HDPUXS3Z.js} +20 -49
  68. package/dist/chunk-HDPUXS3Z.js.map +1 -0
  69. package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
  70. package/dist/{chunk-HPWO4O6S.js → chunk-HREHWL32.js} +4 -4
  71. package/dist/{chunk-HPWO4O6S.js.map → chunk-HREHWL32.js.map} +1 -1
  72. package/dist/{chunk-VZGAONSJ.js → chunk-I5TDIUKM.js} +16 -35
  73. package/dist/chunk-I5TDIUKM.js.map +1 -0
  74. package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
  75. package/dist/chunk-IADZOXKN.js.map +1 -0
  76. package/dist/{chunk-U6YQ6FRI.js → chunk-IDTRSAHE.js} +32 -12
  77. package/dist/chunk-IDTRSAHE.js.map +1 -0
  78. package/dist/{chunk-SPAVAYSW.js → chunk-JEVQ5LKO.js} +7 -5
  79. package/dist/{chunk-SPAVAYSW.js.map → chunk-JEVQ5LKO.js.map} +1 -1
  80. package/dist/{chunk-EBVIKMCH.js → chunk-JKKAIPTU.js} +2 -2
  81. package/dist/chunk-JNJWBTU2.js +3497 -0
  82. package/dist/chunk-JNJWBTU2.js.map +1 -0
  83. package/dist/{chunk-TTBKWWTV.js → chunk-JRZBBPO6.js} +390 -146
  84. package/dist/chunk-JRZBBPO6.js.map +1 -0
  85. package/dist/{chunk-WVUSXNIE.js → chunk-MPZUYCAP.js} +9 -2
  86. package/dist/{chunk-WVUSXNIE.js.map → chunk-MPZUYCAP.js.map} +1 -1
  87. package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
  88. package/dist/chunk-OJNTCYQQ.js.map +1 -0
  89. package/dist/{chunk-IOODYAXL.js → chunk-OTWLERSW.js} +25 -6
  90. package/dist/chunk-OTWLERSW.js.map +1 -0
  91. package/dist/{chunk-AWQPGIR6.js → chunk-PJNENX2A.js} +1535 -422
  92. package/dist/chunk-PJNENX2A.js.map +1 -0
  93. package/dist/{chunk-KHE6L6TD.js → chunk-PKHI276N.js} +97 -11
  94. package/dist/chunk-PKHI276N.js.map +1 -0
  95. package/dist/{chunk-YHKXNYTB.js → chunk-QF3LSMGS.js} +2 -2
  96. package/dist/chunk-QXP3Z3JN.js +131 -0
  97. package/dist/chunk-QXP3Z3JN.js.map +1 -0
  98. package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
  99. package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
  100. package/dist/chunk-SFASB5FL.js +69 -0
  101. package/dist/chunk-SFASB5FL.js.map +1 -0
  102. package/dist/{chunk-WO5BJNIB.js → chunk-SNNSAGMT.js} +7273 -2741
  103. package/dist/chunk-SNNSAGMT.js.map +1 -0
  104. package/dist/{chunk-NZIP4PA2.js → chunk-SO3XRZPX.js} +3 -3
  105. package/dist/chunk-SYOS5CAC.js +176 -0
  106. package/dist/chunk-SYOS5CAC.js.map +1 -0
  107. package/dist/chunk-TAW4UFFF.js +293 -0
  108. package/dist/chunk-TAW4UFFF.js.map +1 -0
  109. package/dist/chunk-TF5HCP33.js +271 -0
  110. package/dist/chunk-TF5HCP33.js.map +1 -0
  111. package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
  112. package/dist/chunk-UUGOUOVT.js.map +1 -0
  113. package/dist/{chunk-AEG2PXBP.js → chunk-V2LQLN5H.js} +7 -7
  114. package/dist/{chunk-KYFZTGMC.js → chunk-VJUVFZ2D.js} +5 -3
  115. package/dist/{chunk-KYFZTGMC.js.map → chunk-VJUVFZ2D.js.map} +1 -1
  116. package/dist/{chunk-JMM6YE7J.js → chunk-VOZA6O7K.js} +708 -709
  117. package/dist/chunk-VOZA6O7K.js.map +1 -0
  118. package/dist/{chunk-5LJCEMFD.js → chunk-VUGQTZ2L.js} +209 -77
  119. package/dist/chunk-VUGQTZ2L.js.map +1 -0
  120. package/dist/chunk-WOM257PW.js +393 -0
  121. package/dist/chunk-WOM257PW.js.map +1 -0
  122. package/dist/chunk-WYXUQGOL.js +191 -0
  123. package/dist/chunk-WYXUQGOL.js.map +1 -0
  124. package/dist/chunk-X5ZBP3IY.js +97 -0
  125. package/dist/chunk-X5ZBP3IY.js.map +1 -0
  126. package/dist/chunk-XQJXNMSB.js +23 -0
  127. package/dist/chunk-XQJXNMSB.js.map +1 -0
  128. package/dist/chunk-Y527D4TV.js +56 -0
  129. package/dist/chunk-Y527D4TV.js.map +1 -0
  130. package/dist/{chunk-VUFAK2LW.js → chunk-YUY4SAGM.js} +17 -2
  131. package/dist/chunk-YUY4SAGM.js.map +1 -0
  132. package/dist/clack-EZ7TDWQU.js +19 -0
  133. package/dist/claude-cli-2YKABJJZ.js +31 -0
  134. package/dist/{cli-O5SN7ZJ4.js → cli-FB4LOA5A.js} +221 -68
  135. package/dist/{cli-O5SN7ZJ4.js.map → cli-FB4LOA5A.js.map} +1 -1
  136. package/dist/codex-event-TYVES3UX.js +16 -0
  137. package/dist/codex-host-WW4H2SKT.js +29 -0
  138. package/dist/codex-install-2C623HPW.js +393 -0
  139. package/dist/codex-install-2C623HPW.js.map +1 -0
  140. package/dist/{config-OJQI27LT.js → config-HOVJFEKD.js} +25 -15
  141. package/dist/doctor-NKU4V5OV.js +1312 -0
  142. package/dist/doctor-NKU4V5OV.js.map +1 -0
  143. package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
  144. package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
  145. package/dist/{fund-WEV6DMTD.js → fund-WEBHTZGN.js} +38 -30
  146. package/dist/{fund-WEV6DMTD.js.map → fund-WEBHTZGN.js.map} +1 -1
  147. package/dist/hook-command-ZA2PNKS6.js +44 -0
  148. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  149. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +3 -2
  150. package/dist/hosts/claude/tenjin/hooks/hooks.json +4 -1
  151. package/dist/hosts/claude/tenjin/hooks/register.tsx +589 -0
  152. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
  153. package/dist/hosts/claude/tenjin/types/index.d.ts +41 -0
  154. package/dist/hosts/codex/.agents/plugins/marketplace.json +20 -0
  155. package/dist/hosts/codex/tenjin/.codex-plugin/plugin.json +16 -0
  156. package/dist/hosts/codex/tenjin/.mcp.json +15 -0
  157. package/dist/hosts/codex/tenjin/hooks/hooks.json +98 -0
  158. package/dist/hosts-AV5MHBAU.js +38 -0
  159. package/dist/index.js +28 -8
  160. package/dist/index.js.map +1 -1
  161. package/dist/install-PT4EZS4R.js +100 -0
  162. package/dist/{install-identity-WHPNMNMQ.js → install-identity-5A4OE6YC.js} +13 -8
  163. package/dist/install-wallet-SAAPKB73.js +281 -0
  164. package/dist/install-wallet-SAAPKB73.js.map +1 -0
  165. package/dist/{mcp-QML7ZMPH.js → mcp-HAWKCTPQ.js} +909 -208
  166. package/dist/mcp-HAWKCTPQ.js.map +1 -0
  167. package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
  168. package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
  169. package/dist/{package-LGKYOEPV.js → package-SR2WB6MK.js} +4 -2
  170. package/dist/passphrase-IFTDS3CU.js +44 -0
  171. package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
  172. package/dist/pay-OXC3WKYV.js +55 -0
  173. package/dist/pay-OXC3WKYV.js.map +1 -0
  174. package/dist/{payments-C44QUFXU.js → payments-3KHMP2MG.js} +18 -13
  175. package/dist/{payments-C44QUFXU.js.map → payments-3KHMP2MG.js.map} +1 -1
  176. package/dist/plugin-registration-N3GRIZVM.js +67 -0
  177. package/dist/plugin-registration-N3GRIZVM.js.map +1 -0
  178. package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
  179. package/dist/redact-D7ASVWKL.js.map +1 -0
  180. package/dist/runtime-UVNUA3AS.js +1203 -0
  181. package/dist/runtime-UVNUA3AS.js.map +1 -0
  182. package/dist/runtime-fetch-EKFRNR6Z.js +20 -0
  183. package/dist/runtime-fetch-EKFRNR6Z.js.map +1 -0
  184. package/dist/runtime-layout-BDWZG2TQ.js +25 -0
  185. package/dist/runtime-layout-BDWZG2TQ.js.map +1 -0
  186. package/dist/{send-KVJX4XIR.js → send-HMKJLT34.js} +26 -18
  187. package/dist/{send-KVJX4XIR.js.map → send-HMKJLT34.js.map} +1 -1
  188. package/dist/{status-S7C3WMSH.js → status-RWXIIWYS.js} +57 -22
  189. package/dist/status-RWXIIWYS.js.map +1 -0
  190. package/dist/{status-line-YR2T5HC4.js → status-line-77XYZP7E.js} +13 -8
  191. package/dist/{status-line-YR2T5HC4.js.map → status-line-77XYZP7E.js.map} +1 -1
  192. package/dist/uninstall-D5G67UJH.js +480 -0
  193. package/dist/uninstall-D5G67UJH.js.map +1 -0
  194. package/dist/update-LRNOEGSB.js +53 -0
  195. package/dist/update-LRNOEGSB.js.map +1 -0
  196. package/dist/{usdc-JK4RRFFQ.js → usdc-D6X7EIQ2.js} +7 -8
  197. package/dist/usdc-D6X7EIQ2.js.map +1 -0
  198. package/dist/{viemAdapter-By13KInL-X2VY6CY3.js → viemAdapter-By13KInL-RL742ETX.js} +3 -3
  199. package/dist/viemAdapter-By13KInL-RL742ETX.js.map +1 -0
  200. package/dist/wallet-XFYC27BR.js +55 -0
  201. package/dist/wallet-XFYC27BR.js.map +1 -0
  202. package/dist/wallet-kdf-worker.mjs +8 -8
  203. package/docs/agent-permissions.md +56 -22
  204. package/docs/safety-model.md +1 -1
  205. package/docs/troubleshooting.md +72 -1
  206. package/package.json +14 -1
  207. package/dist/alive-3J3CHOQP.js +0 -21
  208. package/dist/ccip-NLCSCHKI.js +0 -19
  209. package/dist/chunk-3O2BQIF6.js.map +0 -1
  210. package/dist/chunk-5IEP5EGE.js +0 -5332
  211. package/dist/chunk-5IEP5EGE.js.map +0 -1
  212. package/dist/chunk-5LJCEMFD.js.map +0 -1
  213. package/dist/chunk-6W5GYG3W.js +0 -128
  214. package/dist/chunk-6W5GYG3W.js.map +0 -1
  215. package/dist/chunk-7EKYXMUO.js +0 -7536
  216. package/dist/chunk-7EKYXMUO.js.map +0 -1
  217. package/dist/chunk-7QKHZQKW.js.map +0 -1
  218. package/dist/chunk-AKWGE6JQ.js.map +0 -1
  219. package/dist/chunk-AWQPGIR6.js.map +0 -1
  220. package/dist/chunk-EGELTSPU.js +0 -2865
  221. package/dist/chunk-EGELTSPU.js.map +0 -1
  222. package/dist/chunk-EL56RW2J.js +0 -7611
  223. package/dist/chunk-EL56RW2J.js.map +0 -1
  224. package/dist/chunk-HE2MS4QO.js +0 -256
  225. package/dist/chunk-HE2MS4QO.js.map +0 -1
  226. package/dist/chunk-IOODYAXL.js.map +0 -1
  227. package/dist/chunk-JMM6YE7J.js.map +0 -1
  228. package/dist/chunk-KHE6L6TD.js.map +0 -1
  229. package/dist/chunk-N35E6CM2.js +0 -1185
  230. package/dist/chunk-N35E6CM2.js.map +0 -1
  231. package/dist/chunk-O2FRQ2L2.js.map +0 -1
  232. package/dist/chunk-OK2TDZQU.js.map +0 -1
  233. package/dist/chunk-OSYTBCUC.js.map +0 -1
  234. package/dist/chunk-PAYV4XUA.js.map +0 -1
  235. package/dist/chunk-SJLTEINJ.js.map +0 -1
  236. package/dist/chunk-TTBKWWTV.js.map +0 -1
  237. package/dist/chunk-TTNESUPQ.js.map +0 -1
  238. package/dist/chunk-U6YQ6FRI.js.map +0 -1
  239. package/dist/chunk-VUFAK2LW.js.map +0 -1
  240. package/dist/chunk-VZGAONSJ.js.map +0 -1
  241. package/dist/chunk-WO5BJNIB.js.map +0 -1
  242. package/dist/doctor-IQQJHGGM.js +0 -590
  243. package/dist/doctor-IQQJHGGM.js.map +0 -1
  244. package/dist/hook-command-D2P3ILRV.js +0 -32
  245. package/dist/install-TUCRF32I.js +0 -60
  246. package/dist/install-wallet-MA27FTQ5.js +0 -113
  247. package/dist/install-wallet-MA27FTQ5.js.map +0 -1
  248. package/dist/mcp-QML7ZMPH.js.map +0 -1
  249. package/dist/pay-2C2UBBXJ.js +0 -51
  250. package/dist/status-S7C3WMSH.js.map +0 -1
  251. package/dist/uninstall-HY6LKIIT.js +0 -149
  252. package/dist/uninstall-HY6LKIIT.js.map +0 -1
  253. package/dist/update-OJV22LR3.js +0 -36
  254. package/dist/wallet-PD2IMZDU.js +0 -39
  255. /package/dist/{_esm-CE7KNONL.js.map → _esm-RLLC72MS.js.map} +0 -0
  256. /package/dist/{alive-3J3CHOQP.js.map → alive-MROUMFH3.js.map} +0 -0
  257. /package/dist/{ccip-7RMRLAGV.js.map → auto-update-OPWMRZLS.js.map} +0 -0
  258. /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
  259. /package/dist/{chunk-LFZJM56J.js.map → chunk-445VQTVM.js.map} +0 -0
  260. /package/dist/{chunk-RAULEAZ6.js.map → chunk-4USCZ2NI.js.map} +0 -0
  261. /package/dist/{chunk-VFMQTSXG.js.map → chunk-D3ZURCG7.js.map} +0 -0
  262. /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
  263. /package/dist/{chunk-EBVIKMCH.js.map → chunk-JKKAIPTU.js.map} +0 -0
  264. /package/dist/{chunk-YHKXNYTB.js.map → chunk-QF3LSMGS.js.map} +0 -0
  265. /package/dist/{chunk-NZIP4PA2.js.map → chunk-SO3XRZPX.js.map} +0 -0
  266. /package/dist/{chunk-AEG2PXBP.js.map → chunk-V2LQLN5H.js.map} +0 -0
  267. /package/dist/{config-OJQI27LT.js.map → clack-EZ7TDWQU.js.map} +0 -0
  268. /package/dist/{env-proxy-XL4P73MZ.js.map → claude-cli-2YKABJJZ.js.map} +0 -0
  269. /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → codex-event-TYVES3UX.js.map} +0 -0
  270. /package/dist/{hook-command-D2P3ILRV.js.map → codex-host-WW4H2SKT.js.map} +0 -0
  271. /package/dist/{install-TUCRF32I.js.map → config-HOVJFEKD.js.map} +0 -0
  272. /package/dist/{install-identity-WHPNMNMQ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
  273. /package/dist/{package-LGKYOEPV.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
  274. /package/dist/{paths-POPTXJO6.js.map → hook-command-ZA2PNKS6.js.map} +0 -0
  275. /package/dist/{pay-2C2UBBXJ.js.map → hosts-AV5MHBAU.js.map} +0 -0
  276. /package/dist/{redact-6W23GGJC.js.map → install-PT4EZS4R.js.map} +0 -0
  277. /package/dist/{update-OJV22LR3.js.map → install-identity-5A4OE6YC.js.map} +0 -0
  278. /package/dist/{usdc-JK4RRFFQ.js.map → package-SR2WB6MK.js.map} +0 -0
  279. /package/dist/{viemAdapter-By13KInL-X2VY6CY3.js.map → passphrase-IFTDS3CU.js.map} +0 -0
  280. /package/dist/{wallet-PD2IMZDU.js.map → paths-XCSAKISU.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/wallet/passphrase.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { randomBytes } from 'node:crypto';\nimport { readFile, stat, unlink } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { CliError } from '../errors';\nimport { hasCode } from '../errno';\nimport { writeFileAtomic, writeFileAtomicExclusive } from '../atomic-json';\nimport { readPassphraseRecord } from '../passphrase-record';\nimport {\n dataDir,\n passphraseBlobPath,\n passphraseBlobPathFor,\n passphraseFilePathFor,\n} from '../paths';\nimport {\n FILE_STORE_FAILED_FIX,\n KEYCHAIN_LOCKED_FIX,\n KEYCHAIN_WAIT_LINE,\n REPAIR_IN_TERMINAL,\n unlockDetails,\n type DurableStore,\n} from '../wallet-unlock';\n\nexport type { DurableStore } from '../wallet-unlock';\n\n/**\n * Wallet passphrase resolution. The private key lives on disk as an encrypted\n * Keystore v3 document; the passphrase that unlocks it is resolved here, in a\n * fixed order, so signing works headlessly (env), transparently through the OS\n * store (macOS keychain, Windows DPAPI, desktop-Linux keyring), or interactively\n * (TTY). Every side-effecting seam — the store CLIs and the hidden-input prompt —\n * is injectable so tests never touch a real keychain or terminal.\n *\n * The passphrase never appears in any argv (which the OS process table can show):\n * reads come back on stdout, and writes pipe the secret over the child's stdin.\n * A failed store CLI never carries its stdout anywhere (for a read, that IS the\n * secret): it rejects with a {@link StoreExecError} holding only the exit code,\n * the signal and the stderr {@link classifyStoreFailure} reads, and every detail\n * built from it names only those.\n *\n * ONE ANNOUNCED PLAINTEXT EXCEPTION: where no OS store exists at all (headless\n * Linux, WSL, a sandbox; the probe says `absent`) or the user chose\n * `--insecure-storage`, the passphrase is saved to `passphrase.<address>.plain`\n * at 0600 in the 0700 data dir, the way the GitHub CLI keeps `hosts.yml`.\n * Create and repair say so in one line. A store that exists but is LOCKED never\n * routes there: a locked keychain is unlocked, not worked around. Everywhere\n * else no plaintext is written to disk (the Windows blob is DPAPI-encrypted, not\n * the passphrase itself).\n *\n * Durable entries are PER WALLET (account = lowercase address); the legacy\n * shared slot is only ever read, for migration (#32). Where each wallet's\n * passphrase went is recorded in the sidecar (`src/lib/passphrase-record.ts`),\n * so a recorded wallet reads exactly one store.\n */\n\nconst KEYCHAIN_SERVICE = 'tenjin-cli';\n/**\n * The pre-per-wallet shared slot (service `tenjin-cli`, account `wallet`) that\n * every create used to `-U`-overwrite. Never written anymore; read only as a\n * migration fallback and removed only after a verified per-address copy exists.\n */\nconst LEGACY_ACCOUNT = 'wallet';\n\n/**\n * The account the Secret Service probe looks up: the zero address, which no\n * wallet can own. A hit or a miss both prove a keyring answered.\n */\nconst PROBE_ACCOUNT = '0x0000000000000000000000000000000000000000';\n\n/** A lowercase 0x-prefixed 20-byte hex address — the per-wallet store account. */\nconst ACCOUNT_ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/**\n * base64url alphabet — what generated passphrases use. These still go to the\n * keychain as today's exact `-w '<value>'` line (no quote/backslash/space/newline\n * can appear inside the single quotes), so an existing reader of that shape sees\n * no change.\n */\nconst BASE64URL_RE = /^[A-Za-z0-9_-]+$/;\n\n/**\n * Printable ASCII: what the keychain writer stores at all. Anything outside the\n * base64url alphabet goes as `-X <utf8 hex>`, which carries only `[0-9a-f]` on\n * the piped `security -i` line, so nothing in the value can be read as syntax.\n * Non-printable bytes are refused, not encoded: `security -w` prints a value\n * with them back as hex, which would not read back byte-identical.\n */\nconst PRINTABLE_ASCII_RE = /^[\\x20-\\x7e]+$/;\n\n/**\n * The OS-store account for a wallet address: lowercased (checksum-insensitive)\n * and validated as plain hex before it can reach the piped `security -i` line.\n */\nexport function walletStoreAccount(address: string): string {\n const account = address.toLowerCase();\n if (!ACCOUNT_ADDRESS_RE.test(account)) {\n throw new CliError('INTERNAL', `Not a valid wallet address for passphrase storage: ${address}`);\n }\n return account;\n}\n\nexport type PassphraseSource = 'env' | DurableStore | 'prompt';\n\nexport interface ResolvedPassphrase {\n passphrase: string;\n source: PassphraseSource;\n /**\n * Present ONLY when the passphrase came from the legacy shared slot. Call it\n * strictly AFTER proving the passphrase decrypts this wallet's keystore; it\n * re-keys the slot per migrateLegacyEntry's contract. On a decrypt failure\n * do NOT call it — surface the ambiguity and leave the legacy entry alone.\n */\n migrateLegacy?: () => Promise<boolean>;\n /** true when the sidecar named the store that served it. */\n recorded?: boolean;\n}\n\n/**\n * Runs a command with an argv array (execFile semantics — never shell-interpolated).\n * When `stdin` is provided it is written to the child's stdin and the stream is\n * closed; this is how the passphrase reaches `security -i`, PowerShell, and\n * `secret-tool` WITHOUT ever appearing in an argv the process table can expose.\n *\n * `opts.timeoutMs` absent means the child is never killed: every signing read\n * passes none (B3), so an OS unlock dialog the person may be answering stays up.\n * Rejects only with a {@link StoreExecError} (S2).\n */\nexport type ExecFn = (\n file: string,\n args: string[],\n stdin?: string,\n opts?: { timeoutMs?: number },\n) => Promise<{ stdout: string; stderr: string }>;\n\n/** Reads one line of hidden input, writing `label` to stderr (never stdout). */\nexport type PromptFn = (label: string) => Promise<string>;\n\n/**\n * THE ONLY REJECTION OF {@link defaultExecFor} (S2). A fresh error built from the\n * Node one, never the Node one itself: Node's message and its `stdout` field can\n * carry the child's output, and for a store read that output is the passphrase.\n * There is no `stdout` field here, ever. `stderr` is kept only so\n * {@link classifyStoreFailure} can tell \"no such keychain\" from \"locked\"; it is\n * non-enumerable so a `JSON.stringify` or a log of this error cannot carry it,\n * and nothing copies it into a message, detail, warning or file.\n */\nexport class StoreExecError extends Error {\n readonly code: number | string | null;\n readonly signal: string | null;\n readonly killed: boolean;\n readonly enoent: boolean;\n declare readonly stderr: string;\n\n constructor(\n file: string,\n fields: {\n code?: number | string | null;\n signal?: string | null;\n killed?: boolean;\n enoent?: boolean;\n stderr?: string;\n } = {},\n ) {\n const code = fields.code ?? null;\n const signal = fields.signal ?? null;\n super(`${file} failed (${code ?? signal ?? 'no exit code'})`);\n this.name = 'StoreExecError';\n this.code = code;\n this.signal = signal;\n this.killed = fields.killed ?? false;\n this.enoent = fields.enoent ?? code === 'ENOENT';\n Object.defineProperty(this, 'stderr', {\n value: fields.stderr ?? '',\n enumerable: false,\n writable: false,\n });\n }\n}\n\n/**\n * Store-operation deadlines (decision 7). Reads are NOT here: the router never\n * kills a store read; only verify (doctor, install) bounds one, at\n * `verifyReadMs`. Writes are bounded as a whole: pre-read, write and read-back\n * share one deadline, 10 s headless or 60 s at a terminal, where the person may\n * be answering an OS unlock prompt (`waitLineAfterMs` in, they are told so).\n */\nexport const STORE_TIMEOUTS = {\n verifyReadMs: 5000,\n writeMs: 10000,\n interactiveWriteMs: 60000,\n probeMs: 3000,\n waitLineAfterMs: 1000,\n} as const;\n\n/** {@link STORE_TIMEOUTS}' shape, as plain numbers a test may override. */\nexport type StoreTimeouts = Record<keyof typeof STORE_TIMEOUTS, number>;\n\nexport interface PassphraseDeps {\n env: NodeJS.ProcessEnv;\n /** Data dir that holds the sidecar, the DPAPI blob and the passphrase file; defaults to the resolved data dir. */\n dir?: string;\n /** Defaults to `process.platform`; selects the OS store (or none). */\n platform?: NodeJS.Platform;\n /** Whether an interactive prompt is possible; defaults to `process.stdin.isTTY`. */\n isTTY?: boolean;\n /** The store-CLI exec seam; defaults to a real execFile with stdin support. */\n exec?: ExecFn;\n /** The hidden-input prompt seam; defaults to a raw-mode TTY reader. */\n prompt?: PromptFn;\n /** Test override for {@link STORE_TIMEOUTS}. */\n timeouts?: Partial<StoreTimeouts>;\n /**\n * Read deadline for verify only (doctor and install pass\n * `STORE_TIMEOUTS.verifyReadMs`). Absent means reads are never killed, which\n * is what every signing caller must stay (B3).\n */\n readDeadlineMs?: number;\n /**\n * Create and repair at a TTY: called once with KEYCHAIN_WAIT_LINE when\n * storeDurablyDetailed has not settled after `waitLineAfterMs`. Commands wire it to\n * stderr.\n */\n onWait?: (line: string) => void;\n}\n\n/** One store read, classified. `detail` never carries the store's output (S2). */\nexport type StoreRead =\n | { kind: 'hit'; value: string }\n | { kind: 'miss' }\n | { kind: 'absent'; detail: string }\n | { kind: 'locked'; detail: string };\n\n/** Whether the platform store can answer at all: before create or repair picks a target. */\nexport type StoreProbe = 'available' | 'absent' | 'uncertain';\n\n/**\n * 'kept-existing': the pre-read found a different value and replaceIf said keep it (nothing written).\n * 'conflict': a different value with no replaceIf, or a read-back that differs after the write (S1).\n */\nexport type DurableWrite =\n | 'stored'\n | 'already-stored'\n | 'kept-existing'\n | 'conflict'\n | 'uncertain'\n | 'store-failed'\n | 'rejected-characters';\n\n/** A --replace archive write's outcome ({@link toStoreOutcome}); `no-store`: nowhere to write. */\nexport type StorePassphraseOutcome =\n 'stored' | 'no-store' | 'rejected-characters' | 'store-failed' | 'uncertain';\n\n/** Per-call deadline for every store method (decision 7). Absent = never killed. The file store ignores it. */\nexport interface StoreCallOptions {\n timeoutMs?: number;\n}\n\n/**\n * A durable passphrase store, keyed by ACCOUNT (the wallet's lowercase address,\n * or the read-only legacy `wallet` slot). Reads never throw: they classify. A\n * write throws the StoreExecError (or the fs error, for the file store) so\n * storeDurablyDetailed can tell a killed write, which may have committed, from a\n * definite failure.\n */\ninterface PassphraseStore {\n /** The source label reported when this store serves the passphrase. */\n source: DurableStore;\n read(account: string, o?: StoreCallOptions): Promise<StoreRead>;\n store(account: string, value: string, o?: StoreCallOptions & { update?: boolean }): Promise<void>;\n remove(account: string, o?: StoreCallOptions): Promise<boolean>;\n probe(o?: StoreCallOptions): Promise<{ probe: StoreProbe; detail?: string }>;\n /**\n * When present, a cheap pre-check for values this backend's writer refuses on\n * principle (the keychain's printable-ASCII gate), or that its read would not\n * give back byte for byte (a trailing line break the read strips) — so\n * callers can tell \"this passphrase's characters\" apart from \"the store\n * write failed\", and nothing is written that reads back as another secret.\n */\n storable?(value: string): boolean;\n}\n\n/**\n * The real executor. Each call applies its own `opts.timeoutMs` when given, and\n * kills with SIGKILL: a store CLI that ignored SIGTERM would otherwise outlive\n * the deadline it was given.\n *\n * WHY A WRITE MAY BE KILLED NOW. A killed write used to be a correctness hazard:\n * create treated \"the write did not return\" as \"the write did not stick\" and fell\n * through to a different, prompted passphrase while the committed value won\n * every later decrypt. That fall-through is gone. One secret per address is\n * chosen before any write, and every write is followed by a read-back\n * (storeDurablyDetailed), so a killed write that did commit reads back as stored, and\n * one that did not reads back as missing. The worst a kill leaves is an orphan\n * keychain entry for an address whose create was then abandoned, which no\n * wallet will ever read.\n *\n * WHY READS STAY UNBOUNDED, except in verify. Killing a read closes an OS unlock\n * dialog the person may be answering. The router bounds its WAIT with the call\n * budget instead (routing-payer.ts), and the read keeps running so a later call\n * gets its answer. Only doctor's and install's verify, which run unattended and\n * must finish, pass a read deadline.\n */\nexport function defaultExecFor(): ExecFn {\n return (file, args, stdin, opts) =>\n new Promise((resolve, reject) => {\n const child = execFile(\n file,\n args,\n {\n encoding: 'utf8',\n killSignal: 'SIGKILL',\n // 0 would mean \"no timeout\" to Node; a spent deadline is still a deadline.\n ...(opts?.timeoutMs !== undefined ? { timeout: Math.max(1, opts.timeoutMs) } : {}),\n },\n (err, stdout, stderr) => {\n if (err) reject(toStoreExecError(file, err, stderr));\n else resolve({ stdout, stderr });\n },\n );\n if (stdin !== undefined) {\n // A child that exits before draining stdin closes the pipe; swallow the\n // resulting EPIPE so the exec callback surfaces the real exit error instead.\n child.stdin?.on('error', () => undefined);\n child.stdin?.end(stdin);\n }\n });\n}\n\n/** The scrubbed copy of a Node exec error: no message, no stdout (S2). */\nfunction toStoreExecError(file: string, err: unknown, stderr: unknown): StoreExecError {\n const e = err as { code?: unknown; signal?: unknown; killed?: unknown };\n const code = typeof e.code === 'number' || typeof e.code === 'string' ? e.code : null;\n return new StoreExecError(file, {\n code,\n signal: typeof e.signal === 'string' ? e.signal : null,\n killed: e.killed === true,\n enoent: code === 'ENOENT',\n stderr: typeof stderr === 'string' ? stderr : '',\n });\n}\n\n/** The effective deadlines: STORE_TIMEOUTS with any test override applied. */\nfunction timeoutsOf(deps: PassphraseDeps): StoreTimeouts {\n return { ...STORE_TIMEOUTS, ...deps.timeouts };\n}\n\n/** What a store is called in a sentence: \"the <noun> did not answer\". */\nexport function storeNoun(store: DurableStore): string {\n switch (store) {\n case 'keychain':\n return 'macOS keychain';\n case 'secret-service':\n return 'Linux keyring';\n case 'dpapi':\n return 'Windows DPAPI store';\n case 'file':\n return 'passphrase file';\n }\n}\n\n/**\n * WHY A STORE OPERATION FAILED, in a form that can gate (section 2.5). Anything\n * unclear is `locked`, which is unknown and never a block (Q5): only a store\n * that provably is not there is `absent`, and only the store's own \"no such\n * entry\" is a `miss`.\n *\n * `stderr` is read here to pick the kind and then dropped. Every detail is\n * built only from the kind, the exit code and the signal (S2), never from the\n * child's output or the error's message. A thrown value that is not a\n * StoreExecError (a test fake, a bug) is `locked` with a fixed detail and its\n * message is not read. The file store's fs errors are classified by errno code.\n */\nexport function classifyStoreFailure(\n store: DurableStore,\n err: unknown,\n): Exclude<StoreRead, { kind: 'hit' }> {\n if (store === 'file') {\n if (hasCode(err, 'ENOENT')) return { kind: 'miss' };\n const code = (err as { code?: unknown } | null)?.code;\n const errno = typeof code === 'string' && /^E[A-Z]+$/.test(code) ? ` (${code})` : '';\n return { kind: 'locked', detail: `the passphrase file could not be read${errno}` };\n }\n if (!(err instanceof StoreExecError)) {\n return {\n kind: 'locked',\n detail: `the ${storeNoun(store)} failed for a reason Tenjin could not classify`,\n };\n }\n if (err.killed || err.signal !== null) {\n return {\n kind: 'locked',\n detail: `the ${storeNoun(store)} did not answer (killed by ${err.signal ?? 'SIGKILL'})`,\n };\n }\n switch (store) {\n case 'keychain':\n if (err.enoent) return { kind: 'absent', detail: 'the `security` tool is not installed' };\n if (err.code === 44) return { kind: 'miss' };\n if (/default keychain could not be found/i.test(err.stderr)) {\n return { kind: 'absent', detail: 'there is no default keychain' };\n }\n if (/User interaction is not allowed/.test(err.stderr)) {\n return { kind: 'locked', detail: 'the keychain refused (user interaction is not allowed)' };\n }\n return { kind: 'locked', detail: `security exited ${String(err.code)}` };\n case 'secret-service':\n if (err.enoent) return { kind: 'absent', detail: 'secret-tool is not installed' };\n if (\n /Cannot autolaunch D-Bus|org\\.freedesktop\\.secrets was not provided|Could not connect/.test(\n err.stderr,\n )\n ) {\n return { kind: 'absent', detail: 'no Secret Service is reachable from this session' };\n }\n if (err.code === 1 && err.stderr.trim() === '') return { kind: 'miss' };\n return { kind: 'locked', detail: `secret-tool exited ${String(err.code)}` };\n case 'dpapi':\n if (err.enoent) return { kind: 'absent', detail: 'powershell.exe is not available' };\n return {\n kind: 'locked',\n detail: `the DPAPI unprotect failed (powershell.exe exited ${String(err.code)})`,\n };\n }\n}\n\n/** The durable store for this platform, or null where no built-in one exists. */\nfunction storeFor(deps: PassphraseDeps): PassphraseStore | null {\n switch (deps.platform ?? process.platform) {\n case 'darwin':\n return keychainStore(deps);\n case 'win32':\n return dpapiStore(deps);\n case 'linux':\n return secretServiceStore(deps);\n default:\n return null;\n }\n}\n\n/** Any store by name, the file store included: what a sidecar entry or a chosen target names. */\nfunction storeByName(deps: PassphraseDeps, name: DurableStore): PassphraseStore {\n switch (name) {\n case 'keychain':\n return keychainStore(deps);\n case 'secret-service':\n return secretServiceStore(deps);\n case 'dpapi':\n return dpapiStore(deps);\n case 'file':\n return fileStore(deps);\n }\n}\n\n/**\n * One classified read of `address`'s entry in a named store (repair: \"does the\n * store the sidecar names already hold this passphrase?\"). Never throws.\n */\nexport function readStoredPassphrase(\n deps: PassphraseDeps,\n store: DurableStore,\n address: string,\n o?: StoreCallOptions,\n): Promise<StoreRead> {\n return storeByName(deps, store).read(walletStoreAccount(address), o);\n}\n\n/**\n * Resolve the passphrase to DECRYPT the existing wallet at `address`.\n *\n * 1. `TENJIN_WALLET_PASSPHRASE`, unless `skipEnv` (the wrong-env fallthrough).\n * 2. A sidecar entry: read ONLY that store's per-address entry. There is no\n * other-store fallback: the sidecar is the answer to \"where did it go\".\n * 3. No sidecar entry (every wallet made before the sidecar existed): today's\n * order, so alpha.30 keychain users read exactly the same entry. The OS store\n * per-address, then the legacy slot (only when the OS store exists), then the\n * 0600 file, then the prompt.\n *\n * A store that is LOCKED stops the chain, recorded or not: falling through to\n * the legacy slot or the prompt would answer \"did the keychain say no?\" with a\n * guess. At a TTY the person is asked instead; elsewhere it throws\n * `keychain_locked`, whose fix is to unlock the keychain, never plaintext (S3).\n * A locked LEGACY slot still lets the file be read, but a file miss after it is\n * `keychain_locked` too, never `passphrase_missing`.\n *\n * A legacy hit carries a `migrateLegacy` handle the caller invokes only after\n * proving the passphrase decrypts this wallet (see ResolvedPassphrase). Reads\n * pass `deps.readDeadlineMs` when it is set (verify only) and no deadline\n * otherwise (B3).\n */\nexport async function resolvePassphrase(\n deps: PassphraseDeps,\n address: string,\n opts: { skipEnv?: boolean; promptLabel?: string } = {},\n): Promise<ResolvedPassphrase> {\n if (opts.skipEnv !== true) {\n const fromEnv = envPassphrase(deps.env);\n if (fromEnv !== null) return { passphrase: fromEnv, source: 'env' };\n }\n\n const account = walletStoreAccount(address);\n const readOpts: StoreCallOptions | undefined =\n deps.readDeadlineMs !== undefined ? { timeoutMs: deps.readDeadlineMs } : undefined;\n const prompted = async (): Promise<ResolvedPassphrase> => {\n const entered = await promptOf(deps)(opts.promptLabel ?? 'Wallet passphrase: ');\n if (entered.length === 0) throw noPassphraseError();\n return { passphrase: entered, source: 'prompt' };\n };\n\n const entry = await readPassphraseRecord(deps.dir ?? dataDir(), account);\n if (entry !== null) {\n const got = await storeByName(deps, entry.store).read(account, readOpts);\n if (got.kind === 'hit') return { passphrase: got.value, source: entry.store, recorded: true };\n if (canPrompt(deps)) return prompted();\n if (got.kind === 'miss') {\n throw noPassphraseError(describeStoreLocation(entry.store, account, deps.dir));\n }\n throw storeLockedError(entry.store, account, got.detail, deps.dir, true);\n }\n\n const store = storeFor(deps);\n // A legacy slot that holds an entry but did not answer. The 0600 file is\n // still read (it may hold this wallet's passphrase, and the shared legacy\n // slot may hold another wallet's), but if it misses too the answer is\n // `keychain_locked`, never a definite `passphrase_missing` (Unknown never blocks).\n let legacyLocked: { source: DurableStore; detail: string } | null = null;\n if (store !== null) {\n const own = await store.read(account, readOpts);\n if (own.kind === 'hit') return { passphrase: own.value, source: store.source };\n if (own.kind === 'locked') {\n if (canPrompt(deps)) return prompted();\n throw storeLockedError(store.source, account, own.detail, deps.dir, false);\n }\n if (own.kind === 'miss') {\n const legacy = await store.read(LEGACY_ACCOUNT, readOpts);\n if (legacy.kind === 'hit') {\n return {\n passphrase: legacy.value,\n source: store.source,\n migrateLegacy: () => migrateLegacyEntry(legacyOps(store, deps), account, legacy.value),\n };\n }\n if (legacy.kind === 'locked') legacyLocked = { source: store.source, detail: legacy.detail };\n }\n }\n\n const file = await fileStore(deps).read(account);\n if (file.kind === 'hit') return { passphrase: file.value, source: 'file' };\n\n if (canPrompt(deps)) return prompted();\n if (legacyLocked !== null) {\n throw storeLockedError(\n legacyLocked.source,\n LEGACY_ACCOUNT,\n legacyLocked.detail,\n deps.dir,\n false,\n );\n }\n throw noPassphraseError();\n}\n\n/** The three store operations a legacy migration makes, each under the store write bound. */\ninterface LegacyOps {\n copy(account: string, value: string): Promise<boolean>;\n readBack(account: string): Promise<string | null>;\n removeLegacy(): Promise<boolean>;\n}\n\n/**\n * The legacy migration on the store API (S10). Each call passes the store WRITE\n * bound (`writeMs`): a migration is a write and its check, not a signing read,\n * and a killed read-back is not a hit, so the legacy slot stays. Nothing here\n * writes the sidecar: only create, repair and `--replace` do.\n */\nfunction legacyOps(store: PassphraseStore, deps: PassphraseDeps): LegacyOps {\n const timeoutMs = timeoutsOf(deps).writeMs;\n return {\n async copy(account, value) {\n if (store.storable !== undefined && !store.storable(value)) return false;\n try {\n await store.store(account, value, { timeoutMs });\n return true;\n } catch {\n return false;\n }\n },\n async readBack(account) {\n const got = await store.read(account, { timeoutMs });\n return got.kind === 'hit' ? got.value : null;\n },\n removeLegacy: () => store.remove(LEGACY_ACCOUNT, { timeoutMs }),\n };\n}\n\n/**\n * Re-key the legacy shared slot under the owning wallet's own account: copy\n * first, verify the copy reads back byte-identical, and only then remove the\n * legacy entry. A failed copy or verify returns false with the legacy entry\n * still in place — the invariant is that at every step at least one durable\n * copy of the passphrase exists. The removal itself is best-effort: once the\n * copy has verified, a legacy entry that refuses to delete is redundant, not\n * unsafe (per-address reads win from then on), so it never fails the migration.\n */\nasync function migrateLegacyEntry(\n ops: LegacyOps,\n account: string,\n passphrase: string,\n): Promise<boolean> {\n if (!(await ops.copy(account, passphrase))) return false;\n if ((await ops.readBack(account)) !== passphrase) return false;\n await ops.removeLegacy();\n return true;\n}\n\n/** storeDurablyDetailed's outcome with the classified reason behind it, for the message. */\nexport interface DurableWriteResult {\n outcome: DurableWrite;\n /** Why it was not stored, built from the classified kind only (S2). Absent on success. */\n detail?: string;\n}\n\n/**\n * Save `secret` as `address`'s passphrase in `store`, and say only what a\n * read-back proves.\n *\n * (a) Pre-read. An equal value is `already-stored`. A different value is\n * `conflict` unless `replaceIf(existing)` says to replace it (repair, after\n * proving the old entry does not open the wallet), or `kept-existing` when it\n * says keep it. A locked or absent store is `uncertain` before any write.\n * (b) A value this store's writer refuses is `rejected-characters`.\n * (c) Exactly one write, of exactly this value.\n * (d) Always a read-back. Equal is `stored`; different is `conflict` (S1: some\n * other writer holds the entry, so this is never \"saved\"); a miss after a\n * killed write, or a store that does not answer the read-back, is\n * `uncertain`; a miss after any other write is `store-failed`.\n *\n * All three steps share ONE deadline (decision 7): 10 s headless, 60 s at a\n * terminal. Each call gets the time left; a step with none left is not\n * started. At a terminal, a write still unsettled after a second prints\n * KEYCHAIN_WAIT_LINE once through `onWait`. The file store never waits.\n */\nexport async function storeDurablyDetailed(\n deps: PassphraseDeps,\n storeName: DurableStore,\n address: string,\n secret: string,\n opts: { replaceIf?: (existing: string) => Promise<boolean> } = {},\n): Promise<DurableWriteResult> {\n const store = storeByName(deps, storeName);\n const account = walletStoreAccount(address);\n const t = timeoutsOf(deps);\n const end = Date.now() + (deps.isTTY === true ? t.interactiveWriteMs : t.writeMs);\n const left = (): number => end - Date.now();\n const outOfTime: DurableWriteResult = {\n outcome: 'uncertain',\n detail: `the ${storeNoun(storeName)} did not answer in time`,\n };\n\n let timer: NodeJS.Timeout | undefined;\n if (deps.isTTY === true && storeName !== 'file' && deps.onWait !== undefined) {\n const onWait = deps.onWait;\n timer = setTimeout(() => onWait(KEYCHAIN_WAIT_LINE), t.waitLineAfterMs);\n timer.unref?.();\n }\n try {\n if (left() <= 0) return outOfTime;\n const pre = await store.read(account, { timeoutMs: left() });\n if (pre.kind === 'locked' || pre.kind === 'absent') {\n return { outcome: 'uncertain', detail: pre.detail };\n }\n let update = false;\n if (pre.kind === 'hit') {\n if (pre.value === secret) return { outcome: 'already-stored' };\n if (opts.replaceIf === undefined) {\n return { outcome: 'conflict', detail: 'a different passphrase is already saved there' };\n }\n if (!(await opts.replaceIf(pre.value))) return { outcome: 'kept-existing' };\n update = true;\n }\n\n if (store.storable !== undefined && !store.storable(secret)) {\n return { outcome: 'rejected-characters' };\n }\n\n if (left() <= 0) return outOfTime;\n let writeError: unknown;\n let wrote = true;\n try {\n await store.store(account, secret, {\n timeoutMs: left(),\n ...(update ? { update: true } : {}),\n });\n } catch (err) {\n wrote = false;\n writeError = err;\n }\n\n if (left() <= 0) return outOfTime;\n const back = await store.read(account, { timeoutMs: left() });\n if (back.kind === 'hit') {\n return back.value === secret\n ? { outcome: 'stored' }\n : { outcome: 'conflict', detail: 'a different passphrase is saved there after the write' };\n }\n if (back.kind !== 'miss') return { outcome: 'uncertain', detail: back.detail };\n if (wrote) return { outcome: 'store-failed', detail: 'the saved passphrase did not read back' };\n const failure = classifyStoreFailure(storeName, writeError);\n if (isKilled(writeError)) {\n return { outcome: 'uncertain', detail: 'detail' in failure ? failure.detail : undefined };\n }\n return {\n outcome: 'store-failed',\n detail: writeFailureDetail(storeName, writeError, failure),\n };\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\n/** A write that was killed on its deadline: it may have committed, so only a read-back can say. */\nfunction isKilled(err: unknown): boolean {\n return err instanceof StoreExecError && (err.killed || err.signal !== null);\n}\n\n/** Why a write failed, in classified words: the read classification, or the fs errno for the file. */\nfunction writeFailureDetail(\n store: DurableStore,\n err: unknown,\n failure: Exclude<StoreRead, { kind: 'hit' }>,\n): string {\n if (store === 'file') {\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' && /^E[A-Z]+$/.test(code)\n ? `the passphrase file could not be written (${code})`\n : 'the passphrase file could not be written';\n }\n return 'detail' in failure ? failure.detail : `the ${storeNoun(store)} write failed`;\n}\n\n/**\n * S1: how the --replace archive writer (local.ts) maps storeDurablyDetailed's\n * DurableWrite. `stored` only ever means the store holds the intended value: a\n * store that holds a DIFFERENT one (`conflict`, or `kept-existing`, which that\n * writer never asks for since it passes no replaceIf) is `store-failed`.\n */\nexport function toStoreOutcome(w: DurableWrite): Exclude<StorePassphraseOutcome, 'no-store'> {\n switch (w) {\n case 'stored':\n return 'stored';\n case 'already-stored':\n return 'stored';\n case 'kept-existing':\n return 'store-failed';\n case 'conflict':\n return 'store-failed';\n case 'uncertain':\n return 'uncertain';\n case 'store-failed':\n return 'store-failed';\n case 'rejected-characters':\n return 'rejected-characters';\n }\n}\n\n/** What `resolvePassphraseForCreate` chose, and where the secret now lives. */\nexport interface CreatePassphraseResult {\n passphrase: string;\n source: DurableStore | 'env';\n origin: 'generated' | 'env';\n /** describeStoreLocation of the store, or `TENJIN_WALLET_PASSPHRASE` when nothing durable holds it. */\n location: string;\n /** false only for an env secret whose store write was uncertain or failed. */\n durable: boolean;\n /** Why the file store: the OS store probed absent (S4 line), or --insecure-storage. Absent otherwise. */\n fileReason?: 'no-keyring' | 'insecure-storage';\n /** durable:false only: the store the env secret could not be saved to (picks the passphraseNote wording). */\n attempted?: DurableStore;\n /** durable:false only: why it was not saved there (picks the passphraseNote wording). */\n notSaved?: Exclude<DurableWrite, 'stored' | 'already-stored'>;\n}\n\n/**\n * Is the platform's own store reachable, before create or repair picks a\n * target? `absent` is definite (no `secret-tool`, no D-Bus, no default\n * keychain, no PowerShell, or a platform with no OS store at all) and sends the\n * secret to the 0600 file. `uncertain` (killed at 3 s, refused, anything\n * unclear) is NOT absent: the store exists and may just be locked, so callers\n * refuse rather than fall to plaintext (S3). DPAPI has no lock, so its probe is\n * never `uncertain`: anything but a missing PowerShell is `available`.\n */\nexport async function probeDurableStore(\n deps: PassphraseDeps,\n): Promise<{ store: DurableStore; probe: StoreProbe; detail?: string }> {\n const store = storeFor(deps);\n if (store === null) {\n return { store: 'file', probe: 'absent', detail: 'this platform has no OS credential store' };\n }\n const result = await store.probe({ timeoutMs: timeoutsOf(deps).probeMs });\n return { store: store.source, ...result };\n}\n\n/**\n * Resolve the passphrase to ENCRYPT the new wallet at `address`. It NEVER\n * prompts (Q1): the secret is `TENJIN_WALLET_PASSPHRASE` when set, else 32\n * random bytes, chosen ONCE before any write. Users who want their own\n * passphrase set the variable.\n *\n * Where it goes: the file store with `insecureStorage`; otherwise the platform\n * store when its probe says available, the 0600 file when it says absent (S4),\n * and a refusal when it says uncertain (S3: a locked keychain is never routed\n * around). An env secret is saved durably too (Q2), so a one-shot agent install\n * with the variable set does not strand the wallet once the variable is gone.\n *\n * The write happens BEFORE the caller encrypts and is proven by reading it back\n * (storeDurablyDetailed), so a generated passphrase can never be lost between\n * generating it and persisting the encrypted key: a generated secret that is\n * not proven stored refuses the create. An env secret is still the user's to\n * keep, so its create goes ahead with `durable: false`. This path never touches\n * the legacy shared slot or any other wallet's entry.\n */\nexport async function resolvePassphraseForCreate(\n deps: PassphraseDeps,\n address: string,\n opts: { insecureStorage?: boolean } = {},\n): Promise<CreatePassphraseResult> {\n const fromEnv = envPassphrase(deps.env);\n const origin = fromEnv !== null ? 'env' : 'generated';\n const secret = fromEnv ?? randomBytes(32).toString('base64url');\n const account = walletStoreAccount(address);\n const envOnly = (\n attempted: DurableStore,\n notSaved: Exclude<DurableWrite, 'stored' | 'already-stored'>,\n ): CreatePassphraseResult => ({\n passphrase: secret,\n source: 'env',\n origin,\n location: 'TENJIN_WALLET_PASSPHRASE',\n durable: false,\n attempted,\n notSaved,\n });\n\n let target: DurableStore;\n let fileReason: CreatePassphraseResult['fileReason'];\n if (opts.insecureStorage === true) {\n target = 'file';\n fileReason = 'insecure-storage';\n } else {\n const probed = await probeDurableStore(deps);\n if (probed.probe === 'available') {\n target = probed.store;\n } else if (probed.probe === 'absent') {\n target = 'file';\n fileReason = 'no-keyring';\n } else {\n if (origin === 'env') return envOnly(probed.store, 'uncertain');\n throw new CliError(\n 'REFUSED',\n `The ${storeNoun(probed.store)} did not answer within ${Math.round(timeoutsOf(deps).probeMs / 1000)} s; it may be locked. No wallet was created.`,\n { fix: KEYCHAIN_LOCKED_FIX, details: unlockDetails('keychain_locked') },\n );\n }\n }\n\n const written = await storeDurablyDetailed(deps, target, address, secret);\n if (written.outcome === 'stored' || written.outcome === 'already-stored') {\n return {\n passphrase: secret,\n source: target,\n origin,\n location: describeStoreLocation(target, account, deps.dir),\n durable: true,\n ...(fileReason !== undefined ? { fileReason } : {}),\n };\n }\n if (origin === 'env') return envOnly(target, written.outcome);\n const detail = written.detail ?? `the ${storeNoun(target)} write failed`;\n if (target === 'file') {\n // Decision 6: there is no keychain to unlock here, so neither the fix nor\n // the details may point at one.\n const path = describeStoreLocation('file', account, deps.dir);\n throw new CliError(\n 'REFUSED',\n `Could not save the wallet passphrase to ${path} (${detail}); no wallet was created.`,\n {\n fix: FILE_STORE_FAILED_FIX(path),\n details: { passphraseStore: { kind: 'file-write-failed', path } },\n },\n );\n }\n throw new CliError(\n 'REFUSED',\n `Could not save the wallet passphrase to ${describeStoreLocation(target, account, deps.dir)} (${detail}); no wallet was created.`,\n { fix: KEYCHAIN_LOCKED_FIX, details: unlockDetails('keychain_locked', target) },\n );\n}\n\n/**\n * Where a store keeps `account`'s passphrase, in words an operator can find it\n * by. The file path shows the home directory as `~`.\n */\nexport function describeStoreLocation(store: DurableStore, account: string, dir?: string): string {\n switch (store) {\n case 'keychain':\n return `your macOS keychain (service ${KEYCHAIN_SERVICE}, account ${account})`;\n case 'secret-service':\n return `your Linux keyring (Secret Service, service ${KEYCHAIN_SERVICE}, account ${account})`;\n case 'dpapi':\n return `a DPAPI-encrypted file (passphrase.${account}.dpapi)`;\n case 'file':\n return tildePath(passphraseFilePathFor(account, dir));\n }\n}\n\n/** `path` with the home directory shown as `~`, as a person would type it. */\nfunction tildePath(path: string): string {\n const home = homedir();\n if (home.length > 1 && (path === home || path.startsWith(`${home}/`))) {\n return `~${path.slice(home.length)}`;\n }\n return path;\n}\n\n/** Ask for a passphrase at the hidden prompt (repair, and the `--replace` outgoing wallet). */\nexport function promptPassphrase(deps: PassphraseDeps, label: string): Promise<string> {\n return promptOf(deps)(label);\n}\n\n/**\n * macOS login keychain via the OS `security` tool — the same mechanism the GitHub\n * CLI uses. Reads use `-w`, so the secret comes back on stdout, never in argv.\n * Writes pipe an `add-generic-password` command to `security -i` over stdin so the\n * passphrase never appears in any argv either.\n */\nfunction keychainStore(deps: PassphraseDeps): PassphraseStore {\n const exec = deps.exec ?? defaultExecFor();\n return {\n source: 'keychain',\n async read(account, o) {\n try {\n const { stdout } = await exec(\n 'security',\n ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account, '-w'],\n undefined,\n callOpts(o),\n );\n const value = oneNewlineStripped(stdout);\n return value.length > 0 ? { kind: 'hit', value } : { kind: 'miss' };\n } catch (err) {\n return classifyStoreFailure('keychain', err);\n }\n },\n // The one backend that interpolates into a command line. base64url values\n // keep today's exact `-w '<value>'` line; any other printable-ASCII value is\n // sent as hex, so no character of it is ever syntax. Escaping is NOT a safe\n // alternative (backslash bites even inside single quotes there).\n storable: (value) => PRINTABLE_ASCII_RE.test(value),\n async store(account, value, o) {\n if (!ACCOUNT_ADDRESS_RE.test(account) || !PRINTABLE_ASCII_RE.test(value)) {\n throw new CliError('INTERNAL', 'Refusing to send this value to the keychain writer.');\n }\n const secret = BASE64URL_RE.test(value)\n ? `-w '${value}'`\n : `-X ${Buffer.from(value, 'utf8').toString('hex')}`;\n // No `-U` unless the caller proved the existing entry wrong (repair): a\n // plain add fails on a duplicate instead of overwriting it.\n const update = o?.update === true ? ' -U' : '';\n const command = `add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} ${secret}${update}\\n`;\n await exec('security', ['-i'], command, callOpts(o));\n },\n async remove(account, o) {\n try {\n // No secret transits here; plain argv is fine (and visible is harmless).\n await exec(\n 'security',\n ['delete-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account],\n undefined,\n callOpts(o),\n );\n return true;\n } catch {\n return false;\n }\n },\n async probe(o) {\n try {\n await exec('security', ['default-keychain'], undefined, callOpts(o));\n return { probe: 'available' };\n } catch (err) {\n const failure = classifyStoreFailure('keychain', err);\n if (failure.kind === 'absent') return { probe: 'absent', detail: failure.detail };\n return {\n probe: 'uncertain',\n ...('detail' in failure ? { detail: failure.detail } : {}),\n };\n }\n },\n };\n}\n\n// PowerShell scripts run via built-in Windows PowerShell 5.1 (zero dependency).\n// Each reads its input from stdin and writes its output to stdout, so the\n// passphrase and the blob transit ONLY stdin/stdout, never argv. The stored blob\n// is DPAPI-protected for the CurrentUser scope: it decrypts only as this user on\n// this machine, which is the protection class we want; it is NOT the passphrase in\n// plaintext.\nconst DPAPI_PROTECT_SCRIPT = [\n 'Add-Type -AssemblyName System.Security;',\n '$in = [Console]::In.ReadToEnd();',\n '$bytes = [System.Text.Encoding]::UTF8.GetBytes($in);',\n \"$prot = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser');\",\n '[Console]::Out.Write([Convert]::ToBase64String($prot));',\n].join(' ');\nconst DPAPI_UNPROTECT_SCRIPT = [\n 'Add-Type -AssemblyName System.Security;',\n '$in = [Console]::In.ReadToEnd();',\n '$blob = [Convert]::FromBase64String($in.Trim());',\n \"$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser');\",\n '[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain));',\n].join(' ');\n\nfunction powershellArgs(script: string): string[] {\n return ['-NoProfile', '-NonInteractive', '-Command', script];\n}\n\n/**\n * Windows DPAPI-protected files, via preinstalled PowerShell 5.1 (zero\n * dependency), one blob per account: `passphrase.<address>.dpapi` for wallet\n * accounts, legacy `passphrase.dpapi` for the pre-per-wallet slot. store():\n * protect the passphrase through DPAPI (CurrentUser) and write the base64 blob.\n * read(): a missing file is a miss; otherwise the blob is unprotected back to\n * the passphrase, and a failed unprotect is `locked` (unknown), never a miss.\n */\nfunction dpapiStore(deps: PassphraseDeps): PassphraseStore {\n const exec = deps.exec ?? defaultExecFor();\n const blobPathFor = (account: string): string =>\n account === LEGACY_ACCOUNT\n ? passphraseBlobPath(deps.dir)\n : passphraseBlobPathFor(account, deps.dir);\n return {\n source: 'dpapi',\n async read(account, o) {\n let blob: string;\n try {\n blob = await readFile(blobPathFor(account), 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'miss' }; // No blob yet: a miss, not an error.\n return { kind: 'locked', detail: 'the DPAPI passphrase file could not be read' };\n }\n try {\n const { stdout } = await exec(\n 'powershell.exe',\n powershellArgs(DPAPI_UNPROTECT_SCRIPT),\n blob,\n callOpts(o),\n );\n const value = stdout.replace(/\\r?\\n$/, '');\n return value.length > 0 ? { kind: 'hit', value } : { kind: 'miss' };\n } catch (err) {\n return classifyStoreFailure('dpapi', err);\n }\n },\n storable: readsBackFromStdout,\n async store(account, passphrase, o) {\n const { stdout } = await exec(\n 'powershell.exe',\n powershellArgs(DPAPI_PROTECT_SCRIPT),\n passphrase,\n callOpts(o),\n );\n const blob = stdout.replace(/\\r?\\n$/, '').trim();\n if (blob.length === 0) throw new StoreExecError('powershell.exe', { code: 0 });\n // DPAPI CurrentUser encryption is the real protection here; `mode` is inert\n // on win32 (writeFileAtomic drops it there) and only bites when a POSIX host\n // exercises this store in tests. The blob is ciphertext, not the passphrase.\n await writeFileAtomic(blobPathFor(account), blob, { mode: 0o600 });\n },\n async remove(account) {\n try {\n await unlink(blobPathFor(account));\n return true;\n } catch {\n return false;\n }\n },\n async probe(o) {\n try {\n await exec(\n 'powershell.exe',\n ['-NoProfile', '-NonInteractive', '-Command', '$null'],\n undefined,\n callOpts(o),\n );\n return { probe: 'available' };\n } catch (err) {\n // DPAPI has no lock state: the only thing a probe can learn is whether\n // powershell.exe exists. A slow cold start killed at the probe bound, or\n // any other answer, still means it does, so it is never `uncertain`\n // (which would refuse create and repair with an unlock fix that cannot\n // apply). A write that then fails is reported by the write itself.\n const failure = classifyStoreFailure('dpapi', err);\n if (failure.kind === 'absent') return { probe: 'absent', detail: failure.detail };\n return { probe: 'available' };\n }\n },\n };\n}\n\n/**\n * Desktop-Linux Secret Service via `secret-tool` (libsecret-tools). `secret-tool`\n * reads the secret from stdin when stdin is not a TTY, so the passphrase never\n * appears in argv. Headless Linux, WSL and CI usually have no Secret Service at\n * all: an absent `secret-tool` (ENOENT) or no D-Bus is `absent`, which is what\n * sends create to the 0600 file. A keyring that is there but does not answer is\n * `locked`, which is not.\n */\nfunction secretServiceStore(deps: PassphraseDeps): PassphraseStore {\n const exec = deps.exec ?? defaultExecFor();\n const read: PassphraseStore['read'] = async (account, o) => {\n try {\n const { stdout } = await exec(\n 'secret-tool',\n ['lookup', 'service', KEYCHAIN_SERVICE, 'account', account],\n undefined,\n callOpts(o),\n );\n const value = oneNewlineStripped(stdout);\n return value.length > 0 ? { kind: 'hit', value } : { kind: 'miss' };\n } catch (err) {\n return classifyStoreFailure('secret-service', err);\n }\n };\n return {\n source: 'secret-service',\n read,\n storable: readsBackFromStdout,\n async store(account, passphrase, o) {\n // secret-tool store replaces an existing item itself; `update` adds nothing here.\n await exec(\n 'secret-tool',\n [\n 'store',\n `--label=tenjin-cli wallet ${account}`,\n 'service',\n KEYCHAIN_SERVICE,\n 'account',\n account,\n ],\n passphrase,\n callOpts(o),\n );\n },\n async remove(account, o) {\n try {\n await exec(\n 'secret-tool',\n ['clear', 'service', KEYCHAIN_SERVICE, 'account', account],\n undefined,\n callOpts(o),\n );\n return true;\n } catch {\n return false;\n }\n },\n async probe(o) {\n const got = await read(PROBE_ACCOUNT, o);\n if (got.kind === 'hit' || got.kind === 'miss') return { probe: 'available' };\n if (got.kind === 'absent') return { probe: 'absent', detail: got.detail };\n return { probe: 'uncertain', detail: got.detail };\n },\n };\n}\n\n/**\n * The passphrase FILE store: `<dataDir>/passphrase.<address>.plain`, the\n * plaintext passphrase at 0600 in a 0700 dir, no trailing newline. Used only\n * where no OS store exists or with `--insecure-storage` (see the file header).\n * A first write is NO-CLOBBER, like the wallet file; only repair, after proving\n * the old value wrong, replaces one (`update`). fs calls are not killed, so the\n * per-call deadline is accepted and ignored. A read strips exactly one trailing\n * `\\n` (someone may have written it with `echo`) and nothing else: a secret\n * ending in other whitespace round-trips, and one ending in `\\n` is refused\n * before any write (`storable`), so a failed save never leaves a file that\n * reads back as a different secret.\n */\nfunction fileStore(deps: PassphraseDeps): PassphraseStore {\n const pathFor = (account: string): string => passphraseFilePathFor(account, deps.dir);\n return {\n source: 'file',\n async read(account) {\n try {\n const value = oneLfStripped(await readFile(pathFor(account), 'utf8'));\n return value.length > 0 ? { kind: 'hit', value } : { kind: 'miss' };\n } catch (err) {\n return classifyStoreFailure('file', err);\n }\n },\n // The read strips one trailing LF, so a value ending in one never reads back.\n storable: (value) => !value.endsWith('\\n'),\n async store(account, value, o) {\n const path = pathFor(account);\n const mode = { mode: 0o600, dirMode: 0o700 };\n if (o?.update === true) return writeFileAtomic(path, value, mode);\n try {\n await writeFileAtomicExclusive(path, value, mode);\n } catch (err) {\n // AN EMPTY FILE HOLDS NO SECRET. On Windows the exclusive write opens the\n // target itself before writing, so a crash in between leaves it empty;\n // it reads as a miss, and without this every later save (repair\n // included) would hit EEXIST forever. Replacing it loses nothing.\n if (!hasCode(err, 'EEXIST') || (await stat(path).catch(() => null))?.size !== 0) throw err;\n await writeFileAtomic(path, value, mode);\n }\n },\n async remove(account) {\n try {\n await unlink(pathFor(account));\n return true;\n } catch {\n return false;\n }\n },\n probe: async () => ({ probe: 'available' }),\n };\n}\n\n/** The per-call exec options for a store call: the deadline when one was given, else none. */\nfunction callOpts(o: StoreCallOptions | undefined): { timeoutMs?: number } | undefined {\n return o?.timeoutMs !== undefined ? { timeoutMs: o.timeoutMs } : undefined;\n}\n\n/**\n * Whether a value survives a read that strips one trailing newline (LF or\n * CRLF) from the store CLI's stdout: one that ends in CR or LF does not.\n */\nfunction readsBackFromStdout(value: string): boolean {\n return !/[\\r\\n]$/.test(value);\n}\n\n/**\n * Why `store`'s `storable` gate turned a value away, as a clause: the\n * keychain writer's printable-ASCII rule, or a line break at the end that the\n * other stores' reads strip, so the saved value would not read back.\n */\nexport function unstorableWhy(store: DurableStore): string {\n return store === 'keychain'\n ? 'the macOS keychain writer only stores printable ASCII passphrases'\n : `a passphrase that ends in a line break does not read back from the ${storeNoun(store)}`;\n}\n\n/** A store payload with exactly one optional trailing newline (LF or CRLF) stripped. */\nfunction oneNewlineStripped(stdout: string): string {\n return stdout.replace(/\\r?\\n$/, '');\n}\n\n/** File contents with exactly one trailing LF stripped. */\nfunction oneLfStripped(text: string): string {\n return text.endsWith('\\n') ? text.slice(0, -1) : text;\n}\n\n/** The env passphrase, non-empty and used exactly as given; null when unset/empty. */\nfunction envPassphrase(env: NodeJS.ProcessEnv): string | null {\n const value = env.TENJIN_WALLET_PASSPHRASE;\n return value !== undefined && value.length > 0 ? value : null;\n}\n\nfunction canPrompt(deps: PassphraseDeps): boolean {\n return deps.isTTY ?? Boolean(process.stdin.isTTY);\n}\n\nfunction promptOf(deps: PassphraseDeps): PromptFn {\n return deps.prompt ?? promptHidden;\n}\n\n/**\n * No source holds a passphrase (`passphrase_missing`). The message keeps its\n * prefix (install-wallet matches on it); `location` names the recorded store\n * that came back empty. The fix sends the PERSON to repair (B1): never \"set\n * TENJIN_WALLET_PASSPHRASE\", which invites an agent to ask for the value.\n */\nfunction noPassphraseError(location?: string): CliError {\n return new CliError(\n 'USAGE',\n location === undefined\n ? 'No wallet passphrase is available.'\n : `No wallet passphrase is available: ${location} has no entry for this wallet.`,\n { fix: REPAIR_IN_TERMINAL, details: unlockDetails('passphrase_missing') },\n );\n}\n\n/**\n * A store that exists but did not answer (`keychain_locked`): unknown, never a\n * block, and its fix is to unlock it, never plaintext or another passphrase\n * (S3). `detail` is the classified one (S2). It also rides in\n * `details.storeDetail` so verify can word its row without parsing this message.\n */\nfunction storeLockedError(\n store: DurableStore,\n account: string,\n detail: string,\n dir: string | undefined,\n recorded: boolean,\n): CliError {\n const where = describeStoreLocation(store, account, dir);\n return new CliError(\n 'USAGE',\n `The passphrase store ${recorded ? 'recorded ' : ''}for this wallet, ${where}, did not answer (${detail}).`,\n {\n fix: KEYCHAIN_LOCKED_FIX,\n details: { ...unlockDetails('keychain_locked', store), storeDetail: detail },\n },\n );\n}\n\n// Control bytes handled by the raw-mode reader, named to avoid literal control\n// characters in the source.\nconst CTRL_C = 0x03;\nconst CTRL_D = 0x04;\nconst BACKSPACE = 0x7f;\nconst BACKSPACE_ALT = 0x08;\n\n/**\n * Read one line of input without echoing it. The prompt label goes to stderr so\n * stdout stays the single JSON envelope; typed characters are consumed in raw\n * mode and never printed. Only ever called on a real TTY (canPrompt gates it),\n * so setRawMode is present; tests inject `prompt` and never reach this.\n */\nfunction promptHidden(label: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const stdin = process.stdin;\n const stderr = process.stderr;\n const wasRaw = stdin.isRaw;\n let value = '';\n\n const cleanup = (): void => {\n stdin.setRawMode?.(wasRaw ?? false);\n stdin.pause();\n stdin.removeListener('data', onData);\n };\n const onData = (chunk: Buffer | string): void => {\n for (const ch of chunk.toString('utf8')) {\n const code = ch.charCodeAt(0);\n if (ch === '\\n' || ch === '\\r' || code === CTRL_D) {\n // Enter or Ctrl-D: submit what we have.\n cleanup();\n stderr.write('\\n');\n resolve(value);\n return;\n }\n if (code === CTRL_C) {\n cleanup();\n stderr.write('\\n');\n reject(\n new CliError('USAGE', 'Passphrase entry was cancelled.', {\n fix: 'Run the command again, or set TENJIN_WALLET_PASSPHRASE.',\n }),\n );\n return;\n }\n if (code === BACKSPACE || code === BACKSPACE_ALT) {\n value = value.slice(0, -1);\n } else {\n value += ch;\n }\n }\n };\n\n stderr.write(label);\n stdin.setRawMode?.(true);\n stdin.resume();\n std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;AAIA,IAAM,SAAS;AACf,IAAM,SAAS;AACf,IAAM,YAAY;AAClB,IAAM,gBAAgB;AAQtB,SAAS,aAAa,OAAgC;AACpD,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,QAAQ,QAAQ;AACtB,UAAM,SAAS,QAAQ;AACvB,UAAM,SAAS,MAAM;AACrB,QAAI,QAAQ;AAEZ,UAAM,UAAU,MAAY;AAC1B,YAAM,aAAa,UAAU,KAAK;AAClC,YAAM,MAAM;AACZ,YAAM,eAAe,QAAQ,MAAM;AAAA,IACrC;AACA,UAAM,SAAS,CAAC,UAAiC;AAC/C,iBAAW,MAAM,MAAM,SAAS,MAAM,GAAG;AACvC,cAAM,OAAO,GAAG,WAAW,CAAC;AAC5B,YAAI,OAAO,QAAQ,OAAO,QAAQ,SAAS,QAAQ;AAEjD,kBAAQ;AACR,iBAAO,MAAM,IAAI;AACjB,kBAAQ,KAAK;AACb;AAAA,QACF;AACA,YAAI,SAAS,QAAQ;AACnB,kBAAQ;AACR,iBAAO,MAAM,IAAI;AACjB;AAAA,YACE,IAAI,SAAS,SAAS,mCAAmC;AAAA,cACvD,KAAK;AAAA,YACP,CAAC;AAAA,UACH;AACA;AAAA,QACF;AACA,YAAI,SAAS,aAAa,SAAS,eAAe;AAChD,kBAAQ,MAAM,MAAM,GAAG,EAAE;AAAA,QAC3B,OAAO;AACL,mBAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAEA,WAAO,MAAM,KAAK;AAClB,UAAM,aAAa,IAAI;AACvB,UAAM,OAAO;AACb,UAAM,GAAG,QAAQ,MAAM;AAAA,EACzB,CAAC;AACH;","names":[]}
@@ -1,27 +1,29 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  resolvePublicDestination
4
- } from "./chunk-EBVIKMCH.js";
4
+ } from "./chunk-JKKAIPTU.js";
5
5
  import {
6
6
  releaseUnchargedExposure
7
- } from "./chunk-AEG2PXBP.js";
7
+ } from "./chunk-V2LQLN5H.js";
8
8
  import {
9
9
  withFileLock
10
10
  } from "./chunk-MEFB5KHA.js";
11
11
  import {
12
12
  mask
13
- } from "./chunk-7QKHZQKW.js";
13
+ } from "./chunk-IADZOXKN.js";
14
14
  import {
15
15
  hasCode
16
16
  } from "./chunk-2I4QTOLB.js";
17
17
  import {
18
- USDC_ADDRESS,
18
+ USDC_ADDRESS
19
+ } from "./chunk-DW4YTVR3.js";
20
+ import {
19
21
  writeFileAtomic
20
- } from "./chunk-O2FRQ2L2.js";
22
+ } from "./chunk-7WEQQJLG.js";
21
23
  import {
22
24
  downloadsDir,
23
25
  paidLedgerPath
24
- } from "./chunk-SJLTEINJ.js";
26
+ } from "./chunk-OJNTCYQQ.js";
25
27
 
26
28
  // src/router/paid.ts
27
29
  import { randomBytes } from "node:crypto";
@@ -401,4 +403,4 @@ export {
401
403
  writeAll,
402
404
  createUniqueFile
403
405
  };
404
- //# sourceMappingURL=chunk-OK2TDZQU.js.map
406
+ //# sourceMappingURL=chunk-CISYM4EO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/paid.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { appendFile, mkdir, open, readFile, rm, type FileHandle } from 'node:fs/promises';\nimport { request as httpsRequest } from 'node:https';\nimport type { LookupFunction } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { resolvePublicDestination, type DestinationOptions } from '../lib/destination';\nimport { hasCode } from '../lib/errno';\nimport { withFileLock } from '../lib/lock';\nimport { downloadsDir, paidLedgerPath } from '../lib/paths';\nimport { mask } from '../lib/redact';\nimport { USDC_ADDRESS } from '../lib/usdc-balance';\nimport { releaseUnchargedExposure } from '../lib/wallet/spend';\n\n/**\n * WHAT A PAID ROUTER CALL BOUGHT, KEPT ON THIS MACHINE. One JSON line per paid\n * call in `~/.tenjin/paid/ledger.jsonl`: who was paid, for what, how much, the\n * settlement it carried and the files it saved. It is the user's own record\n * and the receipt `tenjin payments reconcile` resolves an unknown settlement\n * against. Nothing here can fail a lookup: every write swallows its own error.\n */\n\nexport type Settlement = 'settled' | 'unknown' | 'not_charged';\n\n/** The EIP-3009 authorization that was signed, enough to ask the token later\n * whether it was used. */\nexport interface SignedAuthorization {\n from: string;\n nonce: string;\n /** Unix seconds; after it the authorization can no longer be used. */\n validBefore: string;\n}\n\nexport interface PaidRecord {\n version: 1;\n ts: string;\n capabilityId: string;\n provider: string;\n /** The service's display name, when its decision or spec carried one. */\n label?: string;\n url: string;\n /** The input or query sent, masked and cut to {@link MAX_SENT_CHARS}. */\n sent: string;\n amountAtomic: string;\n txHash?: string;\n settlement: Settlement;\n savedFiles: string[];\n authorization?: SignedAuthorization;\n /** When reconcile last asked the chain about it, so a slow or rate-limited\n * RPC is not asked about the same record on every lookup. */\n lastCheckedAt?: string;\n}\n\nexport const MAX_SENT_CHARS = 4_096;\n\n/**\n * A JSON value with every object key and string leaf masked on its own. The\n * mask anchors on word boundaries, which a serialized string hides: after an\n * escaped `\\n` a key reads as `nsk-ant-…`, one word, and passes.\n */\nexport function maskDeep(value: unknown): unknown {\n if (typeof value === 'string') return mask(value);\n if (Array.isArray(value)) return value.map(maskDeep);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n mask(key),\n maskDeep(entry),\n ]),\n );\n }\n return value;\n}\n\n/** The input or query as it is recorded: secrets masked, then cut. */\nexport function recordedSent(sent: string): string {\n return mask(sent).slice(0, MAX_SENT_CHARS);\n}\n\nexport async function appendPaidRecord(dataDir: string, record: PaidRecord): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n // Under the lock reconcile rewrites with, so an append is never lost to it.\n await withFileLock(`${path}.lock`, () =>\n appendFile(path, `${JSON.stringify(record)}\\n`, { mode: 0o600 }),\n );\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/**\n * A JOB'S ROW, FINISHED IN PLACE. A paid call whose seller was still working\n * is recorded when it is paid, so a crash mid-poll loses no row; the files the\n * job later saved, and the settlement its last answer named, are written onto\n * that same row, found by its authorization's nonce, under the lock reconcile\n * rewrites with. One payment, one row. Never throws.\n */\nexport async function updatePaidRecord(\n dataDir: string,\n nonce: string,\n patch: { savedFiles?: string[]; txHash?: string },\n): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n const key = nonce.toLowerCase();\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n let found = false;\n const lines = current.map(({ line, record }) => {\n if (record?.authorization?.nonce.toLowerCase() !== key) return line;\n found = true;\n return JSON.stringify({\n ...record,\n ...(patch.savedFiles !== undefined ? { savedFiles: patch.savedFiles } : {}),\n ...(patch.txHash !== undefined && record.settlement === 'unknown'\n ? { txHash: patch.txHash, settlement: 'settled' }\n : {}),\n });\n });\n if (found) {\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n }\n });\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/** `authorizationState(address,bytes32)`: the first four bytes of its keccak-256. */\nconst AUTHORIZATION_STATE_SELECTOR = '0xe94a0102';\nconst WORD_RE = /^0x[0-9a-fA-F]{64}$/;\n/** How many unknown settlements one pass asks the chain about. */\nexport const MAX_RECONCILE_CHECKS = 3;\n/** How long a record the chain could not answer for waits before it is asked\n * about again by the lookup-time pass. */\nexport const RECHECK_MS = 10 * 60_000;\nconst RECONCILE_TIMEOUT_MS = 1_500;\n\n/**\n * Whether USDC on Base has used this authorization: true once a facilitator\n * settled it, false while it has not. Null when the RPC could not say.\n */\nexport async function authorizationUsed(\n authorization: SignedAuthorization,\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number; blockTag?: string } = {},\n): Promise<boolean | null> {\n const result = await rpcCall(\n rpcUrl,\n 'eth_call',\n [\n {\n to: USDC_ADDRESS,\n data: `${AUTHORIZATION_STATE_SELECTOR}${authorization.from.slice(2).toLowerCase().padStart(64, '0')}${authorization.nonce.slice(2).toLowerCase()}`,\n },\n opts.blockTag ?? 'latest',\n ],\n opts,\n );\n if (typeof result !== 'string' || !WORD_RE.test(result)) return null;\n return BigInt(result) !== 0n;\n}\n\n/**\n * The chain's own clock: the latest block's number and timestamp (seconds).\n * Expiry is decided against it, not this machine's clock, and the state is\n * read at that same block: a node that lags, or a clock running ahead, then\n * agrees with itself. Null when the RPC could not say.\n */\nexport async function latestBlock(\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},\n): Promise<{ tag: string; timestamp: number } | null> {\n const result = await rpcCall(rpcUrl, 'eth_getBlockByNumber', ['latest', false], opts);\n if (result === null || typeof result !== 'object') return null;\n const { number, timestamp } = result as { number?: unknown; timestamp?: unknown };\n if (typeof number !== 'string' || !/^0x[0-9a-fA-F]+$/.test(number)) return null;\n if (typeof timestamp !== 'string' || !/^0x[0-9a-fA-F]+$/.test(timestamp)) return null;\n return { tag: number, timestamp: Number(BigInt(timestamp)) };\n}\n\nasync function rpcCall(\n rpcUrl: string,\n method: string,\n params: unknown[],\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number },\n): Promise<unknown> {\n try {\n const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),\n signal: AbortSignal.timeout(opts.timeoutMs ?? RECONCILE_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return ((await res.json()) as { result?: unknown } | null)?.result ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface ReconcileOutcome {\n /** Records asked about in this pass. */\n checked: number;\n /** The authorization was used: the amount was charged. */\n settled: number;\n /** It expired unused: nothing was charged. */\n notCharged: number;\n /** Still unknown: not yet expired, no authorization on record, or the RPC\n * could not answer. */\n unknown: number;\n /** What the not-charged payments gave back to today's automatic budget. */\n releasedAtomic: string;\n}\n\n/**\n * RESOLVE \"SETTLEMENT UNKNOWN\" FROM THE CHAIN. A paid call whose seller never\n * confirmed settlement leaves a record marked `unknown`. Once the chain's\n * latest block is past its authorization's `validBefore`, the token's own\n * `authorizationState(from, nonce)` read AT THAT BLOCK is final: used means\n * charged, unused means it can never be charged, since no later block can\n * carry it. This machine's clock only decides whether the chain is worth\n * asking. At most `max` records are asked about per pass, and\n * a record the RPC cannot answer for stays unknown, stamped `lastCheckedAt`,\n * and is not asked about again for `recheckMs`.\n *\n * The chain is asked outside the lock; the file is re-read and rewritten under\n * it, so an append made meanwhile is kept.\n */\nexport async function reconcilePayments(\n dataDir: string,\n opts: {\n rpcUrl: string;\n fetchImpl?: typeof fetch;\n now?: () => number;\n max?: number;\n timeoutMs?: number;\n /** Defaults to {@link RECHECK_MS}; the command passes 0. */\n recheckMs?: number;\n },\n): Promise<ReconcileOutcome> {\n const path = paidLedgerPath(dataDir);\n const now = (opts.now ?? Date.now)();\n const records = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const open = records.filter(\n (entry): entry is { line: string; record: PaidRecord } =>\n entry.record !== null && entry.record.settlement === 'unknown',\n );\n const recheckMs = opts.recheckMs ?? RECHECK_MS;\n const due = open.filter(\n ({ record }) =>\n record.authorization !== undefined &&\n Number(record.authorization.validBefore) * 1_000 < now &&\n (record.lastCheckedAt === undefined || now - Date.parse(record.lastCheckedAt) >= recheckMs),\n );\n const answers = new Map<string, Settlement>();\n const asked = new Set<string>();\n let checked = 0;\n const rpc = {\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n };\n const block = due.length > 0 ? await latestBlock(opts.rpcUrl, rpc) : null;\n for (const { record } of due.slice(0, opts.max ?? MAX_RECONCILE_CHECKS)) {\n // Not past validBefore on the chain yet: not asked, and not stamped.\n if (block !== null && Number(record.authorization!.validBefore) >= block.timestamp) continue;\n checked += 1;\n asked.add(record.authorization!.nonce);\n if (block === null) continue;\n const used = await authorizationUsed(record.authorization!, opts.rpcUrl, {\n ...rpc,\n blockTag: block.tag,\n });\n if (used !== null) answers.set(record.authorization!.nonce, used ? 'settled' : 'not_charged');\n }\n // NOT CHARGED GIVES THE DAILY BUDGET BACK FIRST: exactly that payment's\n // exposure, by its nonce, while it is still inside the window that counted\n // it. Only then is the record marked; a release that could not be written\n // leaves it unknown, and the next pass asks again. A second release of the\n // same nonce finds nothing, so a retry never gives back twice.\n let releasedAtomic = 0n;\n for (const [nonce, answer] of [...answers]) {\n if (answer !== 'not_charged') continue;\n const released = await releaseUnchargedExposure(dataDir, nonce, {\n ...(opts.now !== undefined ? { now: opts.now } : {}),\n });\n if (released === null) answers.delete(nonce);\n else releasedAtomic += released;\n }\n if (asked.size > 0) {\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const lines = current.map(({ line, record }) => {\n const nonce =\n record?.settlement === 'unknown' && record.authorization !== undefined\n ? record.authorization.nonce\n : undefined;\n if (nonce === undefined || !asked.has(nonce)) return line;\n const answer = answers.get(nonce);\n const stamp = new Date(now).toISOString();\n return JSON.stringify(\n answer === undefined\n ? { ...record, lastCheckedAt: stamp }\n : { ...record, settlement: answer, lastCheckedAt: stamp, reconciledAt: stamp },\n );\n });\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n });\n }\n const settled = [...answers.values()].filter((value) => value === 'settled').length;\n return {\n checked,\n settled,\n notCharged: answers.size - settled,\n unknown: open.length - answers.size,\n releasedAtomic: releasedAtomic.toString(),\n };\n}\n\n/** Every paid record in the ledger, oldest first; a line that is not one is skipped. */\nexport async function readPaidRecords(dataDir: string): Promise<PaidRecord[]> {\n const raw = await readFile(paidLedgerPath(dataDir), 'utf8').catch(() => '');\n return parseLedger(raw).flatMap(({ record }) => (record === null ? [] : [record]));\n}\n\n/** Every line, and the record it holds when it is one; other lines ride along. */\nfunction parseLedger(raw: string): { line: string; record: PaidRecord | null }[] {\n return raw\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line) => {\n try {\n const value = JSON.parse(line) as PaidRecord;\n return { line, record: value !== null && value.version === 1 ? value : null };\n } catch {\n return { line, record: null };\n }\n });\n}\n\n/** The media a paid result links to, by the extension its path ends in. */\nconst MEDIA_EXTENSIONS = new Set([\n 'png',\n 'jpg',\n 'jpeg',\n 'webp',\n 'gif',\n 'svg',\n 'mp3',\n 'wav',\n 'm4a',\n 'ogg',\n 'mp4',\n 'webm',\n 'mov',\n]);\nexport const MAX_MEDIA_FILES = 5;\nexport const MAX_MEDIA_BYTES = 200 * 1024 * 1024;\nexport const MEDIA_TIMEOUT_MS = 60_000;\nconst MAX_REDIRECTS = 3;\nconst URL_RE = /https:\\/\\/[^\\s\"'<>\\\\]+/g;\n\n/** Every https URL in the result whose path ends in a media extension, in\n * order and without repeats, at most {@link MAX_MEDIA_FILES}. */\nexport function mediaUrlsIn(result: string, limit = MAX_MEDIA_FILES): string[] {\n const found: string[] = [];\n for (const match of result.matchAll(URL_RE)) {\n if (found.length >= limit) break;\n let url: URL;\n try {\n url = new URL(match[0]);\n } catch {\n continue;\n }\n const ext = url.pathname.split('.').pop()?.toLowerCase() ?? '';\n if (!url.pathname.includes('.') || !MEDIA_EXTENSIONS.has(ext)) continue;\n if (!found.includes(url.toString())) found.push(url.toString());\n }\n return found;\n}\n\n/** One GET the media download makes, connected to the address it validated. */\nexport interface PinnedTarget {\n url: URL;\n /** The address `resolvePublicDestination` checked; the socket goes here. */\n address: string;\n family: 4 | 6;\n}\n\nexport interface MediaResponse {\n status: number;\n location?: string;\n contentLength?: number;\n body: AsyncIterable<Uint8Array>;\n /** Drop the connection without reading the rest. */\n discard: () => void;\n}\n\nexport type MediaTransport = (target: PinnedTarget, signal: AbortSignal) => Promise<MediaResponse>;\n\nexport interface MediaDeps {\n /** Test seam; production connects with {@link pinnedGet}. */\n transport?: MediaTransport;\n destination?: DestinationOptions;\n now?: () => number;\n timeoutMs?: number;\n maxBytes?: number;\n /** What the call may still write, shared by every file it saves, side by\n * side or not: charged as each chunk is written, so a download still in\n * flight holds only what it wrote. A chunk that would take it below zero\n * stops that file, and a file that is not kept gives its bytes back. */\n budget?: { leftBytes: number };\n}\n\n/**\n * CONNECT TO THE ADDRESS THAT WAS CHECKED. `fetch` resolves the name again on\n * its own, so a host answering publicly to the check and privately a moment\n * later (DNS rebinding) would get the request. `node:https` with a `lookup`\n * that hands back the one validated address closes that: the socket goes to\n * it, and TLS still verifies the certificate against the URL's own host name.\n */\nexport const pinnedGet: MediaTransport = (target, signal) =>\n new Promise((resolve, reject) => {\n const req = httpsRequest(\n target.url,\n {\n method: 'GET',\n signal,\n lookup: pinnedLookup(target),\n },\n (res) => {\n const length = Number(res.headers['content-length']);\n const location = res.headers.location;\n resolve({\n status: res.statusCode ?? 0,\n ...(typeof location === 'string' ? { location } : {}),\n ...(Number.isFinite(length) ? { contentLength: length } : {}),\n body: res,\n discard: () => res.destroy(),\n });\n },\n );\n req.on('error', reject);\n req.end();\n });\n\n/** A `lookup` that answers every name with the one validated address. */\nexport function pinnedLookup(target: Pick<PinnedTarget, 'address' | 'family'>): LookupFunction {\n return ((_host: string, options: { all?: boolean }, callback: LookupCallback) => {\n if (options.all === true) {\n callback(null, [{ address: target.address, family: target.family }]);\n } else {\n callback(null, target.address, target.family);\n }\n }) as unknown as LookupFunction;\n}\n\ntype LookupCallback = (\n err: Error | null,\n address: string | { address: string; family: number }[],\n family?: number,\n) => void;\n\n/** A file the budget left too little room for. */\nconst CAPPED = Symbol('capped');\n/** A file a later try could save: the network, the file's server or this\n * disk failed, not a rule of ours. */\nconst FAILED = Symbol('failed');\n\n/**\n * Download each URL into the downloads dir, one at a time, each under its own\n * size cap and deadline, every hop of a redirect validated and connected to\n * the address it validated. Returns the paths that were written, whether the\n * budget left a file too little room (`capped`), and whether a download\n * failed in a way a later try could get past (`failed`); a later call could\n * save either. A URL that fails is skipped and never fails the call.\n */\nexport async function saveMedia(\n dataDir: string,\n stem: string,\n urls: string[],\n deps: MediaDeps = {},\n): Promise<{ saved: string[]; capped: boolean; failed: boolean }> {\n const saved: string[] = [];\n let capped = false;\n let failed = false;\n for (const [index, url] of urls.entries()) {\n const path = await saveOne(dataDir, `${stem}-${index + 1}`, url, deps);\n if (path === CAPPED) capped = true;\n else if (path === FAILED) failed = true;\n else if (path !== null) saved.push(path);\n }\n return { saved, capped, failed };\n}\n\n/** Statuses a later try could get past: the server, not the link, failed. */\nconst RETRYABLE_STATUS = new Set([408, 429]);\n\nasync function saveOne(\n dataDir: string,\n stem: string,\n raw: string,\n deps: MediaDeps,\n): Promise<string | typeof CAPPED | typeof FAILED | null> {\n const transport = deps.transport ?? pinnedGet;\n const cap = deps.maxBytes ?? MAX_MEDIA_BYTES;\n const { budget } = deps;\n if (budget !== undefined && budget.leftBytes <= 0) return CAPPED;\n // What this file has taken from the call's budget, given back unless kept.\n let charged = 0;\n let kept = false;\n // Stopped by the call's budget, not by the file's own cap.\n let capped = false;\n // Stopped by a rule of ours (an address, the file's cap), which no later\n // try gets past.\n let refused = false;\n const signal = AbortSignal.timeout(deps.timeoutMs ?? MEDIA_TIMEOUT_MS);\n let target = raw;\n let path: string | null = null;\n try {\n let res: MediaResponse | null = null;\n for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {\n const pinned = await resolvePublicDestination(target, deps.destination ?? {}).catch(\n (err: unknown) => {\n refused = true;\n throw err;\n },\n );\n res = await transport(pinned, signal);\n if (res.status < 300 || res.status >= 400 || res.location === undefined) break;\n res.discard();\n target = new URL(res.location, target).toString();\n res = null;\n }\n if (res === null || res.status < 200 || res.status >= 300) {\n res?.discard();\n const status = res?.status ?? 0;\n return status >= 500 || RETRYABLE_STATUS.has(status) ? FAILED : null;\n }\n const declared = res.contentLength ?? 0;\n if (declared > cap) {\n res.discard();\n return null;\n }\n if (budget !== undefined && declared > budget.leftBytes) {\n res.discard();\n return CAPPED;\n }\n const ext = new URL(target).pathname.split('.').pop()?.toLowerCase() ?? 'bin';\n const file = await createUniqueFile(\n downloadsDir(dataDir),\n `${stem}-${(deps.now ?? Date.now)()}`,\n MEDIA_EXTENSIONS.has(ext) ? ext : 'bin',\n );\n path = file.path;\n let size = 0;\n try {\n for await (const chunk of res.body) {\n size += chunk.byteLength;\n if (size > cap) {\n res.discard();\n refused = true;\n throw new Error('media over the size cap');\n }\n // Charged before the write, in the same turn as the check, so files\n // saving side by side can never write past the call's cap between\n // them.\n if (budget !== undefined) {\n if (chunk.byteLength > budget.leftBytes) {\n res.discard();\n capped = true;\n throw new Error(\"media over the call's download cap\");\n }\n budget.leftBytes -= chunk.byteLength;\n charged += chunk.byteLength;\n }\n await writeAll(file.handle, chunk);\n }\n } finally {\n await file.handle.close();\n }\n kept = true;\n return path;\n } catch {\n if (path !== null) await rm(path, { force: true }).catch(() => undefined);\n return capped ? CAPPED : refused ? null : FAILED;\n } finally {\n if (budget !== undefined && !kept) budget.leftBytes += charged;\n }\n}\n\n/**\n * EVERY BYTE, OR A THROW. `FileHandle.write` may write fewer bytes than it was\n * handed and says so only in `bytesWritten`; a caller that ignores it saves a\n * file with a hole in it. A write that makes no progress is an error.\n */\nexport async function writeAll(\n handle: Pick<FileHandle, 'write'>,\n bytes: Uint8Array,\n): Promise<void> {\n let offset = 0;\n while (offset < bytes.byteLength) {\n const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset);\n if (bytesWritten <= 0) throw new Error('the file write made no progress');\n offset += bytesWritten;\n }\n}\n\n/**\n * A NEW FILE, NEVER ANOTHER CALL'S. The name is the stem plus a random suffix,\n * created with an exclusive flag, so two lookups finishing in the same\n * millisecond each get their own file; a clash is retried with a new suffix.\n */\nexport async function createUniqueFile(\n directory: string,\n stem: string,\n ext: string,\n): Promise<{ path: string; handle: FileHandle }> {\n await mkdir(directory, { recursive: true });\n const safe = stem.replace(/[^A-Za-z0-9_-]+/g, '-').slice(0, 100) || 'lookup';\n for (let attempt = 0; ; attempt += 1) {\n const path = join(directory, `${safe}-${randomBytes(4).toString('hex')}.${ext}`);\n try {\n return { path, handle: await open(path, 'wx', 0o600) };\n } catch (err) {\n if (attempt >= 4 || !hasCode(err, 'EEXIST')) throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,YAAY,OAAO,MAAM,UAAU,UAA2B;AACvE,SAAS,WAAW,oBAAoB;AAExC,SAAS,SAAS,YAAY;AAiDvB,IAAM,iBAAiB;AAOvB,SAAS,SAAS,OAAyB;AAChD,MAAI,OAAO,UAAU,SAAU,QAAO,KAAK,KAAK;AAChD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,QAAQ;AACnD,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAAO;AAAA,MACZ,OAAO,QAAQ,KAAgC,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM;AAAA,QACrE,KAAK,GAAG;AAAA,QACR,SAAS,KAAK;AAAA,MAChB,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,aAAa,MAAsB;AACjD,SAAO,KAAK,IAAI,EAAE,MAAM,GAAG,cAAc;AAC3C;AAEA,eAAsB,iBAAiB,SAAiB,QAAmC;AACzF,MAAI;AACF,UAAM,OAAO,eAAe,OAAO;AACnC,UAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAE3D,UAAM;AAAA,MAAa,GAAG,IAAI;AAAA,MAAS,MACjC,WAAW,MAAM,GAAG,KAAK,UAAU,MAAM,CAAC;AAAA,GAAM,EAAE,MAAM,IAAM,CAAC;AAAA,IACjE;AAAA,EACF,QAAQ;AAAA,EAER;AACF;AASA,eAAsB,iBACpB,SACA,OACA,OACe;AACf,MAAI;AACF,UAAM,OAAO,e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EAAG,OAAM,IAAI,MAAM,iCAAiC;AACxE,cAAU;AAAA,EACZ;AACF;AAOA,eAAsB,iBACpB,WACA,MACA,KAC+C;AAC/C,QAAM,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAC1C,QAAM,OAAO,KAAK,QAAQ,oBAAoB,GAAG,EAAE,MAAM,GAAG,GAAG,KAAK;AACpE,WAAS,UAAU,KAAK,WAAW,GAAG;AACpC,UAAM,OAAO,KAAK,WAAW,GAAG,IAAI,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,IAAI,GAAG,EAAE;AAC/E,QAAI;AACF,aAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,MAAM,MAAM,GAAK,EAAE;AAAA,IACvD,SAAS,KAAK;AACZ,UAAI,WAAW,KAAK,CAAC,QAAQ,KAAK,QAAQ,EAAG,OAAM;AAAA,IACrD;AAAA,EACF;AACF;","names":["open"]}
@@ -1,10 +1,10 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  FileClientChannelStorage
4
- } from "./chunk-YHKXNYTB.js";
4
+ } from "./chunk-QF3LSMGS.js";
5
5
  import {
6
6
  payerDir
7
- } from "./chunk-PAYV4XUA.js";
7
+ } from "./chunk-HDPUXS3Z.js";
8
8
 
9
9
  // src/router/channel-credit.ts
10
10
  import { readdir } from "node:fs/promises";
@@ -26,4 +26,4 @@ async function channelCredit(dataDir, address) {
26
26
  export {
27
27
  channelCredit
28
28
  };
29
- //# sourceMappingURL=chunk-VFMQTSXG.js.map
29
+ //# sourceMappingURL=chunk-D3ZURCG7.js.map