@metamask-previews/wallet-cli 0.0.0-preview-9298fa429 → 0.0.0-preview-574b60e35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -0
- package/dist/daemon/daemon-entry.cjs +245 -0
- package/dist/daemon/daemon-entry.cjs.map +1 -0
- package/dist/daemon/daemon-entry.d.cts +2 -0
- package/dist/daemon/daemon-entry.d.cts.map +1 -0
- package/dist/daemon/daemon-entry.d.mts +2 -0
- package/dist/daemon/daemon-entry.d.mts.map +1 -0
- package/dist/daemon/daemon-entry.mjs +243 -0
- package/dist/daemon/daemon-entry.mjs.map +1 -0
- package/dist/daemon/data-dir.cjs +23 -0
- package/dist/daemon/data-dir.cjs.map +1 -0
- package/dist/daemon/data-dir.d.cts +14 -0
- package/dist/daemon/data-dir.d.cts.map +1 -0
- package/dist/daemon/data-dir.d.mts +14 -0
- package/dist/daemon/data-dir.d.mts.map +1 -0
- package/dist/daemon/data-dir.mjs +19 -0
- package/dist/daemon/data-dir.mjs.map +1 -0
- package/dist/daemon/types.cjs.map +1 -1
- package/dist/daemon/types.d.cts +5 -0
- package/dist/daemon/types.d.cts.map +1 -1
- package/dist/daemon/types.d.mts +5 -0
- package/dist/daemon/types.d.mts.map +1 -1
- package/dist/daemon/types.mjs.map +1 -1
- package/dist/daemon/wallet-factory.cjs +234 -0
- package/dist/daemon/wallet-factory.cjs.map +1 -0
- package/dist/daemon/wallet-factory.d.cts +55 -0
- package/dist/daemon/wallet-factory.d.cts.map +1 -0
- package/dist/daemon/wallet-factory.d.mts +55 -0
- package/dist/daemon/wallet-factory.d.mts.map +1 -0
- package/dist/daemon/wallet-factory.mjs +230 -0
- package/dist/daemon/wallet-factory.mjs.map +1 -0
- package/dist/persistence/persistence.cjs.map +1 -1
- package/dist/persistence/persistence.d.cts +1 -1
- package/dist/persistence/persistence.d.cts.map +1 -1
- package/dist/persistence/persistence.d.mts +1 -1
- package/dist/persistence/persistence.d.mts.map +1 -1
- package/dist/persistence/persistence.mjs.map +1 -1
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
|
+
- Add a wallet factory and daemon entry point that construct a `@metamask/wallet` `Wallet` backed by the SQLite key-value store, hydrate it from persisted state, run controller initialization (aborting startup if any step fails), import the secret recovery phrase on first run, and expose a `dispose` teardown handle ([#9226](https://github.com/MetaMask/core/pull/9226))
|
|
12
13
|
- Add a daemon transport layer: a JSON-RPC client and server over a Unix socket, plus daemon spawn/stop lifecycle helpers ([#9108](https://github.com/MetaMask/core/pull/9108))
|
|
13
14
|
- Add SQLite-backed persistence for wallet controller state ([#9067](https://github.com/MetaMask/core/pull/9067))
|
|
14
15
|
- Initial package scaffold for `@metamask/wallet-cli`, an [oclif](https://oclif.io)-based `mm` CLI for `@metamask/wallet` ([#9065](https://github.com/MetaMask/core/pull/9065)).
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const promises_1 = require("node:fs/promises");
|
|
4
|
+
const daemon_client_1 = require("./daemon-client.cjs");
|
|
5
|
+
const data_dir_1 = require("./data-dir.cjs");
|
|
6
|
+
const paths_1 = require("./paths.cjs");
|
|
7
|
+
const rpc_socket_server_1 = require("./rpc-socket-server.cjs");
|
|
8
|
+
const utils_1 = require("./utils.cjs");
|
|
9
|
+
const wallet_factory_1 = require("./wallet-factory.cjs");
|
|
10
|
+
const startTime = Date.now();
|
|
11
|
+
main().catch((error) => {
|
|
12
|
+
process.stderr.write(`Daemon fatal: ${String(error)}\n`);
|
|
13
|
+
process.exitCode = 1;
|
|
14
|
+
});
|
|
15
|
+
async function main() {
|
|
16
|
+
const dataDir = process.env.MM_DAEMON_DATA_DIR;
|
|
17
|
+
if (!dataDir) {
|
|
18
|
+
throw new Error('MM_DAEMON_DATA_DIR environment variable is required');
|
|
19
|
+
}
|
|
20
|
+
const infuraProjectId = process.env.INFURA_PROJECT_ID;
|
|
21
|
+
if (!infuraProjectId) {
|
|
22
|
+
throw new Error('INFURA_PROJECT_ID environment variable is required');
|
|
23
|
+
}
|
|
24
|
+
const password = process.env.MM_WALLET_PASSWORD;
|
|
25
|
+
if (!password) {
|
|
26
|
+
throw new Error('MM_WALLET_PASSWORD environment variable is required');
|
|
27
|
+
}
|
|
28
|
+
const srp = process.env.MM_WALLET_SRP;
|
|
29
|
+
if (!srp) {
|
|
30
|
+
throw new Error('MM_WALLET_SRP environment variable is required');
|
|
31
|
+
}
|
|
32
|
+
// Scrub the wallet secrets from the environment now they are captured. The
|
|
33
|
+
// daemon is long-lived and dispatches arbitrary messenger actions over its
|
|
34
|
+
// socket, so leaving the SRP/password in `process.env` for its whole lifetime
|
|
35
|
+
// needlessly widens their exposure to any in-process code.
|
|
36
|
+
delete process.env.MM_WALLET_PASSWORD;
|
|
37
|
+
delete process.env.MM_WALLET_SRP;
|
|
38
|
+
await (0, data_dir_1.ensureOwnerOnlyDirectory)(dataDir);
|
|
39
|
+
const { socketPath: defaultSocketPath, pidPath, logPath, dbPath, } = (0, paths_1.getDaemonPaths)(dataDir);
|
|
40
|
+
const socketPath = process.env.MM_DAEMON_SOCKET_PATH ?? defaultSocketPath;
|
|
41
|
+
const log = makeLogger(logPath);
|
|
42
|
+
log('Starting daemon...');
|
|
43
|
+
// Pre-flight: refuse to take over if a responsive daemon already owns this
|
|
44
|
+
// socket. If the existing PID file is stale (or the socket is dead), clean
|
|
45
|
+
// it up so the exclusive PID-file write below has a chance to succeed.
|
|
46
|
+
await claimDaemonSlot(pidPath, socketPath, log);
|
|
47
|
+
const pidFileContents = `${process.pid}\n${startTime}\n`;
|
|
48
|
+
// Claim the slot atomically BEFORE opening the SQLite database or
|
|
49
|
+
// constructing the Wallet. Two concurrent `daemon start` invocations can
|
|
50
|
+
// both pass `claimDaemonSlot` (the gap between its preflight and the slot
|
|
51
|
+
// write is racy); without this ordering, both would open `wallet.db` and
|
|
52
|
+
// both would run first-run SRP import before one loses the wx race.
|
|
53
|
+
try {
|
|
54
|
+
await (0, promises_1.writeFile)(pidPath, pidFileContents, { flag: 'wx' });
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
throw error instanceof Error
|
|
58
|
+
? Object.assign(error, {
|
|
59
|
+
message: `Failed to claim daemon slot at ${pidPath}: ${error.message}`,
|
|
60
|
+
})
|
|
61
|
+
: /* istanbul ignore next -- node:fs/promises always rejects with an Error */
|
|
62
|
+
new Error(`Failed to claim daemon slot at ${pidPath}: ${String(error)}`);
|
|
63
|
+
}
|
|
64
|
+
let wallet;
|
|
65
|
+
let dispose;
|
|
66
|
+
let handle;
|
|
67
|
+
try {
|
|
68
|
+
({ wallet, dispose } = await (0, wallet_factory_1.createWallet)({
|
|
69
|
+
databasePath: dbPath,
|
|
70
|
+
password,
|
|
71
|
+
srp,
|
|
72
|
+
infuraProjectId,
|
|
73
|
+
log,
|
|
74
|
+
}));
|
|
75
|
+
const constructedWallet = wallet;
|
|
76
|
+
const handlers = {
|
|
77
|
+
getStatus: async () => ({
|
|
78
|
+
pid: process.pid,
|
|
79
|
+
uptime: Math.floor((Date.now() - startTime) / 1000),
|
|
80
|
+
}),
|
|
81
|
+
// Arbitrary messenger dispatch is intentional: the CLI exposes the full
|
|
82
|
+
// messenger surface over a Unix socket inside the per-user oclif data
|
|
83
|
+
// directory. The dataDir is chmodded to 0o700 above and the socket to
|
|
84
|
+
// 0o600 by the RPC server on bind, so only the owning user can open
|
|
85
|
+
// them, but there is no in-process auth check beyond that
|
|
86
|
+
// filesystem-permission barrier.
|
|
87
|
+
call: async (params) => {
|
|
88
|
+
if (!Array.isArray(params) || typeof params[0] !== 'string') {
|
|
89
|
+
throw new Error('Expected params to be an array with an action name');
|
|
90
|
+
}
|
|
91
|
+
const [action, ...args] = params;
|
|
92
|
+
const result = constructedWallet.messenger.call(action, ...args);
|
|
93
|
+
return (result instanceof Promise ? await result : result);
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
// `startRpcSocketServer` restricts the socket to the owner (chmod 0o600)
|
|
97
|
+
// on bind and never leaves a live server/socket behind if it rejects, so
|
|
98
|
+
// the catch below has nothing of its own to close.
|
|
99
|
+
handle = await (0, rpc_socket_server_1.startRpcSocketServer)({
|
|
100
|
+
socketPath,
|
|
101
|
+
handlers,
|
|
102
|
+
onShutdown: async () => shutdown('RPC shutdown'),
|
|
103
|
+
log,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
// `dispose` is undefined only when `createWallet` itself threw — it has
|
|
108
|
+
// already torn down its own store in that case.
|
|
109
|
+
if (dispose) {
|
|
110
|
+
await dispose();
|
|
111
|
+
}
|
|
112
|
+
// Only remove the PID file if it's still ours (we may have lost the race
|
|
113
|
+
// and the file now belongs to another daemon).
|
|
114
|
+
await removeOwnedPidFile(pidPath, pidFileContents).catch((rmError) => {
|
|
115
|
+
log(`Failed to remove PID file during cleanup: ${String(rmError)}`);
|
|
116
|
+
});
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
// Stable non-undefined refs for the shutdown closures (TS won't narrow the
|
|
120
|
+
// outer `let`s across closure escape).
|
|
121
|
+
const activeHandle = handle;
|
|
122
|
+
const activeDispose = dispose;
|
|
123
|
+
log(`Daemon started. Socket: ${socketPath}`);
|
|
124
|
+
let shutdownPromise;
|
|
125
|
+
/**
|
|
126
|
+
* Shut down the daemon idempotently. Concurrent calls coalesce.
|
|
127
|
+
*
|
|
128
|
+
* @param reason - A label describing why shutdown was triggered.
|
|
129
|
+
* @returns A promise that resolves when shutdown completes.
|
|
130
|
+
*/
|
|
131
|
+
async function shutdown(reason) {
|
|
132
|
+
if (shutdownPromise === undefined) {
|
|
133
|
+
log(`Shutting down (${reason})...`);
|
|
134
|
+
shutdownPromise = (async () => {
|
|
135
|
+
try {
|
|
136
|
+
await activeHandle.close();
|
|
137
|
+
}
|
|
138
|
+
catch (closeError) {
|
|
139
|
+
log(`handle.close() failed: ${String(closeError)}`);
|
|
140
|
+
}
|
|
141
|
+
await activeDispose();
|
|
142
|
+
await Promise.all([
|
|
143
|
+
removeOwnedPidFile(pidPath, pidFileContents).catch((rmError) => {
|
|
144
|
+
log(`Failed to remove PID file: ${String(rmError)}`);
|
|
145
|
+
}),
|
|
146
|
+
(0, promises_1.rm)(socketPath, { force: true }).catch((rmError) => {
|
|
147
|
+
log(`Failed to remove socket file: ${String(rmError)}`);
|
|
148
|
+
}),
|
|
149
|
+
]);
|
|
150
|
+
})();
|
|
151
|
+
}
|
|
152
|
+
return shutdownPromise;
|
|
153
|
+
}
|
|
154
|
+
process.on('SIGTERM', () => {
|
|
155
|
+
/* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */
|
|
156
|
+
shutdown('SIGTERM').catch(() => undefined);
|
|
157
|
+
});
|
|
158
|
+
process.on('SIGINT', () => {
|
|
159
|
+
/* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */
|
|
160
|
+
shutdown('SIGINT').catch(() => undefined);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Refuse to start if a responsive daemon already owns the socket. Otherwise
|
|
165
|
+
* clear any stale PID/socket files so the exclusive PID-file write can
|
|
166
|
+
* proceed.
|
|
167
|
+
*
|
|
168
|
+
* @param pidPath - The PID file path.
|
|
169
|
+
* @param socketPath - The socket path.
|
|
170
|
+
* @param log - Logger for diagnostic messages.
|
|
171
|
+
*/
|
|
172
|
+
async function claimDaemonSlot(pidPath, socketPath, log) {
|
|
173
|
+
const existingPid = await (0, utils_1.readPidFile)(pidPath);
|
|
174
|
+
const ping = await (0, daemon_client_1.pingDaemon)(socketPath);
|
|
175
|
+
if (ping.status === 'responsive') {
|
|
176
|
+
const pidPart = existingPid === undefined
|
|
177
|
+
? '(no PID file present)'
|
|
178
|
+
: `(pid ${existingPid})`;
|
|
179
|
+
throw new Error(`A daemon is already running on ${socketPath} ${pidPart}`);
|
|
180
|
+
}
|
|
181
|
+
// Refuse to clobber when the recorded PID is still alive, regardless of
|
|
182
|
+
// whether the socket exists. Possible scenarios:
|
|
183
|
+
// - `unreachable`: wedged or mid-startup sibling daemon (socket present
|
|
184
|
+
// but not responding to JSON-RPC).
|
|
185
|
+
// - `absent`: a sibling daemon that hasn't yet bound its socket, or one
|
|
186
|
+
// whose socket was manually removed. In either case, removing its PID
|
|
187
|
+
// file would orphan it from `daemon stop`.
|
|
188
|
+
if (existingPid !== undefined && (0, utils_1.isProcessAlive)(existingPid)) {
|
|
189
|
+
const detail = ping.status === 'unreachable'
|
|
190
|
+
? `socket at ${socketPath} is unresponsive (${ping.error.message})`
|
|
191
|
+
: `no socket at ${socketPath}, but pid is still alive`;
|
|
192
|
+
throw new Error(`A daemon is already running (pid ${existingPid}): ${detail}. ` +
|
|
193
|
+
`Run \`mm daemon stop\` (or \`mm daemon purge\`) before starting a new daemon.`);
|
|
194
|
+
}
|
|
195
|
+
if (ping.status === 'unreachable') {
|
|
196
|
+
log(`Removing stale socket at ${socketPath} (${ping.error.message}).`);
|
|
197
|
+
}
|
|
198
|
+
// Always clear both files before claiming the slot. The PID file may be
|
|
199
|
+
// corrupt (truncated, partial write from a crashed run); without this, the
|
|
200
|
+
// exclusive `wx` write below would fail with EEXIST and the daemon could
|
|
201
|
+
// not start until a human manually deleted the file.
|
|
202
|
+
await Promise.all([
|
|
203
|
+
(0, promises_1.rm)(pidPath, { force: true }),
|
|
204
|
+
(0, promises_1.rm)(socketPath, { force: true }),
|
|
205
|
+
]);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Remove the PID file only if it still contains our exact contents. Guards
|
|
209
|
+
* against a racing daemon's PID file being removed by this daemon during
|
|
210
|
+
* cleanup.
|
|
211
|
+
*
|
|
212
|
+
* @param pidPath - Path to the PID file.
|
|
213
|
+
* @param expectedContents - The contents we wrote when claiming the slot.
|
|
214
|
+
*/
|
|
215
|
+
async function removeOwnedPidFile(pidPath, expectedContents) {
|
|
216
|
+
let actual;
|
|
217
|
+
try {
|
|
218
|
+
actual = await (0, promises_1.readFile)(pidPath, 'utf-8');
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
if ((0, utils_1.isErrorWithCode)(error, 'ENOENT')) {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
if (actual === expectedContents) {
|
|
227
|
+
await (0, promises_1.rm)(pidPath, { force: true });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Create a file logger that appends timestamped lines to `logPath`, falling
|
|
232
|
+
* back to stderr if the append fails.
|
|
233
|
+
*
|
|
234
|
+
* @param logPath - The log file path.
|
|
235
|
+
* @returns A logging function.
|
|
236
|
+
*/
|
|
237
|
+
function makeLogger(logPath) {
|
|
238
|
+
return (message) => {
|
|
239
|
+
const line = `[${new Date().toISOString()}] ${message}\n`;
|
|
240
|
+
(0, promises_1.appendFile)(logPath, line).catch((error) => {
|
|
241
|
+
process.stderr.write(`[log write failed: ${String(error)}] ${message}\n`);
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
//# sourceMappingURL=daemon-entry.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"daemon-entry.cjs","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":";;AAEA,+CAAuE;AAEvE,uDAA6C;AAC7C,6CAAsD;AACtD,uCAAyC;AACzC,+DAA2D;AAG3D,uCAAuE;AACvE,yDAAgD;AAEhD,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAE7B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC9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,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 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';\nimport { ensureOwnerOnlyDirectory } from './data-dir';\nimport { getDaemonPaths } from './paths';\nimport { startRpcSocketServer } from './rpc-socket-server';\nimport type { RpcSocketServerHandle } from './rpc-socket-server';\nimport type { DaemonStatusInfo, Logger, RpcHandlerMap } from './types';\nimport { isErrorWithCode, isProcessAlive, readPidFile } from './utils';\nimport { createWallet } from './wallet-factory';\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 const password = process.env.MM_WALLET_PASSWORD;\n if (!password) {\n throw new Error('MM_WALLET_PASSWORD environment variable is required');\n }\n\n const srp = process.env.MM_WALLET_SRP;\n if (!srp) {\n throw new Error('MM_WALLET_SRP environment variable is required');\n }\n\n // Scrub the wallet secrets from the environment now they are captured. The\n // daemon is long-lived and dispatches arbitrary messenger actions over its\n // socket, so leaving the SRP/password in `process.env` for its whole lifetime\n // needlessly widens their exposure to any in-process code.\n delete process.env.MM_WALLET_PASSWORD;\n delete process.env.MM_WALLET_SRP;\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 const handlers: RpcHandlerMap = {\n getStatus: async (): Promise<DaemonStatusInfo> => ({\n pid: process.pid,\n uptime: Math.floor((Date.now() - startTime) / 1000),\n }),\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\n // them, but there is no in-process auth check beyond that\n // filesystem-permission barrier.\n call: async (params) => {\n if (!Array.isArray(params) || typeof params[0] !== 'string') {\n throw new Error('Expected params to be an array with an action name');\n }\n const [action, ...args] = params as [string, ...Json[]];\n // The messenger's `call` is typed to a literal action-name union; the\n // daemon dispatches arbitrary action names from RPC. Cast to a\n // string-keyed `call` (which preserves arity) rather than to `any`, so\n // the only untyped value is the `unknown` result narrowed below.\n type ArbitraryDispatch = {\n call: (actionName: string, ...callArgs: Json[]) => unknown;\n };\n const result = (\n constructedWallet.messenger as unknown as ArbitraryDispatch\n ).call(action, ...args);\n return (result instanceof Promise ? await result : result) as Json;\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 await activeDispose();\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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"daemon-entry.d.cts","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"daemon-entry.d.mts","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { appendFile, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { pingDaemon } from "./daemon-client.mjs";
|
|
3
|
+
import { ensureOwnerOnlyDirectory } from "./data-dir.mjs";
|
|
4
|
+
import { getDaemonPaths } from "./paths.mjs";
|
|
5
|
+
import { startRpcSocketServer } from "./rpc-socket-server.mjs";
|
|
6
|
+
import { isErrorWithCode, isProcessAlive, readPidFile } from "./utils.mjs";
|
|
7
|
+
import { createWallet } from "./wallet-factory.mjs";
|
|
8
|
+
const startTime = Date.now();
|
|
9
|
+
main().catch((error) => {
|
|
10
|
+
process.stderr.write(`Daemon fatal: ${String(error)}\n`);
|
|
11
|
+
process.exitCode = 1;
|
|
12
|
+
});
|
|
13
|
+
async function main() {
|
|
14
|
+
const dataDir = process.env.MM_DAEMON_DATA_DIR;
|
|
15
|
+
if (!dataDir) {
|
|
16
|
+
throw new Error('MM_DAEMON_DATA_DIR environment variable is required');
|
|
17
|
+
}
|
|
18
|
+
const infuraProjectId = process.env.INFURA_PROJECT_ID;
|
|
19
|
+
if (!infuraProjectId) {
|
|
20
|
+
throw new Error('INFURA_PROJECT_ID environment variable is required');
|
|
21
|
+
}
|
|
22
|
+
const password = process.env.MM_WALLET_PASSWORD;
|
|
23
|
+
if (!password) {
|
|
24
|
+
throw new Error('MM_WALLET_PASSWORD environment variable is required');
|
|
25
|
+
}
|
|
26
|
+
const srp = process.env.MM_WALLET_SRP;
|
|
27
|
+
if (!srp) {
|
|
28
|
+
throw new Error('MM_WALLET_SRP environment variable is required');
|
|
29
|
+
}
|
|
30
|
+
// Scrub the wallet secrets from the environment now they are captured. The
|
|
31
|
+
// daemon is long-lived and dispatches arbitrary messenger actions over its
|
|
32
|
+
// socket, so leaving the SRP/password in `process.env` for its whole lifetime
|
|
33
|
+
// needlessly widens their exposure to any in-process code.
|
|
34
|
+
delete process.env.MM_WALLET_PASSWORD;
|
|
35
|
+
delete process.env.MM_WALLET_SRP;
|
|
36
|
+
await ensureOwnerOnlyDirectory(dataDir);
|
|
37
|
+
const { socketPath: defaultSocketPath, pidPath, logPath, dbPath, } = getDaemonPaths(dataDir);
|
|
38
|
+
const socketPath = process.env.MM_DAEMON_SOCKET_PATH ?? defaultSocketPath;
|
|
39
|
+
const log = makeLogger(logPath);
|
|
40
|
+
log('Starting daemon...');
|
|
41
|
+
// Pre-flight: refuse to take over if a responsive daemon already owns this
|
|
42
|
+
// socket. If the existing PID file is stale (or the socket is dead), clean
|
|
43
|
+
// it up so the exclusive PID-file write below has a chance to succeed.
|
|
44
|
+
await claimDaemonSlot(pidPath, socketPath, log);
|
|
45
|
+
const pidFileContents = `${process.pid}\n${startTime}\n`;
|
|
46
|
+
// Claim the slot atomically BEFORE opening the SQLite database or
|
|
47
|
+
// constructing the Wallet. Two concurrent `daemon start` invocations can
|
|
48
|
+
// both pass `claimDaemonSlot` (the gap between its preflight and the slot
|
|
49
|
+
// write is racy); without this ordering, both would open `wallet.db` and
|
|
50
|
+
// both would run first-run SRP import before one loses the wx race.
|
|
51
|
+
try {
|
|
52
|
+
await writeFile(pidPath, pidFileContents, { flag: 'wx' });
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
throw error instanceof Error
|
|
56
|
+
? Object.assign(error, {
|
|
57
|
+
message: `Failed to claim daemon slot at ${pidPath}: ${error.message}`,
|
|
58
|
+
})
|
|
59
|
+
: /* istanbul ignore next -- node:fs/promises always rejects with an Error */
|
|
60
|
+
new Error(`Failed to claim daemon slot at ${pidPath}: ${String(error)}`);
|
|
61
|
+
}
|
|
62
|
+
let wallet;
|
|
63
|
+
let dispose;
|
|
64
|
+
let handle;
|
|
65
|
+
try {
|
|
66
|
+
({ wallet, dispose } = await createWallet({
|
|
67
|
+
databasePath: dbPath,
|
|
68
|
+
password,
|
|
69
|
+
srp,
|
|
70
|
+
infuraProjectId,
|
|
71
|
+
log,
|
|
72
|
+
}));
|
|
73
|
+
const constructedWallet = wallet;
|
|
74
|
+
const handlers = {
|
|
75
|
+
getStatus: async () => ({
|
|
76
|
+
pid: process.pid,
|
|
77
|
+
uptime: Math.floor((Date.now() - startTime) / 1000),
|
|
78
|
+
}),
|
|
79
|
+
// Arbitrary messenger dispatch is intentional: the CLI exposes the full
|
|
80
|
+
// messenger surface over a Unix socket inside the per-user oclif data
|
|
81
|
+
// directory. The dataDir is chmodded to 0o700 above and the socket to
|
|
82
|
+
// 0o600 by the RPC server on bind, so only the owning user can open
|
|
83
|
+
// them, but there is no in-process auth check beyond that
|
|
84
|
+
// filesystem-permission barrier.
|
|
85
|
+
call: async (params) => {
|
|
86
|
+
if (!Array.isArray(params) || typeof params[0] !== 'string') {
|
|
87
|
+
throw new Error('Expected params to be an array with an action name');
|
|
88
|
+
}
|
|
89
|
+
const [action, ...args] = params;
|
|
90
|
+
const result = constructedWallet.messenger.call(action, ...args);
|
|
91
|
+
return (result instanceof Promise ? await result : result);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
// `startRpcSocketServer` restricts the socket to the owner (chmod 0o600)
|
|
95
|
+
// on bind and never leaves a live server/socket behind if it rejects, so
|
|
96
|
+
// the catch below has nothing of its own to close.
|
|
97
|
+
handle = await startRpcSocketServer({
|
|
98
|
+
socketPath,
|
|
99
|
+
handlers,
|
|
100
|
+
onShutdown: async () => shutdown('RPC shutdown'),
|
|
101
|
+
log,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
// `dispose` is undefined only when `createWallet` itself threw — it has
|
|
106
|
+
// already torn down its own store in that case.
|
|
107
|
+
if (dispose) {
|
|
108
|
+
await dispose();
|
|
109
|
+
}
|
|
110
|
+
// Only remove the PID file if it's still ours (we may have lost the race
|
|
111
|
+
// and the file now belongs to another daemon).
|
|
112
|
+
await removeOwnedPidFile(pidPath, pidFileContents).catch((rmError) => {
|
|
113
|
+
log(`Failed to remove PID file during cleanup: ${String(rmError)}`);
|
|
114
|
+
});
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
// Stable non-undefined refs for the shutdown closures (TS won't narrow the
|
|
118
|
+
// outer `let`s across closure escape).
|
|
119
|
+
const activeHandle = handle;
|
|
120
|
+
const activeDispose = dispose;
|
|
121
|
+
log(`Daemon started. Socket: ${socketPath}`);
|
|
122
|
+
let shutdownPromise;
|
|
123
|
+
/**
|
|
124
|
+
* Shut down the daemon idempotently. Concurrent calls coalesce.
|
|
125
|
+
*
|
|
126
|
+
* @param reason - A label describing why shutdown was triggered.
|
|
127
|
+
* @returns A promise that resolves when shutdown completes.
|
|
128
|
+
*/
|
|
129
|
+
async function shutdown(reason) {
|
|
130
|
+
if (shutdownPromise === undefined) {
|
|
131
|
+
log(`Shutting down (${reason})...`);
|
|
132
|
+
shutdownPromise = (async () => {
|
|
133
|
+
try {
|
|
134
|
+
await activeHandle.close();
|
|
135
|
+
}
|
|
136
|
+
catch (closeError) {
|
|
137
|
+
log(`handle.close() failed: ${String(closeError)}`);
|
|
138
|
+
}
|
|
139
|
+
await activeDispose();
|
|
140
|
+
await Promise.all([
|
|
141
|
+
removeOwnedPidFile(pidPath, pidFileContents).catch((rmError) => {
|
|
142
|
+
log(`Failed to remove PID file: ${String(rmError)}`);
|
|
143
|
+
}),
|
|
144
|
+
rm(socketPath, { force: true }).catch((rmError) => {
|
|
145
|
+
log(`Failed to remove socket file: ${String(rmError)}`);
|
|
146
|
+
}),
|
|
147
|
+
]);
|
|
148
|
+
})();
|
|
149
|
+
}
|
|
150
|
+
return shutdownPromise;
|
|
151
|
+
}
|
|
152
|
+
process.on('SIGTERM', () => {
|
|
153
|
+
/* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */
|
|
154
|
+
shutdown('SIGTERM').catch(() => undefined);
|
|
155
|
+
});
|
|
156
|
+
process.on('SIGINT', () => {
|
|
157
|
+
/* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */
|
|
158
|
+
shutdown('SIGINT').catch(() => undefined);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Refuse to start if a responsive daemon already owns the socket. Otherwise
|
|
163
|
+
* clear any stale PID/socket files so the exclusive PID-file write can
|
|
164
|
+
* proceed.
|
|
165
|
+
*
|
|
166
|
+
* @param pidPath - The PID file path.
|
|
167
|
+
* @param socketPath - The socket path.
|
|
168
|
+
* @param log - Logger for diagnostic messages.
|
|
169
|
+
*/
|
|
170
|
+
async function claimDaemonSlot(pidPath, socketPath, log) {
|
|
171
|
+
const existingPid = await readPidFile(pidPath);
|
|
172
|
+
const ping = await pingDaemon(socketPath);
|
|
173
|
+
if (ping.status === 'responsive') {
|
|
174
|
+
const pidPart = existingPid === undefined
|
|
175
|
+
? '(no PID file present)'
|
|
176
|
+
: `(pid ${existingPid})`;
|
|
177
|
+
throw new Error(`A daemon is already running on ${socketPath} ${pidPart}`);
|
|
178
|
+
}
|
|
179
|
+
// Refuse to clobber when the recorded PID is still alive, regardless of
|
|
180
|
+
// whether the socket exists. Possible scenarios:
|
|
181
|
+
// - `unreachable`: wedged or mid-startup sibling daemon (socket present
|
|
182
|
+
// but not responding to JSON-RPC).
|
|
183
|
+
// - `absent`: a sibling daemon that hasn't yet bound its socket, or one
|
|
184
|
+
// whose socket was manually removed. In either case, removing its PID
|
|
185
|
+
// file would orphan it from `daemon stop`.
|
|
186
|
+
if (existingPid !== undefined && isProcessAlive(existingPid)) {
|
|
187
|
+
const detail = ping.status === 'unreachable'
|
|
188
|
+
? `socket at ${socketPath} is unresponsive (${ping.error.message})`
|
|
189
|
+
: `no socket at ${socketPath}, but pid is still alive`;
|
|
190
|
+
throw new Error(`A daemon is already running (pid ${existingPid}): ${detail}. ` +
|
|
191
|
+
`Run \`mm daemon stop\` (or \`mm daemon purge\`) before starting a new daemon.`);
|
|
192
|
+
}
|
|
193
|
+
if (ping.status === 'unreachable') {
|
|
194
|
+
log(`Removing stale socket at ${socketPath} (${ping.error.message}).`);
|
|
195
|
+
}
|
|
196
|
+
// Always clear both files before claiming the slot. The PID file may be
|
|
197
|
+
// corrupt (truncated, partial write from a crashed run); without this, the
|
|
198
|
+
// exclusive `wx` write below would fail with EEXIST and the daemon could
|
|
199
|
+
// not start until a human manually deleted the file.
|
|
200
|
+
await Promise.all([
|
|
201
|
+
rm(pidPath, { force: true }),
|
|
202
|
+
rm(socketPath, { force: true }),
|
|
203
|
+
]);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Remove the PID file only if it still contains our exact contents. Guards
|
|
207
|
+
* against a racing daemon's PID file being removed by this daemon during
|
|
208
|
+
* cleanup.
|
|
209
|
+
*
|
|
210
|
+
* @param pidPath - Path to the PID file.
|
|
211
|
+
* @param expectedContents - The contents we wrote when claiming the slot.
|
|
212
|
+
*/
|
|
213
|
+
async function removeOwnedPidFile(pidPath, expectedContents) {
|
|
214
|
+
let actual;
|
|
215
|
+
try {
|
|
216
|
+
actual = await readFile(pidPath, 'utf-8');
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
if (isErrorWithCode(error, 'ENOENT')) {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
if (actual === expectedContents) {
|
|
225
|
+
await rm(pidPath, { force: true });
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Create a file logger that appends timestamped lines to `logPath`, falling
|
|
230
|
+
* back to stderr if the append fails.
|
|
231
|
+
*
|
|
232
|
+
* @param logPath - The log file path.
|
|
233
|
+
* @returns A logging function.
|
|
234
|
+
*/
|
|
235
|
+
function makeLogger(logPath) {
|
|
236
|
+
return (message) => {
|
|
237
|
+
const line = `[${new Date().toISOString()}] ${message}\n`;
|
|
238
|
+
appendFile(logPath, line).catch((error) => {
|
|
239
|
+
process.stderr.write(`[log write failed: ${String(error)}] ${message}\n`);
|
|
240
|
+
});
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
//# sourceMappingURL=daemon-entry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"daemon-entry.mjs","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,EAAE,EAAE,SAAS,EAAE,yBAAyB;AAEvE,OAAO,EAAE,UAAU,EAAE,4BAAwB;AAC7C,OAAO,EAAE,wBAAwB,EAAE,uBAAmB;AACtD,OAAO,EAAE,cAAc,EAAE,oBAAgB;AACzC,OAAO,EAAE,oB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AAC,WAAW,EAAE,KAAK,OAAO,IAAI,CAAC;QAC1D,UAAU,CAAC,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 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';\nimport { ensureOwnerOnlyDirectory } from './data-dir';\nimport { getDaemonPaths } from './paths';\nimport { startRpcSocketServer } from './rpc-socket-server';\nimport type { RpcSocketServerHandle } from './rpc-socket-server';\nimport type { DaemonStatusInfo, Logger, RpcHandlerMap } from './types';\nimport { isErrorWithCode, isProcessAlive, readPidFile } from './utils';\nimport { createWallet } from './wallet-factory';\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 const password = process.env.MM_WALLET_PASSWORD;\n if (!password) {\n throw new Error('MM_WALLET_PASSWORD environment variable is required');\n }\n\n const srp = process.env.MM_WALLET_SRP;\n if (!srp) {\n throw new Error('MM_WALLET_SRP environment variable is required');\n }\n\n // Scrub the wallet secrets from the environment now they are captured. The\n // daemon is long-lived and dispatches arbitrary messenger actions over its\n // socket, so leaving the SRP/password in `process.env` for its whole lifetime\n // needlessly widens their exposure to any in-process code.\n delete process.env.MM_WALLET_PASSWORD;\n delete process.env.MM_WALLET_SRP;\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 const handlers: RpcHandlerMap = {\n getStatus: async (): Promise<DaemonStatusInfo> => ({\n pid: process.pid,\n uptime: Math.floor((Date.now() - startTime) / 1000),\n }),\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\n // them, but there is no in-process auth check beyond that\n // filesystem-permission barrier.\n call: async (params) => {\n if (!Array.isArray(params) || typeof params[0] !== 'string') {\n throw new Error('Expected params to be an array with an action name');\n }\n const [action, ...args] = params as [string, ...Json[]];\n // The messenger's `call` is typed to a literal action-name union; the\n // daemon dispatches arbitrary action names from RPC. Cast to a\n // string-keyed `call` (which preserves arity) rather than to `any`, so\n // the only untyped value is the `unknown` result narrowed below.\n type ArbitraryDispatch = {\n call: (actionName: string, ...callArgs: Json[]) => unknown;\n };\n const result = (\n constructedWallet.messenger as unknown as ArbitraryDispatch\n ).call(action, ...args);\n return (result instanceof Promise ? await result : result) as Json;\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 await activeDispose();\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"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ensureOwnerOnlyDirectory = void 0;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const promises_1 = require("node:fs/promises");
|
|
6
|
+
/**
|
|
7
|
+
* Create the daemon's data directory (if it does not exist) and restrict it to
|
|
8
|
+
* the owning user.
|
|
9
|
+
*
|
|
10
|
+
* The mode is `0o700` (owner-only). The daemon exposes the full wallet
|
|
11
|
+
* messenger over the socket inside this directory, so anyone who can traverse
|
|
12
|
+
* the dir can also `connect()` to the socket. Restricting to the owning user is
|
|
13
|
+
* the only access-control boundary. We `chmod` after `mkdir` because the `mode`
|
|
14
|
+
* option is ignored when the directory already exists.
|
|
15
|
+
*
|
|
16
|
+
* @param dataDir - The data directory to create and lock down.
|
|
17
|
+
*/
|
|
18
|
+
async function ensureOwnerOnlyDirectory(dataDir) {
|
|
19
|
+
(0, node_fs_1.mkdirSync)(dataDir, { recursive: true, mode: 0o700 });
|
|
20
|
+
await (0, promises_1.chmod)(dataDir, 0o700);
|
|
21
|
+
}
|
|
22
|
+
exports.ensureOwnerOnlyDirectory = ensureOwnerOnlyDirectory;
|
|
23
|
+
//# sourceMappingURL=data-dir.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-dir.cjs","sourceRoot":"","sources":["../../src/daemon/data-dir.ts"],"names":[],"mappings":";;;AAAA,qCAAoC;AACpC,+CAAyC;AAEzC;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,wBAAwB,CAAC,OAAe;IAC5D,IAAA,mBAAS,EAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACrD,MAAM,IAAA,gBAAK,EAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAC9B,CAAC;AAHD,4DAGC","sourcesContent":["import { mkdirSync } from 'node:fs';\nimport { chmod } from 'node:fs/promises';\n\n/**\n * Create the daemon's data directory (if it does not exist) and restrict it to\n * the owning user.\n *\n * The mode is `0o700` (owner-only). The daemon exposes the full wallet\n * messenger over the socket inside this directory, so anyone who can traverse\n * the dir can also `connect()` to the socket. Restricting to the owning user is\n * the only access-control boundary. We `chmod` after `mkdir` because the `mode`\n * option is ignored when the directory already exists.\n *\n * @param dataDir - The data directory to create and lock down.\n */\nexport async function ensureOwnerOnlyDirectory(dataDir: string): Promise<void> {\n mkdirSync(dataDir, { recursive: true, mode: 0o700 });\n await chmod(dataDir, 0o700);\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Create the daemon's data directory (if it does not exist) and restrict it to
|
|
3
|
+
* the owning user.
|
|
4
|
+
*
|
|
5
|
+
* The mode is `0o700` (owner-only). The daemon exposes the full wallet
|
|
6
|
+
* messenger over the socket inside this directory, so anyone who can traverse
|
|
7
|
+
* the dir can also `connect()` to the socket. Restricting to the owning user is
|
|
8
|
+
* the only access-control boundary. We `chmod` after `mkdir` because the `mode`
|
|
9
|
+
* option is ignored when the directory already exists.
|
|
10
|
+
*
|
|
11
|
+
* @param dataDir - The data directory to create and lock down.
|
|
12
|
+
*/
|
|
13
|
+
export declare function ensureOwnerOnlyDirectory(dataDir: string): Promise<void>;
|
|
14
|
+
//# sourceMappingURL=data-dir.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-dir.d.cts","sourceRoot":"","sources":["../../src/daemon/data-dir.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;GAWG;AACH,wBAAsB,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG7E"}
|