@oneie/cli 4.1.0 → 4.2.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.
@@ -0,0 +1,425 @@
1
+ // CLOSED = satisfied. A closed row is never scheduled into a wave and every
2
+ // edge pointing AT one is dropped before the graph is built.
3
+ export const CLOSED = new Set(['done', 'verified', 'dissolved', 'failed']);
4
+ const HINT_LINE = /^\s*(model|effort|touches|accept)\s*:\s*(.*)$/i;
5
+ // Dispatch hints live in a row's notes as labelled lines, one per line,
6
+ // case-insensitive key, anywhere in the prose.
7
+ export function parseHints(notes) {
8
+ const hints = { touches: [] };
9
+ if (!notes)
10
+ return hints;
11
+ for (const line of notes.split('\n')) {
12
+ const m = HINT_LINE.exec(line);
13
+ if (!m)
14
+ continue;
15
+ const key = m[1].toLowerCase();
16
+ const value = m[2].trim();
17
+ if (!value)
18
+ continue;
19
+ if (key === 'model')
20
+ hints.model = value;
21
+ else if (key === 'effort')
22
+ hints.effort = value;
23
+ else if (key === 'accept')
24
+ hints.accept = value;
25
+ else if (key === 'touches')
26
+ hints.touches = value.split(',').map((s) => s.trim()).filter(Boolean);
27
+ }
28
+ return hints;
29
+ }
30
+ // Root + all descendants via `parent`, root included; [] if root absent.
31
+ export function subtree(rows, rootTid) {
32
+ const byTid = new Map(rows.map((r) => [r.tid, r]));
33
+ if (!byTid.has(rootTid))
34
+ return [];
35
+ const children = new Map();
36
+ for (const r of rows) {
37
+ if (r.parent) {
38
+ const arr = children.get(r.parent) ?? [];
39
+ arr.push(r);
40
+ children.set(r.parent, arr);
41
+ }
42
+ }
43
+ const out = [];
44
+ const seen = new Set();
45
+ const queue = [rootTid];
46
+ while (queue.length > 0) {
47
+ const tid = queue.shift();
48
+ if (seen.has(tid))
49
+ continue;
50
+ seen.add(tid);
51
+ const r = byTid.get(tid);
52
+ if (!r)
53
+ continue;
54
+ out.push(r);
55
+ for (const c of children.get(tid) ?? [])
56
+ queue.push(c.tid);
57
+ }
58
+ return out;
59
+ }
60
+ export function planWaves(rows) {
61
+ const fullMap = new Map();
62
+ for (const r of rows)
63
+ fullMap.set(r.tid, r);
64
+ const closed = [];
65
+ const nodeIds = [];
66
+ for (const r of rows) {
67
+ if (CLOSED.has(r.status))
68
+ closed.push(r.tid);
69
+ else
70
+ nodeIds.push(r.tid);
71
+ }
72
+ const nodeSet = new Set(nodeIds);
73
+ const missing = [];
74
+ const outsideMarked = new Set();
75
+ const outside = [];
76
+ const ownerless = [];
77
+ const implied = [];
78
+ const preds = new Map();
79
+ const succs = new Map();
80
+ for (const tid of nodeIds) {
81
+ preds.set(tid, new Set());
82
+ succs.set(tid, new Set());
83
+ }
84
+ const addEdge = (prereq, waiter) => {
85
+ preds.get(waiter)?.add(prereq);
86
+ succs.get(prereq)?.add(waiter);
87
+ };
88
+ // blockedBy edges + missing/outside accounting
89
+ for (const tid of nodeIds) {
90
+ const r = fullMap.get(tid);
91
+ if (!r.assignee)
92
+ ownerless.push(tid);
93
+ const blockedByArr = r.blockedBy ?? [];
94
+ const absent = [];
95
+ let inSetOpen = 0;
96
+ for (const b of blockedByArr) {
97
+ const br = fullMap.get(b);
98
+ if (!br) {
99
+ absent.push(b);
100
+ continue;
101
+ }
102
+ if (CLOSED.has(br.status))
103
+ continue;
104
+ inSetOpen += 1;
105
+ if (nodeSet.has(b))
106
+ addEdge(b, tid);
107
+ }
108
+ // A blocker absent from the rows is ambiguous: the board read is usually
109
+ // ACTIVE rows only, so a CLOSED blocker is absent too, and so is an open one
110
+ // outside this goal's subtree. The server's openBlockers settles it — never
111
+ // the raw blockedBy (a closed blocker once read as "absent", which is the
112
+ // defect this module exists to stop repeating). Only when the server gave no
113
+ // count is an absent blocker unknowable, and only then is it `missing`.
114
+ if (r.openBlockers === undefined) {
115
+ for (const b of absent)
116
+ missing.push({ tid, blockedBy: b });
117
+ }
118
+ else if (r.openBlockers > inSetOpen) {
119
+ outsideMarked.add(tid);
120
+ outside.push({ tid, open: r.openBlockers - inSetOpen });
121
+ }
122
+ }
123
+ // containment: a parent waits for every non-closed child present in the set.
124
+ for (const tid of nodeIds) {
125
+ const r = fullMap.get(tid);
126
+ if (r.parent && nodeSet.has(r.parent)) {
127
+ addEdge(tid, r.parent);
128
+ implied.push({ tid: r.parent, waitsFor: tid, reason: 'containment' });
129
+ }
130
+ }
131
+ const priorityOf = (tid) => fullMap.get(tid)?.priority ?? 0;
132
+ const runKahn = () => {
133
+ const inDeg = new Map();
134
+ for (const tid of nodeIds)
135
+ inDeg.set(tid, preds.get(tid)?.size ?? 0);
136
+ const scheduled = new Set();
137
+ const waves = [];
138
+ let current = nodeIds.filter((t) => inDeg.get(t) === 0 && !outsideMarked.has(t));
139
+ while (current.length > 0) {
140
+ for (const t of current)
141
+ scheduled.add(t);
142
+ waves.push(current);
143
+ const nextCandidates = new Set();
144
+ for (const t of current) {
145
+ for (const s of succs.get(t) ?? []) {
146
+ const d = (inDeg.get(s) ?? 0) - 1;
147
+ inDeg.set(s, d);
148
+ if (d === 0)
149
+ nextCandidates.add(s);
150
+ }
151
+ }
152
+ current = [...nextCandidates].filter((t) => !outsideMarked.has(t) && !scheduled.has(t));
153
+ }
154
+ return { waves, scheduled };
155
+ };
156
+ // Fixpoint: run Kahn's algorithm, look for same-wave `touches:` collisions,
157
+ // add the implied serialising edge, and recompute until stable.
158
+ let kahn = runKahn();
159
+ const seenTouchesEdge = new Set();
160
+ const maxIters = nodeIds.length + 5;
161
+ for (let iter = 0; iter < maxIters; iter++) {
162
+ let added = false;
163
+ for (const wave of kahn.waves) {
164
+ if (wave.length < 2)
165
+ continue;
166
+ const touchesOf = new Map();
167
+ for (const tid of wave)
168
+ touchesOf.set(tid, parseHints(fullMap.get(tid)?.notes).touches);
169
+ for (let i = 0; i < wave.length; i++) {
170
+ for (let j = i + 1; j < wave.length; j++) {
171
+ const a = wave[i];
172
+ const b = wave[j];
173
+ const aTouches = touchesOf.get(a) ?? [];
174
+ const bTouches = touchesOf.get(b) ?? [];
175
+ const shared = aTouches.find((p) => bTouches.includes(p));
176
+ if (!shared)
177
+ continue;
178
+ if (preds.get(a)?.has(b) || preds.get(b)?.has(a))
179
+ continue;
180
+ const pa = priorityOf(a);
181
+ const pb = priorityOf(b);
182
+ let winner;
183
+ let loser;
184
+ if (pa !== pb) {
185
+ winner = pa > pb ? a : b;
186
+ loser = pa > pb ? b : a;
187
+ }
188
+ else {
189
+ // tie -> lexically larger tid waits
190
+ winner = a < b ? a : b;
191
+ loser = a < b ? b : a;
192
+ }
193
+ const key = `${loser}->${winner}`;
194
+ if (seenTouchesEdge.has(key))
195
+ continue;
196
+ seenTouchesEdge.add(key);
197
+ addEdge(winner, loser);
198
+ implied.push({ tid: loser, waitsFor: winner, reason: 'touches', path: shared });
199
+ added = true;
200
+ }
201
+ }
202
+ }
203
+ if (!added)
204
+ break;
205
+ kahn = runKahn();
206
+ }
207
+ // Leftover = never scheduled and not already explicitly marked outside.
208
+ const leftover = nodeIds.filter((t) => !kahn.scheduled.has(t) && !outsideMarked.has(t));
209
+ const leftoverSet = new Set(leftover);
210
+ const cycles = [];
211
+ {
212
+ let index = 0;
213
+ const indices = new Map();
214
+ const lowlink = new Map();
215
+ const onStack = new Set();
216
+ const stack = [];
217
+ const sccs = [];
218
+ const strongconnect = (v) => {
219
+ indices.set(v, index);
220
+ lowlink.set(v, index);
221
+ index += 1;
222
+ stack.push(v);
223
+ onStack.add(v);
224
+ for (const w of preds.get(v) ?? []) {
225
+ if (!leftoverSet.has(w))
226
+ continue;
227
+ if (!indices.has(w)) {
228
+ strongconnect(w);
229
+ lowlink.set(v, Math.min(lowlink.get(v), lowlink.get(w)));
230
+ }
231
+ else if (onStack.has(w)) {
232
+ lowlink.set(v, Math.min(lowlink.get(v), indices.get(w)));
233
+ }
234
+ }
235
+ if (lowlink.get(v) === indices.get(v)) {
236
+ const comp = [];
237
+ let w;
238
+ do {
239
+ w = stack.pop();
240
+ onStack.delete(w);
241
+ comp.push(w);
242
+ } while (w !== v);
243
+ sccs.push(comp);
244
+ }
245
+ };
246
+ for (const v of leftover) {
247
+ if (!indices.has(v))
248
+ strongconnect(v);
249
+ }
250
+ const cycleMembers = new Set();
251
+ for (const comp of sccs) {
252
+ const isCycle = comp.length > 1 || preds.get(comp[0])?.has(comp[0]);
253
+ if (isCycle) {
254
+ cycles.push(comp.slice().sort());
255
+ for (const t of comp)
256
+ cycleMembers.add(t);
257
+ }
258
+ }
259
+ // Downstream of a cycle (or of an outside-marked node) but not in a
260
+ // cycle itself: still excluded from waves, reported as `outside`.
261
+ for (const t of leftover) {
262
+ if (cycleMembers.has(t))
263
+ continue;
264
+ const unresolved = [...(preds.get(t) ?? [])].filter((p) => !kahn.scheduled.has(p)).length;
265
+ outside.push({ tid: t, open: unresolved });
266
+ }
267
+ }
268
+ // Longest path (by node count) over the final DAG, in execution order.
269
+ const longest = new Map();
270
+ const pathParent = new Map();
271
+ for (const wave of kahn.waves) {
272
+ for (const t of wave) {
273
+ let best = 1;
274
+ let bestParent;
275
+ for (const p of preds.get(t) ?? []) {
276
+ if (!kahn.scheduled.has(p))
277
+ continue;
278
+ const val = (longest.get(p) ?? 1) + 1;
279
+ if (val > best) {
280
+ best = val;
281
+ bestParent = p;
282
+ }
283
+ }
284
+ longest.set(t, best);
285
+ pathParent.set(t, bestParent);
286
+ }
287
+ }
288
+ let bestTid;
289
+ let bestLen = 0;
290
+ for (const t of kahn.waves.flat()) {
291
+ const l = longest.get(t) ?? 1;
292
+ if (l > bestLen) {
293
+ bestLen = l;
294
+ bestTid = t;
295
+ }
296
+ }
297
+ const pathTids = [];
298
+ let cur = bestTid;
299
+ while (cur !== undefined) {
300
+ pathTids.unshift(cur);
301
+ cur = pathParent.get(cur);
302
+ }
303
+ const criticalPath = { hops: Math.max(pathTids.length - 1, 0), tids: pathTids };
304
+ const waves = kahn.waves.map((tids, i) => ({
305
+ n: i + 1,
306
+ tids: tids.slice().sort((a, b) => priorityOf(b) - priorityOf(a)),
307
+ }));
308
+ const seenOutside = new Set();
309
+ const outsideDeduped = [];
310
+ for (const o of outside) {
311
+ if (seenOutside.has(o.tid))
312
+ continue;
313
+ seenOutside.add(o.tid);
314
+ outsideDeduped.push(o);
315
+ }
316
+ return {
317
+ waves,
318
+ criticalPath,
319
+ cycles,
320
+ missing,
321
+ outside: outsideDeduped,
322
+ ownerless,
323
+ implied,
324
+ closed,
325
+ };
326
+ }
327
+ export function toDispatch(res, rows, meta) {
328
+ const byTid = new Map(rows.map((r) => [r.tid, r]));
329
+ const waves = res.waves.map((w) => ({
330
+ n: w.n,
331
+ rows: w.tids.map((tid) => {
332
+ const r = byTid.get(tid);
333
+ const hints = parseHints(r?.notes);
334
+ return {
335
+ tid,
336
+ name: r?.name ?? '',
337
+ assignee: r?.assignee,
338
+ model: hints.model,
339
+ effort: hints.effort,
340
+ touches: hints.touches,
341
+ accept: hints.accept,
342
+ };
343
+ }),
344
+ }));
345
+ const warnings = [];
346
+ for (const c of res.cycles)
347
+ warnings.push(`cycle: ${c.join(', ')}`);
348
+ for (const m of res.missing)
349
+ warnings.push(`${m.tid} blocked by missing ${m.blockedBy}`);
350
+ for (const o of res.outside)
351
+ warnings.push(`${o.tid} waits outside plan (open=${o.open})`);
352
+ if (res.ownerless.length > 0)
353
+ warnings.push(`${res.ownerless.length} rows ownerless`);
354
+ return {
355
+ goal: meta.goal,
356
+ asOf: meta.asOf,
357
+ truncated: meta.truncated,
358
+ waves,
359
+ criticalPath: res.criticalPath,
360
+ warnings,
361
+ };
362
+ }
363
+ // Chains tids in order: edits[i] = { tid: tids[i+1], addBlockedBy: [tids[i]] }.
364
+ export function sequenceEdits(tids) {
365
+ if (tids.length < 2)
366
+ return { ok: false, error: 'need at least two tids' };
367
+ const seen = new Set();
368
+ for (const t of tids) {
369
+ if (seen.has(t))
370
+ return { ok: false, error: `duplicate tid ${t}` };
371
+ seen.add(t);
372
+ }
373
+ const edits = [];
374
+ for (let i = 0; i < tids.length - 1; i++) {
375
+ edits.push({ tid: tids[i + 1], addBlockedBy: [tids[i]] });
376
+ }
377
+ return { ok: true, edits };
378
+ }
379
+ export function renderPlan(res, rows, opts) {
380
+ const byTid = new Map(rows.map((r) => [r.tid, r]));
381
+ const cpSet = new Set(res.criticalPath.tids);
382
+ const lines = [];
383
+ const goal = opts?.goal ?? '';
384
+ lines.push(`plan ${goal} — ${res.waves.length} waves · critical path ${res.criticalPath.hops} hops · ${rows.length} rows (${res.closed.length} closed skipped)`);
385
+ for (const wave of res.waves) {
386
+ lines.push(`wave ${wave.n}`);
387
+ for (const tid of wave.tids) {
388
+ const r = byTid.get(tid);
389
+ const name = (r?.name ?? '').slice(0, 60);
390
+ const assignee = r?.assignee ?? '-';
391
+ const priority = r?.priority ?? 0;
392
+ const marker = cpSet.has(tid) ? ' *' : '';
393
+ lines.push(` ${tid} p${priority} @${assignee} ${name}${marker}`);
394
+ }
395
+ }
396
+ if (res.cycles.length > 0) {
397
+ lines.push('cycles');
398
+ for (const c of res.cycles)
399
+ lines.push(` ${c.join(', ')}`);
400
+ }
401
+ if (res.missing.length > 0) {
402
+ lines.push('missing blockers');
403
+ for (const m of res.missing)
404
+ lines.push(` ${m.tid} → ${m.blockedBy}`);
405
+ }
406
+ if (res.outside.length > 0) {
407
+ lines.push('waits outside plan');
408
+ for (const o of res.outside)
409
+ lines.push(` ${o.tid} (open=${o.open})`);
410
+ }
411
+ if (res.ownerless.length > 0) {
412
+ lines.push('ownerless');
413
+ for (const tid of res.ownerless)
414
+ lines.push(` ${tid}`);
415
+ }
416
+ if (res.implied.length > 0) {
417
+ lines.push('implied order');
418
+ for (const i of res.implied) {
419
+ const suffix = i.reason === 'touches' && i.path ? `: ${i.path}` : '';
420
+ lines.push(` ${i.tid} waits for ${i.waitsFor} (${i.reason}${suffix})`);
421
+ }
422
+ }
423
+ lines.push(`critical path: ${res.criticalPath.tids.length > 0 ? res.criticalPath.tids.join(' → ') : '(none)'}`);
424
+ return lines.join('\n');
425
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The sealed envelope, as far as THIS module is concerned.
3
+ *
4
+ * Deliberately a local structural type rather than an import of
5
+ * `@oneie/sdk/vault-file`'s `VaultBlob`. Nothing here seals or opens anything —
6
+ * it moves an opaque JSON object on and off disk and reads exactly three fields
7
+ * of it. Importing the crypto module to borrow a type would drag Argon2id into
8
+ * the dependency graph of a file that never derives a key, and would couple the
9
+ * CLI's two-runtime-dep budget to a subpath that has to be linked before it
10
+ * resolves. The full type lives with the code that actually uses it.
11
+ */
12
+ export interface SealedVault {
13
+ v: 1;
14
+ wrap: 'passphrase' | 'keychain';
15
+ authPub?: string;
16
+ [k: string]: unknown;
17
+ }
18
+ export declare const VAULT_FILE_NAME = "wallet.json";
19
+ export interface VaultWriteResult {
20
+ ok: boolean;
21
+ path?: string;
22
+ error?: string;
23
+ }
24
+ /** Where a project's vault lives. */
25
+ export declare function vaultPath(dir: string): string;
26
+ /**
27
+ * Write the sealed vault. Ignore entry FIRST — same order, same reason as the
28
+ * API key: a secret written before it is ignored is exposed for the width of the
29
+ * gap, and the gap is where `git add -A` lives. Refuses rather than writing an
30
+ * unignorable credential.
31
+ */
32
+ export declare function writeVaultFolder(dir: string, blob: SealedVault): VaultWriteResult;
33
+ /** Read a sealed vault, or null when the folder has none. Never throws. */
34
+ export declare function readVaultFolder(dir: string): SealedVault | null;
35
+ /**
36
+ * The Keychain service name a vault's wrapping secret is stored under.
37
+ *
38
+ * Scoped by the vault's public identity rather than a constant, so two projects
39
+ * on one machine do not fight over one entry — and so deleting one wallet's
40
+ * secret cannot silently unlock another's.
41
+ */
42
+ export declare function keychainService(authPub: string): string;
43
+ export type KeychainResult = {
44
+ ok: true;
45
+ value?: string;
46
+ } | {
47
+ ok: false;
48
+ error: string;
49
+ };
50
+ /** macOS only — every other platform gets a clear refusal, never a silent no-op. */
51
+ export declare function keychainAvailable(): boolean;
52
+ /**
53
+ * Store the wrapping secret in Apple Keychain, gated by the user's login
54
+ * keychain ACL.
55
+ *
56
+ * `-w` takes the secret on argv, which is normally the thing to avoid — argv is
57
+ * world-readable in `ps`. It is accepted HERE because `security` offers no stdin
58
+ * form for add-generic-password, and the exposure is a race against a local
59
+ * process that could read the unlocked vault anyway. The mnemonic itself never
60
+ * appears on argv; only this random wrapper does, and it is useless without the
61
+ * file.
62
+ */
63
+ export declare function keychainStore(authPub: string, secret: string): KeychainResult;
64
+ /** Read the wrapping secret back. This is the call that prompts for Touch ID. */
65
+ export declare function keychainRead(authPub: string): KeychainResult;
66
+ /**
67
+ * The 24 words laid out for transcription, numbered.
68
+ *
69
+ * Numbered because BIP-39 order is load-bearing and an unnumbered column of 24
70
+ * words is trivially copied out of sequence — a wallet that restores to the
71
+ * wrong addresses with no error. Pure, so it is testable without a wallet.
72
+ */
73
+ export declare function paperSheet(mnemonic: string, addresses: Record<string, string>): string;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * vaultfile.ts — the encrypted wallet folder, and the three ways out of it.
3
+ *
4
+ * `.one/wallet.json` is a sealed 24-word mnemonic. From it `recoverWallet()`
5
+ * derives all four chain keys offline, so the file IS the wallet: lose it and
6
+ * the phrase and the money is gone; copy it and the copy is equally the wallet.
7
+ * That is the property the three export paths below exist to serve.
8
+ *
9
+ * THE KEYS NEVER LEAVE THIS MACHINE unless the human deliberately moves them,
10
+ * and there are exactly three doors:
11
+ * · PAPER — the 24 words, printed once, offline forever.
12
+ * · KEYCHAIN — Apple Keychain (or any OS keystore) holds the WRAPPING secret,
13
+ * released by biometrics. The vault stays on disk.
14
+ * · ADDRESSES — public only. `wallet register` uploads these to be paid at;
15
+ * they are not key material and never were.
16
+ * Nothing else is an export. In particular nothing here ever posts a mnemonic,
17
+ * a private key, or a passphrase to a server — there is no code path for it.
18
+ *
19
+ * WHAT THE SECURE ENCLAVE ACTUALLY DOES, because the difference matters and is
20
+ * easy to oversell: the SE holds NIST P-256 keys ONLY. It cannot hold the
21
+ * ed25519 (Sui, Solana) or secp256k1 (EVM, BTC) keys this wallet is made of. So
22
+ * "open and close it with your biometrics" is TRUE — Touch ID releases the
23
+ * wrapping secret that decrypts the vault — while "your keys live in the Secure
24
+ * Enclave" is FALSE. Once unlocked, the chain keys are in this process's memory
25
+ * like any other program's. That is a real and useful boundary; it is not a
26
+ * hardware signer, and the code says so where a reader will meet it.
27
+ *
28
+ * The write ceremony is `keyfile.ts`'s, reused rather than re-derived: ignore
29
+ * entry before the file, 0700 directory, O_NOFOLLOW writes, symlink refusal.
30
+ * A second implementation of that is a second thing to get wrong.
31
+ */
32
+ import { existsSync, readFileSync, lstatSync } from 'node:fs';
33
+ import { join } from 'node:path';
34
+ import { spawnSync } from 'node:child_process';
35
+ import { ensureIgnored, KEY_DIR_NAME, LEGACY_KEY_DIR_NAME, writeSecret, canonicalDir } from './keyfile.js';
36
+ export const VAULT_FILE_NAME = 'wallet.json';
37
+ /** Where a project's vault lives. */
38
+ export function vaultPath(dir) {
39
+ const root = canonicalDir(dir);
40
+ const current = join(root, KEY_DIR_NAME, VAULT_FILE_NAME);
41
+ if (existsSync(current))
42
+ return current;
43
+ const legacy = join(root, LEGACY_KEY_DIR_NAME, VAULT_FILE_NAME);
44
+ // A vault minted before the rename still opens. New ones are always written
45
+ // to the current directory — vaultPath is used for BOTH, so the fallback only
46
+ // wins when a legacy file is actually there.
47
+ return existsSync(legacy) ? legacy : current;
48
+ }
49
+ /**
50
+ * Write the sealed vault. Ignore entry FIRST — same order, same reason as the
51
+ * API key: a secret written before it is ignored is exposed for the width of the
52
+ * gap, and the gap is where `git add -A` lives. Refuses rather than writing an
53
+ * unignorable credential.
54
+ */
55
+ export function writeVaultFolder(dir, blob) {
56
+ const root = canonicalDir(dir);
57
+ if (!existsSync(root))
58
+ return { ok: false, error: `no such directory: ${root}` };
59
+ if (!ensureIgnored(root)) {
60
+ return { ok: false, error: 'could not write .gitignore — refusing to write a wallet git can see' };
61
+ }
62
+ const path = vaultPath(root);
63
+ if (existsSync(path)) {
64
+ // Overwriting a vault destroys a wallet. There is no undo and no backup,
65
+ // so this refuses and makes the operator move the old one by hand.
66
+ return { ok: false, error: `${path} already exists — move it aside first; overwriting destroys the wallet it holds` };
67
+ }
68
+ try {
69
+ writeSecret(path, JSON.stringify(blob, null, 2) + '\n');
70
+ return { ok: true, path };
71
+ }
72
+ catch (err) {
73
+ return { ok: false, error: `write failed: ${err.message}` };
74
+ }
75
+ }
76
+ /** Read a sealed vault, or null when the folder has none. Never throws. */
77
+ export function readVaultFolder(dir) {
78
+ const path = vaultPath(dir);
79
+ if (!existsSync(path))
80
+ return null;
81
+ try {
82
+ // lstat, not stat: a symlinked vault is refused rather than followed to a
83
+ // file whose mode looks fine.
84
+ const st = lstatSync(path);
85
+ if (st.isSymbolicLink())
86
+ return null;
87
+ if ((st.mode & 0o077) !== 0)
88
+ return null;
89
+ const blob = JSON.parse(readFileSync(path, 'utf8'));
90
+ return blob?.v === 1 ? blob : null;
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ }
96
+ // ─── Keychain ────────────────────────────────────────────────────────────────
97
+ /**
98
+ * The Keychain service name a vault's wrapping secret is stored under.
99
+ *
100
+ * Scoped by the vault's public identity rather than a constant, so two projects
101
+ * on one machine do not fight over one entry — and so deleting one wallet's
102
+ * secret cannot silently unlock another's.
103
+ */
104
+ export function keychainService(authPub) {
105
+ return `one.ie.wallet.${authPub}`;
106
+ }
107
+ /** macOS only — every other platform gets a clear refusal, never a silent no-op. */
108
+ export function keychainAvailable() {
109
+ return process.platform === 'darwin' && spawnSync('which', ['security']).status === 0;
110
+ }
111
+ /**
112
+ * Store the wrapping secret in Apple Keychain, gated by the user's login
113
+ * keychain ACL.
114
+ *
115
+ * `-w` takes the secret on argv, which is normally the thing to avoid — argv is
116
+ * world-readable in `ps`. It is accepted HERE because `security` offers no stdin
117
+ * form for add-generic-password, and the exposure is a race against a local
118
+ * process that could read the unlocked vault anyway. The mnemonic itself never
119
+ * appears on argv; only this random wrapper does, and it is useless without the
120
+ * file.
121
+ */
122
+ export function keychainStore(authPub, secret) {
123
+ if (!keychainAvailable())
124
+ return { ok: false, error: 'Keychain is macOS-only' };
125
+ const r = spawnSync('security', [
126
+ 'add-generic-password',
127
+ '-a', process.env.USER ?? 'one',
128
+ '-s', keychainService(authPub),
129
+ '-w', secret,
130
+ '-U',
131
+ '-T', '', // no app is pre-trusted: every read prompts, which is the biometric gate
132
+ ]);
133
+ if (r.status !== 0) {
134
+ return { ok: false, error: (r.stderr?.toString() || 'security add-generic-password failed').trim() };
135
+ }
136
+ return { ok: true };
137
+ }
138
+ /** Read the wrapping secret back. This is the call that prompts for Touch ID. */
139
+ export function keychainRead(authPub) {
140
+ if (!keychainAvailable())
141
+ return { ok: false, error: 'Keychain is macOS-only' };
142
+ const r = spawnSync('security', [
143
+ 'find-generic-password',
144
+ '-a', process.env.USER ?? 'one',
145
+ '-s', keychainService(authPub),
146
+ '-w',
147
+ ]);
148
+ if (r.status !== 0) {
149
+ return { ok: false, error: 'no Keychain entry for this wallet (or access was denied)' };
150
+ }
151
+ return { ok: true, value: r.stdout.toString().trim() };
152
+ }
153
+ // ─── Paper ───────────────────────────────────────────────────────────────────
154
+ /**
155
+ * The 24 words laid out for transcription, numbered.
156
+ *
157
+ * Numbered because BIP-39 order is load-bearing and an unnumbered column of 24
158
+ * words is trivially copied out of sequence — a wallet that restores to the
159
+ * wrong addresses with no error. Pure, so it is testable without a wallet.
160
+ */
161
+ export function paperSheet(mnemonic, addresses) {
162
+ const words = mnemonic.trim().split(/\s+/);
163
+ const rows = [];
164
+ const half = Math.ceil(words.length / 2);
165
+ for (let i = 0; i < half; i++) {
166
+ const l = `${String(i + 1).padStart(2, ' ')}. ${(words[i] ?? '').padEnd(10)}`;
167
+ const j = i + half;
168
+ const r = j < words.length ? `${String(j + 1).padStart(2, ' ')}. ${words[j]}` : '';
169
+ rows.push(` ${l} ${r}`.trimEnd());
170
+ }
171
+ return [
172
+ 'ONE — wallet recovery sheet',
173
+ '',
174
+ 'These 24 words ARE the wallet. Anyone who reads them owns it.',
175
+ 'Write them down in this order. Store the paper offline.',
176
+ '',
177
+ ...rows,
178
+ '',
179
+ 'Receiving addresses (public — safe to share, this is how you get paid):',
180
+ ...Object.entries(addresses).map(([chain, addr]) => ` ${chain.padEnd(5)} ${addr}`),
181
+ '',
182
+ 'Restore with: one wallet open --recover',
183
+ ].join('\n');
184
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function mediaCmd(): Command;