@metamask-previews/wallet-cli 0.0.0-preview-2a8139a3e → 0.0.0-preview-b8d04f274
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 +0 -5
- package/README.md +1 -13
- package/dist/commands/daemon/start.cjs +3 -7
- package/dist/commands/daemon/start.cjs.map +1 -1
- package/dist/commands/daemon/start.d.cts +1 -1
- package/dist/commands/daemon/start.d.cts.map +1 -1
- package/dist/commands/daemon/start.d.mts +1 -1
- package/dist/commands/daemon/start.d.mts.map +1 -1
- package/dist/commands/daemon/start.mjs +3 -7
- package/dist/commands/daemon/start.mjs.map +1 -1
- package/dist/daemon/daemon-entry.cjs +27 -52
- package/dist/daemon/daemon-entry.cjs.map +1 -1
- package/dist/daemon/daemon-entry.mjs +27 -52
- package/dist/daemon/daemon-entry.mjs.map +1 -1
- package/dist/daemon/daemon-spawn.cjs +8 -19
- 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 +8 -19
- package/dist/daemon/daemon-spawn.mjs.map +1 -1
- package/dist/daemon/prompts.cjs +1 -17
- package/dist/daemon/prompts.cjs.map +1 -1
- package/dist/daemon/prompts.d.cts +0 -9
- package/dist/daemon/prompts.d.cts.map +1 -1
- package/dist/daemon/prompts.d.mts +0 -9
- package/dist/daemon/prompts.d.mts.map +1 -1
- package/dist/daemon/prompts.mjs +0 -15
- package/dist/daemon/prompts.mjs.map +1 -1
- package/dist/daemon/rpc-socket-server.cjs +1 -14
- package/dist/daemon/rpc-socket-server.cjs.map +1 -1
- package/dist/daemon/rpc-socket-server.d.cts.map +1 -1
- package/dist/daemon/rpc-socket-server.d.mts.map +1 -1
- package/dist/daemon/rpc-socket-server.mjs +1 -14
- package/dist/daemon/rpc-socket-server.mjs.map +1 -1
- package/dist/daemon/types.cjs +0 -17
- package/dist/daemon/types.cjs.map +1 -1
- package/dist/daemon/types.d.cts +7 -58
- package/dist/daemon/types.d.cts.map +1 -1
- package/dist/daemon/types.d.mts +7 -58
- package/dist/daemon/types.d.mts.map +1 -1
- package/dist/daemon/types.mjs +1 -15
- package/dist/daemon/types.mjs.map +1 -1
- package/dist/daemon/utils.cjs +2 -14
- package/dist/daemon/utils.cjs.map +1 -1
- package/dist/daemon/utils.d.cts +0 -9
- package/dist/daemon/utils.d.cts.map +1 -1
- package/dist/daemon/utils.d.mts +0 -9
- package/dist/daemon/utils.d.mts.map +1 -1
- package/dist/daemon/utils.mjs +1 -12
- package/dist/daemon/utils.mjs.map +1 -1
- package/dist/daemon/wallet-factory.cjs +8 -50
- package/dist/daemon/wallet-factory.cjs.map +1 -1
- package/dist/daemon/wallet-factory.d.cts +8 -17
- package/dist/daemon/wallet-factory.d.cts.map +1 -1
- package/dist/daemon/wallet-factory.d.mts +8 -17
- package/dist/daemon/wallet-factory.d.mts.map +1 -1
- package/dist/daemon/wallet-factory.mjs +8 -50
- package/dist/daemon/wallet-factory.mjs.map +1 -1
- package/package.json +2 -5
- package/dist/commands/wallet/unlock.cjs +0 -75
- package/dist/commands/wallet/unlock.cjs.map +0 -1
- package/dist/commands/wallet/unlock.d.cts +0 -11
- package/dist/commands/wallet/unlock.d.cts.map +0 -1
- package/dist/commands/wallet/unlock.d.mts +0 -11
- package/dist/commands/wallet/unlock.d.mts.map +0 -1
- package/dist/commands/wallet/unlock.mjs +0 -73
- package/dist/commands/wallet/unlock.mjs.map +0 -1
- package/dist/daemon/secrets.cjs +0 -137
- package/dist/daemon/secrets.cjs.map +0 -1
- package/dist/daemon/secrets.d.cts +0 -72
- package/dist/daemon/secrets.d.cts.map +0 -1
- package/dist/daemon/secrets.d.mts +0 -72
- package/dist/daemon/secrets.d.mts.map +0 -1
- package/dist/daemon/secrets.mjs +0 -132
- package/dist/daemon/secrets.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,8 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
|
-
- Wire the `transactionController` slot in the daemon wallet's instance options, so the daemon runs the `TransactionController` with an explicit CLI-appropriate configuration (swaps processing disabled, no client hooks) rather than relying on the controller's implicit defaults ([#9509](https://github.com/MetaMask/core/pull/9509))
|
|
13
|
-
- Add the `mm wallet unlock` command, which dispatches `KeyringController:submitPassword` over the daemon socket, allowing the keyring to be unlocked after a daemon start with no password or after a `mm daemon call KeyringController:setLocked` ([#8821](https://github.com/MetaMask/core/pull/8821))
|
|
14
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))
|
|
15
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))
|
|
16
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))
|
|
@@ -20,10 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
20
18
|
|
|
21
19
|
### Changed
|
|
22
20
|
|
|
23
|
-
- `--password` / `MM_WALLET_PASSWORD` is now optional on `mm daemon start`; on subsequent runs, omitting it starts the daemon with a locked keyring, and the persisted vault is auto-unlocked when a password is supplied ([#8821](https://github.com/MetaMask/core/pull/8821))
|
|
24
|
-
- The daemon RPC server now validates `params` against each handler's superstruct before dispatch, returning a `-32602 invalidParams` error on mismatch instead of passing raw params to the handler ([#8846](https://github.com/MetaMask/core/pull/8846))
|
|
25
21
|
- Report daemon socket connection errors consistently across `mm daemon call` and `mm daemon list` ([#9339](https://github.com/MetaMask/core/pull/9339))
|
|
26
22
|
- Bump `@metamask/wallet` from `^3.0.0` to `^7.0.1` ([#9218](https://github.com/MetaMask/core/pull/9218), [#9263](https://github.com/MetaMask/core/pull/9263), [#9349](https://github.com/MetaMask/core/pull/9349), [#9396](https://github.com/MetaMask/core/pull/9396), [#9470](https://github.com/MetaMask/core/pull/9470))
|
|
27
|
-
- Wrap daemon password and SRP in opaque `Password` and `Srp` types that redact on logging; validated and unwrapped only at trust boundaries ([#8863](https://github.com/MetaMask/core/pull/8863))
|
|
28
23
|
|
|
29
24
|
[Unreleased]: https://github.com/MetaMask/core/
|
package/README.md
CHANGED
|
@@ -12,24 +12,12 @@ or
|
|
|
12
12
|
|
|
13
13
|
## Usage
|
|
14
14
|
|
|
15
|
-
The CLI drives a long-lived background daemon that holds
|
|
15
|
+
The CLI drives a long-lived background **daemon** that holds an unlocked `@metamask/wallet` in memory and exposes its messenger over a per-user Unix socket. All commands live under the `mm daemon` topic; run `mm --help` (or `mm daemon <command> --help`) for the full reference.
|
|
16
16
|
|
|
17
17
|
Start the daemon (flags may also be supplied as the `INFURA_PROJECT_ID`, `MM_WALLET_PASSWORD`, and `MM_WALLET_SRP` environment variables — preferred for secrets):
|
|
18
18
|
|
|
19
19
|
```sh
|
|
20
|
-
# First run — password required to import the secret recovery phrase:
|
|
21
20
|
mm daemon start --infura-project-id <key> --password <pw> --srp "<phrase>"
|
|
22
|
-
|
|
23
|
-
# Subsequent runs — password optional. Omit to start with a locked keyring
|
|
24
|
-
# and unlock later with `mm wallet unlock`:
|
|
25
|
-
mm daemon start --infura-project-id <key> --srp "<phrase>"
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
Unlock the keyring after a password-less start (or after `KeyringController:setLocked`):
|
|
29
|
-
|
|
30
|
-
```sh
|
|
31
|
-
mm wallet unlock --password <pw> # or: MM_WALLET_PASSWORD=<pw> mm wallet unlock
|
|
32
|
-
mm wallet unlock # prompts interactively (input masked)
|
|
33
21
|
```
|
|
34
22
|
|
|
35
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:
|
|
@@ -2,13 +2,11 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
const core_1 = require("@oclif/core");
|
|
4
4
|
const daemon_spawn_1 = require("../../daemon/daemon-spawn.cjs");
|
|
5
|
-
const secrets_1 = require("../../daemon/secrets.cjs");
|
|
6
5
|
class DaemonStart extends core_1.Command {
|
|
7
6
|
async run() {
|
|
8
7
|
const { flags } = await this.parse(DaemonStart);
|
|
9
8
|
const infuraProjectId = flags['infura-project-id'];
|
|
10
|
-
const password
|
|
11
|
-
const srp = secrets_1.Srp.from(flags.srp);
|
|
9
|
+
const { password, srp } = flags;
|
|
12
10
|
const { state, socketPath } = await (0, daemon_spawn_1.ensureDaemon)({
|
|
13
11
|
dataDir: this.config.dataDir,
|
|
14
12
|
infuraProjectId,
|
|
@@ -28,7 +26,6 @@ DaemonStart.description = 'Start the wallet daemon';
|
|
|
28
26
|
DaemonStart.examples = [
|
|
29
27
|
'<%= config.bin %> daemon start --infura-project-id <key> --password <pw> --srp <phrase>',
|
|
30
28
|
'INFURA_PROJECT_ID=<key> MM_WALLET_PASSWORD=<pw> MM_WALLET_SRP=<phrase> <%= config.bin %> daemon start',
|
|
31
|
-
'<%= config.bin %> daemon start --infura-project-id <key> --srp <phrase> # then `mm wallet unlock` later',
|
|
32
29
|
];
|
|
33
30
|
DaemonStart.flags = {
|
|
34
31
|
'infura-project-id': core_1.Flags.string({
|
|
@@ -37,10 +34,9 @@ DaemonStart.flags = {
|
|
|
37
34
|
required: true,
|
|
38
35
|
}),
|
|
39
36
|
password: core_1.Flags.string({
|
|
40
|
-
description: 'Wallet password (testing only — use MM_WALLET_PASSWORD env var in production)
|
|
41
|
-
'Required on first run; on subsequent runs, omit (and leave MM_WALLET_PASSWORD unset) to start with a locked keyring and use `mm wallet unlock`.',
|
|
37
|
+
description: 'Wallet password (testing only — use MM_WALLET_PASSWORD env var in production)',
|
|
42
38
|
env: 'MM_WALLET_PASSWORD',
|
|
43
|
-
required:
|
|
39
|
+
required: true,
|
|
44
40
|
}),
|
|
45
41
|
srp: core_1.Flags.string({
|
|
46
42
|
description: 'Secret recovery phrase (testing only — use MM_WALLET_SRP env var in production)',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.cjs","sourceRoot":"","sources":["../../../src/commands/daemon/start.ts"],"names":[],"mappings":";;AAAA,sCAA6C;AAE7C,gEAAyD;
|
|
1
|
+
{"version":3,"file":"start.cjs","sourceRoot":"","sources":["../../../src/commands/daemon/start.ts"],"names":[],"mappings":";;AAAA,sCAA6C;AAE7C,gEAAyD;AAEzD,MAAqB,WAAY,SAAQ,cAAO;IA4BvC,KAAK,CAAC,GAAG;QACd,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAChD,MAAM,eAAe,GAAG,KAAK,CAAC,mBAAmB,CAAC,CAAC;QACnD,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,GAAG,KAAK,CAAC;QAEhC,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,MAAM,IAAA,2BAAY,EAAC;YAC/C,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO;YAC5B,eAAe;YACf,QAAQ;YACR,GAAG;YACH,WAAW,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI;SAC9B,CAAC,CAAC;QAEH,IAAI,KAAK,KAAK,iBAAiB,EAAE,CAAC;YAChC,IAAI,CAAC,GAAG,CACN,mCAAmC,UAAU,IAAI;gBAC/C,6FAA6F,CAChG,CAAC;YACF,OAAO;QACT,CAAC;QAED,IAAI,CAAC,GAAG,CAAC,2BAA2B,UAAU,EAAE,CAAC,CAAC;IACpD,CAAC;;AAjDe,uBAAW,GAAG,yBAAyB,CAAC;AAExC,oBAAQ,GAAG;IACzB,yFAAyF;IACzF,uGAAuG;CACxG,CAAC;AAEc,iBAAK,GAAG;IACtB,mBAAmB,EAAE,YAAK,CAAC,MAAM,CAAC;QAChC,WAAW,EAAE,sCAAsC;QACnD,GAAG,EAAE,mBAAmB;QACxB,QAAQ,EAAE,IAAI;KACf,CAAC;IACF,QAAQ,EAAE,YAAK,CAAC,MAAM,CAAC;QACrB,WAAW,EACT,+EAA+E;QACjF,GAAG,EAAE,oBAAoB;QACzB,QAAQ,EAAE,IAAI;KACf,CAAC;IACF,GAAG,EAAE,YAAK,CAAC,MAAM,CAAC;QAChB,WAAW,EACT,iFAAiF;QACnF,GAAG,EAAE,eAAe;QACpB,QAAQ,EAAE,IAAI;KACf,CAAC;CACH,CAAC;kBA1BiB,WAAW","sourcesContent":["import { Command, Flags } from '@oclif/core';\n\nimport { ensureDaemon } from '../../daemon/daemon-spawn';\n\nexport default class DaemonStart extends Command {\n static override description = 'Start the wallet daemon';\n\n static override examples = [\n '<%= config.bin %> daemon start --infura-project-id <key> --password <pw> --srp <phrase>',\n 'INFURA_PROJECT_ID=<key> MM_WALLET_PASSWORD=<pw> MM_WALLET_SRP=<phrase> <%= config.bin %> daemon start',\n ];\n\n static override flags = {\n 'infura-project-id': Flags.string({\n description: 'Infura project ID for network access',\n env: 'INFURA_PROJECT_ID',\n required: true,\n }),\n password: Flags.string({\n description:\n 'Wallet password (testing only — use MM_WALLET_PASSWORD env var in production)',\n env: 'MM_WALLET_PASSWORD',\n required: true,\n }),\n srp: Flags.string({\n description:\n 'Secret recovery phrase (testing only — use MM_WALLET_SRP env var in production)',\n env: 'MM_WALLET_SRP',\n required: true,\n }),\n };\n\n public async run(): Promise<void> {\n const { flags } = await this.parse(DaemonStart);\n const infuraProjectId = flags['infura-project-id'];\n const { password, srp } = flags;\n\n const { state, socketPath } = await ensureDaemon({\n dataDir: this.config.dataDir,\n infuraProjectId,\n password,\n srp,\n packageRoot: this.config.root,\n });\n\n if (state === 'already-running') {\n this.log(\n `Daemon already running. Socket: ${socketPath}. ` +\n `The provided flags were not applied; run \\`mm daemon stop\\` and start again to change them.`,\n );\n return;\n }\n\n this.log(`Daemon running. Socket: ${socketPath}`);\n }\n}\n"]}
|
|
@@ -4,7 +4,7 @@ export default class DaemonStart extends Command {
|
|
|
4
4
|
static examples: string[];
|
|
5
5
|
static flags: {
|
|
6
6
|
'infura-project-id': import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
|
|
7
|
-
password: import("@oclif/core/interfaces").OptionFlag<string
|
|
7
|
+
password: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
|
|
8
8
|
srp: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
|
|
9
9
|
};
|
|
10
10
|
run(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.d.cts","sourceRoot":"","sources":["../../../src/commands/daemon/start.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAS,oBAAoB;
|
|
1
|
+
{"version":3,"file":"start.d.cts","sourceRoot":"","sources":["../../../src/commands/daemon/start.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAS,oBAAoB;AAI7C,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,OAAO;IAC9C,OAAgB,WAAW,SAA6B;IAExD,OAAgB,QAAQ,WAGtB;IAEF,OAAgB,KAAK;;;;MAkBnB;IAEW,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;CAuBlC"}
|
|
@@ -4,7 +4,7 @@ export default class DaemonStart extends Command {
|
|
|
4
4
|
static examples: string[];
|
|
5
5
|
static flags: {
|
|
6
6
|
'infura-project-id': import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
|
|
7
|
-
password: import("@oclif/core/interfaces").OptionFlag<string
|
|
7
|
+
password: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
|
|
8
8
|
srp: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
|
|
9
9
|
};
|
|
10
10
|
run(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.d.mts","sourceRoot":"","sources":["../../../src/commands/daemon/start.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAS,oBAAoB;
|
|
1
|
+
{"version":3,"file":"start.d.mts","sourceRoot":"","sources":["../../../src/commands/daemon/start.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAS,oBAAoB;AAI7C,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,OAAO;IAC9C,OAAgB,WAAW,SAA6B;IAExD,OAAgB,QAAQ,WAGtB;IAEF,OAAgB,KAAK;;;;MAkBnB;IAEW,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;CAuBlC"}
|
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
import { Command, Flags } from "@oclif/core";
|
|
2
2
|
import { ensureDaemon } from "../../daemon/daemon-spawn.mjs";
|
|
3
|
-
import { Password, Srp } from "../../daemon/secrets.mjs";
|
|
4
3
|
class DaemonStart extends Command {
|
|
5
4
|
async run() {
|
|
6
5
|
const { flags } = await this.parse(DaemonStart);
|
|
7
6
|
const infuraProjectId = flags['infura-project-id'];
|
|
8
|
-
const password
|
|
9
|
-
const srp = Srp.from(flags.srp);
|
|
7
|
+
const { password, srp } = flags;
|
|
10
8
|
const { state, socketPath } = await ensureDaemon({
|
|
11
9
|
dataDir: this.config.dataDir,
|
|
12
10
|
infuraProjectId,
|
|
@@ -26,7 +24,6 @@ DaemonStart.description = 'Start the wallet daemon';
|
|
|
26
24
|
DaemonStart.examples = [
|
|
27
25
|
'<%= config.bin %> daemon start --infura-project-id <key> --password <pw> --srp <phrase>',
|
|
28
26
|
'INFURA_PROJECT_ID=<key> MM_WALLET_PASSWORD=<pw> MM_WALLET_SRP=<phrase> <%= config.bin %> daemon start',
|
|
29
|
-
'<%= config.bin %> daemon start --infura-project-id <key> --srp <phrase> # then `mm wallet unlock` later',
|
|
30
27
|
];
|
|
31
28
|
DaemonStart.flags = {
|
|
32
29
|
'infura-project-id': Flags.string({
|
|
@@ -35,10 +32,9 @@ DaemonStart.flags = {
|
|
|
35
32
|
required: true,
|
|
36
33
|
}),
|
|
37
34
|
password: Flags.string({
|
|
38
|
-
description: 'Wallet password (testing only — use MM_WALLET_PASSWORD env var in production)
|
|
39
|
-
'Required on first run; on subsequent runs, omit (and leave MM_WALLET_PASSWORD unset) to start with a locked keyring and use `mm wallet unlock`.',
|
|
35
|
+
description: 'Wallet password (testing only — use MM_WALLET_PASSWORD env var in production)',
|
|
40
36
|
env: 'MM_WALLET_PASSWORD',
|
|
41
|
-
required:
|
|
37
|
+
required: true,
|
|
42
38
|
}),
|
|
43
39
|
srp: Flags.string({
|
|
44
40
|
description: 'Secret recovery phrase (testing only — use MM_WALLET_SRP env var in production)',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.mjs","sourceRoot":"","sources":["../../../src/commands/daemon/start.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAE7C,OAAO,EAAE,YAAY,EAAE,sCAAkC;
|
|
1
|
+
{"version":3,"file":"start.mjs","sourceRoot":"","sources":["../../../src/commands/daemon/start.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAE7C,OAAO,EAAE,YAAY,EAAE,sCAAkC;AAEzD,MAAqB,WAAY,SAAQ,OAAO;IA4BvC,KAAK,CAAC,GAAG;QACd,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAChD,MAAM,eAAe,GAAG,KAAK,CAAC,mBAAmB,CAAC,CAAC;QACnD,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,GAAG,KAAK,CAAC;QAEhC,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,MAAM,YAAY,CAAC;YAC/C,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO;YAC5B,eAAe;YACf,QAAQ;YACR,GAAG;YACH,WAAW,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI;SAC9B,CAAC,CAAC;QAEH,IAAI,KAAK,KAAK,iBAAiB,EAAE,CAAC;YAChC,IAAI,CAAC,GAAG,CACN,mCAAmC,UAAU,IAAI;gBAC/C,6FAA6F,CAChG,CAAC;YACF,OAAO;QACT,CAAC;QAED,IAAI,CAAC,GAAG,CAAC,2BAA2B,UAAU,EAAE,CAAC,CAAC;IACpD,CAAC;;AAjDe,uBAAW,GAAG,yBAAyB,CAAC;AAExC,oBAAQ,GAAG;IACzB,yFAAyF;IACzF,uGAAuG;CACxG,CAAC;AAEc,iBAAK,GAAG;IACtB,mBAAmB,EAAE,KAAK,CAAC,MAAM,CAAC;QAChC,WAAW,EAAE,sCAAsC;QACnD,GAAG,EAAE,mBAAmB;QACxB,QAAQ,EAAE,IAAI;KACf,CAAC;IACF,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC;QACrB,WAAW,EACT,+EAA+E;QACjF,GAAG,EAAE,oBAAoB;QACzB,QAAQ,EAAE,IAAI;KACf,CAAC;IACF,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC;QAChB,WAAW,EACT,iFAAiF;QACnF,GAAG,EAAE,eAAe;QACpB,QAAQ,EAAE,IAAI;KACf,CAAC;CACH,CAAC;eA1BiB,WAAW","sourcesContent":["import { Command, Flags } from '@oclif/core';\n\nimport { ensureDaemon } from '../../daemon/daemon-spawn';\n\nexport default class DaemonStart extends Command {\n static override description = 'Start the wallet daemon';\n\n static override examples = [\n '<%= config.bin %> daemon start --infura-project-id <key> --password <pw> --srp <phrase>',\n 'INFURA_PROJECT_ID=<key> MM_WALLET_PASSWORD=<pw> MM_WALLET_SRP=<phrase> <%= config.bin %> daemon start',\n ];\n\n static override flags = {\n 'infura-project-id': Flags.string({\n description: 'Infura project ID for network access',\n env: 'INFURA_PROJECT_ID',\n required: true,\n }),\n password: Flags.string({\n description:\n 'Wallet password (testing only — use MM_WALLET_PASSWORD env var in production)',\n env: 'MM_WALLET_PASSWORD',\n required: true,\n }),\n srp: Flags.string({\n description:\n 'Secret recovery phrase (testing only — use MM_WALLET_SRP env var in production)',\n env: 'MM_WALLET_SRP',\n required: true,\n }),\n };\n\n public async run(): Promise<void> {\n const { flags } = await this.parse(DaemonStart);\n const infuraProjectId = flags['infura-project-id'];\n const { password, srp } = flags;\n\n const { state, socketPath } = await ensureDaemon({\n dataDir: this.config.dataDir,\n infuraProjectId,\n password,\n srp,\n packageRoot: this.config.root,\n });\n\n if (state === 'already-running') {\n this.log(\n `Daemon already running. Socket: ${socketPath}. ` +\n `The provided flags were not applied; run \\`mm daemon stop\\` and start again to change them.`,\n );\n return;\n }\n\n this.log(`Daemon running. Socket: ${socketPath}`);\n }\n}\n"]}
|
|
@@ -1,32 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
const superstruct_1 = require("@metamask/superstruct");
|
|
4
3
|
const promises_1 = require("node:fs/promises");
|
|
5
4
|
const daemon_client_1 = require("./daemon-client.cjs");
|
|
6
5
|
const data_dir_1 = require("./data-dir.cjs");
|
|
7
6
|
const paths_1 = require("./paths.cjs");
|
|
8
7
|
const rpc_socket_server_1 = require("./rpc-socket-server.cjs");
|
|
9
|
-
const secrets_1 = require("./secrets.cjs");
|
|
10
|
-
const types_1 = require("./types.cjs");
|
|
11
8
|
const utils_1 = require("./utils.cjs");
|
|
12
9
|
const wallet_factory_1 = require("./wallet-factory.cjs");
|
|
13
|
-
/**
|
|
14
|
-
* Params struct for the `call` RPC method. `params` must be a non-empty array
|
|
15
|
-
* whose first element is the messenger action name; remaining elements are
|
|
16
|
-
* positional action arguments forwarded as-is to `messenger.call`.
|
|
17
|
-
*/
|
|
18
|
-
const callParamsStruct = (0, superstruct_1.define)('CallParams', (value) => {
|
|
19
|
-
if (!Array.isArray(value)) {
|
|
20
|
-
return 'Expected an array';
|
|
21
|
-
}
|
|
22
|
-
if (value.length === 0) {
|
|
23
|
-
return 'Expected a non-empty array';
|
|
24
|
-
}
|
|
25
|
-
if (typeof value[0] !== 'string') {
|
|
26
|
-
return 'Expected the first element to be a string action name';
|
|
27
|
-
}
|
|
28
|
-
return true;
|
|
29
|
-
});
|
|
30
10
|
const startTime = Date.now();
|
|
31
11
|
main().catch((error) => {
|
|
32
12
|
process.stderr.write(`Daemon fatal: ${String(error)}\n`);
|
|
@@ -41,22 +21,20 @@ async function main() {
|
|
|
41
21
|
if (!infuraProjectId) {
|
|
42
22
|
throw new Error('INFURA_PROJECT_ID environment variable is required');
|
|
43
23
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const srpRaw = process.env.MM_WALLET_SRP;
|
|
51
|
-
if (!srpRaw) {
|
|
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) {
|
|
52
30
|
throw new Error('MM_WALLET_SRP environment variable is required');
|
|
53
31
|
}
|
|
54
|
-
// Scrub
|
|
55
|
-
//
|
|
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.
|
|
56
36
|
delete process.env.MM_WALLET_PASSWORD;
|
|
57
37
|
delete process.env.MM_WALLET_SRP;
|
|
58
|
-
const password = passwordRaw ? secrets_1.Password.from(passwordRaw) : undefined;
|
|
59
|
-
const srp = secrets_1.Srp.from(srpRaw);
|
|
60
38
|
await (0, data_dir_1.ensureOwnerOnlyDirectory)(dataDir);
|
|
61
39
|
const { socketPath: defaultSocketPath, pidPath, logPath, dbPath, } = (0, paths_1.getDaemonPaths)(dataDir);
|
|
62
40
|
const socketPath = process.env.MM_DAEMON_SOCKET_PATH ?? defaultSocketPath;
|
|
@@ -95,27 +73,29 @@ async function main() {
|
|
|
95
73
|
log,
|
|
96
74
|
}));
|
|
97
75
|
const constructedWallet = wallet;
|
|
98
|
-
// Arbitrary messenger dispatch is intentional: the CLI exposes the full
|
|
99
|
-
// messenger surface over a Unix socket inside the per-user oclif data
|
|
100
|
-
// directory. The dataDir is chmodded to 0o700 above and the socket to
|
|
101
|
-
// 0o600 by the RPC server on bind, so only the owning user can open them,
|
|
102
|
-
// but there is no in-process auth check beyond that filesystem-permission
|
|
103
|
-
// barrier. The messenger is strongly typed by action name; we narrow it
|
|
104
|
-
// once here to the RpcDispatcher shape the `call` handler needs.
|
|
105
|
-
const dispatch = constructedWallet.messenger.call.bind(constructedWallet.messenger);
|
|
106
76
|
const handlers = {
|
|
107
|
-
getStatus:
|
|
77
|
+
getStatus: async () => ({
|
|
108
78
|
pid: process.pid,
|
|
109
79
|
uptime: Math.floor((Date.now() - startTime) / 1000),
|
|
110
|
-
})),
|
|
111
|
-
call: (0, types_1.defineHandler)(callParamsStruct, async (params) => {
|
|
112
|
-
const [action, ...args] = params;
|
|
113
|
-
return await dispatch(action, ...args);
|
|
114
80
|
}),
|
|
115
81
|
// Exposes the callable surface for discovery: it grows silently as
|
|
116
82
|
// controllers are wired, so consumers need a way to see it without a
|
|
117
83
|
// hand-kept catalog that would rot.
|
|
118
|
-
listActions:
|
|
84
|
+
listActions: async () => constructedWallet.messenger.getRegisteredActionTypes(),
|
|
85
|
+
// Arbitrary messenger dispatch is intentional: the CLI exposes the full
|
|
86
|
+
// messenger surface over a Unix socket inside the per-user oclif data
|
|
87
|
+
// directory. The dataDir is chmodded to 0o700 above and the socket to
|
|
88
|
+
// 0o600 by the RPC server on bind, so only the owning user can open
|
|
89
|
+
// them, but there is no in-process auth check beyond that
|
|
90
|
+
// filesystem-permission barrier.
|
|
91
|
+
call: async (params) => {
|
|
92
|
+
if (!Array.isArray(params) || typeof params[0] !== 'string') {
|
|
93
|
+
throw new Error('Expected params to be an array with an action name');
|
|
94
|
+
}
|
|
95
|
+
const [action, ...args] = params;
|
|
96
|
+
const result = constructedWallet.messenger.call(action, ...args);
|
|
97
|
+
return (result instanceof Promise ? await result : result);
|
|
98
|
+
},
|
|
119
99
|
};
|
|
120
100
|
// `startRpcSocketServer` restricts the socket to the owner (chmod 0o600)
|
|
121
101
|
// on bind and never leaves a live server/socket behind if it rejects, so
|
|
@@ -162,12 +142,7 @@ async function main() {
|
|
|
162
142
|
catch (closeError) {
|
|
163
143
|
log(`handle.close() failed: ${String(closeError)}`);
|
|
164
144
|
}
|
|
165
|
-
|
|
166
|
-
await activeDispose();
|
|
167
|
-
}
|
|
168
|
-
catch (disposeError) {
|
|
169
|
-
log(`dispose() failed during shutdown: ${String(disposeError)}`);
|
|
170
|
-
}
|
|
145
|
+
await activeDispose();
|
|
171
146
|
await Promise.all([
|
|
172
147
|
removeOwnedPidFile(pidPath, pidFileContents).catch((rmError) => {
|
|
173
148
|
log(`Failed to remove PID file: ${String(rmError)}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"daemon-entry.cjs","sourceRoot":"","sources":["../../src/daemon/daemon-entry.ts"],"names":[],"mappings":";;AAAA,uDAAwD;AAGxD,+CAAuE;AAEvE,uDAA6C;AAC7C,6CAAsD;AACtD,uCAAyC;AACzC,+DAA2D;AAE3D,2CAA0C;AAC1C,uCAAwC;AAOxC,uCAAuE;AACvE,yDAAgD;AAEhD;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,IAAA,oBAAM,EAC7B,YAAY,EACZ,CAAC,KAAK,EAAE,EAAE;IACR,IA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E,CAAC;KAChC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,kBAAkB,CAC/B,OAAe,EACf,gBAAwB;IAExB,IAAI,MAAc,CAAC;IACnB,IAAI,CAAC;QACH,MAAM,GAAG,MAAM,IAAA,mBAAQ,EAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,IAAA,uBAAe,EAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YACrC,OAAO;QACT,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IACD,IAAI,MAAM,KAAK,gBAAgB,EAAE,CAAC;QAChC,MAAM,IAAA,aAAE,EAAC,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,IAAA,qBAAU,EAAC,OAAO,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACjD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,sBAAsB,MAAM,CAAC,KAAK,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC;QAC5E,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { define, literal } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport type { Wallet } from '@metamask/wallet';\nimport { appendFile, readFile, rm, writeFile } from 'node:fs/promises';\n\nimport { pingDaemon } from './daemon-client';\nimport { ensureOwnerOnlyDirectory } from './data-dir';\nimport { getDaemonPaths } from './paths';\nimport { startRpcSocketServer } from './rpc-socket-server';\nimport type { RpcSocketServerHandle } from './rpc-socket-server';\nimport { Password, Srp } from './secrets';\nimport { defineHandler } from './types';\nimport type {\n DaemonStatusInfo,\n Logger,\n RpcDispatcher,\n RpcHandlerMap,\n} from './types';\nimport { isErrorWithCode, isProcessAlive, readPidFile } from './utils';\nimport { createWallet } from './wallet-factory';\n\n/**\n * Params struct for the `call` RPC method. `params` must be a non-empty array\n * whose first element is the messenger action name; remaining elements are\n * positional action arguments forwarded as-is to `messenger.call`.\n */\nconst callParamsStruct = define<[string, ...unknown[]]>(\n 'CallParams',\n (value) => {\n if (!Array.isArray(value)) {\n return 'Expected an array';\n }\n if (value.length === 0) {\n return 'Expected a non-empty array';\n }\n if (typeof value[0] !== 'string') {\n return 'Expected the first element to be a string action name';\n }\n return true;\n },\n);\n\nconst startTime = Date.now();\n\nmain().catch((error: unknown) => {\n process.stderr.write(`Daemon fatal: ${String(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const dataDir = process.env.MM_DAEMON_DATA_DIR;\n if (!dataDir) {\n throw new Error('MM_DAEMON_DATA_DIR environment variable is required');\n }\n\n const infuraProjectId = process.env.INFURA_PROJECT_ID;\n if (!infuraProjectId) {\n throw new Error('INFURA_PROJECT_ID environment variable is required');\n }\n\n // Password is optional: when absent, the daemon starts without unlocking\n // the keyring (e.g. when the user prefers to call `mm wallet unlock`\n // interactively rather than embed the password in their environment).\n // First-run startup still requires a password; wallet-factory enforces\n // that and surfaces a clear error.\n const passwordRaw = process.env.MM_WALLET_PASSWORD;\n\n const srpRaw = process.env.MM_WALLET_SRP;\n if (!srpRaw) {\n throw new Error('MM_WALLET_SRP environment variable is required');\n }\n\n // Scrub before validation so a throw from Password.from / Srp.from (bad\n // value) does not leave the raw secrets in the long-lived daemon's env.\n delete process.env.MM_WALLET_PASSWORD;\n delete process.env.MM_WALLET_SRP;\n\n const password = passwordRaw ? Password.from(passwordRaw) : undefined;\n const srp = Srp.from(srpRaw);\n\n await ensureOwnerOnlyDirectory(dataDir);\n\n const {\n socketPath: defaultSocketPath,\n pidPath,\n logPath,\n dbPath,\n } = getDaemonPaths(dataDir);\n const socketPath = process.env.MM_DAEMON_SOCKET_PATH ?? defaultSocketPath;\n\n const log = makeLogger(logPath);\n log('Starting daemon...');\n\n // Pre-flight: refuse to take over if a responsive daemon already owns this\n // socket. If the existing PID file is stale (or the socket is dead), clean\n // it up so the exclusive PID-file write below has a chance to succeed.\n await claimDaemonSlot(pidPath, socketPath, log);\n\n const pidFileContents = `${process.pid}\\n${startTime}\\n`;\n\n // Claim the slot atomically BEFORE opening the SQLite database or\n // constructing the Wallet. Two concurrent `daemon start` invocations can\n // both pass `claimDaemonSlot` (the gap between its preflight and the slot\n // write is racy); without this ordering, both would open `wallet.db` and\n // both would run first-run SRP import before one loses the wx race.\n try {\n await writeFile(pidPath, pidFileContents, { flag: 'wx' });\n } catch (error) {\n throw error instanceof Error\n ? Object.assign(error, {\n message: `Failed to claim daemon slot at ${pidPath}: ${error.message}`,\n })\n : /* istanbul ignore next -- node:fs/promises always rejects with an Error */\n new Error(\n `Failed to claim daemon slot at ${pidPath}: ${String(error)}`,\n );\n }\n\n let wallet: Wallet | undefined;\n let dispose: (() => Promise<void>) | undefined;\n let handle: RpcSocketServerHandle | undefined;\n\n try {\n ({ wallet, dispose } = await createWallet({\n databasePath: dbPath,\n password,\n srp,\n infuraProjectId,\n log,\n }));\n\n const constructedWallet = wallet;\n // Arbitrary messenger dispatch is intentional: the CLI exposes the full\n // messenger surface over a Unix socket inside the per-user oclif data\n // directory. The dataDir is chmodded to 0o700 above and the socket to\n // 0o600 by the RPC server on bind, so only the owning user can open them,\n // but there is no in-process auth check beyond that filesystem-permission\n // barrier. The messenger is strongly typed by action name; we narrow it\n // once here to the RpcDispatcher shape the `call` handler needs.\n const dispatch = constructedWallet.messenger.call.bind(\n constructedWallet.messenger,\n ) as unknown as RpcDispatcher;\n\n const handlers: RpcHandlerMap = {\n getStatus: defineHandler(\n literal(null),\n async (): Promise<DaemonStatusInfo> => ({\n pid: process.pid,\n uptime: Math.floor((Date.now() - startTime) / 1000),\n }),\n ),\n call: defineHandler(callParamsStruct, async (params) => {\n const [action, ...args] = params;\n return await dispatch(action, ...(args as Json[]));\n }),\n // Exposes the callable surface for discovery: it grows silently as\n // controllers are wired, so consumers need a way to see it without a\n // hand-kept catalog that would rot.\n listActions: defineHandler(\n literal(null),\n async (): Promise<Json> =>\n constructedWallet.messenger.getRegisteredActionTypes(),\n ),\n };\n\n // `startRpcSocketServer` restricts the socket to the owner (chmod 0o600)\n // on bind and never leaves a live server/socket behind if it rejects, so\n // the catch below has nothing of its own to close.\n handle = await startRpcSocketServer({\n socketPath,\n handlers,\n onShutdown: async () => shutdown('RPC shutdown'),\n log,\n });\n } catch (error) {\n // `dispose` is undefined only when `createWallet` itself threw — it has\n // already torn down its own store in that case.\n if (dispose) {\n await dispose();\n }\n // Only remove the PID file if it's still ours (we may have lost the race\n // and the file now belongs to another daemon).\n await removeOwnedPidFile(pidPath, pidFileContents).catch(\n (rmError: unknown) => {\n log(`Failed to remove PID file during cleanup: ${String(rmError)}`);\n },\n );\n throw error;\n }\n\n // Stable non-undefined refs for the shutdown closures (TS won't narrow the\n // outer `let`s across closure escape).\n const activeHandle = handle;\n const activeDispose = dispose;\n\n log(`Daemon started. Socket: ${socketPath}`);\n\n let shutdownPromise: Promise<void> | undefined;\n\n /**\n * Shut down the daemon idempotently. Concurrent calls coalesce.\n *\n * @param reason - A label describing why shutdown was triggered.\n * @returns A promise that resolves when shutdown completes.\n */\n async function shutdown(reason: string): Promise<void> {\n if (shutdownPromise === undefined) {\n log(`Shutting down (${reason})...`);\n shutdownPromise = (async (): Promise<void> => {\n try {\n await activeHandle.close();\n } catch (closeError) {\n log(`handle.close() failed: ${String(closeError)}`);\n }\n try {\n await activeDispose();\n } catch (disposeError) {\n log(`dispose() failed during shutdown: ${String(disposeError)}`);\n }\n await Promise.all([\n removeOwnedPidFile(pidPath, pidFileContents).catch(\n (rmError: unknown) => {\n log(`Failed to remove PID file: ${String(rmError)}`);\n },\n ),\n rm(socketPath, { force: true }).catch((rmError: unknown) => {\n log(`Failed to remove socket file: ${String(rmError)}`);\n }),\n ]);\n })();\n }\n return shutdownPromise;\n }\n\n process.on('SIGTERM', () => {\n /* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */\n shutdown('SIGTERM').catch(() => undefined);\n });\n process.on('SIGINT', () => {\n /* istanbul ignore next -- `shutdown` logs each step internally; the catch only guards against an unhandled rejection from the signal handler. */\n shutdown('SIGINT').catch(() => undefined);\n });\n}\n\n/**\n * Refuse to start if a responsive daemon already owns the socket. Otherwise\n * clear any stale PID/socket files so the exclusive PID-file write can\n * proceed.\n *\n * @param pidPath - The PID file path.\n * @param socketPath - The socket path.\n * @param log - Logger for diagnostic messages.\n */\nasync function claimDaemonSlot(\n pidPath: string,\n socketPath: string,\n log: Logger,\n): Promise<void> {\n const existingPid = await readPidFile(pidPath);\n const ping = await pingDaemon(socketPath);\n\n if (ping.status === 'responsive') {\n const pidPart =\n existingPid === undefined\n ? '(no PID file present)'\n : `(pid ${existingPid})`;\n throw new Error(`A daemon is already running on ${socketPath} ${pidPart}`);\n }\n\n // Refuse to clobber when the recorded PID is still alive, regardless of\n // whether the socket exists. Possible scenarios:\n // - `unreachable`: wedged or mid-startup sibling daemon (socket present\n // but not responding to JSON-RPC).\n // - `absent`: a sibling daemon that hasn't yet bound its socket, or one\n // whose socket was manually removed. In either case, removing its PID\n // file would orphan it from `daemon stop`.\n if (existingPid !== undefined && isProcessAlive(existingPid)) {\n const detail =\n ping.status === 'unreachable'\n ? `socket at ${socketPath} is unresponsive (${ping.error.message})`\n : `no socket at ${socketPath}, but pid is still alive`;\n throw new Error(\n `A daemon is already running (pid ${existingPid}): ${detail}. ` +\n `Run \\`mm daemon stop\\` (or \\`mm daemon purge\\`) before starting a new daemon.`,\n );\n }\n\n if (ping.status === 'unreachable') {\n log(`Removing stale socket at ${socketPath} (${ping.error.message}).`);\n }\n // Always clear both files before claiming the slot. The PID file may be\n // corrupt (truncated, partial write from a crashed run); without this, the\n // exclusive `wx` write below would fail with EEXIST and the daemon could\n // not start until a human manually deleted the file.\n await Promise.all([\n rm(pidPath, { force: true }),\n rm(socketPath, { force: true }),\n ]);\n}\n\n/**\n * Remove the PID file only if it still contains our exact contents. Guards\n * against a racing daemon's PID file being removed by this daemon during\n * cleanup.\n *\n * @param pidPath - Path to the PID file.\n * @param expectedContents - The contents we wrote when claiming the slot.\n */\nasync function removeOwnedPidFile(\n pidPath: string,\n expectedContents: string,\n): Promise<void> {\n let actual: string;\n try {\n actual = await readFile(pidPath, 'utf-8');\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ENOENT')) {\n return;\n }\n throw error;\n }\n if (actual === expectedContents) {\n await rm(pidPath, { force: true });\n }\n}\n\n/**\n * Create a file logger that appends timestamped lines to `logPath`, falling\n * back to stderr if the append fails.\n *\n * @param logPath - The log file path.\n * @returns A logging function.\n */\nfunction makeLogger(logPath: string): Logger {\n return (message: string): void => {\n const line = `[${new Date().toISOString()}] ${message}\\n`;\n appendFile(logPath, line).catch((error: unknown) => {\n process.stderr.write(`[log write failed: ${String(error)}] ${message}\\n`);\n });\n };\n}\n"]}
|
|
1
|
+
{"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,CAAC;IACzD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC;AAEH,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AAM,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"]}
|
|
@@ -1,30 +1,10 @@
|
|
|
1
|
-
import { define, literal } from "@metamask/superstruct";
|
|
2
1
|
import { appendFile, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
2
|
import { pingDaemon } from "./daemon-client.mjs";
|
|
4
3
|
import { ensureOwnerOnlyDirectory } from "./data-dir.mjs";
|
|
5
4
|
import { getDaemonPaths } from "./paths.mjs";
|
|
6
5
|
import { startRpcSocketServer } from "./rpc-socket-server.mjs";
|
|
7
|
-
import { Password, Srp } from "./secrets.mjs";
|
|
8
|
-
import { defineHandler } from "./types.mjs";
|
|
9
6
|
import { isErrorWithCode, isProcessAlive, readPidFile } from "./utils.mjs";
|
|
10
7
|
import { createWallet } from "./wallet-factory.mjs";
|
|
11
|
-
/**
|
|
12
|
-
* Params struct for the `call` RPC method. `params` must be a non-empty array
|
|
13
|
-
* whose first element is the messenger action name; remaining elements are
|
|
14
|
-
* positional action arguments forwarded as-is to `messenger.call`.
|
|
15
|
-
*/
|
|
16
|
-
const callParamsStruct = define('CallParams', (value) => {
|
|
17
|
-
if (!Array.isArray(value)) {
|
|
18
|
-
return 'Expected an array';
|
|
19
|
-
}
|
|
20
|
-
if (value.length === 0) {
|
|
21
|
-
return 'Expected a non-empty array';
|
|
22
|
-
}
|
|
23
|
-
if (typeof value[0] !== 'string') {
|
|
24
|
-
return 'Expected the first element to be a string action name';
|
|
25
|
-
}
|
|
26
|
-
return true;
|
|
27
|
-
});
|
|
28
8
|
const startTime = Date.now();
|
|
29
9
|
main().catch((error) => {
|
|
30
10
|
process.stderr.write(`Daemon fatal: ${String(error)}\n`);
|
|
@@ -39,22 +19,20 @@ async function main() {
|
|
|
39
19
|
if (!infuraProjectId) {
|
|
40
20
|
throw new Error('INFURA_PROJECT_ID environment variable is required');
|
|
41
21
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const srpRaw = process.env.MM_WALLET_SRP;
|
|
49
|
-
if (!srpRaw) {
|
|
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) {
|
|
50
28
|
throw new Error('MM_WALLET_SRP environment variable is required');
|
|
51
29
|
}
|
|
52
|
-
// Scrub
|
|
53
|
-
//
|
|
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.
|
|
54
34
|
delete process.env.MM_WALLET_PASSWORD;
|
|
55
35
|
delete process.env.MM_WALLET_SRP;
|
|
56
|
-
const password = passwordRaw ? Password.from(passwordRaw) : undefined;
|
|
57
|
-
const srp = Srp.from(srpRaw);
|
|
58
36
|
await ensureOwnerOnlyDirectory(dataDir);
|
|
59
37
|
const { socketPath: defaultSocketPath, pidPath, logPath, dbPath, } = getDaemonPaths(dataDir);
|
|
60
38
|
const socketPath = process.env.MM_DAEMON_SOCKET_PATH ?? defaultSocketPath;
|
|
@@ -93,27 +71,29 @@ async function main() {
|
|
|
93
71
|
log,
|
|
94
72
|
}));
|
|
95
73
|
const constructedWallet = wallet;
|
|
96
|
-
// Arbitrary messenger dispatch is intentional: the CLI exposes the full
|
|
97
|
-
// messenger surface over a Unix socket inside the per-user oclif data
|
|
98
|
-
// directory. The dataDir is chmodded to 0o700 above and the socket to
|
|
99
|
-
// 0o600 by the RPC server on bind, so only the owning user can open them,
|
|
100
|
-
// but there is no in-process auth check beyond that filesystem-permission
|
|
101
|
-
// barrier. The messenger is strongly typed by action name; we narrow it
|
|
102
|
-
// once here to the RpcDispatcher shape the `call` handler needs.
|
|
103
|
-
const dispatch = constructedWallet.messenger.call.bind(constructedWallet.messenger);
|
|
104
74
|
const handlers = {
|
|
105
|
-
getStatus:
|
|
75
|
+
getStatus: async () => ({
|
|
106
76
|
pid: process.pid,
|
|
107
77
|
uptime: Math.floor((Date.now() - startTime) / 1000),
|
|
108
|
-
})),
|
|
109
|
-
call: defineHandler(callParamsStruct, async (params) => {
|
|
110
|
-
const [action, ...args] = params;
|
|
111
|
-
return await dispatch(action, ...args);
|
|
112
78
|
}),
|
|
113
79
|
// Exposes the callable surface for discovery: it grows silently as
|
|
114
80
|
// controllers are wired, so consumers need a way to see it without a
|
|
115
81
|
// hand-kept catalog that would rot.
|
|
116
|
-
listActions:
|
|
82
|
+
listActions: async () => constructedWallet.messenger.getRegisteredActionTypes(),
|
|
83
|
+
// Arbitrary messenger dispatch is intentional: the CLI exposes the full
|
|
84
|
+
// messenger surface over a Unix socket inside the per-user oclif data
|
|
85
|
+
// directory. The dataDir is chmodded to 0o700 above and the socket to
|
|
86
|
+
// 0o600 by the RPC server on bind, so only the owning user can open
|
|
87
|
+
// them, but there is no in-process auth check beyond that
|
|
88
|
+
// filesystem-permission barrier.
|
|
89
|
+
call: async (params) => {
|
|
90
|
+
if (!Array.isArray(params) || typeof params[0] !== 'string') {
|
|
91
|
+
throw new Error('Expected params to be an array with an action name');
|
|
92
|
+
}
|
|
93
|
+
const [action, ...args] = params;
|
|
94
|
+
const result = constructedWallet.messenger.call(action, ...args);
|
|
95
|
+
return (result instanceof Promise ? await result : result);
|
|
96
|
+
},
|
|
117
97
|
};
|
|
118
98
|
// `startRpcSocketServer` restricts the socket to the owner (chmod 0o600)
|
|
119
99
|
// on bind and never leaves a live server/socket behind if it rejects, so
|
|
@@ -160,12 +140,7 @@ async function main() {
|
|
|
160
140
|
catch (closeError) {
|
|
161
141
|
log(`handle.close() failed: ${String(closeError)}`);
|
|
162
142
|
}
|
|
163
|
-
|
|
164
|
-
await activeDispose();
|
|
165
|
-
}
|
|
166
|
-
catch (disposeError) {
|
|
167
|
-
log(`dispose() failed during shutdown: ${String(disposeError)}`);
|
|
168
|
-
}
|
|
143
|
+
await activeDispose();
|
|
169
144
|
await Promise.all([
|
|
170
145
|
removeOwnedPidFile(pidPath, pidFileContents).catch((rmError) => {
|
|
171
146
|
log(`Failed to remove PID file: ${String(rmError)}`);
|