@did-btcr2/cli 0.16.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.
Files changed (40) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/cjs/index.js +310 -42
  3. package/dist/esm/src/commands/init.js +7 -1
  4. package/dist/esm/src/commands/init.js.map +1 -1
  5. package/dist/esm/src/commands/keystore.js +107 -8
  6. package/dist/esm/src/commands/keystore.js.map +1 -1
  7. package/dist/esm/src/config.js +27 -6
  8. package/dist/esm/src/config.js.map +1 -1
  9. package/dist/esm/src/keystore/file-key-store.js +48 -0
  10. package/dist/esm/src/keystore/file-key-store.js.map +1 -1
  11. package/dist/esm/src/keystore/passphrase.js +13 -0
  12. package/dist/esm/src/keystore/passphrase.js.map +1 -1
  13. package/dist/esm/src/keystore/session.js +250 -0
  14. package/dist/esm/src/keystore/session.js.map +1 -0
  15. package/dist/esm/src/paths.js +12 -0
  16. package/dist/esm/src/paths.js.map +1 -1
  17. package/dist/esm/src/types.js.map +1 -1
  18. package/dist/types/src/commands/init.d.ts.map +1 -1
  19. package/dist/types/src/commands/keystore.d.ts +5 -4
  20. package/dist/types/src/commands/keystore.d.ts.map +1 -1
  21. package/dist/types/src/config.d.ts.map +1 -1
  22. package/dist/types/src/keystore/file-key-store.d.ts +16 -0
  23. package/dist/types/src/keystore/file-key-store.d.ts.map +1 -1
  24. package/dist/types/src/keystore/passphrase.d.ts +10 -0
  25. package/dist/types/src/keystore/passphrase.d.ts.map +1 -1
  26. package/dist/types/src/keystore/session.d.ts +105 -0
  27. package/dist/types/src/keystore/session.d.ts.map +1 -0
  28. package/dist/types/src/paths.d.ts +10 -0
  29. package/dist/types/src/paths.d.ts.map +1 -1
  30. package/dist/types/src/types.d.ts +15 -0
  31. package/dist/types/src/types.d.ts.map +1 -1
  32. package/package.json +4 -4
  33. package/src/commands/init.ts +7 -1
  34. package/src/commands/keystore.ts +143 -9
  35. package/src/config.ts +28 -6
  36. package/src/keystore/file-key-store.ts +43 -0
  37. package/src/keystore/passphrase.ts +23 -0
  38. package/src/keystore/session.ts +303 -0
  39. package/src/paths.ts +13 -0
  40. package/src/types.ts +4 -1
@@ -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 CHANGED
@@ -23,6 +23,8 @@ export const ENV_HOME = 'BTCR2_HOME';
23
23
  /** The config and keystore file names, kept side by side under the home root. */
24
24
  export const CONFIG_FILENAME = 'config.json';
25
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';
26
28
 
27
29
  /**
28
30
  * Resolves the CLI home directory: the single root that holds `config.json` and
@@ -77,3 +79,14 @@ export function defaultConfigPath(overrides?: PathOverrides): string {
77
79
  export function defaultKeystorePath(overrides?: PathOverrides): string {
78
80
  return join(resolveHome(overrides), KEYSTORE_FILENAME);
79
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,6 +4,7 @@ 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';
@@ -66,8 +67,10 @@ export type CommandResult =
66
67
  | { action: 'config-path'; data: { home: string; config: string; keystore: string } }
67
68
  | { action: 'config-doctor'; data: DoctorReport }
68
69
  | { action: 'keystore-init'; data: { path: string; protection: 'encrypted' | 'dev' } }
69
- | { action: 'keystore-status'; data: { path: string; protection: KeystoreProtectionLabel; established: boolean; keyCount: number; active: string | undefined } }
70
+ | { action: 'keystore-status'; data: { path: string; protection: KeystoreProtectionLabel; established: boolean; keyCount: number; active: string | undefined; session: SessionStatus } }
70
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 } }
71
74
  | { action: 'profile-add'; data: { profile: string } }
72
75
  | { action: 'profile-use'; data: { profile: string } }
73
76
  | { action: 'profile-show'; data: unknown }