tenjin-cli 0.1.0-alpha.33 → 0.1.0-alpha.35
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.
- package/NOTICE.md +110 -0
- package/README.md +87 -81
- package/dist/{_esm-BIN7VY2L.js → _esm-2KST7HQ7.js} +7 -7
- package/dist/alive-5TV22PNF.js +51 -0
- package/dist/auth-XI7BJFLW.js +47 -0
- package/dist/{auto-update-Y24UL56V.js → auto-update-7L24KDWA.js} +4 -5
- package/dist/balance-DFHC6XEU.js +71 -0
- package/dist/{ccip-DHDFKTQV.js → ccip-HOW3DZYF.js} +4 -4
- package/dist/chunk-24XKUN2S.js +202 -0
- package/dist/chunk-24XKUN2S.js.map +1 -0
- package/dist/chunk-2L7TDGLV.js +56 -0
- package/dist/chunk-2L7TDGLV.js.map +1 -0
- package/dist/{chunk-C2Q76BVM.js → chunk-2U7H35IP.js} +29 -7
- package/dist/chunk-2U7H35IP.js.map +1 -0
- package/dist/chunk-2W4DQQUU.js +176 -0
- package/dist/chunk-2W4DQQUU.js.map +1 -0
- package/dist/{chunk-LRW6S53P.js → chunk-34SAECKZ.js} +35 -11
- package/dist/chunk-34SAECKZ.js.map +1 -0
- package/dist/{chunk-2I4QTOLB.js → chunk-3MZ7DYRO.js} +1 -1
- package/dist/chunk-3MZ7DYRO.js.map +1 -0
- package/dist/{chunk-RVPYTUP4.js → chunk-3Y2EHT4F.js} +13 -9
- package/dist/chunk-3Y2EHT4F.js.map +1 -0
- package/dist/chunk-3Y6BHIN6.js +169 -0
- package/dist/chunk-3Y6BHIN6.js.map +1 -0
- package/dist/{chunk-4K7TQHNP.js → chunk-3YPL6T3P.js} +17 -33
- package/dist/chunk-3YPL6T3P.js.map +1 -0
- package/dist/{chunk-E7SW44LM.js → chunk-44MVIRZH.js} +121 -6
- package/dist/chunk-44MVIRZH.js.map +1 -0
- package/dist/chunk-45MMSBHA.js +321 -0
- package/dist/chunk-45MMSBHA.js.map +1 -0
- package/dist/{chunk-3FMZGI7I.js → chunk-4CE6TMI5.js} +1 -1
- package/dist/chunk-4CE6TMI5.js.map +1 -0
- package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
- package/dist/chunk-4MBCJFY4.js.map +1 -0
- package/dist/chunk-4TPL54KW.js +227 -0
- package/dist/chunk-4TPL54KW.js.map +1 -0
- package/dist/chunk-54ELBTKE.js +1615 -0
- package/dist/chunk-54ELBTKE.js.map +1 -0
- package/dist/{chunk-NDGZDTSJ.js → chunk-5F4OB5B3.js} +115 -57
- package/dist/chunk-5F4OB5B3.js.map +1 -0
- package/dist/chunk-5HN4KVQU.js +3348 -0
- package/dist/chunk-5HN4KVQU.js.map +1 -0
- package/dist/{chunk-ZDZERB6L.js → chunk-5J4E5GYI.js} +572 -407
- package/dist/chunk-5J4E5GYI.js.map +1 -0
- package/dist/{chunk-ZNNXRNFD.js → chunk-5N4GGUBN.js} +48 -6
- package/dist/chunk-5N4GGUBN.js.map +1 -0
- package/dist/chunk-5USBZ2MU.js +58 -0
- package/dist/chunk-5USBZ2MU.js.map +1 -0
- package/dist/chunk-64WOMNYR.js +183 -0
- package/dist/chunk-64WOMNYR.js.map +1 -0
- package/dist/{chunk-ILNIZ5I2.js → chunk-65RS4LQS.js} +1825 -1715
- package/dist/chunk-65RS4LQS.js.map +1 -0
- package/dist/{chunk-IE7P2BZE.js → chunk-6QMDUDF2.js} +3 -3
- package/dist/{chunk-IADZOXKN.js → chunk-7SLOTLO7.js} +19 -697
- package/dist/chunk-7SLOTLO7.js.map +1 -0
- package/dist/{chunk-WFSPCCVW.js → chunk-7V25UAQO.js} +99 -99
- package/dist/{chunk-WFSPCCVW.js.map → chunk-7V25UAQO.js.map} +1 -1
- package/dist/chunk-BGA4DO5M.js +719 -0
- package/dist/chunk-BGA4DO5M.js.map +1 -0
- package/dist/chunk-BVP7YK2J.js +706 -0
- package/dist/chunk-BVP7YK2J.js.map +1 -0
- package/dist/chunk-C265QIMJ.js +83 -0
- package/dist/chunk-C265QIMJ.js.map +1 -0
- package/dist/{chunk-XQJXNMSB.js → chunk-CRG54LEB.js} +1 -1
- package/dist/chunk-CRG54LEB.js.map +1 -0
- package/dist/{chunk-KG3D7FIF.js → chunk-CZJOMUBP.js} +2 -2
- package/dist/{chunk-36RVGZNY.js → chunk-D6M3ZK66.js} +22 -39
- package/dist/chunk-D6M3ZK66.js.map +1 -0
- package/dist/{chunk-3UCIG4TG.js → chunk-DI4QAGRZ.js} +1 -11
- package/dist/chunk-DI4QAGRZ.js.map +1 -0
- package/dist/{chunk-JKKAIPTU.js → chunk-DIH2G3YG.js} +47 -10
- package/dist/chunk-DIH2G3YG.js.map +1 -0
- package/dist/chunk-DJ36BM62.js +78 -0
- package/dist/chunk-DJ36BM62.js.map +1 -0
- package/dist/chunk-DTEWAVNE.js +114 -0
- package/dist/chunk-DTEWAVNE.js.map +1 -0
- package/dist/chunk-F2KJAJ7T.js +13 -0
- package/dist/chunk-F2KJAJ7T.js.map +1 -0
- package/dist/{chunk-BF4XHEQK.js → chunk-F3QPGYOY.js} +6 -6
- package/dist/chunk-F3QPGYOY.js.map +1 -0
- package/dist/{chunk-3GNJXKIT.js → chunk-F43CV6UC.js} +2 -2
- package/dist/{chunk-J57UC3DD.js → chunk-FKVJKLPI.js} +3 -3
- package/dist/{chunk-V2LQLN5H.js → chunk-FYFHH7V5.js} +59 -8
- package/dist/{chunk-V2LQLN5H.js.map → chunk-FYFHH7V5.js.map} +1 -1
- package/dist/chunk-GAJC4BQZ.js +1096 -0
- package/dist/chunk-GAJC4BQZ.js.map +1 -0
- package/dist/{chunk-DOQGNFHM.js → chunk-GH5UKMZD.js} +2 -12
- package/dist/{chunk-DOQGNFHM.js.map → chunk-GH5UKMZD.js.map} +1 -1
- package/dist/{chunk-WYXUQGOL.js → chunk-HAZAN4UM.js} +7 -6
- package/dist/chunk-HAZAN4UM.js.map +1 -0
- package/dist/chunk-HI5XQOX2.js +393 -0
- package/dist/chunk-HI5XQOX2.js.map +1 -0
- package/dist/chunk-HKGUKAQW.js +488 -0
- package/dist/chunk-HKGUKAQW.js.map +1 -0
- package/dist/{chunk-SO3XRZPX.js → chunk-HPRVFJPM.js} +6 -6
- package/dist/{chunk-L6JEXB3E.js → chunk-HQR4BWKX.js} +3 -131
- package/dist/chunk-HQR4BWKX.js.map +1 -0
- package/dist/chunk-HZKANST2.js +177 -0
- package/dist/chunk-HZKANST2.js.map +1 -0
- package/dist/{chunk-UUGOUOVT.js → chunk-I557SAOM.js} +8 -2
- package/dist/chunk-I557SAOM.js.map +1 -0
- package/dist/{chunk-TC2WZLSC.js → chunk-IGLWLH73.js} +8 -7
- package/dist/chunk-IGLWLH73.js.map +1 -0
- package/dist/chunk-ILWCKCOI.js +58 -0
- package/dist/chunk-ILWCKCOI.js.map +1 -0
- package/dist/{chunk-2GP3HRYK.js → chunk-INSIW65E.js} +182 -182
- package/dist/{chunk-MPZUYCAP.js → chunk-IULCDMVG.js} +12 -1
- package/dist/chunk-IULCDMVG.js.map +1 -0
- package/dist/{chunk-INTFHMU4.js → chunk-IVNSUAVC.js} +25 -26
- package/dist/chunk-IVNSUAVC.js.map +1 -0
- package/dist/chunk-JDQZCREI.js +87 -0
- package/dist/chunk-JDQZCREI.js.map +1 -0
- package/dist/chunk-JHFFUVON.js +1050 -0
- package/dist/chunk-JHFFUVON.js.map +1 -0
- package/dist/{chunk-RL5UUDT4.js → chunk-JNUKLSMZ.js} +3 -3
- package/dist/chunk-JTILUN4W.js +2933 -0
- package/dist/chunk-JTILUN4W.js.map +1 -0
- package/dist/{chunk-OJNTCYQQ.js → chunk-JTX3BUDK.js} +37 -53
- package/dist/chunk-JTX3BUDK.js.map +1 -0
- package/dist/{chunk-X5ZBP3IY.js → chunk-JUUBBBY5.js} +2 -2
- package/dist/chunk-JUUBBBY5.js.map +1 -0
- package/dist/chunk-JWAK7JQB.js +15 -0
- package/dist/chunk-JWAK7JQB.js.map +1 -0
- package/dist/{chunk-UXZONNEQ.js → chunk-K5KNGC4I.js} +34 -31
- package/dist/chunk-K5KNGC4I.js.map +1 -0
- package/dist/chunk-KAQ4Q3TO.js +135 -0
- package/dist/chunk-KAQ4Q3TO.js.map +1 -0
- package/dist/chunk-KFVJYLVL.js +125 -0
- package/dist/chunk-KFVJYLVL.js.map +1 -0
- package/dist/chunk-KGUE5AVX.js +69 -0
- package/dist/chunk-KGUE5AVX.js.map +1 -0
- package/dist/{chunk-FVIGCDSV.js → chunk-KLDMLWXT.js} +11 -85
- package/dist/chunk-KLDMLWXT.js.map +1 -0
- package/dist/chunk-KNKDMTHU.js +453 -0
- package/dist/chunk-KNKDMTHU.js.map +1 -0
- package/dist/chunk-LDA6TAYQ.js +95 -0
- package/dist/chunk-LDA6TAYQ.js.map +1 -0
- package/dist/chunk-LWSSIZOY.js +347 -0
- package/dist/chunk-LWSSIZOY.js.map +1 -0
- package/dist/{chunk-ZURZHELF.js → chunk-MAHNZA6C.js} +158 -41
- package/dist/chunk-MAHNZA6C.js.map +1 -0
- package/dist/chunk-MEWZCIA6.js +220 -0
- package/dist/chunk-MEWZCIA6.js.map +1 -0
- package/dist/{chunk-2SNUOHAT.js → chunk-MEZJ3I63.js} +49 -1
- package/dist/chunk-MEZJ3I63.js.map +1 -0
- package/dist/chunk-MJDO4EXD.js +353 -0
- package/dist/chunk-MJDO4EXD.js.map +1 -0
- package/dist/chunk-NJA6NT3A.js +6595 -0
- package/dist/chunk-NJA6NT3A.js.map +1 -0
- package/dist/{chunk-LHHMV4GU.js → chunk-NVSKJPRC.js} +1 -1
- package/dist/{chunk-LHHMV4GU.js.map → chunk-NVSKJPRC.js.map} +1 -1
- package/dist/{chunk-4YOZGGTZ.js → chunk-OC7K2DVZ.js} +5 -5
- package/dist/chunk-OC7K2DVZ.js.map +1 -0
- package/dist/chunk-ODRPASFP.js +2078 -0
- package/dist/chunk-ODRPASFP.js.map +1 -0
- package/dist/chunk-OJJFANO6.js +133 -0
- package/dist/chunk-OJJFANO6.js.map +1 -0
- package/dist/{chunk-JNJWBTU2.js → chunk-OQWPRFAC.js} +332 -882
- package/dist/chunk-OQWPRFAC.js.map +1 -0
- package/dist/chunk-P4I7BFNJ.js +11 -0
- package/dist/chunk-P4I7BFNJ.js.map +1 -0
- package/dist/{chunk-SNNSAGMT.js → chunk-P6YQWIT2.js} +4058 -4039
- package/dist/chunk-P6YQWIT2.js.map +1 -0
- package/dist/{chunk-JRGFKVAZ.js → chunk-PETQ5WEA.js} +2 -2
- package/dist/{chunk-HMWYAUA6.js → chunk-Q6RSJCXB.js} +29 -69
- package/dist/chunk-Q6RSJCXB.js.map +1 -0
- package/dist/{chunk-U3IKUGRP.js → chunk-QKEUKBRK.js} +17 -23
- package/dist/chunk-QKEUKBRK.js.map +1 -0
- package/dist/{chunk-2RWB7RKE.js → chunk-QKYUCITR.js} +174 -5814
- package/dist/chunk-QKYUCITR.js.map +1 -0
- package/dist/chunk-QQDPRTLP.js +127 -0
- package/dist/chunk-QQDPRTLP.js.map +1 -0
- package/dist/chunk-QQYCYAKI.js +79 -0
- package/dist/chunk-QQYCYAKI.js.map +1 -0
- package/dist/chunk-R4KDH477.js +1064 -0
- package/dist/chunk-R4KDH477.js.map +1 -0
- package/dist/chunk-R5TR2DIK.js +119 -0
- package/dist/chunk-R5TR2DIK.js.map +1 -0
- package/dist/chunk-R62PKTAG.js +66 -0
- package/dist/chunk-R62PKTAG.js.map +1 -0
- package/dist/{chunk-BFDQ4WNW.js → chunk-RFZA7PSM.js} +4 -5
- package/dist/chunk-RFZA7PSM.js.map +1 -0
- package/dist/chunk-RGCPELQN.js +219 -0
- package/dist/chunk-RGCPELQN.js.map +1 -0
- package/dist/chunk-RGVCOG2S.js +910 -0
- package/dist/chunk-RGVCOG2S.js.map +1 -0
- package/dist/chunk-SOLNJ3AZ.js +209 -0
- package/dist/chunk-SOLNJ3AZ.js.map +1 -0
- package/dist/chunk-TFT2X7SH.js +77 -0
- package/dist/chunk-TFT2X7SH.js.map +1 -0
- package/dist/chunk-TUCKEEXE.js +2 -0
- package/dist/chunk-TVWCLUBI.js +293 -0
- package/dist/chunk-TVWCLUBI.js.map +1 -0
- package/dist/chunk-U4TRWSVE.js +78 -0
- package/dist/chunk-U4TRWSVE.js.map +1 -0
- package/dist/chunk-UIB33QQP.js +379 -0
- package/dist/chunk-UIB33QQP.js.map +1 -0
- package/dist/chunk-V6GIVALQ.js +1889 -0
- package/dist/chunk-V6GIVALQ.js.map +1 -0
- package/dist/chunk-VHXCPXUS.js +366 -0
- package/dist/chunk-VHXCPXUS.js.map +1 -0
- package/dist/{chunk-HGZEPQUT.js → chunk-VU6GMWF6.js} +17 -8
- package/dist/chunk-VU6GMWF6.js.map +1 -0
- package/dist/chunk-VWZYE3NC.js +8415 -0
- package/dist/chunk-VWZYE3NC.js.map +1 -0
- package/dist/{chunk-AGMVASXZ.js → chunk-W2GXIARJ.js} +88 -11
- package/dist/chunk-W2GXIARJ.js.map +1 -0
- package/dist/chunk-W4G3K3V7.js +288 -0
- package/dist/chunk-W4G3K3V7.js.map +1 -0
- package/dist/chunk-W74LJ5OT.js +588 -0
- package/dist/chunk-W74LJ5OT.js.map +1 -0
- package/dist/chunk-W7ELYLYK.js +233 -0
- package/dist/chunk-W7ELYLYK.js.map +1 -0
- package/dist/{chunk-BPMWXTFX.js → chunk-WFZX352D.js} +7 -7
- package/dist/chunk-WXA3WTPF.js +20 -0
- package/dist/chunk-WXA3WTPF.js.map +1 -0
- package/dist/chunk-XRGFH7FI.js +454 -0
- package/dist/chunk-XRGFH7FI.js.map +1 -0
- package/dist/chunk-XSCGUO2U.js +330 -0
- package/dist/chunk-XSCGUO2U.js.map +1 -0
- package/dist/chunk-XWROSMI5.js +1039 -0
- package/dist/chunk-XWROSMI5.js.map +1 -0
- package/dist/chunk-Y2EXZ47H.js +40 -0
- package/dist/chunk-Y2EXZ47H.js.map +1 -0
- package/dist/chunk-YJGEVBKZ.js +47 -0
- package/dist/chunk-YJGEVBKZ.js.map +1 -0
- package/dist/{chunk-6CMM6YCB.js → chunk-YWWMISDY.js} +2 -2
- package/dist/{chunk-WXA2BWTE.js → chunk-ZCT5DJ3G.js} +2 -48
- package/dist/chunk-ZCT5DJ3G.js.map +1 -0
- package/dist/chunk-ZEYA2WWX.js +982 -0
- package/dist/chunk-ZEYA2WWX.js.map +1 -0
- package/dist/chunk-ZRC7Z5X3.js +82 -0
- package/dist/chunk-ZRC7Z5X3.js.map +1 -0
- package/dist/{chunk-3AIHRXKO.js → chunk-ZS7JIUJ3.js} +12 -10
- package/dist/chunk-ZS7JIUJ3.js.map +1 -0
- package/dist/{clack-EZ7TDWQU.js → clack-Q4RNC5VE.js} +2 -6
- package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
- package/dist/claude-install-BAUSJMW3.js +64 -0
- package/dist/{cli-E36SPKBW.js → cli-QY4KKA3D.js} +632 -150
- package/dist/cli-QY4KKA3D.js.map +1 -0
- package/dist/client-3YQKORVK.js +710 -0
- package/dist/client-3YQKORVK.js.map +1 -0
- package/dist/{codex-event-ZO2GEFE6.js → codex-event-EUTCAOTQ.js} +3 -5
- package/dist/{codex-host-KECJVTA2.js → codex-host-ZON3S6HU.js} +7 -7
- package/dist/{codex-install-HQZDGFXW.js → codex-install-HZV2DOAB.js} +242 -88
- package/dist/codex-install-HZV2DOAB.js.map +1 -0
- package/dist/config-QZOBMTEL.js +57 -0
- package/dist/config-names-Z5NZD5R2.js +224 -0
- package/dist/config-names-Z5NZD5R2.js.map +1 -0
- package/dist/config-rules-YOYHS6YL.js +55 -0
- package/dist/config-subagents-WQV2ZAD5.js +362 -0
- package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
- package/dist/connect-YDWTYU4B.js +1020 -0
- package/dist/connect-YDWTYU4B.js.map +1 -0
- package/dist/core-0a66n3e7-TTP554XV.js +127 -0
- package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
- package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
- package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
- package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
- package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
- package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
- package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
- package/dist/core-zg882d22-LKV5DZYW.js +37 -0
- package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
- package/dist/decision-QSKHOGCO.js +145 -0
- package/dist/{doctor-I6XQEKWD.js → doctor-ZWJXRD75.js} +162 -148
- package/dist/doctor-ZWJXRD75.js.map +1 -0
- package/dist/{env-proxy-R6ZMLQTT.js → env-proxy-XLSLHBKQ.js} +2 -2
- package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js → ethersCompat-Df4a6QIZ-K3DMHR6Y.js} +5 -5
- package/dist/explicit-ME2NRADQ.js +371 -0
- package/dist/explicit-ME2NRADQ.js.map +1 -0
- package/dist/flush-stdio-NYIJ3QXT.js +18 -0
- package/dist/fund-VF7TLDJH.js +722 -0
- package/dist/fund-VF7TLDJH.js.map +1 -0
- package/dist/hook-command-VZ27MGWO.js +49 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
- package/dist/hosts/claude/tenjin/hooks/hook-data.ts +152 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
- package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
- package/dist/hosts/claude/tenjin/hooks/register.tsx +527 -56
- package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
- package/dist/hosts/claude/tenjin/types/index.d.ts +144 -1
- package/dist/{hosts-DVQJ32QC.js → hosts-3EMTVM4H.js} +7 -6
- package/dist/index.js +18 -15
- package/dist/index.js.map +1 -1
- package/dist/install-ZA7L2UF3.js +115 -0
- package/dist/install-funding-JDGYTF72.js +30 -0
- package/dist/install-identity-FFAYEFLX.js +30 -0
- package/dist/{install-wallet-5M4OTYLX.js → install-wallet-2SFOVE3Q.js} +68 -53
- package/dist/install-wallet-2SFOVE3Q.js.map +1 -0
- package/dist/mcp-36S6MK3C.js +67642 -0
- package/dist/mcp-36S6MK3C.js.map +1 -0
- package/dist/new-install-5L4GY3LN.js +51 -0
- package/dist/{package-IJFGMWEV.js → package-BONDXSV3.js} +2 -2
- package/dist/{passphrase-IFTDS3CU.js → passphrase-T4ULBN4M.js} +16 -12
- package/dist/{paths-XCSAKISU.js → paths-O2KDWZ76.js} +18 -28
- package/dist/pay-CMV5KL74.js +74 -0
- package/dist/{payments-HFPPWHTV.js → payments-Z6UBZL4Z.js} +36 -26
- package/dist/payments-Z6UBZL4Z.js.map +1 -0
- package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
- package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
- package/dist/{redact-D7ASVWKL.js → redact-LOTHE5TS.js} +2 -8
- package/dist/redact-LOTHE5TS.js.map +1 -0
- package/dist/routing-quote-AHLAREXR.js +40 -0
- package/dist/routing-quote-AHLAREXR.js.map +1 -0
- package/dist/run-JH7ELYAM.js +88 -0
- package/dist/run-JH7ELYAM.js.map +1 -0
- package/dist/runtime-2GX4ALJP.js +410 -0
- package/dist/runtime-2GX4ALJP.js.map +1 -0
- package/dist/runtime-activate-IDQ2NCSP.js +39 -0
- package/dist/runtime-activate-IDQ2NCSP.js.map +1 -0
- package/dist/{runtime-fetch-ZSSSK72Y.js → runtime-fetch-6LOBHBEN.js} +4 -4
- package/dist/runtime-fetch-6LOBHBEN.js.map +1 -0
- package/dist/runtime-launchers-YAPKCBHV.js +31 -0
- package/dist/runtime-launchers-YAPKCBHV.js.map +1 -0
- package/dist/{runtime-layout-WIDILZ6K.js → runtime-layout-QHZQJV7C.js} +5 -4
- package/dist/runtime-layout-QHZQJV7C.js.map +1 -0
- package/dist/runtime-place-4POL4KK4.js +37 -0
- package/dist/runtime-place-4POL4KK4.js.map +1 -0
- package/dist/runtime-provenance-MNJGVBV2.js +12 -0
- package/dist/runtime-provenance-MNJGVBV2.js.map +1 -0
- package/dist/{secp256k1-ZZZT2CAX.js → secp256k1-N5P2GVGF.js} +3 -3
- package/dist/secp256k1-N5P2GVGF.js.map +1 -0
- package/dist/{send-GCVEAQKL.js → send-ELXFKEKY.js} +35 -32
- package/dist/send-ELXFKEKY.js.map +1 -0
- package/dist/status-FXUFWJDM.js +404 -0
- package/dist/status-FXUFWJDM.js.map +1 -0
- package/dist/{status-line-OPCXDHL2.js → status-line-IH5JBWBC.js} +51 -43
- package/dist/status-line-IH5JBWBC.js.map +1 -0
- package/dist/streamableHttp-CP2ZQBIK.js +768 -0
- package/dist/streamableHttp-CP2ZQBIK.js.map +1 -0
- package/dist/{uninstall-BAWRBXXQ.js → uninstall-LJZUKM4D.js} +76 -76
- package/dist/uninstall-LJZUKM4D.js.map +1 -0
- package/dist/update-EUIX72IX.js +68 -0
- package/dist/update-EUIX72IX.js.map +1 -0
- package/dist/usage-EKDC7LUC.js +180 -0
- package/dist/usage-EKDC7LUC.js.map +1 -0
- package/dist/{usdc-VG4CIOUK.js → usdc-YIHK2OMC.js} +8 -12
- package/dist/usdc-YIHK2OMC.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-DOFTEIJV.js → viemAdapter-By13KInL-PRLSIESK.js} +5 -5
- package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
- package/dist/wallet-HSW757W6.js +80 -0
- package/dist/wallet-HSW757W6.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +1433 -818
- package/docs/agent-permissions.md +88 -155
- package/docs/router-reference.md +236 -0
- package/docs/safety-model.md +31 -33
- package/docs/subagents-internals.md +97 -0
- package/docs/subagents.md +348 -0
- package/docs/troubleshooting.md +10 -6
- package/package.json +12 -8
- package/scripts/installers/install.sh +7 -1
- package/dist/alive-GSOWKUOY.js +0 -38
- package/dist/chunk-2I4QTOLB.js.map +0 -1
- package/dist/chunk-2M2VPI2E.js +0 -560
- package/dist/chunk-2M2VPI2E.js.map +0 -1
- package/dist/chunk-2RWB7RKE.js.map +0 -1
- package/dist/chunk-2SNUOHAT.js.map +0 -1
- package/dist/chunk-3623BLPV.js +0 -184
- package/dist/chunk-3623BLPV.js.map +0 -1
- package/dist/chunk-36RVGZNY.js.map +0 -1
- package/dist/chunk-3AIHRXKO.js.map +0 -1
- package/dist/chunk-3FMZGI7I.js.map +0 -1
- package/dist/chunk-3UCIG4TG.js.map +0 -1
- package/dist/chunk-4K7TQHNP.js.map +0 -1
- package/dist/chunk-4LMUQMBH.js +0 -29
- package/dist/chunk-4LMUQMBH.js.map +0 -1
- package/dist/chunk-4USCZ2NI.js +0 -228
- package/dist/chunk-4USCZ2NI.js.map +0 -1
- package/dist/chunk-4YOZGGTZ.js.map +0 -1
- package/dist/chunk-62KNUYWD.js +0 -111
- package/dist/chunk-62KNUYWD.js.map +0 -1
- package/dist/chunk-A5GKIG5O.js +0 -2037
- package/dist/chunk-A5GKIG5O.js.map +0 -1
- package/dist/chunk-AGMVASXZ.js.map +0 -1
- package/dist/chunk-BF4XHEQK.js.map +0 -1
- package/dist/chunk-BFDQ4WNW.js.map +0 -1
- package/dist/chunk-C2Q76BVM.js.map +0 -1
- package/dist/chunk-CEXSOI5R.js +0 -808
- package/dist/chunk-CEXSOI5R.js.map +0 -1
- package/dist/chunk-E7SW44LM.js.map +0 -1
- package/dist/chunk-EDJWHDDL.js +0 -33
- package/dist/chunk-EDJWHDDL.js.map +0 -1
- package/dist/chunk-FVIGCDSV.js.map +0 -1
- package/dist/chunk-GTTUCOPD.js +0 -105
- package/dist/chunk-GTTUCOPD.js.map +0 -1
- package/dist/chunk-HDPUXS3Z.js +0 -122
- package/dist/chunk-HDPUXS3Z.js.map +0 -1
- package/dist/chunk-HGGWCP7W.js +0 -120
- package/dist/chunk-HGGWCP7W.js.map +0 -1
- package/dist/chunk-HGZEPQUT.js.map +0 -1
- package/dist/chunk-HMWYAUA6.js.map +0 -1
- package/dist/chunk-IADZOXKN.js.map +0 -1
- package/dist/chunk-ILNIZ5I2.js.map +0 -1
- package/dist/chunk-INTFHMU4.js.map +0 -1
- package/dist/chunk-JKKAIPTU.js.map +0 -1
- package/dist/chunk-JNJWBTU2.js.map +0 -1
- package/dist/chunk-KM7RY2ZS.js +0 -246
- package/dist/chunk-KM7RY2ZS.js.map +0 -1
- package/dist/chunk-KOGZDMHO.js +0 -21
- package/dist/chunk-KOGZDMHO.js.map +0 -1
- package/dist/chunk-L6JEXB3E.js.map +0 -1
- package/dist/chunk-LRW6S53P.js.map +0 -1
- package/dist/chunk-LXAYUOXI.js +0 -511
- package/dist/chunk-LXAYUOXI.js.map +0 -1
- package/dist/chunk-MEFB5KHA.js +0 -59
- package/dist/chunk-MEFB5KHA.js.map +0 -1
- package/dist/chunk-MPZUYCAP.js.map +0 -1
- package/dist/chunk-NDGZDTSJ.js.map +0 -1
- package/dist/chunk-OJNTCYQQ.js.map +0 -1
- package/dist/chunk-P3LFTKE7.js +0 -58
- package/dist/chunk-P3LFTKE7.js.map +0 -1
- package/dist/chunk-QXP3Z3JN.js.map +0 -1
- package/dist/chunk-RVPYTUP4.js.map +0 -1
- package/dist/chunk-SNNSAGMT.js.map +0 -1
- package/dist/chunk-TC2WZLSC.js.map +0 -1
- package/dist/chunk-TKPF35W6.js +0 -29
- package/dist/chunk-TKPF35W6.js.map +0 -1
- package/dist/chunk-U3IKUGRP.js.map +0 -1
- package/dist/chunk-UUGOUOVT.js.map +0 -1
- package/dist/chunk-UXZONNEQ.js.map +0 -1
- package/dist/chunk-WXA2BWTE.js.map +0 -1
- package/dist/chunk-WYXUQGOL.js.map +0 -1
- package/dist/chunk-X5ZBP3IY.js.map +0 -1
- package/dist/chunk-XKESD27X.js +0 -10
- package/dist/chunk-XKESD27X.js.map +0 -1
- package/dist/chunk-XQJXNMSB.js.map +0 -1
- package/dist/chunk-Y527D4TV.js +0 -56
- package/dist/chunk-Y527D4TV.js.map +0 -1
- package/dist/chunk-ZDZERB6L.js.map +0 -1
- package/dist/chunk-ZNNXRNFD.js.map +0 -1
- package/dist/chunk-ZURZHELF.js.map +0 -1
- package/dist/cli-E36SPKBW.js.map +0 -1
- package/dist/codex-install-HQZDGFXW.js.map +0 -1
- package/dist/config-HY2E4GGW.js +0 -55
- package/dist/doctor-I6XQEKWD.js.map +0 -1
- package/dist/fund-2QRO7OJL.js +0 -378
- package/dist/fund-2QRO7OJL.js.map +0 -1
- package/dist/hook-command-2UBCSZG6.js +0 -43
- package/dist/install-ILUX5C4A.js +0 -107
- package/dist/install-identity-TZKGY6LQ.js +0 -31
- package/dist/install-wallet-5M4OTYLX.js.map +0 -1
- package/dist/mcp-LE4DUS22.js +0 -14127
- package/dist/mcp-LE4DUS22.js.map +0 -1
- package/dist/pay-WCG3IH4R.js +0 -55
- package/dist/payments-HFPPWHTV.js.map +0 -1
- package/dist/plugin-registration-PZFI5GZW.js +0 -68
- package/dist/runtime-UZOKSUZX.js +0 -1321
- package/dist/runtime-UZOKSUZX.js.map +0 -1
- package/dist/send-GCVEAQKL.js.map +0 -1
- package/dist/status-HCVAOCN7.js +0 -150
- package/dist/status-HCVAOCN7.js.map +0 -1
- package/dist/status-line-OPCXDHL2.js.map +0 -1
- package/dist/uninstall-BAWRBXXQ.js.map +0 -1
- package/dist/update-CACXLQLR.js +0 -56
- package/dist/wallet-QL4UUXEZ.js +0 -55
- /package/dist/{_esm-BIN7VY2L.js.map → _esm-2KST7HQ7.js.map} +0 -0
- /package/dist/{alive-GSOWKUOY.js.map → alive-5TV22PNF.js.map} +0 -0
- /package/dist/{auto-update-Y24UL56V.js.map → auth-XI7BJFLW.js.map} +0 -0
- /package/dist/{ccip-DHDFKTQV.js.map → auto-update-7L24KDWA.js.map} +0 -0
- /package/dist/{clack-EZ7TDWQU.js.map → balance-DFHC6XEU.js.map} +0 -0
- /package/dist/{claude-cli-2YKABJJZ.js.map → ccip-HOW3DZYF.js.map} +0 -0
- /package/dist/{chunk-IE7P2BZE.js.map → chunk-6QMDUDF2.js.map} +0 -0
- /package/dist/{chunk-KG3D7FIF.js.map → chunk-CZJOMUBP.js.map} +0 -0
- /package/dist/{chunk-3GNJXKIT.js.map → chunk-F43CV6UC.js.map} +0 -0
- /package/dist/{chunk-J57UC3DD.js.map → chunk-FKVJKLPI.js.map} +0 -0
- /package/dist/{chunk-SO3XRZPX.js.map → chunk-HPRVFJPM.js.map} +0 -0
- /package/dist/{chunk-2GP3HRYK.js.map → chunk-INSIW65E.js.map} +0 -0
- /package/dist/{chunk-RL5UUDT4.js.map → chunk-JNUKLSMZ.js.map} +0 -0
- /package/dist/{chunk-JRGFKVAZ.js.map → chunk-PETQ5WEA.js.map} +0 -0
- /package/dist/{codex-event-ZO2GEFE6.js.map → chunk-TUCKEEXE.js.map} +0 -0
- /package/dist/{chunk-BPMWXTFX.js.map → chunk-WFZX352D.js.map} +0 -0
- /package/dist/{chunk-6CMM6YCB.js.map → chunk-YWWMISDY.js.map} +0 -0
- /package/dist/{codex-host-KECJVTA2.js.map → clack-Q4RNC5VE.js.map} +0 -0
- /package/dist/{config-HY2E4GGW.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
- /package/dist/{env-proxy-R6ZMLQTT.js.map → claude-install-BAUSJMW3.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js.map → codex-event-EUTCAOTQ.js.map} +0 -0
- /package/dist/{hook-command-2UBCSZG6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
- /package/dist/{hosts-DVQJ32QC.js.map → config-QZOBMTEL.js.map} +0 -0
- /package/dist/{install-ILUX5C4A.js.map → config-rules-YOYHS6YL.js.map} +0 -0
- /package/dist/{install-identity-TZKGY6LQ.js.map → decision-QSKHOGCO.js.map} +0 -0
- /package/dist/{package-IJFGMWEV.js.map → env-proxy-XLSLHBKQ.js.map} +0 -0
- /package/dist/{passphrase-IFTDS3CU.js.map → ethersCompat-Df4a6QIZ-K3DMHR6Y.js.map} +0 -0
- /package/dist/{paths-XCSAKISU.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
- /package/dist/{pay-WCG3IH4R.js.map → hook-command-VZ27MGWO.js.map} +0 -0
- /package/dist/{plugin-registration-PZFI5GZW.js.map → hosts-3EMTVM4H.js.map} +0 -0
- /package/dist/{redact-D7ASVWKL.js.map → install-ZA7L2UF3.js.map} +0 -0
- /package/dist/{runtime-fetch-ZSSSK72Y.js.map → install-funding-JDGYTF72.js.map} +0 -0
- /package/dist/{runtime-layout-WIDILZ6K.js.map → install-identity-FFAYEFLX.js.map} +0 -0
- /package/dist/{secp256k1-ZZZT2CAX.js.map → new-install-5L4GY3LN.js.map} +0 -0
- /package/dist/{update-CACXLQLR.js.map → package-BONDXSV3.js.map} +0 -0
- /package/dist/{usdc-VG4CIOUK.js.map → passphrase-T4ULBN4M.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-DOFTEIJV.js.map → paths-O2KDWZ76.js.map} +0 -0
- /package/dist/{wallet-QL4UUXEZ.js.map → pay-CMV5KL74.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/wallet/store.ts","../src/lib/wallet/local.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/pbkdf2.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/accounts/generatePrivateKey.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/accounts/toAccount.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/accounts/utils/sign.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/accounts/utils/signAuthorization.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/accounts/utils/signMessage.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/accounts/utils/signTransaction.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/accounts/utils/signTypedData.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/accounts/privateKeyToAccount.ts","../node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/src/utils.ts","../node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/src/aes.ts","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/scrypt.ts","../node_modules/.pnpm/ox@0.14.30_typescript@6.0.3_zod@4.6.7/node_modules/ox/core/Keystore.ts","../src/lib/wallet/keystore-kdf.ts","../src/lib/wallet/index.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport * as Keystore from 'ox/Keystore';\nimport { CliError } from '../errors';\nimport { writeFileAtomicExclusive } from '../atomic-json';\nimport { hasCode } from '../errno';\nimport { walletPath } from '../paths';\nimport { unlockDetails } from '../wallet-unlock';\nimport { ADDRESS_RE } from '../ids';\n\n/**\n * A 0x-prefixed 32-byte hex private key (case-insensitive). Defined once, in the\n * hook-safe `wallet-unlock.ts`, so the hooks' wallet facts and `loadCredential`\n * test exactly the same thing; re-exported here for the wallet layer.\n */\nexport { PRIVATE_KEY_RE } from '../wallet-unlock';\n\n/**\n * The at-rest shape of a Keystore v3 document (Web3 Secret Storage). Validated\n * structurally on read so an obviously-corrupt keystore fails as\n * WALLET_INVALID_KEY before we ever ask for a passphrase; the real integrity\n * check is the keystore's own MAC, verified by ox at decrypt time. `kdfparams`\n * stays an open object because scrypt and pbkdf2 carry different fields and only\n * ox needs to interpret them.\n */\nconst KeystoreV3Schema = z.object({\n crypto: z.object({\n cipher: z.literal('aes-128-ctr'),\n ciphertext: z.string(),\n cipherparams: z.object({ iv: z.string() }),\n kdf: z.enum(['scrypt', 'pbkdf2']),\n kdfparams: z.record(z.string(), z.unknown()),\n mac: z.string(),\n }),\n id: z.string(),\n version: z.literal(3),\n});\n\n/** The wallet-record schema this build writes and reads. Anything higher on disk\n * was written by a newer CLI; see `readWalletRecord`. */\nexport const WALLET_SCHEMA_VERSION = 2;\n\n/**\n * The persisted wallet record (schema v2). The private key is NEVER stored in\n * cleartext: `keystore` is a Keystore v3 document (scrypt + AES-128-CTR) and the\n * key is recovered only by decrypting it with the wallet passphrase. `address`\n * stays top-level in cleartext ON PURPOSE so `show`/`balance` keep working\n * without a passphrase; signing decrypts, and so does `doctor` when it can reach\n * a passphrase without prompting. The `provider`\n * discriminator keeps the schema from implying every future wallet embeds a\n * keystore. Validated on read (a corrupt file is WALLET_INVALID_KEY, never a\n * silent partial parse).\n */\nexport const WalletRecordSchema = z.object({\n schemaVersion: z.literal(WALLET_SCHEMA_VERSION),\n provider: z.literal('local'),\n address: z.string().regex(ADDRESS_RE, 'expected a 0x-prefixed 20-byte address'),\n keystore: KeystoreV3Schema,\n createdAt: z.string(),\n});\nexport type WalletRecord = Omit<z.infer<typeof WalletRecordSchema>, 'keystore'> & {\n keystore: Keystore.Keystore;\n};\n\nexport async function walletFileExists(dir: string): Promise<boolean> {\n return (await walletFileMode(dir)) !== null;\n}\n\n/** File permission bits (`mode & 0o777`), or null when the wallet file is absent. */\nexport async function walletFileMode(dir: string): Promise<number | null> {\n try {\n return (await stat(walletPath(dir))).mode & 0o777;\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return null;\n throw err;\n }\n}\n\n/** Read + validate the wallet record; null when absent, WALLET_INVALID_KEY when corrupt. */\nexport async function readWalletRecord(dir: string): Promise<WalletRecord | null> {\n const path = walletPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return null;\n throw new CliError('WALLET_INVALID_KEY', `Could not read the wallet file at ${path}.`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n details: unlockDetails('wallet_corrupt'),\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('WALLET_INVALID_KEY', `The wallet file at ${path} is not valid JSON.`, {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n cause: err,\n details: unlockDetails('wallet_corrupt'),\n });\n }\n // A pre-encryption record (schema v1 stored the raw key). There is no in-place\n // migration: the old key must be swept and a fresh encrypted wallet created.\n if (isPreEncryptionRecord(json)) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} predates encrypted storage.`,\n {\n fix: `Move ${path} aside and run \\`tenjin wallet create\\`; sweep any funds from the old address first.`,\n details: unlockDetails('wallet_corrupt'),\n },\n );\n }\n // A NEWER CLI's record is a downgrade, not a corruption, and must be caught\n // BEFORE the generic parse failure below: that failure says to move the file\n // aside and run `wallet create`, which on a downgrade abandons a funded wallet.\n // CONTRACT_MISMATCH is the API layer's code for a schema version skew.\n const newer = newerSchemaVersion(json);\n if (newer !== null) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,\n {\n fix: 'Upgrade with `tenjin update`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds.',\n },\n );\n }\n const parsed = WalletRecordSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} is not a valid wallet record.`,\n {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n details: parsed.error.issues,\n },\n );\n }\n return parsed.data as WalletRecord;\n}\n\n/**\n * The one WALLET_EXISTS error, shared by the create pre-check and the exclusive\n * write's race loser so the two surfaces can never drift apart.\n */\nexport function walletExistsError(dir: string, cause?: unknown): CliError {\n const path = walletPath(dir);\n return new CliError('WALLET_EXISTS', `A wallet already exists at ${path}.`, {\n fix: `Run \\`tenjin wallet create --replace\\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable — never delete the credential-store entry, or the wallet's funds are stranded.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n/**\n * Persist a validated record at 0600 in a 0700 dir, NO-CLOBBER. The exclusive\n * write — not an earlier existence check — is the authority: two concurrent\n * `create` runs can both pass a pre-check, but only one can win the atomic\n * commit; the loser surfaces as WALLET_EXISTS instead of silently overwriting\n * (and losing) a non-recoverable key.\n */\nexport async function writeWalletRecord(dir: string, record: WalletRecord): Promise<void> {\n const validated = WalletRecordSchema.parse(record);\n const path = walletPath(dir);\n try {\n await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n if (hasCode(err, 'EEXIST')) throw walletExistsError(dir, err);\n throw err;\n }\n}\n\n/** The schema version of a record from a future CLI, or null when this build reads it. */\nfunction newerSchemaVersion(json: unknown): number | null {\n if (typeof json !== 'object' || json === null) return null;\n const v = (json as Record<string, unknown>).schemaVersion;\n // Integral only: `2.5` is not a schema we will ship, and calling it \"from the\n // future\" would send the operator into an upgrade loop. Integrality rather than\n // SAFE integrality, because an absurd-but-whole version is still a version, and\n // the alternative branch tells them to move the wallet aside and recreate it.\n return typeof v === 'number' && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;\n}\n\n/** A cleartext-key record from before encrypted storage: schema v1 or a bare `privateKey`. */\nfunction isPreEncryptionRecord(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) return false;\n const rec = json as Record<string, unknown>;\n return rec.schemaVersion === 1 || 'privateKey' in rec;\n}\n","import { link, readdir, stat, unlink } from 'node:fs/promises';\nimport { fsyncDir } from '../atomic-json';\nimport { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';\nimport type { PrivateKeyAccount } from 'viem/accounts';\nimport type { Address, Hex } from 'viem';\nimport * as Keystore from 'ox/Keystore';\nimport { CliError } from '../errors';\nimport { deriveKeystoreKey, type KeystoreDerivationOptions } from './keystore-kdf';\nimport { hasCode } from '../errno';\nimport { archivedWalletPath, passphraseFilePathFor, walletPath } from '../paths';\nimport { readPassphraseRecord, writePassphraseRecord } from '../passphrase-record';\nimport {\n ENV_PASSPHRASE_WRONG,\n FILE_STORE_FAILED_FIX,\n KEYCHAIN_LOCKED_FIX,\n REPAIR_CLAUSE,\n REPAIR_IN_TERMINAL,\n unlockDetails,\n unlockReasonOf,\n type DurableStore,\n type SigningSource,\n} from '../wallet-unlock';\nimport {\n PRIVATE_KEY_RE,\n WALLET_SCHEMA_VERSION,\n readWalletRecord,\n walletFileMode,\n writeWalletRecord,\n type WalletRecord,\n} from './store';\nimport {\n STORE_TIMEOUTS,\n describeStoreLocation,\n probeDurableStore,\n readStoredPassphrase,\n resolvePassphrase,\n storeDurablyDetailed,\n storeNoun,\n toStoreOutcome,\n unstorableWhy,\n walletStoreAccount,\n type PassphraseDeps,\n type PassphraseSource,\n type ResolvedPassphrase,\n type StorePassphraseOutcome,\n} from './passphrase';\nimport type {\n TenjinSigner,\n WalletDescription,\n WalletDiagnostics,\n WalletProvider,\n WalletVerification,\n} from './provider';\n\n/** Passphrase seams the local provider forwards to the resolver (env comes from `deps.env`). */\nexport type PassphraseOverrides = Omit<PassphraseDeps, 'env'>;\n\n/**\n * Said once per provider instance per keystore: TENJIN_WALLET_PASSPHRASE does\n * not open the wallet, a saved passphrase did, and signing went ahead with it.\n */\nexport interface WalletWarning {\n code: 'env_passphrase_wrong';\n message: typeof ENV_PASSPHRASE_WRONG;\n}\n\nexport interface LocalProviderDeps {\n dir: string;\n env: NodeJS.ProcessEnv;\n /** Test seam for keychain exec / TTY prompt / platform during decryption. */\n passphrase?: PassphraseOverrides;\n /** Bounds only pure KDF work; credential-store migration remains unchanged. */\n derivation?: KeystoreDerivationOptions;\n /** Fired at most once per provider instance per keystore id, including on a cache hit. */\n onWarning?: (w: WalletWarning) => void;\n}\n\nexport const isWindows = process.platform === 'win32';\nexport const KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\n\n/**\n * A one-shot decrypt cache. The CLI is a single invocation, so a signer derived\n * once (scrypt is deliberately slow) is reused for the rest of the process.\n * Keyed by the keystore's unique id, so distinct wallets never collide.\n * `envShadowed` remembers that a wrong TENJIN_WALLET_PASSPHRASE was passed over\n * to get there, so a provider that hits the cache still says so once.\n */\nconst signerCache = new Map<string, { account: PrivateKeyAccount; envShadowed: boolean }>();\n\n/**\n * The local provider: a viem account whose key comes from the env\n * override or the encrypted wallet file. `describe()` returns just the address\n * and posture WITHOUT a passphrase (the address is stored cleartext on purpose);\n * `getSigner()` is the single door to key material a caller can SIGN with.\n * `verify()` also decrypts, but returns a verdict rather than the key.\n *\n * Each instance warns once per keystore that a wrong TENJIN_WALLET_PASSPHRASE\n * was passed over, even when another instance decrypted first and this one\n * only hit the cache: the routing payer's provider must still hear it when the\n * request tool's provider unlocked the wallet.\n */\nexport function createLocalProvider(deps: LocalProviderDeps): WalletProvider {\n const warned = new Set<string>();\n const warnOnce = (keystoreId: string): void => {\n if (warned.has(keystoreId)) return;\n warned.add(keystoreId);\n deps.onWarning?.({ code: 'env_passphrase_wrong', message: ENV_PASSPHRASE_WRONG });\n };\n return {\n id: 'local',\n async describe(): Promise<WalletDescription> {\n const cred = await credentialOrThrow(deps);\n return {\n // A file credential's address is stored cleartext and returned as-is —\n // no decryption. An env credential derives (and thereby validates) its\n // key. getSigner is where a file wallet's key/address match is checked.\n address: cred.source === 'env' ? accountFromKey(cred.key, 'env').address : cred.address,\n provider: 'local',\n credentialSource: cred.source,\n policyEnforcement: 'client-only',\n };\n },\n async getSigner(): Promise<TenjinSigner> {\n const cred = await credentialOrThrow(deps);\n const account = await accountForSigning(cred, deps, warnOnce);\n return {\n address: account.address,\n signMessage: (args) => account.signMessage({ message: args.message }),\n signTypedData: (args) => account.signTypedData(args),\n signTransaction: (tx) => account.signTransaction(tx),\n };\n },\n diagnostics(): Promise<WalletDiagnostics> {\n return localWalletDiagnostics(deps);\n },\n verify(): Promise<WalletVerification> {\n return verifyLocalWallet(deps);\n },\n };\n}\n\n/** What decrypting a keystore with one passphrase proved. */\ntype Opened =\n | { kind: 'ok'; account: PrivateKeyAccount }\n | { kind: 'wrong'; cause: unknown }\n /** Decrypts, but to a key that is not this wallet's: a tampered file. `derived` is null for a key off the curve. */\n | { kind: 'mismatch'; derived: Address | null; cause?: unknown };\n\n/**\n * THE decrypt-and-compare, shared by signing, verify, `--replace` and repair:\n * derive (scrypt), decrypt (MAC-checked), then require the key to derive the\n * stored address. A cancelled or timed-out derivation is rethrown, never read\n * as a wrong passphrase: it says nothing about the passphrase, and must never\n * trigger a migration or a \"wrong\" verdict.\n */\nasync function openKeystoreAccount(\n keystore: Keystore.Keystore,\n address: string,\n passphrase: string,\n derivation?: KeystoreDerivationOptions,\n): Promise<Opened> {\n let key: Hex;\n try {\n const derived = await deriveKeystoreKey(keystore, passphrase, derivation);\n key = Keystore.decrypt(keystore, derived);\n } catch (err) {\n if (isCancellation(err)) throw err;\n return { kind: 'wrong', cause: err };\n }\n let account: PrivateKeyAccount;\n try {\n account = privateKeyToAccount(key);\n } catch (err) {\n return { kind: 'mismatch', derived: null, cause: err };\n }\n if (account.address.toLowerCase() !== address.toLowerCase()) {\n return { kind: 'mismatch', derived: account.address };\n }\n return { kind: 'ok', account };\n}\n\n/**\n * Does `passphrase` open this keystore? `ok`, `wrong` (it does not decrypt), or\n * `mismatch` (it decrypts to a key that is not this wallet's: tampered).\n * Rethrows AbortError / TimeoutError from the derivation.\n */\nexport async function openKeystore(\n keystore: Keystore.Keystore,\n address: string,\n passphrase: string,\n derivation?: KeystoreDerivationOptions,\n): Promise<'ok' | 'wrong' | 'mismatch'> {\n return (await openKeystoreAccount(keystore, address, passphrase, derivation)).kind;\n}\n\nfunction isCancellation(err: unknown): boolean {\n return err instanceof Error && ['AbortError', 'TimeoutError'].includes(err.name);\n}\n\n/** The person's fix when TENJIN_WALLET_PASSPHRASE opens nothing and no saved passphrase does either. */\nconst ENV_WRONG_FIX = `TENJIN_WALLET_PASSPHRASE is set but does not open this wallet. Remove it from the environment, then: ${REPAIR_IN_TERMINAL}`;\n\n/** The person's fix when a STORED passphrase does not decrypt the wallet (the line-568 shape). */\nfunction storedWrongFix(source: PassphraseSource, account: string, dir: string): string {\n return `${storedEntryText(source, account, dir)} does not decrypt it. ${REPAIR_IN_TERMINAL}`;\n}\n\n/** \"The OS credential store entry (…)\" for keychain/keyring, the file or blob otherwise. */\nfunction storedEntryText(source: PassphraseSource, account: string, dir: string): string {\n if (source === 'keychain' || source === 'secret-service') {\n return `The OS credential store entry (service tenjin-cli, account ${account})`;\n }\n if (source === 'dpapi' || source === 'file') {\n return `The passphrase in ${describeStoreLocation(source, account, dir)}`;\n }\n return `The passphrase from ${passphraseOrigin(source, account, dir)}`;\n}\n\n/** The legacy-slot fix: the entry is someone else's; repair is for a person who knows this one's. */\nfunction legacyWrongFix(source: PassphraseSource, account: string, dir: string): string {\n return `That passphrase likely belongs to a wallet created later, and the entry was left untouched. If you know this wallet's passphrase: ${REPAIR_IN_TERMINAL} Otherwise restore ${passphraseOrigin(source, account, dir)} from a backup.`;\n}\n\n/**\n * Can this wallet actually sign, without asking anyone? An env key is proven by\n * deriving it; a file wallet needs its passphrase from the env or a saved\n * store, and the keystore decrypted and checked against the stored address.\n *\n * Nothing here prompts (`isTTY: false` is forced last, so no test seam can turn\n * it back on) and nothing here writes: a legacy-slot hit is used to decrypt but\n * its `migrateLegacy` handle is deliberately never invoked, and the signer cache\n * is left alone so the migration still happens on the first real signing. Both\n * would be side effects of a read-only diagnostic.\n *\n * A wrong TENJIN_WALLET_PASSPHRASE falls through to the saved passphrase, the\n * same way signing does: verified with `warning: ENV_PASSPHRASE_WRONG` when that\n * opens it, broken `env_passphrase_wrong` when nothing does.\n *\n * The one read path with a deadline: `doctor` and `install` run unattended\n * and a locked keychain would otherwise hang them, so every store read here,\n * fallback included, gets `STORE_TIMEOUTS.verifyReadMs`. A killed read is\n * `keychain_locked`, which is unknown, never a block. Signing passes none.\n */\nexport async function verifyLocalWallet(deps: LocalProviderDeps): Promise<WalletVerification> {\n const cred = await loadCredential(deps);\n // Details read as a fragment: the caller prefixes them with the wallet line.\n if (cred === null) return { status: 'unverified', detail: 'there is no credential to verify' };\n if (cred.source === 'env') {\n // Deriving is the whole proof for a raw key, and it is cheap.\n accountFromKey(cred.key, 'env');\n return {\n status: 'verified',\n detail: 'TENJIN_WALLET_KEY derives a valid signing key',\n source: 'key-env',\n };\n }\n\n const account = walletStoreAccount(cred.address);\n const passphraseDeps: PassphraseDeps = {\n env: deps.env,\n dir: deps.dir,\n ...deps.passphrase,\n isTTY: false,\n readDeadlineMs: deps.passphrase?.timeouts?.verifyReadMs ?? STORE_TIMEOUTS.verifyReadMs,\n };\n const unreachable = (err: unknown): WalletVerification => {\n if (unlockReasonOf(err) === 'keychain_locked') {\n const store = (err as CliError).details as {\n unlock?: { source?: string };\n storeDetail?: string;\n };\n const noun = isDurableStore(store.unlock?.source)\n ? storeNoun(store.unlock.source)\n : 'keychain';\n return {\n status: 'unverified',\n reason: 'keychain_locked',\n detail: `the ${noun} did not answer (${store.storeDetail ?? 'no answer'}), so the keystore was not opened`,\n };\n }\n return {\n status: 'unverified',\n reason: 'passphrase_missing',\n detail: 'no passphrase is reachable without prompting, so the keystore was not opened',\n };\n };\n\n let resolved: ResolvedPassphrase;\n try {\n resolved = await resolvePassphrase(passphraseDeps, cred.address);\n } catch (err) {\n return unreachable(err);\n }\n\n const cancelled: WalletVerification = {\n status: 'unverified',\n reason: 'unlock_timeout',\n detail: 'keystore verification was cancelled or timed out',\n };\n let opened: Opened;\n try {\n opened = await openKeystoreAccount(\n cred.keystore,\n account,\n resolved.passphrase,\n deps.derivation,\n );\n } catch {\n return cancelled;\n }\n const origin = resolvedOrigin(resolved, account, deps.dir);\n if (opened.kind === 'ok') {\n return {\n status: 'verified',\n detail: `keystore decrypts with the passphrase from ${origin}`,\n source: signingSourceOf(resolved),\n };\n }\n if (opened.kind === 'mismatch') return tamperedVerification(cred.address, opened);\n\n // The orphaned-slot shape: the only durable passphrase is the pre-per-address\n // shared slot and it belongs to some later wallet, so this keystore is\n // unopenable and its address unsignable. Named apart from a plain wrong\n // passphrase because the remedy is different.\n if (resolved.migrateLegacy !== undefined) {\n return {\n status: 'broken',\n reason: 'passphrase_wrong',\n detail: `the keystore cannot be decrypted: the only stored passphrase is ${legacyOrigin(resolved.source)}, which does not open it`,\n fix: legacyWrongFix(resolved.source, account, deps.dir),\n };\n }\n if (resolved.source !== 'env') {\n return {\n status: 'broken',\n reason: 'passphrase_wrong',\n detail: `the keystore cannot be decrypted with the passphrase from ${origin}`,\n fix: storedWrongFix(resolved.source, account, deps.dir),\n };\n }\n\n // A wrong TENJIN_WALLET_PASSPHRASE: does a SAVED passphrase open it?\n let saved: ResolvedPassphrase;\n try {\n saved = await resolvePassphrase(passphraseDeps, cred.address, { skipEnv: true });\n } catch (err) {\n if (unlockReasonOf(err) === 'keychain_locked') return unreachable(err);\n return envWrongVerification();\n }\n let fallback: Opened;\n try {\n fallback = await openKeystoreAccount(cred.keystore, account, saved.passphrase, deps.derivation);\n } catch {\n return cancelled;\n }\n if (fallback.kind === 'ok') {\n return {\n status: 'verified',\n detail: `keystore decrypts with the passphrase from ${resolvedOrigin(saved, account, deps.dir)}; TENJIN_WALLET_PASSPHRASE does not open it`,\n source: signingSourceOf(saved),\n warning: ENV_PASSPHRASE_WRONG,\n };\n }\n if (fallback.kind === 'mismatch') return tamperedVerification(cred.address, fallback);\n return envWrongVerification();\n}\n\nfunction envWrongVerification(): WalletVerification {\n return {\n status: 'broken',\n reason: 'env_passphrase_wrong',\n detail: 'the keystore cannot be decrypted with the passphrase from TENJIN_WALLET_PASSPHRASE',\n fix: ENV_WRONG_FIX,\n };\n}\n\nfunction tamperedVerification(\n address: string,\n opened: Extract<Opened, { kind: 'mismatch' }>,\n): WalletVerification {\n return {\n status: 'broken',\n reason: 'wallet_corrupt',\n detail:\n opened.derived === null\n ? 'the decrypted key is not a valid secp256k1 key'\n : `the decrypted key does not derive the wallet file's stored address ${address}`,\n fix: 'The wallet file may be tampered. Move it aside, then run `tenjin wallet create` for a fresh key or set TENJIN_WALLET_KEY to use the intended one.',\n };\n}\n\n/** What produced a signature, as doctor and install report it. */\nfunction signingSourceOf(resolved: ResolvedPassphrase): SigningSource {\n if (resolved.migrateLegacy !== undefined) return 'legacy';\n if (resolved.source === 'env') return 'passphrase-env';\n // isTTY is forced false wherever this is asked, so 'prompt' cannot happen;\n // name it the file rather than invent a source.\n return resolved.source === 'prompt' ? 'file' : resolved.source;\n}\n\nfunction isDurableStore(value: unknown): value is DurableStore {\n return (\n value === 'keychain' || value === 'secret-service' || value === 'dpapi' || value === 'file'\n );\n}\n\n/** Where a resolved passphrase came from, the legacy slot named as such. */\nfunction resolvedOrigin(resolved: ResolvedPassphrase, account: string, dir: string): string {\n return resolved.migrateLegacy !== undefined\n ? legacyOrigin(resolved.source)\n : passphraseOrigin(resolved.source, account, dir);\n}\n\n/**\n * Where a resolved passphrase came from, in words an operator can act on.\n * Windows stores a per-wallet DPAPI file rather than a service/account entry, so\n * naming one model for both would send that operator looking for something that\n * does not exist on their machine.\n */\nfunction passphraseOrigin(source: PassphraseSource, account: string, dir?: string): string {\n if (source === 'env') return 'TENJIN_WALLET_PASSPHRASE';\n if (source === 'prompt') return 'the prompt';\n if (source === 'dpapi') return `the DPAPI-protected passphrase file for ${account}`;\n if (source === 'file') return describeStoreLocation('file', account, dir);\n return `the OS credential store (service tenjin-cli, account ${account})`;\n}\n\n/** The same, for the pre-per-wallet shared slot every backend still reads once. */\nfunction legacyOrigin(source: PassphraseSource): string {\n return source === 'dpapi'\n ? 'the legacy shared DPAPI passphrase file (passphrase.dpapi)'\n : 'the legacy shared entry (service tenjin-cli, account \"wallet\")';\n}\n\n/**\n * File-custody warnings for the local provider: an env key shadowing the file,\n * non-0600 perms (the wallet file, and the passphrase file when the sidecar says\n * that is where the passphrase lives), and the Windows \"perms not checkable\"\n * note. Keyless. Also reports the at-rest key protection (`keyStorage`), where\n * the sidecar says the passphrase was saved (`passphraseStore`, a file read, not\n * a store probe) and — only when it is cheap and side-effect-free (the env\n * passphrase) — the passphrase source, so `show` can surface custody posture\n * without decrypting or probing the keychain.\n */\nexport async function localWalletDiagnostics(deps: LocalProviderDeps): Promise<WalletDiagnostics> {\n const mode = await walletFileMode(deps.dir);\n const fileExists = mode !== null;\n const envKey = deps.env.TENJIN_WALLET_KEY;\n const envSet = envKey !== undefined && envKey.length > 0;\n const path = walletPath(deps.dir);\n\n const warnings: string[] = [];\n if (envSet && fileExists) {\n warnings.push('TENJIN_WALLET_KEY is set and shadows the wallet file at runtime.');\n }\n if (mode !== null) {\n if (isWindows) {\n warnings.push('File permission checks are not available on Windows.');\n } else if (mode !== 0o600) {\n warnings.push(\n `Wallet file permissions are ${mode.toString(8)}, expected 600. Run \\`chmod 600 ${path}\\`.`,\n );\n }\n }\n const passphraseStore = fileExists ? await recordedStore(deps.dir) : null;\n if (passphraseStore?.store === 'file' && !isWindows) {\n const plain = passphraseFilePathFor(passphraseStore.account, deps.dir);\n const plainMode = await stat(plain).then(\n (s) => s.mode & 0o777,\n () => null,\n );\n if (plainMode !== null && plainMode !== 0o600) {\n warnings.push(\n `Passphrase file permissions are ${plainMode.toString(8)}, expected 600. Run \\`chmod 600 ${plain}\\`.`,\n );\n }\n }\n const passphraseSource =\n deps.env.TENJIN_WALLET_PASSPHRASE !== undefined && deps.env.TENJIN_WALLET_PASSPHRASE.length > 0\n ? 'TENJIN_WALLET_PASSPHRASE'\n : undefined;\n const archivedWallets = await listArchivedWallets(deps.dir);\n return {\n ...(fileExists ? { walletPath: path, keyStorage: KEY_STORAGE } : {}),\n ...(fileExists && passphraseSource !== undefined ? { passphraseSource } : {}),\n ...(passphraseStore !== null ? { passphraseStore: passphraseStore.store } : {}),\n ...(archivedWallets.length > 0 ? { archivedWallets } : {}),\n warnings,\n };\n}\n\n/** The sidecar's store for the active wallet file, or null (no record, or no readable wallet). */\nasync function recordedStore(\n dir: string,\n): Promise<{ store: DurableStore; account: string } | null> {\n const record = await readWalletRecord(dir).catch(() => null);\n if (record === null) return null;\n const account = record.address.toLowerCase();\n const entry = await readPassphraseRecord(dir, account);\n return entry === null ? null : { store: entry.store, account };\n}\n\n/** Archive filenames written by `wallet create --replace`; group 1 is the address. */\nconst ARCHIVED_WALLET_RE = /^wallet\\.(0x[0-9a-f]{40})\\.json\\.bak$/;\n\n/**\n * Addresses of wallets parked by `wallet create --replace`, from a cheap dir\n * scan (no keychain probe, no file reads — the address is the filename). A\n * recovery hint for `show`; the single-active-wallet model reads none of these.\n */\nasync function listArchivedWallets(dir: string): Promise<string[]> {\n let names: string[];\n try {\n names = await readdir(dir);\n } catch {\n return []; // No data dir yet: nothing archived.\n }\n return names\n .map((name) => ARCHIVED_WALLET_RE.exec(name)?.[1])\n .filter((address): address is string => address !== undefined)\n .sort();\n}\n\nexport interface LocalWalletInfo {\n address: Address;\n walletPath: string;\n}\n\n/**\n * The encryption passphrase for a create: a fixed string, or a resolver invoked\n * with the freshly derived ADDRESS — so passphrase storage can be keyed to the\n * wallet's own per-address OS-store entry before the key is ever encrypted.\n */\nexport type CreatePassphrase = string | ((address: Address) => Promise<string>);\n\n/**\n * A wallet fully built in memory but not yet on disk — so `--replace` can\n * finish every fallible step BEFORE touching the active slot.\n */\nexport interface PreparedLocalWallet {\n address: Address;\n record: WalletRecord;\n}\n\n/**\n * Generate a fresh key, resolve the passphrase FOR THAT ADDRESS (before\n * encryption, so a stored passphrase always exists by the time an encrypted\n * wallet does), and encrypt — no disk write, no cleartext key anywhere.\n */\nexport async function prepareLocalWallet(\n passphrase: CreatePassphrase,\n): Promise<PreparedLocalWallet> {\n const key = generatePrivateKey();\n const address = privateKeyToAccount(key).address;\n const resolved = typeof passphrase === 'string' ? passphrase : await passphrase(address);\n const keystore = await encryptToKeystore(key, resolved);\n return { address, record: walletRecord(address, keystore) };\n}\n\n/**\n * Persist a prepared wallet NO-CLOBBER. The write, not a caller's pre-check, is\n * the authority: a lost create race throws WALLET_EXISTS rather than\n * overwriting a funded key.\n */\nexport async function commitLocalWallet(\n dir: string,\n prepared: PreparedLocalWallet,\n): Promise<LocalWalletInfo> {\n await writeWalletRecord(dir, prepared.record);\n return { address: prepared.address, walletPath: walletPath(dir) };\n}\n\n/** Prepare + commit in one step — the plain `wallet create` path. */\nexport async function createLocalWallet(\n dir: string,\n passphrase: CreatePassphrase,\n): Promise<LocalWalletInfo> {\n return commitLocalWallet(dir, await prepareLocalWallet(passphrase));\n}\n\n/** Where the archived wallet's passphrase remains durable after a --replace. */\nexport type ArchivedPassphraseLocation = 'store' | 'env' | 'unarchived';\n/**\n * When `unarchived`: why no durable copy could be made. Only these two park the\n * outgoing wallet without one; an `uncertain` or `store-failed` write refuses\n * the replace instead.\n */\nexport type UnarchivedReason = Extract<StorePassphraseOutcome, 'no-store' | 'rejected-characters'>;\n\nexport interface PreservedWalletInfo {\n address: Address;\n /** The wallet's OS-store account / archive filename key (lowercase address). */\n account: string;\n passphraseLocation: ArchivedPassphraseLocation;\n unarchivedReason?: UnarchivedReason;\n /** When `store`: where the passphrase is kept (describeStoreLocation), if known. */\n location?: string;\n}\n\nexport interface ArchivedWalletInfo extends PreservedWalletInfo {\n /** Where the keystore file was parked (wallet.<address>.json.bak). */\n archivedPath: string;\n}\n\n/**\n * The verify-and-preserve half of `--replace`: prove the outgoing wallet's\n * passphrase decrypts its keystore (MAC + derived-address check), then ensure a\n * durable per-address copy exists (legacy slot re-keyed, REFUSING on failure).\n * Touches no wallet file — the park runs separately, after the replacement is\n * fully prepared, so every failure here leaves the old wallet active and\n * untouched.\n *\n * The one prompt left in create. When no env value or saved store\n * serves the OUTGOING wallet's passphrase, a person at a terminal is asked for\n * it, by that wallet's address. The new wallet's secret is never prompted for.\n * A prompt-entered passphrase is then saved durably: to the platform store when\n * its probe answers, the 0600 file where there is none, and the replace refuses\n * when the store does not answer or does not read the passphrase back:\n * parking a funded wallet with no durable copy of its passphrase is how funds\n * get stranded. Only a proven write records the sidecar (`by: 'replace'`). The\n * one exception kept from before: a typed passphrase the keychain writer cannot\n * store at all (`rejected-characters`) is parked `unarchived`, and create's\n * output says so.\n */\nexport async function verifyAndPreserveOutgoingWallet(\n deps: LocalProviderDeps,\n): Promise<PreservedWalletInfo> {\n const record = await readWalletRecord(deps.dir);\n if (record === null) {\n throw new CliError('WALLET_MISSING', 'No wallet found to archive.', {\n fix: 'Run `tenjin wallet create` without --replace.',\n });\n }\n const address = record.address as Address;\n const account = walletStoreAccount(address);\n const passphraseDeps: PassphraseDeps = { env: deps.env, dir: deps.dir, ...deps.passphrase };\n const resolved = await resolvePassphrase(passphraseDeps, address, {\n promptLabel: `Passphrase for the existing wallet ${address}: `,\n });\n\n let opened: Opened;\n try {\n opened = await openKeystoreAccount(record.keystore, account, resolved.passphrase);\n } catch (err) {\n opened = { kind: 'wrong', cause: err };\n }\n if (opened.kind === 'wrong') {\n // Name the escape that actually applies to where the passphrase came from:\n // once a store serves a value, resolution never falls through to a prompt.\n // A person at a terminal runs --replace, so this keeps its own wording.\n const escape =\n resolved.source === 'prompt'\n ? \"Retry and enter that wallet's correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it\"\n : resolved.source === 'env'\n ? 'TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase'\n : `Set TENJIN_WALLET_PASSPHRASE to its passphrase, or fix ${storedEntryText(resolved.source, account, deps.dir).replace(/^The /, 'the ')}`;\n throw new CliError(\n 'REFUSED',\n `Cannot verify the passphrase of the existing wallet ${address}; --replace refused.`,\n {\n fix: `Replacing now could strand that wallet's funds. ${escape}, then retry.`,\n cause: opened.cause,\n },\n );\n }\n if (opened.kind === 'mismatch') {\n throw new CliError(\n 'REFUSED',\n `The wallet file's stored address ${address} does not match its key; --replace refused.`,\n {\n fix: 'The wallet file may be tampered. Resolve that before replacing it.',\n details: unlockDetails('wallet_corrupt'),\n },\n );\n }\n\n // A durable per-address copy must exist BEFORE the active slot changes hands.\n if (resolved.source === 'env') {\n return { address, account, passphraseLocation: 'env' };\n }\n if (resolved.migrateLegacy !== undefined) {\n if (!(await resolved.migrateLegacy())) {\n throw new CliError(\n 'REFUSED',\n `Could not archive the existing wallet's passphrase under its own address; --replace refused.`,\n {\n fix: `The passphrase currently lives only in the legacy shared slot (service tenjin-cli, account \"wallet\"), and copying it to account ${account} failed. Retry, or check OS credential store access.`,\n },\n );\n }\n return { address, account, passphraseLocation: 'store' };\n }\n if (resolved.source === 'prompt') {\n return archivePromptedPassphrase(\n passphraseDeps,\n deps.dir,\n address,\n account,\n resolved.passphrase,\n );\n }\n // Served from its own entry (a store, or the 0600 file): already archived.\n return {\n address,\n account,\n passphraseLocation: 'store',\n location: describeStoreLocation(resolved.source, account, deps.dir),\n };\n}\n\n/** Save a prompt-entered outgoing passphrase durably, or refuse the replace (see above). */\nasync function archivePromptedPassphrase(\n passphraseDeps: PassphraseDeps,\n dir: string,\n address: Address,\n account: string,\n passphrase: string,\n): Promise<PreservedWalletInfo> {\n const probed = await probeDurableStore(passphraseDeps);\n if (probed.probe === 'uncertain') throw outgoingUncertainError(probed.store);\n const target: DurableStore = probed.probe === 'available' ? probed.store : 'file';\n const written = await storeDurablyDetailed(passphraseDeps, target, address, passphrase);\n // A file cannot be \"locked\": an fs error there is a failed write, and its\n // fix is the directory, never a keychain.\n const outcome =\n target === 'file' && written.outcome === 'uncertain'\n ? 'store-failed'\n : toStoreOutcome(written.outcome);\n switch (outcome) {\n case 'stored':\n await writePassphraseRecord(dir, account, { store: target, by: 'replace' });\n return {\n address,\n account,\n passphraseLocation: 'store',\n location: describeStoreLocation(target, account, dir),\n };\n case 'uncertain':\n throw outgoingUncertainError(target);\n case 'store-failed': {\n const detail = written.detail ?? `the ${storeNoun(target)} write failed`;\n const message = `Could not save the existing wallet's passphrase (${detail}); --replace refused.`;\n if (target === 'file') {\n const path = describeStoreLocation('file', account, dir);\n throw new CliError('REFUSED', message, {\n fix: FILE_STORE_FAILED_FIX(path),\n details: { passphraseStore: { kind: 'file-write-failed', path } },\n });\n }\n throw new CliError('REFUSED', message, {\n fix: KEYCHAIN_LOCKED_FIX,\n details: unlockDetails('keychain_locked', target),\n });\n }\n case 'rejected-characters':\n return { address, account, passphraseLocation: 'unarchived', unarchivedReason: outcome };\n }\n}\n\nfunction outgoingUncertainError(store: DurableStore): CliError {\n return new CliError(\n 'REFUSED',\n `Could not save the existing wallet's passphrase (the ${storeNoun(store)} did not answer); --replace refused.`,\n { fix: KEYCHAIN_LOCKED_FIX, details: unlockDetails('keychain_locked', store) },\n );\n}\n\n/**\n * The park half of `--replace`: move the outgoing keystore to\n * wallet.<address>.json.bak, NO-CLOBBER (link + unlink, so an existing archive\n * is never silently replaced — the .bak is the last copy of a funded key). Run\n * only after verify-and-preserve succeeded AND the replacement is fully\n * prepared. Returns the archive path.\n */\nexport async function parkOutgoingWallet(dir: string, account: string): Promise<string> {\n const src = walletPath(dir);\n const dst = archivedWalletPath(account, dir);\n try {\n await link(src, dst);\n } catch (err) {\n if (hasCode(err, 'EEXIST')) {\n throw new CliError('REFUSED', `An archived wallet already exists at ${dst}.`, {\n fix: `Move ${dst} aside, then retry \\`tenjin wallet create --replace\\`. Nothing has moved; the current wallet is still active.`,\n cause: err,\n });\n }\n throw new CliError('INTERNAL', `Could not park the outgoing keystore at ${dst}.`, {\n fix: `Nothing has moved; the current wallet is still active at ${src}. Fix the underlying filesystem error and retry.`,\n cause: err,\n });\n }\n try {\n await unlink(src);\n } catch (err) {\n // link succeeded but the active slot would not clear (e.g. EBUSY on win32\n // with the file held open): both names point at one inode and the ACTIVE\n // wallet would be listed as archived. Best-effort undo the new link so the\n // state stays exactly as before the park.\n await unlink(dst).catch(() => undefined);\n throw new CliError(\n 'INTERNAL',\n `Could not clear the active wallet slot ${src} while parking the outgoing wallet.`,\n {\n fix: 'The previous wallet is still active and nothing was lost. Fix the underlying filesystem error (on Windows, close any process holding the wallet file open) and retry.',\n cause: err,\n },\n );\n }\n await syncWalletDir(dir);\n return dst;\n}\n\n/**\n * Undo a park (rollback when the replacement failed to commit), NO-CLOBBER: if\n * a wallet.json appeared out of band, `link` throws EEXIST rather than\n * overwriting it — the caller surfaces both paths instead of guessing.\n */\nexport async function restoreParkedWallet(dir: string, archivedPath: string): Promise<void> {\n await link(archivedPath, walletPath(dir));\n // The active wallet is restored from here on; a stale .bak link is a listing\n // blemish, not a loss, so its removal is best-effort.\n await unlink(archivedPath).catch(() => undefined);\n await syncWalletDir(dir);\n}\n\n/** fsync the wallet dir so a park/restore survives a crash (POSIX only). */\nasync function syncWalletDir(dir: string): Promise<void> {\n if (isWindows) return; // a directory cannot be fsynced on win32\n await fsyncDir(dir);\n}\n\ntype Credential =\n { source: 'env'; key: Hex } | { source: 'file'; keystore: Keystore.Keystore; address: Address };\n\n/** Env override beats the wallet file (CI + ephemeral agents); null when neither exists. */\nasync function loadCredential(deps: LocalProviderDeps): Promise<Credential | null> {\n const envKey = deps.env.TENJIN_WALLET_KEY;\n if (envKey !== undefined && envKey.trim().length > 0) {\n const key = envKey.trim();\n if (!PRIVATE_KEY_RE.test(key)) {\n throw new CliError('WALLET_INVALID_KEY', 'TENJIN_WALLET_KEY is not a valid private key.', {\n fix: 'Set TENJIN_WALLET_KEY to a 0x-prefixed 32-byte hex key, or unset it to use the wallet file.',\n details: unlockDetails('env_key_invalid'),\n });\n }\n return { source: 'env', key: key as Hex };\n }\n const record = await readWalletRecord(deps.dir);\n if (record !== null) {\n return { source: 'file', keystore: record.keystore, address: record.address as Address };\n }\n return null;\n}\n\n/**\n * Build the viem account for SIGNING. An env credential uses its raw key; a\n * file credential resolves the passphrase for its address, decrypts, then\n * verifies the recovered key derives the stored address (tamper signal). A\n * legacy-served passphrase migrates only AFTER that proof; a decrypt failure\n * with one surfaces the ambiguity and leaves the legacy entry untouched.\n *\n * A wrong env passphrase falls through. A correct TENJIN_WALLET_PASSPHRASE\n * opens on the first try and no store is read. One that does not open the\n * wallet is passed over: the passphrase is resolved again without it and\n * without a prompt, and when the saved one opens the wallet, signing goes\n * ahead and `onWarning` says the variable is wrong, once per provider per\n * keystore. That fallback read passes no deadline. A locked store on the\n * way is rethrown as `keychain_locked`; nothing else opening it is\n * `env_passphrase_wrong`.\n *\n * Every throw carries `details.unlock`, so the payer, the hooks and doctor can\n * act on the reason without reading the message. No fix here tells anyone to\n * set TENJIN_WALLET_PASSPHRASE to a value: repair asks the person for it.\n */\nasync function accountForSigning(\n cred: Credential,\n deps: LocalProviderDeps,\n warnOnce: (keystoreId: string) => void,\n): Promise<PrivateKeyAccount> {\n if (cred.source === 'env') return accountFromKey(cred.key, 'env');\n\n const id = cred.keystore.id;\n const cached = signerCache.get(id);\n if (cached !== undefined) {\n if (cached.envShadowed) warnOnce(id);\n return cached.account;\n }\n\n const account = walletStoreAccount(cred.address);\n const passphraseDeps: PassphraseDeps = { env: deps.env, dir: deps.dir, ...deps.passphrase };\n const resolved = await resolvePassphrase(passphraseDeps, cred.address);\n const opened = await openKeystoreAccount(\n cred.keystore,\n account,\n resolved.passphrase,\n deps.derivation,\n );\n if (opened.kind === 'ok') return unlocked(resolved, opened.account, false);\n if (opened.kind === 'mismatch') throw tamperedError(cred.address, opened);\n\n if (resolved.migrateLegacy !== undefined) {\n // The only durable passphrase came from the legacy shared slot and it does\n // NOT decrypt this wallet: it almost certainly belongs to whichever wallet\n // was created last before per-wallet entries existed. Do not migrate, do\n // not delete — surface the ambiguity and leave the entry for its owner.\n throw new CliError(\n 'WALLET_INVALID_KEY',\n 'The legacy shared passphrase entry (service tenjin-cli, account \"wallet\") does not decrypt this wallet.',\n {\n fix: `That entry likely belongs to a different wallet created later and was left untouched. If you know this wallet's passphrase: ${REPAIR_IN_TERMINAL}`,\n cause: opened.cause,\n details: unlockDetails('passphrase_wrong', 'legacy'),\n },\n );\n }\n if (resolved.source !== 'env') {\n // Name only the escape that applies to where the passphrase came from —\n // resolution never falls through to a prompt after a store hit.\n throw new CliError('WALLET_INVALID_KEY', 'Could not decrypt the wallet keystore.', {\n fix:\n resolved.source === 'prompt'\n ? 'Retry and enter the correct passphrase at the prompt.'\n : storedWrongFix(resolved.source, account, deps.dir),\n cause: opened.cause,\n details: unlockDetails('passphrase_wrong', resolved.source),\n });\n }\n\n // TENJIN_WALLET_PASSPHRASE did not open it: does a saved passphrase?\n const saved = await resolvePassphrase({ ...passphraseDeps, isTTY: false }, cred.address, {\n skipEnv: true,\n }).catch((err: unknown) => err);\n if (!(saved instanceof Error) && isResolved(saved)) {\n const fallback = await openKeystoreAccount(\n cred.keystore,\n account,\n saved.passphrase,\n deps.derivation,\n );\n if (fallback.kind === 'ok') {\n const result = await unlocked(saved, fallback.account, true);\n warnOnce(id);\n return result;\n }\n if (fallback.kind === 'mismatch') throw tamperedError(cred.address, fallback);\n } else if (unlockReasonOf(saved) === 'keychain_locked') {\n const locked = saved as CliError;\n throw new CliError(\n locked.code,\n `TENJIN_WALLET_PASSPHRASE does not open the wallet, and ${lowerFirst(locked.message)}`,\n {\n ...(locked.fix !== undefined ? { fix: locked.fix } : {}),\n details: locked.details,\n },\n );\n }\n throw new CliError('WALLET_INVALID_KEY', 'Could not decrypt the wallet keystore.', {\n fix: ENV_WRONG_FIX,\n cause: opened.cause,\n details: unlockDetails('env_passphrase_wrong', 'env'),\n });\n\n /** Cache the opened account, after running a proven legacy migration. */\n async function unlocked(\n from: ResolvedPassphrase,\n signer: PrivateKeyAccount,\n envShadowed: boolean,\n ): Promise<PrivateKeyAccount> {\n // Decrypt + address check passed: this wallet provably owns the legacy\n // passphrase, so re-key it under the wallet's own address (copy, verify,\n // then remove the legacy slot). Best-effort: on failure the legacy entry\n // remains the durable copy and the next signing retries the migration.\n if (from.migrateLegacy !== undefined) await from.migrateLegacy();\n signerCache.set(id, { account: signer, envShadowed });\n return signer;\n }\n}\n\nfunction isResolved(value: unknown): value is ResolvedPassphrase {\n return typeof value === 'object' && value !== null && 'passphrase' in value;\n}\n\nfunction lowerFirst(text: string): string {\n return text.length > 0 ? `${text.charAt(0).toLowerCase()}${text.slice(1)}` : text;\n}\n\n/** The tamper error: the keystore decrypts, but not to this wallet's key. */\nfunction tamperedError(address: string, opened: Extract<Opened, { kind: 'mismatch' }>): CliError {\n if (opened.derived === null) return invalidKeyError('file', opened.cause);\n return new CliError(\n 'WALLET_INVALID_KEY',\n `The decrypted key derives ${opened.derived}, not the wallet file's stored address ${address}.`,\n {\n fix: 'The wallet file may be tampered. Move it aside, then run `tenjin wallet create` for a fresh key or set TENJIN_WALLET_KEY to use the intended one.',\n details: unlockDetails('wallet_corrupt'),\n },\n );\n}\n\n/** viem account from a raw key, mapping viem's throw on a bad key to WALLET_INVALID_KEY. */\nfunction accountFromKey(key: Hex, source: 'env' | 'file'): PrivateKeyAccount {\n try {\n return privateKeyToAccount(key);\n } catch (err) {\n throw invalidKeyError(source, err);\n }\n}\n\n/** A key off the secp256k1 curve: a corrupt file, or a bad TENJIN_WALLET_KEY. */\nfunction invalidKeyError(source: 'env' | 'file', cause: unknown): CliError {\n return new CliError('WALLET_INVALID_KEY', 'The private key is not a valid secp256k1 key.', {\n fix:\n source === 'file'\n ? 'Move the wallet file aside, then run `tenjin wallet create` for a fresh key or set TENJIN_WALLET_KEY to use the intended one.'\n : 'Set TENJIN_WALLET_KEY to a valid 0x-prefixed 32-byte hex key.',\n cause,\n details: unlockDetails(source === 'file' ? 'wallet_corrupt' : 'env_key_invalid'),\n });\n}\n\n/** Encrypt a raw key into a Keystore v3 document using ox's default scrypt parameters. */\nasync function encryptToKeystore(key: Hex, passphrase: string): Promise<Keystore.Keystore> {\n const [derivedKey, opts] = await Keystore.scryptAsync({ password: passphrase });\n return Keystore.encrypt(key, derivedKey, opts);\n}\n\nasync function credentialOrThrow(deps: LocalProviderDeps): Promise<Credential> {\n const cred = await loadCredential(deps);\n if (cred !== null) return cred;\n // Name any archived (replaced) wallets so a missing active wallet never hides\n // recoverable funds behind a bare \"create one\".\n const archived = await listArchivedWallets(deps.dir);\n const hint =\n archived.length > 0\n ? ` Archived wallets exist (${archived.join(', ')}); restore one with \\`mv ${archivedWalletPath('<address>', deps.dir)} ${walletPath(deps.dir)}\\`.`\n : '';\n throw new CliError('WALLET_MISSING', 'No wallet found.', {\n fix: `Run \\`tenjin wallet create\\` to create one.${hint}`,\n });\n}\n\nfunction walletRecord(address: Address, keystore: Keystore.Keystore): WalletRecord {\n return {\n schemaVersion: WALLET_SCHEMA_VERSION,\n provider: 'local',\n address,\n keystore,\n createdAt: new Date().toISOString(),\n };\n}\n\n/** What `tenjin wallet repair` did. */\nexport interface RepairOutcome {\n address: Address;\n account: string;\n store: DurableStore;\n location: string;\n /** The store already held this passphrase (or an entry that opens the wallet): nothing was written. */\n alreadySaved: boolean;\n /** An existing entry that did NOT open the wallet was replaced (`-U`). */\n replacedUnusableEntry: boolean;\n fileReason?: 'no-keyring' | 'insecure-storage';\n}\n\n/**\n * SAVE A PASSPHRASE THE PERSON PROVED, for a wallet Claude Code cannot unlock.\n *\n * 1. The passphrase must open THIS wallet (`openKeystore`): a wrong one saves\n * nothing, and a tampered file refuses. The address never changes and\n * wallet.json is never rewritten.\n * 2. The target: the store the sidecar names when it already reads this\n * passphrase back (nothing to do); the 0600 file with `insecureStorage`;\n * otherwise the platform store when its probe answers, the 0600 file when\n * there is none, and a refusal when it does not answer (never a hint at\n * plaintext).\n * 3. storeDurablyDetailed, allowed to replace an existing entry ONLY after proving that\n * entry does not open the wallet. It succeeds only when the store reads this\n * passphrase back: a different value after the write is a refusal,\n * never \"saved\".\n * 4. Only then the sidecar records the store (`by: 'repair'`).\n *\n * Never touches the legacy slot, another account, or wallet.json. The caller\n * holds `wallet.create.lock`.\n */\nexport async function repairLocalWalletPassphrase(\n deps: LocalProviderDeps,\n passphrase: string,\n opts: { insecureStorage?: boolean } = {},\n): Promise<RepairOutcome> {\n const record = await readWalletRecord(deps.dir);\n if (record === null) {\n throw new CliError('WALLET_MISSING', 'No wallet found to repair.', {\n fix: 'Run `tenjin wallet create` to create one.',\n });\n }\n const address = record.address as Address;\n const account = walletStoreAccount(address);\n const opened = await openKeystoreAccount(record.keystore, account, passphrase, deps.derivation);\n if (opened.kind === 'wrong') {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `That passphrase does not open wallet ${address}; nothing was saved.`,\n {\n fix: `Check the passphrase, then: ${REPAIR_IN_TERMINAL}`,\n details: unlockDetails('passphrase_wrong', 'prompt'),\n },\n );\n }\n if (opened.kind === 'mismatch') throw tamperedError(address, opened);\n\n const passphraseDeps: PassphraseDeps = { env: deps.env, dir: deps.dir, ...deps.passphrase };\n const location = (store: DurableStore): string => describeStoreLocation(store, account, deps.dir);\n const done = (\n store: DurableStore,\n fields: Partial<Pick<RepairOutcome, 'alreadySaved' | 'replacedUnusableEntry' | 'fileReason'>>,\n ): RepairOutcome => ({\n address,\n account,\n store,\n location: location(store),\n alreadySaved: fields.alreadySaved ?? false,\n replacedUnusableEntry: fields.replacedUnusableEntry ?? false,\n ...(fields.fileReason !== undefined ? { fileReason: fields.fileReason } : {}),\n });\n\n const recorded = await readPassphraseRecord(deps.dir, account);\n if (recorded !== null) {\n const timeouts = { ...STORE_TIMEOUTS, ...passphraseDeps.timeouts };\n const bound = passphraseDeps.isTTY === true ? timeouts.interactiveWriteMs : timeouts.writeMs;\n const held = await readStoredPassphrase(passphraseDeps, recorded.store, address, {\n timeoutMs: bound,\n });\n if (held.kind === 'hit' && held.value === passphrase) {\n return done(recorded.store, { alreadySaved: true });\n }\n }\n\n let target: DurableStore;\n let fileReason: RepairOutcome['fileReason'];\n if (opts.insecureStorage === true) {\n target = 'file';\n fileReason = 'insecure-storage';\n } else {\n const probed = await probeDurableStore(passphraseDeps);\n if (probed.probe === 'uncertain') {\n throw new CliError(\n 'REFUSED',\n `The ${storeNoun(probed.store)} did not answer; nothing was saved.`,\n { fix: KEYCHAIN_LOCKED_FIX, details: unlockDetails('keychain_locked', probed.store) },\n );\n }\n if (probed.probe === 'available') {\n target = probed.store;\n } else {\n target = 'file';\n fileReason = 'no-keyring';\n }\n }\n\n let replaced = false;\n const written = await storeDurablyDetailed(passphraseDeps, target, address, passphrase, {\n // Replace an existing entry only once it is PROVEN not to open this wallet.\n replaceIf: async (existing) => {\n replaced = (await openKeystore(record.keystore, account, existing, deps.derivation)) !== 'ok';\n return replaced;\n },\n });\n const reason = fileReason !== undefined ? { fileReason } : {};\n // A file cannot be \"locked\": an fs error there is a failed write, and its\n // fix is the directory, never a keychain.\n const outcome =\n target === 'file' && written.outcome === 'uncertain' ? 'store-failed' : written.outcome;\n switch (outcome) {\n case 'stored':\n await writePassphraseRecord(deps.dir, account, { store: target, by: 'repair' });\n return done(target, { replacedUnusableEntry: replaced, ...reason });\n case 'already-stored':\n case 'kept-existing':\n await writePassphraseRecord(deps.dir, account, { store: target, by: 'repair' });\n return done(target, { alreadySaved: true, ...reason });\n case 'uncertain':\n throw new CliError('REFUSED', `The ${storeNoun(target)} did not answer; nothing was saved.`, {\n fix: KEYCHAIN_LOCKED_FIX,\n details: unlockDetails('keychain_locked', target),\n });\n case 'conflict':\n throw new CliError(\n 'REFUSED',\n `The ${storeNoun(target)} holds a different passphrase for wallet ${address} after the write; nothing was confirmed.`,\n {\n fix: `Run \\`tenjin wallet repair\\` again yourself ${REPAIR_CLAUSE}; if this repeats, another program is writing that entry: run \\`tenjin doctor\\`.`,\n details: unlockDetails('keychain_locked', target),\n },\n );\n case 'rejected-characters':\n throw new CliError(\n 'REFUSED',\n `This passphrase cannot be saved: ${unstorableWhy(target)}; nothing was saved.`,\n {\n fix: 'Keep TENJIN_WALLET_PASSPHRASE set in the environment Claude Code starts from.',\n },\n );\n case 'store-failed': {\n const detail = written.detail ?? `the ${storeNoun(target)} write failed`;\n if (target === 'file') {\n const path = location('file');\n throw new CliError(\n 'REFUSED',\n `Could not save the passphrase to ${path} (${detail}); nothing was saved.`,\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 passphrase to ${location(target)} (${detail}); nothing was saved.`,\n { fix: KEYCHAIN_LOCKED_FIX, details: unlockDetails('keychain_locked', target) },\n );\n }\n }\n}\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes,\n type CHash,\n type KDFInput\n} from './utils.ts';\n\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c);\n anumber(dkLen);\n anumber(asyncTick);\n if (c < 1) throw new Error('iterations (c) should be >= 1');\n const password = kdfInputToBytes(_password);\n const salt = kdfInputToBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output<T extends Hash<T>>(\n PRF: Hash<T>,\n PRFSalt: Hash<T>,\n DK: Uint8Array,\n prfW: Hash<T>,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Uint8Array {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Promise<Uint8Array> {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nexport type GeneratePrivateKeyErrorType = ToHexErrorType | ErrorType\n\n/**\n * @description Generates a random private key.\n *\n * @returns A randomly generated private key.\n */\nexport function generatePrivateKey(): Hex {\n return toHex(secp256k1.utils.randomPrivateKey())\n}\n","// TODO(v3): Rename to `toLocalAccount` + add `source` property to define source (privateKey, mnemonic, hdKey, etc).\n\nimport type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.js'\nimport type {\n AccountSource,\n CustomSource,\n JsonRpcAccount,\n LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType<accountSource extends AccountSource> =\n | (accountSource extends Address ? JsonRpcAccount : never)\n | (accountSource extends CustomSource ? LocalAccount : never)\n\nexport type ToAccountErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a custom signing implementation.\n *\n * @returns A Local Account.\n */\nexport function toAccount<accountSource extends AccountSource>(\n source: accountSource,\n): GetAccountReturnType<accountSource> {\n if (typeof source === 'string') {\n if (!isAddress(source, { strict: false }))\n throw new InvalidAddressError({ address: source })\n return {\n address: source,\n type: 'json-rpc',\n } as GetAccountReturnType<accountSource>\n }\n\n if (!isAddress(source.address, { strict: false }))\n throw new InvalidAddressError({ address: source.address })\n return {\n address: source.address,\n nonceManager: source.nonceManager,\n sign: source.sign,\n signAuthorization: source.signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType<accountSource>\n}\n","// TODO(v3): Convert to sync.\n\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignParameters<to extends To = 'object'> = {\n hash: Hex\n privateKey: Hex\n to?: to | To | undefined\n}\n\nexport type SignReturnType<to extends To = 'object'> =\n | (to extends 'object' ? Signature : never)\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type SignErrorType =\n | HexToBytesErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | ErrorType\n\nlet extraEntropy: Hex | boolean = false\n\n/**\n * Sets extra entropy for signing functions.\n */\nexport function setSignEntropy(entropy: true | Hex) {\n if (!entropy) throw new Error('must be a `true` or a hex value.')\n extraEntropy = entropy\n}\n\n/**\n * @description Signs a hash with a given private key.\n *\n * @param hash The hash to sign.\n * @param privateKey The private key to sign with.\n *\n * @returns The signature.\n */\nexport async function sign<to extends To = 'object'>({\n hash,\n privateKey,\n to = 'object',\n}: SignParameters<to>): Promise<SignReturnType<to>> {\n const { r, s, recovery } = secp256k1.sign(\n hash.slice(2),\n privateKey.slice(2),\n {\n lowS: true,\n extraEntropy: isHex(extraEntropy, { strict: false })\n ? hexToBytes(extraEntropy)\n : extraEntropy,\n },\n )\n const signature = {\n r: numberToHex(r, { size: 32 }),\n s: numberToHex(s, { size: 32 }),\n v: recovery ? 28n : 27n,\n yParity: recovery,\n }\n return (() => {\n if (to === 'bytes' || to === 'hex')\n return serializeSignature({ ...signature, to })\n return signature\n })() as SignReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../utils/authorization/hashAuthorization.js'\nimport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n sign,\n} from './sign.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignAuthorizationParameters<to extends To = 'object'> =\n AuthorizationRequest & {\n /** The private key to sign with. */\n privateKey: Hex\n to?: SignParameters<to>['to'] | undefined\n }\n\nexport type SignAuthorizationReturnType<to extends To = 'object'> = Prettify<\n to extends 'object' ? SignedAuthorization : SignReturnType<to>\n>\n\nexport type SignAuthorizationErrorType =\n | SignErrorType\n | HashAuthorizationErrorType\n | ErrorType\n\n/**\n * Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport async function signAuthorization<to extends To = 'object'>(\n parameters: SignAuthorizationParameters<to>,\n): Promise<SignAuthorizationReturnType<to>> {\n const { chainId, nonce, privateKey, to = 'object' } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const signature = await sign({\n hash: hashAuthorization({ address, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n address,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport {\n type HashMessageErrorType,\n hashMessage,\n} from '../../utils/signature/hashMessage.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignMessageParameters = {\n /** The message to sign. */\n message: SignableMessage\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n | SignErrorType\n | HashMessageErrorType\n | ErrorType\n\n/**\n * @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signMessage({\n message,\n privateKey,\n}: SignMessageParameters): Promise<SignMessageReturnType> {\n return await sign({ hash: hashMessage(message), privateKey, to: 'hex' })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerialized,\n} from '../../types/transaction.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport {\n type SerializeTransactionFn,\n serializeTransaction,\n} from '../../utils/transaction/serializeTransaction.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTransactionParameters<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n> = {\n privateKey: Hex\n transaction: transaction\n serializer?: serializer | undefined\n}\n\nexport type SignTransactionReturnType<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n> = TransactionSerialized<GetTransactionType<transaction>>\n\nexport type SignTransactionErrorType =\n | Keccak256ErrorType\n | SignErrorType\n | ErrorType\n\nexport async function signTransaction<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n>(\n parameters: SignTransactionParameters<serializer, transaction>,\n): Promise<SignTransactionReturnType<serializer, transaction>> {\n const {\n privateKey,\n transaction,\n serializer = serializeTransaction,\n } = parameters\n\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === 'eip4844')\n return {\n ...transaction,\n sidecars: false,\n }\n return transaction\n })()\n\n const signature = await sign({\n hash: keccak256(await serializer(signableTransaction)),\n privateKey,\n })\n return (await serializer(\n transaction,\n signature,\n )) as SignTransactionReturnType<serializer, transaction>\n}\n","import type { TypedData } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition<typedData, primaryType> & {\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n | HashTypedDataErrorType\n | SignErrorType\n | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):\n * `sign(keccak256(\"\\x19\\x01\" ‖ domainSeparator ‖ hashStruct(message)))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: SignTypedDataParameters<typedData, primaryType>,\n): Promise<SignTypedDataReturnType> {\n const { privateKey, ...typedData } =\n parameters as unknown as SignTypedDataParameters\n return await sign({\n hash: hashTypedData(typedData),\n privateKey,\n to: 'hex',\n })\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\nimport type { NonceManager } from '../utils/nonceManager.js'\nimport { type ToAccountErrorType, toAccount } from './toAccount.js'\nimport type { PrivateKeyAccount } from './types.js'\nimport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nimport { type SignErrorType, sign } from './utils/sign.js'\nimport { signAuthorization } from './utils/signAuthorization.js'\nimport { type SignMessageErrorType, signMessage } from './utils/signMessage.js'\nimport {\n type SignTransactionErrorType,\n signTransaction,\n} from './utils/signTransaction.js'\nimport {\n type SignTypedDataErrorType,\n signTypedData,\n} from './utils/signTypedData.js'\n\nexport type PrivateKeyToAccountOptions = {\n nonceManager?: NonceManager | undefined\n}\n\nexport type PrivateKeyToAccountErrorType =\n | ToAccountErrorType\n | ToHexErrorType\n | PublicKeyToAddressErrorType\n | SignErrorType\n | SignMessageErrorType\n | SignTransactionErrorType\n | SignTypedDataErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a private key.\n *\n * @returns A Private Key Account.\n */\nexport function privateKeyToAccount(\n privateKey: Hex,\n options: PrivateKeyToAccountOptions = {},\n): PrivateKeyAccount {\n const { nonceManager } = options\n const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n const address = publicKeyToAddress(publicKey)\n\n const account = toAccount({\n address,\n nonceManager,\n async sign({ hash }) {\n return sign({ hash, privateKey, to: 'hex' })\n },\n async signAuthorization(authorization) {\n return signAuthorization({ ...authorization, privateKey })\n },\n async signMessage({ message }) {\n return signMessage({ message, privateKey })\n },\n async signTransaction(transaction, { serializer } = {}) {\n return signTransaction({ privateKey, transaction, serializer })\n },\n async signTypedData(typedData) {\n return signTypedData({ ...typedData, privateKey } as any)\n },\n })\n\n return {\n ...account,\n publicKey,\n source: 'privateKey',\n } as PrivateKeyAccount\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is boolean. */\nexport function abool(b: boolean): void {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/**\n * Asserts something is hash\n * TODO: remove\n * @deprecated\n */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\nexport type IHash = {\n (data: string | Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n// Used in micro\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian\n}\n\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\n// Used in micro, ff1\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// TODO: remove\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async (): Promise<void> => {};\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n// TODO: remove\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: string | Uint8Array): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = copyBytes(data);\n else throw new Error('Uint8Array expected, got ' + typeof data);\n return data;\n}\n\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n */\nexport function overlapBytes(a: Uint8Array, b: Uint8Array): boolean {\n return (\n a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)\n */\nexport function complexOverlapBytes(input: Uint8Array, output: Uint8Array): void {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Used in ARX only\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Compares 2 uint8array-s in kinda constant time. */\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// TODO: remove\n/** For runtime check if class implements interface. */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: string | Uint8Array): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\n\n/** Sync cipher: takes byte array and returns byte array. */\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\n/** Async cipher e.g. from built-in WebCrypto. */\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise<Uint8Array>;\n decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;\n};\n\n/** Cipher with `output` argument which can optimize by doing 1 less allocation. */\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n/**\n * Params are outside of return type, so it is accessible before calling constructor.\n * If function support multiple nonceLength's, we return the best one.\n */\nexport type CipherParams = {\n blockSize: number;\n nonceLength?: number;\n tagLength?: number;\n varSizeNonce?: boolean;\n};\n/** ARX cipher, like salsa or chacha. */\nexport type ARXCipher = ((\n key: Uint8Array,\n nonce: Uint8Array,\n AAD?: Uint8Array\n) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n};\nexport type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(\n params: P,\n constructor: C\n): C & P => {\n function wrappedCipher(key: Uint8Array, ...args: any[]): CipherWithOutput {\n // Validate key\n abytes(key);\n\n // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n if (!isLE) throw new Error('Non little-endian hardware is not yet supported');\n\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n if (!nonce) throw new Error('nonce / iv required');\n if (params.varSizeNonce) abytes(nonce);\n else abytes(nonce, params.nonceLength);\n }\n\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined) {\n abytes(args[1]);\n }\n\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength: number, output?: Uint8Array) => {\n if (output !== undefined) {\n if (fnLength !== 2) throw new Error('cipher output not supported');\n abytes(output);\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data: Uint8Array, output?: Uint8Array) {\n if (called) throw new Error('cannot encrypt() twice with same key + nonce');\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return (cipher as CipherWithOutput).encrypt(data, output);\n },\n decrypt(data: Uint8Array, output?: Uint8Array) {\n abytes(data);\n if (tagl && data.length < tagl)\n throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return (cipher as CipherWithOutput).decrypt(data, output);\n },\n };\n\n return wrCipher;\n }\n\n Object.assign(wrappedCipher, params);\n return wrappedCipher as C & P;\n};\n\n/** Represents salsa / chacha stream. */\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(\n expectedLength: number,\n out?: Uint8Array,\n onlyAligned = true\n): Uint8Array {\n if (out === undefined) return new Uint8Array(expectedLength);\n if (out.length !== expectedLength)\n throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);\n if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');\n return out;\n}\n\n/** Polyfill for Safari 14. */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): Uint8Array {\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(aadLength), isLE);\n setBigUint64(view, 8, BigInt(dataLength), isLE);\n return num;\n}\n\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes: Uint8Array): boolean {\n return bytes.byteOffset % 4 === 0;\n}\n\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n","/**\n * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)\n * a.k.a. Advanced Encryption Standard\n * is a variant of Rijndael block cipher, standardized by NIST in 2001.\n * We provide the fastest available pure JS implementation.\n *\n * Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n * 1. **S-box**, table substitution\n * 2. **Shift rows**, cyclic shift left of all rows of data array\n * 3. **Mix columns**, multiplying every column by fixed polynomial\n * 4. **Add round key**, round_key xor i-th column of array\n *\n * Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf)\n * and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)\n * @module\n */\nimport { ghash, polyval } from './_polyval.ts';\n// prettier-ignore\nimport {\n abytes, clean, complexOverlapBytes, concatBytes,\n copyBytes, createView, equalBytes, getOutput, isAligned32, overlapBytes,\n setBigUint64, u32, u64Lengths, u8, wrapCipher,\n type Cipher, type CipherWithOutput,\n} from './utils.ts';\n\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n\n// TODO: remove multiplication, binary ops only\nfunction mul2(n: number) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\n\nfunction mul(a: number, b: number) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n\n// Rotate u32 by 8\nconst rotr32_8 = (n: number) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n: number) => (n << 8) | (n >>> 24);\n// The byte swap operation for uint32 (LE<->BE)\nconst byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox: Uint8Array, fn: (n: number) => number) {\n if (sbox.length !== 256) throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n\nconst tableEncoding = /* @__PURE__ */ genTtable(\n sbox,\n (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)\n);\nconst tableDecoding = /* @__PURE__ */ genTtable(\n invSbox,\n (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)\n);\n\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x;\n return p;\n})();\n\n/** Key expansion used in CTR. */\nfunction expandKeyLE(key: Uint8Array): Uint32Array {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n if (!isAligned32(key)) toClean.push((key = copyBytes(key)));\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n: number) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4) t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\n\nfunction expandKeyDecLE(key: Uint8Array): Uint32Array {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n\n// Apply tables\nfunction apply0123(\n T01: Uint32Array,\n T23: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n) {\n return (\n T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]\n );\n}\n\nfunction applySbox(sbox2: Uint16Array, s0: number, s1: number, s2: number, s3: number) {\n return (\n sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)\n );\n}\n\nfunction encrypt(\n xk: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n): { s0: number; s1: number; s2: number; s3: number } {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(\n xk: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n): {\n s0: number;\n s1: number;\n s2: number;\n s3: number;\n} {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0: number = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1: number = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2: number = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3: number = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\n// TODO: investigate merging with ctr32\nfunction ctrCounter(\n xk: Uint32Array,\n nonce: Uint8Array,\n src: Uint8Array,\n dst?: Uint8Array\n): Uint8Array {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n complexOverlapBytes(src, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(\n xk: Uint32Array,\n isLE: boolean,\n nonce: Uint8Array,\n src: Uint8Array,\n dst?: Uint8Array\n): Uint8Array {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getOutput(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr: ((key: Uint8Array, nonce: Uint8Array) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function aesctr(key: Uint8Array, nonce: Uint8Array): CipherWithOutput {\n function processCtr(buf: Uint8Array, dst?: Uint8Array) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n if (!isAligned32(dst)) throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf)) toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCtr(plaintext, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCtr(ciphertext, dst),\n };\n }\n);\n\nfunction validateBlockDecrypt(data: Uint8Array) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(\n 'aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE\n );\n }\n}\n\nfunction validateBlockEncrypt(plaintext: Uint8Array, pcks5: boolean, dst?: Uint8Array) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n if (!isAligned32(plaintext)) plaintext = copyBytes(plaintext);\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n dst = getOutput(outLen, dst);\n complexOverlapBytes(plaintext, dst);\n const o = u32(dst);\n return { b, o, out: dst };\n}\n\nfunction validatePCKS(data: Uint8Array, pcks5: boolean) {\n if (!pcks5) return data;\n const len = data.length;\n if (!len) throw new Error('aes/pcks5: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16) throw new Error('aes/pcks5: wrong padding');\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte) throw new Error('aes/pcks5: wrong padding');\n return out;\n}\n\nfunction padPCKS(left: Uint8Array) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;\n return tmp32;\n}\n\n/** Options for ECB and CBC. */\nexport type BlockOpts = { disablePadding?: boolean };\n\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb: ((key: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {\n blockSize: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16 },\n function aesecb(key: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext: Uint8Array, dst?: Uint8Array) {\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(xk);\n return _out;\n },\n decrypt(ciphertext: Uint8Array, dst?: Uint8Array) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n dst = getOutput(ciphertext.length, dst);\n const toClean: (Uint8Array | Uint32Array)[] = [xk];\n if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n complexOverlapBytes(ciphertext, dst);\n const b = u32(ciphertext);\n const o = u32(dst);\n for (let i = 0; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return validatePCKS(dst, pcks5);\n },\n };\n }\n);\n\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc: ((key: Uint8Array, iv: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function aescbc(key: Uint8Array, iv: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext: Uint8Array, dst?: Uint8Array) {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n let _iv = iv;\n const toClean: (Uint8Array | Uint32Array)[] = [xk];\n if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length; ) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext: Uint8Array, dst?: Uint8Array) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n let _iv = iv;\n const toClean: (Uint8Array | Uint32Array)[] = [xk];\n if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n dst = getOutput(ciphertext.length, dst);\n if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n complexOverlapBytes(ciphertext, dst);\n const b = u32(ciphertext);\n const o = u32(dst);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length; ) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n clean(...toClean);\n return validatePCKS(dst, pcks5);\n },\n };\n }\n);\n\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb: ((key: Uint8Array, iv: Uint8Array) => CipherWithOutput) & {\n blockSize: number;\n nonceLength: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function aescfb(key: Uint8Array, iv: Uint8Array): CipherWithOutput {\n function processCfb(src: Uint8Array, isEncrypt: boolean, dst?: Uint8Array) {\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n if (overlapBytes(src, dst)) throw new Error('overlapping src and dst not supported.');\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean: (Uint8Array | Uint32Array)[] = [xk];\n if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));\n if (!isAligned32(src)) toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length; ) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCfb(ciphertext, false, dst),\n };\n }\n);\n\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(\n fn: typeof ghash,\n isLE: boolean,\n key: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n) {\n const aadLength = AAD ? AAD.length : 0;\n const h = fn.create(key, data.length + aadLength);\n if (AAD) h.update(AAD);\n const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);\n h.update(data);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n\n/**\n * GCM: Galois/Counter Mode.\n * Modern, parallel version of CTR, with MAC.\n * Be careful: MACs can be forged.\n * Unsafe to use random nonces under the same key, due to collision chance.\n * As for nonce size, prefer 12-byte, instead of 8-byte.\n */\nexport const gcm: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n varSizeNonce: true;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true },\n function aesgcm(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n // NIST 800-38d doesn't enforce minimum nonce length.\n // We enforce 8 bytes for compat with openssl.\n // 12 bytes are recommended. More than 12 bytes would be converted into 12.\n if (nonce.length < 8) throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey: Uint8Array, tagMask: Uint8Array, data: Uint8Array) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n } else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext: Uint8Array) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext: Uint8Array) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n if (!equalBytes(tag, passedTag)) throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n }\n);\n\nconst limit = (name: string, min: number, max: number) => (value: number) => {\n if (!Number.isSafeInteger(value) || min > value || value > max) {\n const minmax = '[' + min + '..' + max + ']';\n throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);\n }\n};\n\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const gcmsiv: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {\n blockSize: number;\n nonceLength: number;\n tagLength: number;\n varSizeNonce: true;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true },\n function aessiv(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key, 16, 24, 32);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined) AAD_LIMIT(AAD.length);\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean: (Uint8Array | Uint32Array)[] = [xk, encKey];\n let _nonce = nonce;\n if (!isAligned32(_nonce)) toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey: Uint32Array, authKey: Uint8Array, data: Uint8Array) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++) tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey: Uint32Array, tag: Uint8Array, input: Uint8Array) {\n let block = copyBytes(tag);\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext: Uint8Array) {\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey, tag];\n if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext: Uint8Array) {\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey];\n if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n if (!equalBytes(tag, expectedTag)) {\n clean(...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n }\n);\n\n/**\n * AES-GCM-SIV, not AES-SIV.\n * This is legace name, use `gcmsiv` export instead.\n * @deprecated\n */\nexport const siv: typeof gcmsiv = gcmsiv;\n\nfunction isBytes32(a: unknown): a is Uint32Array {\n return (\n a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array')\n );\n}\n\nfunction encryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\nfunction decryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek: Uint8Array, out: Uint8Array) {\n // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.\n // If you need it larger, open an issue.\n if (out.length >= 2 ** 32) throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n if (out.length === 16) encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i\n (a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1); // out = A || out\n }\n xk.fill(0);\n },\n decrypt(kek: Uint8Array, out: Uint8Array) {\n if (out.length - 8 >= 2 ** 32) throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n if (chunks === 1) decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1);\n }\n xk.fill(0);\n },\n};\n\nconst AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * For padded version, use aeskwp.\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).\n */\nexport const aeskw: ((kek: Uint8Array) => Cipher) & {\n blockSize: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 8 },\n (kek: Uint8Array): Cipher => ({\n encrypt(plaintext: Uint8Array) {\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext: Uint8Array) {\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV)) throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n })\n);\n\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\n\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n\n/**\n * AES-KW, but with padding and allows random keys.\n * Second u32 of IV is used as counter for length.\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)\n */\nexport const aeskwp: ((kek: Uint8Array) => Cipher) & {\n blockSize: number;\n} = /* @__PURE__ */ wrapCipher(\n { blockSize: 8 },\n (kek: Uint8Array): Cipher => ({\n encrypt(plaintext: Uint8Array) {\n if (!plaintext.length) throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = AESKWP_IV;\n out32[1] = byteSwap(plaintext.length);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext: Uint8Array) {\n // 16 because should have at least one block\n if (ciphertext.length < 16) throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(o32[1]) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0) throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n })\n);\n\n/** Unsafe low-level internal methods. May change at any time. */\nexport const unsafe: {\n expandKeyLE: typeof expandKeyLE;\n expandKeyDecLE: typeof expandKeyDecLE;\n encrypt: typeof encrypt;\n decrypt: typeof decrypt;\n encryptBlock: typeof encryptBlock;\n decryptBlock: typeof decryptBlock;\n ctrCounter: typeof ctrCounter;\n ctr32: typeof ctr32;\n} = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n","/**\n * RFC 7914 Scrypt KDF. Can be used to create a key from password and salt.\n * @module\n */\nimport { pbkdf2 } from './pbkdf2.ts';\nimport { sha256 } from './sha2.ts';\n// prettier-ignore\nimport {\n anumber, asyncLoop,\n checkOpts, clean,\n type KDFInput, rotl,\n swap32IfBE,\n u32\n} from './utils.ts';\n\n// The main Scrypt loop: uses Salsa extensively.\n// Six versions of the function were tried, this is the fastest one.\n// prettier-ignore\nfunction XorAndSalsa(\n prev: Uint32Array,\n pi: number,\n input: Uint32Array,\n ii: number,\n out: Uint32Array,\n oi: number\n) {\n // Based on https://cr.yp.to/salsa20.html\n // Xor blocks\n let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];\n let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];\n let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];\n let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];\n let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];\n let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];\n let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];\n let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];\n // Save state to temporary variables (salsa)\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n // Main loop (salsa)\n for (let i = 0; i < 8; i += 2) {\n x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);\n x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);\n x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);\n x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);\n x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);\n x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);\n x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);\n x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);\n x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);\n x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);\n x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);\n x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);\n x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);\n x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);\n x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);\n x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);\n }\n // Write output (salsa)\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n\nfunction BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) {\n // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)\n let head = oi + 0;\n let tail = oi + 16 * r;\n for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]\n for (let i = 0; i < r; i++, head += 16, ii += 16) {\n // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1\n XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])\n if (i > 0) tail += 16; // First iteration overwrites tmp value in tail\n XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])\n }\n}\n\nexport type ScryptOpts = {\n N: number; // cost factor\n r: number; // block size\n p: number; // parallelization\n dkLen?: number; // key length\n asyncTick?: number; // block execution max time\n maxmem?: number;\n onProgress?: (progress: number) => void;\n};\n\n// Common prologue and epilogue for sync/async functions\nfunction scryptInit(password: KDFInput, salt: KDFInput, _opts?: ScryptOpts) {\n // Maxmem - 1GB+1KB by default\n const opts = checkOpts(\n {\n dkLen: 32,\n asyncTick: 10,\n maxmem: 1024 ** 3 + 1024,\n },\n _opts\n );\n const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;\n anumber(N);\n anumber(r);\n anumber(p);\n anumber(dkLen);\n anumber(asyncTick);\n anumber(maxmem);\n if (onProgress !== undefined && typeof onProgress !== 'function')\n throw new Error('progressCb should be function');\n const blockSize = 128 * r;\n const blockSize32 = blockSize / 4;\n\n // Max N is 2^32 (Integrify is 32-bit). Real limit is 2^22: JS engines Uint8Array limit is 4GB in 2024.\n // Spec check `N >= 2^(blockSize / 8)` is not done for compat with popular libs,\n // which used incorrect r: 1, p: 8. Also, the check seems to be a spec error:\n // https://www.rfc-editor.org/errata_search.php?rfc=7914\n const pow32 = Math.pow(2, 32);\n if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) {\n throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32');\n }\n if (p < 0 || p > ((pow32 - 1) * 32) / blockSize) {\n throw new Error(\n 'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'\n );\n }\n if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {\n throw new Error(\n 'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'\n );\n }\n const memUsed = blockSize * (N + p);\n if (memUsed > maxmem) {\n throw new Error(\n 'Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of ' + maxmem\n );\n }\n // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)\n // Since it has only one iteration there is no reason to use async variant\n const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });\n const B32 = u32(B);\n // Re-used between parallel iterations. Array(iterations) of B\n const V = u32(new Uint8Array(blockSize * N));\n const tmp = u32(new Uint8Array(blockSize));\n let blockMixCb = () => {};\n if (onProgress) {\n const totalBlockMix = 2 * N * p;\n // Invoke callback if progress changes from 10.01 to 10.02\n // Allows to draw smooth progress bar on up to 8K screen\n const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);\n let blockMixCnt = 0;\n blockMixCb = () => {\n blockMixCnt++;\n if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))\n onProgress(blockMixCnt / totalBlockMix);\n };\n }\n return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };\n}\n\nfunction scryptOutput(\n password: KDFInput,\n dkLen: number,\n B: Uint8Array,\n V: Uint32Array,\n tmp: Uint32Array\n) {\n const res = pbkdf2(sha256, password, B, { c: 1, dkLen });\n clean(B, V, tmp);\n return res;\n}\n\n/**\n * Scrypt KDF from RFC 7914.\n * @param password - pass\n * @param salt - salt\n * @param opts - parameters\n * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)\n * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance\n * - `p` is parallelization factor (1 is common)\n * - `dkLen` is output key length in bytes e.g. 32.\n * - `asyncTick` - (default: 10) max time in ms for which async function can block execution\n * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt\n * - `onProgress` - callback function that would be executed for progress report\n * @returns Derived key\n * @example\n * scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });\n */\nexport function scrypt(password: KDFInput, salt: KDFInput, opts: ScryptOpts): Uint8Array {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(\n password,\n salt,\n opts\n );\n swap32IfBE(B32);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i]\n for (let i = 0, pos = 0; i < N - 1; i++) {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n }\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n for (let i = 0; i < N; i++) {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n }\n }\n swap32IfBE(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n\n/**\n * Scrypt KDF from RFC 7914. Async version.\n * @example\n * await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });\n */\nexport async function scryptAsync(\n password: KDFInput,\n salt: KDFInput,\n opts: ScryptOpts\n): Promise<Uint8Array> {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(\n password,\n salt,\n opts\n );\n swap32IfBE(B32);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i]\n let pos = 0;\n await asyncLoop(N - 1, asyncTick, () => {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n });\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n await asyncLoop(N, asyncTick, () => {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n });\n }\n swap32IfBE(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n","import { ctr } from '@noble/ciphers/aes'\nimport {\n pbkdf2 as pbkdf2_noble,\n pbkdf2Async as pbkdf2Async_noble,\n} from '@noble/hashes/pbkdf2'\nimport {\n scrypt as scrypt_noble,\n scryptAsync as scryptAsync_noble,\n} from '@noble/hashes/scrypt'\nimport { sha256 } from '@noble/hashes/sha2'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport type * as Hex from './Hex.js'\nimport type { OneOf } from './internal/types.js'\n\n/** Base Derivation Options. */\ntype BaseDeriveOpts<\n kdf extends string = string,\n kdfparams extends Record<string, unknown> = Record<string, unknown>,\n> = {\n iv: Bytes.Bytes\n kdfparams: kdfparams\n kdf: kdf\n}\n\n/** Keystore. */\nexport type Keystore = {\n crypto: {\n cipher: 'aes-128-ctr'\n ciphertext: string\n cipherparams: {\n iv: string\n }\n mac: string\n } & Pick<DeriveOpts, 'kdf' | 'kdfparams'>\n id: string\n version: 3\n}\n\n/** Key. */\nexport type Key = (() => Hex.Hex) | Hex.Hex\n\n/** Derivation Options. */\nexport type DeriveOpts = Pbkdf2DeriveOpts | ScryptDeriveOpts\n\n/** PBKDF2 Derivation Options. */\nexport type Pbkdf2DeriveOpts = BaseDeriveOpts<\n 'pbkdf2',\n {\n c: number\n dklen: number\n prf: 'hmac-sha256'\n salt: string\n }\n>\n\n/** Scrypt Derivation Options. */\nexport type ScryptDeriveOpts = BaseDeriveOpts<\n 'scrypt',\n {\n dklen: number\n n: number\n p: number\n r: number\n salt: string\n }\n>\n\n/**\n * Decrypts a [JSON keystore](https://ethereum.org/en/developers/docs/data-structures-and-encoding/web3-secret-storage/)\n * into a private key.\n *\n * Supports the following key derivation functions (KDFs):\n * - {@link ox#Keystore.(pbkdf2:function)}\n * - {@link ox#Keystore.(scrypt:function)}\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Keystore, Secp256k1 } from 'ox'\n *\n * // JSON keystore.\n * const keystore = { crypto: { ... }, id: '...', version: 3 }\n *\n * // Derive the key using your password.\n * const key = Keystore.toKey(keystore, { password: 'hunter2' })\n *\n * // Decrypt the private key.\n * const privateKey = Keystore.decrypt(keystore, key)\n * // @log: \"0x...\"\n * ```\n *\n * @param keystore - JSON keystore.\n * @param key - Key to use for decryption.\n * @param options - Decryption options.\n * @returns Decrypted private key.\n */\nexport function decrypt<as extends 'Hex' | 'Bytes' = 'Hex'>(\n keystore: Keystore,\n key: Key,\n options: decrypt.Options<as> = {},\n): decrypt.ReturnType<as> {\n const { as = 'Hex' } = options\n const key_ = Bytes.from(typeof key === 'function' ? key() : key)\n\n const encKey = Bytes.slice(key_, 0, 16)\n const macKey = Bytes.slice(key_, 16, 32)\n\n const ciphertext = Bytes.from(`0x${keystore.crypto.ciphertext}`)\n const mac = Hash.keccak256(Bytes.concat(macKey, ciphertext))\n\n if (!Bytes.isEqual(mac, Bytes.from(`0x${keystore.crypto.mac}`)))\n throw new Error('corrupt keystore')\n\n const data = ctr(\n encKey,\n Bytes.from(`0x${keystore.crypto.cipherparams.iv}`),\n ).decrypt(ciphertext)\n\n if (as === 'Hex') return Bytes.toHex(data) as never\n return data as never\n}\n\nexport declare namespace decrypt {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> = {\n /** Output format. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =\n | (as extends 'Hex' ? Hex.Hex : never)\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n}\n\n/**\n * Encrypts a private key as a [JSON keystore](https://ethereum.org/en/developers/docs/data-structures-and-encoding/web3-secret-storage/)\n * using a derived key.\n *\n * Supports the following key derivation functions (KDFs):\n * - {@link ox#Keystore.(pbkdf2:function)}\n * - {@link ox#Keystore.(scrypt:function)}\n *\n * @example\n * ```ts twoslash\n * import { Keystore, Secp256k1 } from 'ox'\n *\n * // Generate a random private key.\n * const privateKey = Secp256k1.randomPrivateKey()\n *\n * // Derive key from password.\n * const [key, opts] = Keystore.pbkdf2({ password: 'testpassword' })\n *\n * // Encrypt the private key.\n * const encrypted = Keystore.encrypt(privateKey, key, opts)\n * // @log: {\n * // @log: \"crypto\": {\n * // @log: \"cipher\": \"aes-128-ctr\",\n * // @log: \"ciphertext\": \"...\",\n * // @log: \"cipherparams\": {\n * // @log: \"iv\": \"...\",\n * // @log: },\n * // @log: \"kdf\": \"pbkdf2\",\n * // @log: \"kdfparams\": {\n * // @log: \"salt\": \"...\",\n * // @log: \"dklen\": 32,\n * // @log: \"prf\": \"hmac-sha256\",\n * // @log: \"c\": 262144,\n * // @log: },\n * // @log: \"mac\": \"...\",\n * // @log: },\n * // @log: \"id\": \"...\",\n * // @log: \"version\": 3,\n * // @log: }\n * ```\n *\n * @param privateKey - Private key to encrypt.\n * @param key - Key to use for encryption.\n * @param options - Encryption options.\n * @returns Encrypted keystore.\n */\nexport function encrypt(\n privateKey: Bytes.Bytes | Hex.Hex,\n key: Key,\n options: encrypt.Options,\n): Keystore {\n const { id = crypto.randomUUID(), kdf, kdfparams, iv } = options\n\n const key_ = Bytes.from(typeof key === 'function' ? key() : key)\n const value_ = Bytes.from(privateKey)\n\n const encKey = Bytes.slice(key_, 0, 16)\n const macKey = Bytes.slice(key_, 16, 32)\n\n const ciphertext = ctr(encKey, iv).encrypt(value_)\n const mac = Hash.keccak256(Bytes.concat(macKey, ciphertext))\n\n return {\n crypto: {\n cipher: 'aes-128-ctr',\n ciphertext: Bytes.toHex(ciphertext).slice(2),\n cipherparams: { iv: Bytes.toHex(iv).slice(2) },\n kdf,\n kdfparams,\n mac: Bytes.toHex(mac).slice(2),\n } as Keystore['crypto'],\n id,\n version: 3,\n }\n}\n\nexport declare namespace encrypt {\n type Options = DeriveOpts & {\n /** UUID. */\n id?: string | undefined\n }\n}\n\n/**\n * Derives a key from a password using [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2).\n *\n * @example\n * ```ts twoslash\n * import { Keystore } from 'ox'\n *\n * const [key, opts] = Keystore.pbkdf2({ password: 'testpassword' })\n * ```\n *\n * @param options - PBKDF2 options.\n * @returns PBKDF2 key.\n */\nexport function pbkdf2(options: pbkdf2.Options) {\n const { iv, iterations = 262_144, password } = options\n\n const salt = options.salt ? Bytes.from(options.salt) : Bytes.random(32)\n const key = Bytes.toHex(\n pbkdf2_noble(sha256, password, salt, { c: iterations, dkLen: 32 }),\n )\n\n return defineKey(() => key, {\n iv,\n kdfparams: {\n c: iterations,\n dklen: 32,\n prf: 'hmac-sha256',\n salt: Bytes.toHex(salt).slice(2),\n },\n kdf: 'pbkdf2',\n }) satisfies [Key, Pbkdf2DeriveOpts]\n}\n\nexport declare namespace pbkdf2 {\n type Options = {\n /** The counter to use for the AES-CTR encryption. */\n iv?: Bytes.Bytes | Hex.Hex | undefined\n /** The number of iterations to use. @default 262_144 */\n iterations?: number | undefined\n /** Password to derive key from. */\n password: string\n /** Salt to use for key derivation. @default `Bytes.random(32)` */\n salt?: Bytes.Bytes | Hex.Hex | undefined\n }\n}\n\n/**\n * Derives a key from a password using [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2).\n *\n * @example\n * ```ts twoslash\n * import { Keystore } from 'ox'\n *\n * const [key, opts] = await Keystore.pbkdf2Async({ password: 'testpassword' })\n * ```\n *\n * @param options - PBKDF2 options.\n * @returns PBKDF2 key.\n */\nexport async function pbkdf2Async(options: pbkdf2.Options) {\n const { iv, iterations = 262_144, password } = options\n\n const salt = options.salt ? Bytes.from(options.salt) : Bytes.random(32)\n const key = Bytes.toHex(\n await pbkdf2Async_noble(sha256, password, salt, {\n c: iterations,\n dkLen: 32,\n }),\n )\n\n return defineKey(() => key, {\n iv,\n kdfparams: {\n c: iterations,\n dklen: 32,\n prf: 'hmac-sha256',\n salt: Bytes.toHex(salt).slice(2),\n },\n kdf: 'pbkdf2',\n }) satisfies [Key, Pbkdf2DeriveOpts]\n}\n\nexport declare namespace pbkdf2Async {\n type Options = pbkdf2.Options\n}\n\n/**\n * Derives a key from a password using [scrypt](https://en.wikipedia.org/wiki/Scrypt).\n *\n * @example\n * ```ts twoslash\n * import { Keystore } from 'ox'\n *\n * const [key, opts] = Keystore.scrypt({ password: 'testpassword' })\n * ```\n *\n * @param options - Scrypt options.\n * @returns Scrypt key.\n */\nexport function scrypt(options: scrypt.Options) {\n const { iv, n = 262_144, password, p = 8, r = 1 } = options\n\n const salt = options.salt ? Bytes.from(options.salt) : Bytes.random(32)\n const key = Bytes.toHex(\n scrypt_noble(password, salt, { N: n, dkLen: 32, r, p }),\n )\n\n return defineKey(() => key, {\n iv,\n kdfparams: {\n dklen: 32,\n n,\n p,\n r,\n salt: Bytes.toHex(salt).slice(2),\n },\n kdf: 'scrypt',\n }) satisfies [Key, ScryptDeriveOpts]\n}\n\nexport declare namespace scrypt {\n type Options = {\n /** The counter to use for the AES-CTR encryption. */\n iv?: Bytes.Bytes | Hex.Hex | undefined\n /** Cost factor. @default 262_144 */\n n?: number | undefined\n /** Parallelization factor. @default 8 */\n p?: number | undefined\n /** Block size. @default 1 */\n r?: number | undefined\n /** Password to derive key from. */\n password: string\n /** Salt to use for key derivation. @default `Bytes.random(32)` */\n salt?: Bytes.Bytes | Hex.Hex | undefined\n }\n}\n\n/**\n * Derives a key from a password using [scrypt](https://en.wikipedia.org/wiki/Scrypt).\n *\n * @example\n * ```ts twoslash\n * import { Keystore } from 'ox'\n *\n * const [key, opts] = await Keystore.scryptAsync({ password: 'testpassword' })\n * ```\n *\n * @param options - Scrypt options.\n * @returns Scrypt key.\n */\nexport async function scryptAsync(options: scrypt.Options) {\n const { iv, n = 262_144, password } = options\n\n const p = 8\n const r = 1\n\n const salt = options.salt ? Bytes.from(options.salt) : Bytes.random(32)\n const key = Bytes.toHex(\n await scryptAsync_noble(password, salt, { N: n, dkLen: 32, r, p }),\n )\n\n return defineKey(() => key, {\n iv,\n kdfparams: {\n dklen: 32,\n n,\n p,\n r,\n salt: Bytes.toHex(salt).slice(2),\n },\n kdf: 'scrypt',\n }) satisfies [Key, ScryptDeriveOpts]\n}\n\nexport declare namespace scryptAsync {\n type Options = scrypt.Options\n}\n\n/**\n * Extracts a Key from a JSON Keystore to use for decryption.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Keystore } from 'ox'\n *\n * // JSON keystore.\n * const keystore = { crypto: { ... }, id: '...', version: 3 }\n *\n * const key = Keystore.toKey(keystore, { password: 'hunter2' }) // [!code focus]\n *\n * const decrypted = Keystore.decrypt(keystore, key)\n * ```\n *\n * @param keystore - JSON Keystore\n * @param options - Options\n * @returns Key\n */\nexport function toKey(keystore: Keystore, options: toKey.Options): Key {\n const { crypto } = keystore\n const { password } = options\n const { cipherparams, kdf, kdfparams } = crypto\n const { iv } = cipherparams\n const { c, n, p, r, salt } = kdfparams as OneOf<\n Pbkdf2DeriveOpts['kdfparams'] | ScryptDeriveOpts['kdfparams']\n >\n\n const [key] = (() => {\n switch (kdf) {\n case 'scrypt':\n return scrypt({\n iv: Bytes.from(`0x${iv}`),\n n,\n p,\n r,\n salt: Bytes.from(`0x${salt}`),\n password,\n })\n case 'pbkdf2':\n return pbkdf2({\n iv: Bytes.from(`0x${iv}`),\n iterations: c,\n password,\n salt: Bytes.from(`0x${salt}`),\n })\n default:\n throw new Error('unsupported kdf')\n }\n })()\n\n return key\n}\n\nexport declare namespace toKey {\n type Options = {\n /** Password to derive key from. */\n password: string\n }\n}\n\n/**\n * Extracts a Key asynchronously from a JSON Keystore to use for decryption.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Keystore } from 'ox'\n *\n * // JSON keystore.\n * const keystore = { crypto: { ... }, id: '...', version: 3 }\n *\n * const key = await Keystore.toKeyAsync(keystore, { password: 'hunter2' }) // [!code focus]\n *\n * const decrypted = Keystore.decrypt(keystore, key)\n * ```\n *\n * @param keystore - JSON Keystore\n * @param options - Options\n * @returns Key\n */\nexport async function toKeyAsync(\n keystore: Keystore,\n options: toKeyAsync.Options,\n): Promise<Key> {\n const { crypto } = keystore\n const { password } = options\n const { cipherparams, kdf, kdfparams } = crypto\n const { iv } = cipherparams\n const { c, n, p, r, salt } = kdfparams as OneOf<\n Pbkdf2DeriveOpts['kdfparams'] | ScryptDeriveOpts['kdfparams']\n >\n\n const [key] = await (async () => {\n switch (kdf) {\n case 'scrypt':\n return await scryptAsync({\n iv: Bytes.from(`0x${iv}`),\n n,\n p,\n r,\n salt: Bytes.from(`0x${salt}`),\n password,\n })\n case 'pbkdf2':\n return await pbkdf2({\n iv: Bytes.from(`0x${iv}`),\n iterations: c,\n password,\n salt: Bytes.from(`0x${salt}`),\n })\n default:\n throw new Error('unsupported kdf')\n }\n })()\n\n return key\n}\n\nexport declare namespace toKeyAsync {\n type Options = {\n /** Password to derive key from. */\n password: string\n }\n}\n\n///////////////////////////////////////////////////////////////////////////\n\n/** @internal */\n// biome-ignore lint/correctness/noUnusedVariables: _\nfunction defineKey<\n const key extends Key,\n const options extends defineKey.Options,\n>(key: key, options: options): [key, options & { iv: Bytes.Bytes }] {\n const iv = options.iv ? Bytes.from(options.iv) : Bytes.random(16)\n return [key, { ...options, iv }] as never\n}\n\n/** @internal */\ndeclare namespace defineKey {\n type Options<\n kdf extends string = string,\n kdfparams extends Record<string, unknown> = Record<string, unknown>,\n > = Omit<BaseDeriveOpts<kdf, kdfparams>, 'iv'> & {\n iv?: Bytes.Bytes | Hex.Hex | undefined\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import { Worker } from 'node:worker_threads';\nimport type * as Keystore from 'ox/Keystore';\n\nexport interface KeystoreDerivationOptions {\n /** Pure computation only: this never cancels credential-store reads or writes. */\n signal?: AbortSignal;\n /** A single derivation's bound; interactive wallet callers allow up to two minutes. */\n timeoutMs?: number;\n}\n\n/**\n * Scrypt's CPU work stays in a disposable worker so timers remain responsive.\n * The worker accelerates the existing wallet parameters with hash-wasm and\n * retains Ox for other shapes; native OpenSSL scrypt rejects N=262144,r=1,p=8.\n * No credential-store operation or payment signature runs in this worker.\n */\nexport async function deriveKeystoreKey(\n keystore: Keystore.Keystore,\n password: string,\n options: KeystoreDerivationOptions = {},\n): Promise<Keystore.Key> {\n const timeoutMs = options.timeoutMs ?? 120_000;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000)\n throw new Error('Keystore derivation timeout must be between 1 and 120000 milliseconds.');\n if (options.signal?.aborted) throw derivationError('AbortError');\n\n // Source tests run the .ts worker through native type stripping (unflagged from Node 22.18).\n // Every bundled entry and code-split chunk is adjacent to the worker in dist.\n const url = new URL(\n import.meta.url.endsWith('.ts') ? './keystore-kdf-worker.ts' : './wallet-kdf-worker.mjs',\n import.meta.url,\n );\n return new Promise<Keystore.Key>((resolve, reject) => {\n const worker = new Worker(url, { workerData: { keystore, password }, execArgv: [] });\n let settled = false;\n const onAbort = () => finish(derivationError('AbortError'));\n function finish(error?: Error, key?: Keystore.Key): void {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n options.signal?.removeEventListener('abort', onAbort);\n // Await termination before the caller continues, so timeout/success never\n // accumulates background KDF workers or leaves an abandoned key producer.\n void worker.terminate().then(\n () => (error ? reject(error) : resolve(key!)),\n () => reject(new Error('Keystore derivation worker could not terminate.')),\n );\n }\n worker.once('message', (message: unknown) => {\n if (\n typeof message === 'object' &&\n message !== null &&\n 'key' in message &&\n typeof message.key === 'string' &&\n /^0x[0-9a-fA-F]{64}$/.test(message.key)\n ) {\n finish(undefined, message.key as `0x${string}`);\n } else finish(new Error('Keystore derivation failed.'));\n });\n worker.once('error', () => finish(new Error('Keystore derivation worker failed.')));\n worker.once('exit', () => {\n if (!settled) finish(new Error('Keystore derivation worker exited without a result.'));\n });\n const timer = setTimeout(() => finish(derivationError('TimeoutError')), timeoutMs);\n options.signal?.addEventListener('abort', onAbort, { once: true });\n if (options.signal?.aborted) onAbort();\n });\n}\n\nfunction derivationError(name: 'AbortError' | 'TimeoutError'): Error {\n return Object.assign(\n new Error(`Keystore derivation ${name === 'AbortError' ? 'aborted' : 'timed out'}.`),\n {\n name,\n },\n );\n}\n","import { CliError } from '../errors';\nimport { emitNotice } from '../output';\nimport { spendLedgerPath } from '../paths';\nimport { createLocalProvider, type PassphraseOverrides, type WalletWarning } from './local';\nimport { createLocalSpendAuthorizer, type SpendAuthorizer } from './spend';\nimport type { SpendPolicy } from '../policy';\nimport type { CommandContext } from '../../context';\nimport type { WalletDescription, WalletProvider } from './provider';\n\nexport * from './provider';\nexport {\n commitLocalWallet,\n createLocalWallet,\n openKeystore,\n parkOutgoingWallet,\n prepareLocalWallet,\n repairLocalWalletPassphrase,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n verifyLocalWallet,\n type ArchivedPassphraseLocation,\n type ArchivedWalletInfo,\n type CreatePassphrase,\n type LocalWalletInfo,\n type PreparedLocalWallet,\n type PassphraseOverrides,\n type PreservedWalletInfo,\n type RepairOutcome,\n type UnarchivedReason,\n type WalletWarning,\n} from './local';\nexport { classifyUnlockError, ENV_PASSPHRASE_WRONG, type UnlockReason } from '../wallet-unlock';\nexport {\n createLocalSpendAuthorizer,\n type SpendAuthorizer,\n type SpendAuthorization,\n type SpendRequest,\n} from './spend';\n\nexport interface ResolveWalletProviderOptions {\n /** Test-injection seam: bypass the local provider with a fake (e.g. a remote stub). */\n provider?: WalletProvider;\n /**\n * Passphrase seams (keychain exec, platform) for the local provider. `doctor`\n * threads its own through so a test never reaches the developer's real OS\n * credential store; `isTTY` is still decided here, never by a caller.\n */\n passphrase?: Omit<PassphraseOverrides, 'isTTY'>;\n /**\n * Where a wallet warning goes (today: TENJIN_WALLET_PASSPHRASE is set but\n * wrong, and a saved passphrase signed instead). Default for CLI commands: a\n * dim stderr notice, `emitNotice(ctx.io, w.message, { json: ctx.flags.json })`.\n * `tenjin mcp` routes it to the router observer instead.\n */\n onWarning?: (w: WalletWarning) => void;\n}\n\n/**\n * The commands' one entry to a wallet. Production always gets the `local`\n * provider bound to the context's data dir and process env; tests pass\n * `opts.provider` to prove `show`/`balance` work against any provider without a\n * real key on disk.\n *\n * The context's interactivity is threaded into the passphrase resolver: a\n * non-interactive context (io.isTTY:false — every `tenjin mcp` context, and any\n * piped-stdout run) can NEVER trigger a hidden-input passphrase prompt, which\n * under the MCP stdio transport would fight the transport for stdin. It fails with\n * the coded no-passphrase error instead. This mirrors pay's confirm gate, which\n * already declines when !ctx.io.isTTY. A real TTY passes isTTY:undefined, keeping\n * the resolver's existing process.stdin.isTTY default untouched.\n */\nexport function resolveWalletProvider(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): WalletProvider {\n if (opts.provider !== undefined) return opts.provider;\n return createLocalProvider({\n dir: ctx.dataDir,\n env: process.env,\n passphrase: { ...opts.passphrase, isTTY: ctx.io.isTTY ? undefined : false },\n onWarning: opts.onWarning ?? ((w) => emitNotice(ctx.io, w.message, { json: ctx.flags.json })),\n });\n}\n\nexport interface ResolveSpendAuthorizerOptions {\n /** Test-injection seam: bypass the local authorizer (e.g. a provider-enforced stub). */\n authorizer?: SpendAuthorizer;\n}\n\n/**\n * The commands' one entry to spend enforcement. Production gets the local\n * (client-only) authorizer bound to the context's data dir and the resolved\n * policy; a future hosted provider returns its own provider-enforced authorizer\n * here, and every spend path already routes through it.\n *\n * The corrupt-ledger notice is attached here because this is the only place the\n * local authorizer meets a context: the authorizer fails open on an unreadable\n * ledger (a spend must not be blocked by a local cache), and this line is what\n * keeps that reset from being invisible to the human whose budget just reset.\n */\nexport function resolveSpendAuthorizer(\n ctx: CommandContext,\n policy: SpendPolicy,\n opts: ResolveSpendAuthorizerOptions = {},\n): SpendAuthorizer {\n if (opts.authorizer !== undefined) return opts.authorizer;\n return createLocalSpendAuthorizer({\n dir: ctx.dataDir,\n policy,\n onCorrupt: (reason) =>\n emitNotice(\n ctx.io,\n `spend ledger at ${spendLedgerPath(ctx.dataDir)} was unreadable (${reason}); spending window restarted`,\n { json: ctx.flags.json },\n ),\n });\n}\n\n/**\n * Call `describe()` through the error contract: a CliError (e.g. WALLET_MISSING\n * from the local provider) passes through, but any other rejection — a remote\n * provider's network/refusal error — normalizes to PROVIDER_ERROR so callers\n * always see a coded failure, never a bare stack trace.\n */\nexport async function describeWallet(provider: WalletProvider): Promise<WalletDescription> {\n try {\n return await provider.describe();\n } catch (err) {\n if (err instanceof CliError) throw err;\n const message = err instanceof Error ? err.message : 'unknown error';\n throw new CliError('PROVIDER_ERROR', `Wallet provider \"${provider.id}\" failed: ${message}`, {\n fix: 'Check the wallet provider and try again.',\n cause: err,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AAyB/B,IAAM,mBAAmB,iBAAE,OAAO;AAAA,EAChC,QAAQ,iBAAE,OAAO;AAAA,IACf,QAAQ,iBAAE,QAAQ,aAAa;AAAA,IAC/B,YAAY,iBAAE,OAAO;AAAA,IACrB,cAAc,iBAAE,OAAO,EAAE,IAAI,iBAAE,OAAO,EAAE,CAAC;AAAA,IACzC,KAAK,iBAAE,KAAK,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A,QACA,OAAsC,CAAC,GACtB;AACjB,MAAI,KAAK,eAAe,OAAW,QAAO,KAAK;AAC/C,SAAO,2BAA2B;AAAA,IAChC,KAAK,IAAI;AAAA,IACT;AAAA,IACA,WAAW,CAAC,WACV;AAAA,MACE,IAAI;AAAA,MACJ,mBAAmB,gBAAgB,IAAI,OAAO,CAAC,oBAAoB,MAAM;AAAA,MACzE,EAAE,MAAM,IAAI,MAAM,KAAK;AAAA,IACzB;AAAA,EACJ,CAAC;AACH;AAQA,eAAsB,eAAe,UAAsD;AACzF,MAAI;AACF,WAAO,MAAM,SAAS,SAAS;AAAA,EACjC,SAAS,KAAK;AACZ,QAAI,eAAe,SAAU,OAAM;AACnC,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;AACrD,UAAM,IAAI,SAAS,kBAAkB,oBAAoB,SAAS,EAAE,aAAa,OAAO,IAAI;AAAA,MAC1F,KAAK;AAAA,MACL,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":["stat","u32","clean","clean","sbox","sbox2","u32","clean","t0","t1","t2","t3","ctr","u32","i","clean","clean","keccak256","toHex","encrypt","scryptAsync","toHex","stat","from","scryptAsync","encrypt"]}
|