oneie 5.8.0 → 5.9.0

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 (270) hide show
  1. package/README.md +114 -6
  2. package/dist/package.json +37 -11
  3. package/dist/src/age-1k8hs4ec.js +1 -0
  4. package/dist/src/client-n6fpnd9f.js +1 -0
  5. package/dist/src/evm-tx-cqhm9rtt.js +1 -0
  6. package/dist/src/hl-run-0pv1e0p2.js +1 -0
  7. package/dist/src/index-f5vhzspa.js +12 -0
  8. package/dist/src/index-h3nrt8bx.js +4 -0
  9. package/dist/src/index-st6k9vhc.js +2062 -0
  10. package/dist/src/index.js +1122 -134
  11. package/dist/src/message-key-yczrxszr.js +1 -0
  12. package/dist/src/message-lock-thr851d5.js +5 -0
  13. package/dist/src/sweep-order-jrq2hkye.js +1 -0
  14. package/dist/src/sweep-runner-jftw9em7.js +1 -0
  15. package/package.json +37 -11
  16. package/dist/src/agent.d.ts +0 -75
  17. package/dist/src/agent.js +0 -1334
  18. package/dist/src/agentverse.d.ts +0 -26
  19. package/dist/src/agentverse.js +0 -171
  20. package/dist/src/args.d.ts +0 -9
  21. package/dist/src/args.js +0 -61
  22. package/dist/src/auth.d.ts +0 -6
  23. package/dist/src/auth.js +0 -121
  24. package/dist/src/balances.d.ts +0 -89
  25. package/dist/src/balances.js +0 -202
  26. package/dist/src/banner.d.ts +0 -1
  27. package/dist/src/banner.js +0 -17
  28. package/dist/src/broadcast.d.ts +0 -8
  29. package/dist/src/broadcast.js +0 -175
  30. package/dist/src/catalog.d.ts +0 -12
  31. package/dist/src/catalog.js +0 -76
  32. package/dist/src/ceiling.d.ts +0 -36
  33. package/dist/src/ceiling.js +0 -189
  34. package/dist/src/chat.d.ts +0 -2
  35. package/dist/src/chat.js +0 -92
  36. package/dist/src/check.d.ts +0 -11
  37. package/dist/src/check.js +0 -53
  38. package/dist/src/client.d.ts +0 -5
  39. package/dist/src/client.js +0 -157
  40. package/dist/src/compiler.d.ts +0 -36
  41. package/dist/src/compiler.js +0 -366
  42. package/dist/src/config.d.ts +0 -24
  43. package/dist/src/config.js +0 -70
  44. package/dist/src/connect.d.ts +0 -2
  45. package/dist/src/connect.js +0 -64
  46. package/dist/src/coordinate.d.ts +0 -3
  47. package/dist/src/coordinate.js +0 -58
  48. package/dist/src/create.d.ts +0 -2
  49. package/dist/src/create.js +0 -113
  50. package/dist/src/credits.d.ts +0 -29
  51. package/dist/src/credits.js +0 -88
  52. package/dist/src/deploy.d.ts +0 -2
  53. package/dist/src/deploy.js +0 -19
  54. package/dist/src/dev.d.ts +0 -2
  55. package/dist/src/dev.js +0 -75
  56. package/dist/src/device-flow.d.ts +0 -57
  57. package/dist/src/device-flow.js +0 -173
  58. package/dist/src/doctor.d.ts +0 -26
  59. package/dist/src/doctor.js +0 -146
  60. package/dist/src/draw.d.ts +0 -18
  61. package/dist/src/draw.js +0 -156
  62. package/dist/src/endpoint.d.ts +0 -2
  63. package/dist/src/endpoint.js +0 -250
  64. package/dist/src/env.d.ts +0 -3
  65. package/dist/src/env.js +0 -37
  66. package/dist/src/eval.d.ts +0 -2
  67. package/dist/src/eval.js +0 -43
  68. package/dist/src/fn.d.ts +0 -2
  69. package/dist/src/fn.js +0 -70
  70. package/dist/src/group.d.ts +0 -2
  71. package/dist/src/group.js +0 -117
  72. package/dist/src/hl-run.d.ts +0 -119
  73. package/dist/src/hl-run.js +0 -480
  74. package/dist/src/hl.d.ts +0 -17
  75. package/dist/src/hl.js +0 -148
  76. package/dist/src/index.d.ts +0 -2
  77. package/dist/src/init.d.ts +0 -76
  78. package/dist/src/init.js +0 -278
  79. package/dist/src/join.d.ts +0 -11
  80. package/dist/src/join.js +0 -297
  81. package/dist/src/key-publish.d.ts +0 -40
  82. package/dist/src/key-publish.js +0 -232
  83. package/dist/src/key-seal.d.ts +0 -21
  84. package/dist/src/key-seal.js +0 -142
  85. package/dist/src/key-sweep.d.ts +0 -93
  86. package/dist/src/key-sweep.js +0 -270
  87. package/dist/src/key.d.ts +0 -26
  88. package/dist/src/key.js +0 -338
  89. package/dist/src/lib/age-plugin.d.ts +0 -51
  90. package/dist/src/lib/age-plugin.js +0 -130
  91. package/dist/src/lib/agent-env.d.ts +0 -12
  92. package/dist/src/lib/agent-env.js +0 -48
  93. package/dist/src/lib/api-path.d.ts +0 -2
  94. package/dist/src/lib/api-path.js +0 -40
  95. package/dist/src/lib/asker.d.ts +0 -34
  96. package/dist/src/lib/asker.js +0 -126
  97. package/dist/src/lib/check-words.d.ts +0 -57
  98. package/dist/src/lib/check-words.js +0 -144
  99. package/dist/src/lib/client.d.ts +0 -20
  100. package/dist/src/lib/client.js +0 -71
  101. package/dist/src/lib/env-sealed.d.ts +0 -53
  102. package/dist/src/lib/env-sealed.js +0 -184
  103. package/dist/src/lib/flow-tag.d.ts +0 -86
  104. package/dist/src/lib/flow-tag.js +0 -230
  105. package/dist/src/lib/hl-core/actions.d.ts +0 -99
  106. package/dist/src/lib/hl-core/actions.js +0 -69
  107. package/dist/src/lib/hl-core/eip712.d.ts +0 -33
  108. package/dist/src/lib/hl-core/eip712.js +0 -107
  109. package/dist/src/lib/hl-core/errors.d.ts +0 -10
  110. package/dist/src/lib/hl-core/errors.js +0 -15
  111. package/dist/src/lib/hl-core/exchange.d.ts +0 -24
  112. package/dist/src/lib/hl-core/exchange.js +0 -47
  113. package/dist/src/lib/hl-core/index.d.ts +0 -13
  114. package/dist/src/lib/hl-core/index.js +0 -14
  115. package/dist/src/lib/hl-core/meta.d.ts +0 -57
  116. package/dist/src/lib/hl-core/meta.js +0 -110
  117. package/dist/src/lib/hl-core/msgpack.d.ts +0 -18
  118. package/dist/src/lib/hl-core/msgpack.js +0 -136
  119. package/dist/src/lib/hl-core/net.d.ts +0 -2
  120. package/dist/src/lib/hl-core/net.js +0 -7
  121. package/dist/src/lib/hl-core/signing.d.ts +0 -103
  122. package/dist/src/lib/hl-core/signing.js +0 -295
  123. package/dist/src/lib/hl-core/wire.d.ts +0 -34
  124. package/dist/src/lib/hl-core/wire.js +0 -81
  125. package/dist/src/lib/invoked-as.d.ts +0 -2
  126. package/dist/src/lib/invoked-as.js +0 -24
  127. package/dist/src/lib/journey-words.d.ts +0 -84
  128. package/dist/src/lib/journey-words.js +0 -363
  129. package/dist/src/lib/journey.d.ts +0 -150
  130. package/dist/src/lib/journey.js +0 -264
  131. package/dist/src/lib/key-receipt.d.ts +0 -48
  132. package/dist/src/lib/key-receipt.js +0 -116
  133. package/dist/src/lib/key-source.d.ts +0 -9
  134. package/dist/src/lib/key-source.js +0 -33
  135. package/dist/src/lib/keyfile.d.ts +0 -136
  136. package/dist/src/lib/keyfile.js +0 -397
  137. package/dist/src/lib/launch-claude.d.ts +0 -5
  138. package/dist/src/lib/launch-claude.js +0 -45
  139. package/dist/src/lib/lock-lookup.d.ts +0 -40
  140. package/dist/src/lib/lock-lookup.js +0 -92
  141. package/dist/src/lib/message-seal.d.ts +0 -63
  142. package/dist/src/lib/message-seal.js +0 -150
  143. package/dist/src/lib/net-choice.d.ts +0 -28
  144. package/dist/src/lib/net-choice.js +0 -72
  145. package/dist/src/lib/network.d.ts +0 -22
  146. package/dist/src/lib/network.js +0 -50
  147. package/dist/src/lib/next-words.d.ts +0 -105
  148. package/dist/src/lib/next-words.js +0 -298
  149. package/dist/src/lib/paths.d.ts +0 -41
  150. package/dist/src/lib/paths.js +0 -91
  151. package/dist/src/lib/plan-draw.d.ts +0 -56
  152. package/dist/src/lib/plan-draw.js +0 -219
  153. package/dist/src/lib/plan-live.d.ts +0 -20
  154. package/dist/src/lib/plan-live.js +0 -192
  155. package/dist/src/lib/qr.d.ts +0 -21
  156. package/dist/src/lib/qr.js +0 -402
  157. package/dist/src/lib/roster.d.ts +0 -20
  158. package/dist/src/lib/roster.js +0 -79
  159. package/dist/src/lib/sale-card.d.ts +0 -117
  160. package/dist/src/lib/sale-card.js +0 -261
  161. package/dist/src/lib/shop-init.d.ts +0 -62
  162. package/dist/src/lib/shop-init.js +0 -63
  163. package/dist/src/lib/sui-grpc-send.d.ts +0 -90
  164. package/dist/src/lib/sui-grpc-send.js +0 -128
  165. package/dist/src/lib/swap-core.d.ts +0 -163
  166. package/dist/src/lib/swap-core.js +0 -405
  167. package/dist/src/lib/tasks-digest.d.ts +0 -66
  168. package/dist/src/lib/tasks-digest.js +0 -200
  169. package/dist/src/lib/tasks-graph.d.ts +0 -79
  170. package/dist/src/lib/tasks-graph.js +0 -463
  171. package/dist/src/lib/tasks-lens.d.ts +0 -31
  172. package/dist/src/lib/tasks-lens.js +0 -47
  173. package/dist/src/lib/tasks-next.d.ts +0 -25
  174. package/dist/src/lib/tasks-next.js +0 -103
  175. package/dist/src/lib/tasks-prove.d.ts +0 -15
  176. package/dist/src/lib/tasks-prove.js +0 -68
  177. package/dist/src/lib/tasks-route.d.ts +0 -29
  178. package/dist/src/lib/tasks-route.js +0 -151
  179. package/dist/src/lib/tasks-score.d.ts +0 -36
  180. package/dist/src/lib/tasks-score.js +0 -152
  181. package/dist/src/lib/tasks-workspace.d.ts +0 -18
  182. package/dist/src/lib/tasks-workspace.js +0 -73
  183. package/dist/src/lib/timed-fetch.d.ts +0 -33
  184. package/dist/src/lib/timed-fetch.js +0 -59
  185. package/dist/src/lib/vault-read.d.ts +0 -24
  186. package/dist/src/lib/vault-read.js +0 -77
  187. package/dist/src/lib/vaultfile.d.ts +0 -103
  188. package/dist/src/lib/vaultfile.js +0 -249
  189. package/dist/src/lib/wallet-money.d.ts +0 -222
  190. package/dist/src/lib/wallet-money.js +0 -578
  191. package/dist/src/lib/wallet-request.d.ts +0 -50
  192. package/dist/src/lib/wallet-request.js +0 -86
  193. package/dist/src/links.d.ts +0 -5
  194. package/dist/src/links.js +0 -45
  195. package/dist/src/media.d.ts +0 -29
  196. package/dist/src/media.js +0 -487
  197. package/dist/src/message-receipt.d.ts +0 -25
  198. package/dist/src/message-receipt.js +0 -71
  199. package/dist/src/message.d.ts +0 -13
  200. package/dist/src/message.js +0 -92
  201. package/dist/src/move.d.ts +0 -36
  202. package/dist/src/move.js +0 -152
  203. package/dist/src/network-cmd.d.ts +0 -17
  204. package/dist/src/network-cmd.js +0 -74
  205. package/dist/src/next.d.ts +0 -12
  206. package/dist/src/next.js +0 -67
  207. package/dist/src/onboard.d.ts +0 -16
  208. package/dist/src/onboard.js +0 -149
  209. package/dist/src/plugin.d.ts +0 -2
  210. package/dist/src/plugin.js +0 -193
  211. package/dist/src/push.d.ts +0 -2
  212. package/dist/src/push.js +0 -115
  213. package/dist/src/render.d.ts +0 -21
  214. package/dist/src/render.js +0 -32
  215. package/dist/src/secrets-device.d.ts +0 -32
  216. package/dist/src/secrets-device.js +0 -127
  217. package/dist/src/secrets-give.d.ts +0 -125
  218. package/dist/src/secrets-give.js +0 -236
  219. package/dist/src/secrets-list.d.ts +0 -27
  220. package/dist/src/secrets-list.js +0 -84
  221. package/dist/src/secrets-run.d.ts +0 -31
  222. package/dist/src/secrets-run.js +0 -182
  223. package/dist/src/secrets.d.ts +0 -33
  224. package/dist/src/secrets.js +0 -200
  225. package/dist/src/setup.d.ts +0 -6
  226. package/dist/src/setup.js +0 -127
  227. package/dist/src/ship.d.ts +0 -2
  228. package/dist/src/ship.js +0 -18
  229. package/dist/src/shop-buy.d.ts +0 -16
  230. package/dist/src/shop-buy.js +0 -101
  231. package/dist/src/shop.d.ts +0 -10
  232. package/dist/src/shop.js +0 -112
  233. package/dist/src/skill-parser.d.ts +0 -14
  234. package/dist/src/skill-parser.js +0 -113
  235. package/dist/src/skill.d.ts +0 -2
  236. package/dist/src/skill.js +0 -493
  237. package/dist/src/slug.d.ts +0 -2
  238. package/dist/src/slug.js +0 -6
  239. package/dist/src/social.d.ts +0 -2
  240. package/dist/src/social.js +0 -106
  241. package/dist/src/staff.d.ts +0 -2
  242. package/dist/src/staff.js +0 -104
  243. package/dist/src/start.d.ts +0 -27
  244. package/dist/src/start.js +0 -225
  245. package/dist/src/status.d.ts +0 -2
  246. package/dist/src/status.js +0 -52
  247. package/dist/src/substrate.d.ts +0 -2
  248. package/dist/src/substrate.js +0 -258
  249. package/dist/src/swap.d.ts +0 -93
  250. package/dist/src/swap.js +0 -622
  251. package/dist/src/tasks.d.ts +0 -2
  252. package/dist/src/tasks.js +0 -743
  253. package/dist/src/templates.d.ts +0 -1
  254. package/dist/src/templates.js +0 -213
  255. package/dist/src/thread.d.ts +0 -2
  256. package/dist/src/thread.js +0 -52
  257. package/dist/src/trade.d.ts +0 -2
  258. package/dist/src/trade.js +0 -91
  259. package/dist/src/trail.d.ts +0 -2
  260. package/dist/src/trail.js +0 -41
  261. package/dist/src/validate.d.ts +0 -13
  262. package/dist/src/validate.js +0 -35
  263. package/dist/src/wallet-money.d.ts +0 -158
  264. package/dist/src/wallet-money.js +0 -664
  265. package/dist/src/wallet.d.ts +0 -169
  266. package/dist/src/wallet.js +0 -973
  267. package/dist/src/workflow.d.ts +0 -2
  268. package/dist/src/workflow.js +0 -169
  269. package/dist/src/write.d.ts +0 -43
  270. package/dist/src/write.js +0 -180
@@ -1,973 +0,0 @@
1
- import { Command } from 'commander';
2
- import { mergeEnv } from './env.js';
3
- import { writeFileSync, chmodSync, readFileSync, existsSync, rmSync } from 'node:fs';
4
- import { createInterface } from 'node:readline';
5
- import { generateWallet, recoverWallet, readDerivation } from '@oneie/sdk/wallet';
6
- import { sealVault, openVault, mintKeychainSecret } from '@oneie/sdk/vault-file';
7
- import { proveAddresses } from '@oneie/sdk/address-proof';
8
- import { askPath } from './lib/api-path.js';
9
- import { balancesCmd } from './balances.js';
10
- import { workspaceFor } from './lib/keyfile.js';
11
- import { resolveKey } from './lib/client.js';
12
- import { keySourceOf } from './lib/key-source.js';
13
- import { readMachineKey } from './lib/paths.js';
14
- import { wordsStdoutRefusal, agentType } from './lib/agent-env.js';
15
- import { cliPrefix } from './lib/invoked-as.js';
16
- import { writeVaultFolder, readVaultFolder, vaultPath, paperSheet, keychainStore, keychainRead, keychainAvailable, keychainDelete, seSealPath, seIdentityPath, } from './lib/vaultfile.js';
17
- import { keygen, openWithAge, recipientOf, sealWithAge } from './lib/age-plugin.js';
18
- import { receiveCmd, requestCmd, sendCmd, upgradeBalances } from './wallet-money.js';
19
- import { ceilingCmd } from './ceiling.js';
20
- import { savedNet } from './lib/net-choice.js';
21
- const DEFAULT_API = process.env.ONEIE_BASE_URL ?? process.env.ONE_API_URL ?? 'https://api.one.ie';
22
- // Re-exported for existing callers/tests — canonical implementation now lives
23
- // in ./lib/api-path.ts so trade.ts/client.ts/coordinate.ts/catalog.ts can share
24
- // it instead of each hardcoding /api/ask/<receiver> against DEFAULT_API.
25
- export { askPath };
26
- /**
27
- * The refusal as the server said it. `wallet:send → failure` alone hid the reason —
28
- * measured 2026-11-03 (text/agent-path.md § Stop 8): the server had answered
29
- * `forbidden · requires manage_workspace · callerRole agent · "Requires the owner role"`.
30
- */
31
- export function refusalMessage(receiver, envelope) {
32
- const r = envelope.result ?? {};
33
- const why = [r.error ?? envelope.error, r.required && `requires ${String(r.required)}`, r.callerRole && `you are ${String(r.callerRole)}`]
34
- .filter(Boolean).map(String);
35
- const hint = typeof r.hint === 'string' ? ` — ${r.hint}` : '';
36
- return `${receiver} → ${envelope.outcome}${why.length ? `: ${why.join(' · ')}` : ''}${hint}`;
37
- }
38
- /** A wallet receiver that has not answered in this long is not going to: say so, never wait forever (lib/timed-fetch.ts). */
39
- const WALLET_ASK_TIMEOUT_MS = 60_000;
40
- async function ask(base, key, receiver, data) {
41
- const signal = AbortSignal.timeout(WALLET_ASK_TIMEOUT_MS);
42
- const res = await fetch(askPath(base, receiver), {
43
- method: 'POST',
44
- headers: { 'Content-Type': 'application/json', ...(key ? { Authorization: `Bearer ${key}` } : {}) },
45
- body: JSON.stringify({ data }),
46
- signal,
47
- }).catch((e) => {
48
- if (signal.aborted)
49
- throw new Error(`${receiver} did not answer in ${WALLET_ASK_TIMEOUT_MS / 1000} s`);
50
- throw e;
51
- });
52
- if (!res.ok) {
53
- const body = await res.text().catch(() => '');
54
- throw new Error(`${receiver} → ${res.status}\n${body}`);
55
- }
56
- const envelope = (await res.json());
57
- if (envelope.outcome && envelope.outcome !== 'result')
58
- throw new Error(refusalMessage(receiver, envelope));
59
- return envelope.result ?? envelope;
60
- }
61
- const DEFAULT_PAY = process.env.ONEIE_PAY_URL ?? 'https://pay.one.ie';
62
- // pay.one.ie is a separate service from the gateway/one.ie ask surface above —
63
- // its own protocol envelope, POST <payUrl>/ { protocol, data } → { success, data,
64
- // error? }. faucet_request is public (no credential), matching the threat model:
65
- // funding ≠ ownership, anyone can fund any address (wallet-plan.md).
66
- async function payProtocol(payUrl, protocol, data) {
67
- const res = await fetch(`${payUrl.replace(/\/$/, '')}/`, {
68
- method: 'POST',
69
- headers: { 'Content-Type': 'application/json' },
70
- body: JSON.stringify({ protocol, data }),
71
- });
72
- const body = (await res.json().catch(() => ({})));
73
- if (!res.ok || !body.success) {
74
- throw new Error(`${protocol} → ${body.error?.message ?? body.error?.code ?? res.status}`);
75
- }
76
- return body.data ?? {};
77
- }
78
- // ── which derivation a wallet is born under ─────────────────────────────────
79
- /**
80
- * A FRESH mint is born v2 — the same as one.ie (`NEW_MASTER_DERIVATION` in
81
- * one.ie/web/src/lib/derive-multichain.ts). Before this the CLI minted v1 and the
82
- * browser v2, so the same 24 words opened a different, empty wallet on each
83
- * surface and nothing errored (task:01a0c33a93bbebfc8e2ebba0).
84
- *
85
- * A RECOVER has no marker to read, so it takes `--derivation` and an absent one is
86
- * v1: the words may belong to a v1 key, and a v1 key recovers its v1 addresses
87
- * forever. Guessing v2 here would recreate the same silent divergence in reverse.
88
- */
89
- export const MINT_DERIVATION = 'v2';
90
- export function walletDerivation(opts) {
91
- if (opts.derivation === undefined)
92
- return opts.recover ? 'v1' : MINT_DERIVATION;
93
- return readDerivation(opts.derivation);
94
- }
95
- /** Mint or recover, under the derivation named above — the one door both commands use. */
96
- export async function walletFor(opts, words) {
97
- const derivation = walletDerivation(opts);
98
- const wallet = opts.recover ? await recoverWallet(words(), derivation) : await generateWallet(derivation);
99
- return { wallet, derivation };
100
- }
101
- /** Seal the words WITH their derivation. v1 is the field's absence (it rides the
102
- * AAD only when present), so a v1 vault stays byte-compatible with every one
103
- * written before the marker existed. */
104
- export async function sealWallet(mnemonic, passphrase, opts) {
105
- return sealVault(mnemonic, passphrase, {
106
- wrap: opts.wrap,
107
- authPub: opts.authPub,
108
- kdf: opts.kdf,
109
- ...(opts.derivation === 'v2' ? { derivation: 'v2' } : {}),
110
- });
111
- }
112
- /** The addresses a sealed vault holds, read under ITS marker — absent is v1. */
113
- export async function openedWallet(blob, mnemonic) {
114
- return recoverWallet(mnemonic, readDerivation(blob.derivation));
115
- }
116
- function resolveAuth(opts) {
117
- const env = mergeEnv(process.cwd());
118
- const key = opts.key ?? env.ONEIE_API_KEY ?? env.ONE_API_KEY ?? resolveKey();
119
- return { base: opts.api.replace(/\/$/, ''), key };
120
- }
121
- export { workspaceFor };
122
- function resolveWorkspace(explicit) {
123
- const workspace = workspaceFor(explicit, process.cwd(), mergeEnv(process.cwd()));
124
- if (!workspace) {
125
- process.stderr.write('--workspace required (or set AGENCY_SLUG, or run from the folder `npx oneie` made)\n');
126
- process.exit(1);
127
- }
128
- return workspace;
129
- }
130
- // A chain with no auto-fund path (ETH/USDC/BTC) legitimately returns success:false
131
- // with a manualUrls fallback — that's documented, expected behavior (wallet-plan.md:
132
- // "SUI/SOL auto-fund; ETH/USDC/BTC return a manual URL"), never a call failure.
133
- // `ok` here means "the request was answered" (payProtocol already throws on a real
134
- // failure) — per-chain funded/manual status lives in `results`, read that, not `ok`.
135
- export function faucetOk(results) {
136
- return results.length > 0;
137
- }
138
- // wallet:get/create/transactions return bare data or { error } — no `ok` field
139
- // of their own. wallet:send already returns { ok, ... }. Normalize both to the
140
- // { ok, ... } shape out() expects without ever overwriting a real error/false
141
- // with a hardcoded ok:true.
142
- export function okWrap(result) {
143
- if ('ok' in result)
144
- return result;
145
- if ('error' in result)
146
- return { ok: false, ...result };
147
- return { ok: true, ...result };
148
- }
149
- export function walletCmd() {
150
- const cmd = new Command('wallet').description('Read balances, provision a wallet row, fund from testnet, send crypto — wallet:* receivers + pay.one.ie');
151
- cmd.command('get')
152
- .description('Credits, spend ceiling, wallet rows, live chain balances (sui · evm · solana · btc · hyperliquid), delegated wallets')
153
- .option('--workspace <slug>', 'Workspace (defaults to AGENCY_SLUG)')
154
- .option('--actor <id>', 'Actor within the workspace (defaults to workspace)')
155
- .option('--net <network>', 'mainnet | testnet — the one network every balance is read on (default: ONE_NETWORK, then `one network`, then the deploy\'s)')
156
- .option('--api <url>', 'API base URL', DEFAULT_API)
157
- .option('--key <key>', 'API key (overrides ONEIE_API_KEY env)')
158
- .action(async (opts) => {
159
- // The server already defaults to its own deploy; send a network only when one is NAMED here.
160
- if (!opts.net)
161
- opts.net = process.env.ONE_NETWORK?.trim() || savedNet() || undefined;
162
- if (opts.net && opts.net !== 'mainnet' && opts.net !== 'testnet') {
163
- out(cmd, { ok: false, error: '--net must be mainnet or testnet' });
164
- process.exitCode = 1;
165
- return;
166
- }
167
- const { base, key } = resolveAuth(opts);
168
- const workspace = resolveWorkspace(opts.workspace);
169
- const result = await ask(base, key, 'wallet:get', { workspace, actor: opts.actor, ...(opts.net ? { net: opts.net } : {}) });
170
- out(cmd, okWrap(result));
171
- });
172
- // ceiling — the agent's on-chain spend ceiling (src/ceiling.ts): owner-signed create/set, show, register with pay.
173
- cmd.addCommand(ceilingCmd());
174
- // balances — the REAL mainnet balances of the loaded wallet, read from the chains (src/balances.ts).
175
- // `get` above is ONE's own ledger and shows test money for most chains.
176
- cmd.addCommand(balancesCmd({
177
- fetch: (url, init) => fetch(url, init),
178
- addresses: async (opts) => {
179
- const { base, key } = resolveAuth(opts);
180
- const workspace = resolveWorkspace(opts.workspace);
181
- const w = await ask(base, key, 'wallet:get', { workspace, actor: opts.actor });
182
- const rows = Array.isArray(w['addresses']) ? w['addresses'] : [];
183
- const who = opts.actor ?? workspace;
184
- const mine = (chain) => rows.find((x) => x.chain === chain && x.actor === who && typeof x.address === 'string')?.address;
185
- return { evm: mine('evm'), sui: mine('sui') };
186
- },
187
- }, DEFAULT_API));
188
- // list — every wallet in the workspace with the words it wears (treasury · agent · person ·
189
- // limit · paused · no-limit · sweep · vault · no-address). The tags are wallet:get's own,
190
- // derived on the server from the rows, the caps and the signed sweep rules.
191
- cmd.command('list')
192
- .description('Every wallet in the workspace with its tags, limit and sweep rule')
193
- .option('--workspace <slug>', 'Workspace (defaults to AGENCY_SLUG)')
194
- .option('--api <url>', 'API base URL', DEFAULT_API)
195
- .option('--key <key>', 'API key (overrides ONEIE_API_KEY env)')
196
- .action(async (opts) => {
197
- const { base, key } = resolveAuth(opts);
198
- const workspace = resolveWorkspace(opts.workspace);
199
- const result = await ask(base, key, 'wallet:get', { workspace });
200
- const wallets = Array.isArray(result.wallets) ? result.wallets : [];
201
- const rows = wallets.map(walletLine);
202
- if (cmd.parent?.opts().json) {
203
- process.stdout.write(JSON.stringify({ ok: !result.error, workspace, wallets: rows, ...(result.error ? { error: result.error } : {}) }) + '\n');
204
- return;
205
- }
206
- if (result.error)
207
- return out(cmd, okWrap(result));
208
- if (!rows.length)
209
- return console.log(`no wallets in ${workspace} yet`);
210
- for (const r of rows)
211
- console.log(formatWalletLine(r));
212
- });
213
- // limit — the owner's one number for an agent: credits a month, 0 pauses it. Lowering is
214
- // open to anyone who controls the workspace; raising needs a person (this CLI's own human
215
- // key counts, an agent key never does). The server decides — this only sends the number.
216
- cmd.command('limit <agent> <credits>')
217
- .description('Set an agent\'s spending limit in credits a month (1000 = $1). 0 pauses it')
218
- .option('--workspace <slug>', 'Workspace (defaults to AGENCY_SLUG)')
219
- .option('--api <url>', 'API base URL', DEFAULT_API)
220
- .option('--key <key>', 'API key (overrides ONEIE_API_KEY env)')
221
- .action(async (agent, raw, opts) => {
222
- const credits = parseCredits(raw);
223
- if (credits === null) {
224
- out(cmd, { ok: false, error: 'credits must be a whole number from 0 to 10000000' });
225
- process.exitCode = 1;
226
- return;
227
- }
228
- const { base, key } = resolveAuth(opts);
229
- const workspace = resolveWorkspace(opts.workspace);
230
- const result = await ask(base, key, 'wallet:update', { workspace, actor: agent, limit: credits });
231
- if (!result.ok)
232
- process.exitCode = 1;
233
- out(cmd, okWrap(result));
234
- });
235
- cmd.command('create')
236
- .description('Provision a wallet row for an actor (idempotent)')
237
- .option('--workspace <slug>', 'Workspace (defaults to AGENCY_SLUG)')
238
- .option('--actor <id>', 'Actor to provision (defaults to workspace)')
239
- .option('--kind <kind>', 'human | agent', 'human')
240
- .option('--api <url>', 'API base URL', DEFAULT_API)
241
- .option('--key <key>', 'API key (overrides ONEIE_API_KEY env)')
242
- .action(async (opts) => {
243
- const { base, key } = resolveAuth(opts);
244
- const workspace = resolveWorkspace(opts.workspace);
245
- const result = await ask(base, key, 'wallet:create', { workspace, actor: opts.actor, kind: opts.kind });
246
- out(cmd, okWrap(result));
247
- });
248
- cmd.command('transactions')
249
- .description('Unified transaction feed across every settlement rail')
250
- .option('--workspace <slug>', 'Workspace (defaults to AGENCY_SLUG)')
251
- .option('--limit <n>', 'Max rows (default 100, max 500)', '100')
252
- .option('--api <url>', 'API base URL', DEFAULT_API)
253
- .option('--key <key>', 'API key (overrides ONEIE_API_KEY env)')
254
- .action(async (opts) => {
255
- const { base, key } = resolveAuth(opts);
256
- const workspace = resolveWorkspace(opts.workspace);
257
- const result = await ask(base, key, 'wallet:transactions', { workspace, limit: Number(opts.limit) });
258
- out(cmd, okWrap(result));
259
- });
260
- cmd.command('faucet <address>')
261
- .description('Fund an address from a testnet tap — Sui and Solana auto-fund; ETH/USDC/BTC return a manual faucet URL')
262
- .requiredOption('--chain <chain>', 'sui | sol | eth | usdc | btc | all')
263
- .option('--network <network>', 'testnet | devnet (Sui only)')
264
- .option('--pay-url <url>', 'pay.one.ie base URL', DEFAULT_PAY)
265
- .action(async (address, opts) => {
266
- const data = await payProtocol(opts.payUrl, 'faucet_request', { chain: opts.chain, address, network: opts.network });
267
- const results = (data.results ?? []);
268
- out(cmd, { ok: faucetOk(results), results, manualFaucets: data.manualFaucets });
269
- });
270
- // receive · send · request, and --net on balances — the loaded wallet's money (src/wallet-money.ts).
271
- // `send <amount> <asset>[@chain] <to>` signs with the sealed vault on --live; the older
272
- // `send <to> --chain --amount --payment-tx` form still records a transfer signed elsewhere.
273
- const money = {
274
- ask: (o, receiver, data) => { const { base, key } = resolveAuth(o); return ask(base, key, receiver, data); },
275
- workspace: resolveWorkspace,
276
- // Who the key acts as and where it came from — wallet:challenge names the actor; the key itself is never printed.
277
- identity: async (o, which) => {
278
- const src = keySourceOf(o);
279
- if (which === 'machine' && !src.local)
280
- return null;
281
- const { base, key } = resolveAuth(o);
282
- const useKey = which === 'machine' ? readMachineKey() : key;
283
- const from = which === 'machine' ? keySourceOf({}, '/nonexistent-folder', {}).label : src.label;
284
- let actor;
285
- try {
286
- actor = String((await ask(base, useKey, 'wallet:challenge', {}))['actor'] ?? '') || undefined;
287
- }
288
- catch { /* unread: the header says so */ }
289
- return { actor, from, local: which === 'machine' ? false : src.local };
290
- },
291
- unlock: (dir) => unlock(dir),
292
- defaultApi: DEFAULT_API,
293
- relay: async (_c, to, o) => {
294
- const opts = o;
295
- const { base, key } = resolveAuth(opts);
296
- const workspace = resolveWorkspace(opts.workspace);
297
- const result = await ask(base, key, 'wallet:send', {
298
- workspace, to, chain: opts.chain, amount: Number(opts.amount), paymentTx: opts.paymentTx,
299
- unit: opts.unit, currency: opts.currency, userAddress: opts.userAddress, memo: opts.memo,
300
- });
301
- out(cmd, okWrap(result));
302
- },
303
- };
304
- const balances = cmd.commands.find((c) => c.name() === 'balances');
305
- if (balances)
306
- upgradeBalances(balances, money);
307
- cmd.addCommand(receiveCmd(money));
308
- cmd.addCommand(sendCmd(money));
309
- cmd.addCommand(requestCmd(money));
310
- cmd.command('register')
311
- .description('Register a keygen output\'s PUBLIC receiving addresses with a workspace — sends addresses only, never a key or a mnemonic. With --kind agent the keys in --from (or the sealed wallet in --dir) sign a server challenge locally, and only the signatures are sent. First write wins per chain and is permanent')
312
- .option('--from <file>', 'A `wallet keygen --out` file (or any JSON with `addresses` / `keys`) — only the address fields are read')
313
- .option('--addresses <json>', 'Inline JSON address map, e.g. \'{"sui":"0x…","evm":"0x…"}\'')
314
- .option('--dir <path>', 'With --kind agent: open the SEALED wallet in this project folder (what `oneie init` / `wallet new` write) — passphrase at the terminal, or Touch ID for a keychain wallet — and register it by proof')
315
- .option('--workspace <slug>', 'Workspace (defaults to AGENCY_SLUG)')
316
- .option('--actor <id>', 'Actor to register for (defaults to workspace)')
317
- .option('--kind <kind>', 'human | agent', 'human')
318
- .option('--yes', 'Skip the confirmation prompt (for scripted provisioning)')
319
- .option('--api <url>', 'API base URL', DEFAULT_API)
320
- .option('--key <key>', 'API key (overrides ONEIE_API_KEY env)')
321
- .action(async (opts) => {
322
- const { base, key } = resolveAuth(opts);
323
- const workspace = resolveWorkspace(opts.workspace);
324
- if (opts.dir !== undefined) {
325
- if (opts.from || opts.addresses) {
326
- out(cmd, { ok: false, error: '--dir opens a sealed wallet — pass it alone, not with --from or --addresses' });
327
- return;
328
- }
329
- if (opts.kind !== 'agent') {
330
- out(cmd, { ok: false, error: '--dir registers by proof, which is the agent path — pass --kind agent' });
331
- return;
332
- }
333
- const actor = opts.actor ?? workspace;
334
- out(cmd, await registerSealedWallet({
335
- base, key, workspace, actor, dir: opts.dir,
336
- confirmAddresses: async (addresses) => {
337
- process.stderr.write(`Registering PUBLIC receiving addresses for actor '${actor}' in workspace '${workspace}':\n`);
338
- for (const [chain, addr] of Object.entries(addresses))
339
- process.stderr.write(` ${chain.padEnd(7)} ${addr}\n`);
340
- process.stderr.write('This is permanent — the first address written to a chain cannot be changed.\n');
341
- return Boolean(opts.yes) || confirm('Register these addresses? [y/N] ');
342
- },
343
- }));
344
- return;
345
- }
346
- const source = opts.from
347
- ? JSON.parse(readFileSync(opts.from, 'utf8'))
348
- : opts.addresses
349
- ? JSON.parse(opts.addresses)
350
- : (() => { throw new Error('register needs --from <file> or --addresses <json>'); })();
351
- const addresses = addressesOnly(source);
352
- if (Object.keys(addresses).length === 0) {
353
- throw new Error('no addresses found — expected an `addresses` map or a `keys` array of { chain, address }');
354
- }
355
- // mergeAddresses is FIRST-WRITE-WINS: a wrong address here is where every future
356
- // payment lands, and the row refuses to change it afterwards (address_conflict).
357
- // So the operator reads the exact strings back before anything is sent.
358
- const actor = opts.actor ?? workspace;
359
- process.stderr.write(`Registering PUBLIC receiving addresses for actor '${actor}' in workspace '${workspace}':\n`);
360
- for (const [chain, addr] of Object.entries(addresses)) {
361
- process.stderr.write(` ${chain.padEnd(7)} ${addr}\n`);
362
- }
363
- process.stderr.write('This is permanent — the first address written to a chain cannot be changed.\n');
364
- if (!opts.yes && !(await confirm('Register these addresses? [y/N] '))) {
365
- out(cmd, { ok: false, error: 'cancelled' });
366
- return;
367
- }
368
- // An agent's addresses are taken only with proof of control, so an agent
369
- // registration signs locally with the keygen file's keys — inline
370
- // --addresses carries no keys and cannot prove anything.
371
- if (opts.kind === 'agent') {
372
- const keys = signingKeys(source);
373
- if (keys.length === 0) {
374
- out(cmd, { ok: false, error: 'an agent registration signs a server challenge — pass --from <a `wallet keygen --out` file> holding the keys' });
375
- return;
376
- }
377
- out(cmd, await registerAgentWallet({ base, key, workspace, actor, keys }));
378
- return;
379
- }
380
- // `actor`, not `opts.actor` — what the operator confirmed on screen is what gets
381
- // written, rather than relying on the resolver's own default to agree.
382
- const result = await ask(base, key, 'wallet:create', { workspace, actor, kind: opts.kind, addresses });
383
- out(cmd, okWrap(result));
384
- });
385
- cmd.command('keygen')
386
- .description('Generate or recover a self-hosted wallet locally — Sui/EVM/Sol/BTC, plus ASI under v2, fully offline, never touches the network or a server. Prints once by default; use --out for scripted bulk provisioning')
387
- .option('--recover', 'Recover from a 24-word BIP-39 mnemonic (ONE_WALLET_MNEMONIC env or stdin) instead of generating a fresh one')
388
- .option('--derivation <v>', 'v2 (default for a fresh key — what one.ie mints) or v1. With --recover the default is v1: the words carry no marker, and a v1 key recovers its v1 addresses forever')
389
- .option('--out <file>', 'Write the mnemonic + keys to a file at mode 0600 instead of printing once')
390
- .option('--yes-i-accept-plaintext-file', 'Required with --out — acknowledge that unencrypted key material will be written to disk')
391
- .action(async (opts) => {
392
- const { wallet, derivation } = await walletFor(opts, readMnemonic);
393
- const addresses = Object.fromEntries(wallet.keys.map((k) => [k.chain, k.address]));
394
- if (opts.out) {
395
- const contents = JSON.stringify({ mnemonic: wallet.mnemonic, derivation, keys: wallet.keys }, null, 2) + '\n';
396
- writeKeysFile(opts.out, contents, Boolean(opts.yesIAcceptPlaintextFile));
397
- out(cmd, { ok: true, out: opts.out, derivation, chains: wallet.keys.map((k) => k.chain), addresses });
398
- }
399
- else {
400
- out(cmd, { ok: true, mnemonic: wallet.mnemonic, derivation, addresses, keys: wallet.keys });
401
- }
402
- });
403
- // ── the encrypted wallet folder ────────────────────────────────────────────
404
- cmd.command('new')
405
- .description('Create an encrypted wallet in this folder — 24 words sealed with a passphrase, four chains (five under v2, with ASI), fully offline')
406
- .option('--dir <path>', 'Project directory', '.')
407
- .option('--recover', 'Seal an EXISTING 24-word phrase instead of generating a new one (ONE_WALLET_MNEMONIC or stdin)')
408
- .option('--derivation <v>', 'v2 (default for a fresh wallet — what one.ie mints) or v1. With --recover the default is v1: the words carry no marker, and a v1 key recovers its v1 addresses forever')
409
- .option('--keychain', 'Seal with a random secret stored in Apple Keychain, so Touch ID opens it instead of a passphrase')
410
- .action(async (opts) => {
411
- // Refuse BEFORE generating. Minting a wallet and then failing to store it
412
- // is the one outcome that loses money: the words would exist only in a
413
- // process about to exit.
414
- if (existsSync(vaultPath(opts.dir))) {
415
- out(cmd, { ok: false, error: `a wallet already exists at ${vaultPath(opts.dir)} — move it aside first` });
416
- return;
417
- }
418
- if (opts.keychain && !keychainAvailable()) {
419
- out(cmd, { ok: false, error: 'Keychain is macOS-only — omit --keychain to seal with a passphrase' });
420
- return;
421
- }
422
- // A bad --derivation is refused before the passphrase is asked for, not after.
423
- try {
424
- walletDerivation(opts);
425
- }
426
- catch {
427
- out(cmd, { ok: false, error: '--derivation must be v1 or v2' });
428
- return;
429
- }
430
- let passphrase;
431
- let wrap;
432
- if (opts.keychain) {
433
- passphrase = mintKeychainSecret();
434
- wrap = 'keychain';
435
- }
436
- else {
437
- passphrase = await promptSecret('Passphrase for this wallet: ');
438
- const again = await promptSecret('Repeat it: ');
439
- if (passphrase !== again) {
440
- out(cmd, { ok: false, error: 'passphrases did not match — nothing was written' });
441
- return;
442
- }
443
- if (passphrase.length < 8) {
444
- out(cmd, { ok: false, error: 'passphrase too short — this is the only thing between a stolen laptop and the wallet' });
445
- return;
446
- }
447
- wrap = 'passphrase';
448
- }
449
- const { wallet, derivation } = await walletFor(opts, readMnemonic);
450
- const addresses = Object.fromEntries(wallet.keys.map((k) => [k.chain, k.address]));
451
- const authPub = wallet.keys.find((k) => k.chain === 'sui')?.publicKeyHex ?? '';
452
- const blob = await sealWallet(wallet.mnemonic, passphrase, { wrap, authPub, derivation });
453
- const res = writeVaultFolder(opts.dir, { ...blob });
454
- if (!res.ok) {
455
- out(cmd, { ok: false, error: res.error });
456
- return;
457
- }
458
- if (opts.keychain) {
459
- const k = keychainStore(authPub, passphrase);
460
- if (!k.ok) {
461
- // The vault is sealed with a secret nobody can now produce. Remove it
462
- // rather than leaving an unopenable file that looks like a wallet.
463
- rmSync(res.path, { force: true });
464
- out(cmd, { ok: false, error: `Keychain write failed (${k.error}) — the wallet was removed rather than left unopenable` });
465
- return;
466
- }
467
- }
468
- out(cmd, {
469
- ok: true,
470
- wallet: res.path,
471
- wrap,
472
- derivation,
473
- addresses,
474
- next: `${cliPrefix()} wallet paper${opts.dir === '.' ? '' : ` --dir ${opts.dir}`} # write the 24 words down — this is the ONLY backup`,
475
- });
476
- });
477
- cmd.command('open')
478
- .description('Unlock the wallet in this folder and show its addresses — the phrase never leaves this machine')
479
- .option('--dir <path>', 'Project directory', '.')
480
- .action(async (opts) => {
481
- const r = await unlock(opts.dir);
482
- if ('error' in r) {
483
- out(cmd, { ok: false, error: r.error });
484
- return;
485
- }
486
- out(cmd, { ok: true, wrap: r.blob.wrap, addresses: r.addresses });
487
- });
488
- cmd.command('paper')
489
- .description('Print the recovery sheet — 24 numbered words plus the public addresses. Print it, then close the terminal')
490
- .option('--dir <path>', 'Project directory', '.')
491
- .option('--yes-print-to-pipe', 'Print the words even though stdout is not a terminal — a printer, on purpose. An agent shell is refused regardless')
492
- .action(async (opts) => {
493
- // Refuse BEFORE unlock: no passphrase prompt, no Touch ID, when the words could not be shown.
494
- const why = wordsStdoutRefusal(process.env, Boolean(process.stdout.isTTY), Boolean(opts.yesPrintToPipe));
495
- if (why) {
496
- out(cmd, { ok: false, error: why });
497
- process.exitCode = 1;
498
- return;
499
- }
500
- const r = await paperFor(opts.dir);
501
- if ('error' in r) {
502
- out(cmd, { ok: false, error: r.error });
503
- return;
504
- }
505
- // Straight to stdout, never through out(): a --json receipt carrying 24
506
- // words would put the whole wallet into any pipeline or CI log that
507
- // captured it.
508
- process.stdout.write(r.sheet + '\n');
509
- });
510
- cmd.command('keychain')
511
- .description('Move this wallet behind Touch ID — stores its passphrase in Apple Keychain so biometrics open it')
512
- .option('--dir <path>', 'Project directory', '.')
513
- .action(async (opts) => {
514
- if (!keychainAvailable()) {
515
- out(cmd, { ok: false, error: 'Keychain is macOS-only' });
516
- return;
517
- }
518
- const blob = readVaultFolder(opts.dir);
519
- if (!blob) {
520
- out(cmd, { ok: false, error: `no wallet at ${vaultPath(opts.dir)}` });
521
- return;
522
- }
523
- if (blob.wrap === 'keychain') {
524
- out(cmd, { ok: true, note: 'already opened by Keychain' });
525
- return;
526
- }
527
- const pass = await promptSecret('Current passphrase: ');
528
- // Prove the passphrase before storing it — storing an unverified string
529
- // would put a secret in Keychain that opens nothing.
530
- try {
531
- await openVault(blob, pass);
532
- }
533
- catch {
534
- out(cmd, { ok: false, error: 'wrong passphrase — nothing was stored' });
535
- return;
536
- }
537
- const k = keychainStore(String(blob.authPub ?? ''), pass);
538
- out(cmd, k.ok ? { ok: true, note: 'Touch ID now opens this wallet' } : { ok: false, error: k.error });
539
- });
540
- cmd.command('secure')
541
- .description("Put this wallet behind the Secure Enclave: its passphrase is sealed to a chip key that only the CURRENT fingerprint opens, so no process can sign without Touch ID. wallet.json is not rewritten. Then --drop-keychain, after one Touch ID open proves it, deletes the Keychain copy")
542
- .option('--dir <path>', 'Project directory', '.')
543
- .option('--drop-keychain', 'Open once through the Secure Enclave (Touch ID), prove it opens the vault, then delete the Keychain copy')
544
- .option('--access <rule>', 'age-plugin-se access control', 'current-biometry')
545
- .action(async (opts) => {
546
- const t0 = Date.now();
547
- const blob = readVaultFolder(opts.dir);
548
- if (!blob) {
549
- out(cmd, { ok: false, error: `no wallet at ${vaultPath(opts.dir)}` });
550
- return;
551
- }
552
- if (blob.wrap !== 'keychain') {
553
- out(cmd, { ok: false, error: 'not_a_keychain_wallet', detail: 'only a Keychain-wrapped wallet moves to the Secure Enclave' });
554
- return;
555
- }
556
- const authPub = String(blob.authPub ?? '');
557
- const sealed = seSealPath(opts.dir), identity = seIdentityPath(opts.dir);
558
- if (!existsSync(sealed)) {
559
- const k = keychainRead(authPub);
560
- if (!k.ok || !k.value) {
561
- out(cmd, { ok: false, error: 'keychain_unreadable', detail: k.ok ? 'empty' : k.error });
562
- return;
563
- }
564
- // Prove the Keychain copy opens THIS vault before sealing it anywhere.
565
- try {
566
- await openVault(blob, k.value);
567
- }
568
- catch {
569
- out(cmd, { ok: false, error: 'keychain_copy_does_not_open_vault' });
570
- return;
571
- }
572
- const made = keygen(identity, opts.access);
573
- if (made !== true) {
574
- out(cmd, { ok: false, error: typeof made === 'string' ? made : 'se_keygen_failed' });
575
- return;
576
- }
577
- chmodSync(identity, 0o600);
578
- const lock = recipientOf(identity);
579
- if (!lock) {
580
- rmSync(identity, { force: true });
581
- out(cmd, { ok: false, error: 'se_lock_unreadable' });
582
- return;
583
- }
584
- try {
585
- writeFileSync(sealed, sealWithAge(new TextEncoder().encode(k.value), [lock]), { mode: 0o600 });
586
- }
587
- catch {
588
- rmSync(identity, { force: true });
589
- out(cmd, { ok: false, error: 'se_seal_failed' });
590
- return;
591
- }
592
- if (!opts.dropKeychain) {
593
- out(cmd, { ok: true, sealed: true, lock, access: opts.access, keychain: 'kept until proven', next: `${cliPrefix()} wallet secure --dir ${opts.dir} --drop-keychain (Touch ID once, then the Keychain copy is deleted)`, ms: Date.now() - t0 });
594
- return;
595
- }
596
- }
597
- if (!opts.dropKeychain) {
598
- out(cmd, { ok: true, sealed: true, note: 'already behind the Secure Enclave', next: `${cliPrefix()} wallet secure --dir ${opts.dir} --drop-keychain` });
599
- return;
600
- }
601
- // The proof: open through the chip (this is where Touch ID asks), and the result must open the vault.
602
- let pass;
603
- try {
604
- pass = openSeDefault(sealed, identity);
605
- }
606
- catch {
607
- out(cmd, { ok: false, error: 'touch_id_not_given', detail: 'the Secure Enclave did not open — the Keychain copy is KEPT, nothing was deleted' });
608
- return;
609
- }
610
- try {
611
- await openVault(blob, pass);
612
- }
613
- catch {
614
- out(cmd, { ok: false, error: 'se_copy_does_not_open_vault', detail: 'the Keychain copy is KEPT' });
615
- return;
616
- }
617
- const d = keychainDelete(authPub);
618
- if (!d.ok) {
619
- out(cmd, { ok: false, error: 'keychain_delete_failed', detail: d.error });
620
- return;
621
- }
622
- const after = keychainRead(authPub);
623
- out(cmd, { ok: !after.ok || !after.value, provedWithTouchId: true, keychainCopy: after.ok && after.value ? 'STILL PRESENT' : 'deleted', ms: Date.now() - t0 });
624
- });
625
- // The browser's /w/restore "Key file" door opens a vault sealed with a TYPED
626
- // passphrase — it cannot read this machine's Keychain. This writes that copy:
627
- // the same 24 words, the same derivation, a passphrase the person types twice.
628
- // Nothing secret reaches stdout; the file is useless without the passphrase.
629
- cmd.command('file')
630
- .description('Write a browser copy of this wallet — the same key re-sealed with a passphrase you type, for the Key file door on /w/restore (drag and drop). Prints only the path and the addresses')
631
- .option('--dir <path>', 'Project directory', '.')
632
- .option('--out <path>', 'Where to write it', '')
633
- .action(async (opts) => {
634
- if (!process.stdin.isTTY) {
635
- out(cmd, { ok: false, error: 'a passphrase is typed at a terminal, never piped — run this yourself' });
636
- process.exitCode = 1;
637
- return;
638
- }
639
- const agentHere = agentType(process.env);
640
- if (agentHere) {
641
- out(cmd, { ok: false, error: `refusing: this shell is driven by ${agentHere}. Run it yourself in a terminal no agent drives` });
642
- process.exitCode = 1;
643
- return;
644
- }
645
- const r = await unlock(opts.dir);
646
- if ('error' in r) {
647
- out(cmd, { ok: false, error: r.error });
648
- return;
649
- }
650
- const p1 = await promptSecret('Passphrase for the browser copy (12+ characters): ');
651
- if (p1.length < 12) {
652
- out(cmd, { ok: false, error: 'too short — nothing written' });
653
- return;
654
- }
655
- const p2 = await promptSecret('Again: ');
656
- if (p1 !== p2) {
657
- out(cmd, { ok: false, error: 'they differ — nothing written' });
658
- return;
659
- }
660
- const blob = await sealVault(r.mnemonic, p1, { wrap: 'passphrase', derivation: r.blob.derivation });
661
- const target = opts.out || `${opts.dir.replace(/\/$/, '')}/wallet-file.json`;
662
- writeFileSync(target, JSON.stringify(blob, null, 1) + '\n');
663
- chmodSync(target, 0o600);
664
- out(cmd, { ok: true, out: target, addresses: r.addresses, next: 'drop it on /w/restore → Key file, type the passphrase; delete the copy once the browser holds the key' });
665
- });
666
- // One chain's private key, to the CLIPBOARD and nowhere else — for MetaMask,
667
- // Phantom, Slush, Sparrow. Never stdout: a terminal scrollback, a CI log or an
668
- // agent transcript would keep it. The key is derived on demand and dropped.
669
- cmd.command('key')
670
- .description('Copy one chain\'s private key to the clipboard for another wallet app (MetaMask, Phantom, Slush, Sparrow). Clipboard only — it is never printed. Prints the address it belongs to')
671
- .option('--dir <path>', 'Project directory', '.')
672
- .option('--chain <chain>', 'evm | sui | sol | btc | asi', 'evm')
673
- .option('--clipboard', 'Required: the only destination this command has')
674
- .action(async (opts) => {
675
- if (!opts.clipboard) {
676
- out(cmd, { ok: false, error: 'add --clipboard — the key goes to the clipboard, never to the screen' });
677
- process.exitCode = 1;
678
- return;
679
- }
680
- // The same gate as `paper`, BEFORE unlock: a shell an agent drives must not
681
- // move a private key anywhere — a clipboard is one paste from a transcript.
682
- // And a terminal, so the hand on the keyboard is a person's.
683
- const agent = agentType(process.env);
684
- if (agent) {
685
- out(cmd, { ok: false, error: `refusing: this shell is driven by ${agent}. Run it yourself in a terminal no agent drives` });
686
- process.exitCode = 1;
687
- return;
688
- }
689
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
690
- out(cmd, { ok: false, error: 'refusing: not a terminal (a pipe, a file or a log)' });
691
- process.exitCode = 1;
692
- return;
693
- }
694
- const want = opts.chain.toLowerCase();
695
- const r = await unlock(opts.dir);
696
- if ('error' in r) {
697
- out(cmd, { ok: false, error: r.error });
698
- return;
699
- }
700
- const k = r.keys.find((x) => String(x.chain).toLowerCase() === want || (want === 'evm' && ['eth', 'ethereum'].includes(String(x.chain).toLowerCase())) || (want === 'sol' && String(x.chain).toLowerCase() === 'solana'));
701
- if (!k) {
702
- out(cmd, { ok: false, error: `no ${want} key in this wallet` });
703
- return;
704
- }
705
- const { spawnSync, spawn } = await import('node:child_process');
706
- // Fixed system paths only — never a PATH or cwd lookup, which a project-local
707
- // `pbcopy` could shadow and read the key.
708
- const copier = process.platform === 'darwin' ? ['/usr/bin/pbcopy']
709
- : process.platform === 'win32' ? [`${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\clip.exe`]
710
- : existsSync('/usr/bin/wl-copy') ? ['/usr/bin/wl-copy'] : ['/usr/bin/xclip', '-selection', 'clipboard'];
711
- if (!existsSync(copier[0])) {
712
- out(cmd, { ok: false, error: `no clipboard tool at ${copier[0]} — nothing was printed` });
713
- return;
714
- }
715
- const p = spawnSync(copier[0], copier.slice(1), { input: k.privateKeyHex.replace(/^0x/, '') });
716
- if (p.status !== 0) {
717
- out(cmd, { ok: false, error: `clipboard tool ${copier[0]} failed — nothing was printed` });
718
- return;
719
- }
720
- // Clear it after the paste window: the key must not sit on the clipboard.
721
- // --clear-after defaults to 60 s; the clear is a second spawn of the same tool.
722
- const seconds = 60;
723
- const sweeper = spawn(process.execPath, ['-e', `setTimeout(()=>{require('child_process').spawnSync(${JSON.stringify(copier[0])},${JSON.stringify(copier.slice(1))},{input:'cleared'})},${seconds * 1000})`], { detached: true, stdio: 'ignore' });
724
- sweeper.unref();
725
- out(cmd, { ok: true, chain: want, address: k.address, note: `private key on the clipboard for ${seconds} s — paste it into the wallet app now; it clears itself after` });
726
- });
727
- return cmd;
728
- }
729
- /**
730
- * Register an AGENT's locally generated addresses: fetch a fresh wallet:challenge,
731
- * sign one statement per address with the local keys, send addresses + proofs.
732
- * The server refuses an agent address without this (`address_proof_required`).
733
- *
734
- * The private keys are read here and go into `proveAddresses` only; the request
735
- * body is built from its `{ addresses, proofs }` — public bytes — and nothing else.
736
- */
737
- export async function registerAgentWallet(opts) {
738
- const issued = okWrap(await ask(opts.base, opts.key, 'wallet:challenge', { workspace: opts.workspace, actor: opts.actor }));
739
- if (!issued.ok || typeof issued.challenge !== 'string')
740
- return { ok: false, error: issued.error ?? 'no challenge issued' };
741
- const { addresses, proofs } = proveAddresses(opts.keys, {
742
- challenge: issued.challenge, workspace: opts.workspace, actor: opts.actor,
743
- });
744
- if (Object.keys(addresses).length === 0)
745
- return { ok: false, error: 'no signable keys — expected a `keys` array of { chain, address, privateKeyHex }' };
746
- return okWrap(await ask(opts.base, opts.key, 'wallet:create', {
747
- workspace: opts.workspace, actor: opts.actor, kind: 'agent', addresses, challenge: issued.challenge, proofs,
748
- }));
749
- }
750
- /**
751
- * Register the SEALED wallet in `dir` — the vault `oneie init` and `wallet new`
752
- * write — by the same challenge → sign → register flow. Opens it the way
753
- * `wallet open` does (Keychain or the typed passphrase), so a sealed agent wallet
754
- * whose first registration failed can be retried without ever being written out
755
- * in the clear. The words and keys stay in this process.
756
- */
757
- export async function registerSealedWallet(opts) {
758
- const opened = await unlock(opts.dir, opts.io);
759
- if ('error' in opened)
760
- return { ok: false, error: opened.error };
761
- if (opts.confirmAddresses && !(await opts.confirmAddresses(opened.addresses)))
762
- return { ok: false, error: 'cancelled' };
763
- return registerAgentWallet({ base: opts.base, key: opts.key, workspace: opts.workspace, actor: opts.actor, keys: opened.keys });
764
- }
765
- /** The `keys` array of a keygen file, or [] — read for SIGNING only, never sent. */
766
- export function signingKeys(source) {
767
- const keys = (source && typeof source === 'object' ? source['keys'] : undefined);
768
- return (Array.isArray(keys) ? keys : []).filter((k) => !!k && typeof k.chain === 'string' && typeof k.address === 'string' && typeof k.privateKeyHex === 'string');
769
- }
770
- // Chain-name spellings a keygen output may use -> the five columns wallet:create
771
- // declares. `eth`/`sol` are the SDK's WalletChain spellings; `evm`/`solana` are the
772
- // server's. Must cover every chain proveAddresses signs, or the confirm screen
773
- // shows fewer addresses than the agent registration sends.
774
- const REGISTER_CHAINS = {
775
- sui: 'sui', evm: 'evm', eth: 'evm', ethereum: 'evm',
776
- sol: 'solana', solana: 'solana', btc: 'btc', bitcoin: 'btc',
777
- asi: 'asi', fetch: 'asi',
778
- };
779
- /**
780
- * Reduce ANY keygen-shaped object to public receiving addresses. This is a
781
- * whitelist build, never a spread or a delete-list: the returned object is
782
- * constructed field-by-field from four known chain keys whose values must be
783
- * strings, so a `privateKey`, `secretKey`, `mnemonic` or any other field on the
784
- * input has no route into the value this command transmits. The custody
785
- * invariant here is structural, not a policy the caller has to remember.
786
- */
787
- export function addressesOnly(source) {
788
- const addresses = {};
789
- const put = (rawChain, rawAddress) => {
790
- const chain = REGISTER_CHAINS[String(rawChain).toLowerCase()];
791
- if (!chain || typeof rawAddress !== 'string' || !rawAddress)
792
- return;
793
- addresses[chain] = rawAddress;
794
- };
795
- const src = (source && typeof source === 'object' ? source : {});
796
- const nested = (src['addresses'] && typeof src['addresses'] === 'object' ? src['addresses'] : {});
797
- for (const [chain, value] of Object.entries(src))
798
- put(chain, value);
799
- for (const [chain, value] of Object.entries(nested))
800
- put(chain, value);
801
- for (const k of (Array.isArray(src['keys']) ? src['keys'] : [])) {
802
- put(k?.['chain'], k?.['address']);
803
- }
804
- return addresses;
805
- }
806
- // Ask the operator on the terminal. Used only for the permanent, first-write-wins
807
- // address registration — every other verb is non-destructive.
808
- async function confirm(prompt) {
809
- const rl = createInterface({ input: process.stdin, output: process.stderr });
810
- try {
811
- const answer = await new Promise((resolve) => rl.question(prompt, resolve));
812
- return /^y(es)?$/i.test(answer.trim());
813
- }
814
- finally {
815
- rl.close();
816
- }
817
- }
818
- // Read the recovery mnemonic for `keygen --recover`: ONE_WALLET_MNEMONIC env first
819
- // (scriptable), else stdin (fd 0). Never a CLI arg — keeps the phrase out of the
820
- // process table / shell history.
821
- function readMnemonic() {
822
- const fromEnv = process.env.ONE_WALLET_MNEMONIC?.trim();
823
- if (fromEnv)
824
- return fromEnv;
825
- try {
826
- return readFileSync(0, 'utf8').trim();
827
- }
828
- catch {
829
- throw new Error('--recover needs a mnemonic — set ONE_WALLET_MNEMONIC or pipe the phrase on stdin');
830
- }
831
- }
832
- // Write key material to a plaintext file at mode 0600, and ONLY when the operator
833
- // explicitly accepted the risk. chmod after write in case umask stripped bits at
834
- // create time. Exported for the demo gate.
835
- export function writeKeysFile(filePath, contents, accepted) {
836
- if (!accepted) {
837
- throw new Error('refusing to write plaintext key material to disk — pass --yes-i-accept-plaintext-file to override');
838
- }
839
- writeFileSync(filePath, contents, { mode: 0o600 });
840
- chmodSync(filePath, 0o600);
841
- }
842
- function out(cmd, data) {
843
- const isJson = cmd.parent?.opts().json;
844
- if (isJson) {
845
- process.stdout.write(JSON.stringify(data) + '\n');
846
- }
847
- else if (data.ok) {
848
- const pairs = Object.entries(data)
849
- .filter(([k]) => k !== 'ok')
850
- .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
851
- .join(' ');
852
- console.log('✓', pairs);
853
- }
854
- else {
855
- const detail = data.error ?? data.errors ?? data.issues ?? data;
856
- console.error('✗', typeof detail === 'string' ? detail : JSON.stringify(detail));
857
- }
858
- }
859
- /** Read a secret from the TTY with echo off. Never argv (world-readable in ps), never env. */
860
- export async function promptSecret(prompt) {
861
- if (!process.stdin.isTTY)
862
- throw new Error('a passphrase must be typed at a terminal — refusing to read one from a pipe');
863
- const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
864
- const stdout = process.stdout;
865
- const orig = stdout.write.bind(stdout);
866
- process.stdout.write(prompt);
867
- stdout.write = () => true;
868
- try {
869
- return await new Promise((resolve) => rl.question('', (a) => { resolve(a); }));
870
- }
871
- finally {
872
- ;
873
- stdout.write = orig;
874
- rl.close();
875
- orig('\n');
876
- }
877
- }
878
- /** The sheet `wallet paper` prints — unlock, then lay out what restore needs. */
879
- export async function paperFor(dir, io = terminalIO(), cli = cliPrefix()) {
880
- const r = await unlock(dir, io);
881
- if ('error' in r)
882
- return { error: r.error };
883
- // The vault's OWN marker, read the way unlock derived the addresses above — an
884
- // absent marker is v1 — so the sheet names the derivation those addresses are.
885
- return { sheet: paperSheet(r.mnemonic, r.addresses, { derivation: readDerivation(r.blob.derivation), cli }) };
886
- }
887
- const openSeDefault = (sealedPath, identityPath) => new TextDecoder().decode(openWithAge(new Uint8Array(readFileSync(sealedPath)), identityPath));
888
- const terminalIO = () => ({
889
- interactive: Boolean(process.stdin.isTTY), readPassphrase: promptSecret, readKeychain: keychainRead, openSe: openSeDefault,
890
- });
891
- /**
892
- * Open the folder's vault, asking Keychain or the human depending on how it was
893
- * SEALED. `wrap` is what makes this possible: without it a keychain vault is
894
- * indistinguishable from a passphrase one and the only way to find out is to
895
- * prompt for a passphrase that was never set.
896
- *
897
- * A passphrase vault with no terminal has no passphrase source — the passphrase
898
- * is never read from argv, env or a pipe — so it is refused BY NAME, the same
899
- * name `oneie init` refuses with, rather than surfacing promptSecret's throw.
900
- */
901
- export async function unlock(dir, io = terminalIO()) {
902
- const raw = readVaultFolder(dir);
903
- if (!raw)
904
- return { error: `no wallet at ${vaultPath(dir)} — run \`${cliPrefix()} wallet new\`` };
905
- const blob = raw;
906
- let passphrase;
907
- if (existsSync(seSealPath(dir))) {
908
- // Sealed to the Secure Enclave (`wallet secure`): the chip opens it with the current
909
- // finger, or nothing does. Keychain is never consulted, even if a copy is still there.
910
- // The moment a person meets their key. Said on the terminal only (stderr, a TTY), never in --json.
911
- const say = (line) => { if (process.stderr.isTTY)
912
- process.stderr.write(line + '\n'); };
913
- say('\n ◉ Touch ID — your finger is the key. It never leaves this Mac.');
914
- try {
915
- passphrase = (io.openSe ?? openSeDefault)(seSealPath(dir), seIdentityPath(dir));
916
- say(' ✓ That was you. Opened, and signing now.\n');
917
- }
918
- catch {
919
- say(' · Not opened — nothing was signed, nothing moved. Run it again when you are ready.\n');
920
- return { error: 'touch_id_required: this wallet opens only with Touch ID on this Mac, and the Secure Enclave did not open it (no finger, cancelled, or a fingerprint changed). Recover from the 24 words if this Mac is gone' };
921
- }
922
- }
923
- else if (blob.wrap === 'keychain') {
924
- const k = io.readKeychain(String(blob.authPub ?? ''));
925
- if (!k.ok || !k.value)
926
- return { error: k.ok ? 'Keychain returned nothing' : String(k.error) };
927
- passphrase = k.value;
928
- }
929
- else {
930
- if (!io.interactive) {
931
- return { error: `wallet_passphrase_unavailable: the wallet at ${vaultPath(dir)} is sealed with a passphrase typed at a terminal, and stdin is not one. Run this at a terminal, or move the wallet behind Touch ID with \`${cliPrefix()} wallet keychain\`` };
932
- }
933
- passphrase = await io.readPassphrase('Passphrase: ');
934
- }
935
- let mnemonic;
936
- try {
937
- mnemonic = await openVault(blob, passphrase);
938
- }
939
- catch (e) {
940
- return { error: e.message };
941
- }
942
- const wallet = await openedWallet(blob, mnemonic);
943
- return { blob, mnemonic, addresses: Object.fromEntries(wallet.keys.map((k) => [k.chain, k.address])), keys: wallet.keys };
944
- }
945
- /** "5000" → 5000; anything that is not a whole number in 0..10M → null (the server checks again). */
946
- export function parseCredits(raw) {
947
- if (!/^\d{1,8}$/.test(raw.trim()))
948
- return null;
949
- const n = Number(raw.trim());
950
- return n <= 10_000_000 ? n : null;
951
- }
952
- /** One wallet:get row reduced to what a person reads: who, the tags, the first address, the limit, the sweep. */
953
- export function walletLine(w) {
954
- const address = ['sui_address', 'evm_address', 'solana_address', 'btc_address', 'asi_address']
955
- .map((k) => w[k]).find((v) => typeof v === 'string' && v.length > 0) ?? null;
956
- return {
957
- actor: String(w.actor ?? ''),
958
- tags: Array.isArray(w.tags) ? w.tags.map(String) : [],
959
- address,
960
- limit: w.limit ?? null,
961
- sweep: w.sweep ?? null,
962
- };
963
- }
964
- export function formatWalletLine(r) {
965
- const parts = [r.actor.padEnd(24), `[${r.tags.join(' ')}]`];
966
- if (r.limit)
967
- parts.push(r.limit.paused ? 'paused' : `limit ${r.limit.spentCredits}/${r.limit.monthlyCredits} credits`);
968
- if (r.sweep)
969
- parts.push(`sweeps ${r.sweep.chain} above ${r.sweep.thresholdUnits} keeping ${r.sweep.floatUnits}`);
970
- if (r.address)
971
- parts.push(r.address);
972
- return parts.join(' ');
973
- }