tenjin-cli 0.1.0-alpha.0 → 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/NOTICE.md +33 -0
  2. package/README.md +575 -50
  3. package/dist/{_esm-ZH2J4QEH.js → _esm-C5CRWCYU.js} +2 -2
  4. package/dist/_esm-N4KAVXQR.js +881 -0
  5. package/dist/buy-FMDBZ4NY.js +44 -0
  6. package/dist/candidate-7LAELUQD.js +23 -0
  7. package/dist/ccip-RPPPKTJR.js +19 -0
  8. package/dist/{ccip-FXWZDDF5.js → ccip-ZGGWQN4X.js} +6 -5
  9. package/dist/chunk-2GSRYTZS.js +127 -0
  10. package/dist/chunk-2GSRYTZS.js.map +1 -0
  11. package/dist/chunk-2I4QTOLB.js +11 -0
  12. package/dist/chunk-2I4QTOLB.js.map +1 -0
  13. package/dist/chunk-36X2CA3N.js +311 -0
  14. package/dist/chunk-36X2CA3N.js.map +1 -0
  15. package/dist/{chunk-F5DZJLU3.js → chunk-47PP7TAG.js} +1441 -634
  16. package/dist/chunk-47PP7TAG.js.map +1 -0
  17. package/dist/chunk-5JMKIDMM.js +316 -0
  18. package/dist/chunk-5JMKIDMM.js.map +1 -0
  19. package/dist/chunk-5JXAZP7H.js +206 -0
  20. package/dist/chunk-5JXAZP7H.js.map +1 -0
  21. package/dist/chunk-5SE6BJRP.js +135 -0
  22. package/dist/chunk-5SE6BJRP.js.map +1 -0
  23. package/dist/chunk-6BZLSRNU.js +149 -0
  24. package/dist/chunk-6BZLSRNU.js.map +1 -0
  25. package/dist/{chunk-PAAL45FJ.js → chunk-7FK2UN2T.js} +3410 -412
  26. package/dist/chunk-7FK2UN2T.js.map +1 -0
  27. package/dist/chunk-7WDY4AXV.js +14620 -0
  28. package/dist/chunk-7WDY4AXV.js.map +1 -0
  29. package/dist/chunk-A6KCZPNQ.js +83 -0
  30. package/dist/chunk-A6KCZPNQ.js.map +1 -0
  31. package/dist/chunk-AWQ6A4CI.js +341 -0
  32. package/dist/chunk-AWQ6A4CI.js.map +1 -0
  33. package/dist/chunk-BJJ5BQO6.js +162 -0
  34. package/dist/chunk-BJJ5BQO6.js.map +1 -0
  35. package/dist/chunk-BUDHTDKL.js +612 -0
  36. package/dist/chunk-BUDHTDKL.js.map +1 -0
  37. package/dist/chunk-DKQMJTG7.js +188 -0
  38. package/dist/chunk-DKQMJTG7.js.map +1 -0
  39. package/dist/chunk-FKSAUOJU.js +137 -0
  40. package/dist/chunk-FKSAUOJU.js.map +1 -0
  41. package/dist/chunk-GECSWJ7O.js +1645 -0
  42. package/dist/chunk-GECSWJ7O.js.map +1 -0
  43. package/dist/chunk-GSDZRCGF.js +105 -0
  44. package/dist/chunk-GSDZRCGF.js.map +1 -0
  45. package/dist/chunk-JSSIMGQT.js +174 -0
  46. package/dist/chunk-JSSIMGQT.js.map +1 -0
  47. package/dist/chunk-KYH4KPE5.js +1357 -0
  48. package/dist/chunk-KYH4KPE5.js.map +1 -0
  49. package/dist/chunk-KYQVEKP5.js +209 -0
  50. package/dist/chunk-KYQVEKP5.js.map +1 -0
  51. package/dist/chunk-KZAAWQNP.js +6199 -0
  52. package/dist/chunk-KZAAWQNP.js.map +1 -0
  53. package/dist/{chunk-SXQQ2ZSR.js → chunk-M2O56UK7.js} +243 -75
  54. package/dist/chunk-M2O56UK7.js.map +1 -0
  55. package/dist/chunk-MD7WGYYI.js +125 -0
  56. package/dist/chunk-MD7WGYYI.js.map +1 -0
  57. package/dist/chunk-MJZZTKCC.js +323 -0
  58. package/dist/chunk-MJZZTKCC.js.map +1 -0
  59. package/dist/chunk-O6CAUZGY.js +317 -0
  60. package/dist/chunk-O6CAUZGY.js.map +1 -0
  61. package/dist/chunk-P74I3WH4.js +204 -0
  62. package/dist/chunk-P74I3WH4.js.map +1 -0
  63. package/dist/chunk-POF7HPRV.js +145 -0
  64. package/dist/chunk-POF7HPRV.js.map +1 -0
  65. package/dist/chunk-POJRB2AE.js +83 -0
  66. package/dist/chunk-POJRB2AE.js.map +1 -0
  67. package/dist/{chunk-FIYZLITH.js → chunk-PZRAAAY2.js} +107 -18
  68. package/dist/chunk-PZRAAAY2.js.map +1 -0
  69. package/dist/chunk-PZSUWDF2.js +35 -0
  70. package/dist/chunk-PZSUWDF2.js.map +1 -0
  71. package/dist/chunk-QW2Q2KAH.js +27 -0
  72. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  73. package/dist/chunk-R2VLGNFD.js +181 -0
  74. package/dist/chunk-R2VLGNFD.js.map +1 -0
  75. package/dist/{chunk-CPUZRZ2A.js → chunk-RBJPAZFI.js} +25 -170
  76. package/dist/chunk-RBJPAZFI.js.map +1 -0
  77. package/dist/chunk-S5RYMCV6.js +70 -0
  78. package/dist/chunk-S5RYMCV6.js.map +1 -0
  79. package/dist/chunk-SGK2B724.js +67 -0
  80. package/dist/chunk-SGK2B724.js.map +1 -0
  81. package/dist/chunk-STND72DS.js +242 -0
  82. package/dist/chunk-STND72DS.js.map +1 -0
  83. package/dist/chunk-TEL27PR5.js +124 -0
  84. package/dist/chunk-TEL27PR5.js.map +1 -0
  85. package/dist/chunk-TWRYSGAW.js +134 -0
  86. package/dist/chunk-TWRYSGAW.js.map +1 -0
  87. package/dist/{chunk-WOHCAMDQ.js → chunk-U5S527PP.js} +1887 -1029
  88. package/dist/chunk-U5S527PP.js.map +1 -0
  89. package/dist/chunk-UHTVXQ2O.js +140 -0
  90. package/dist/chunk-UHTVXQ2O.js.map +1 -0
  91. package/dist/chunk-UOJRKQTZ.js +213 -0
  92. package/dist/chunk-UOJRKQTZ.js.map +1 -0
  93. package/dist/chunk-V4WWTZHZ.js +233 -0
  94. package/dist/chunk-V4WWTZHZ.js.map +1 -0
  95. package/dist/chunk-VRRLTZ2Q.js +651 -0
  96. package/dist/chunk-VRRLTZ2Q.js.map +1 -0
  97. package/dist/{chunk-TX5T3LKJ.js → chunk-W6R3HAAG.js} +21 -17
  98. package/dist/{chunk-TX5T3LKJ.js.map → chunk-W6R3HAAG.js.map} +1 -1
  99. package/dist/chunk-X3OOVSPX.js +154 -0
  100. package/dist/chunk-X3OOVSPX.js.map +1 -0
  101. package/dist/chunk-XJN5WUKL.js +204 -0
  102. package/dist/chunk-XJN5WUKL.js.map +1 -0
  103. package/dist/chunk-Y7ERTA7D.js +146 -0
  104. package/dist/chunk-Y7ERTA7D.js.map +1 -0
  105. package/dist/chunk-YLYINX2H.js +7806 -0
  106. package/dist/chunk-YLYINX2H.js.map +1 -0
  107. package/dist/chunk-ZQIQ55KK.js +51 -0
  108. package/dist/chunk-ZQIQ55KK.js.map +1 -0
  109. package/dist/chunk-ZUAQRIVP.js +1369 -0
  110. package/dist/chunk-ZUAQRIVP.js.map +1 -0
  111. package/dist/{chunk-3IMLRUZE.js → chunk-ZXTAQYNA.js} +6 -2
  112. package/dist/chunk-ZXTAQYNA.js.map +1 -0
  113. package/dist/{cli-LMHGCZ5S.js → cli-HK2XAWNW.js} +438 -177
  114. package/dist/cli-HK2XAWNW.js.map +1 -0
  115. package/dist/config-LYCHHNAJ.js +26 -0
  116. package/dist/config-LYCHHNAJ.js.map +1 -0
  117. package/dist/dist-U4M6QCKE.js +2842 -0
  118. package/dist/dist-U4M6QCKE.js.map +1 -0
  119. package/dist/doctor-2KPUQURC.js +27 -0
  120. package/dist/doctor-2KPUQURC.js.map +1 -0
  121. package/dist/edit-TST3OCKQ.js +38 -0
  122. package/dist/edit-TST3OCKQ.js.map +1 -0
  123. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js +18 -0
  124. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js.map +1 -0
  125. package/dist/index.js +1 -1
  126. package/dist/inspect-TPTHVPBB.js +35 -0
  127. package/dist/inspect-TPTHVPBB.js.map +1 -0
  128. package/dist/install-PT3XEDJ6.js +1869 -0
  129. package/dist/install-PT3XEDJ6.js.map +1 -0
  130. package/dist/{mine.wasm-GQECMSGN.js → mine.wasm-6PIT3DK6.js} +2 -2
  131. package/dist/outcome-NPNSF2Q7.js +22 -0
  132. package/dist/outcome-NPNSF2Q7.js.map +1 -0
  133. package/dist/publish-XP5SEWST.js +41 -0
  134. package/dist/publish-XP5SEWST.js.map +1 -0
  135. package/dist/read-D4VXRWOG.js +158 -0
  136. package/dist/read-D4VXRWOG.js.map +1 -0
  137. package/dist/run-3IPGEXW7.js +16902 -0
  138. package/dist/run-3IPGEXW7.js.map +1 -0
  139. package/dist/search-YOBD6VDI.js +24 -0
  140. package/dist/search-YOBD6VDI.js.map +1 -0
  141. package/dist/{secp256k1-35YNNB6F.js → secp256k1-XRPVBC6V.js} +5 -4
  142. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  143. package/dist/send-BWNP6WN4.js +223 -0
  144. package/dist/send-BWNP6WN4.js.map +1 -0
  145. package/dist/session-GZEZBOMI.js +88 -0
  146. package/dist/session-GZEZBOMI.js.map +1 -0
  147. package/dist/skill-heal-OK6YALW6.js +85 -0
  148. package/dist/skill-heal-OK6YALW6.js.map +1 -0
  149. package/dist/usdc-4VCDHFWX.js +38 -0
  150. package/dist/usdc-4VCDHFWX.js.map +1 -0
  151. package/dist/viemAdapter-By13KInL-TUQJBMHM.js +14 -0
  152. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  153. package/dist/wallet-5RHDFPN2.js +32 -0
  154. package/dist/wallet-5RHDFPN2.js.map +1 -0
  155. package/dist/wallet-YEGQBWWL.js +42 -0
  156. package/dist/wallet-YEGQBWWL.js.map +1 -0
  157. package/docs/agent-permissions.md +281 -0
  158. package/package.json +26 -17
  159. package/skills/tenjin/SKILL.md +364 -0
  160. package/skills/tenjin-publish/SKILL.md +219 -0
  161. package/skills/tenjin-search/SKILL.md +335 -0
  162. package/dist/chunk-376LHMK2.js +0 -100
  163. package/dist/chunk-376LHMK2.js.map +0 -1
  164. package/dist/chunk-CPUZRZ2A.js.map +0 -1
  165. package/dist/chunk-F5DZJLU3.js.map +0 -1
  166. package/dist/chunk-FIYZLITH.js.map +0 -1
  167. package/dist/chunk-LTTRND4A.js +0 -135
  168. package/dist/chunk-LTTRND4A.js.map +0 -1
  169. package/dist/chunk-PAAL45FJ.js.map +0 -1
  170. package/dist/chunk-QHIEYBLV.js +0 -320
  171. package/dist/chunk-QHIEYBLV.js.map +0 -1
  172. package/dist/chunk-SXQQ2ZSR.js.map +0 -1
  173. package/dist/chunk-WOHCAMDQ.js.map +0 -1
  174. package/dist/chunk-ZPZFPVDN.js +0 -67
  175. package/dist/chunk-ZPZFPVDN.js.map +0 -1
  176. package/dist/cli-LMHGCZ5S.js.map +0 -1
  177. package/dist/config-XVXZ3V2Q.js +0 -206
  178. package/dist/config-XVXZ3V2Q.js.map +0 -1
  179. package/dist/doctor-MVLZRVPU.js +0 -338
  180. package/dist/doctor-MVLZRVPU.js.map +0 -1
  181. package/dist/usdc-OQUOFF6R.js +0 -18
  182. package/dist/wallet-NRKWLKHX.js +0 -153
  183. package/dist/wallet-NRKWLKHX.js.map +0 -1
  184. package/dist/wallet-QUWK2PA4.js +0 -22
  185. /package/dist/{_esm-ZH2J4QEH.js.map → _esm-C5CRWCYU.js.map} +0 -0
  186. /package/dist/{ccip-FXWZDDF5.js.map → _esm-N4KAVXQR.js.map} +0 -0
  187. /package/dist/{chunk-3IMLRUZE.js.map → buy-FMDBZ4NY.js.map} +0 -0
  188. /package/dist/{secp256k1-35YNNB6F.js.map → candidate-7LAELUQD.js.map} +0 -0
  189. /package/dist/{usdc-OQUOFF6R.js.map → ccip-RPPPKTJR.js.map} +0 -0
  190. /package/dist/{wallet-QUWK2PA4.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  191. /package/dist/{mine.wasm-GQECMSGN.js.map → mine.wasm-6PIT3DK6.js.map} +0 -0
@@ -0,0 +1,1645 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ PRIVATE_KEY_RE,
4
+ WALLET_SCHEMA_VERSION,
5
+ readWalletRecord,
6
+ walletFileMode,
7
+ writeWalletRecord
8
+ } from "./chunk-Y7ERTA7D.js";
9
+ import {
10
+ emitNotice
11
+ } from "./chunk-R2VLGNFD.js";
12
+ import {
13
+ evaluateSpendPolicy,
14
+ withFileLock
15
+ } from "./chunk-FKSAUOJU.js";
16
+ import {
17
+ archivedWalletPath,
18
+ passphraseBlobPath,
19
+ passphraseBlobPathFor,
20
+ spendLedgerPath,
21
+ walletPath
22
+ } from "./chunk-ZQIQ55KK.js";
23
+ import {
24
+ hasCode
25
+ } from "./chunk-2I4QTOLB.js";
26
+ import {
27
+ CliError,
28
+ external_exports,
29
+ fsyncDir,
30
+ writeFileAtomic
31
+ } from "./chunk-PZRAAAY2.js";
32
+ import {
33
+ hashAuthorization,
34
+ hashMessage,
35
+ hashTypedData,
36
+ keccak256 as keccak2562,
37
+ publicKeyToAddress,
38
+ serializeSignature,
39
+ serializeTransaction
40
+ } from "./chunk-M2O56UK7.js";
41
+ import {
42
+ hmac,
43
+ secp256k1,
44
+ sha256
45
+ } from "./chunk-W6R3HAAG.js";
46
+ import {
47
+ InvalidAddressError,
48
+ concat2 as concat,
49
+ from,
50
+ hexToBytes,
51
+ isAddress,
52
+ isEqual,
53
+ isHex,
54
+ keccak256,
55
+ numberToHex,
56
+ random,
57
+ slice2 as slice,
58
+ toHex,
59
+ toHex2
60
+ } from "./chunk-47PP7TAG.js";
61
+ import {
62
+ ahash,
63
+ anumber,
64
+ asyncLoop,
65
+ checkOpts,
66
+ clean,
67
+ createView,
68
+ kdfInputToBytes,
69
+ rotl,
70
+ swap32IfBE,
71
+ u32
72
+ } from "./chunk-KYQVEKP5.js";
73
+
74
+ // src/lib/wallet/local.ts
75
+ import { link, readdir, unlink as unlink2 } from "fs/promises";
76
+
77
+ // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
78
+ function pbkdf2Init(hash, _password, _salt, _opts) {
79
+ ahash(hash);
80
+ const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
81
+ const { c, dkLen, asyncTick } = opts;
82
+ anumber(c);
83
+ anumber(dkLen);
84
+ anumber(asyncTick);
85
+ if (c < 1)
86
+ throw new Error("iterations (c) should be >= 1");
87
+ const password = kdfInputToBytes(_password);
88
+ const salt = kdfInputToBytes(_salt);
89
+ const DK = new Uint8Array(dkLen);
90
+ const PRF = hmac.create(hash, password);
91
+ const PRFSalt = PRF._cloneInto().update(salt);
92
+ return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
93
+ }
94
+ function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
95
+ PRF.destroy();
96
+ PRFSalt.destroy();
97
+ if (prfW)
98
+ prfW.destroy();
99
+ clean(u);
100
+ return DK;
101
+ }
102
+ function pbkdf2(hash, password, salt, opts) {
103
+ const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
104
+ let prfW;
105
+ const arr = new Uint8Array(4);
106
+ const view = createView(arr);
107
+ const u = new Uint8Array(PRF.outputLen);
108
+ for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
109
+ const Ti = DK.subarray(pos, pos + PRF.outputLen);
110
+ view.setInt32(0, ti, false);
111
+ (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
112
+ Ti.set(u.subarray(0, Ti.length));
113
+ for (let ui = 1; ui < c; ui++) {
114
+ PRF._cloneInto(prfW).update(u).digestInto(u);
115
+ for (let i = 0; i < Ti.length; i++)
116
+ Ti[i] ^= u[i];
117
+ }
118
+ }
119
+ return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
120
+ }
121
+
122
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/generatePrivateKey.js
123
+ function generatePrivateKey() {
124
+ return toHex(secp256k1.utils.randomPrivateKey());
125
+ }
126
+
127
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/toAccount.js
128
+ function toAccount(source) {
129
+ if (typeof source === "string") {
130
+ if (!isAddress(source, { strict: false }))
131
+ throw new InvalidAddressError({ address: source });
132
+ return {
133
+ address: source,
134
+ type: "json-rpc"
135
+ };
136
+ }
137
+ if (!isAddress(source.address, { strict: false }))
138
+ throw new InvalidAddressError({ address: source.address });
139
+ return {
140
+ address: source.address,
141
+ nonceManager: source.nonceManager,
142
+ sign: source.sign,
143
+ signAuthorization: source.signAuthorization,
144
+ signMessage: source.signMessage,
145
+ signTransaction: source.signTransaction,
146
+ signTypedData: source.signTypedData,
147
+ source: "custom",
148
+ type: "local"
149
+ };
150
+ }
151
+
152
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/sign.js
153
+ var extraEntropy = false;
154
+ async function sign({ hash, privateKey, to = "object" }) {
155
+ const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), {
156
+ lowS: true,
157
+ extraEntropy: isHex(extraEntropy, { strict: false }) ? hexToBytes(extraEntropy) : extraEntropy
158
+ });
159
+ const signature = {
160
+ r: numberToHex(r, { size: 32 }),
161
+ s: numberToHex(s, { size: 32 }),
162
+ v: recovery ? 28n : 27n,
163
+ yParity: recovery
164
+ };
165
+ return (() => {
166
+ if (to === "bytes" || to === "hex")
167
+ return serializeSignature({ ...signature, to });
168
+ return signature;
169
+ })();
170
+ }
171
+
172
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signAuthorization.js
173
+ async function signAuthorization(parameters) {
174
+ const { chainId, nonce, privateKey, to = "object" } = parameters;
175
+ const address = parameters.contractAddress ?? parameters.address;
176
+ const signature = await sign({
177
+ hash: hashAuthorization({ address, chainId, nonce }),
178
+ privateKey,
179
+ to
180
+ });
181
+ if (to === "object")
182
+ return {
183
+ address,
184
+ chainId,
185
+ nonce,
186
+ ...signature
187
+ };
188
+ return signature;
189
+ }
190
+
191
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signMessage.js
192
+ async function signMessage({ message, privateKey }) {
193
+ return await sign({ hash: hashMessage(message), privateKey, to: "hex" });
194
+ }
195
+
196
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signTransaction.js
197
+ async function signTransaction(parameters) {
198
+ const { privateKey, transaction, serializer = serializeTransaction } = parameters;
199
+ const signableTransaction = (() => {
200
+ if (transaction.type === "eip4844")
201
+ return {
202
+ ...transaction,
203
+ sidecars: false
204
+ };
205
+ return transaction;
206
+ })();
207
+ const signature = await sign({
208
+ hash: keccak256(await serializer(signableTransaction)),
209
+ privateKey
210
+ });
211
+ return await serializer(transaction, signature);
212
+ }
213
+
214
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/utils/signTypedData.js
215
+ async function signTypedData(parameters) {
216
+ const { privateKey, ...typedData } = parameters;
217
+ return await sign({
218
+ hash: hashTypedData(typedData),
219
+ privateKey,
220
+ to: "hex"
221
+ });
222
+ }
223
+
224
+ // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/accounts/privateKeyToAccount.js
225
+ function privateKeyToAccount(privateKey, options = {}) {
226
+ const { nonceManager } = options;
227
+ const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
228
+ const address = publicKeyToAddress(publicKey);
229
+ const account = toAccount({
230
+ address,
231
+ nonceManager,
232
+ async sign({ hash }) {
233
+ return sign({ hash, privateKey, to: "hex" });
234
+ },
235
+ async signAuthorization(authorization) {
236
+ return signAuthorization({ ...authorization, privateKey });
237
+ },
238
+ async signMessage({ message }) {
239
+ return signMessage({ message, privateKey });
240
+ },
241
+ async signTransaction(transaction, { serializer } = {}) {
242
+ return signTransaction({ privateKey, transaction, serializer });
243
+ },
244
+ async signTypedData(typedData) {
245
+ return signTypedData({ ...typedData, privateKey });
246
+ }
247
+ });
248
+ return {
249
+ ...account,
250
+ publicKey,
251
+ source: "privateKey"
252
+ };
253
+ }
254
+
255
+ // node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js
256
+ function isBytes(a) {
257
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
258
+ }
259
+ function abytes(b, ...lengths) {
260
+ if (!isBytes(b))
261
+ throw new Error("Uint8Array expected");
262
+ if (lengths.length > 0 && !lengths.includes(b.length))
263
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
264
+ }
265
+ function u8(arr) {
266
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
267
+ }
268
+ function u322(arr) {
269
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
270
+ }
271
+ function clean2(...arrays) {
272
+ for (let i = 0; i < arrays.length; i++) {
273
+ arrays[i].fill(0);
274
+ }
275
+ }
276
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
277
+ function overlapBytes(a, b) {
278
+ return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
279
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
280
+ b.byteOffset < a.byteOffset + a.byteLength;
281
+ }
282
+ function complexOverlapBytes(input, output) {
283
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
284
+ throw new Error("complex overlap of input and output is not supported");
285
+ }
286
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
287
+ function wrappedCipher(key, ...args) {
288
+ abytes(key);
289
+ if (!isLE)
290
+ throw new Error("Non little-endian hardware is not yet supported");
291
+ if (params.nonceLength !== void 0) {
292
+ const nonce = args[0];
293
+ if (!nonce)
294
+ throw new Error("nonce / iv required");
295
+ if (params.varSizeNonce)
296
+ abytes(nonce);
297
+ else
298
+ abytes(nonce, params.nonceLength);
299
+ }
300
+ const tagl = params.tagLength;
301
+ if (tagl && args[1] !== void 0) {
302
+ abytes(args[1]);
303
+ }
304
+ const cipher = constructor(key, ...args);
305
+ const checkOutput = (fnLength, output) => {
306
+ if (output !== void 0) {
307
+ if (fnLength !== 2)
308
+ throw new Error("cipher output not supported");
309
+ abytes(output);
310
+ }
311
+ };
312
+ let called = false;
313
+ const wrCipher = {
314
+ encrypt(data, output) {
315
+ if (called)
316
+ throw new Error("cannot encrypt() twice with same key + nonce");
317
+ called = true;
318
+ abytes(data);
319
+ checkOutput(cipher.encrypt.length, output);
320
+ return cipher.encrypt(data, output);
321
+ },
322
+ decrypt(data, output) {
323
+ abytes(data);
324
+ if (tagl && data.length < tagl)
325
+ throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
326
+ checkOutput(cipher.decrypt.length, output);
327
+ return cipher.decrypt(data, output);
328
+ }
329
+ };
330
+ return wrCipher;
331
+ }
332
+ Object.assign(wrappedCipher, params);
333
+ return wrappedCipher;
334
+ };
335
+ function getOutput(expectedLength, out, onlyAligned = true) {
336
+ if (out === void 0)
337
+ return new Uint8Array(expectedLength);
338
+ if (out.length !== expectedLength)
339
+ throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
340
+ if (onlyAligned && !isAligned32(out))
341
+ throw new Error("invalid output, must be aligned");
342
+ return out;
343
+ }
344
+ function isAligned32(bytes) {
345
+ return bytes.byteOffset % 4 === 0;
346
+ }
347
+ function copyBytes(bytes) {
348
+ return Uint8Array.from(bytes);
349
+ }
350
+
351
+ // node_modules/.pnpm/@noble+ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js
352
+ var BLOCK_SIZE = 16;
353
+ var BLOCK_SIZE32 = 4;
354
+ var POLY = 283;
355
+ function mul2(n) {
356
+ return n << 1 ^ POLY & -(n >> 7);
357
+ }
358
+ function mul(a, b) {
359
+ let res = 0;
360
+ for (; b > 0; b >>= 1) {
361
+ res ^= a & -(b & 1);
362
+ a = mul2(a);
363
+ }
364
+ return res;
365
+ }
366
+ var sbox = /* @__PURE__ */ (() => {
367
+ const t = new Uint8Array(256);
368
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
369
+ t[i] = x;
370
+ const box = new Uint8Array(256);
371
+ box[0] = 99;
372
+ for (let i = 0; i < 255; i++) {
373
+ let x = t[255 - i];
374
+ x |= x << 8;
375
+ box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
376
+ }
377
+ clean2(t);
378
+ return box;
379
+ })();
380
+ var rotr32_8 = (n) => n << 24 | n >>> 8;
381
+ var rotl32_8 = (n) => n << 8 | n >>> 24;
382
+ function genTtable(sbox2, fn) {
383
+ if (sbox2.length !== 256)
384
+ throw new Error("Wrong sbox length");
385
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
386
+ const T1 = T0.map(rotl32_8);
387
+ const T2 = T1.map(rotl32_8);
388
+ const T3 = T2.map(rotl32_8);
389
+ const T01 = new Uint32Array(256 * 256);
390
+ const T23 = new Uint32Array(256 * 256);
391
+ const sbox22 = new Uint16Array(256 * 256);
392
+ for (let i = 0; i < 256; i++) {
393
+ for (let j = 0; j < 256; j++) {
394
+ const idx = i * 256 + j;
395
+ T01[idx] = T0[i] ^ T1[j];
396
+ T23[idx] = T2[i] ^ T3[j];
397
+ sbox22[idx] = sbox2[i] << 8 | sbox2[j];
398
+ }
399
+ }
400
+ return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
401
+ }
402
+ var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
403
+ var xPowers = /* @__PURE__ */ (() => {
404
+ const p = new Uint8Array(16);
405
+ for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
406
+ p[i] = x;
407
+ return p;
408
+ })();
409
+ function expandKeyLE(key) {
410
+ abytes(key);
411
+ const len = key.length;
412
+ if (![16, 24, 32].includes(len))
413
+ throw new Error("aes: invalid key size, should be 16, 24 or 32, got " + len);
414
+ const { sbox2 } = tableEncoding;
415
+ const toClean = [];
416
+ if (!isAligned32(key))
417
+ toClean.push(key = copyBytes(key));
418
+ const k32 = u322(key);
419
+ const Nk = k32.length;
420
+ const subByte = (n) => applySbox(sbox2, n, n, n, n);
421
+ const xk = new Uint32Array(len + 28);
422
+ xk.set(k32);
423
+ for (let i = Nk; i < xk.length; i++) {
424
+ let t = xk[i - 1];
425
+ if (i % Nk === 0)
426
+ t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
427
+ else if (Nk > 6 && i % Nk === 4)
428
+ t = subByte(t);
429
+ xk[i] = xk[i - Nk] ^ t;
430
+ }
431
+ clean2(...toClean);
432
+ return xk;
433
+ }
434
+ function apply0123(T01, T23, s0, s1, s2, s3) {
435
+ return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
436
+ }
437
+ function applySbox(sbox2, s0, s1, s2, s3) {
438
+ return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
439
+ }
440
+ function encrypt(xk, s0, s1, s2, s3) {
441
+ const { sbox2, T01, T23 } = tableEncoding;
442
+ let k = 0;
443
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
444
+ const rounds = xk.length / 4 - 2;
445
+ for (let i = 0; i < rounds; i++) {
446
+ const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
447
+ const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
448
+ const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
449
+ const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
450
+ s0 = t02, s1 = t12, s2 = t22, s3 = t32;
451
+ }
452
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
453
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
454
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
455
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
456
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
457
+ }
458
+ function ctrCounter(xk, nonce, src, dst) {
459
+ abytes(nonce, BLOCK_SIZE);
460
+ abytes(src);
461
+ const srcLen = src.length;
462
+ dst = getOutput(srcLen, dst);
463
+ complexOverlapBytes(src, dst);
464
+ const ctr2 = nonce;
465
+ const c32 = u322(ctr2);
466
+ let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
467
+ const src32 = u322(src);
468
+ const dst32 = u322(dst);
469
+ for (let i = 0; i + 4 <= src32.length; i += 4) {
470
+ dst32[i + 0] = src32[i + 0] ^ s0;
471
+ dst32[i + 1] = src32[i + 1] ^ s1;
472
+ dst32[i + 2] = src32[i + 2] ^ s2;
473
+ dst32[i + 3] = src32[i + 3] ^ s3;
474
+ let carry = 1;
475
+ for (let i2 = ctr2.length - 1; i2 >= 0; i2--) {
476
+ carry = carry + (ctr2[i2] & 255) | 0;
477
+ ctr2[i2] = carry & 255;
478
+ carry >>>= 8;
479
+ }
480
+ ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
481
+ }
482
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
483
+ if (start < srcLen) {
484
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
485
+ const buf = u8(b32);
486
+ for (let i = start, pos = 0; i < srcLen; i++, pos++)
487
+ dst[i] = src[i] ^ buf[pos];
488
+ clean2(b32);
489
+ }
490
+ return dst;
491
+ }
492
+ var ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
493
+ function processCtr(buf, dst) {
494
+ abytes(buf);
495
+ if (dst !== void 0) {
496
+ abytes(dst);
497
+ if (!isAligned32(dst))
498
+ throw new Error("unaligned destination");
499
+ }
500
+ const xk = expandKeyLE(key);
501
+ const n = copyBytes(nonce);
502
+ const toClean = [xk, n];
503
+ if (!isAligned32(buf))
504
+ toClean.push(buf = copyBytes(buf));
505
+ const out = ctrCounter(xk, n, buf, dst);
506
+ clean2(...toClean);
507
+ return out;
508
+ }
509
+ return {
510
+ encrypt: (plaintext, dst) => processCtr(plaintext, dst),
511
+ decrypt: (ciphertext, dst) => processCtr(ciphertext, dst)
512
+ };
513
+ });
514
+
515
+ // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/scrypt.js
516
+ function XorAndSalsa(prev, pi, input, ii, out, oi) {
517
+ let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
518
+ let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
519
+ let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
520
+ let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
521
+ let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
522
+ let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
523
+ let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
524
+ let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
525
+ let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
526
+ for (let i = 0; i < 8; i += 2) {
527
+ x04 ^= rotl(x00 + x12 | 0, 7);
528
+ x08 ^= rotl(x04 + x00 | 0, 9);
529
+ x12 ^= rotl(x08 + x04 | 0, 13);
530
+ x00 ^= rotl(x12 + x08 | 0, 18);
531
+ x09 ^= rotl(x05 + x01 | 0, 7);
532
+ x13 ^= rotl(x09 + x05 | 0, 9);
533
+ x01 ^= rotl(x13 + x09 | 0, 13);
534
+ x05 ^= rotl(x01 + x13 | 0, 18);
535
+ x14 ^= rotl(x10 + x06 | 0, 7);
536
+ x02 ^= rotl(x14 + x10 | 0, 9);
537
+ x06 ^= rotl(x02 + x14 | 0, 13);
538
+ x10 ^= rotl(x06 + x02 | 0, 18);
539
+ x03 ^= rotl(x15 + x11 | 0, 7);
540
+ x07 ^= rotl(x03 + x15 | 0, 9);
541
+ x11 ^= rotl(x07 + x03 | 0, 13);
542
+ x15 ^= rotl(x11 + x07 | 0, 18);
543
+ x01 ^= rotl(x00 + x03 | 0, 7);
544
+ x02 ^= rotl(x01 + x00 | 0, 9);
545
+ x03 ^= rotl(x02 + x01 | 0, 13);
546
+ x00 ^= rotl(x03 + x02 | 0, 18);
547
+ x06 ^= rotl(x05 + x04 | 0, 7);
548
+ x07 ^= rotl(x06 + x05 | 0, 9);
549
+ x04 ^= rotl(x07 + x06 | 0, 13);
550
+ x05 ^= rotl(x04 + x07 | 0, 18);
551
+ x11 ^= rotl(x10 + x09 | 0, 7);
552
+ x08 ^= rotl(x11 + x10 | 0, 9);
553
+ x09 ^= rotl(x08 + x11 | 0, 13);
554
+ x10 ^= rotl(x09 + x08 | 0, 18);
555
+ x12 ^= rotl(x15 + x14 | 0, 7);
556
+ x13 ^= rotl(x12 + x15 | 0, 9);
557
+ x14 ^= rotl(x13 + x12 | 0, 13);
558
+ x15 ^= rotl(x14 + x13 | 0, 18);
559
+ }
560
+ out[oi++] = y00 + x00 | 0;
561
+ out[oi++] = y01 + x01 | 0;
562
+ out[oi++] = y02 + x02 | 0;
563
+ out[oi++] = y03 + x03 | 0;
564
+ out[oi++] = y04 + x04 | 0;
565
+ out[oi++] = y05 + x05 | 0;
566
+ out[oi++] = y06 + x06 | 0;
567
+ out[oi++] = y07 + x07 | 0;
568
+ out[oi++] = y08 + x08 | 0;
569
+ out[oi++] = y09 + x09 | 0;
570
+ out[oi++] = y10 + x10 | 0;
571
+ out[oi++] = y11 + x11 | 0;
572
+ out[oi++] = y12 + x12 | 0;
573
+ out[oi++] = y13 + x13 | 0;
574
+ out[oi++] = y14 + x14 | 0;
575
+ out[oi++] = y15 + x15 | 0;
576
+ }
577
+ function BlockMix(input, ii, out, oi, r) {
578
+ let head = oi + 0;
579
+ let tail = oi + 16 * r;
580
+ for (let i = 0; i < 16; i++)
581
+ out[tail + i] = input[ii + (2 * r - 1) * 16 + i];
582
+ for (let i = 0; i < r; i++, head += 16, ii += 16) {
583
+ XorAndSalsa(out, tail, input, ii, out, head);
584
+ if (i > 0)
585
+ tail += 16;
586
+ XorAndSalsa(out, head, input, ii += 16, out, tail);
587
+ }
588
+ }
589
+ function scryptInit(password, salt, _opts) {
590
+ const opts = checkOpts({
591
+ dkLen: 32,
592
+ asyncTick: 10,
593
+ maxmem: 1024 ** 3 + 1024
594
+ }, _opts);
595
+ const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
596
+ anumber(N);
597
+ anumber(r);
598
+ anumber(p);
599
+ anumber(dkLen);
600
+ anumber(asyncTick);
601
+ anumber(maxmem);
602
+ if (onProgress !== void 0 && typeof onProgress !== "function")
603
+ throw new Error("progressCb should be function");
604
+ const blockSize = 128 * r;
605
+ const blockSize32 = blockSize / 4;
606
+ const pow32 = Math.pow(2, 32);
607
+ if (N <= 1 || (N & N - 1) !== 0 || N > pow32) {
608
+ throw new Error("Scrypt: N must be larger than 1, a power of 2, and less than 2^32");
609
+ }
610
+ if (p < 0 || p > (pow32 - 1) * 32 / blockSize) {
611
+ throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");
612
+ }
613
+ if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
614
+ throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");
615
+ }
616
+ const memUsed = blockSize * (N + p);
617
+ if (memUsed > maxmem) {
618
+ throw new Error("Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of " + maxmem);
619
+ }
620
+ const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
621
+ const B32 = u32(B);
622
+ const V = u32(new Uint8Array(blockSize * N));
623
+ const tmp = u32(new Uint8Array(blockSize));
624
+ let blockMixCb = () => {
625
+ };
626
+ if (onProgress) {
627
+ const totalBlockMix = 2 * N * p;
628
+ const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1);
629
+ let blockMixCnt = 0;
630
+ blockMixCb = () => {
631
+ blockMixCnt++;
632
+ if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
633
+ onProgress(blockMixCnt / totalBlockMix);
634
+ };
635
+ }
636
+ return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
637
+ }
638
+ function scryptOutput(password, dkLen, B, V, tmp) {
639
+ const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
640
+ clean(B, V, tmp);
641
+ return res;
642
+ }
643
+ async function scryptAsync(password, salt, opts) {
644
+ const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
645
+ swap32IfBE(B32);
646
+ for (let pi = 0; pi < p; pi++) {
647
+ const Pi = blockSize32 * pi;
648
+ for (let i = 0; i < blockSize32; i++)
649
+ V[i] = B32[Pi + i];
650
+ let pos = 0;
651
+ await asyncLoop(N - 1, asyncTick, () => {
652
+ BlockMix(V, pos, V, pos += blockSize32, r);
653
+ blockMixCb();
654
+ });
655
+ BlockMix(V, (N - 1) * blockSize32, B32, Pi, r);
656
+ blockMixCb();
657
+ await asyncLoop(N, asyncTick, () => {
658
+ const j = B32[Pi + blockSize32 - 16] % N;
659
+ for (let k = 0; k < blockSize32; k++)
660
+ tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];
661
+ BlockMix(tmp, 0, B32, Pi, r);
662
+ blockMixCb();
663
+ });
664
+ }
665
+ swap32IfBE(B32);
666
+ return scryptOutput(password, dkLen, B, V, tmp);
667
+ }
668
+
669
+ // node_modules/.pnpm/ox@0.14.30_typescript@6.0.3_zod@4.4.3/node_modules/ox/_esm/core/Keystore.js
670
+ function decrypt(keystore, key, options = {}) {
671
+ const { as = "Hex" } = options;
672
+ const key_ = from(typeof key === "function" ? key() : key);
673
+ const encKey = slice(key_, 0, 16);
674
+ const macKey = slice(key_, 16, 32);
675
+ const ciphertext = from(`0x${keystore.crypto.ciphertext}`);
676
+ const mac = keccak2562(concat(macKey, ciphertext));
677
+ if (!isEqual(mac, from(`0x${keystore.crypto.mac}`)))
678
+ throw new Error("corrupt keystore");
679
+ const data = ctr(encKey, from(`0x${keystore.crypto.cipherparams.iv}`)).decrypt(ciphertext);
680
+ if (as === "Hex")
681
+ return toHex2(data);
682
+ return data;
683
+ }
684
+ function encrypt2(privateKey, key, options) {
685
+ const { id = crypto.randomUUID(), kdf, kdfparams, iv } = options;
686
+ const key_ = from(typeof key === "function" ? key() : key);
687
+ const value_ = from(privateKey);
688
+ const encKey = slice(key_, 0, 16);
689
+ const macKey = slice(key_, 16, 32);
690
+ const ciphertext = ctr(encKey, iv).encrypt(value_);
691
+ const mac = keccak2562(concat(macKey, ciphertext));
692
+ return {
693
+ crypto: {
694
+ cipher: "aes-128-ctr",
695
+ ciphertext: toHex2(ciphertext).slice(2),
696
+ cipherparams: { iv: toHex2(iv).slice(2) },
697
+ kdf,
698
+ kdfparams,
699
+ mac: toHex2(mac).slice(2)
700
+ },
701
+ id,
702
+ version: 3
703
+ };
704
+ }
705
+ function pbkdf22(options) {
706
+ const { iv, iterations = 262144, password } = options;
707
+ const salt = options.salt ? from(options.salt) : random(32);
708
+ const key = toHex2(pbkdf2(sha256, password, salt, { c: iterations, dkLen: 32 }));
709
+ return defineKey(() => key, {
710
+ iv,
711
+ kdfparams: {
712
+ c: iterations,
713
+ dklen: 32,
714
+ prf: "hmac-sha256",
715
+ salt: toHex2(salt).slice(2)
716
+ },
717
+ kdf: "pbkdf2"
718
+ });
719
+ }
720
+ async function scryptAsync2(options) {
721
+ const { iv, n = 262144, password } = options;
722
+ const p = 8;
723
+ const r = 1;
724
+ const salt = options.salt ? from(options.salt) : random(32);
725
+ const key = toHex2(await scryptAsync(password, salt, { N: n, dkLen: 32, r, p }));
726
+ return defineKey(() => key, {
727
+ iv,
728
+ kdfparams: {
729
+ dklen: 32,
730
+ n,
731
+ p,
732
+ r,
733
+ salt: toHex2(salt).slice(2)
734
+ },
735
+ kdf: "scrypt"
736
+ });
737
+ }
738
+ async function toKeyAsync(keystore, options) {
739
+ const { crypto: crypto2 } = keystore;
740
+ const { password } = options;
741
+ const { cipherparams, kdf, kdfparams } = crypto2;
742
+ const { iv } = cipherparams;
743
+ const { c, n, p, r, salt } = kdfparams;
744
+ const [key] = await (async () => {
745
+ switch (kdf) {
746
+ case "scrypt":
747
+ return await scryptAsync2({
748
+ iv: from(`0x${iv}`),
749
+ n,
750
+ p,
751
+ r,
752
+ salt: from(`0x${salt}`),
753
+ password
754
+ });
755
+ case "pbkdf2":
756
+ return await pbkdf22({
757
+ iv: from(`0x${iv}`),
758
+ iterations: c,
759
+ password,
760
+ salt: from(`0x${salt}`)
761
+ });
762
+ default:
763
+ throw new Error("unsupported kdf");
764
+ }
765
+ })();
766
+ return key;
767
+ }
768
+ function defineKey(key, options) {
769
+ const iv = options.iv ? from(options.iv) : random(16);
770
+ return [key, { ...options, iv }];
771
+ }
772
+
773
+ // src/lib/wallet/passphrase.ts
774
+ import { execFile } from "child_process";
775
+ import { randomBytes } from "crypto";
776
+ import { readFile, unlink } from "fs/promises";
777
+ var KEYCHAIN_SERVICE = "tenjin-cli";
778
+ var LEGACY_ACCOUNT = "wallet";
779
+ var ACCOUNT_ADDRESS_RE = /^0x[0-9a-f]{40}$/;
780
+ var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
781
+ function walletStoreAccount(address) {
782
+ const account = address.toLowerCase();
783
+ if (!ACCOUNT_ADDRESS_RE.test(account)) {
784
+ throw new CliError("INTERNAL", `Not a valid wallet address for passphrase storage: ${address}`);
785
+ }
786
+ return account;
787
+ }
788
+ function defaultExecFor(timeoutMs) {
789
+ return (file, args, stdin) => new Promise((resolve, reject) => {
790
+ const child = execFile(
791
+ file,
792
+ args,
793
+ { encoding: "utf8", ...timeoutMs !== void 0 ? { timeout: timeoutMs } : {} },
794
+ (err, stdout, stderr) => {
795
+ if (err) reject(err);
796
+ else resolve({ stdout, stderr });
797
+ }
798
+ );
799
+ if (stdin !== void 0) {
800
+ child.stdin?.on("error", () => void 0);
801
+ child.stdin?.end(stdin);
802
+ }
803
+ });
804
+ }
805
+ function storeFor(deps) {
806
+ switch (deps.platform ?? process.platform) {
807
+ case "darwin":
808
+ return keychainStore(deps);
809
+ case "win32":
810
+ return dpapiStore(deps);
811
+ case "linux":
812
+ return secretServiceStore(deps);
813
+ default:
814
+ return null;
815
+ }
816
+ }
817
+ async function resolvePassphrase(deps, address) {
818
+ const fromEnv = envPassphrase(deps.env);
819
+ if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
820
+ const store = storeFor(deps);
821
+ if (store !== null) {
822
+ const account = walletStoreAccount(address);
823
+ const own = await store.read(account);
824
+ if (own !== null) return { passphrase: own, source: store.source };
825
+ const legacy = await store.read(LEGACY_ACCOUNT);
826
+ if (legacy !== null) {
827
+ return {
828
+ passphrase: legacy,
829
+ source: store.source,
830
+ migrateLegacy: () => migrateLegacyEntry(store, account, legacy)
831
+ };
832
+ }
833
+ }
834
+ if (canPrompt(deps)) {
835
+ const entered = await promptOf(deps)("Wallet passphrase: ");
836
+ if (entered.length === 0) throw noPassphraseError();
837
+ return { passphrase: entered, source: "prompt" };
838
+ }
839
+ throw noPassphraseError();
840
+ }
841
+ async function migrateLegacyEntry(store, account, passphrase) {
842
+ if (!await store.store(account, passphrase)) return false;
843
+ if (await store.read(account) !== passphrase) return false;
844
+ await store.remove(LEGACY_ACCOUNT);
845
+ return true;
846
+ }
847
+ async function storePassphraseForWallet(deps, address, passphrase) {
848
+ const store = storeFor(deps);
849
+ if (store === null) return "no-store";
850
+ const account = walletStoreAccount(address);
851
+ if (await store.read(account) === passphrase) return "stored";
852
+ if (store.storable !== void 0 && !store.storable(passphrase)) return "rejected-characters";
853
+ if (!await store.store(account, passphrase)) return "store-failed";
854
+ return await store.read(account) === passphrase ? "stored" : "store-failed";
855
+ }
856
+ async function resolvePassphraseForCreate(deps, address) {
857
+ const fromEnv = envPassphrase(deps.env);
858
+ if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
859
+ const store = storeFor(deps);
860
+ if (store !== null) {
861
+ const account = walletStoreAccount(address);
862
+ const generated = randomBytes(32).toString("base64url");
863
+ if (await store.store(account, generated) && await store.read(account) === generated) {
864
+ return { passphrase: generated, source: store.source };
865
+ }
866
+ }
867
+ if (canPrompt(deps)) {
868
+ const prompt = promptOf(deps);
869
+ const first = await prompt("Set a wallet passphrase: ");
870
+ if (first.length === 0) {
871
+ throw new CliError("USAGE", "The wallet passphrase must not be empty.", {
872
+ fix: "Enter a non-empty passphrase, or set TENJIN_WALLET_PASSPHRASE."
873
+ });
874
+ }
875
+ const second = await prompt("Confirm passphrase: ");
876
+ if (first !== second) {
877
+ throw new CliError("USAGE", "The passphrases did not match.", {
878
+ fix: "Run `tenjin wallet create` again and enter the same passphrase both times."
879
+ });
880
+ }
881
+ return { passphrase: first, source: "prompt" };
882
+ }
883
+ throw noPassphraseError();
884
+ }
885
+ function keychainStore(deps) {
886
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
887
+ return {
888
+ source: "keychain",
889
+ async read(account) {
890
+ try {
891
+ const { stdout } = await exec("security", [
892
+ "find-generic-password",
893
+ "-s",
894
+ KEYCHAIN_SERVICE,
895
+ "-a",
896
+ account,
897
+ "-w"
898
+ ]);
899
+ return trimmedNonEmpty(stdout);
900
+ } catch {
901
+ return null;
902
+ }
903
+ },
904
+ // The one backend that interpolates into a command line, so only base64url
905
+ // values pass; escaping is NOT a safe alternative (backslash bites even
906
+ // inside single quotes there).
907
+ storable: (passphrase) => BASE64URL_RE.test(passphrase),
908
+ async store(account, passphrase) {
909
+ if (!BASE64URL_RE.test(passphrase) || !BASE64URL_RE.test(account)) return false;
910
+ try {
911
+ const command = `add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} -w '${passphrase}'
912
+ `;
913
+ await exec("security", ["-i"], command);
914
+ return true;
915
+ } catch {
916
+ return false;
917
+ }
918
+ },
919
+ async remove(account) {
920
+ try {
921
+ await exec("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account]);
922
+ return true;
923
+ } catch {
924
+ return false;
925
+ }
926
+ }
927
+ };
928
+ }
929
+ var DPAPI_PROTECT_SCRIPT = [
930
+ "Add-Type -AssemblyName System.Security;",
931
+ "$in = [Console]::In.ReadToEnd();",
932
+ "$bytes = [System.Text.Encoding]::UTF8.GetBytes($in);",
933
+ "$prot = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser');",
934
+ "[Console]::Out.Write([Convert]::ToBase64String($prot));"
935
+ ].join(" ");
936
+ var DPAPI_UNPROTECT_SCRIPT = [
937
+ "Add-Type -AssemblyName System.Security;",
938
+ "$in = [Console]::In.ReadToEnd();",
939
+ "$blob = [Convert]::FromBase64String($in.Trim());",
940
+ "$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser');",
941
+ "[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain));"
942
+ ].join(" ");
943
+ function powershellArgs(script) {
944
+ return ["-NoProfile", "-NonInteractive", "-Command", script];
945
+ }
946
+ function dpapiStore(deps) {
947
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
948
+ const blobPathFor = (account) => account === LEGACY_ACCOUNT ? passphraseBlobPath(deps.dir) : passphraseBlobPathFor(account, deps.dir);
949
+ return {
950
+ source: "dpapi",
951
+ async read(account) {
952
+ let blob;
953
+ try {
954
+ blob = await readFile(blobPathFor(account), "utf8");
955
+ } catch {
956
+ return null;
957
+ }
958
+ try {
959
+ const { stdout } = await exec(
960
+ "powershell.exe",
961
+ powershellArgs(DPAPI_UNPROTECT_SCRIPT),
962
+ blob
963
+ );
964
+ const passphrase = stdout.replace(/\r?\n$/, "");
965
+ return passphrase.length > 0 ? passphrase : null;
966
+ } catch {
967
+ return null;
968
+ }
969
+ },
970
+ async store(account, passphrase) {
971
+ try {
972
+ const { stdout } = await exec(
973
+ "powershell.exe",
974
+ powershellArgs(DPAPI_PROTECT_SCRIPT),
975
+ passphrase
976
+ );
977
+ const blob = stdout.replace(/\r?\n$/, "").trim();
978
+ if (blob.length === 0) return false;
979
+ await writeFileAtomic(blobPathFor(account), blob, { mode: 384 });
980
+ return true;
981
+ } catch {
982
+ return false;
983
+ }
984
+ },
985
+ async remove(account) {
986
+ try {
987
+ await unlink(blobPathFor(account));
988
+ return true;
989
+ } catch {
990
+ return false;
991
+ }
992
+ }
993
+ };
994
+ }
995
+ function secretServiceStore(deps) {
996
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
997
+ return {
998
+ source: "secret-service",
999
+ async read(account) {
1000
+ try {
1001
+ const { stdout } = await exec("secret-tool", [
1002
+ "lookup",
1003
+ "service",
1004
+ KEYCHAIN_SERVICE,
1005
+ "account",
1006
+ account
1007
+ ]);
1008
+ return trimmedNonEmpty(stdout);
1009
+ } catch {
1010
+ return null;
1011
+ }
1012
+ },
1013
+ async store(account, passphrase) {
1014
+ try {
1015
+ await exec(
1016
+ "secret-tool",
1017
+ [
1018
+ "store",
1019
+ `--label=tenjin-cli wallet ${account}`,
1020
+ "service",
1021
+ KEYCHAIN_SERVICE,
1022
+ "account",
1023
+ account
1024
+ ],
1025
+ passphrase
1026
+ );
1027
+ return true;
1028
+ } catch {
1029
+ return false;
1030
+ }
1031
+ },
1032
+ async remove(account) {
1033
+ try {
1034
+ await exec("secret-tool", ["clear", "service", KEYCHAIN_SERVICE, "account", account]);
1035
+ return true;
1036
+ } catch {
1037
+ return false;
1038
+ }
1039
+ }
1040
+ };
1041
+ }
1042
+ function trimmedNonEmpty(stdout) {
1043
+ const value = stdout.replace(/\r?\n$/, "");
1044
+ return value.length > 0 ? value : null;
1045
+ }
1046
+ function envPassphrase(env) {
1047
+ const value = env.TENJIN_WALLET_PASSPHRASE;
1048
+ return value !== void 0 && value.length > 0 ? value : null;
1049
+ }
1050
+ function canPrompt(deps) {
1051
+ return deps.isTTY ?? Boolean(process.stdin.isTTY);
1052
+ }
1053
+ function promptOf(deps) {
1054
+ return deps.prompt ?? promptHidden;
1055
+ }
1056
+ function noPassphraseError() {
1057
+ return new CliError("USAGE", "No wallet passphrase is available.", {
1058
+ fix: "Set TENJIN_WALLET_PASSPHRASE (headless) or run in a terminal."
1059
+ });
1060
+ }
1061
+ var CTRL_C = 3;
1062
+ var CTRL_D = 4;
1063
+ var BACKSPACE = 127;
1064
+ var BACKSPACE_ALT = 8;
1065
+ function promptHidden(label) {
1066
+ return new Promise((resolve, reject) => {
1067
+ const stdin = process.stdin;
1068
+ const stderr = process.stderr;
1069
+ const wasRaw = stdin.isRaw;
1070
+ let value = "";
1071
+ const cleanup = () => {
1072
+ stdin.setRawMode?.(wasRaw ?? false);
1073
+ stdin.pause();
1074
+ stdin.removeListener("data", onData);
1075
+ };
1076
+ const onData = (chunk) => {
1077
+ for (const ch of chunk.toString("utf8")) {
1078
+ const code = ch.charCodeAt(0);
1079
+ if (ch === "\n" || ch === "\r" || code === CTRL_D) {
1080
+ cleanup();
1081
+ stderr.write("\n");
1082
+ resolve(value);
1083
+ return;
1084
+ }
1085
+ if (code === CTRL_C) {
1086
+ cleanup();
1087
+ stderr.write("\n");
1088
+ reject(
1089
+ new CliError("USAGE", "Passphrase entry was cancelled.", {
1090
+ fix: "Run the command again, or set TENJIN_WALLET_PASSPHRASE."
1091
+ })
1092
+ );
1093
+ return;
1094
+ }
1095
+ if (code === BACKSPACE || code === BACKSPACE_ALT) {
1096
+ value = value.slice(0, -1);
1097
+ } else {
1098
+ value += ch;
1099
+ }
1100
+ }
1101
+ };
1102
+ stderr.write(label);
1103
+ stdin.setRawMode?.(true);
1104
+ stdin.resume();
1105
+ stdin.on("data", onData);
1106
+ });
1107
+ }
1108
+
1109
+ // src/lib/wallet/local.ts
1110
+ var isWindows = process.platform === "win32";
1111
+ var KEY_STORAGE = "encrypted (keystore v3, scrypt)";
1112
+ var STORE_READ_TIMEOUT_MS = 5e3;
1113
+ var signerCache = /* @__PURE__ */ new Map();
1114
+ function createLocalProvider(deps) {
1115
+ return {
1116
+ id: "local",
1117
+ async describe() {
1118
+ const cred = await credentialOrThrow(deps);
1119
+ return {
1120
+ // A file credential's address is stored cleartext and returned as-is —
1121
+ // no decryption. An env credential derives (and thereby validates) its
1122
+ // key. getSigner is where a file wallet's key/address match is checked.
1123
+ address: cred.source === "env" ? accountFromKey(cred.key, "env").address : cred.address,
1124
+ provider: "local",
1125
+ credentialSource: cred.source,
1126
+ policyEnforcement: "client-only"
1127
+ };
1128
+ },
1129
+ async getSigner() {
1130
+ const cred = await credentialOrThrow(deps);
1131
+ const account = await accountForSigning(cred, deps);
1132
+ return {
1133
+ address: account.address,
1134
+ signMessage: (args) => account.signMessage({ message: args.message }),
1135
+ signTypedData: (args) => account.signTypedData(args),
1136
+ signTransaction: (tx) => account.signTransaction(tx)
1137
+ };
1138
+ },
1139
+ diagnostics() {
1140
+ return localWalletDiagnostics(deps);
1141
+ },
1142
+ verify() {
1143
+ return verifyLocalWallet(deps);
1144
+ }
1145
+ };
1146
+ }
1147
+ async function verifyLocalWallet(deps) {
1148
+ const cred = await loadCredential(deps);
1149
+ if (cred === null) return { status: "unverified", detail: "there is no credential to verify" };
1150
+ if (cred.source === "env") {
1151
+ accountFromKey(cred.key, "env");
1152
+ return { status: "verified", detail: "TENJIN_WALLET_KEY derives a valid signing key" };
1153
+ }
1154
+ const account = walletStoreAccount(cred.address);
1155
+ let resolved;
1156
+ try {
1157
+ resolved = await resolvePassphrase(
1158
+ {
1159
+ env: deps.env,
1160
+ dir: deps.dir,
1161
+ ...deps.passphrase,
1162
+ isTTY: false,
1163
+ timeoutMs: STORE_READ_TIMEOUT_MS
1164
+ },
1165
+ cred.address
1166
+ );
1167
+ } catch {
1168
+ return {
1169
+ status: "unverified",
1170
+ detail: "no passphrase is reachable without prompting, so the keystore was not opened"
1171
+ };
1172
+ }
1173
+ let key;
1174
+ try {
1175
+ const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1176
+ key = decrypt(cred.keystore, derived);
1177
+ } catch {
1178
+ if (resolved.migrateLegacy !== void 0) {
1179
+ return {
1180
+ status: "broken",
1181
+ detail: `the keystore cannot be decrypted: the only stored passphrase is ${legacyOrigin(resolved.source)}, which does not open it`,
1182
+ fix: `That passphrase likely belongs to a wallet created later. Set TENJIN_WALLET_PASSPHRASE to this wallet's own passphrase, or restore ${passphraseOrigin(resolved.source, account)}.`
1183
+ };
1184
+ }
1185
+ const escape = resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not open it; set it to the correct passphrase" : `The passphrase from ${passphraseOrigin(resolved.source, account)} does not open it; set TENJIN_WALLET_PASSPHRASE to the correct passphrase`;
1186
+ return {
1187
+ status: "broken",
1188
+ detail: `the keystore cannot be decrypted with the passphrase from ${passphraseOrigin(resolved.source, account)}`,
1189
+ fix: `${escape}. Without it the key is unrecoverable and this address can no longer sign or publish.`
1190
+ };
1191
+ }
1192
+ if (privateKeyToAccount(key).address.toLowerCase() !== account) {
1193
+ return {
1194
+ status: "broken",
1195
+ detail: `the decrypted key does not derive the wallet file's stored address ${cred.address}`,
1196
+ 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."
1197
+ };
1198
+ }
1199
+ return {
1200
+ status: "verified",
1201
+ detail: `keystore decrypts with the passphrase from ${passphraseOrigin(resolved.source, account)}`
1202
+ };
1203
+ }
1204
+ function passphraseOrigin(source, account) {
1205
+ if (source === "env") return "TENJIN_WALLET_PASSPHRASE";
1206
+ if (source === "prompt") return "the prompt";
1207
+ if (source === "dpapi") return `the DPAPI-protected passphrase file for ${account}`;
1208
+ return `the OS credential store (service tenjin-cli, account ${account})`;
1209
+ }
1210
+ function legacyOrigin(source) {
1211
+ return source === "dpapi" ? "the legacy shared DPAPI passphrase file (passphrase.dpapi)" : 'the legacy shared entry (service tenjin-cli, account "wallet")';
1212
+ }
1213
+ async function localWalletDiagnostics(deps) {
1214
+ const mode = await walletFileMode(deps.dir);
1215
+ const fileExists = mode !== null;
1216
+ const envKey = deps.env.TENJIN_WALLET_KEY;
1217
+ const envSet = envKey !== void 0 && envKey.length > 0;
1218
+ const path = walletPath(deps.dir);
1219
+ const warnings = [];
1220
+ if (envSet && fileExists) {
1221
+ warnings.push("TENJIN_WALLET_KEY is set and shadows the wallet file at runtime.");
1222
+ }
1223
+ if (mode !== null) {
1224
+ if (isWindows) {
1225
+ warnings.push("File permission checks are not available on Windows.");
1226
+ } else if (mode !== 384) {
1227
+ warnings.push(
1228
+ `Wallet file permissions are ${mode.toString(8)}, expected 600. Run \`chmod 600 ${path}\`.`
1229
+ );
1230
+ }
1231
+ }
1232
+ const passphraseSource = deps.env.TENJIN_WALLET_PASSPHRASE !== void 0 && deps.env.TENJIN_WALLET_PASSPHRASE.length > 0 ? "TENJIN_WALLET_PASSPHRASE" : void 0;
1233
+ const archivedWallets = await listArchivedWallets(deps.dir);
1234
+ return {
1235
+ ...fileExists ? { walletPath: path, keyStorage: KEY_STORAGE } : {},
1236
+ ...fileExists && passphraseSource !== void 0 ? { passphraseSource } : {},
1237
+ ...archivedWallets.length > 0 ? { archivedWallets } : {},
1238
+ warnings
1239
+ };
1240
+ }
1241
+ var ARCHIVED_WALLET_RE = /^wallet\.(0x[0-9a-f]{40})\.json\.bak$/;
1242
+ async function listArchivedWallets(dir) {
1243
+ let names;
1244
+ try {
1245
+ names = await readdir(dir);
1246
+ } catch {
1247
+ return [];
1248
+ }
1249
+ return names.map((name) => ARCHIVED_WALLET_RE.exec(name)?.[1]).filter((address) => address !== void 0).sort();
1250
+ }
1251
+ async function prepareLocalWallet(passphrase) {
1252
+ const key = generatePrivateKey();
1253
+ const address = privateKeyToAccount(key).address;
1254
+ const resolved = typeof passphrase === "string" ? passphrase : await passphrase(address);
1255
+ const keystore = await encryptToKeystore(key, resolved);
1256
+ return { address, record: walletRecord(address, keystore) };
1257
+ }
1258
+ async function commitLocalWallet(dir, prepared) {
1259
+ await writeWalletRecord(dir, prepared.record);
1260
+ return { address: prepared.address, walletPath: walletPath(dir) };
1261
+ }
1262
+ async function createLocalWallet(dir, passphrase) {
1263
+ return commitLocalWallet(dir, await prepareLocalWallet(passphrase));
1264
+ }
1265
+ async function verifyAndPreserveOutgoingWallet(deps) {
1266
+ const record = await readWalletRecord(deps.dir);
1267
+ if (record === null) {
1268
+ throw new CliError("WALLET_MISSING", "No wallet found to archive.", {
1269
+ fix: "Run `tenjin wallet create` without --replace."
1270
+ });
1271
+ }
1272
+ const address = record.address;
1273
+ const account = walletStoreAccount(address);
1274
+ const passphraseDeps = { env: deps.env, dir: deps.dir, ...deps.passphrase };
1275
+ const resolved = await resolvePassphrase(passphraseDeps, address);
1276
+ let key;
1277
+ try {
1278
+ const derived = await toKeyAsync(record.keystore, { password: resolved.passphrase });
1279
+ key = decrypt(record.keystore, derived);
1280
+ } catch (err) {
1281
+ const escape = resolved.source === "prompt" ? "Retry and enter that wallet's correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it" : resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase" : `Set TENJIN_WALLET_PASSPHRASE to its passphrase, or fix its OS credential store entry (service tenjin-cli, account ${account})`;
1282
+ throw new CliError(
1283
+ "REFUSED",
1284
+ `Cannot verify the passphrase of the existing wallet ${address}; --replace refused.`,
1285
+ {
1286
+ fix: `Replacing now could strand that wallet's funds. ${escape}, then retry.`,
1287
+ cause: err
1288
+ }
1289
+ );
1290
+ }
1291
+ if (privateKeyToAccount(key).address.toLowerCase() !== account) {
1292
+ throw new CliError(
1293
+ "REFUSED",
1294
+ `The wallet file's stored address ${address} does not match its key; --replace refused.`,
1295
+ { fix: "The wallet file may be tampered. Resolve that before replacing it." }
1296
+ );
1297
+ }
1298
+ if (resolved.source === "env") {
1299
+ return { address, account, passphraseLocation: "env" };
1300
+ }
1301
+ if (resolved.migrateLegacy !== void 0) {
1302
+ if (!await resolved.migrateLegacy()) {
1303
+ throw new CliError(
1304
+ "REFUSED",
1305
+ `Could not archive the existing wallet's passphrase under its own address; --replace refused.`,
1306
+ {
1307
+ 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.`
1308
+ }
1309
+ );
1310
+ }
1311
+ return { address, account, passphraseLocation: "store" };
1312
+ }
1313
+ if (resolved.source === "prompt") {
1314
+ const outcome = await storePassphraseForWallet(passphraseDeps, address, resolved.passphrase);
1315
+ return outcome === "stored" ? { address, account, passphraseLocation: "store" } : { address, account, passphraseLocation: "unarchived", unarchivedReason: outcome };
1316
+ }
1317
+ return { address, account, passphraseLocation: "store" };
1318
+ }
1319
+ async function parkOutgoingWallet(dir, account) {
1320
+ const src = walletPath(dir);
1321
+ const dst = archivedWalletPath(account, dir);
1322
+ try {
1323
+ await link(src, dst);
1324
+ } catch (err) {
1325
+ if (hasCode(err, "EEXIST")) {
1326
+ throw new CliError("REFUSED", `An archived wallet already exists at ${dst}.`, {
1327
+ fix: `Move ${dst} aside, then retry \`tenjin wallet create --replace\`. Nothing has moved; the current wallet is still active.`,
1328
+ cause: err
1329
+ });
1330
+ }
1331
+ throw new CliError("INTERNAL", `Could not park the outgoing keystore at ${dst}.`, {
1332
+ fix: `Nothing has moved; the current wallet is still active at ${src}. Fix the underlying filesystem error and retry.`,
1333
+ cause: err
1334
+ });
1335
+ }
1336
+ try {
1337
+ await unlink2(src);
1338
+ } catch (err) {
1339
+ await unlink2(dst).catch(() => void 0);
1340
+ throw new CliError(
1341
+ "INTERNAL",
1342
+ `Could not clear the active wallet slot ${src} while parking the outgoing wallet.`,
1343
+ {
1344
+ 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.",
1345
+ cause: err
1346
+ }
1347
+ );
1348
+ }
1349
+ await syncWalletDir(dir);
1350
+ return dst;
1351
+ }
1352
+ async function restoreParkedWallet(dir, archivedPath) {
1353
+ await link(archivedPath, walletPath(dir));
1354
+ await unlink2(archivedPath).catch(() => void 0);
1355
+ await syncWalletDir(dir);
1356
+ }
1357
+ async function syncWalletDir(dir) {
1358
+ if (isWindows) return;
1359
+ await fsyncDir(dir);
1360
+ }
1361
+ async function loadCredential(deps) {
1362
+ const envKey = deps.env.TENJIN_WALLET_KEY;
1363
+ if (envKey !== void 0 && envKey.trim().length > 0) {
1364
+ const key = envKey.trim();
1365
+ if (!PRIVATE_KEY_RE.test(key)) {
1366
+ throw new CliError("WALLET_INVALID_KEY", "TENJIN_WALLET_KEY is not a valid private key.", {
1367
+ fix: "Set TENJIN_WALLET_KEY to a 0x-prefixed 32-byte hex key, or unset it to use the wallet file."
1368
+ });
1369
+ }
1370
+ return { source: "env", key };
1371
+ }
1372
+ const record = await readWalletRecord(deps.dir);
1373
+ if (record !== null) {
1374
+ return { source: "file", keystore: record.keystore, address: record.address };
1375
+ }
1376
+ return null;
1377
+ }
1378
+ async function accountForSigning(cred, deps) {
1379
+ if (cred.source === "env") return accountFromKey(cred.key, "env");
1380
+ const cached = signerCache.get(cred.keystore.id);
1381
+ if (cached !== void 0) return cached;
1382
+ const resolved = await resolvePassphrase(
1383
+ {
1384
+ env: deps.env,
1385
+ dir: deps.dir,
1386
+ ...deps.passphrase
1387
+ },
1388
+ cred.address
1389
+ );
1390
+ let key;
1391
+ try {
1392
+ const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1393
+ key = decrypt(cred.keystore, derived);
1394
+ } catch (err) {
1395
+ if (resolved.migrateLegacy !== void 0) {
1396
+ throw new CliError(
1397
+ "WALLET_INVALID_KEY",
1398
+ 'The legacy shared passphrase entry (service tenjin-cli, account "wallet") does not decrypt this wallet.',
1399
+ {
1400
+ fix: "That entry likely belongs to a different wallet created later and was left untouched. If you know this wallet's passphrase, set TENJIN_WALLET_PASSPHRASE to it (a store-served passphrase is never re-asked at a prompt).",
1401
+ cause: err
1402
+ }
1403
+ );
1404
+ }
1405
+ const escape = resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase" : resolved.source === "prompt" ? "Retry and enter the correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it" : `The OS credential store entry (service tenjin-cli, account ${cred.address.toLowerCase()}) does not decrypt it; set TENJIN_WALLET_PASSPHRASE to the correct passphrase`;
1406
+ throw new CliError("WALLET_INVALID_KEY", "Could not decrypt the wallet keystore.", {
1407
+ fix: `${escape}.`,
1408
+ cause: err
1409
+ });
1410
+ }
1411
+ const account = accountFromKey(key, "file");
1412
+ if (account.address.toLowerCase() !== cred.address.toLowerCase()) {
1413
+ throw new CliError(
1414
+ "WALLET_INVALID_KEY",
1415
+ `The decrypted key derives ${account.address}, not the wallet file's stored address ${cred.address}.`,
1416
+ {
1417
+ 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."
1418
+ }
1419
+ );
1420
+ }
1421
+ if (resolved.migrateLegacy !== void 0) await resolved.migrateLegacy();
1422
+ signerCache.set(cred.keystore.id, account);
1423
+ return account;
1424
+ }
1425
+ function accountFromKey(key, source) {
1426
+ try {
1427
+ return privateKeyToAccount(key);
1428
+ } catch (err) {
1429
+ throw new CliError("WALLET_INVALID_KEY", "The private key is not a valid secp256k1 key.", {
1430
+ fix: source === "file" ? "Move the wallet file aside, then run `tenjin wallet create` for a fresh key or set TENJIN_WALLET_KEY to use the intended one." : "Set TENJIN_WALLET_KEY to a valid 0x-prefixed 32-byte hex key.",
1431
+ cause: err
1432
+ });
1433
+ }
1434
+ }
1435
+ async function encryptToKeystore(key, passphrase) {
1436
+ const [derivedKey, opts] = await scryptAsync2({ password: passphrase });
1437
+ return encrypt2(key, derivedKey, opts);
1438
+ }
1439
+ async function credentialOrThrow(deps) {
1440
+ const cred = await loadCredential(deps);
1441
+ if (cred !== null) return cred;
1442
+ const archived = await listArchivedWallets(deps.dir);
1443
+ const hint = archived.length > 0 ? ` Archived wallets exist (${archived.join(", ")}); restore one with \`mv ${archivedWalletPath("<address>", deps.dir)} ${walletPath(deps.dir)}\`.` : "";
1444
+ throw new CliError("WALLET_MISSING", "No wallet found.", {
1445
+ fix: `Run \`tenjin wallet create\` to create one.${hint}`
1446
+ });
1447
+ }
1448
+ function walletRecord(address, keystore) {
1449
+ return {
1450
+ schemaVersion: WALLET_SCHEMA_VERSION,
1451
+ provider: "local",
1452
+ address,
1453
+ keystore,
1454
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1455
+ };
1456
+ }
1457
+
1458
+ // src/lib/wallet/spend.ts
1459
+ import { mkdir, readFile as readFile2 } from "fs/promises";
1460
+ import { randomUUID } from "crypto";
1461
+ var DEFAULT_WINDOW_MS = 864e5;
1462
+ var RESERVATION_TTL_MS = 6e5;
1463
+ var ReservationSchema = external_exports.object({
1464
+ id: external_exports.string(),
1465
+ amountAtomic: external_exports.string().regex(/^\d+$/),
1466
+ atMs: external_exports.number()
1467
+ });
1468
+ var LedgerSchema = external_exports.object({
1469
+ schemaVersion: external_exports.literal(2),
1470
+ windowStartMs: external_exports.number(),
1471
+ committedAtomic: external_exports.string().regex(/^\d+$/),
1472
+ reservations: external_exports.array(ReservationSchema)
1473
+ });
1474
+ function emptyLedger(nowMs) {
1475
+ return { schemaVersion: 2, windowStartMs: nowMs, committedAtomic: "0", reservations: [] };
1476
+ }
1477
+ function createLocalSpendAuthorizer(deps) {
1478
+ const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;
1479
+ const now = deps.now ?? Date.now;
1480
+ const path = spendLedgerPath(deps.dir);
1481
+ const lockPath = `${path}.lock`;
1482
+ let warnedCorrupt = false;
1483
+ const freshen = (ledger, nowMs) => {
1484
+ if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);
1485
+ return {
1486
+ ...ledger,
1487
+ reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS)
1488
+ };
1489
+ };
1490
+ const spentOf = (ledger) => ledger.reservations.reduce(
1491
+ (sum, r) => sum + BigInt(r.amountAtomic),
1492
+ BigInt(ledger.committedAtomic)
1493
+ );
1494
+ const persist = async (ledger) => {
1495
+ await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}
1496
+ `, {
1497
+ mode: 384,
1498
+ dirMode: 448
1499
+ });
1500
+ };
1501
+ async function withLedger(fn) {
1502
+ await mkdir(deps.dir, { recursive: true, mode: 448 });
1503
+ return withFileLock(lockPath, async () => {
1504
+ const nowMs = now();
1505
+ const read = await readLedger(path);
1506
+ if (read.corrupt !== void 0 && !warnedCorrupt) {
1507
+ warnedCorrupt = true;
1508
+ deps.onCorrupt?.(read.corrupt);
1509
+ }
1510
+ const ledger = freshen(read.ledger, nowMs);
1511
+ return fn(ledger, nowMs);
1512
+ });
1513
+ }
1514
+ return {
1515
+ policyEnforcement: "client-only",
1516
+ async authorize(req) {
1517
+ return withLedger(async (ledger) => {
1518
+ const sessionSpentAtomic = spentOf(ledger);
1519
+ const evaluation = evaluateSpendPolicy(deps.policy, {
1520
+ amountAtomic: req.amountAtomic,
1521
+ creator: req.creator,
1522
+ ...req.maxPriceAtomic !== void 0 ? { maxPriceAtomic: req.maxPriceAtomic } : {},
1523
+ sessionSpentAtomic
1524
+ });
1525
+ const base = {
1526
+ ...evaluation,
1527
+ amountAtomic: req.amountAtomic,
1528
+ sessionSpentAtomic,
1529
+ sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,
1530
+ policyEnforcement: "client-only"
1531
+ };
1532
+ if (evaluation.decision === "deny" || deps.policy.sessionBudgetAtomic === 0n) {
1533
+ return base;
1534
+ }
1535
+ const reservation = {
1536
+ id: randomUUID(),
1537
+ amountAtomic: req.amountAtomic.toString(),
1538
+ atMs: now()
1539
+ };
1540
+ await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });
1541
+ return { ...base, reservationId: reservation.id };
1542
+ });
1543
+ },
1544
+ async commit(reservationId, amountAtomic) {
1545
+ await withLedger(async (ledger) => {
1546
+ const reservation = reservationId !== void 0 ? ledger.reservations.find((r) => r.id === reservationId) : void 0;
1547
+ const settled = reservation !== void 0 ? BigInt(reservation.amountAtomic) : amountAtomic;
1548
+ await persist({
1549
+ ...ledger,
1550
+ committedAtomic: (BigInt(ledger.committedAtomic) + settled).toString(),
1551
+ reservations: reservationId !== void 0 ? ledger.reservations.filter((r) => r.id !== reservationId) : ledger.reservations
1552
+ });
1553
+ });
1554
+ },
1555
+ async release(reservationId) {
1556
+ if (reservationId === void 0) return;
1557
+ await withLedger(async (ledger) => {
1558
+ if (!ledger.reservations.some((r) => r.id === reservationId)) return;
1559
+ await persist({
1560
+ ...ledger,
1561
+ reservations: ledger.reservations.filter((r) => r.id !== reservationId)
1562
+ });
1563
+ });
1564
+ }
1565
+ };
1566
+ }
1567
+ async function readLedger(path) {
1568
+ let raw;
1569
+ try {
1570
+ raw = await readFile2(path, "utf8");
1571
+ } catch (err) {
1572
+ if (hasCode(err, "ENOENT")) return { ledger: null };
1573
+ return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };
1574
+ }
1575
+ let json;
1576
+ try {
1577
+ json = JSON.parse(raw);
1578
+ } catch {
1579
+ return { ledger: null, corrupt: "not valid JSON" };
1580
+ }
1581
+ const parsed = LedgerSchema.safeParse(json);
1582
+ if (parsed.success) return { ledger: parsed.data };
1583
+ const issue = parsed.error.issues[0];
1584
+ const field = issue?.path.join(".");
1585
+ const message = issue?.message ?? "schema mismatch";
1586
+ return {
1587
+ ledger: null,
1588
+ corrupt: field !== void 0 && field.length > 0 ? `${field}: ${message}` : message
1589
+ };
1590
+ }
1591
+
1592
+ // src/lib/wallet/index.ts
1593
+ function resolveWalletProvider(ctx, opts = {}) {
1594
+ if (opts.provider !== void 0) return opts.provider;
1595
+ return createLocalProvider({
1596
+ dir: ctx.dataDir,
1597
+ env: process.env,
1598
+ passphrase: { ...opts.passphrase, isTTY: ctx.io.isTTY ? void 0 : false }
1599
+ });
1600
+ }
1601
+ function resolveSpendAuthorizer(ctx, policy, opts = {}) {
1602
+ if (opts.authorizer !== void 0) return opts.authorizer;
1603
+ return createLocalSpendAuthorizer({
1604
+ dir: ctx.dataDir,
1605
+ policy,
1606
+ onCorrupt: (reason) => emitNotice(
1607
+ ctx.io,
1608
+ `spend ledger at ${spendLedgerPath(ctx.dataDir)} was unreadable (${reason}); spending window restarted`,
1609
+ { json: ctx.flags.json }
1610
+ )
1611
+ });
1612
+ }
1613
+ async function describeWallet(provider) {
1614
+ try {
1615
+ return await provider.describe();
1616
+ } catch (err) {
1617
+ if (err instanceof CliError) throw err;
1618
+ const message = err instanceof Error ? err.message : "unknown error";
1619
+ throw new CliError("PROVIDER_ERROR", `Wallet provider "${provider.id}" failed: ${message}`, {
1620
+ fix: "Check the wallet provider and try again.",
1621
+ cause: err
1622
+ });
1623
+ }
1624
+ }
1625
+
1626
+ export {
1627
+ resolvePassphraseForCreate,
1628
+ verifyLocalWallet,
1629
+ prepareLocalWallet,
1630
+ commitLocalWallet,
1631
+ createLocalWallet,
1632
+ verifyAndPreserveOutgoingWallet,
1633
+ parkOutgoingWallet,
1634
+ restoreParkedWallet,
1635
+ createLocalSpendAuthorizer,
1636
+ resolveWalletProvider,
1637
+ resolveSpendAuthorizer,
1638
+ describeWallet
1639
+ };
1640
+ /*! Bundled license information:
1641
+
1642
+ @noble/ciphers/esm/utils.js:
1643
+ (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1644
+ */
1645
+ //# sourceMappingURL=chunk-GECSWJ7O.js.map