@did-btcr2/cli 0.15.0 → 0.17.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.
- package/README.md +47 -6
- package/dist/.tsbuildinfo +1 -1
- package/dist/cjs/index.js +836 -122
- package/dist/esm/src/cli.js +7 -4
- package/dist/esm/src/cli.js.map +1 -1
- package/dist/esm/src/commands/config.js +11 -15
- package/dist/esm/src/commands/config.js.map +1 -1
- package/dist/esm/src/commands/create.js +4 -1
- package/dist/esm/src/commands/create.js.map +1 -1
- package/dist/esm/src/commands/deactivate.js +3 -1
- package/dist/esm/src/commands/deactivate.js.map +1 -1
- package/dist/esm/src/commands/index.js +2 -0
- package/dist/esm/src/commands/index.js.map +1 -1
- package/dist/esm/src/commands/init.js +69 -0
- package/dist/esm/src/commands/init.js.map +1 -0
- package/dist/esm/src/commands/keystore.js +180 -0
- package/dist/esm/src/commands/keystore.js.map +1 -0
- package/dist/esm/src/commands/profile.js +1 -1
- package/dist/esm/src/commands/profile.js.map +1 -1
- package/dist/esm/src/commands/update.js +3 -1
- package/dist/esm/src/commands/update.js.map +1 -1
- package/dist/esm/src/config.js +109 -31
- package/dist/esm/src/config.js.map +1 -1
- package/dist/esm/src/keystore/file-key-store.js +388 -32
- package/dist/esm/src/keystore/file-key-store.js.map +1 -1
- package/dist/esm/src/keystore/passphrase.js +53 -10
- package/dist/esm/src/keystore/passphrase.js.map +1 -1
- package/dist/esm/src/keystore/paths.js +6 -18
- package/dist/esm/src/keystore/paths.js.map +1 -1
- package/dist/esm/src/keystore/session.js +250 -0
- package/dist/esm/src/keystore/session.js.map +1 -0
- package/dist/esm/src/paths.js +71 -0
- package/dist/esm/src/paths.js.map +1 -0
- package/dist/esm/src/types.js.map +1 -1
- package/dist/types/src/cli.d.ts.map +1 -1
- package/dist/types/src/commands/config.d.ts.map +1 -1
- package/dist/types/src/commands/create.d.ts.map +1 -1
- package/dist/types/src/commands/deactivate.d.ts.map +1 -1
- package/dist/types/src/commands/index.d.ts +2 -0
- package/dist/types/src/commands/index.d.ts.map +1 -1
- package/dist/types/src/commands/init.d.ts +13 -0
- package/dist/types/src/commands/init.d.ts.map +1 -0
- package/dist/types/src/commands/keystore.d.ts +11 -0
- package/dist/types/src/commands/keystore.d.ts.map +1 -0
- package/dist/types/src/commands/update.d.ts.map +1 -1
- package/dist/types/src/config.d.ts +38 -14
- package/dist/types/src/config.d.ts.map +1 -1
- package/dist/types/src/keystore/file-key-store.d.ts +102 -10
- package/dist/types/src/keystore/file-key-store.d.ts.map +1 -1
- package/dist/types/src/keystore/passphrase.d.ts +26 -1
- package/dist/types/src/keystore/passphrase.d.ts.map +1 -1
- package/dist/types/src/keystore/paths.d.ts +6 -10
- package/dist/types/src/keystore/paths.d.ts.map +1 -1
- package/dist/types/src/keystore/session.d.ts +105 -0
- package/dist/types/src/keystore/session.d.ts.map +1 -0
- package/dist/types/src/paths.d.ts +64 -0
- package/dist/types/src/paths.d.ts.map +1 -0
- package/dist/types/src/types.d.ts +53 -0
- package/dist/types/src/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/cli.ts +8 -3
- package/src/commands/config.ts +12 -14
- package/src/commands/create.ts +4 -1
- package/src/commands/deactivate.ts +3 -1
- package/src/commands/index.ts +2 -0
- package/src/commands/init.ts +80 -0
- package/src/commands/keystore.ts +232 -0
- package/src/commands/profile.ts +1 -1
- package/src/commands/update.ts +3 -1
- package/src/config.ts +118 -35
- package/src/keystore/file-key-store.ts +498 -43
- package/src/keystore/passphrase.ts +71 -8
- package/src/keystore/paths.ts +6 -19
- package/src/keystore/session.ts +303 -0
- package/src/paths.ts +92 -0
- package/src/types.ts +16 -1
|
@@ -12,6 +12,23 @@ export type PassphraseOptions = {
|
|
|
12
12
|
prompt?: string;
|
|
13
13
|
/** When true, prompt twice and require the entries to match (for a new keystore). */
|
|
14
14
|
confirm?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* When true, skip the environment variable and passphrase file and require a
|
|
17
|
+
* fresh terminal entry. Used for the *new* passphrase in `change-passphrase`,
|
|
18
|
+
* where the env var / file holds the *current* passphrase and must not silently
|
|
19
|
+
* satisfy the new one (which would make the change a no-op).
|
|
20
|
+
*/
|
|
21
|
+
forcePrompt?: boolean;
|
|
22
|
+
/**
|
|
23
|
+
* An optional non-interactive source consulted *after* the env var and
|
|
24
|
+
* passphrase file and *before* the terminal prompt (and before the "no TTY"
|
|
25
|
+
* failure). The session unlock agent (ADR 081) wires this to a cached
|
|
26
|
+
* passphrase, so a returning command consumes the session instead of
|
|
27
|
+
* prompting, and a non-interactive follow-on command does not hard-fail. It
|
|
28
|
+
* returns `undefined` when no session is available. Skipped when `forcePrompt`
|
|
29
|
+
* is set, and never wired during passphrase establishment (`confirm`).
|
|
30
|
+
*/
|
|
31
|
+
beforePrompt?: () => string | undefined;
|
|
15
32
|
};
|
|
16
33
|
|
|
17
34
|
/**
|
|
@@ -19,16 +36,32 @@ export type PassphraseOptions = {
|
|
|
19
36
|
* (which would leak into process listings and shell history). Resolution order:
|
|
20
37
|
* the {@link ENV_KEYSTORE_PASSPHRASE} environment variable, a passphrase file,
|
|
21
38
|
* then a non-echoing terminal prompt. Throws if none is available and standard
|
|
22
|
-
* input is not a terminal.
|
|
39
|
+
* input is not a terminal. When `forcePrompt` is set, the env var and file are
|
|
40
|
+
* skipped and a terminal entry is required.
|
|
23
41
|
*/
|
|
24
42
|
export function acquirePassphrase(options: PassphraseOptions = {}): string {
|
|
25
43
|
// All sources are normalized identically (at most one trailing newline
|
|
26
44
|
// removed) so the KDF input is source-independent.
|
|
27
|
-
|
|
28
|
-
|
|
45
|
+
if (!options.forcePrompt) {
|
|
46
|
+
const fromEnv = process.env[ENV_KEYSTORE_PASSPHRASE];
|
|
47
|
+
if (fromEnv) return assertNonEmpty(fromEnv.replace(/\r?\n$/, ''));
|
|
29
48
|
|
|
30
|
-
|
|
31
|
-
|
|
49
|
+
if (options.passphraseFile) {
|
|
50
|
+
return assertNonEmpty(readFileSync(options.passphraseFile, 'utf-8').replace(/\r?\n$/, ''));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// A cached session (ADR 081) sits below the env var and file but above the
|
|
54
|
+
// interactive prompt, so it is consulted before the "no TTY" failure: a
|
|
55
|
+
// scripted or piped follow-on command consumes the session instead of
|
|
56
|
+
// hard-failing. Establishment never reaches here (its caller omits it).
|
|
57
|
+
//
|
|
58
|
+
// The session already holds the exact, keystore-verified passphrase (encoded
|
|
59
|
+
// and decoded byte-for-byte), not a raw source needing newline normalization.
|
|
60
|
+
// Return it verbatim: re-stripping a trailing newline here would corrupt the
|
|
61
|
+
// KDF input for a passphrase that legitimately ends in one, even though unlock
|
|
62
|
+
// itself succeeded. assertNonEmpty is a defensive guard only.
|
|
63
|
+
const fromSession = options.beforePrompt?.();
|
|
64
|
+
if (fromSession) return assertNonEmpty(fromSession);
|
|
32
65
|
}
|
|
33
66
|
|
|
34
67
|
if (!process.stdin.isTTY) {
|
|
@@ -56,9 +89,34 @@ function assertNonEmpty(passphrase: string): string {
|
|
|
56
89
|
return passphrase;
|
|
57
90
|
}
|
|
58
91
|
|
|
92
|
+
/**
|
|
93
|
+
* A 4-byte shared buffer used only as an {@link Atomics.wait} target. It lets
|
|
94
|
+
* {@link promptHidden} block briefly on an empty non-blocking TTY instead of
|
|
95
|
+
* busy-spinning. It is never written to, so the wait always times out.
|
|
96
|
+
*/
|
|
97
|
+
const IDLE_WAIT = new Int32Array(new SharedArrayBuffer(4));
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Milliseconds to block on each empty read. Imperceptible to a typist yet long
|
|
101
|
+
* enough that an open prompt sits idle rather than pegging a CPU core.
|
|
102
|
+
*/
|
|
103
|
+
const IDLE_POLL_MS = 20;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Removes the last whole UTF-8 character from an accumulating byte array in
|
|
107
|
+
* place: pops any trailing continuation bytes (0b10xxxxxx) then the leading
|
|
108
|
+
* byte. Exported for testing; a backspace mid-entry must not strand a fragment
|
|
109
|
+
* that later decodes to U+FFFD.
|
|
110
|
+
*/
|
|
111
|
+
export function dropLastUtf8Char(bytes: number[]): void {
|
|
112
|
+
while (bytes.length > 0 && (bytes[bytes.length - 1] & 0xc0) === 0x80) bytes.pop();
|
|
113
|
+
bytes.pop();
|
|
114
|
+
}
|
|
115
|
+
|
|
59
116
|
/**
|
|
60
117
|
* Reads a line from the terminal synchronously without echoing keystrokes.
|
|
61
|
-
* Bytes are accumulated and decoded as UTF-8 so multibyte passphrases survive
|
|
118
|
+
* Bytes are accumulated and decoded as UTF-8 so multibyte passphrases survive,
|
|
119
|
+
* including a backspace that spans a whole multibyte character.
|
|
62
120
|
* This path runs only when standard input is a terminal.
|
|
63
121
|
*/
|
|
64
122
|
function promptHidden(label: string): string {
|
|
@@ -75,7 +133,12 @@ function promptHidden(label: string): string {
|
|
|
75
133
|
read = readSync(stdin.fd, byte, 0, 1, null);
|
|
76
134
|
} catch (error) {
|
|
77
135
|
const code = (error as { code?: string }).code;
|
|
78
|
-
if (code === 'EAGAIN')
|
|
136
|
+
if (code === 'EAGAIN') {
|
|
137
|
+
// No byte ready yet on a non-blocking TTY. Block briefly instead of
|
|
138
|
+
// spinning so an open prompt does not peg a CPU core while it waits.
|
|
139
|
+
Atomics.wait(IDLE_WAIT, 0, 0, IDLE_POLL_MS);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
79
142
|
if (code === 'EOF') break;
|
|
80
143
|
throw error;
|
|
81
144
|
}
|
|
@@ -86,7 +149,7 @@ function promptHidden(label: string): string {
|
|
|
86
149
|
throw new KeyStoreError('Passphrase entry aborted.', 'PASSPHRASE_REQUIRED_ERROR');
|
|
87
150
|
}
|
|
88
151
|
if (ch === 0x7f || ch === 0x08) { // DEL or backspace
|
|
89
|
-
bytes
|
|
152
|
+
dropLastUtf8Char(bytes);
|
|
90
153
|
continue;
|
|
91
154
|
}
|
|
92
155
|
bytes.push(ch);
|
package/src/keystore/paths.ts
CHANGED
|
@@ -1,21 +1,8 @@
|
|
|
1
|
-
import { homedir } from 'node:os';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { blankToUndef } from '../types.js';
|
|
4
|
-
|
|
5
1
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* Resolution order:
|
|
12
|
-
* 1. `$XDG_DATA_HOME/btcr2/keystore.json`
|
|
13
|
-
* 2. `%LOCALAPPDATA%/btcr2/keystore.json` (Windows)
|
|
14
|
-
* 3. `~/.local/share/btcr2/keystore.json` (fallback)
|
|
2
|
+
* The default keystore path now lives alongside the config file under a single
|
|
3
|
+
* CLI home root (`<home>/keystore.json`, ADR 079). The implementation lives in
|
|
4
|
+
* `../paths.ts` (the single source of truth for on-disk state locations); it is
|
|
5
|
+
* re-exported here so existing `./paths.js` importers in the keystore layer keep
|
|
6
|
+
* their import surface.
|
|
15
7
|
*/
|
|
16
|
-
export
|
|
17
|
-
const base = blankToUndef(process.env.XDG_DATA_HOME)
|
|
18
|
-
?? blankToUndef(process.env.LOCALAPPDATA)
|
|
19
|
-
?? join(homedir(), '.local', 'share');
|
|
20
|
-
return join(base, 'btcr2', 'keystore.json');
|
|
21
|
-
}
|
|
8
|
+
export { defaultKeystorePath } from '../paths.js';
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { closeSync, constants, existsSync, fstatSync, openSync, readdirSync, readFileSync, rmSync } from 'node:fs';
|
|
2
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { utf8ToBytes } from '@noble/hashes/utils.js';
|
|
4
|
+
import { base64urlnopad } from '@scure/base';
|
|
5
|
+
import { ensureDir, writeFileAtomic } from './atomic.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The session unlock agent (ADR 081). `keystore unlock` caches the verified
|
|
9
|
+
* keystore passphrase in a single `<home>/session.json`, and subsequent commands
|
|
10
|
+
* read it in place of a prompt until it expires or `keystore lock` revokes it.
|
|
11
|
+
*
|
|
12
|
+
* This is an on-disk v1 design. The cached passphrase is base64url-*encoded*, not
|
|
13
|
+
* encrypted: its only protection at rest is the file's `0600` mode. That is the
|
|
14
|
+
* deliberate, documented cost of a portable, minimal-diff convenience; a future
|
|
15
|
+
* in-memory agent (v2) that never persists the secret is the real fix. Every read
|
|
16
|
+
* here is defensive and never throws, so a bad or hostile session degrades to a
|
|
17
|
+
* passphrase prompt rather than a crash.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Current session-file format version. */
|
|
21
|
+
export const SESSION_VERSION = 1 as const;
|
|
22
|
+
|
|
23
|
+
/** Default session lifetime: one hour. */
|
|
24
|
+
export const DEFAULT_SESSION_TTL_MS = 60 * 60 * 1000;
|
|
25
|
+
/** Hard cap on a cached-passphrase lifetime: 24 hours. A longer TTL is refused. */
|
|
26
|
+
export const MAX_SESSION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
27
|
+
/** Environment variable supplying a default TTL below the `--ttl` flag. */
|
|
28
|
+
export const ENV_KEYSTORE_TTL = 'BTCR2_KEYSTORE_TTL';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The on-disk session file. `passphrase` is base64url(utf8(passphrase)): an
|
|
32
|
+
* encoding, not encryption. `keystore` binds the session to one keystore, and
|
|
33
|
+
* `verifierId` (a hash of that keystore's verifier) invalidates the session when
|
|
34
|
+
* the passphrase is rotated. `allowMainnet` records whether the operator unlocked
|
|
35
|
+
* with `--allow-mainnet`; a session without it is withheld from a `bitcoin`
|
|
36
|
+
* operation so mainnet keeps per-use authentication (ADR 081). No derived key,
|
|
37
|
+
* keystore ciphertext, or signing-key bytes ever appear here.
|
|
38
|
+
*/
|
|
39
|
+
export interface SessionFile {
|
|
40
|
+
v : typeof SESSION_VERSION;
|
|
41
|
+
keystore : string;
|
|
42
|
+
verifierId : string;
|
|
43
|
+
passphrase : string;
|
|
44
|
+
allowMainnet : boolean;
|
|
45
|
+
createdAt : number;
|
|
46
|
+
expiresAt : number;
|
|
47
|
+
ttlSeconds : number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Inputs for {@link writeSession}. */
|
|
51
|
+
export interface WriteSessionInput {
|
|
52
|
+
/** The keystore this session unlocks (stored resolved/normalized). */
|
|
53
|
+
keystorePath : string;
|
|
54
|
+
/** Fingerprint of the keystore verifier, from `keystoreVerifierId`. */
|
|
55
|
+
verifierId : string;
|
|
56
|
+
/** The verified passphrase to cache. */
|
|
57
|
+
passphrase : string;
|
|
58
|
+
/** Lifetime in milliseconds. */
|
|
59
|
+
ttlMs : number;
|
|
60
|
+
/**
|
|
61
|
+
* Whether this session may be consumed for a mainnet (`bitcoin`) operation,
|
|
62
|
+
* from the `unlock --allow-mainnet` flag. Defaults to `false` (deny), so
|
|
63
|
+
* mainnet operations fall through to a per-use passphrase prompt (ADR 081).
|
|
64
|
+
*/
|
|
65
|
+
allowMainnet? : boolean;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Writes the session file atomically at `0600` (temp sibling + rename), returning
|
|
70
|
+
* the written record so the caller can report expiry without re-reading. The
|
|
71
|
+
* caller is responsible for verifying the passphrase first; this only persists it.
|
|
72
|
+
*/
|
|
73
|
+
export function writeSession(sessionPath: string, input: WriteSessionInput): SessionFile {
|
|
74
|
+
const createdAt = Date.now();
|
|
75
|
+
const session: SessionFile = {
|
|
76
|
+
v : SESSION_VERSION,
|
|
77
|
+
keystore : resolve(input.keystorePath),
|
|
78
|
+
verifierId : input.verifierId,
|
|
79
|
+
passphrase : base64urlnopad.encode(utf8ToBytes(input.passphrase)),
|
|
80
|
+
allowMainnet : input.allowMainnet ?? false,
|
|
81
|
+
createdAt,
|
|
82
|
+
expiresAt : createdAt + input.ttlMs,
|
|
83
|
+
ttlSeconds : Math.round(input.ttlMs / 1000),
|
|
84
|
+
};
|
|
85
|
+
ensureDir(dirname(sessionPath), 0o700);
|
|
86
|
+
writeFileAtomic(sessionPath, `${JSON.stringify(session, null, 2)}\n`, 0o600);
|
|
87
|
+
return session;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Deletes the session file and any crash-orphaned `writeFileAtomic` temp sibling
|
|
92
|
+
* (each of which would hold a plaintext passphrase). Idempotent; needs no
|
|
93
|
+
* passphrase. Returns whether a session file was present. Unlink is best-effort:
|
|
94
|
+
* it removes the name, it does not securely erase the bytes (see ADR 081).
|
|
95
|
+
*/
|
|
96
|
+
export function clearSession(sessionPath: string): boolean {
|
|
97
|
+
let existed = false;
|
|
98
|
+
try {
|
|
99
|
+
existed = existsSync(sessionPath);
|
|
100
|
+
if (existed) rmSync(sessionPath, { force: true });
|
|
101
|
+
} catch {
|
|
102
|
+
// Best effort: a session we cannot remove is reported as not-cleared below.
|
|
103
|
+
existed = false;
|
|
104
|
+
}
|
|
105
|
+
sweepSessionTemps(sessionPath);
|
|
106
|
+
return existed;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Removes `.session.json.<pid>.<n>.tmp` leftovers from an interrupted atomic write. */
|
|
110
|
+
function sweepSessionTemps(sessionPath: string): void {
|
|
111
|
+
const dir = dirname(sessionPath);
|
|
112
|
+
const prefix = `.${basename(sessionPath)}.`;
|
|
113
|
+
try {
|
|
114
|
+
for (const name of readdirSync(dir)) {
|
|
115
|
+
if (name.startsWith(prefix) && name.endsWith('.tmp')) {
|
|
116
|
+
try {
|
|
117
|
+
rmSync(join(dir, name), { force: true });
|
|
118
|
+
} catch {
|
|
119
|
+
// A temp file we cannot remove is left for the next sweep.
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
} catch {
|
|
124
|
+
// Directory unreadable or absent: nothing to sweep.
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Returns the cached passphrase for `keystorePath` when a live, matching session
|
|
130
|
+
* exists, else `undefined`. Never throws. A session that is expired, stale (the
|
|
131
|
+
* keystore passphrase rotated), future-dated, or malformed is pruned on read; a
|
|
132
|
+
* live session bound to a *different* keystore is left in place (it prompts for
|
|
133
|
+
* the current keystore instead).
|
|
134
|
+
*
|
|
135
|
+
* `isMainnetOperation` gates the one case the network is known at consumption: a
|
|
136
|
+
* live session that was not unlocked with `--allow-mainnet` is withheld from a
|
|
137
|
+
* `bitcoin` operation (returning `undefined` so the caller falls through to a
|
|
138
|
+
* per-use prompt) but *not* pruned, since it remains valid for the non-mainnet
|
|
139
|
+
* operations the operator unlocked for (ADR 081).
|
|
140
|
+
*/
|
|
141
|
+
export function readLiveSessionPassphrase(
|
|
142
|
+
sessionPath : string,
|
|
143
|
+
keystorePath : string,
|
|
144
|
+
currentVerifierId : string | undefined,
|
|
145
|
+
isMainnetOperation = false,
|
|
146
|
+
): string | undefined {
|
|
147
|
+
const verdict = evaluateSession(sessionPath, keystorePath, currentVerifierId, Date.now());
|
|
148
|
+
if (verdict.status === 'live') {
|
|
149
|
+
// Withhold a session lacking mainnet allowance from a mainnet operation, so
|
|
150
|
+
// signing a `bitcoin` DID still authenticates per use. Leave it in place: it
|
|
151
|
+
// is a valid session, just not for this operation (like a foreign keystore).
|
|
152
|
+
if (isMainnetOperation && !verdict.session.allowMainnet) return undefined;
|
|
153
|
+
try {
|
|
154
|
+
return Buffer.from(base64urlnopad.decode(verdict.session.passphrase)).toString('utf-8');
|
|
155
|
+
} catch {
|
|
156
|
+
clearSession(sessionPath);
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Prune a session that is dead for everyone or dead for this keystore. A
|
|
161
|
+
// 'foreign' (live, different keystore) or 'none' session is left untouched.
|
|
162
|
+
if (verdict.status === 'expired' || verdict.status === 'stale'
|
|
163
|
+
|| verdict.status === 'future' || verdict.status === 'malformed') {
|
|
164
|
+
clearSession(sessionPath);
|
|
165
|
+
}
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Public, redacted view of the session state for `keystore status`. Never emits the passphrase. */
|
|
170
|
+
export interface SessionStatus {
|
|
171
|
+
active : boolean;
|
|
172
|
+
expiresAt? : number;
|
|
173
|
+
secondsRemaining? : number;
|
|
174
|
+
/** Whether the session may sign a mainnet operation prompt-free (unlocked with `--allow-mainnet`). */
|
|
175
|
+
allowMainnet? : boolean;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Reports whether a live session exists for `keystorePath` and its remaining
|
|
180
|
+
* lifetime, without decrypting, prompting, throwing, or emitting the passphrase.
|
|
181
|
+
* An expired, foreign, stale, or malformed session reports inactive. Read-only:
|
|
182
|
+
* unlike {@link readLiveSessionPassphrase}, it does not prune.
|
|
183
|
+
*/
|
|
184
|
+
export function readSessionStatus(
|
|
185
|
+
sessionPath : string,
|
|
186
|
+
keystorePath : string,
|
|
187
|
+
currentVerifierId : string | undefined,
|
|
188
|
+
): SessionStatus {
|
|
189
|
+
const now = Date.now();
|
|
190
|
+
const verdict = evaluateSession(sessionPath, keystorePath, currentVerifierId, now);
|
|
191
|
+
if (verdict.status !== 'live') return { active: false };
|
|
192
|
+
return {
|
|
193
|
+
active : true,
|
|
194
|
+
expiresAt : verdict.session.expiresAt,
|
|
195
|
+
secondsRemaining : Math.max(0, Math.round((verdict.session.expiresAt - now) / 1000)),
|
|
196
|
+
allowMainnet : verdict.session.allowMainnet,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Parses a TTL string into milliseconds: a bare integer is seconds; an `s`, `m`,
|
|
202
|
+
* or `h` suffix scales it. Returns `undefined` for any malformed input. The
|
|
203
|
+
* caller applies the default, the 24h cap, and the `<= 0` rejection.
|
|
204
|
+
*/
|
|
205
|
+
export function parseTtlToMs(raw: string): number | undefined {
|
|
206
|
+
const match = /^(\d+)([smh]?)$/.exec(raw.trim());
|
|
207
|
+
if (!match) return undefined;
|
|
208
|
+
const n = Number(match[1]);
|
|
209
|
+
if (!Number.isFinite(n)) return undefined;
|
|
210
|
+
const unitMs = match[2] === 'h' ? 3_600_000 : match[2] === 'm' ? 60_000 : 1_000;
|
|
211
|
+
return n * unitMs;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The outcome of inspecting a session file against the current keystore and clock. */
|
|
215
|
+
type SessionVerdict =
|
|
216
|
+
| { status: 'live'; session: SessionFile }
|
|
217
|
+
| { status: 'none' | 'foreign' | 'expired' | 'stale' | 'future' | 'malformed' };
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Classifies the session file: read it securely, then check version, shape,
|
|
221
|
+
* clock, keystore binding, and verifier fingerprint in that order. Ordering
|
|
222
|
+
* `expired` before `foreign` means an expired session is pruned regardless of
|
|
223
|
+
* which keystore it was for. Never throws.
|
|
224
|
+
*/
|
|
225
|
+
function evaluateSession(
|
|
226
|
+
sessionPath : string,
|
|
227
|
+
keystorePath : string,
|
|
228
|
+
currentVerifierId : string | undefined,
|
|
229
|
+
now : number,
|
|
230
|
+
): SessionVerdict {
|
|
231
|
+
const session = secureReadSession(sessionPath);
|
|
232
|
+
if (!session) return { status: 'none' };
|
|
233
|
+
if (session.v !== SESSION_VERSION) return { status: 'malformed' };
|
|
234
|
+
if (typeof session.passphrase !== 'string' || typeof session.keystore !== 'string'
|
|
235
|
+
|| typeof session.verifierId !== 'string' || typeof session.allowMainnet !== 'boolean'
|
|
236
|
+
|| typeof session.createdAt !== 'number' || typeof session.expiresAt !== 'number') {
|
|
237
|
+
return { status: 'malformed' };
|
|
238
|
+
}
|
|
239
|
+
if (session.createdAt > now) return { status: 'future' };
|
|
240
|
+
if (now >= session.expiresAt) return { status: 'expired' };
|
|
241
|
+
if (resolve(session.keystore) !== resolve(keystorePath)) return { status: 'foreign' };
|
|
242
|
+
if (currentVerifierId === undefined || session.verifierId !== currentVerifierId) return { status: 'stale' };
|
|
243
|
+
return { status: 'live', session };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Reads and parses the session file with a plaintext secret in mind. On POSIX,
|
|
248
|
+
* opens with `O_NOFOLLOW` (refusing a symlink) and refuses a non-regular file, a
|
|
249
|
+
* file not owned by this user, or one accessible by group or other, best-effort
|
|
250
|
+
* deleting a rejected file and reading only from the opened descriptor (no TOCTOU
|
|
251
|
+
* re-open). On Windows those POSIX guards are skipped (they would throw), so the
|
|
252
|
+
* file is read normally under the same directory ACL the keystore trusts, keeping
|
|
253
|
+
* the session usable rather than silently ignored. Returns `undefined` on any
|
|
254
|
+
* failure; never throws.
|
|
255
|
+
*/
|
|
256
|
+
function secureReadSession(sessionPath: string): SessionFile | undefined {
|
|
257
|
+
let raw: string;
|
|
258
|
+
if (process.platform === 'win32') {
|
|
259
|
+
try {
|
|
260
|
+
raw = readFileSync(sessionPath, 'utf-8');
|
|
261
|
+
} catch {
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
} else {
|
|
265
|
+
let fd: number;
|
|
266
|
+
try {
|
|
267
|
+
fd = openSync(sessionPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
268
|
+
} catch {
|
|
269
|
+
// ENOENT (no session), ELOOP (symlink refused by O_NOFOLLOW), or any other
|
|
270
|
+
// open failure: no usable session.
|
|
271
|
+
return undefined;
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
const st = fstatSync(fd);
|
|
275
|
+
const myUid = typeof process.getuid === 'function' ? process.getuid() : undefined;
|
|
276
|
+
if (!st.isFile() || (myUid !== undefined && st.uid !== myUid) || (st.mode & 0o077) !== 0) {
|
|
277
|
+
// Not a regular file we own with 0600 perms: it was not written by this
|
|
278
|
+
// process. Best-effort remove it (it may hold a plaintext passphrase) and
|
|
279
|
+
// fall back to a prompt.
|
|
280
|
+
try {
|
|
281
|
+
rmSync(sessionPath, { force: true });
|
|
282
|
+
} catch {
|
|
283
|
+
// Cannot remove a file we do not own; ignoring it is enough.
|
|
284
|
+
}
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
raw = readFileSync(fd, 'utf-8');
|
|
288
|
+
} catch {
|
|
289
|
+
return undefined;
|
|
290
|
+
} finally {
|
|
291
|
+
try {
|
|
292
|
+
closeSync(fd);
|
|
293
|
+
} catch {
|
|
294
|
+
// Descriptor already gone; nothing to close.
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
try {
|
|
299
|
+
return JSON.parse(raw) as SessionFile;
|
|
300
|
+
} catch {
|
|
301
|
+
return undefined;
|
|
302
|
+
}
|
|
303
|
+
}
|
package/src/paths.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { blankToUndef } from './types.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* State-location overrides that influence where the CLI keeps its home
|
|
7
|
+
* directory and its two state files. A subset of the broader
|
|
8
|
+
* `ConnectionOverrides`, restated here so this module (the single source of
|
|
9
|
+
* truth for on-disk locations) has no runtime dependency on `config.ts`.
|
|
10
|
+
*/
|
|
11
|
+
export interface PathOverrides {
|
|
12
|
+
/** Explicit home root from the `--home` flag. Wins over `$BTCR2_HOME`. */
|
|
13
|
+
home? : string;
|
|
14
|
+
/** Explicit config-file path from the `--config` flag. Overrides the home default. */
|
|
15
|
+
config? : string;
|
|
16
|
+
/** Explicit keystore path from the `--keystore` flag. Overrides the home default. */
|
|
17
|
+
keystore? : string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Environment variable naming the CLI home directory (all state colocated). */
|
|
21
|
+
export const ENV_HOME = 'BTCR2_HOME';
|
|
22
|
+
|
|
23
|
+
/** The config and keystore file names, kept side by side under the home root. */
|
|
24
|
+
export const CONFIG_FILENAME = 'config.json';
|
|
25
|
+
export const KEYSTORE_FILENAME = 'keystore.json';
|
|
26
|
+
/** The session file name, holding the unlock agent's cached passphrase (ADR 081). */
|
|
27
|
+
export const SESSION_FILENAME = 'session.json';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Resolves the CLI home directory: the single root that holds `config.json` and
|
|
31
|
+
* `keystore.json` side by side (ADR 079). Resolution order, highest wins:
|
|
32
|
+
*
|
|
33
|
+
* 1. `--home <dir>` (the {@link PathOverrides.home} flag)
|
|
34
|
+
* 2. `$BTCR2_HOME`
|
|
35
|
+
* 3. the platform default (see {@link platformDefaultHome})
|
|
36
|
+
*
|
|
37
|
+
* A blank value at any layer defers to the next, mirroring the `blankToUndef`
|
|
38
|
+
* treatment every other precedence layer uses, so an exported-but-empty
|
|
39
|
+
* `BTCR2_HOME` does not resolve the home to a bare relative path.
|
|
40
|
+
*/
|
|
41
|
+
export function resolveHome(overrides?: PathOverrides): string {
|
|
42
|
+
return blankToUndef(overrides?.home)
|
|
43
|
+
?? blankToUndef(process.env[ENV_HOME])
|
|
44
|
+
?? platformDefaultHome();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The default home when no `--home` / `$BTCR2_HOME` override is present, chosen
|
|
49
|
+
* per OS so the location is idiomatic while staying a single colocated dir:
|
|
50
|
+
*
|
|
51
|
+
* - Windows: `%LOCALAPPDATA%\btcr2` (fallback `%APPDATA%\btcr2`, then the user
|
|
52
|
+
* profile), the native place for per-user application state.
|
|
53
|
+
* - Linux / macOS: `~/.btcr2`, the short, teachable dot-directory in the same
|
|
54
|
+
* family as `~/.ssh`, `~/.aws`, and `~/.gnupg`.
|
|
55
|
+
*/
|
|
56
|
+
export function platformDefaultHome(): string {
|
|
57
|
+
if (process.platform === 'win32') {
|
|
58
|
+
const base = blankToUndef(process.env.LOCALAPPDATA)
|
|
59
|
+
?? blankToUndef(process.env.APPDATA)
|
|
60
|
+
?? homedir();
|
|
61
|
+
return join(base, 'btcr2');
|
|
62
|
+
}
|
|
63
|
+
return join(homedir(), '.btcr2');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Default config-file path: `<home>/config.json`. The `--config` flag, when
|
|
68
|
+
* present, overrides it wholesale (it names a specific file, not a home).
|
|
69
|
+
*/
|
|
70
|
+
export function defaultConfigPath(overrides?: PathOverrides): string {
|
|
71
|
+
return join(resolveHome(overrides), CONFIG_FILENAME);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Default keystore path: `<home>/keystore.json`. The `--keystore` flag and a
|
|
76
|
+
* profile's `identity.keystore` (resolved in `config.ts`) override it; this
|
|
77
|
+
* function is the final fallback in that chain.
|
|
78
|
+
*/
|
|
79
|
+
export function defaultKeystorePath(overrides?: PathOverrides): string {
|
|
80
|
+
return join(resolveHome(overrides), KEYSTORE_FILENAME);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Session file path: `<home>/session.json`, where the unlock agent caches the
|
|
85
|
+
* keystore passphrase (ADR 081). Deliberately derived from the home root alone,
|
|
86
|
+
* never from `--config` / `--keystore` or the config file, so `keystore lock`
|
|
87
|
+
* can revoke a session even under a malformed config, and so the read and write
|
|
88
|
+
* paths always agree on one location per home.
|
|
89
|
+
*/
|
|
90
|
+
export function defaultSessionPath(overrides?: PathOverrides): string {
|
|
91
|
+
return join(resolveHome(overrides), SESSION_FILENAME);
|
|
92
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -4,10 +4,18 @@ import type { Btcr2DidDocument, ResolutionOptions } from '@did-btcr2/method';
|
|
|
4
4
|
import type { DidResolutionResult } from '@web5/dids';
|
|
5
5
|
import type { DoctorReport, EffectiveConfig } from './config.js';
|
|
6
6
|
import type { ConfigIssue } from './config-schema.js';
|
|
7
|
+
import type { SessionStatus } from './keystore/session.js';
|
|
7
8
|
|
|
8
9
|
export type NetworkOption = 'bitcoin' | 'testnet3' | 'testnet4' | 'signet' | 'mutinynet' | 'regtest';
|
|
9
10
|
export type OutputFormat = 'json' | 'text';
|
|
10
11
|
|
|
12
|
+
/**
|
|
13
|
+
* How a keystore protects its secrets, as reported by `keystore status` and
|
|
14
|
+
* `btcr2 init`: `encrypted` (passphrase-sealed), `dev` (plaintext, testnet-only),
|
|
15
|
+
* or `absent` (no keystore file yet).
|
|
16
|
+
*/
|
|
17
|
+
export type KeystoreProtectionLabel = 'encrypted' | 'dev' | 'absent';
|
|
18
|
+
|
|
11
19
|
export const SUPPORTED_NETWORKS: NetworkOption[] = [
|
|
12
20
|
'bitcoin', 'testnet3', 'testnet4', 'signet', 'mutinynet', 'regtest'
|
|
13
21
|
];
|
|
@@ -48,6 +56,7 @@ export type CommandResult =
|
|
|
48
56
|
| { action: 'key-export'; data: { keyId: string; publicKey?: string; secretWrittenTo?: string } }
|
|
49
57
|
| { action: 'key-delete'; data: { keyId: string; deleted: true } }
|
|
50
58
|
| { action: 'key-use'; data: { keyId: string; active: true } }
|
|
59
|
+
| { action: 'init'; data: { home: string; config: string; keystore: string; created: string[]; protection: KeystoreProtectionLabel } }
|
|
51
60
|
| { action: 'config-init'; data: { path: string } }
|
|
52
61
|
| { action: 'config-get'; data: unknown }
|
|
53
62
|
| { action: 'config-set'; data: { path: string } }
|
|
@@ -55,8 +64,13 @@ export type CommandResult =
|
|
|
55
64
|
| { action: 'config-list'; data: unknown }
|
|
56
65
|
| { action: 'config-validate'; data: { ok: boolean; issues: ConfigIssue[] } }
|
|
57
66
|
| { action: 'config-effective'; data: EffectiveConfig }
|
|
58
|
-
| { action: 'config-path'; data: { config: string; keystore: string } }
|
|
67
|
+
| { action: 'config-path'; data: { home: string; config: string; keystore: string } }
|
|
59
68
|
| { action: 'config-doctor'; data: DoctorReport }
|
|
69
|
+
| { action: 'keystore-init'; data: { path: string; protection: 'encrypted' | 'dev' } }
|
|
70
|
+
| { action: 'keystore-status'; data: { path: string; protection: KeystoreProtectionLabel; established: boolean; keyCount: number; active: string | undefined; session: SessionStatus } }
|
|
71
|
+
| { action: 'keystore-change-passphrase'; data: { path: string; rekeyed: number } }
|
|
72
|
+
| { action: 'keystore-unlock'; data: { keystore: string; expiresAt: number; ttlSeconds: number } }
|
|
73
|
+
| { action: 'keystore-lock'; data: { path: string; cleared: boolean } }
|
|
60
74
|
| { action: 'profile-add'; data: { profile: string } }
|
|
61
75
|
| { action: 'profile-use'; data: { profile: string } }
|
|
62
76
|
| { action: 'profile-show'; data: unknown }
|
|
@@ -66,6 +80,7 @@ export interface GlobalOptions {
|
|
|
66
80
|
output : OutputFormat;
|
|
67
81
|
verbose : boolean;
|
|
68
82
|
quiet : boolean;
|
|
83
|
+
home? : string;
|
|
69
84
|
config? : string;
|
|
70
85
|
profile? : string;
|
|
71
86
|
btcRest? : string;
|