@metamask-previews/wallet-cli 0.0.0-preview-8bfa290fb → 0.0.0-preview-e8a256c39

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 (264) hide show
  1. package/CHANGELOG.md +8 -4
  2. package/dist/commands/daemon/{call.d.mts → call.d.ts} +2 -2
  3. package/dist/commands/daemon/call.d.ts.map +1 -0
  4. package/dist/commands/daemon/{call.mjs → call.js} +30 -31
  5. package/dist/commands/daemon/call.js.map +1 -0
  6. package/dist/commands/daemon/{list.d.cts → list.d.ts} +2 -2
  7. package/dist/commands/daemon/list.d.ts.map +1 -0
  8. package/dist/commands/daemon/{list.mjs → list.js} +9 -10
  9. package/dist/commands/daemon/list.js.map +1 -0
  10. package/dist/commands/daemon/{purge.d.cts → purge.d.ts} +2 -2
  11. package/dist/commands/daemon/purge.d.ts.map +1 -0
  12. package/dist/commands/daemon/{purge.mjs → purge.js} +19 -20
  13. package/dist/commands/daemon/purge.js.map +1 -0
  14. package/dist/commands/daemon/{start.d.cts → start.d.ts} +2 -2
  15. package/dist/commands/daemon/start.d.ts.map +1 -0
  16. package/dist/commands/daemon/start.js +49 -0
  17. package/dist/commands/daemon/{start.cjs.map → start.js.map} +1 -1
  18. package/dist/commands/daemon/{status.d.cts → status.d.ts} +2 -2
  19. package/dist/commands/daemon/status.d.ts.map +1 -0
  20. package/dist/commands/daemon/{status.mjs → status.js} +10 -11
  21. package/dist/commands/daemon/status.js.map +1 -0
  22. package/dist/commands/daemon/{stop.d.cts → stop.d.ts} +2 -2
  23. package/dist/commands/daemon/stop.d.ts.map +1 -0
  24. package/dist/commands/daemon/{stop.mjs → stop.js} +9 -10
  25. package/dist/commands/daemon/stop.js.map +1 -0
  26. package/dist/commands/wallet/{send.d.cts → send.d.ts} +3 -3
  27. package/dist/commands/wallet/send.d.ts.map +1 -0
  28. package/dist/commands/wallet/{send.mjs → send.js} +111 -123
  29. package/dist/commands/wallet/send.js.map +1 -0
  30. package/dist/commands/wallet/{unlock.d.cts → unlock.d.ts} +2 -2
  31. package/dist/commands/wallet/unlock.d.ts.map +1 -0
  32. package/dist/commands/wallet/{unlock.mjs → unlock.js} +29 -30
  33. package/dist/commands/wallet/unlock.js.map +1 -0
  34. package/dist/daemon/{auto-approval.d.mts → auto-approval.d.ts} +3 -3
  35. package/dist/daemon/auto-approval.d.ts.map +1 -0
  36. package/dist/daemon/{auto-approval.mjs → auto-approval.js} +1 -1
  37. package/dist/daemon/auto-approval.js.map +1 -0
  38. package/dist/daemon/{daemon-client.d.mts → daemon-client.d.ts} +2 -2
  39. package/dist/daemon/daemon-client.d.ts.map +1 -0
  40. package/dist/daemon/{daemon-client.mjs → daemon-client.js} +8 -8
  41. package/dist/daemon/daemon-client.js.map +1 -0
  42. package/dist/daemon/daemon-entry.d.ts +2 -0
  43. package/dist/daemon/daemon-entry.d.ts.map +1 -0
  44. package/dist/daemon/{daemon-entry.mjs → daemon-entry.js} +12 -12
  45. package/dist/daemon/daemon-entry.js.map +1 -0
  46. package/dist/daemon/{daemon-spawn.d.mts → daemon-spawn.d.ts} +2 -2
  47. package/dist/daemon/daemon-spawn.d.ts.map +1 -0
  48. package/dist/daemon/{daemon-spawn.mjs → daemon-spawn.js} +7 -7
  49. package/dist/daemon/daemon-spawn.js.map +1 -0
  50. package/dist/daemon/{data-dir.d.cts → data-dir.d.ts} +1 -1
  51. package/dist/daemon/data-dir.d.ts.map +1 -0
  52. package/dist/daemon/{data-dir.mjs → data-dir.js} +3 -3
  53. package/dist/daemon/data-dir.js.map +1 -0
  54. package/dist/daemon/{paths.d.mts → paths.d.ts} +2 -2
  55. package/dist/daemon/paths.d.ts.map +1 -0
  56. package/dist/daemon/{paths.mjs → paths.js} +2 -2
  57. package/dist/daemon/paths.js.map +1 -0
  58. package/dist/daemon/{prompts.d.cts → prompts.d.ts} +1 -1
  59. package/dist/daemon/prompts.d.ts.map +1 -0
  60. package/dist/daemon/{prompts.mjs → prompts.js} +4 -4
  61. package/dist/daemon/prompts.js.map +1 -0
  62. package/dist/daemon/{rpc-socket-server.d.cts → rpc-socket-server.d.ts} +2 -2
  63. package/dist/daemon/rpc-socket-server.d.ts.map +1 -0
  64. package/dist/daemon/{rpc-socket-server.mjs → rpc-socket-server.js} +8 -8
  65. package/dist/daemon/rpc-socket-server.js.map +1 -0
  66. package/dist/daemon/{secrets.d.cts → secrets.d.ts} +1 -1
  67. package/dist/daemon/secrets.d.ts.map +1 -0
  68. package/dist/daemon/{secrets.mjs → secrets.js} +11 -23
  69. package/dist/daemon/secrets.js.map +1 -0
  70. package/dist/daemon/{send-transaction.d.cts → send-transaction.d.ts} +9 -9
  71. package/dist/daemon/send-transaction.d.ts.map +1 -0
  72. package/dist/daemon/{send-transaction.mjs → send-transaction.js} +3 -3
  73. package/dist/daemon/send-transaction.js.map +1 -0
  74. package/dist/daemon/{socket-line.d.cts → socket-line.d.ts} +2 -5
  75. package/dist/daemon/socket-line.d.ts.map +1 -0
  76. package/dist/daemon/{socket-line.mjs → socket-line.js} +1 -1
  77. package/dist/daemon/socket-line.js.map +1 -0
  78. package/dist/daemon/{stop-daemon.d.cts → stop-daemon.d.ts} +1 -1
  79. package/dist/daemon/stop-daemon.d.ts.map +1 -0
  80. package/dist/daemon/{stop-daemon.mjs → stop-daemon.js} +7 -7
  81. package/dist/daemon/stop-daemon.js.map +1 -0
  82. package/dist/daemon/{types.d.cts → types.d.ts} +4 -4
  83. package/dist/daemon/types.d.ts.map +1 -0
  84. package/dist/daemon/{types.mjs → types.js} +1 -1
  85. package/dist/daemon/types.js.map +1 -0
  86. package/dist/daemon/{utils.d.cts → utils.d.ts} +2 -3
  87. package/dist/daemon/utils.d.ts.map +1 -0
  88. package/dist/daemon/{utils.mjs → utils.js} +3 -3
  89. package/dist/daemon/utils.js.map +1 -0
  90. package/dist/daemon/{wallet-factory.d.cts → wallet-factory.d.ts} +4 -4
  91. package/dist/daemon/wallet-factory.d.ts.map +1 -0
  92. package/dist/daemon/{wallet-factory.mjs → wallet-factory.js} +12 -12
  93. package/dist/daemon/wallet-factory.js.map +1 -0
  94. package/dist/persistence/{KeyValueStore.d.cts → KeyValueStore.d.ts} +2 -2
  95. package/dist/persistence/KeyValueStore.d.ts.map +1 -0
  96. package/dist/persistence/KeyValueStore.js +59 -0
  97. package/dist/persistence/KeyValueStore.js.map +1 -0
  98. package/dist/persistence/{persistence.d.cts → persistence.d.ts} +5 -5
  99. package/dist/persistence/persistence.d.ts.map +1 -0
  100. package/dist/persistence/{persistence.mjs → persistence.js} +2 -2
  101. package/dist/persistence/persistence.js.map +1 -0
  102. package/dist/test/{run-command.d.cts → run-command.d.ts} +4 -4
  103. package/dist/test/run-command.d.ts.map +1 -0
  104. package/dist/test/{run-command.mjs → run-command.js} +3 -3
  105. package/dist/test/run-command.js.map +1 -0
  106. package/package.json +19 -15
  107. package/dist/commands/daemon/call.cjs +0 -79
  108. package/dist/commands/daemon/call.cjs.map +0 -1
  109. package/dist/commands/daemon/call.d.cts +0 -14
  110. package/dist/commands/daemon/call.d.cts.map +0 -1
  111. package/dist/commands/daemon/call.d.mts.map +0 -1
  112. package/dist/commands/daemon/call.mjs.map +0 -1
  113. package/dist/commands/daemon/list.cjs +0 -48
  114. package/dist/commands/daemon/list.cjs.map +0 -1
  115. package/dist/commands/daemon/list.d.cts.map +0 -1
  116. package/dist/commands/daemon/list.d.mts +0 -7
  117. package/dist/commands/daemon/list.d.mts.map +0 -1
  118. package/dist/commands/daemon/list.mjs.map +0 -1
  119. package/dist/commands/daemon/purge.cjs +0 -58
  120. package/dist/commands/daemon/purge.cjs.map +0 -1
  121. package/dist/commands/daemon/purge.d.cts.map +0 -1
  122. package/dist/commands/daemon/purge.d.mts +0 -10
  123. package/dist/commands/daemon/purge.d.mts.map +0 -1
  124. package/dist/commands/daemon/purge.mjs.map +0 -1
  125. package/dist/commands/daemon/start.cjs +0 -52
  126. package/dist/commands/daemon/start.d.cts.map +0 -1
  127. package/dist/commands/daemon/start.d.mts +0 -12
  128. package/dist/commands/daemon/start.d.mts.map +0 -1
  129. package/dist/commands/daemon/start.mjs +0 -50
  130. package/dist/commands/daemon/start.mjs.map +0 -1
  131. package/dist/commands/daemon/status.cjs +0 -59
  132. package/dist/commands/daemon/status.cjs.map +0 -1
  133. package/dist/commands/daemon/status.d.cts.map +0 -1
  134. package/dist/commands/daemon/status.d.mts +0 -7
  135. package/dist/commands/daemon/status.d.mts.map +0 -1
  136. package/dist/commands/daemon/status.mjs.map +0 -1
  137. package/dist/commands/daemon/stop.cjs +0 -26
  138. package/dist/commands/daemon/stop.cjs.map +0 -1
  139. package/dist/commands/daemon/stop.d.cts.map +0 -1
  140. package/dist/commands/daemon/stop.d.mts +0 -7
  141. package/dist/commands/daemon/stop.d.mts.map +0 -1
  142. package/dist/commands/daemon/stop.mjs.map +0 -1
  143. package/dist/commands/wallet/send.cjs +0 -332
  144. package/dist/commands/wallet/send.cjs.map +0 -1
  145. package/dist/commands/wallet/send.d.cts.map +0 -1
  146. package/dist/commands/wallet/send.d.mts +0 -42
  147. package/dist/commands/wallet/send.d.mts.map +0 -1
  148. package/dist/commands/wallet/send.mjs.map +0 -1
  149. package/dist/commands/wallet/unlock.cjs +0 -75
  150. package/dist/commands/wallet/unlock.cjs.map +0 -1
  151. package/dist/commands/wallet/unlock.d.cts.map +0 -1
  152. package/dist/commands/wallet/unlock.d.mts +0 -11
  153. package/dist/commands/wallet/unlock.d.mts.map +0 -1
  154. package/dist/commands/wallet/unlock.mjs.map +0 -1
  155. package/dist/daemon/auto-approval.cjs +0 -86
  156. package/dist/daemon/auto-approval.cjs.map +0 -1
  157. package/dist/daemon/auto-approval.d.cts +0 -22
  158. package/dist/daemon/auto-approval.d.cts.map +0 -1
  159. package/dist/daemon/auto-approval.d.mts.map +0 -1
  160. package/dist/daemon/auto-approval.mjs.map +0 -1
  161. package/dist/daemon/daemon-client.cjs +0 -149
  162. package/dist/daemon/daemon-client.cjs.map +0 -1
  163. package/dist/daemon/daemon-client.d.cts +0 -84
  164. package/dist/daemon/daemon-client.d.cts.map +0 -1
  165. package/dist/daemon/daemon-client.d.mts.map +0 -1
  166. package/dist/daemon/daemon-client.mjs.map +0 -1
  167. package/dist/daemon/daemon-entry.cjs +0 -278
  168. package/dist/daemon/daemon-entry.cjs.map +0 -1
  169. package/dist/daemon/daemon-entry.d.cts +0 -2
  170. package/dist/daemon/daemon-entry.d.cts.map +0 -1
  171. package/dist/daemon/daemon-entry.d.mts +0 -2
  172. package/dist/daemon/daemon-entry.d.mts.map +0 -1
  173. package/dist/daemon/daemon-entry.mjs.map +0 -1
  174. package/dist/daemon/daemon-spawn.cjs +0 -138
  175. package/dist/daemon/daemon-spawn.cjs.map +0 -1
  176. package/dist/daemon/daemon-spawn.d.cts +0 -28
  177. package/dist/daemon/daemon-spawn.d.cts.map +0 -1
  178. package/dist/daemon/daemon-spawn.d.mts.map +0 -1
  179. package/dist/daemon/daemon-spawn.mjs.map +0 -1
  180. package/dist/daemon/data-dir.cjs +0 -23
  181. package/dist/daemon/data-dir.cjs.map +0 -1
  182. package/dist/daemon/data-dir.d.cts.map +0 -1
  183. package/dist/daemon/data-dir.d.mts +0 -14
  184. package/dist/daemon/data-dir.d.mts.map +0 -1
  185. package/dist/daemon/data-dir.mjs.map +0 -1
  186. package/dist/daemon/paths.cjs +0 -20
  187. package/dist/daemon/paths.cjs.map +0 -1
  188. package/dist/daemon/paths.d.cts +0 -9
  189. package/dist/daemon/paths.d.cts.map +0 -1
  190. package/dist/daemon/paths.d.mts.map +0 -1
  191. package/dist/daemon/paths.mjs.map +0 -1
  192. package/dist/daemon/prompts.cjs +0 -55
  193. package/dist/daemon/prompts.cjs.map +0 -1
  194. package/dist/daemon/prompts.d.cts.map +0 -1
  195. package/dist/daemon/prompts.d.mts +0 -31
  196. package/dist/daemon/prompts.d.mts.map +0 -1
  197. package/dist/daemon/prompts.mjs.map +0 -1
  198. package/dist/daemon/rpc-socket-server.cjs +0 -284
  199. package/dist/daemon/rpc-socket-server.cjs.map +0 -1
  200. package/dist/daemon/rpc-socket-server.d.cts.map +0 -1
  201. package/dist/daemon/rpc-socket-server.d.mts +0 -44
  202. package/dist/daemon/rpc-socket-server.d.mts.map +0 -1
  203. package/dist/daemon/rpc-socket-server.mjs.map +0 -1
  204. package/dist/daemon/secrets.cjs +0 -137
  205. package/dist/daemon/secrets.cjs.map +0 -1
  206. package/dist/daemon/secrets.d.cts.map +0 -1
  207. package/dist/daemon/secrets.d.mts +0 -72
  208. package/dist/daemon/secrets.d.mts.map +0 -1
  209. package/dist/daemon/secrets.mjs.map +0 -1
  210. package/dist/daemon/send-transaction.cjs +0 -147
  211. package/dist/daemon/send-transaction.cjs.map +0 -1
  212. package/dist/daemon/send-transaction.d.cts.map +0 -1
  213. package/dist/daemon/send-transaction.d.mts +0 -102
  214. package/dist/daemon/send-transaction.d.mts.map +0 -1
  215. package/dist/daemon/send-transaction.mjs.map +0 -1
  216. package/dist/daemon/socket-line.cjs +0 -93
  217. package/dist/daemon/socket-line.cjs.map +0 -1
  218. package/dist/daemon/socket-line.d.cts.map +0 -1
  219. package/dist/daemon/socket-line.d.mts +0 -21
  220. package/dist/daemon/socket-line.d.mts.map +0 -1
  221. package/dist/daemon/socket-line.mjs.map +0 -1
  222. package/dist/daemon/stop-daemon.cjs +0 -117
  223. package/dist/daemon/stop-daemon.cjs.map +0 -1
  224. package/dist/daemon/stop-daemon.d.cts.map +0 -1
  225. package/dist/daemon/stop-daemon.d.mts +0 -28
  226. package/dist/daemon/stop-daemon.d.mts.map +0 -1
  227. package/dist/daemon/stop-daemon.mjs.map +0 -1
  228. package/dist/daemon/types.cjs +0 -20
  229. package/dist/daemon/types.cjs.map +0 -1
  230. package/dist/daemon/types.d.cts.map +0 -1
  231. package/dist/daemon/types.d.mts +0 -94
  232. package/dist/daemon/types.d.mts.map +0 -1
  233. package/dist/daemon/types.mjs.map +0 -1
  234. package/dist/daemon/utils.cjs +0 -172
  235. package/dist/daemon/utils.cjs.map +0 -1
  236. package/dist/daemon/utils.d.cts.map +0 -1
  237. package/dist/daemon/utils.d.mts +0 -87
  238. package/dist/daemon/utils.d.mts.map +0 -1
  239. package/dist/daemon/utils.mjs.map +0 -1
  240. package/dist/daemon/wallet-factory.cjs +0 -341
  241. package/dist/daemon/wallet-factory.cjs.map +0 -1
  242. package/dist/daemon/wallet-factory.d.cts.map +0 -1
  243. package/dist/daemon/wallet-factory.d.mts +0 -64
  244. package/dist/daemon/wallet-factory.d.mts.map +0 -1
  245. package/dist/daemon/wallet-factory.mjs.map +0 -1
  246. package/dist/persistence/KeyValueStore.cjs +0 -79
  247. package/dist/persistence/KeyValueStore.cjs.map +0 -1
  248. package/dist/persistence/KeyValueStore.d.cts.map +0 -1
  249. package/dist/persistence/KeyValueStore.d.mts +0 -18
  250. package/dist/persistence/KeyValueStore.d.mts.map +0 -1
  251. package/dist/persistence/KeyValueStore.mjs +0 -79
  252. package/dist/persistence/KeyValueStore.mjs.map +0 -1
  253. package/dist/persistence/persistence.cjs +0 -204
  254. package/dist/persistence/persistence.cjs.map +0 -1
  255. package/dist/persistence/persistence.d.cts.map +0 -1
  256. package/dist/persistence/persistence.d.mts +0 -45
  257. package/dist/persistence/persistence.d.mts.map +0 -1
  258. package/dist/persistence/persistence.mjs.map +0 -1
  259. package/dist/test/run-command.cjs +0 -73
  260. package/dist/test/run-command.cjs.map +0 -1
  261. package/dist/test/run-command.d.cts.map +0 -1
  262. package/dist/test/run-command.d.mts +0 -27
  263. package/dist/test/run-command.d.mts.map +0 -1
  264. package/dist/test/run-command.mjs.map +0 -1
@@ -1,278 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const superstruct_1 = require("@metamask/superstruct");
4
- const promises_1 = require("node:fs/promises");
5
- const daemon_client_js_1 = require("./daemon-client.cjs");
6
- const data_dir_js_1 = require("./data-dir.cjs");
7
- const paths_js_1 = require("./paths.cjs");
8
- const rpc_socket_server_js_1 = require("./rpc-socket-server.cjs");
9
- const secrets_js_1 = require("./secrets.cjs");
10
- const send_transaction_js_1 = require("./send-transaction.cjs");
11
- const types_js_1 = require("./types.cjs");
12
- const utils_js_1 = require("./utils.cjs");
13
- const wallet_factory_js_1 = require("./wallet-factory.cjs");
14
- /**
15
- * Params struct for the `call` RPC method. `params` must be a non-empty array
16
- * whose first element is the messenger action name; remaining elements are
17
- * positional action arguments forwarded as-is to `messenger.call`.
18
- */
19
- const callParamsStruct = (0, superstruct_1.define)('CallParams', (value) => {
20
- if (!Array.isArray(value)) {
21
- return 'Expected an array';
22
- }
23
- if (value.length === 0) {
24
- return 'Expected a non-empty array';
25
- }
26
- if (typeof value[0] !== 'string') {
27
- return 'Expected the first element to be a string action name';
28
- }
29
- return true;
30
- });
31
- const startTime = Date.now();
32
- main().catch((error) => {
33
- process.stderr.write(`Daemon fatal: ${String(error)}\n`);
34
- process.exitCode = 1;
35
- });
36
- async function main() {
37
- const dataDir = process.env.MM_DAEMON_DATA_DIR;
38
- if (!dataDir) {
39
- throw new Error('MM_DAEMON_DATA_DIR environment variable is required');
40
- }
41
- const infuraProjectId = process.env.INFURA_PROJECT_ID;
42
- if (!infuraProjectId) {
43
- throw new Error('INFURA_PROJECT_ID environment variable is required');
44
- }
45
- // Password is optional: when absent, the daemon starts without unlocking
46
- // the keyring (e.g. when the user prefers to call `mm wallet unlock`
47
- // interactively rather than embed the password in their environment).
48
- // First-run startup still requires a password; wallet-factory enforces
49
- // that and surfaces a clear error.
50
- const passwordRaw = process.env.MM_WALLET_PASSWORD;
51
- const srpRaw = process.env.MM_WALLET_SRP;
52
- if (!srpRaw) {
53
- throw new Error('MM_WALLET_SRP environment variable is required');
54
- }
55
- // Scrub before validation so a throw from Password.from / Srp.from (bad
56
- // value) does not leave the raw secrets in the long-lived daemon's env.
57
- delete process.env.MM_WALLET_PASSWORD;
58
- delete process.env.MM_WALLET_SRP;
59
- const password = passwordRaw ? secrets_js_1.Password.from(passwordRaw) : undefined;
60
- const srp = secrets_js_1.Srp.from(srpRaw);
61
- await (0, data_dir_js_1.ensureOwnerOnlyDirectory)(dataDir);
62
- const { socketPath: defaultSocketPath, pidPath, logPath, dbPath, } = (0, paths_js_1.getDaemonPaths)(dataDir);
63
- const socketPath = process.env.MM_DAEMON_SOCKET_PATH ?? defaultSocketPath;
64
- const log = makeLogger(logPath);
65
- log('Starting daemon...');
66
- // Pre-flight: refuse to take over if a responsive daemon already owns this
67
- // socket. If the existing PID file is stale (or the socket is dead), clean
68
- // it up so the exclusive PID-file write below has a chance to succeed.
69
- await claimDaemonSlot(pidPath, socketPath, log);
70
- const pidFileContents = `${process.pid}\n${startTime}\n`;
71
- // Claim the slot atomically BEFORE opening the SQLite database or
72
- // constructing the Wallet. Two concurrent `daemon start` invocations can
73
- // both pass `claimDaemonSlot` (the gap between its preflight and the slot
74
- // write is racy); without this ordering, both would open `wallet.db` and
75
- // both would run first-run SRP import before one loses the wx race.
76
- try {
77
- await (0, promises_1.writeFile)(pidPath, pidFileContents, { flag: 'wx' });
78
- }
79
- catch (error) {
80
- throw error instanceof Error
81
- ? Object.assign(error, {
82
- message: `Failed to claim daemon slot at ${pidPath}: ${error.message}`,
83
- })
84
- : /* istanbul ignore next -- node:fs/promises always rejects with an Error */
85
- new Error(`Failed to claim daemon slot at ${pidPath}: ${String(error)}`);
86
- }
87
- let wallet;
88
- let dispose;
89
- let handle;
90
- try {
91
- ({ wallet, dispose } = await (0, wallet_factory_js_1.createWallet)({
92
- databasePath: dbPath,
93
- password,
94
- srp,
95
- infuraProjectId,
96
- log,
97
- }));
98
- const constructedWallet = wallet;
99
- // Arbitrary messenger dispatch is intentional: the CLI exposes the full
100
- // messenger surface over a Unix socket inside the per-user oclif data
101
- // directory. The dataDir is chmodded to 0o700 above and the socket to
102
- // 0o600 by the RPC server on bind, so only the owning user can open them,
103
- // but there is no in-process auth check beyond that filesystem-permission
104
- // barrier. The messenger is strongly typed by action name; we narrow it
105
- // once here to the RpcDispatcher shape the `call` handler needs.
106
- const dispatch = constructedWallet.messenger.call.bind(constructedWallet.messenger);
107
- const handlers = {
108
- getStatus: (0, types_js_1.defineHandler)((0, superstruct_1.literal)(null), async () => ({
109
- pid: process.pid,
110
- uptime: Math.floor((Date.now() - startTime) / 1000),
111
- })),
112
- call: (0, types_js_1.defineHandler)(callParamsStruct, async (params) => {
113
- const [action, ...args] = params;
114
- return await dispatch(action, ...args);
115
- }),
116
- // Exposes the callable surface for discovery: it grows silently as
117
- // controllers are wired, so consumers need a way to see it without a
118
- // hand-kept catalog that would rot.
119
- listActions: (0, types_js_1.defineHandler)((0, superstruct_1.literal)(null), async () => constructedWallet.messenger.getRegisteredActionTypes()),
120
- // Dedicated send handler; see `runSendTransaction` for why the generic
121
- // `call` dispatch cannot carry a broadcast result.
122
- sendTransaction: (0, types_js_1.defineHandler)(send_transaction_js_1.SendTransactionParamsStruct, async (params) => (0, send_transaction_js_1.runSendTransaction)(constructedWallet.messenger, params)),
123
- };
124
- // `startRpcSocketServer` restricts the socket to the owner (chmod 0o600)
125
- // on bind and never leaves a live server/socket behind if it rejects, so
126
- // the catch below has nothing of its own to close.
127
- handle = await (0, rpc_socket_server_js_1.startRpcSocketServer)({
128
- socketPath,
129
- handlers,
130
- onShutdown: async () => shutdown('RPC shutdown'),
131
- log,
132
- });
133
- }
134
- catch (error) {
135
- // `dispose` is undefined only when `createWallet` itself threw — it has
136
- // already torn down its own store in that case.
137
- if (dispose) {
138
- await dispose();
139
- }
140
- // Only remove the PID file if it's still ours (we may have lost the race
141
- // and the file now belongs to another daemon).
142
- await removeOwnedPidFile(pidPath, pidFileContents).catch((rmError) => {
143
- log(`Failed to remove PID file during cleanup: ${String(rmError)}`);
144
- });
145
- throw error;
146
- }
147
- // Stable non-undefined refs for the shutdown closures (TS won't narrow the
148
- // outer `let`s across closure escape).
149
- const activeHandle = handle;
150
- const activeDispose = dispose;
151
- log(`Daemon started. Socket: ${socketPath}`);
152
- let shutdownPromise;
153
- /**
154
- * Shut down the daemon idempotently. Concurrent calls coalesce.
155
- *
156
- * @param reason - A label describing why shutdown was triggered.
157
- * @returns A promise that resolves when shutdown completes.
158
- */
159
- async function shutdown(reason) {
160
- if (shutdownPromise === undefined) {
161
- log(`Shutting down (${reason})...`);
162
- shutdownPromise = (async () => {
163
- try {
164
- await activeHandle.close();
165
- }
166
- catch (closeError) {
167
- log(`handle.close() failed: ${String(closeError)}`);
168
- }
169
- try {
170
- await activeDispose();
171
- }
172
- catch (disposeError) {
173
- log(`dispose() failed during shutdown: ${String(disposeError)}`);
174
- }
175
- await Promise.all([
176
- removeOwnedPidFile(pidPath, pidFileContents).catch((rmError) => {
177
- log(`Failed to remove PID file: ${String(rmError)}`);
178
- }),
179
- (0, promises_1.rm)(socketPath, { force: true }).catch((rmError) => {
180
- log(`Failed to remove socket file: ${String(rmError)}`);
181
- }),
182
- ]);
183
- })();
184
- }
185
- return shutdownPromise;
186
- }
187
- process.on('SIGTERM', () => {
188
- /* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */
189
- shutdown('SIGTERM').catch(() => undefined);
190
- });
191
- process.on('SIGINT', () => {
192
- /* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */
193
- shutdown('SIGINT').catch(() => undefined);
194
- });
195
- }
196
- /**
197
- * Refuse to start if a responsive daemon already owns the socket. Otherwise
198
- * clear any stale PID/socket files so the exclusive PID-file write can
199
- * proceed.
200
- *
201
- * @param pidPath - The PID file path.
202
- * @param socketPath - The socket path.
203
- * @param log - Logger for diagnostic messages.
204
- */
205
- async function claimDaemonSlot(pidPath, socketPath, log) {
206
- const existingPid = await (0, utils_js_1.readPidFile)(pidPath);
207
- const ping = await (0, daemon_client_js_1.pingDaemon)(socketPath);
208
- if (ping.status === 'responsive') {
209
- const pidPart = existingPid === undefined
210
- ? '(no PID file present)'
211
- : `(pid ${existingPid})`;
212
- throw new Error(`A daemon is already running on ${socketPath} ${pidPart}`);
213
- }
214
- // Refuse to clobber when the recorded PID is still alive, regardless of
215
- // whether the socket exists. Possible scenarios:
216
- // - `unreachable`: wedged or mid-startup sibling daemon (socket present
217
- // but not responding to JSON-RPC).
218
- // - `absent`: a sibling daemon that hasn't yet bound its socket, or one
219
- // whose socket was manually removed. In either case, removing its PID
220
- // file would orphan it from `daemon stop`.
221
- if (existingPid !== undefined && (0, utils_js_1.isProcessAlive)(existingPid)) {
222
- const detail = ping.status === 'unreachable'
223
- ? `socket at ${socketPath} is unresponsive (${ping.error.message})`
224
- : `no socket at ${socketPath}, but pid is still alive`;
225
- throw new Error(`A daemon is already running (pid ${existingPid}): ${detail}. ` +
226
- `Run \`mm daemon stop\` (or \`mm daemon purge\`) before starting a new daemon.`);
227
- }
228
- if (ping.status === 'unreachable') {
229
- log(`Removing stale socket at ${socketPath} (${ping.error.message}).`);
230
- }
231
- // Always clear both files before claiming the slot. The PID file may be
232
- // corrupt (truncated, partial write from a crashed run); without this, the
233
- // exclusive `wx` write below would fail with EEXIST and the daemon could
234
- // not start until a human manually deleted the file.
235
- await Promise.all([
236
- (0, promises_1.rm)(pidPath, { force: true }),
237
- (0, promises_1.rm)(socketPath, { force: true }),
238
- ]);
239
- }
240
- /**
241
- * Remove the PID file only if it still contains our exact contents. Guards
242
- * against a racing daemon's PID file being removed by this daemon during
243
- * cleanup.
244
- *
245
- * @param pidPath - Path to the PID file.
246
- * @param expectedContents - The contents we wrote when claiming the slot.
247
- */
248
- async function removeOwnedPidFile(pidPath, expectedContents) {
249
- let actual;
250
- try {
251
- actual = await (0, promises_1.readFile)(pidPath, 'utf-8');
252
- }
253
- catch (error) {
254
- if ((0, utils_js_1.isErrorWithCode)(error, 'ENOENT')) {
255
- return;
256
- }
257
- throw error;
258
- }
259
- if (actual === expectedContents) {
260
- await (0, promises_1.rm)(pidPath, { force: true });
261
- }
262
- }
263
- /**
264
- * Create a file logger that appends timestamped lines to `logPath`, falling
265
- * back to stderr if the append fails.
266
- *
267
- * @param logPath - The log file path.
268
- * @returns A logging function.
269
- */
270
- function makeLogger(logPath) {
271
- return (message) => {
272
- const line = `[${new Date().toISOString()}] ${message}\n`;
273
- (0, promises_1.appendFile)(logPath, line).catch((error) => {
274
- process.stderr.write(`[log write failed: ${String(error)}] ${message}\n`);
275
- });
276
- };
277
- }
278
- //# sourceMappingURL=daemon-entry.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-entry.cjs","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":";;AAAA,uDAAwD;AAGxD,+CAAuE;AAEvE,0DAAgD;AAChD,gDAAyD;AACzD,0CAA4C;AAC5C,kEAA8D;AAE9D,8CAA6C;AAC7C,gEAG+B;AAC/B,0CAA2C;AAO3C,0CAA0E;AAC1E,4DAAmD;AAEnD;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,IAAA,oBAAM,EAC7B,YAAY,EACZ,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,mBAAmB,CAAC;IAC7B,CAAC;IACD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,OAAO,4BAA4B,CAAC;IACtC,CAAC;IACD,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE,CAAC;QACjC,OAAO,uDAAuD,CAAC;IACjE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC;AAEF,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAE7B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC9B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC;AAEH,KAAK,UAAU,IAAI;IACjB,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG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AI,EAAE,CAAC,CAAC;IACrC,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAS,UAAU,CAAC,OAAe;IACjC,OAAO,CAAC,OAAe,EAAQ,EAAE;QAC/B,MAAM,IAAI,GAAG,IAAI,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,KAAK,OAAO,IAAI,CAAC;QAC1D,IAAA,qBAAU,EAAC,OAAO,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACjD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,sBAAsB,MAAM,CAAC,KAAK,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC;QAC5E,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { define, literal } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport type { Wallet } from '@metamask/wallet';\nimport { appendFile, readFile, rm, writeFile } from 'node:fs/promises';\n\nimport { pingDaemon } from './daemon-client.js';\nimport { ensureOwnerOnlyDirectory } from './data-dir.js';\nimport { getDaemonPaths } from './paths.js';\nimport { startRpcSocketServer } from './rpc-socket-server.js';\nimport type { RpcSocketServerHandle } from './rpc-socket-server.js';\nimport { Password, Srp } from './secrets.js';\nimport {\n runSendTransaction,\n SendTransactionParamsStruct,\n} from './send-transaction.js';\nimport { defineHandler } from './types.js';\nimport type {\n DaemonStatusInfo,\n Logger,\n RpcDispatcher,\n RpcHandlerMap,\n} from './types.js';\nimport { isErrorWithCode, isProcessAlive, readPidFile } from './utils.js';\nimport { createWallet } from './wallet-factory.js';\n\n/**\n * Params struct for the `call` RPC method. `params` must be a non-empty array\n * whose first element is the messenger action name; remaining elements are\n * positional action arguments forwarded as-is to `messenger.call`.\n */\nconst callParamsStruct = define<[string, ...unknown[]]>(\n 'CallParams',\n (value) => {\n if (!Array.isArray(value)) {\n return 'Expected an array';\n }\n if (value.length === 0) {\n return 'Expected a non-empty array';\n }\n if (typeof value[0] !== 'string') {\n return 'Expected the first element to be a string action name';\n }\n return true;\n },\n);\n\nconst startTime = Date.now();\n\nmain().catch((error: unknown) => {\n process.stderr.write(`Daemon fatal: ${String(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const dataDir = process.env.MM_DAEMON_DATA_DIR;\n if (!dataDir) {\n throw new Error('MM_DAEMON_DATA_DIR environment variable is required');\n }\n\n const infuraProjectId = process.env.INFURA_PROJECT_ID;\n if (!infuraProjectId) {\n throw new Error('INFURA_PROJECT_ID environment variable is required');\n }\n\n // Password is optional: when absent, the daemon starts without unlocking\n // the keyring (e.g. when the user prefers to call `mm wallet unlock`\n // interactively rather than embed the password in their environment).\n // First-run startup still requires a password; wallet-factory enforces\n // that and surfaces a clear error.\n const passwordRaw = process.env.MM_WALLET_PASSWORD;\n\n const srpRaw = process.env.MM_WALLET_SRP;\n if (!srpRaw) {\n throw new Error('MM_WALLET_SRP environment variable is required');\n }\n\n // Scrub before validation so a throw from Password.from / Srp.from (bad\n // value) does not leave the raw secrets in the long-lived daemon's env.\n delete process.env.MM_WALLET_PASSWORD;\n delete process.env.MM_WALLET_SRP;\n\n const password = passwordRaw ? Password.from(passwordRaw) : undefined;\n const srp = Srp.from(srpRaw);\n\n await ensureOwnerOnlyDirectory(dataDir);\n\n const {\n socketPath: defaultSocketPath,\n pidPath,\n logPath,\n dbPath,\n } = getDaemonPaths(dataDir);\n const socketPath = process.env.MM_DAEMON_SOCKET_PATH ?? defaultSocketPath;\n\n const log = makeLogger(logPath);\n log('Starting daemon...');\n\n // Pre-flight: refuse to take over if a responsive daemon already owns this\n // socket. If the existing PID file is stale (or the socket is dead), clean\n // it up so the exclusive PID-file write below has a chance to succeed.\n await claimDaemonSlot(pidPath, socketPath, log);\n\n const pidFileContents = `${process.pid}\\n${startTime}\\n`;\n\n // Claim the slot atomically BEFORE opening the SQLite database or\n // constructing the Wallet. Two concurrent `daemon start` invocations can\n // both pass `claimDaemonSlot` (the gap between its preflight and the slot\n // write is racy); without this ordering, both would open `wallet.db` and\n // both would run first-run SRP import before one loses the wx race.\n try {\n await writeFile(pidPath, pidFileContents, { flag: 'wx' });\n } catch (error) {\n throw error instanceof Error\n ? Object.assign(error, {\n message: `Failed to claim daemon slot at ${pidPath}: ${error.message}`,\n })\n : /* istanbul ignore next -- node:fs/promises always rejects with an Error */\n new Error(\n `Failed to claim daemon slot at ${pidPath}: ${String(error)}`,\n );\n }\n\n let wallet: Wallet | undefined;\n let dispose: (() => Promise<void>) | undefined;\n let handle: RpcSocketServerHandle | undefined;\n\n try {\n ({ wallet, dispose } = await createWallet({\n databasePath: dbPath,\n password,\n srp,\n infuraProjectId,\n log,\n }));\n\n const constructedWallet = wallet;\n // Arbitrary messenger dispatch is intentional: the CLI exposes the full\n // messenger surface over a Unix socket inside the per-user oclif data\n // directory. The dataDir is chmodded to 0o700 above and the socket to\n // 0o600 by the RPC server on bind, so only the owning user can open them,\n // but there is no in-process auth check beyond that filesystem-permission\n // barrier. The messenger is strongly typed by action name; we narrow it\n // once here to the RpcDispatcher shape the `call` handler needs.\n const dispatch = constructedWallet.messenger.call.bind(\n constructedWallet.messenger,\n ) as unknown as RpcDispatcher;\n\n const handlers: RpcHandlerMap = {\n getStatus: defineHandler(\n literal(null),\n async (): Promise<DaemonStatusInfo> => ({\n pid: process.pid,\n uptime: Math.floor((Date.now() - startTime) / 1000),\n }),\n ),\n call: defineHandler(callParamsStruct, async (params) => {\n const [action, ...args] = params;\n return await dispatch(action, ...(args as Json[]));\n }),\n // Exposes the callable surface for discovery: it grows silently as\n // controllers are wired, so consumers need a way to see it without a\n // hand-kept catalog that would rot.\n listActions: defineHandler(\n literal(null),\n async (): Promise<Json> =>\n constructedWallet.messenger.getRegisteredActionTypes(),\n ),\n // Dedicated send handler; see `runSendTransaction` for why the generic\n // `call` dispatch cannot carry a broadcast result.\n sendTransaction: defineHandler(\n SendTransactionParamsStruct,\n async (params) =>\n runSendTransaction(constructedWallet.messenger, params),\n ),\n };\n\n // `startRpcSocketServer` restricts the socket to the owner (chmod 0o600)\n // on bind and never leaves a live server/socket behind if it rejects, so\n // the catch below has nothing of its own to close.\n handle = await startRpcSocketServer({\n socketPath,\n handlers,\n onShutdown: async () => shutdown('RPC shutdown'),\n log,\n });\n } catch (error) {\n // `dispose` is undefined only when `createWallet` itself threw — it has\n // already torn down its own store in that case.\n if (dispose) {\n await dispose();\n }\n // Only remove the PID file if it's still ours (we may have lost the race\n // and the file now belongs to another daemon).\n await removeOwnedPidFile(pidPath, pidFileContents).catch(\n (rmError: unknown) => {\n log(`Failed to remove PID file during cleanup: ${String(rmError)}`);\n },\n );\n throw error;\n }\n\n // Stable non-undefined refs for the shutdown closures (TS won't narrow the\n // outer `let`s across closure escape).\n const activeHandle = handle;\n const activeDispose = dispose;\n\n log(`Daemon started. Socket: ${socketPath}`);\n\n let shutdownPromise: Promise<void> | undefined;\n\n /**\n * Shut down the daemon idempotently. Concurrent calls coalesce.\n *\n * @param reason - A label describing why shutdown was triggered.\n * @returns A promise that resolves when shutdown completes.\n */\n async function shutdown(reason: string): Promise<void> {\n if (shutdownPromise === undefined) {\n log(`Shutting down (${reason})...`);\n shutdownPromise = (async (): Promise<void> => {\n try {\n await activeHandle.close();\n } catch (closeError) {\n log(`handle.close() failed: ${String(closeError)}`);\n }\n try {\n await activeDispose();\n } catch (disposeError) {\n log(`dispose() failed during shutdown: ${String(disposeError)}`);\n }\n await Promise.all([\n removeOwnedPidFile(pidPath, pidFileContents).catch(\n (rmError: unknown) => {\n log(`Failed to remove PID file: ${String(rmError)}`);\n },\n ),\n rm(socketPath, { force: true }).catch((rmError: unknown) => {\n log(`Failed to remove socket file: ${String(rmError)}`);\n }),\n ]);\n })();\n }\n return shutdownPromise;\n }\n\n process.on('SIGTERM', () => {\n /* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */\n shutdown('SIGTERM').catch(() => undefined);\n });\n process.on('SIGINT', () => {\n /* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */\n shutdown('SIGINT').catch(() => undefined);\n });\n}\n\n/**\n * Refuse to start if a responsive daemon already owns the socket. Otherwise\n * clear any stale PID/socket files so the exclusive PID-file write can\n * proceed.\n *\n * @param pidPath - The PID file path.\n * @param socketPath - The socket path.\n * @param log - Logger for diagnostic messages.\n */\nasync function claimDaemonSlot(\n pidPath: string,\n socketPath: string,\n log: Logger,\n): Promise<void> {\n const existingPid = await readPidFile(pidPath);\n const ping = await pingDaemon(socketPath);\n\n if (ping.status === 'responsive') {\n const pidPart =\n existingPid === undefined\n ? '(no PID file present)'\n : `(pid ${existingPid})`;\n throw new Error(`A daemon is already running on ${socketPath} ${pidPart}`);\n }\n\n // Refuse to clobber when the recorded PID is still alive, regardless of\n // whether the socket exists. Possible scenarios:\n // - `unreachable`: wedged or mid-startup sibling daemon (socket present\n // but not responding to JSON-RPC).\n // - `absent`: a sibling daemon that hasn't yet bound its socket, or one\n // whose socket was manually removed. In either case, removing its PID\n // file would orphan it from `daemon stop`.\n if (existingPid !== undefined && isProcessAlive(existingPid)) {\n const detail =\n ping.status === 'unreachable'\n ? `socket at ${socketPath} is unresponsive (${ping.error.message})`\n : `no socket at ${socketPath}, but pid is still alive`;\n throw new Error(\n `A daemon is already running (pid ${existingPid}): ${detail}. ` +\n `Run \\`mm daemon stop\\` (or \\`mm daemon purge\\`) before starting a new daemon.`,\n );\n }\n\n if (ping.status === 'unreachable') {\n log(`Removing stale socket at ${socketPath} (${ping.error.message}).`);\n }\n // Always clear both files before claiming the slot. The PID file may be\n // corrupt (truncated, partial write from a crashed run); without this, the\n // exclusive `wx` write below would fail with EEXIST and the daemon could\n // not start until a human manually deleted the file.\n await Promise.all([\n rm(pidPath, { force: true }),\n rm(socketPath, { force: true }),\n ]);\n}\n\n/**\n * Remove the PID file only if it still contains our exact contents. Guards\n * against a racing daemon's PID file being removed by this daemon during\n * cleanup.\n *\n * @param pidPath - Path to the PID file.\n * @param expectedContents - The contents we wrote when claiming the slot.\n */\nasync function removeOwnedPidFile(\n pidPath: string,\n expectedContents: string,\n): Promise<void> {\n let actual: string;\n try {\n actual = await readFile(pidPath, 'utf-8');\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ENOENT')) {\n return;\n }\n throw error;\n }\n if (actual === expectedContents) {\n await rm(pidPath, { force: true });\n }\n}\n\n/**\n * Create a file logger that appends timestamped lines to `logPath`, falling\n * back to stderr if the append fails.\n *\n * @param logPath - The log file path.\n * @returns A logging function.\n */\nfunction makeLogger(logPath: string): Logger {\n return (message: string): void => {\n const line = `[${new Date().toISOString()}] ${message}\\n`;\n appendFile(logPath, line).catch((error: unknown) => {\n process.stderr.write(`[log write failed: ${String(error)}] ${message}\\n`);\n });\n };\n}\n"]}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=daemon-entry.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-entry.d.cts","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=daemon-entry.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-entry.d.mts","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-entry.mjs","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,8BAA8B;AAGxD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,EAAE,EAAE,SAAS,EAAE,yBAAyB;AAEvE,OAAO,EAAE,UAAU,EAAE,4BAA2B;AAChD,OAAO,EAAE,wBAAwB,EAAE,uBAAsB;AACzD,OAAO,EAAE,cAAc,EAAE,oBAAmB;AAC5C,OAAO,EAAE,oBAAoB,EAAE,gCAA+B;AAE9D,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,sBAAqB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CAAC,CAAC;QAC5E,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { define, literal } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport type { Wallet } from '@metamask/wallet';\nimport { appendFile, readFile, rm, writeFile } from 'node:fs/promises';\n\nimport { pingDaemon } from './daemon-client.js';\nimport { ensureOwnerOnlyDirectory } from './data-dir.js';\nimport { getDaemonPaths } from './paths.js';\nimport { startRpcSocketServer } from './rpc-socket-server.js';\nimport type { RpcSocketServerHandle } from './rpc-socket-server.js';\nimport { Password, Srp } from './secrets.js';\nimport {\n runSendTransaction,\n SendTransactionParamsStruct,\n} from './send-transaction.js';\nimport { defineHandler } from './types.js';\nimport type {\n DaemonStatusInfo,\n Logger,\n RpcDispatcher,\n RpcHandlerMap,\n} from './types.js';\nimport { isErrorWithCode, isProcessAlive, readPidFile } from './utils.js';\nimport { createWallet } from './wallet-factory.js';\n\n/**\n * Params struct for the `call` RPC method. `params` must be a non-empty array\n * whose first element is the messenger action name; remaining elements are\n * positional action arguments forwarded as-is to `messenger.call`.\n */\nconst callParamsStruct = define<[string, ...unknown[]]>(\n 'CallParams',\n (value) => {\n if (!Array.isArray(value)) {\n return 'Expected an array';\n }\n if (value.length === 0) {\n return 'Expected a non-empty array';\n }\n if (typeof value[0] !== 'string') {\n return 'Expected the first element to be a string action name';\n }\n return true;\n },\n);\n\nconst startTime = Date.now();\n\nmain().catch((error: unknown) => {\n process.stderr.write(`Daemon fatal: ${String(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const dataDir = process.env.MM_DAEMON_DATA_DIR;\n if (!dataDir) {\n throw new Error('MM_DAEMON_DATA_DIR environment variable is required');\n }\n\n const infuraProjectId = process.env.INFURA_PROJECT_ID;\n if (!infuraProjectId) {\n throw new Error('INFURA_PROJECT_ID environment variable is required');\n }\n\n // Password is optional: when absent, the daemon starts without unlocking\n // the keyring (e.g. when the user prefers to call `mm wallet unlock`\n // interactively rather than embed the password in their environment).\n // First-run startup still requires a password; wallet-factory enforces\n // that and surfaces a clear error.\n const passwordRaw = process.env.MM_WALLET_PASSWORD;\n\n const srpRaw = process.env.MM_WALLET_SRP;\n if (!srpRaw) {\n throw new Error('MM_WALLET_SRP environment variable is required');\n }\n\n // Scrub before validation so a throw from Password.from / Srp.from (bad\n // value) does not leave the raw secrets in the long-lived daemon's env.\n delete process.env.MM_WALLET_PASSWORD;\n delete process.env.MM_WALLET_SRP;\n\n const password = passwordRaw ? Password.from(passwordRaw) : undefined;\n const srp = Srp.from(srpRaw);\n\n await ensureOwnerOnlyDirectory(dataDir);\n\n const {\n socketPath: defaultSocketPath,\n pidPath,\n logPath,\n dbPath,\n } = getDaemonPaths(dataDir);\n const socketPath = process.env.MM_DAEMON_SOCKET_PATH ?? defaultSocketPath;\n\n const log = makeLogger(logPath);\n log('Starting daemon...');\n\n // Pre-flight: refuse to take over if a responsive daemon already owns this\n // socket. If the existing PID file is stale (or the socket is dead), clean\n // it up so the exclusive PID-file write below has a chance to succeed.\n await claimDaemonSlot(pidPath, socketPath, log);\n\n const pidFileContents = `${process.pid}\\n${startTime}\\n`;\n\n // Claim the slot atomically BEFORE opening the SQLite database or\n // constructing the Wallet. Two concurrent `daemon start` invocations can\n // both pass `claimDaemonSlot` (the gap between its preflight and the slot\n // write is racy); without this ordering, both would open `wallet.db` and\n // both would run first-run SRP import before one loses the wx race.\n try {\n await writeFile(pidPath, pidFileContents, { flag: 'wx' });\n } catch (error) {\n throw error instanceof Error\n ? Object.assign(error, {\n message: `Failed to claim daemon slot at ${pidPath}: ${error.message}`,\n })\n : /* istanbul ignore next -- node:fs/promises always rejects with an Error */\n new Error(\n `Failed to claim daemon slot at ${pidPath}: ${String(error)}`,\n );\n }\n\n let wallet: Wallet | undefined;\n let dispose: (() => Promise<void>) | undefined;\n let handle: RpcSocketServerHandle | undefined;\n\n try {\n ({ wallet, dispose } = await createWallet({\n databasePath: dbPath,\n password,\n srp,\n infuraProjectId,\n log,\n }));\n\n const constructedWallet = wallet;\n // Arbitrary messenger dispatch is intentional: the CLI exposes the full\n // messenger surface over a Unix socket inside the per-user oclif data\n // directory. The dataDir is chmodded to 0o700 above and the socket to\n // 0o600 by the RPC server on bind, so only the owning user can open them,\n // but there is no in-process auth check beyond that filesystem-permission\n // barrier. The messenger is strongly typed by action name; we narrow it\n // once here to the RpcDispatcher shape the `call` handler needs.\n const dispatch = constructedWallet.messenger.call.bind(\n constructedWallet.messenger,\n ) as unknown as RpcDispatcher;\n\n const handlers: RpcHandlerMap = {\n getStatus: defineHandler(\n literal(null),\n async (): Promise<DaemonStatusInfo> => ({\n pid: process.pid,\n uptime: Math.floor((Date.now() - startTime) / 1000),\n }),\n ),\n call: defineHandler(callParamsStruct, async (params) => {\n const [action, ...args] = params;\n return await dispatch(action, ...(args as Json[]));\n }),\n // Exposes the callable surface for discovery: it grows silently as\n // controllers are wired, so consumers need a way to see it without a\n // hand-kept catalog that would rot.\n listActions: defineHandler(\n literal(null),\n async (): Promise<Json> =>\n constructedWallet.messenger.getRegisteredActionTypes(),\n ),\n // Dedicated send handler; see `runSendTransaction` for why the generic\n // `call` dispatch cannot carry a broadcast result.\n sendTransaction: defineHandler(\n SendTransactionParamsStruct,\n async (params) =>\n runSendTransaction(constructedWallet.messenger, params),\n ),\n };\n\n // `startRpcSocketServer` restricts the socket to the owner (chmod 0o600)\n // on bind and never leaves a live server/socket behind if it rejects, so\n // the catch below has nothing of its own to close.\n handle = await startRpcSocketServer({\n socketPath,\n handlers,\n onShutdown: async () => shutdown('RPC shutdown'),\n log,\n });\n } catch (error) {\n // `dispose` is undefined only when `createWallet` itself threw — it has\n // already torn down its own store in that case.\n if (dispose) {\n await dispose();\n }\n // Only remove the PID file if it's still ours (we may have lost the race\n // and the file now belongs to another daemon).\n await removeOwnedPidFile(pidPath, pidFileContents).catch(\n (rmError: unknown) => {\n log(`Failed to remove PID file during cleanup: ${String(rmError)}`);\n },\n );\n throw error;\n }\n\n // Stable non-undefined refs for the shutdown closures (TS won't narrow the\n // outer `let`s across closure escape).\n const activeHandle = handle;\n const activeDispose = dispose;\n\n log(`Daemon started. Socket: ${socketPath}`);\n\n let shutdownPromise: Promise<void> | undefined;\n\n /**\n * Shut down the daemon idempotently. Concurrent calls coalesce.\n *\n * @param reason - A label describing why shutdown was triggered.\n * @returns A promise that resolves when shutdown completes.\n */\n async function shutdown(reason: string): Promise<void> {\n if (shutdownPromise === undefined) {\n log(`Shutting down (${reason})...`);\n shutdownPromise = (async (): Promise<void> => {\n try {\n await activeHandle.close();\n } catch (closeError) {\n log(`handle.close() failed: ${String(closeError)}`);\n }\n try {\n await activeDispose();\n } catch (disposeError) {\n log(`dispose() failed during shutdown: ${String(disposeError)}`);\n }\n await Promise.all([\n removeOwnedPidFile(pidPath, pidFileContents).catch(\n (rmError: unknown) => {\n log(`Failed to remove PID file: ${String(rmError)}`);\n },\n ),\n rm(socketPath, { force: true }).catch((rmError: unknown) => {\n log(`Failed to remove socket file: ${String(rmError)}`);\n }),\n ]);\n })();\n }\n return shutdownPromise;\n }\n\n process.on('SIGTERM', () => {\n /* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */\n shutdown('SIGTERM').catch(() => undefined);\n });\n process.on('SIGINT', () => {\n /* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */\n shutdown('SIGINT').catch(() => undefined);\n });\n}\n\n/**\n * Refuse to start if a responsive daemon already owns the socket. Otherwise\n * clear any stale PID/socket files so the exclusive PID-file write can\n * proceed.\n *\n * @param pidPath - The PID file path.\n * @param socketPath - The socket path.\n * @param log - Logger for diagnostic messages.\n */\nasync function claimDaemonSlot(\n pidPath: string,\n socketPath: string,\n log: Logger,\n): Promise<void> {\n const existingPid = await readPidFile(pidPath);\n const ping = await pingDaemon(socketPath);\n\n if (ping.status === 'responsive') {\n const pidPart =\n existingPid === undefined\n ? '(no PID file present)'\n : `(pid ${existingPid})`;\n throw new Error(`A daemon is already running on ${socketPath} ${pidPart}`);\n }\n\n // Refuse to clobber when the recorded PID is still alive, regardless of\n // whether the socket exists. Possible scenarios:\n // - `unreachable`: wedged or mid-startup sibling daemon (socket present\n // but not responding to JSON-RPC).\n // - `absent`: a sibling daemon that hasn't yet bound its socket, or one\n // whose socket was manually removed. In either case, removing its PID\n // file would orphan it from `daemon stop`.\n if (existingPid !== undefined && isProcessAlive(existingPid)) {\n const detail =\n ping.status === 'unreachable'\n ? `socket at ${socketPath} is unresponsive (${ping.error.message})`\n : `no socket at ${socketPath}, but pid is still alive`;\n throw new Error(\n `A daemon is already running (pid ${existingPid}): ${detail}. ` +\n `Run \\`mm daemon stop\\` (or \\`mm daemon purge\\`) before starting a new daemon.`,\n );\n }\n\n if (ping.status === 'unreachable') {\n log(`Removing stale socket at ${socketPath} (${ping.error.message}).`);\n }\n // Always clear both files before claiming the slot. The PID file may be\n // corrupt (truncated, partial write from a crashed run); without this, the\n // exclusive `wx` write below would fail with EEXIST and the daemon could\n // not start until a human manually deleted the file.\n await Promise.all([\n rm(pidPath, { force: true }),\n rm(socketPath, { force: true }),\n ]);\n}\n\n/**\n * Remove the PID file only if it still contains our exact contents. Guards\n * against a racing daemon's PID file being removed by this daemon during\n * cleanup.\n *\n * @param pidPath - Path to the PID file.\n * @param expectedContents - The contents we wrote when claiming the slot.\n */\nasync function removeOwnedPidFile(\n pidPath: string,\n expectedContents: string,\n): Promise<void> {\n let actual: string;\n try {\n actual = await readFile(pidPath, 'utf-8');\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ENOENT')) {\n return;\n }\n throw error;\n }\n if (actual === expectedContents) {\n await rm(pidPath, { force: true });\n }\n}\n\n/**\n * Create a file logger that appends timestamped lines to `logPath`, falling\n * back to stderr if the append fails.\n *\n * @param logPath - The log file path.\n * @returns A logging function.\n */\nfunction makeLogger(logPath: string): Logger {\n return (message: string): void => {\n const line = `[${new Date().toISOString()}] ${message}\\n`;\n appendFile(logPath, line).catch((error: unknown) => {\n process.stderr.write(`[log write failed: ${String(error)}] ${message}\\n`);\n });\n };\n}\n"]}
@@ -1,138 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensureDaemon = void 0;
4
- const node_child_process_1 = require("node:child_process");
5
- const node_fs_1 = require("node:fs");
6
- const node_path_1 = require("node:path");
7
- const daemon_client_js_1 = require("./daemon-client.cjs");
8
- const data_dir_js_1 = require("./data-dir.cjs");
9
- const paths_js_1 = require("./paths.cjs");
10
- const POLL_INTERVAL_MS = 100;
11
- const MAX_POLLS = 300; // 30 seconds
12
- /**
13
- * Ensure the daemon is running. If a responsive daemon already exists, return
14
- * `'already-running'` (caller decides how to surface that). Otherwise spawn
15
- * one as a detached process and wait until the socket becomes responsive.
16
- *
17
- * Refuses to spawn when pinging the existing socket fails with anything other
18
- * than `ENOENT` (wedged or foreign daemon) — taking over could orphan the
19
- * existing process and corrupt its PID file.
20
- *
21
- * @param config - Spawn configuration.
22
- * @returns The state of the daemon and the socket path it's listening on.
23
- */
24
- async function ensureDaemon(config) {
25
- const { socketPath, logPath } = (0, paths_js_1.getDaemonPaths)(config.dataDir);
26
- const initialPing = await (0, daemon_client_js_1.pingDaemon)(socketPath);
27
- switch (initialPing.status) {
28
- case 'responsive':
29
- return { state: 'already-running', socketPath };
30
- case 'unreachable':
31
- if (initialPing.reason === 'permission') {
32
- throw new Error(`Refusing to start: the socket at ${socketPath} is owned by another user. ` +
33
- `Choose a different data directory (MM_DAEMON_DATA_DIR) or remove the socket manually. ` +
34
- `(${initialPing.error.message})`);
35
- }
36
- throw new Error(`Refusing to start: a daemon socket already exists at ${socketPath} but is unresponsive. ` +
37
- `Run \`mm daemon stop\` (or \`mm daemon purge\`) before starting a new daemon. ` +
38
- `(${initialPing.error.message})`);
39
- case 'absent':
40
- break;
41
- /* istanbul ignore next -- exhaustiveness guard; unreachable for the current PingResult union */
42
- default: {
43
- const exhaustiveCheck = initialPing;
44
- throw new Error(`Unexpected daemon ping status: ${String(exhaustiveCheck)}`);
45
- }
46
- }
47
- process.stderr.write('Starting daemon...\n');
48
- const { entryPath, args } = resolveEntryPoint(config.packageRoot);
49
- // Create the data directory before opening the log file inside it. The daemon
50
- // entry also does this, but only after spawn — opening the log first would
51
- // ENOENT on a fresh data directory.
52
- await (0, data_dir_js_1.ensureOwnerOnlyDirectory)(config.dataDir);
53
- // Redirect the detached daemon's stderr to its log file rather than
54
- // discarding it, so a crash after startup stays diagnosable. stdout stays
55
- // ignored — structured status goes through the file logger.
56
- const logFileDescriptor = (0, node_fs_1.openSync)(logPath, 'a');
57
- const childEnv = {
58
- ...process.env,
59
- MM_DAEMON_DATA_DIR: config.dataDir,
60
- MM_DAEMON_SOCKET_PATH: socketPath,
61
- INFURA_PROJECT_ID: config.infuraProjectId,
62
- MM_WALLET_SRP: config.srp.unwrap(),
63
- };
64
- // `childEnv` spreads `process.env`, so an inherited `MM_WALLET_PASSWORD`
65
- // would otherwise leak into the child and unlock a daemon the caller meant
66
- // to start locked. When no password was supplied, delete the inherited key
67
- // so the daemon comes up locked; otherwise overwrite it with the supplied
68
- // value.
69
- if (config.password === undefined) {
70
- delete childEnv.MM_WALLET_PASSWORD;
71
- }
72
- else {
73
- childEnv.MM_WALLET_PASSWORD = config.password.unwrap();
74
- }
75
- const child = (0, node_child_process_1.spawn)(process.execPath, [...args, entryPath], {
76
- detached: true,
77
- stdio: ['ignore', 'ignore', logFileDescriptor],
78
- env: childEnv,
79
- });
80
- // The child dup'd the file descriptor into its stderr, so drop the parent's
81
- // copy. Safe on the success path: `spawn` reports failures via the 'error'
82
- // event, not a synchronous throw.
83
- (0, node_fs_1.closeSync)(logFileDescriptor);
84
- // A failed spawn (bad interpreter, EACCES, ENOENT) emits 'error' and may
85
- // never emit 'exit', so 'error' is recorded first and not overwritten by a
86
- // later 'exit' — the loop surfaces the real cause instead of hanging.
87
- const outcome = { current: { kind: 'pending' } };
88
- child.on('error', (error) => {
89
- process.stderr.write(`Failed to spawn daemon process: ${String(error)}\n`);
90
- outcome.current = { kind: 'error', error };
91
- });
92
- child.on('exit', (code, signal) => {
93
- if (outcome.current.kind === 'pending') {
94
- outcome.current = { kind: 'exited', code, signal };
95
- }
96
- });
97
- child.unref();
98
- for (let i = 0; i < MAX_POLLS; i++) {
99
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
100
- const settled = outcome.current;
101
- if (settled.kind === 'error') {
102
- throw new Error(`Failed to spawn daemon process: ${settled.error.message}. ` +
103
- `Check the daemon log at ${logPath}.`);
104
- }
105
- if (settled.kind === 'exited') {
106
- throw new Error(`Daemon process exited during startup (code=${String(settled.code)}, signal=${String(settled.signal)}). ` +
107
- `Check the daemon log at ${logPath}.`);
108
- }
109
- const ping = await (0, daemon_client_js_1.pingDaemon)(socketPath);
110
- if (ping.status === 'responsive') {
111
- process.stderr.write('Daemon ready.\n');
112
- return { state: 'started', socketPath };
113
- }
114
- }
115
- throw new Error(`Daemon did not start within ${(MAX_POLLS * POLL_INTERVAL_MS) / 1000}s`);
116
- }
117
- exports.ensureDaemon = ensureDaemon;
118
- /**
119
- * Resolve the daemon entry point path and any extra Node.js args needed.
120
- *
121
- * In production, uses the compiled dist output. In development, uses tsx
122
- * to run TypeScript source directly.
123
- *
124
- * @param packageRoot - The root directory of the wallet-cli package.
125
- * @returns The entry path and any extra node args.
126
- */
127
- function resolveEntryPoint(packageRoot) {
128
- const distEntry = (0, node_path_1.join)(packageRoot, 'dist', 'daemon', 'daemon-entry.mjs');
129
- if ((0, node_fs_1.existsSync)(distEntry)) {
130
- return { entryPath: distEntry, args: [] };
131
- }
132
- const srcEntry = (0, node_path_1.join)(packageRoot, 'src', 'daemon', 'daemon-entry.ts');
133
- return {
134
- entryPath: srcEntry,
135
- args: ['--import', 'tsx'],
136
- };
137
- }
138
- //# sourceMappingURL=daemon-spawn.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-spawn.cjs","sourceRoot":"","sources":["../../src/daemon/daemon-spaw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ACD,MAAM,IAAI,GAAG,MAAM,IAAA,6BAAU,EAAC,UAAU,CAAC,CAAC;QAC1C,IAAI,IAAI,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;YACjC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;YACxC,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC;QAC1C,CAAC;IACH,CAAC;IAED,MAAM,IAAI,KAAK,CACb,+BAA+B,CAAC,SAAS,GAAG,gBAAgB,CAAC,GAAG,IAAI,GAAG,CACxE,CAAC;AACJ,CAAC;AAzHD,oCAyHC;AAED;;;;;;;;GAQG;AACH,SAAS,iBAAiB,CAAC,WAAmB;IAI5C,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,kBAAkB,CAAC,CAAC;IAC1E,IAAI,IAAA,oBAAU,EAAC,SAAS,CAAC,EAAE,CAAC;QAC1B,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;IAC5C,CAAC;IAED,MAAM,QAAQ,GAAG,IAAA,gBAAI,EAAC,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,iBAAiB,CAAC,CAAC;IACvE,OAAO;QACL,SAAS,EAAE,QAAQ;QACnB,IAAI,EAAE,CAAC,UAAU,EAAE,KAAK,CAAC;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from 'node:child_process';\nimport { closeSync, existsSync, openSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { pingDaemon } from './daemon-client.js';\nimport { ensureOwnerOnlyDirectory } from './data-dir.js';\nimport { getDaemonPaths } from './paths.js';\nimport type { DaemonSpawnConfig } from './types.js';\n\nconst POLL_INTERVAL_MS = 100;\nconst MAX_POLLS = 300; // 30 seconds\n\n/**\n * Outcome of {@link ensureDaemon}.\n *\n * - `'already-running'`: a responsive daemon was found at the configured\n * socket path. The supplied flags (`infuraProjectId`, `password`, `srp`)\n * were NOT applied to that daemon; the caller should surface this so a\n * user who is trying to change them isn't silently ignored.\n * - `'started'`: a new daemon was spawned and is now responsive.\n */\nexport type EnsureDaemonResult = {\n state: 'already-running' | 'started';\n socketPath: string;\n};\n\n/**\n * Ensure the daemon is running. If a responsive daemon already exists, return\n * `'already-running'` (caller decides how to surface that). Otherwise spawn\n * one as a detached process and wait until the socket becomes responsive.\n *\n * Refuses to spawn when pinging the existing socket fails with anything other\n * than `ENOENT` (wedged or foreign daemon) — taking over could orphan the\n * existing process and corrupt its PID file.\n *\n * @param config - Spawn configuration.\n * @returns The state of the daemon and the socket path it's listening on.\n */\nexport async function ensureDaemon(\n config: DaemonSpawnConfig,\n): Promise<EnsureDaemonResult> {\n const { socketPath, logPath } = getDaemonPaths(config.dataDir);\n\n const initialPing = await pingDaemon(socketPath);\n switch (initialPing.status) {\n case 'responsive':\n return { state: 'already-running', socketPath };\n case 'unreachable':\n if (initialPing.reason === 'permission') {\n throw new Error(\n `Refusing to start: the socket at ${socketPath} is owned by another user. ` +\n `Choose a different data directory (MM_DAEMON_DATA_DIR) or remove the socket manually. ` +\n `(${initialPing.error.message})`,\n );\n }\n throw new Error(\n `Refusing to start: a daemon socket already exists at ${socketPath} but is unresponsive. ` +\n `Run \\`mm daemon stop\\` (or \\`mm daemon purge\\`) before starting a new daemon. ` +\n `(${initialPing.error.message})`,\n );\n case 'absent':\n break;\n /* istanbul ignore next -- exhaustiveness guard; unreachable for the current PingResult union */\n default: {\n const exhaustiveCheck: never = initialPing;\n throw new Error(\n `Unexpected daemon ping status: ${String(exhaustiveCheck)}`,\n );\n }\n }\n\n process.stderr.write('Starting daemon...\\n');\n\n const { entryPath, args } = resolveEntryPoint(config.packageRoot);\n\n // Create the data directory before opening the log file inside it. The daemon\n // entry also does this, but only after spawn — opening the log first would\n // ENOENT on a fresh data directory.\n await ensureOwnerOnlyDirectory(config.dataDir);\n\n // Redirect the detached daemon's stderr to its log file rather than\n // discarding it, so a crash after startup stays diagnosable. stdout stays\n // ignored — structured status goes through the file logger.\n const logFileDescriptor = openSync(logPath, 'a');\n\n const childEnv: NodeJS.ProcessEnv = {\n ...process.env,\n MM_DAEMON_DATA_DIR: config.dataDir,\n MM_DAEMON_SOCKET_PATH: socketPath,\n INFURA_PROJECT_ID: config.infuraProjectId,\n MM_WALLET_SRP: config.srp.unwrap(),\n };\n // `childEnv` spreads `process.env`, so an inherited `MM_WALLET_PASSWORD`\n // would otherwise leak into the child and unlock a daemon the caller meant\n // to start locked. When no password was supplied, delete the inherited key\n // so the daemon comes up locked; otherwise overwrite it with the supplied\n // value.\n if (config.password === undefined) {\n delete childEnv.MM_WALLET_PASSWORD;\n } else {\n childEnv.MM_WALLET_PASSWORD = config.password.unwrap();\n }\n\n const child = spawn(process.execPath, [...args, entryPath], {\n detached: true,\n stdio: ['ignore', 'ignore', logFileDescriptor],\n env: childEnv,\n });\n // The child dup'd the file descriptor into its stderr, so drop the parent's\n // copy. Safe on the success path: `spawn` reports failures via the 'error'\n // event, not a synchronous throw.\n closeSync(logFileDescriptor);\n\n type StartupOutcome =\n | { kind: 'pending' }\n | { kind: 'error'; error: Error }\n | { kind: 'exited'; code: number | null; signal: NodeJS.Signals | null };\n\n // A failed spawn (bad interpreter, EACCES, ENOENT) emits 'error' and may\n // never emit 'exit', so 'error' is recorded first and not overwritten by a\n // later 'exit' — the loop surfaces the real cause instead of hanging.\n const outcome: { current: StartupOutcome } = { current: { kind: 'pending' } };\n\n child.on('error', (error: Error) => {\n process.stderr.write(`Failed to spawn daemon process: ${String(error)}\\n`);\n outcome.current = { kind: 'error', error };\n });\n child.on('exit', (code, signal) => {\n if (outcome.current.kind === 'pending') {\n outcome.current = { kind: 'exited', code, signal };\n }\n });\n child.unref();\n\n for (let i = 0; i < MAX_POLLS; i++) {\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n const settled = outcome.current;\n if (settled.kind === 'error') {\n throw new Error(\n `Failed to spawn daemon process: ${settled.error.message}. ` +\n `Check the daemon log at ${logPath}.`,\n );\n }\n if (settled.kind === 'exited') {\n throw new Error(\n `Daemon process exited during startup (code=${String(settled.code)}, signal=${String(settled.signal)}). ` +\n `Check the daemon log at ${logPath}.`,\n );\n }\n const ping = await pingDaemon(socketPath);\n if (ping.status === 'responsive') {\n process.stderr.write('Daemon ready.\\n');\n return { state: 'started', socketPath };\n }\n }\n\n throw new Error(\n `Daemon did not start within ${(MAX_POLLS * POLL_INTERVAL_MS) / 1000}s`,\n );\n}\n\n/**\n * Resolve the daemon entry point path and any extra Node.js args needed.\n *\n * In production, uses the compiled dist output. In development, uses tsx\n * to run TypeScript source directly.\n *\n * @param packageRoot - The root directory of the wallet-cli package.\n * @returns The entry path and any extra node args.\n */\nfunction resolveEntryPoint(packageRoot: string): {\n entryPath: string;\n args: string[];\n} {\n const distEntry = join(packageRoot, 'dist', 'daemon', 'daemon-entry.mjs');\n if (existsSync(distEntry)) {\n return { entryPath: distEntry, args: [] };\n }\n\n const srcEntry = join(packageRoot, 'src', 'daemon', 'daemon-entry.ts');\n return {\n entryPath: srcEntry,\n args: ['--import', 'tsx'],\n };\n}\n"]}
@@ -1,28 +0,0 @@
1
- import type { DaemonSpawnConfig } from "./types.cjs";
2
- /**
3
- * Outcome of {@link ensureDaemon}.
4
- *
5
- * - `'already-running'`: a responsive daemon was found at the configured
6
- * socket path. The supplied flags (`infuraProjectId`, `password`, `srp`)
7
- * were NOT applied to that daemon; the caller should surface this so a
8
- * user who is trying to change them isn't silently ignored.
9
- * - `'started'`: a new daemon was spawned and is now responsive.
10
- */
11
- export type EnsureDaemonResult = {
12
- state: 'already-running' | 'started';
13
- socketPath: string;
14
- };
15
- /**
16
- * Ensure the daemon is running. If a responsive daemon already exists, return
17
- * `'already-running'` (caller decides how to surface that). Otherwise spawn
18
- * one as a detached process and wait until the socket becomes responsive.
19
- *
20
- * Refuses to spawn when pinging the existing socket fails with anything other
21
- * than `ENOENT` (wedged or foreign daemon) — taking over could orphan the
22
- * existing process and corrupt its PID file.
23
- *
24
- * @param config - Spawn configuration.
25
- * @returns The state of the daemon and the socket path it's listening on.
26
- */
27
- export declare function ensureDaemon(config: DaemonSpawnConfig): Promise<EnsureDaemonResult>;
28
- //# sourceMappingURL=daemon-spawn.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-spawn.d.cts","sourceRoot":"","sources":["../../src/daemon/daemon-spawn.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,oBAAmB;AAKpD;;;;;;;;GAQG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,KAAK,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACrC,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,iBAAiB,GACxB,OAAO,CAAC,kBAAkB,CAAC,CAuH7B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-spawn.d.mts","sourceRoot":"","sources":["../../src/daemon/daemon-spawn.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,oBAAmB;AAKpD;;;;;;;;GAQG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,KAAK,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACrC,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,iBAAiB,GACxB,OAAO,CAAC,kBAAkB,CAAC,CAuH7B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-spawn.mjs","sourceRoot":"","sources":["../../src/daemon/daemon-spawn.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,2BAA2B;AAC3C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,gBAAgB;AAC1D,OAAO,EAAE,IAAI,EAAE,kBAAkB;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AM,UAAU,CAAC,UAAU,CAAC,CAAC;QAC1C,IAAI,IAAI,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;YACjC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;YACxC,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC;QAC1C,CAAC;IACH,CAAC;IAED,MAAM,IAAI,KAAK,CACb,+BAA+B,CAAC,SAAS,GAAG,gBAAgB,CAAC,GAAG,IAAI,GAAG,CACxE,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,iBAAiB,CAAC,WAAmB;IAI5C,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,kBAAkB,CAAC,CAAC;IAC1E,IAAI,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QAC1B,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;IAC5C,CAAC;IAED,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,iBAAiB,CAAC,CAAC;IACvE,OAAO;QACL,SAAS,EAAE,QAAQ;QACnB,IAAI,EAAE,CAAC,UAAU,EAAE,KAAK,CAAC;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from 'node:child_process';\nimport { closeSync, existsSync, openSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { pingDaemon } from './daemon-client.js';\nimport { ensureOwnerOnlyDirectory } from './data-dir.js';\nimport { getDaemonPaths } from './paths.js';\nimport type { DaemonSpawnConfig } from './types.js';\n\nconst POLL_INTERVAL_MS = 100;\nconst MAX_POLLS = 300; // 30 seconds\n\n/**\n * Outcome of {@link ensureDaemon}.\n *\n * - `'already-running'`: a responsive daemon was found at the configured\n * socket path. The supplied flags (`infuraProjectId`, `password`, `srp`)\n * were NOT applied to that daemon; the caller should surface this so a\n * user who is trying to change them isn't silently ignored.\n * - `'started'`: a new daemon was spawned and is now responsive.\n */\nexport type EnsureDaemonResult = {\n state: 'already-running' | 'started';\n socketPath: string;\n};\n\n/**\n * Ensure the daemon is running. If a responsive daemon already exists, return\n * `'already-running'` (caller decides how to surface that). Otherwise spawn\n * one as a detached process and wait until the socket becomes responsive.\n *\n * Refuses to spawn when pinging the existing socket fails with anything other\n * than `ENOENT` (wedged or foreign daemon) — taking over could orphan the\n * existing process and corrupt its PID file.\n *\n * @param config - Spawn configuration.\n * @returns The state of the daemon and the socket path it's listening on.\n */\nexport async function ensureDaemon(\n config: DaemonSpawnConfig,\n): Promise<EnsureDaemonResult> {\n const { socketPath, logPath } = getDaemonPaths(config.dataDir);\n\n const initialPing = await pingDaemon(socketPath);\n switch (initialPing.status) {\n case 'responsive':\n return { state: 'already-running', socketPath };\n case 'unreachable':\n if (initialPing.reason === 'permission') {\n throw new Error(\n `Refusing to start: the socket at ${socketPath} is owned by another user. ` +\n `Choose a different data directory (MM_DAEMON_DATA_DIR) or remove the socket manually. ` +\n `(${initialPing.error.message})`,\n );\n }\n throw new Error(\n `Refusing to start: a daemon socket already exists at ${socketPath} but is unresponsive. ` +\n `Run \\`mm daemon stop\\` (or \\`mm daemon purge\\`) before starting a new daemon. ` +\n `(${initialPing.error.message})`,\n );\n case 'absent':\n break;\n /* istanbul ignore next -- exhaustiveness guard; unreachable for the current PingResult union */\n default: {\n const exhaustiveCheck: never = initialPing;\n throw new Error(\n `Unexpected daemon ping status: ${String(exhaustiveCheck)}`,\n );\n }\n }\n\n process.stderr.write('Starting daemon...\\n');\n\n const { entryPath, args } = resolveEntryPoint(config.packageRoot);\n\n // Create the data directory before opening the log file inside it. The daemon\n // entry also does this, but only after spawn — opening the log first would\n // ENOENT on a fresh data directory.\n await ensureOwnerOnlyDirectory(config.dataDir);\n\n // Redirect the detached daemon's stderr to its log file rather than\n // discarding it, so a crash after startup stays diagnosable. stdout stays\n // ignored — structured status goes through the file logger.\n const logFileDescriptor = openSync(logPath, 'a');\n\n const childEnv: NodeJS.ProcessEnv = {\n ...process.env,\n MM_DAEMON_DATA_DIR: config.dataDir,\n MM_DAEMON_SOCKET_PATH: socketPath,\n INFURA_PROJECT_ID: config.infuraProjectId,\n MM_WALLET_SRP: config.srp.unwrap(),\n };\n // `childEnv` spreads `process.env`, so an inherited `MM_WALLET_PASSWORD`\n // would otherwise leak into the child and unlock a daemon the caller meant\n // to start locked. When no password was supplied, delete the inherited key\n // so the daemon comes up locked; otherwise overwrite it with the supplied\n // value.\n if (config.password === undefined) {\n delete childEnv.MM_WALLET_PASSWORD;\n } else {\n childEnv.MM_WALLET_PASSWORD = config.password.unwrap();\n }\n\n const child = spawn(process.execPath, [...args, entryPath], {\n detached: true,\n stdio: ['ignore', 'ignore', logFileDescriptor],\n env: childEnv,\n });\n // The child dup'd the file descriptor into its stderr, so drop the parent's\n // copy. Safe on the success path: `spawn` reports failures via the 'error'\n // event, not a synchronous throw.\n closeSync(logFileDescriptor);\n\n type StartupOutcome =\n | { kind: 'pending' }\n | { kind: 'error'; error: Error }\n | { kind: 'exited'; code: number | null; signal: NodeJS.Signals | null };\n\n // A failed spawn (bad interpreter, EACCES, ENOENT) emits 'error' and may\n // never emit 'exit', so 'error' is recorded first and not overwritten by a\n // later 'exit' — the loop surfaces the real cause instead of hanging.\n const outcome: { current: StartupOutcome } = { current: { kind: 'pending' } };\n\n child.on('error', (error: Error) => {\n process.stderr.write(`Failed to spawn daemon process: ${String(error)}\\n`);\n outcome.current = { kind: 'error', error };\n });\n child.on('exit', (code, signal) => {\n if (outcome.current.kind === 'pending') {\n outcome.current = { kind: 'exited', code, signal };\n }\n });\n child.unref();\n\n for (let i = 0; i < MAX_POLLS; i++) {\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n const settled = outcome.current;\n if (settled.kind === 'error') {\n throw new Error(\n `Failed to spawn daemon process: ${settled.error.message}. ` +\n `Check the daemon log at ${logPath}.`,\n );\n }\n if (settled.kind === 'exited') {\n throw new Error(\n `Daemon process exited during startup (code=${String(settled.code)}, signal=${String(settled.signal)}). ` +\n `Check the daemon log at ${logPath}.`,\n );\n }\n const ping = await pingDaemon(socketPath);\n if (ping.status === 'responsive') {\n process.stderr.write('Daemon ready.\\n');\n return { state: 'started', socketPath };\n }\n }\n\n throw new Error(\n `Daemon did not start within ${(MAX_POLLS * POLL_INTERVAL_MS) / 1000}s`,\n );\n}\n\n/**\n * Resolve the daemon entry point path and any extra Node.js args needed.\n *\n * In production, uses the compiled dist output. In development, uses tsx\n * to run TypeScript source directly.\n *\n * @param packageRoot - The root directory of the wallet-cli package.\n * @returns The entry path and any extra node args.\n */\nfunction resolveEntryPoint(packageRoot: string): {\n entryPath: string;\n args: string[];\n} {\n const distEntry = join(packageRoot, 'dist', 'daemon', 'daemon-entry.mjs');\n if (existsSync(distEntry)) {\n return { entryPath: distEntry, args: [] };\n }\n\n const srcEntry = join(packageRoot, 'src', 'daemon', 'daemon-entry.ts');\n return {\n entryPath: srcEntry,\n args: ['--import', 'tsx'],\n };\n}\n"]}