@metamask-previews/wallet-cli 0.0.0-preview-48e768b22 → 0.0.0-preview-29a675b
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 +3 -1
- package/README.md +16 -2
- package/dist/commands/daemon/call.cjs +3 -7
- package/dist/commands/daemon/call.cjs.map +1 -1
- package/dist/commands/daemon/call.d.cts.map +1 -1
- package/dist/commands/daemon/call.d.mts.map +1 -1
- package/dist/commands/daemon/call.mjs +4 -8
- package/dist/commands/daemon/call.mjs.map +1 -1
- package/dist/commands/daemon/list.cjs +48 -0
- package/dist/commands/daemon/list.cjs.map +1 -0
- package/dist/commands/daemon/list.d.cts +7 -0
- package/dist/commands/daemon/list.d.cts.map +1 -0
- package/dist/commands/daemon/list.d.mts +7 -0
- package/dist/commands/daemon/list.d.mts.map +1 -0
- package/dist/commands/daemon/list.mjs +46 -0
- package/dist/commands/daemon/list.mjs.map +1 -0
- package/dist/daemon/daemon-entry.cjs +4 -0
- package/dist/daemon/daemon-entry.cjs.map +1 -1
- package/dist/daemon/daemon-entry.mjs +4 -0
- package/dist/daemon/daemon-entry.mjs.map +1 -1
- package/dist/daemon/daemon-spawn.cjs +46 -25
- package/dist/daemon/daemon-spawn.cjs.map +1 -1
- package/dist/daemon/daemon-spawn.d.cts.map +1 -1
- package/dist/daemon/daemon-spawn.d.mts.map +1 -1
- package/dist/daemon/daemon-spawn.mjs +47 -26
- package/dist/daemon/daemon-spawn.mjs.map +1 -1
- package/dist/daemon/socket-line.cjs +8 -4
- package/dist/daemon/socket-line.cjs.map +1 -1
- package/dist/daemon/socket-line.d.cts +2 -0
- package/dist/daemon/socket-line.d.cts.map +1 -1
- package/dist/daemon/socket-line.d.mts +2 -0
- package/dist/daemon/socket-line.d.mts.map +1 -1
- package/dist/daemon/socket-line.mjs +8 -4
- package/dist/daemon/socket-line.mjs.map +1 -1
- package/dist/daemon/stop-daemon.cjs +23 -9
- package/dist/daemon/stop-daemon.cjs.map +1 -1
- package/dist/daemon/stop-daemon.d.cts +17 -7
- package/dist/daemon/stop-daemon.d.cts.map +1 -1
- package/dist/daemon/stop-daemon.d.mts +17 -7
- package/dist/daemon/stop-daemon.d.mts.map +1 -1
- package/dist/daemon/stop-daemon.mjs +23 -9
- package/dist/daemon/stop-daemon.mjs.map +1 -1
- package/dist/daemon/utils.cjs +52 -1
- package/dist/daemon/utils.cjs.map +1 -1
- package/dist/daemon/utils.d.cts +28 -0
- package/dist/daemon/utils.d.cts.map +1 -1
- package/dist/daemon/utils.d.mts +28 -0
- package/dist/daemon/utils.d.mts.map +1 -1
- package/dist/daemon/utils.mjs +48 -0
- package/dist/daemon/utils.mjs.map +1 -1
- package/package.json +3 -2
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 the `mm daemon list` command, which prints the messenger actions the running daemon can dispatch via `daemon call`, enumerated from the live messenger so the list cannot drift from what `call` accepts ([#9339](https://github.com/MetaMask/core/pull/9339))
|
|
12
13
|
- Add the `mm daemon` command suite (`start`, `stop`, `status`, `purge`, and `call`) for running the wallet daemon and dispatching messenger actions over its socket ([#9255](https://github.com/MetaMask/core/pull/9255))
|
|
13
14
|
- 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))
|
|
14
15
|
- 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))
|
|
@@ -17,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
17
18
|
|
|
18
19
|
### Changed
|
|
19
20
|
|
|
20
|
-
-
|
|
21
|
+
- Report daemon socket connection errors consistently across `mm daemon call` and `mm daemon list` ([#9339](https://github.com/MetaMask/core/pull/9339))
|
|
22
|
+
- Bump `@metamask/wallet` from `^3.0.0` to `^6.0.0` ([#9218](https://github.com/MetaMask/core/pull/9218), [#9263](https://github.com/MetaMask/core/pull/9263), [#9349](https://github.com/MetaMask/core/pull/9349))
|
|
21
23
|
|
|
22
24
|
[Unreleased]: https://github.com/MetaMask/core/
|
package/README.md
CHANGED
|
@@ -20,13 +20,21 @@ Start the daemon (flags may also be supplied as the `INFURA_PROJECT_ID`, `MM_WAL
|
|
|
20
20
|
mm daemon start --infura-project-id <key> --password <pw> --srp "<phrase>"
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
+
Discover what the running wallet can do — `list` prints every messenger action currently dispatchable via `call`. This surface grows as more controllers are wired, so treat it as evolving rather than a stability contract:
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
mm daemon list
|
|
27
|
+
```
|
|
28
|
+
|
|
23
29
|
Call any messenger action on the running wallet (positional JSON array for arguments, optional `--timeout`):
|
|
24
30
|
|
|
25
31
|
```sh
|
|
26
|
-
mm daemon call
|
|
27
|
-
mm daemon call
|
|
32
|
+
mm daemon call KeyringController:getState
|
|
33
|
+
mm daemon call NetworkController:getState --timeout 10000
|
|
28
34
|
```
|
|
29
35
|
|
|
36
|
+
For the exact parameters and return shape of a given action, see the TypeDoc/README of the controller that owns it (e.g. [`@metamask/keyring-controller`](https://github.com/MetaMask/core/tree/main/packages/keyring-controller#readme)).
|
|
37
|
+
|
|
30
38
|
Inspect or tear it down:
|
|
31
39
|
|
|
32
40
|
```sh
|
|
@@ -55,6 +63,12 @@ Or invoke `prebuild-install` directly from the monorepo root (where `better-sqli
|
|
|
55
63
|
cd node_modules/better-sqlite3 && node ../.bin/prebuild-install
|
|
56
64
|
```
|
|
57
65
|
|
|
66
|
+
## Testing
|
|
67
|
+
|
|
68
|
+
Unit tests run with `yarn workspace @metamask/wallet-cli test`.
|
|
69
|
+
|
|
70
|
+
The subprocess end-to-end suite (in `tests/`) spawns the built `mm` CLI and the native `better-sqlite3` addon as real processes, so it is kept out of the unit run and its coverage gate. Build the workspace dependencies first (`yarn build` from the repo root), then run it with `yarn workspace @metamask/wallet-cli test:e2e`.
|
|
71
|
+
|
|
58
72
|
## Contributing
|
|
59
73
|
|
|
60
74
|
This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
|
|
@@ -38,14 +38,10 @@ class DaemonCall extends core_1.Command {
|
|
|
38
38
|
});
|
|
39
39
|
}
|
|
40
40
|
catch (error) {
|
|
41
|
-
|
|
42
|
-
(0, utils_2.isErrorWithCode)(error, 'ECONNREFUSED')) {
|
|
43
|
-
this.error('Daemon is not running. Start it with `mm daemon start`.');
|
|
44
|
-
}
|
|
45
|
-
this.error(error instanceof Error ? error.message : String(error));
|
|
41
|
+
this.error((0, utils_2.makeDaemonConnectionError)(error));
|
|
46
42
|
}
|
|
47
43
|
if ((0, utils_1.isJsonRpcFailure)(response)) {
|
|
48
|
-
this.error(
|
|
44
|
+
this.error((0, utils_2.formatJsonRpcError)(response.error));
|
|
49
45
|
}
|
|
50
46
|
const isTTY = process.stdout.isTTY ?? false;
|
|
51
47
|
if (isTTY) {
|
|
@@ -64,7 +60,7 @@ DaemonCall.examples = [
|
|
|
64
60
|
];
|
|
65
61
|
DaemonCall.args = {
|
|
66
62
|
action: core_1.Args.string({
|
|
67
|
-
description: 'The messenger action name (e.g.
|
|
63
|
+
description: 'The messenger action name (e.g. KeyringController:getState)',
|
|
68
64
|
required: true,
|
|
69
65
|
}),
|
|
70
66
|
params: core_1.Args.string({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call.cjs","sourceRoot":"","sources":["../../../src/commands/daemon/call.ts"],"names":[],"mappings":";;AACA,2CAAmD;AACnD,sCAAmD;AAEnD,kEAAyD;AACzD,kDAAoD;AACpD,
|
|
1
|
+
{"version":3,"file":"call.cjs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AAC;CACH,CAAC;kBA3BiB,UAAU","sourcesContent":["import type { Json } from '@metamask/utils';\nimport { isJsonRpcFailure } from '@metamask/utils';\nimport { Args, Command, Flags } from '@oclif/core';\n\nimport { sendCommand } from '../../daemon/daemon-client';\nimport { getDaemonPaths } from '../../daemon/paths';\nimport {\n formatJsonRpcError,\n makeDaemonConnectionError,\n} from '../../daemon/utils';\n\nexport default class DaemonCall extends Command {\n static override description = 'Call a messenger action on the wallet daemon';\n\n static override examples = [\n '<%= config.bin %> daemon call KeyringController:getState',\n '<%= config.bin %> daemon call NetworkController:getState',\n '<%= config.bin %> daemon call ApprovalController:getState --timeout 10000',\n ];\n\n static override args = {\n action: Args.string({\n description:\n 'The messenger action name (e.g. KeyringController:getState)',\n required: true,\n }),\n params: Args.string({\n description: 'JSON-encoded arguments array (e.g. \\'[\"arg1\", \"arg2\"]\\')',\n required: false,\n }),\n };\n\n static override flags = {\n timeout: Flags.integer({\n char: 't',\n description: 'Response timeout in milliseconds',\n required: false,\n }),\n };\n\n public async run(): Promise<void> {\n const { args, flags } = await this.parse(DaemonCall);\n const { action } = args;\n const timeoutMs = flags.timeout;\n\n // The daemon's `call` RPC expects `[action, ...args]`. `JSON.parse` returns\n // `unknown`, but anything it produces is structurally `Json`, so we cast to\n // `Json[]` once we've confirmed the parsed payload is an array.\n const rpcParams: Json[] = [action];\n if (args.params !== undefined) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(args.params);\n } catch {\n this.error('params must be valid JSON');\n }\n\n if (!Array.isArray(parsed)) {\n this.error('params must be a JSON array');\n }\n\n rpcParams.push(...(parsed as Json[]));\n }\n\n const { socketPath } = getDaemonPaths(this.config.dataDir);\n\n let response;\n try {\n response = await sendCommand({\n socketPath,\n method: 'call',\n params: rpcParams,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n });\n } catch (error) {\n this.error(makeDaemonConnectionError(error));\n }\n\n if (isJsonRpcFailure(response)) {\n this.error(formatJsonRpcError(response.error));\n }\n\n const isTTY = process.stdout.isTTY ?? false;\n if (isTTY) {\n this.log(JSON.stringify(response.result, null, 2));\n } else {\n process.stdout.write(`${JSON.stringify(response.result)}\\n`);\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call.d.cts","sourceRoot":"","sources":["../../../src/commands/daemon/call.ts"],"names":[],"mappings":"AAEA,OAAO,EAAQ,OAAO,EAAS,oBAAoB;
|
|
1
|
+
{"version":3,"file":"call.d.cts","sourceRoot":"","sources":["../../../src/commands/daemon/call.ts"],"names":[],"mappings":"AAEA,OAAO,EAAQ,OAAO,EAAS,oBAAoB;AASnD,MAAM,CAAC,OAAO,OAAO,UAAW,SAAQ,OAAO;IAC7C,OAAgB,WAAW,SAAkD;IAE7E,OAAgB,QAAQ,WAItB;IAEF,OAAgB,IAAI;;;MAUlB;IAEF,OAAgB,KAAK;;MAMnB;IAEW,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;CAiDlC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call.d.mts","sourceRoot":"","sources":["../../../src/commands/daemon/call.ts"],"names":[],"mappings":"AAEA,OAAO,EAAQ,OAAO,EAAS,oBAAoB;
|
|
1
|
+
{"version":3,"file":"call.d.mts","sourceRoot":"","sources":["../../../src/commands/daemon/call.ts"],"names":[],"mappings":"AAEA,OAAO,EAAQ,OAAO,EAAS,oBAAoB;AASnD,MAAM,CAAC,OAAO,OAAO,UAAW,SAAQ,OAAO;IAC7C,OAAgB,WAAW,SAAkD;IAE7E,OAAgB,QAAQ,WAItB;IAEF,OAAgB,IAAI;;;MAUlB;IAEF,OAAgB,KAAK;;MAMnB;IAEW,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;CAiDlC"}
|
|
@@ -2,7 +2,7 @@ import { isJsonRpcFailure } from "@metamask/utils";
|
|
|
2
2
|
import { Args, Command, Flags } from "@oclif/core";
|
|
3
3
|
import { sendCommand } from "../../daemon/daemon-client.mjs";
|
|
4
4
|
import { getDaemonPaths } from "../../daemon/paths.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { formatJsonRpcError, makeDaemonConnectionError } from "../../daemon/utils.mjs";
|
|
6
6
|
class DaemonCall extends Command {
|
|
7
7
|
async run() {
|
|
8
8
|
const { args, flags } = await this.parse(DaemonCall);
|
|
@@ -36,14 +36,10 @@ class DaemonCall extends Command {
|
|
|
36
36
|
});
|
|
37
37
|
}
|
|
38
38
|
catch (error) {
|
|
39
|
-
|
|
40
|
-
isErrorWithCode(error, 'ECONNREFUSED')) {
|
|
41
|
-
this.error('Daemon is not running. Start it with `mm daemon start`.');
|
|
42
|
-
}
|
|
43
|
-
this.error(error instanceof Error ? error.message : String(error));
|
|
39
|
+
this.error(makeDaemonConnectionError(error));
|
|
44
40
|
}
|
|
45
41
|
if (isJsonRpcFailure(response)) {
|
|
46
|
-
this.error(
|
|
42
|
+
this.error(formatJsonRpcError(response.error));
|
|
47
43
|
}
|
|
48
44
|
const isTTY = process.stdout.isTTY ?? false;
|
|
49
45
|
if (isTTY) {
|
|
@@ -62,7 +58,7 @@ DaemonCall.examples = [
|
|
|
62
58
|
];
|
|
63
59
|
DaemonCall.args = {
|
|
64
60
|
action: Args.string({
|
|
65
|
-
description: 'The messenger action name (e.g.
|
|
61
|
+
description: 'The messenger action name (e.g. KeyringController:getState)',
|
|
66
62
|
required: true,
|
|
67
63
|
}),
|
|
68
64
|
params: Args.string({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call.mjs","sourceRoot":"","sources":["../../../src/commands/daemon/call.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,wBAAwB;AACnD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEnD,OAAO,EAAE,WAAW,EAAE,uCAAmC;AACzD,OAAO,EAAE,cAAc,EAAE,+BAA2B;AACpD,OAAO,
|
|
1
|
+
{"version":3,"file":"call.mjs","sourceRoot":"","sources":["../../../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E,KAAK,CAAC,OAAO,CAAC;QACrB,IAAI,EAAE,GAAG;QACT,WAAW,EAAE,kCAAkC;QAC/C,QAAQ,EAAE,KAAK;KAChB,CAAC;CACH,CAAC;eA3BiB,UAAU","sourcesContent":["import type { Json } from '@metamask/utils';\nimport { isJsonRpcFailure } from '@metamask/utils';\nimport { Args, Command, Flags } from '@oclif/core';\n\nimport { sendCommand } from '../../daemon/daemon-client';\nimport { getDaemonPaths } from '../../daemon/paths';\nimport {\n formatJsonRpcError,\n makeDaemonConnectionError,\n} from '../../daemon/utils';\n\nexport default class DaemonCall extends Command {\n static override description = 'Call a messenger action on the wallet daemon';\n\n static override examples = [\n '<%= config.bin %> daemon call KeyringController:getState',\n '<%= config.bin %> daemon call NetworkController:getState',\n '<%= config.bin %> daemon call ApprovalController:getState --timeout 10000',\n ];\n\n static override args = {\n action: Args.string({\n description:\n 'The messenger action name (e.g. KeyringController:getState)',\n required: true,\n }),\n params: Args.string({\n description: 'JSON-encoded arguments array (e.g. \\'[\"arg1\", \"arg2\"]\\')',\n required: false,\n }),\n };\n\n static override flags = {\n timeout: Flags.integer({\n char: 't',\n description: 'Response timeout in milliseconds',\n required: false,\n }),\n };\n\n public async run(): Promise<void> {\n const { args, flags } = await this.parse(DaemonCall);\n const { action } = args;\n const timeoutMs = flags.timeout;\n\n // The daemon's `call` RPC expects `[action, ...args]`. `JSON.parse` returns\n // `unknown`, but anything it produces is structurally `Json`, so we cast to\n // `Json[]` once we've confirmed the parsed payload is an array.\n const rpcParams: Json[] = [action];\n if (args.params !== undefined) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(args.params);\n } catch {\n this.error('params must be valid JSON');\n }\n\n if (!Array.isArray(parsed)) {\n this.error('params must be a JSON array');\n }\n\n rpcParams.push(...(parsed as Json[]));\n }\n\n const { socketPath } = getDaemonPaths(this.config.dataDir);\n\n let response;\n try {\n response = await sendCommand({\n socketPath,\n method: 'call',\n params: rpcParams,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n });\n } catch (error) {\n this.error(makeDaemonConnectionError(error));\n }\n\n if (isJsonRpcFailure(response)) {\n this.error(formatJsonRpcError(response.error));\n }\n\n const isTTY = process.stdout.isTTY ?? false;\n if (isTTY) {\n this.log(JSON.stringify(response.result, null, 2));\n } else {\n process.stdout.write(`${JSON.stringify(response.result)}\\n`);\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const utils_1 = require("@metamask/utils");
|
|
4
|
+
const core_1 = require("@oclif/core");
|
|
5
|
+
const daemon_client_1 = require("../../daemon/daemon-client.cjs");
|
|
6
|
+
const paths_1 = require("../../daemon/paths.cjs");
|
|
7
|
+
const utils_2 = require("../../daemon/utils.cjs");
|
|
8
|
+
class DaemonList extends core_1.Command {
|
|
9
|
+
async run() {
|
|
10
|
+
await this.parse(DaemonList);
|
|
11
|
+
const { socketPath } = (0, paths_1.getDaemonPaths)(this.config.dataDir);
|
|
12
|
+
let response;
|
|
13
|
+
try {
|
|
14
|
+
response = await (0, daemon_client_1.sendCommand)({ socketPath, method: 'listActions' });
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
this.error((0, utils_2.makeDaemonConnectionError)(error));
|
|
18
|
+
}
|
|
19
|
+
if ((0, utils_1.isJsonRpcFailure)(response)) {
|
|
20
|
+
this.error((0, utils_2.formatJsonRpcError)(response.error));
|
|
21
|
+
}
|
|
22
|
+
if (!(0, utils_2.isStringArray)(response.result)) {
|
|
23
|
+
this.error('Daemon returned an unexpected action list.');
|
|
24
|
+
}
|
|
25
|
+
const actions = [...response.result].sort();
|
|
26
|
+
const isTTY = process.stdout.isTTY ?? false;
|
|
27
|
+
if (!isTTY) {
|
|
28
|
+
// Bare output so it pipes cleanly into `grep`/`fzf`.
|
|
29
|
+
if (actions.length > 0) {
|
|
30
|
+
process.stdout.write(`${actions.join('\n')}\n`);
|
|
31
|
+
}
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (actions.length === 0) {
|
|
35
|
+
this.log('The daemon has no callable actions registered.');
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
this.log(`${actions.length} callable action${actions.length === 1 ? '' : 's'} ` +
|
|
39
|
+
'(dispatch with `mm daemon call <action>`):');
|
|
40
|
+
for (const action of actions) {
|
|
41
|
+
this.log(` ${action}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
DaemonList.description = 'List the messenger actions the running daemon can dispatch via `daemon call`';
|
|
46
|
+
DaemonList.examples = ['<%= config.bin %> daemon list'];
|
|
47
|
+
exports.default = DaemonList;
|
|
48
|
+
//# sourceMappingURL=list.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"list.cjs","sourceRoot":"","sources":["../../../src/commands/daemon/list.ts"],"names":[],"mappings":";;AAAA,2CAAmD;AACnD,sCAAsC;AAEtC,kEAAyD;AACzD,kDAAoD;AACpD,kDAI4B;AAE5B,MAAqB,UAAW,SAAQ,cAAO;IAMtC,KAAK,CAAC,GAAG;QACd,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC7B,MAAM,EAAE,UAAU,EAAE,GAAG,IAAA,sBAAc,EAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAE3D,IAAI,QAAQ,CAAC;QACb,IAAI,CAAC;YACH,QAAQ,GAAG,MAAM,IAAA,2BAAW,EAAC,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC,CAAC;QACtE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,IAAA,iCAAyB,EAAC,KAAK,CAAC,CAAC,CAAC;QAC/C,CAAC;QAED,IAAI,IAAA,wBAAgB,EAAC,QAAQ,CAAC,EAAE,CAAC;YAC/B,IAAI,CAAC,KAAK,CAAC,IAAA,0BAAkB,EAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;QACjD,CAAC;QAED,IAAI,CAAC,IAAA,qBAAa,EAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YACpC,IAAI,CAAC,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC3D,CAAC;QAED,MAAM,OAAO,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;QAE5C,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC;QAC5C,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,qDAAqD;YACrD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAClD,CAAC;YACD,OAAO;QACT,CAAC;QAED,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;YAC3D,OAAO;QACT,CAAC;QAED,IAAI,CAAC,GAAG,CACN,GAAG,OAAO,CAAC,MAAM,mBAAmB,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG;YACpE,4CAA4C,CAC/C,CAAC;QACF,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,GAAG,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;;AA/Ce,sBAAW,GACzB,8EAA8E,CAAC;AAEjE,mBAAQ,GAAG,CAAC,+BAA+B,CAAC,CAAC;kBAJ1C,UAAU","sourcesContent":["import { isJsonRpcFailure } from '@metamask/utils';\nimport { Command } from '@oclif/core';\n\nimport { sendCommand } from '../../daemon/daemon-client';\nimport { getDaemonPaths } from '../../daemon/paths';\nimport {\n formatJsonRpcError,\n isStringArray,\n makeDaemonConnectionError,\n} from '../../daemon/utils';\n\nexport default class DaemonList extends Command {\n static override description =\n 'List the messenger actions the running daemon can dispatch via `daemon call`';\n\n static override examples = ['<%= config.bin %> daemon list'];\n\n public async run(): Promise<void> {\n await this.parse(DaemonList);\n const { socketPath } = getDaemonPaths(this.config.dataDir);\n\n let response;\n try {\n response = await sendCommand({ socketPath, method: 'listActions' });\n } catch (error) {\n this.error(makeDaemonConnectionError(error));\n }\n\n if (isJsonRpcFailure(response)) {\n this.error(formatJsonRpcError(response.error));\n }\n\n if (!isStringArray(response.result)) {\n this.error('Daemon returned an unexpected action list.');\n }\n\n const actions = [...response.result].sort();\n\n const isTTY = process.stdout.isTTY ?? false;\n if (!isTTY) {\n // Bare output so it pipes cleanly into `grep`/`fzf`.\n if (actions.length > 0) {\n process.stdout.write(`${actions.join('\\n')}\\n`);\n }\n return;\n }\n\n if (actions.length === 0) {\n this.log('The daemon has no callable actions registered.');\n return;\n }\n\n this.log(\n `${actions.length} callable action${actions.length === 1 ? '' : 's'} ` +\n '(dispatch with `mm daemon call <action>`):',\n );\n for (const action of actions) {\n this.log(` ${action}`);\n }\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"list.d.cts","sourceRoot":"","sources":["../../../src/commands/daemon/list.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,oBAAoB;AAUtC,MAAM,CAAC,OAAO,OAAO,UAAW,SAAQ,OAAO;IAC7C,OAAgB,WAAW,SACsD;IAEjF,OAAgB,QAAQ,WAAqC;IAEhD,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;CA2ClC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"list.d.mts","sourceRoot":"","sources":["../../../src/commands/daemon/list.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,oBAAoB;AAUtC,MAAM,CAAC,OAAO,OAAO,UAAW,SAAQ,OAAO;IAC7C,OAAgB,WAAW,SACsD;IAEjF,OAAgB,QAAQ,WAAqC;IAEhD,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;CA2ClC"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { isJsonRpcFailure } from "@metamask/utils";
|
|
2
|
+
import { Command } from "@oclif/core";
|
|
3
|
+
import { sendCommand } from "../../daemon/daemon-client.mjs";
|
|
4
|
+
import { getDaemonPaths } from "../../daemon/paths.mjs";
|
|
5
|
+
import { formatJsonRpcError, isStringArray, makeDaemonConnectionError } from "../../daemon/utils.mjs";
|
|
6
|
+
class DaemonList extends Command {
|
|
7
|
+
async run() {
|
|
8
|
+
await this.parse(DaemonList);
|
|
9
|
+
const { socketPath } = getDaemonPaths(this.config.dataDir);
|
|
10
|
+
let response;
|
|
11
|
+
try {
|
|
12
|
+
response = await sendCommand({ socketPath, method: 'listActions' });
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
this.error(makeDaemonConnectionError(error));
|
|
16
|
+
}
|
|
17
|
+
if (isJsonRpcFailure(response)) {
|
|
18
|
+
this.error(formatJsonRpcError(response.error));
|
|
19
|
+
}
|
|
20
|
+
if (!isStringArray(response.result)) {
|
|
21
|
+
this.error('Daemon returned an unexpected action list.');
|
|
22
|
+
}
|
|
23
|
+
const actions = [...response.result].sort();
|
|
24
|
+
const isTTY = process.stdout.isTTY ?? false;
|
|
25
|
+
if (!isTTY) {
|
|
26
|
+
// Bare output so it pipes cleanly into `grep`/`fzf`.
|
|
27
|
+
if (actions.length > 0) {
|
|
28
|
+
process.stdout.write(`${actions.join('\n')}\n`);
|
|
29
|
+
}
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (actions.length === 0) {
|
|
33
|
+
this.log('The daemon has no callable actions registered.');
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
this.log(`${actions.length} callable action${actions.length === 1 ? '' : 's'} ` +
|
|
37
|
+
'(dispatch with `mm daemon call <action>`):');
|
|
38
|
+
for (const action of actions) {
|
|
39
|
+
this.log(` ${action}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
DaemonList.description = 'List the messenger actions the running daemon can dispatch via `daemon call`';
|
|
44
|
+
DaemonList.examples = ['<%= config.bin %> daemon list'];
|
|
45
|
+
export default DaemonList;
|
|
46
|
+
//# sourceMappingURL=list.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"list.mjs","sourceRoot":"","sources":["../../../src/commands/daemon/list.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,wBAAwB;AACnD,OAAO,EAAE,OAAO,EAAE,oBAAoB;AAEtC,OAAO,EAAE,WAAW,EAAE,uCAAmC;AACzD,OAAO,EAAE,cAAc,EAAE,+BAA2B;AACpD,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,yBAAyB,EAC1B,+BAA2B;AAE5B,MAAqB,UAAW,SAAQ,OAAO;IAMtC,KAAK,CAAC,GAAG;QACd,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC7B,MAAM,EAAE,UAAU,EAAE,GAAG,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAE3D,IAAI,QAAQ,CAAC;QACb,IAAI,CAAC;YACH,QAAQ,GAAG,MAAM,WAAW,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC,CAAC;QACtE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC/C,CAAC;QAED,IAAI,gBAAgB,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC/B,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;QACjD,CAAC;QAED,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YACpC,IAAI,CAAC,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC3D,CAAC;QAED,MAAM,OAAO,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;QAE5C,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC;QAC5C,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,qDAAqD;YACrD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAClD,CAAC;YACD,OAAO;QACT,CAAC;QAED,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;YAC3D,OAAO;QACT,CAAC;QAED,IAAI,CAAC,GAAG,CACN,GAAG,OAAO,CAAC,MAAM,mBAAmB,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG;YACpE,4CAA4C,CAC/C,CAAC;QACF,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,GAAG,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;;AA/Ce,sBAAW,GACzB,8EAA8E,CAAC;AAEjE,mBAAQ,GAAG,CAAC,+BAA+B,CAAC,CAAC;eAJ1C,UAAU","sourcesContent":["import { isJsonRpcFailure } from '@metamask/utils';\nimport { Command } from '@oclif/core';\n\nimport { sendCommand } from '../../daemon/daemon-client';\nimport { getDaemonPaths } from '../../daemon/paths';\nimport {\n formatJsonRpcError,\n isStringArray,\n makeDaemonConnectionError,\n} from '../../daemon/utils';\n\nexport default class DaemonList extends Command {\n static override description =\n 'List the messenger actions the running daemon can dispatch via `daemon call`';\n\n static override examples = ['<%= config.bin %> daemon list'];\n\n public async run(): Promise<void> {\n await this.parse(DaemonList);\n const { socketPath } = getDaemonPaths(this.config.dataDir);\n\n let response;\n try {\n response = await sendCommand({ socketPath, method: 'listActions' });\n } catch (error) {\n this.error(makeDaemonConnectionError(error));\n }\n\n if (isJsonRpcFailure(response)) {\n this.error(formatJsonRpcError(response.error));\n }\n\n if (!isStringArray(response.result)) {\n this.error('Daemon returned an unexpected action list.');\n }\n\n const actions = [...response.result].sort();\n\n const isTTY = process.stdout.isTTY ?? false;\n if (!isTTY) {\n // Bare output so it pipes cleanly into `grep`/`fzf`.\n if (actions.length > 0) {\n process.stdout.write(`${actions.join('\\n')}\\n`);\n }\n return;\n }\n\n if (actions.length === 0) {\n this.log('The daemon has no callable actions registered.');\n return;\n }\n\n this.log(\n `${actions.length} callable action${actions.length === 1 ? '' : 's'} ` +\n '(dispatch with `mm daemon call <action>`):',\n );\n for (const action of actions) {\n this.log(` ${action}`);\n }\n }\n}\n"]}
|
|
@@ -78,6 +78,10 @@ async function main() {
|
|
|
78
78
|
pid: process.pid,
|
|
79
79
|
uptime: Math.floor((Date.now() - startTime) / 1000),
|
|
80
80
|
}),
|
|
81
|
+
// Exposes the callable surface for discovery: it grows silently as
|
|
82
|
+
// controllers are wired, so consumers need a way to see it without a
|
|
83
|
+
// hand-kept catalog that would rot.
|
|
84
|
+
listActions: async () => constructedWallet.messenger.getRegisteredActionTypes(),
|
|
81
85
|
// Arbitrary messenger dispatch is intentional: the CLI exposes the full
|
|
82
86
|
// messenger surface over a Unix socket inside the per-user oclif data
|
|
83
87
|
// directory. The dataDir is chmodded to 0o700 above and the socket to
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"daemon-entry.cjs","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":";;AAEA,+CAAuE;AAEvE,u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E;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 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"]}
|
|
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;IAC9B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CA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,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 // 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: async (): Promise<Json> =>\n constructedWallet.messenger.getRegisteredActionTypes(),\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"]}
|
|
@@ -76,6 +76,10 @@ async function main() {
|
|
|
76
76
|
pid: process.pid,
|
|
77
77
|
uptime: Math.floor((Date.now() - startTime) / 1000),
|
|
78
78
|
}),
|
|
79
|
+
// Exposes the callable surface for discovery: it grows silently as
|
|
80
|
+
// controllers are wired, so consumers need a way to see it without a
|
|
81
|
+
// hand-kept catalog that would rot.
|
|
82
|
+
listActions: async () => constructedWallet.messenger.getRegisteredActionTypes(),
|
|
79
83
|
// Arbitrary messenger dispatch is intentional: the CLI exposes the full
|
|
80
84
|
// messenger surface over a Unix socket inside the per-user oclif data
|
|
81
85
|
// directory. The dataDir is chmodded to 0o700 above and the socket to
|
|
@@ -1 +1 @@
|
|
|
1
|
-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CAAC;IACd,CAAC;IACD,IAAI,MAAM,KAAK,gBAAgB,EAAE,CAAC;QAChC,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,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,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"]}
|
|
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;AA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AAM,KAAK,gBAAgB,EAAE,CAAC;QAChC,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,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,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 // 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: async (): Promise<Json> =>\n constructedWallet.messenger.getRegisteredActionTypes(),\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"]}
|