@did-btcr2/cli 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +95 -14
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/cjs/index.js +674 -54
  4. package/dist/esm/src/cli.js +25 -3
  5. package/dist/esm/src/cli.js.map +1 -1
  6. package/dist/esm/src/commands/config.js +124 -8
  7. package/dist/esm/src/commands/config.js.map +1 -1
  8. package/dist/esm/src/commands/create.js +10 -1
  9. package/dist/esm/src/commands/create.js.map +1 -1
  10. package/dist/esm/src/commands/deactivate.js +33 -6
  11. package/dist/esm/src/commands/deactivate.js.map +1 -1
  12. package/dist/esm/src/commands/profile.js +5 -3
  13. package/dist/esm/src/commands/profile.js.map +1 -1
  14. package/dist/esm/src/commands/update.js +33 -6
  15. package/dist/esm/src/commands/update.js.map +1 -1
  16. package/dist/esm/src/config-schema.js +149 -0
  17. package/dist/esm/src/config-schema.js.map +1 -0
  18. package/dist/esm/src/config.js +515 -35
  19. package/dist/esm/src/config.js.map +1 -1
  20. package/dist/esm/src/keystore/paths.js +3 -2
  21. package/dist/esm/src/keystore/paths.js.map +1 -1
  22. package/dist/esm/src/output.js +49 -0
  23. package/dist/esm/src/output.js.map +1 -1
  24. package/dist/esm/src/types.js +11 -0
  25. package/dist/esm/src/types.js.map +1 -1
  26. package/dist/types/src/cli.d.ts.map +1 -1
  27. package/dist/types/src/commands/config.d.ts.map +1 -1
  28. package/dist/types/src/commands/create.d.ts.map +1 -1
  29. package/dist/types/src/commands/deactivate.d.ts.map +1 -1
  30. package/dist/types/src/commands/profile.d.ts.map +1 -1
  31. package/dist/types/src/commands/update.d.ts.map +1 -1
  32. package/dist/types/src/config-schema.d.ts +24 -0
  33. package/dist/types/src/config-schema.d.ts.map +1 -0
  34. package/dist/types/src/config.d.ts +228 -6
  35. package/dist/types/src/config.d.ts.map +1 -1
  36. package/dist/types/src/keystore/paths.d.ts.map +1 -1
  37. package/dist/types/src/output.d.ts +22 -0
  38. package/dist/types/src/output.d.ts.map +1 -1
  39. package/dist/types/src/types.d.ts +33 -0
  40. package/dist/types/src/types.d.ts.map +1 -1
  41. package/package.json +4 -4
  42. package/src/cli.ts +27 -3
  43. package/src/commands/config.ts +135 -8
  44. package/src/commands/create.ts +13 -1
  45. package/src/commands/deactivate.ts +53 -6
  46. package/src/commands/profile.ts +5 -3
  47. package/src/commands/update.ts +53 -6
  48. package/src/config-schema.ts +178 -0
  49. package/src/config.ts +693 -43
  50. package/src/keystore/paths.ts +3 -2
  51. package/src/output.ts +53 -0
  52. package/src/types.ts +23 -0
@@ -1,4 +1,5 @@
1
- import { createApi, Identifier } from '@did-btcr2/api';
1
+ import { createApi, DEFAULT_BITCOIN_NETWORK_CONFIG, DEFAULT_CAS_GATEWAY, Identifier } from '@did-btcr2/api';
2
+ import { StaticFeeEstimator } from '@did-btcr2/method';
2
3
  import { readFileSync } from 'node:fs';
3
4
  import { homedir } from 'node:os';
4
5
  import { dirname, join } from 'node:path';
@@ -7,13 +8,18 @@ import { ensureDir, writeFileAtomic } from './keystore/atomic.js';
7
8
  import { FileBackedKeyManager } from './keystore/file-backed-key-manager.js';
8
9
  import { defaultKeystorePath } from './keystore/paths.js';
9
10
  import { acquirePassphrase } from './keystore/passphrase.js';
10
- import { SUPPORTED_NETWORKS } from './types.js';
11
+ import { blankToUndef, SUPPORTED_NETWORKS } from './types.js';
11
12
  /** Current config-file schema version, stamped on every write. */
12
13
  export const CONFIG_SCHEMA_VERSION = 1;
13
14
  /**
14
15
  * Read-modify-write a config file, preserving unknown keys. Reads the raw JSON
15
16
  * (so keys outside {@link ConfigFile} survive a rewrite), applies `mutate`,
16
17
  * stamps the schema version, and writes atomically (file 0600, dir 0700).
18
+ *
19
+ * A file that exists but cannot be parsed makes {@link readConfigFile} throw, so
20
+ * a write never starts from `{}` over a malformed-but-recoverable file and can
21
+ * never clobber the other profiles and defaults it still holds. A genuinely
22
+ * absent file (ENOENT) still starts from `{}`.
17
23
  */
18
24
  export function writeConfigFile(path, mutate) {
19
25
  const raw = readConfigFile(path) ?? {};
@@ -26,9 +32,18 @@ export function writeConfigFile(path, mutate) {
26
32
  export function getConfigPath(config, path) {
27
33
  return path.split('.').reduce((node, key) => node?.[key], config);
28
34
  }
35
+ /** Dotted-path segments that would let a write reach the prototype chain. */
36
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
37
+ /** Rejects a path segment that would let a `config set`/`unset` reach the prototype chain. */
38
+ function assertSafeKey(key, path) {
39
+ if (UNSAFE_KEYS.has(key)) {
40
+ throw new CLIError(`Illegal config path segment "${key}" in "${path}".`, 'INVALID_ARGUMENT_ERROR', { path, key });
41
+ }
42
+ }
29
43
  /** Sets the value at a dotted path, creating intermediate objects. */
30
44
  export function setConfigPath(config, path, value) {
31
45
  const keys = path.split('.');
46
+ keys.forEach(key => assertSafeKey(key, path));
32
47
  const last = keys.pop();
33
48
  if (!last)
34
49
  throw new CLIError('Config path must be non-empty.', 'INVALID_ARGUMENT_ERROR');
@@ -43,6 +58,7 @@ export function setConfigPath(config, path, value) {
43
58
  /** Deletes the value at a dotted path. No-op if the path does not exist. */
44
59
  export function unsetConfigPath(config, path) {
45
60
  const keys = path.split('.');
61
+ keys.forEach(key => assertSafeKey(key, path));
46
62
  const last = keys.pop();
47
63
  if (!last)
48
64
  return;
@@ -64,6 +80,10 @@ export function unsetConfigPath(config, path) {
64
80
  * | `BTCR2_BTC_RPC_USER` | `--btc-rpc-user` |
65
81
  * | `BTCR2_BTC_RPC_PASS` | `--btc-rpc-pass` |
66
82
  * | `BTCR2_CAS_GATEWAY` | `--cas-gateway` |
83
+ * | `BTCR2_CAS_RPC_URL` | `--cas-rpc-url` |
84
+ * | `BTCR2_BTC_TIMEOUT` | `--btc-timeout` |
85
+ * | `BTCR2_CAS_TIMEOUT` | `--cas-timeout` |
86
+ * | `BTCR2_FEE_RATE` | `--fee-rate` |
67
87
  */
68
88
  export const ENV_VARS = {
69
89
  BTC_REST: 'BTCR2_BTC_REST',
@@ -71,6 +91,10 @@ export const ENV_VARS = {
71
91
  BTC_RPC_USER: 'BTCR2_BTC_RPC_USER',
72
92
  BTC_RPC_PASS: 'BTCR2_BTC_RPC_PASS',
73
93
  CAS_GATEWAY: 'BTCR2_CAS_GATEWAY',
94
+ CAS_RPC_URL: 'BTCR2_CAS_RPC_URL',
95
+ BTC_TIMEOUT: 'BTCR2_BTC_TIMEOUT',
96
+ CAS_TIMEOUT: 'BTCR2_CAS_TIMEOUT',
97
+ FEE_RATE: 'BTCR2_FEE_RATE',
74
98
  };
75
99
  /**
76
100
  * Reads {@link ConnectionOverrides} from environment variables.
@@ -84,6 +108,7 @@ export function readEnvOverrides() {
84
108
  btcRpcUser: env(ENV_VARS.BTC_RPC_USER),
85
109
  btcRpcPass: env(ENV_VARS.BTC_RPC_PASS),
86
110
  casGateway: env(ENV_VARS.CAS_GATEWAY),
111
+ casRpcUrl: env(ENV_VARS.CAS_RPC_URL),
87
112
  };
88
113
  }
89
114
  /**
@@ -95,22 +120,64 @@ export function readEnvOverrides() {
95
120
  * 3. `~/.config/btcr2/config.json` (fallback)
96
121
  */
97
122
  export function defaultConfigPath() {
98
- const base = process.env.XDG_CONFIG_HOME
99
- ?? process.env.APPDATA
123
+ const base = blankToUndef(process.env.XDG_CONFIG_HOME)
124
+ ?? blankToUndef(process.env.APPDATA)
100
125
  ?? join(homedir(), '.config');
101
126
  return join(base, 'btcr2', 'config.json');
102
127
  }
103
128
  /**
104
- * Reads and parses a config file. Returns `undefined` if the file does
105
- * not exist or cannot be parsed.
129
+ * Reads and JSON-parses a config file without applying the schema-version
130
+ * ceiling check. Returns `undefined` only for a genuinely absent file (ENOENT).
131
+ * Any other read failure, and any JSON parse failure, throws a {@link CLIError}
132
+ * that names the file. Used by `config validate`, which reports a newer-than-
133
+ * supported `schemaVersion` as a finding rather than aborting on it.
106
134
  */
107
- export function readConfigFile(path) {
135
+ export function parseConfigFileRaw(path) {
136
+ let content;
137
+ try {
138
+ content = readFileSync(path, 'utf-8');
139
+ }
140
+ catch (error) {
141
+ if (error.code === 'ENOENT')
142
+ return undefined;
143
+ throw new CLIError(`Failed to read config file at ${path}: ${error.message}`, 'CONFIG_READ_ERROR', { path });
144
+ }
108
145
  try {
109
- const content = readFileSync(path, 'utf-8');
110
146
  return JSON.parse(content);
111
147
  }
112
- catch {
148
+ catch (error) {
149
+ throw new CLIError(`Config file at ${path} is not valid JSON: ${error.message}. `
150
+ + 'Fix the file by hand; the CLI will not overwrite it while it is unparseable.', 'CONFIG_PARSE_ERROR', { path });
151
+ }
152
+ }
153
+ /**
154
+ * Reads and parses a config file. Returns `undefined` only when the file is
155
+ * genuinely absent (ENOENT), so callers can safely treat "no file" as "use
156
+ * defaults". Any other read failure, and any JSON parse failure, throws a
157
+ * {@link CLIError} that names the file, rather than silently degrading to the
158
+ * public network defaults. A file written by a newer CLI (higher `schemaVersion`)
159
+ * is also refused.
160
+ */
161
+ export function readConfigFile(path) {
162
+ const parsed = parseConfigFileRaw(path);
163
+ if (parsed === undefined)
113
164
  return undefined;
165
+ migrateConfigShape(parsed, path);
166
+ return parsed;
167
+ }
168
+ /**
169
+ * Validates a parsed config's `schemaVersion` against {@link CONFIG_SCHEMA_VERSION}
170
+ * and brings an older shape up to the current version in place. A file written by
171
+ * a newer CLI is refused so today's assumptions are never applied blindly to an
172
+ * unknown shape. An absent version is treated as the earliest and migrated
173
+ * forward. No structural migrations are registered yet (the schema is at version
174
+ * 1); future versions register their transforms here in ascending order.
175
+ */
176
+ function migrateConfigShape(raw, path) {
177
+ const version = typeof raw.schemaVersion === 'number' ? raw.schemaVersion : 0;
178
+ if (version > CONFIG_SCHEMA_VERSION) {
179
+ throw new CLIError(`Config file at ${path} has schemaVersion ${version}, but this CLI supports up to `
180
+ + `${CONFIG_SCHEMA_VERSION}. Upgrade the btcr2 CLI to read it.`, 'CONFIG_SCHEMA_VERSION_ERROR', { path, fileVersion: version, supported: CONFIG_SCHEMA_VERSION });
114
181
  }
115
182
  }
116
183
  /**
@@ -127,13 +194,35 @@ export function profileToOverrides(config, profileName) {
127
194
  btcRpcUser: profile.btc?.rpcUser,
128
195
  btcRpcPass: profile.btc?.rpcPass,
129
196
  casGateway: profile.cas?.gateway,
197
+ casRpcUrl: profile.cas?.rpcUrl,
130
198
  };
131
199
  }
200
+ /**
201
+ * Resolves the active profile name and the network it targets, shared by
202
+ * {@link resolveDefaultNetwork} and {@link resolveConnectionConfig} so the two
203
+ * can never disagree about which profile is active or which network it means.
204
+ *
205
+ * The active profile name is the explicit `--profile` flag, else the config
206
+ * file's `defaults.profile`. The network is the profile's own `network` field
207
+ * when set to a supported value, else the profile name itself when it is a
208
+ * network name (the historical convention). A profile that declares no network
209
+ * and is not named after one yields `network: undefined`.
210
+ */
211
+ export function resolveActiveProfile(file, overrides) {
212
+ const name = blankToUndef(overrides?.profile) ?? file?.defaults?.profile;
213
+ if (!name)
214
+ return { name: undefined, network: undefined };
215
+ const declared = file?.profiles?.[name]?.network;
216
+ const network = (declared && SUPPORTED_NETWORKS.includes(declared))
217
+ ? declared
218
+ : (SUPPORTED_NETWORKS.includes(name) ? name : undefined);
219
+ return { name, network };
220
+ }
132
221
  /**
133
222
  * Resolves the default Bitcoin network for offline identifier creation when no
134
223
  * `--network` flag is given. Resolution order: the config file's
135
- * `defaults.network`, then an active profile named for a network (an explicit
136
- * `--profile` flag or `defaults.profile`), then `regtest` as the development
224
+ * `defaults.network`, then the active profile's network (its explicit `network`
225
+ * field, else its network-derived name), then `regtest` as the development
137
226
  * fallback. Generation itself is offline; this only fixes which network the
138
227
  * identifier encodes.
139
228
  */
@@ -143,12 +232,83 @@ export function resolveDefaultNetwork(overrides) {
143
232
  const explicit = file?.defaults?.network;
144
233
  if (explicit && SUPPORTED_NETWORKS.includes(explicit))
145
234
  return explicit;
146
- const profile = overrides?.profile ?? file?.defaults?.profile;
147
- if (profile && SUPPORTED_NETWORKS.includes(profile)) {
148
- return profile;
149
- }
235
+ const { network } = resolveActiveProfile(file, overrides);
236
+ if (network)
237
+ return network;
150
238
  return 'regtest';
151
239
  }
240
+ /**
241
+ * Reports a coherence conflict between the network a `create` run is about to
242
+ * encode and the network the active profile declares, so the CLI can warn
243
+ * instead of silently minting an identifier on one network while wiring
244
+ * endpoints for another. Returns `undefined` when the active profile declares
245
+ * no network or agrees with the one being encoded.
246
+ */
247
+ export function profileNetworkMismatch(network, overrides) {
248
+ // This drives only a warning, so a malformed config must not break an otherwise
249
+ // offline `create`; a genuinely broken config is still surfaced loudly by any
250
+ // command that actually resolves a connection.
251
+ let file;
252
+ try {
253
+ file = readConfigFile(overrides?.config ?? defaultConfigPath());
254
+ }
255
+ catch {
256
+ return undefined;
257
+ }
258
+ const { name, network: declared } = resolveActiveProfile(file, overrides);
259
+ if (name && declared && declared !== network)
260
+ return { profile: name, declared };
261
+ return undefined;
262
+ }
263
+ /**
264
+ * Resolves the effective output format: the `-o/--output` flag, then the
265
+ * `BTCR2_OUTPUT` environment variable, then the config file's `defaults.output`,
266
+ * then `'text'`. A malformed config never blocks output resolution (the command's
267
+ * own read path surfaces it); output format falls back to `'text'` instead.
268
+ */
269
+ export function resolveOutputFormat(options) {
270
+ const candidates = [
271
+ blankToUndef(options.output),
272
+ process.env.BTCR2_OUTPUT || undefined,
273
+ ];
274
+ try {
275
+ candidates.push(readConfigFile(options.config ?? defaultConfigPath())?.defaults?.output);
276
+ }
277
+ catch {
278
+ // Output format is cosmetic; a broken config is reported by the command
279
+ // itself rather than aborting here (which would block a recovery command).
280
+ }
281
+ for (const candidate of candidates) {
282
+ if (candidate === 'json' || candidate === 'text')
283
+ return candidate;
284
+ }
285
+ return 'text';
286
+ }
287
+ /**
288
+ * Resolves the RPC credential unit atomically: the highest-precedence layer that
289
+ * supplies a url, else the highest that supplies a username or password. url,
290
+ * user, and pass therefore always come from one layer, so a host from one layer
291
+ * is never handed another layer's credentials (ADR 074). When no layer supplies a
292
+ * url, the credentials still resolve (so they reach the SDK's per-network default
293
+ * host, e.g. regtest's, without the url being restated). Returns `undefined` when
294
+ * no layer supplies a url or a credential.
295
+ */
296
+ function resolveRpcUnit(overrides, env, fileOverrides) {
297
+ const layers = [
298
+ { src: 'flag', url: overrides?.btcRpcUrl, user: overrides?.btcRpcUser, pass: overrides?.btcRpcPass },
299
+ { src: 'env', url: env?.btcRpcUrl, user: env?.btcRpcUser, pass: env?.btcRpcPass },
300
+ { src: 'file', url: fileOverrides?.btcRpcUrl, user: fileOverrides?.btcRpcUser, pass: fileOverrides?.btcRpcPass },
301
+ ];
302
+ const withUrl = layers.find(l => blankToUndef(l.url) !== undefined);
303
+ if (withUrl) {
304
+ return { src: withUrl.src, url: blankToUndef(withUrl.url), user: blankToUndef(withUrl.user), pass: blankToUndef(withUrl.pass) };
305
+ }
306
+ const withCreds = layers.find(l => blankToUndef(l.user) !== undefined || blankToUndef(l.pass) !== undefined);
307
+ if (withCreds) {
308
+ return { src: withCreds.src, url: undefined, user: blankToUndef(withCreds.user), pass: blankToUndef(withCreds.pass) };
309
+ }
310
+ return undefined;
311
+ }
152
312
  /**
153
313
  * Resolves the Bitcoin and CAS connection config for a network by merging,
154
314
  * in precedence order, CLI flags, environment variables, and the config-file
@@ -160,37 +320,330 @@ export function resolveDefaultNetwork(overrides) {
160
320
  * When no `--profile` is given, the network name is used as the profile key
161
321
  * (e.g. a regtest DID auto-selects the `"regtest"` profile).
162
322
  */
163
- function resolveConnectionConfig(network, overrides) {
323
+ export function resolveConnectionConfig(network, overrides) {
164
324
  if (!network)
165
325
  return {};
166
- // Layer 1: Config file profile (lowest precedence of the three override layers)
326
+ // Layer 1: Config file profile (lowest precedence of the three override layers).
327
+ // The active-profile name is resolved through the same shared helper as
328
+ // resolveDefaultNetwork so the two cannot disagree about which profile is live.
167
329
  const configPath = overrides?.config ?? defaultConfigPath();
168
330
  const file = readConfigFile(configPath);
169
- const profileName = overrides?.profile ?? file?.defaults?.profile ?? network;
331
+ const { name: activeProfile } = resolveActiveProfile(file, overrides);
332
+ const profileName = activeProfile ?? network;
170
333
  const fileOverrides = file ? profileToOverrides(file, profileName) : {};
171
334
  // Layer 2: Environment variables
172
335
  const env = readEnvOverrides();
173
- // Merge: CLI flags -> env vars -> config file -> (network defaults handled by BitcoinConnection)
174
- const merged = {
175
- btcRest: overrides?.btcRest ?? env.btcRest ?? fileOverrides.btcRest,
176
- btcRpcUrl: overrides?.btcRpcUrl ?? env.btcRpcUrl ?? fileOverrides.btcRpcUrl,
177
- btcRpcUser: overrides?.btcRpcUser ?? env.btcRpcUser ?? fileOverrides.btcRpcUser,
178
- btcRpcPass: overrides?.btcRpcPass ?? env.btcRpcPass ?? fileOverrides.btcRpcPass,
179
- casGateway: overrides?.casGateway ?? env.casGateway ?? fileOverrides.casGateway,
180
- };
336
+ // Blank-aware precedence merge: CLI flag -> env var -> config file. A blank at
337
+ // any layer defers to the next instead of masking it (mirrors the env layer's
338
+ // `|| undefined`), so an empty flag or profile field no longer silently reverts
339
+ // resolution to the SDK network default.
340
+ const pick = (flag, envVal, fileVal) => blankToUndef(flag) ?? blankToUndef(envVal) ?? blankToUndef(fileVal);
341
+ const profileBtc = file?.profiles?.[profileName]?.btc;
342
+ const profileCas = file?.profiles?.[profileName]?.cas;
181
343
  const btc = { network };
182
- if (merged.btcRest) {
183
- btc.rest = { host: merged.btcRest };
344
+ // REST host and headers. Headers apply even without a host override, layering
345
+ // onto the per-network default host inside the api's config merge, so an
346
+ // authenticated Esplora/mempool endpoint can be reached with the default host.
347
+ const btcRest = pick(overrides?.btcRest, env.btcRest, fileOverrides.btcRest);
348
+ const restHeaders = mergeHeaders(profileBtc?.headers, parseHeaderList(overrides?.btcRestHeader, '--btc-rest-header'));
349
+ if (btcRest || restHeaders) {
350
+ btc.rest = { ...(btcRest ? { host: btcRest } : {}), ...(restHeaders ? { headers: restHeaders } : {}) };
184
351
  }
185
- if (merged.btcRpcUrl) {
352
+ // Resolve the RPC endpoint as one atomic credential unit (url + user + pass from
353
+ // one layer), plus the orthogonal wallet and header augmentations.
354
+ const rpcUnit = resolveRpcUnit(overrides, env, fileOverrides);
355
+ const rpcWallet = pick(overrides?.btcRpcWallet, undefined, profileBtc?.wallet);
356
+ const rpcHeaders = mergeHeaders(profileBtc?.rpcHeaders, parseHeaderList(overrides?.btcRpcHeader, '--btc-rpc-header'));
357
+ // Build an RPC config only when a host will actually exist to talk to: either
358
+ // the unit supplies a url, or the network has a default RPC host (regtest).
359
+ // Wallet/header (or credential) knobs alone with no host would otherwise point
360
+ // a phantom client at the default 127.0.0.1:8332 and, on public networks, flip
361
+ // the connection to "has RPC" spuriously (and could leak a header credential
362
+ // meant for a remote proxy). The pass-file fallback is read lazily inside this
363
+ // block, so a set-but-unreadable BTCR2_BTC_RPC_PASS_FILE never aborts a command
364
+ // that uses no RPC at all.
365
+ const networkHasDefaultRpc = DEFAULT_BITCOIN_NETWORK_CONFIG[network].rpc !== undefined;
366
+ const wantsRpc = rpcUnit !== undefined || rpcWallet !== undefined || rpcHeaders !== undefined;
367
+ const hasRpcHost = rpcUnit?.url !== undefined || networkHasDefaultRpc;
368
+ if (wantsRpc && hasRpcHost) {
369
+ const password = resolveSecretRef(rpcUnit?.pass) ?? readRpcPassFile();
186
370
  btc.rpc = {
187
- host: merged.btcRpcUrl,
188
- username: merged.btcRpcUser,
189
- password: merged.btcRpcPass,
371
+ ...(rpcUnit?.url !== undefined ? { host: rpcUnit.url } : {}),
372
+ ...(rpcUnit?.user !== undefined ? { username: rpcUnit.user } : {}),
373
+ ...(password !== undefined ? { password } : {}),
374
+ ...(rpcWallet ? { wallet: rpcWallet } : {}),
375
+ ...(rpcHeaders ? { headers: rpcHeaders } : {}),
190
376
  };
191
377
  }
192
- const cas = merged.casGateway ? { gateway: merged.casGateway } : undefined;
193
- return { btc, ...(cas && { cas }) };
378
+ // Bitcoin request timeout. No default: honored only when explicitly set, so
379
+ // callers that rely on unbounded waits are unaffected (ADR 076).
380
+ const btcTimeout = resolveTimeout(overrides?.btcTimeout, process.env[ENV_VARS.BTC_TIMEOUT], profileBtc?.timeoutMs, '--btc-timeout', 1);
381
+ if (btcTimeout !== undefined)
382
+ btc.timeoutMs = btcTimeout;
383
+ // A configured RPC endpoint is writable and takes precedence over the
384
+ // read-only gateway (matching the api's CasConfig priority: rpcUrl > gateway).
385
+ // Both may be set; the api selects one executor from them.
386
+ const casGateway = pick(overrides?.casGateway, env.casGateway, fileOverrides.casGateway);
387
+ const casRpcUrl = pick(overrides?.casRpcUrl, env.casRpcUrl, fileOverrides.casRpcUrl);
388
+ const casTimeout = resolveTimeout(overrides?.casTimeout, process.env[ENV_VARS.CAS_TIMEOUT], profileCas?.timeoutMs, '--cas-timeout');
389
+ const cas = {};
390
+ if (casGateway)
391
+ cas.gateway = casGateway;
392
+ if (casRpcUrl)
393
+ cas.rpcUrl = casRpcUrl;
394
+ if (casTimeout !== undefined) {
395
+ cas.timeoutMs = casTimeout;
396
+ // A timeout needs an endpoint to attach to. When none is configured, fall
397
+ // back to the same default gateway the api would otherwise apply, so the
398
+ // timeout is honored rather than dropped (the api only defaults the gateway
399
+ // when the whole cas config is absent).
400
+ if (!casGateway && !casRpcUrl)
401
+ cas.gateway = DEFAULT_CAS_GATEWAY;
402
+ }
403
+ const hasCas = casGateway || casRpcUrl || casTimeout !== undefined;
404
+ return { btc, ...(hasCas && { cas }) };
405
+ }
406
+ /**
407
+ * Resolves a millisecond timeout from a flag string, an env string, then a
408
+ * config-file number, in precedence order. Returns `undefined` when none is set
409
+ * (preserving unbounded behavior). Throws a {@link CLIError} for a value below
410
+ * `min` or not a finite number. `min` is `0` for CAS (where `0` disables the
411
+ * timeout) and `1` for the Bitcoin timeout (where `0` would abort every request
412
+ * immediately, which is never intended).
413
+ */
414
+ function resolveTimeout(flag, envVal, fileVal, flagName = 'timeout', min = 0) {
415
+ const raw = blankToUndef(flag) ?? blankToUndef(envVal) ?? (typeof fileVal === 'number' ? String(fileVal) : undefined);
416
+ if (raw === undefined)
417
+ return undefined;
418
+ const ms = Number(raw);
419
+ if (!Number.isFinite(ms) || ms < min) {
420
+ throw new CLIError(`Invalid ${flagName} value "${raw}": expected a number of milliseconds >= ${min}.`, 'INVALID_ARGUMENT_ERROR', { value: raw });
421
+ }
422
+ return ms;
423
+ }
424
+ /**
425
+ * Parses repeatable `Key: Value` header flag values into a header map. Returns
426
+ * `undefined` for an empty list. Throws a {@link CLIError} for an entry missing a
427
+ * colon or with an empty key.
428
+ */
429
+ export function parseHeaderList(list, flagName = '--header') {
430
+ if (!list || list.length === 0)
431
+ return undefined;
432
+ const headers = {};
433
+ for (const entry of list) {
434
+ const idx = entry.indexOf(':');
435
+ const key = idx === -1 ? '' : entry.slice(0, idx).trim();
436
+ if (idx === -1 || key === '') {
437
+ throw new CLIError(`Invalid ${flagName} "${entry}": expected "Key: Value".`, 'INVALID_ARGUMENT_ERROR', { header: entry });
438
+ }
439
+ headers[key] = entry.slice(idx + 1).trim();
440
+ }
441
+ return headers;
442
+ }
443
+ /**
444
+ * Merges a base header map (from the config-file profile) with an override map
445
+ * (from flags), with the override winning per key. Returns `undefined` when both
446
+ * are absent so callers can skip attaching an empty header map.
447
+ */
448
+ function mergeHeaders(base, override) {
449
+ if (!base && !override)
450
+ return undefined;
451
+ return { ...base, ...override };
452
+ }
453
+ /** Environment variable naming a file whose contents are the Bitcoin Core RPC password. */
454
+ export const ENV_RPC_PASS_FILE = 'BTCR2_BTC_RPC_PASS_FILE';
455
+ /** Removes at most one trailing newline, matching the keystore-passphrase normalization. */
456
+ function trimTrailingNewline(value) {
457
+ return value.replace(/\r?\n$/, '');
458
+ }
459
+ /** Reads a secret file, throwing a {@link CLIError} (not a raw Node error) that names the path and source. */
460
+ function readSecretFile(path, source) {
461
+ try {
462
+ return trimTrailingNewline(readFileSync(path, 'utf-8'));
463
+ }
464
+ catch (error) {
465
+ throw new CLIError(`Could not read the RPC password ${source} at ${path}: ${error.message}`, 'CONFIG_READ_ERROR', { path });
466
+ }
467
+ }
468
+ /**
469
+ * Resolves an RPC-password secret reference to its literal value: `env:<VAR>`
470
+ * reads the named environment variable, `file:<path>` reads the file, and any
471
+ * other value is returned as-is. A trailing newline is trimmed from file/env
472
+ * sources so a secret written by `echo` matches an inline value (ADR 077).
473
+ */
474
+ export function resolveSecretRef(value) {
475
+ if (value === undefined)
476
+ return undefined;
477
+ if (value.startsWith('env:')) {
478
+ const fromEnv = process.env[value.slice(4)];
479
+ return fromEnv === undefined ? undefined : trimTrailingNewline(fromEnv);
480
+ }
481
+ if (value.startsWith('file:')) {
482
+ return readSecretFile(value.slice(5), 'file reference');
483
+ }
484
+ return value;
485
+ }
486
+ /** Reads the RPC password from an {@link ENV_RPC_PASS_FILE}-named file, if set. */
487
+ function readRpcPassFile() {
488
+ const path = process.env[ENV_RPC_PASS_FILE];
489
+ if (!path)
490
+ return undefined;
491
+ return readSecretFile(path, `file named by ${ENV_RPC_PASS_FILE}`);
492
+ }
493
+ /**
494
+ * Resolves the beacon {@link BroadcastOptions} for an update/deactivate from the
495
+ * fee-rate and change-address knobs, following the CLI precedence chain.
496
+ *
497
+ * - Fee rate: `--fee-rate` flag, then `BTCR2_FEE_RATE`, then profile
498
+ * `btc.feeRate`. A positive sats/vByte value wrapped in a `StaticFeeEstimator`.
499
+ * - Change address: `--change-address` flag, then profile `btc.changeAddress`
500
+ * (no env, since a change address is DID/network-specific). Validated against
501
+ * the DID network by the beacon at broadcast time.
502
+ *
503
+ * Returns `undefined` when neither is set, so the SDK defaults (5 sat/vB, change
504
+ * back to the beacon address) still apply.
505
+ */
506
+ export function resolveBroadcastOptions(network, overrides, flags) {
507
+ const file = readConfigFile(overrides?.config ?? defaultConfigPath());
508
+ const { name: activeProfile } = resolveActiveProfile(file, overrides);
509
+ const profileBtc = file?.profiles?.[activeProfile ?? network]?.btc;
510
+ const options = {};
511
+ const feeRateRaw = blankToUndef(flags.feeRate)
512
+ ?? blankToUndef(process.env[ENV_VARS.FEE_RATE])
513
+ ?? (typeof profileBtc?.feeRate === 'number' ? String(profileBtc.feeRate) : undefined);
514
+ if (feeRateRaw !== undefined)
515
+ options.feeEstimator = new StaticFeeEstimator(parseFeeRate(feeRateRaw));
516
+ const changeAddress = blankToUndef(flags.changeAddress) ?? blankToUndef(profileBtc?.changeAddress);
517
+ if (changeAddress)
518
+ options.changeAddress = changeAddress;
519
+ return options.feeEstimator || options.changeAddress ? options : undefined;
520
+ }
521
+ /** Parses a positive sats/vByte fee rate, throwing a {@link CLIError} otherwise. */
522
+ function parseFeeRate(raw) {
523
+ const rate = Number(raw);
524
+ if (!Number.isFinite(rate) || rate <= 0) {
525
+ throw new CLIError(`Invalid --fee-rate "${raw}": expected a positive number of sats per vByte.`, 'INVALID_ARGUMENT_ERROR', { value: raw });
526
+ }
527
+ return rate;
528
+ }
529
+ /**
530
+ * Resolves the effective connection config with provenance for `config effective`.
531
+ * The btc values are read back from the constructed api (so SDK network defaults
532
+ * are reflected), the cas and timeout values from {@link resolveConnectionConfig},
533
+ * and each `source` is derived by the same precedence order the merge uses.
534
+ */
535
+ export function resolveEffectiveConfig(network, overrides) {
536
+ const file = readConfigFile(overrides?.config ?? defaultConfigPath());
537
+ const { name: activeProfile } = resolveActiveProfile(file, overrides);
538
+ const profileName = activeProfile ?? network;
539
+ const fileOv = file ? profileToOverrides(file, profileName) : {};
540
+ const profileBtc = file?.profiles?.[profileName]?.btc;
541
+ const profileCas = file?.profiles?.[profileName]?.cas;
542
+ const env = readEnvOverrides();
543
+ const api = defaultApiFactory(network, overrides);
544
+ const restCfg = api.btc.connection.rest.config;
545
+ const rpcCfg = api.btc.connection.rpc?.config;
546
+ const conn = resolveConnectionConfig(network, overrides);
547
+ const src = (flag, envVal, fileVal) => blankToUndef(flag) !== undefined ? 'flag'
548
+ : blankToUndef(envVal) !== undefined ? 'env'
549
+ : (fileVal !== undefined && fileVal !== null && String(fileVal).trim() !== '') ? 'file'
550
+ : 'default';
551
+ // CAS has no client to read back from; derive its resolved endpoint from the
552
+ // connection resolver, defaulting the gateway the way the api would.
553
+ const casGatewayVal = conn.cas?.gateway ?? (conn.cas?.rpcUrl ? undefined : DEFAULT_CAS_GATEWAY);
554
+ // RPC url/user/pass provenance follows the atomic-credential unit, so a value's
555
+ // reported source is the layer the merge actually bound it to (never an
556
+ // independent per-field guess that could disagree with the resolver). A password
557
+ // taken from BTCR2_BTC_RPC_PASS_FILE when the unit supplied none is env-sourced.
558
+ const rpcUnit = resolveRpcUnit(overrides, env, fileOv);
559
+ const rpcSrc = rpcUnit?.src ?? 'default';
560
+ const passFromFile = rpcUnit?.pass === undefined
561
+ && process.env[ENV_RPC_PASS_FILE] !== undefined
562
+ && rpcCfg?.password !== undefined;
563
+ return {
564
+ network,
565
+ profile: activeProfile,
566
+ btc: {
567
+ rest: { value: restCfg.host, source: src(overrides?.btcRest, env.btcRest, fileOv.btcRest) },
568
+ rpcUrl: { value: rpcCfg?.host, source: rpcUnit?.url !== undefined ? rpcSrc : 'default' },
569
+ rpcUser: { value: rpcCfg?.username, source: rpcUnit?.user !== undefined ? rpcSrc : 'default' },
570
+ rpcPass: { value: rpcCfg?.password, source: rpcUnit?.pass !== undefined ? rpcSrc : (passFromFile ? 'env' : 'default') },
571
+ rpcWallet: { value: rpcCfg?.wallet, source: src(overrides?.btcRpcWallet, undefined, profileBtc?.wallet) },
572
+ timeoutMs: { value: conn.btc?.timeoutMs, source: src(overrides?.btcTimeout, process.env[ENV_VARS.BTC_TIMEOUT], profileBtc?.timeoutMs) },
573
+ },
574
+ cas: {
575
+ gateway: { value: casGatewayVal, source: src(overrides?.casGateway, env.casGateway, fileOv.casGateway) },
576
+ rpcUrl: { value: conn.cas?.rpcUrl, source: src(overrides?.casRpcUrl, env.casRpcUrl, fileOv.casRpcUrl) },
577
+ timeoutMs: { value: conn.cas?.timeoutMs, source: src(overrides?.casTimeout, process.env[ENV_VARS.CAS_TIMEOUT], profileCas?.timeoutMs) },
578
+ },
579
+ };
580
+ }
581
+ /** Default per-probe timeout (ms) for `config doctor`. */
582
+ const DOCTOR_PROBE_TIMEOUT_MS = 5000;
583
+ /** Fetches a URL with a bounded timeout, reporting reachability rather than throwing. */
584
+ async function probeEndpoint(endpoint, target, url, opts) {
585
+ try {
586
+ const res = await fetch(url, {
587
+ method: opts?.method ?? 'GET',
588
+ headers: opts?.headers,
589
+ signal: AbortSignal.timeout(DOCTOR_PROBE_TIMEOUT_MS),
590
+ });
591
+ return res.ok
592
+ ? { endpoint, target, ok: true }
593
+ : { endpoint, target, ok: false, detail: `HTTP ${res.status}` };
594
+ }
595
+ catch (error) {
596
+ return { endpoint, target, ok: false, detail: error.message };
597
+ }
598
+ }
599
+ /** Races a promise against a timeout so a stalled RPC call cannot hang `doctor`. */
600
+ function withProbeTimeout(promise, ms) {
601
+ let timer;
602
+ const timeout = new Promise((_, reject) => {
603
+ timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
604
+ });
605
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
606
+ }
607
+ /**
608
+ * Probes reachability of the resolved endpoints for `config doctor`: a
609
+ * lightweight REST call against btc-rest, a `getblockchaininfo` against btc-rpc
610
+ * when configured, and a reachability check against the resolved CAS. Also
611
+ * surfaces the profile/network coherence warning. Reads and touches the network;
612
+ * never writes.
613
+ */
614
+ export async function runDoctor(network, overrides) {
615
+ const api = defaultApiFactory(network, overrides);
616
+ const checks = [];
617
+ const restHost = api.btc.connection.rest.config.host.replace(/\/+$/, '');
618
+ checks.push(await probeEndpoint('btc-rest', restHost, `${restHost}/blocks/tip/height`, { headers: api.btc.connection.rest.config.headers }));
619
+ const rpc = api.btc.connection.rpc;
620
+ if (rpc) {
621
+ const target = rpc.config.host ?? '(default rpc)';
622
+ try {
623
+ await withProbeTimeout(rpc.getBlockchainInfo(), DOCTOR_PROBE_TIMEOUT_MS);
624
+ checks.push({ endpoint: 'btc-rpc', target, ok: true });
625
+ }
626
+ catch (error) {
627
+ checks.push({ endpoint: 'btc-rpc', target, ok: false, detail: error.message });
628
+ }
629
+ }
630
+ // A writable IPFS RPC (Kubo) answers only POST, so a bare GET would falsely
631
+ // report a healthy node as down; probe its version endpoint with POST. A
632
+ // read-only gateway answers a plain GET on its base URL.
633
+ const conn = resolveConnectionConfig(network, overrides);
634
+ if (conn.cas?.rpcUrl) {
635
+ const base = conn.cas.rpcUrl.replace(/\/+$/, '');
636
+ checks.push(await probeEndpoint('cas', conn.cas.rpcUrl, `${base}/api/v0/version`, { method: 'POST' }));
637
+ }
638
+ else {
639
+ const gateway = (conn.cas?.gateway ?? DEFAULT_CAS_GATEWAY).replace(/\/+$/, '');
640
+ checks.push(await probeEndpoint('cas', gateway, gateway));
641
+ }
642
+ const mismatch = profileNetworkMismatch(network, overrides);
643
+ return {
644
+ checks,
645
+ ...(mismatch ? { coherence: { profile: mismatch.profile, declared: mismatch.declared, encoding: network } } : {}),
646
+ };
194
647
  }
195
648
  /**
196
649
  * Default {@link ApiFactory} backed by network defaults from
@@ -213,10 +666,37 @@ export function defaultApiFactory(network, overrides) {
213
666
  */
214
667
  function buildKeystoreKms(overrides) {
215
668
  return new FileBackedKeyManager({
216
- path: overrides?.keystore ?? defaultKeystorePath(),
669
+ path: resolveKeystorePath(overrides),
217
670
  getPassphrase: () => acquirePassphrase({ passphraseFile: overrides?.passphraseFile }),
218
671
  });
219
672
  }
673
+ /**
674
+ * Resolves the keystore file path: the `--keystore` flag, else the active
675
+ * profile's `identity.keystore`, else the default XDG keystore path. The flag
676
+ * always wins over the profile default.
677
+ */
678
+ export function resolveKeystorePath(overrides) {
679
+ return overrides?.keystore ?? activeProfileIdentity(overrides)?.keystore ?? defaultKeystorePath();
680
+ }
681
+ /**
682
+ * Reads the active profile's `identity` block (keystore + default signing key),
683
+ * or `undefined` when no profile is active. A profile is active only when
684
+ * selected by `--profile` or the config's `defaults.profile`.
685
+ */
686
+ function activeProfileIdentity(overrides) {
687
+ const file = readConfigFile(overrides?.config ?? defaultConfigPath());
688
+ const { name } = resolveActiveProfile(file, overrides);
689
+ return name ? file?.profiles?.[name]?.identity : undefined;
690
+ }
691
+ /**
692
+ * Resolves the signing-key reference for update/deactivate: the `--signing-key`
693
+ * flag, else the active profile's `identity.default`, else `undefined` (letting
694
+ * the KMS fall back to its active key). The flag always wins over the profile
695
+ * default, consistent with the flag -> profile precedence used elsewhere.
696
+ */
697
+ export function resolveSigningKeyRef(overrides) {
698
+ return blankToUndef(overrides?.signingKey) ?? blankToUndef(activeProfileIdentity(overrides)?.default);
699
+ }
220
700
  /**
221
701
  * Keystore-aware {@link ApiFactory} for commands that need a signing identity
222
702
  * (key management, update, deactivate). Identical to {@link defaultApiFactory}