| 155 |
185
|
|
: join(homedir(), ".openagents", "identity");
|
| 156 |
186
|
|
};
|
| 157 |
187
|
|
|
| 158 |
|
- |
/** The seed file itself: one line, the mnemonic, mode `0600`. */
|
|
188
|
+ |
/**
|
|
189
|
+ |
* The seed file: a sealed envelope under the OS keychain, or the mnemonic itself
|
|
190
|
+ |
* where there is no keychain. Mode `0600` either way.
|
|
191
|
+ |
*/
|
| 159 |
192
|
|
export const seedPath = (): string => join(seedDirectory(), "seed");
|
| 160 |
193
|
|
|
|
194
|
+ |
/** Where the atomic rewrite stages, so the phrase is never in two files. */
|
|
195
|
+ |
const seedTempPath = (): string => join(seedDirectory(), "seed.tmp");
|
|
196
|
+ |
|
| 161 |
197
|
|
/** True when a seed is already stored. Presence only; the bytes stay on disk. */
|
| 162 |
198
|
|
export const seedPresent = (): boolean => existsSync(seedPath());
|
| 163 |
199
|
|
|
|
200
|
+ |
// ---------------------------------------------------------------------------
|
|
201
|
+ |
// protection at rest
|
|
202
|
+ |
// ---------------------------------------------------------------------------
|
|
203
|
+ |
|
|
204
|
+ |
/**
|
|
205
|
+ |
* What is actually protecting the stored seed. Every surface that shows an
|
|
206
|
+ |
* identity reports this, because the difference between the two is the whole
|
|
207
|
+ |
* security posture of the machine and a person cannot infer it from the path.
|
|
208
|
+ |
*/
|
|
209
|
+ |
export type SeedProtection = "os_keychain" | "plaintext_file";
|
|
210
|
+ |
|
|
211
|
+ |
/** True when the file on disk is ciphertext rather than the phrase. */
|
|
212
|
+ |
export const seedEncryptedAtRest = (protection: SeedProtection): boolean =>
|
|
213
|
+ |
protection === "os_keychain";
|
|
214
|
+ |
|
|
215
|
+ |
/**
|
|
216
|
+ |
* The sentence a person reads. It says what is protecting the seed and, for the
|
|
217
|
+ |
* plaintext store, what that protection does not cover — a fallback nobody is
|
|
218
|
+ |
* told about is the same defect as a redaction that reports success and leaves
|
|
219
|
+ |
* the secret in place.
|
|
220
|
+ |
*/
|
|
221
|
+ |
export const describeSeedProtection = (protection: SeedProtection, path: string): string =>
|
|
222
|
+ |
protection === "os_keychain"
|
|
223
|
+ |
? `Protection: OS keychain. The seed at ${path} is encrypted (${SEED_ENVELOPE_ALG}); ` +
|
|
224
|
+ |
`the key that opens it is held by the OS keychain under service ${IDENTITY_KEYCHAIN_SERVICE}, ` +
|
|
225
|
+ |
"never in the file and never in a backup of it."
|
|
226
|
+ |
: `Protection: NONE. The seed phrase is stored as readable text at ${path} (mode 0600). ` +
|
|
227
|
+ |
"No OS keychain is available here, so file permissions are the whole protection: " +
|
|
228
|
+ |
"they stop another local user, and they stop nothing that already runs as you — " +
|
|
229
|
+ |
"a backup tool, a sync client, or an agent that can read your home directory. " +
|
|
230
|
+ |
"Treat this file the way you would treat the phrase written on paper.";
|
|
231
|
+ |
|
|
232
|
+ |
// ---------------------------------------------------------------------------
|
|
233
|
+ |
// the sealed envelope
|
|
234
|
+ |
// ---------------------------------------------------------------------------
|
|
235
|
+ |
|
|
236
|
+ |
/**
|
|
237
|
+ |
* The on-disk format both CLIs read and write. Changing any of these three
|
|
238
|
+ |
* constants makes one CLI unable to open the other's seed.
|
|
239
|
+ |
*/
|
|
240
|
+ |
export const SEED_ENVELOPE_SCHEMA = "openagents.cli_identity_seed.v1";
|
|
241
|
+ |
export const SEED_ENVELOPE_ALG = "chacha20-poly1305";
|
|
242
|
+ |
/** Bound into the AEAD, so an envelope cannot be replayed under another schema. */
|
|
243
|
+ |
const SEED_ENVELOPE_AAD = Buffer.from(SEED_ENVELOPE_SCHEMA, "utf8");
|
|
244
|
+ |
const SEED_NONCE_BYTES = 12;
|
|
245
|
+ |
const SEED_TAG_BYTES = 16;
|
|
246
|
+ |
const SEED_KEY_BYTES = 32;
|
|
247
|
+ |
|
|
248
|
+ |
interface SeedEnvelope {
|
|
249
|
+ |
readonly schema: string;
|
|
250
|
+ |
readonly alg: string;
|
|
251
|
+ |
/** The 12-byte AEAD nonce, hex. Fresh on every write. */
|
|
252
|
+ |
readonly nonce: string;
|
|
253
|
+ |
/** Ciphertext with the 16-byte Poly1305 tag appended, hex. */
|
|
254
|
+ |
readonly ciphertext: string;
|
|
255
|
+ |
}
|
|
256
|
+ |
|
|
257
|
+ |
/**
|
|
258
|
+ |
* True when the file at hand is a sealed envelope rather than a bare mnemonic. A
|
|
259
|
+ |
* BIP-39 phrase can never start with `{`, so the two formats cannot be confused
|
|
260
|
+ |
* and an old plaintext seed is still recognised for migration.
|
|
261
|
+ |
*/
|
|
262
|
+ |
const looksSealed = (text: string): boolean => text.trimStart().startsWith("{");
|
|
263
|
+ |
|
|
264
|
+ |
const sealPhrase = (phrase: string, key: Uint8Array): string => {
|
|
265
|
+ |
const nonce = randomBytes(SEED_NONCE_BYTES);
|
|
266
|
+ |
const cipher = createCipheriv(SEED_ENVELOPE_ALG, key, nonce, {
|
|
267
|
+ |
authTagLength: SEED_TAG_BYTES,
|
|
268
|
+ |
});
|
|
269
|
+ |
cipher.setAAD(SEED_ENVELOPE_AAD, { plaintextLength: Buffer.byteLength(phrase, "utf8") });
|
|
270
|
+ |
const body = Buffer.concat([cipher.update(phrase, "utf8"), cipher.final()]);
|
|
271
|
+ |
const envelope: SeedEnvelope = {
|
|
272
|
+ |
schema: SEED_ENVELOPE_SCHEMA,
|
|
273
|
+ |
alg: SEED_ENVELOPE_ALG,
|
|
274
|
+ |
nonce: nonce.toString("hex"),
|
|
275
|
+ |
ciphertext: Buffer.concat([body, cipher.getAuthTag()]).toString("hex"),
|
|
276
|
+ |
};
|
|
277
|
+ |
return JSON.stringify(envelope);
|
|
278
|
+ |
};
|
|
279
|
+ |
|
|
280
|
+ |
const undecryptable = (path: string): Error =>
|
|
281
|
+ |
new Error(
|
|
282
|
+ |
`The seed at ${path} is encrypted and the key in the OS keychain does not open it. ` +
|
|
283
|
+ |
"Restore the seed phrase with openagents identity import.",
|
|
284
|
+ |
);
|
|
285
|
+ |
|
|
286
|
+ |
const openEnvelope = (text: string, key: Uint8Array, path: string): string => {
|
|
287
|
+ |
let envelope: SeedEnvelope;
|
|
288
|
+ |
try {
|
|
289
|
+ |
envelope = JSON.parse(text.trim()) as SeedEnvelope;
|
|
290
|
+ |
} catch {
|
|
291
|
+ |
throw undecryptable(path);
|
|
292
|
+ |
}
|
|
293
|
+ |
if (envelope.schema !== SEED_ENVELOPE_SCHEMA || envelope.alg !== SEED_ENVELOPE_ALG) {
|
|
294
|
+ |
throw undecryptable(path);
|
|
295
|
+ |
}
|
|
296
|
+ |
const nonce = Buffer.from(envelope.nonce, "hex");
|
|
297
|
+ |
const sealed = Buffer.from(envelope.ciphertext, "hex");
|
|
298
|
+ |
if (nonce.length !== SEED_NONCE_BYTES || sealed.length <= SEED_TAG_BYTES)
|
|
299
|
+ |
throw undecryptable(path);
|
|
300
|
+ |
const body = sealed.subarray(0, sealed.length - SEED_TAG_BYTES);
|
|
301
|
+ |
const tag = sealed.subarray(sealed.length - SEED_TAG_BYTES);
|
|
302
|
+ |
try {
|
|
303
|
+ |
const decipher = createDecipheriv(SEED_ENVELOPE_ALG, key, nonce, {
|
|
304
|
+ |
authTagLength: SEED_TAG_BYTES,
|
|
305
|
+ |
});
|
|
306
|
+ |
decipher.setAAD(SEED_ENVELOPE_AAD, { plaintextLength: body.length });
|
|
307
|
+ |
decipher.setAuthTag(tag);
|
|
308
|
+ |
return normalize(Buffer.concat([decipher.update(body), decipher.final()]).toString("utf8"));
|
|
309
|
+ |
} catch {
|
|
310
|
+ |
throw undecryptable(path);
|
|
311
|
+ |
}
|
|
312
|
+ |
};
|
|
313
|
+ |
|
|
314
|
+ |
// ---------------------------------------------------------------------------
|
|
315
|
+ |
// where the wrapping key lives
|
|
316
|
+ |
// ---------------------------------------------------------------------------
|
|
317
|
+ |
|
|
318
|
+ |
/**
|
|
319
|
+ |
* The service name the OS keychain files the identity wrapping key under. It is
|
|
320
|
+ |
* deliberately not `openagents-cli` (account tokens) or `openagents-cli-computer`
|
|
321
|
+ |
* (machine tokens), so no two of the three can overwrite each other. The Rust CLI
|
|
322
|
+ |
* uses the same one.
|
|
323
|
+ |
*/
|
|
324
|
+ |
export const IDENTITY_KEYCHAIN_SERVICE = "openagents-cli-identity";
|
|
325
|
+ |
|
|
326
|
+ |
/**
|
|
327
|
+ |
* Set this to opt out of the keychain and store the phrase as plaintext at
|
|
328
|
+ |
* `0600`. It exists because a keychain that prompts is worse than no keychain on
|
|
329
|
+ |
* an unattended host, and because the choice should be stateable rather than
|
|
330
|
+ |
* discovered. It is never selected implicitly.
|
|
331
|
+ |
*/
|
|
332
|
+ |
export const PLAINTEXT_ENV = "OPENAGENTS_IDENTITY_PLAINTEXT";
|
|
333
|
+ |
|
|
334
|
+ |
/**
|
|
335
|
+ |
* Where the 32-byte wrapping key lives. One implementation talks to the OS
|
|
336
|
+ |
* keychain; the others exist so a test exercises the real seal, open, and
|
|
337
|
+ |
* migration paths without touching the developer's own keychain.
|
|
338
|
+ |
*/
|
|
339
|
+ |
export interface SeedKeyStore {
|
|
340
|
+ |
/** False when this machine has no keychain, which selects the plaintext file. */
|
|
341
|
+ |
readonly available: () => boolean;
|
|
342
|
+ |
/**
|
|
343
|
+ |
* `undefined` means the store answered and holds no key for this identity
|
|
344
|
+ |
* directory. A throw must never be read as "no key": minting a second one
|
|
345
|
+ |
* would orphan the sealed seed.
|
|
346
|
+ |
*/
|
|
347
|
+ |
readonly get: () => Uint8Array | undefined;
|
|
348
|
+ |
/**
|
|
349
|
+ |
* Store the key and prove it by reading it back. A store that reports success
|
|
350
|
+ |
* without keeping the value would seal a seed nobody can open.
|
|
351
|
+ |
*/
|
|
352
|
+ |
readonly put: (key: Uint8Array) => void;
|
|
353
|
+ |
/** Best-effort removal, so a forgotten identity leaves no key behind. */
|
|
354
|
+ |
readonly delete: () => void;
|
|
355
|
+ |
}
|
|
356
|
+ |
|
|
357
|
+ |
interface KeychainCommand {
|
|
358
|
+ |
readonly command: string;
|
|
359
|
+ |
readonly args: ReadonlyArray<string>;
|
|
360
|
+ |
readonly input?: string;
|
|
361
|
+ |
}
|
|
362
|
+ |
|
|
363
|
+ |
/**
|
|
364
|
+ |
* The command that reads, writes, or clears the wrapping key. Exported so a test
|
|
365
|
+ |
* can assert the shape without a keychain, and so the two CLIs can be compared
|
|
366
|
+ |
* side by side.
|
|
367
|
+ |
*/
|
|
368
|
+ |
export const identityKeychainCommandFor = (
|
|
369
|
+ |
platform: NodeJS.Platform,
|
|
370
|
+ |
operation: "get" | "put" | "delete",
|
|
371
|
+ |
account: string,
|
|
372
|
+ |
key?: string,
|
|
373
|
+ |
): KeychainCommand | undefined => {
|
|
374
|
+ |
if (platform === "darwin") {
|
|
375
|
+ |
if (operation === "get") {
|
|
376
|
+ |
return {
|
|
377
|
+ |
command: "security",
|
|
378
|
+ |
args: ["find-generic-password", "-a", account, "-s", IDENTITY_KEYCHAIN_SERVICE, "-w"],
|
|
379
|
+ |
};
|
|
380
|
+ |
}
|
|
381
|
+ |
if (operation === "put" && key !== undefined) {
|
|
382
|
+ |
// `security` reads the value from argv, so the wrapping key is briefly
|
|
383
|
+ |
// visible to `ps`. The seed phrase never is: it goes to the file sealed,
|
|
384
|
+ |
// and the key alone opens nothing without that file.
|
|
385
|
+ |
return {
|
|
386
|
+ |
command: "security",
|
|
387
|
+ |
args: [
|
|
388
|
+ |
"add-generic-password",
|
|
389
|
+ |
"-U",
|
|
390
|
+ |
"-a",
|
|
391
|
+ |
account,
|
|
392
|
+ |
"-s",
|
|
393
|
+ |
IDENTITY_KEYCHAIN_SERVICE,
|
|
394
|
+ |
"-w",
|
|
395
|
+ |
key,
|
|
396
|
+ |
],
|
|
397
|
+ |
};
|
|
398
|
+ |
}
|
|
399
|
+ |
if (operation === "delete") {
|
|
400
|
+ |
return {
|
|
401
|
+ |
command: "security",
|
|
402
|
+ |
args: ["delete-generic-password", "-a", account, "-s", IDENTITY_KEYCHAIN_SERVICE],
|
|
403
|
+ |
};
|
|
404
|
+ |
}
|
|
405
|
+ |
return undefined;
|
|
406
|
+ |
}
|
|
407
|
+ |
if (platform === "linux") {
|
|
408
|
+ |
if (operation === "get") {
|
|
409
|
+ |
return {
|
|
410
|
+ |
command: "secret-tool",
|
|
411
|
+ |
args: ["lookup", "service", IDENTITY_KEYCHAIN_SERVICE, "account", account],
|
|
412
|
+ |
};
|
|
413
|
+ |
}
|
|
414
|
+ |
if (operation === "put" && key !== undefined) {
|
|
415
|
+ |
return {
|
|
416
|
+ |
command: "secret-tool",
|
|
417
|
+ |
args: [
|
|
418
|
+ |
"store",
|
|
419
|
+ |
"--label=OpenAgents identity",
|
|
420
|
+ |
"service",
|
|
421
|
+ |
IDENTITY_KEYCHAIN_SERVICE,
|
|
422
|
+ |
"account",
|
|
423
|
+ |
account,
|
|
424
|
+ |
],
|
|
425
|
+ |
input: key,
|
|
426
|
+ |
};
|
|
427
|
+ |
}
|
|
428
|
+ |
if (operation === "delete") {
|
|
429
|
+ |
return {
|
|
430
|
+ |
command: "secret-tool",
|
|
431
|
+ |
args: ["clear", "service", IDENTITY_KEYCHAIN_SERVICE, "account", account],
|
|
432
|
+ |
};
|
|
433
|
+ |
}
|
|
434
|
+ |
}
|
|
435
|
+ |
return undefined;
|
|
436
|
+ |
};
|
|
437
|
+ |
|
|
438
|
+ |
const HEX_KEY = /^[0-9a-f]{64}$/;
|
|
439
|
+ |
|
| 164 |
440
|
|
/**
|
| 165 |
|
- |
* Read the stored mnemonic. This is the only function that returns secret
|
| 166 |
|
- |
* material, and every caller of it either derives from it or hands it to the
|
| 167 |
|
- |
* reader who asked for a backup. Returns `undefined` when no seed is stored.
|
|
441
|
+ |
* The OS keychain: `security` on macOS, `secret-tool` on Linux.
|
|
442
|
+ |
*
|
|
443
|
+ |
* The record is keyed by the identity directory, exactly as the credential store
|
|
444
|
+ |
* keys tokens by origin, so a second identity directory gets a second key and a
|
|
445
|
+ |
* test with a temporary directory can never reach the developer's own.
|
| 168 |
446
|
|
*/
|
| 169 |
|
- |
export const readSeedPhrase = (): string | undefined => {
|
|
447
|
+ |
export const osKeychainKeyStore = (account: string): SeedKeyStore => {
|
|
448
|
+ |
const run = (operation: "get" | "put" | "delete", key?: string) => {
|
|
449
|
+ |
const command = identityKeychainCommandFor(process.platform, operation, account, key);
|
|
450
|
+ |
if (command === undefined) return undefined;
|
|
451
|
+ |
const result = spawnSync(command.command, [...command.args], {
|
|
452
|
+ |
input: command.input,
|
|
453
|
+ |
encoding: "utf8",
|
|
454
|
+ |
stdio: ["pipe", "pipe", "ignore"],
|
|
455
|
+ |
});
|
|
456
|
+ |
// A `security` or `secret-tool` that will not start is not an empty store:
|
|
457
|
+ |
// this platform has no keychain, and that is a different answer.
|
|
458
|
+ |
if (result.error !== undefined) return undefined;
|
|
459
|
+ |
return result;
|
|
460
|
+ |
};
|
|
461
|
+ |
|
|
462
|
+ |
return {
|
|
463
|
+ |
available: () => run("get") !== undefined,
|
|
464
|
+ |
get: () => {
|
|
465
|
+ |
const result = run("get");
|
|
466
|
+ |
if (result === undefined) return undefined;
|
|
467
|
+ |
if (result.status !== 0) return undefined;
|
|
468
|
+ |
const value = (result.stdout ?? "").trim();
|
|
469
|
+ |
if (value.length === 0) return undefined;
|
|
470
|
+ |
if (!HEX_KEY.test(value)) {
|
|
471
|
+ |
// Never regenerate here. A record that is not a wrapping key means
|
|
472
|
+ |
// something else wrote it, and overwriting it would make the sealed seed
|
|
473
|
+ |
// permanently unopenable.
|
|
474
|
+ |
throw new Error(
|
|
475
|
+ |
`The record under service ${IDENTITY_KEYCHAIN_SERVICE} is not an identity wrapping key.`,
|
|
476
|
+ |
);
|
|
477
|
+ |
}
|
|
478
|
+ |
return Uint8Array.from(Buffer.from(value, "hex"));
|
|
479
|
+ |
},
|
|
480
|
+ |
put: (key) => {
|
|
481
|
+ |
const encoded = Buffer.from(key).toString("hex");
|
|
482
|
+ |
const result = run("put", encoded);
|
|
483
|
+ |
if (result === undefined || result.status !== 0) {
|
|
484
|
+ |
throw new Error("The OS keychain refused to store the identity wrapping key.");
|
|
485
|
+ |
}
|
|
486
|
+ |
const readBack = run("get");
|
|
487
|
+ |
if (readBack === undefined || (readBack.stdout ?? "").trim() !== encoded) {
|
|
488
|
+ |
throw new Error("The OS keychain did not return the key that was just written.");
|
|
489
|
+ |
}
|
|
490
|
+ |
},
|
|
491
|
+ |
delete: () => {
|
|
492
|
+ |
run("delete");
|
|
493
|
+ |
},
|
|
494
|
+ |
};
|
|
495
|
+ |
};
|
|
496
|
+ |
|
|
497
|
+ |
/**
|
|
498
|
+ |
* A machine with no keychain: CI, a container, an unattended agent host. This
|
|
499
|
+ |
* selects the plaintext store and the warning that goes with it.
|
|
500
|
+ |
*/
|
|
501
|
+ |
export const noKeyStore: SeedKeyStore = {
|
|
502
|
+ |
available: () => false,
|
|
503
|
+ |
get: () => undefined,
|
|
504
|
+ |
put: () => {
|
|
505
|
+ |
throw new Error("This machine has no OS keychain, so there is nowhere to hold a key.");
|
|
506
|
+ |
},
|
|
507
|
+ |
delete: () => {},
|
|
508
|
+ |
};
|
|
509
|
+ |
|
|
510
|
+ |
/**
|
|
511
|
+ |
* A keychain that lives for the length of one test, so the seal, open, and
|
|
512
|
+ |
* migration paths are exercised for real without writing to the developer's own
|
|
513
|
+ |
* keychain or depending on one existing.
|
|
514
|
+ |
*/
|
|
515
|
+ |
export const inMemoryKeyStore = (): SeedKeyStore => {
|
|
516
|
+ |
let held: Uint8Array | undefined;
|
|
517
|
+ |
return {
|
|
518
|
+ |
available: () => true,
|
|
519
|
+ |
get: () => held,
|
|
520
|
+ |
put: (key) => {
|
|
521
|
+ |
held = Uint8Array.from(key);
|
|
522
|
+ |
},
|
|
523
|
+ |
delete: () => {
|
|
524
|
+ |
held = undefined;
|
|
525
|
+ |
},
|
|
526
|
+ |
};
|
|
527
|
+ |
};
|
|
528
|
+ |
|
|
529
|
+ |
/** True when the environment asks for the plaintext store. */
|
|
530
|
+ |
const plaintextRequested = (): boolean => {
|
|
531
|
+ |
const value = (process.env[PLAINTEXT_ENV] ?? "").trim().toLowerCase();
|
|
532
|
+ |
return !(value.length === 0 || value === "0" || value === "false" || value === "no");
|
|
533
|
+ |
};
|
|
534
|
+ |
|
|
535
|
+ |
/**
|
|
536
|
+ |
* The production key store: the OS keychain, unless {@link PLAINTEXT_ENV} says
|
|
537
|
+ |
* otherwise. Computed per call because the identity directory is an environment
|
|
538
|
+ |
* override and may change between calls in a test.
|
|
539
|
+ |
*/
|
|
540
|
+ |
export const defaultSeedKeyStore = (): SeedKeyStore =>
|
|
541
|
+ |
plaintextRequested() ? noKeyStore : osKeychainKeyStore(seedDirectory());
|
|
542
|
+ |
|
|
543
|
+ |
// ---------------------------------------------------------------------------
|
|
544
|
+ |
// reading and writing the seed
|
|
545
|
+ |
// ---------------------------------------------------------------------------
|
|
546
|
+ |
|
|
547
|
+ |
/** A seed read back off disk, and what was protecting it there. */
|
|
548
|
+ |
export interface StoredSeed {
|
|
549
|
+ |
/** The mnemonic. Secret. */
|
|
550
|
+ |
readonly phrase: string;
|
|
551
|
+ |
readonly protection: SeedProtection;
|
|
552
|
+ |
}
|
|
553
|
+ |
|
|
554
|
+ |
/**
|
|
555
|
+ |
* What a write would use on this machine right now: the keychain when one
|
|
556
|
+ |
* answers, the plaintext file when none exists. A keychain that answers with a
|
|
557
|
+ |
* record that is not a wrapping key throws from {@link SeedKeyStore.get} rather
|
|
558
|
+ |
* than being downgraded to plaintext here.
|
|
559
|
+ |
*/
|
|
560
|
+ |
export const seedProtectionAvailable = (
|
|
561
|
+ |
keyStore: SeedKeyStore = defaultSeedKeyStore(),
|
|
562
|
+ |
): SeedProtection => (keyStore.available() ? "os_keychain" : "plaintext_file");
|
|
563
|
+ |
|
|
564
|
+ |
/**
|
|
565
|
+ |
* What is protecting the seed that is on disk now, without opening it.
|
|
566
|
+ |
* `undefined` when nothing is stored.
|
|
567
|
+ |
*/
|
|
568
|
+ |
export const seedProtectionOnDisk = (): SeedProtection | undefined => {
|
| 170 |
569
|
|
const path = seedPath();
|
| 171 |
570
|
|
if (!existsSync(path)) return undefined;
|
| 172 |
|
- |
const phrase = normalize(readFileSync(path, "utf8"));
|
| 173 |
|
- |
return phrase.length === 0 ? undefined : phrase;
|
|
571
|
+ |
const text = readFileSync(path, "utf8");
|
|
572
|
+ |
if (text.trim().length === 0) return undefined;
|
|
573
|
+ |
return looksSealed(text) ? "os_keychain" : "plaintext_file";
|
| 174 |
574
|
|
};
|
| 175 |
575
|
|
|
| 176 |
576
|
|
/**
|
| 177 |
|
- |
* Write the mnemonic, `0600` inside a `0700` directory, after validating it.
|
| 178 |
|
- |
* The validation is not politeness: an unwritable-back phrase stored here would
|
| 179 |
|
- |
* be an identity that cannot be recovered from its own backup.
|
|
577
|
+ |
* Read the stored seed and report what was protecting it. This and
|
|
578
|
+ |
* {@link readSeedPhrase} are the only functions that return secret material.
|
| 180 |
579
|
|
*/
|
| 181 |
|
- |
export const writeSeedPhrase = (phrase: string): string => {
|
| 182 |
|
- |
const normalized = normalize(phrase);
|
| 183 |
|
- |
if (!validateMnemonic(normalized, wordlist)) {
|
| 184 |
|
- |
throw new Error("The seed phrase is not a valid English BIP-39 mnemonic.");
|
|
580
|
+ |
export const loadSeed = (
|
|
581
|
+ |
keyStore: SeedKeyStore = defaultSeedKeyStore(),
|
|
582
|
+ |
): StoredSeed | undefined => {
|
|
583
|
+ |
const path = seedPath();
|
|
584
|
+ |
if (!existsSync(path)) return undefined;
|
|
585
|
+ |
const text = readFileSync(path, "utf8");
|
|
586
|
+ |
if (text.trim().length === 0) return undefined;
|
|
587
|
+ |
if (!looksSealed(text)) return { phrase: normalize(text), protection: "plaintext_file" };
|
|
588
|
+ |
// Sealed. A keychain that cannot be read is never reported as "no seed": that
|
|
589
|
+ |
// reads as an identity that vanished, and the next command would offer to make
|
|
590
|
+ |
// a new one.
|
|
591
|
+ |
const key = keyStore.get();
|
|
592
|
+ |
if (key === undefined) {
|
|
593
|
+ |
throw new Error(
|
|
594
|
+ |
`The seed at ${path} is encrypted, and the OS keychain holds no key that opens it. ` +
|
|
595
|
+ |
"The key does not travel with the file and is not in any backup of it. " +
|
|
596
|
+ |
"Restore the seed phrase with openagents identity import.",
|
|
597
|
+ |
);
|
| 185 |
598
|
|
}
|
|
599
|
+ |
return { phrase: openEnvelope(text, key, path), protection: "os_keychain" };
|
|
600
|
+ |
};
|
|
601
|
+ |
|
|
602
|
+ |
/**
|
|
603
|
+ |
* Read the stored mnemonic. Every caller either derives from it or hands it to
|
|
604
|
+ |
* the reader who asked for a backup. Returns `undefined` when no seed is stored.
|
|
605
|
+ |
*/
|
|
606
|
+ |
export const readSeedPhrase = (
|
|
607
|
+ |
keyStore: SeedKeyStore = defaultSeedKeyStore(),
|
|
608
|
+ |
): string | undefined => {
|
|
609
|
+ |
const stored = loadSeed(keyStore);
|
|
610
|
+ |
return stored === undefined || stored.phrase.length === 0 ? undefined : stored.phrase;
|
|
611
|
+ |
};
|
|
612
|
+ |
|
|
613
|
+ |
const writeAtomic = (body: string): string => {
|
| 186 |
614
|
|
const directory = seedDirectory();
|
| 187 |
615
|
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
616
|
+ |
chmodSync(directory, 0o700);
|
| 188 |
617
|
|
const path = seedPath();
|
| 189 |
|
- |
writeFileSync(path, `${normalized}\n`, { mode: 0o600 });
|
|
618
|
+ |
const temporary = seedTempPath();
|
|
619
|
+ |
rmSync(temporary, { force: true });
|
|
620
|
+ |
try {
|
|
621
|
+ |
writeFileSync(temporary, body, { mode: 0o600 });
|
|
622
|
+ |
chmodSync(temporary, 0o600);
|
|
623
|
+ |
renameSync(temporary, path);
|
|
624
|
+ |
} catch (cause) {
|
|
625
|
+ |
rmSync(temporary, { force: true });
|
|
626
|
+ |
throw cause;
|
|
627
|
+ |
}
|
| 190 |
628
|
|
chmodSync(path, 0o600);
|
| 191 |
629
|
|
return path;
|
| 192 |
630
|
|
};
|
| 193 |
631
|
|
|
| 194 |
|
- |
/** Remove the stored seed. Idempotent, and it deletes nothing else. */
|
| 195 |
|
- |
export const forgetSeedPhrase = (): boolean => {
|
|
632
|
+ |
/**
|
|
633
|
+ |
* Write the mnemonic under the best protection this machine has, `0600` inside a
|
|
634
|
+ |
* `0700` directory, after validating it. The validation is not politeness: an
|
|
635
|
+ |
* unwritable-back phrase stored here would be an identity that cannot be
|
|
636
|
+ |
* recovered from its own backup.
|
|
637
|
+ |
*
|
|
638
|
+ |
* The write is atomic — staged in a sibling file and renamed over the target —
|
|
639
|
+ |
* so the phrase is never in two files at once and a crash mid-write leaves the
|
|
640
|
+ |
* previous seed intact rather than half of the new one.
|
|
641
|
+ |
*/
|
|
642
|
+ |
export const storeSeedPhrase = (
|
|
643
|
+ |
phrase: string,
|
|
644
|
+ |
keyStore: SeedKeyStore = defaultSeedKeyStore(),
|
|
645
|
+ |
): { readonly path: string; readonly protection: SeedProtection } => {
|
|
646
|
+ |
const normalized = normalize(phrase);
|
|
647
|
+ |
if (!validateMnemonic(normalized, wordlist)) {
|
|
648
|
+ |
throw new Error("The seed phrase is not a valid English BIP-39 mnemonic.");
|
|
649
|
+ |
}
|
|
650
|
+ |
const protection = seedProtectionAvailable(keyStore);
|
|
651
|
+ |
if (protection === "plaintext_file") {
|
|
652
|
+ |
return { path: writeAtomic(`${normalized}\n`), protection };
|
|
653
|
+ |
}
|
|
654
|
+ |
let key = keyStore.get();
|
|
655
|
+ |
if (key === undefined) {
|
|
656
|
+ |
// Prove the keychain kept it before anything is sealed under it. Sealing
|
|
657
|
+ |
// first would produce a file no key opens.
|
|
658
|
+ |
const fresh = Uint8Array.from(randomBytes(SEED_KEY_BYTES));
|
|
659
|
+ |
keyStore.put(fresh);
|
|
660
|
+ |
key = fresh;
|
|
661
|
+ |
}
|
|
662
|
+ |
return { path: writeAtomic(`${sealPhrase(normalized, key)}\n`), protection };
|
|
663
|
+ |
};
|
|
664
|
+ |
|
|
665
|
+ |
/** {@link storeSeedPhrase}, for callers that only need the path. */
|
|
666
|
+ |
export const writeSeedPhrase = (
|
|
667
|
+ |
phrase: string,
|
|
668
|
+ |
keyStore: SeedKeyStore = defaultSeedKeyStore(),
|
|
669
|
+ |
): string => storeSeedPhrase(phrase, keyStore).path;
|
|
670
|
+ |
|
|
671
|
+ |
/**
|
|
672
|
+ |
* Move a plaintext seed under the OS keychain, and report what is protecting it
|
|
673
|
+ |
* afterwards. `undefined` when nothing is stored.
|
|
674
|
+ |
*
|
|
675
|
+ |
* The rewrite lands on the same path by rename, so there is never a moment with
|
|
676
|
+ |
* the phrase in two files, and the plaintext is gone the instant the sealed
|
|
677
|
+ |
* envelope arrives. On a machine with no keychain this changes nothing and
|
|
678
|
+ |
* reports `plaintext_file`, which is what the caller then has to say out loud.
|
|
679
|
+ |
*/
|
|
680
|
+ |
export const protectSeed = (
|
|
681
|
+ |
keyStore: SeedKeyStore = defaultSeedKeyStore(),
|
|
682
|
+ |
): SeedProtection | undefined => {
|
|
683
|
+ |
const onDisk = seedProtectionOnDisk();
|
|
684
|
+ |
if (onDisk === undefined) return undefined;
|
|
685
|
+ |
if (onDisk === "os_keychain") return "os_keychain";
|
|
686
|
+ |
if (seedProtectionAvailable(keyStore) !== "os_keychain") return "plaintext_file";
|
|
687
|
+ |
const stored = loadSeed(keyStore);
|
|
688
|
+ |
if (stored === undefined) return undefined;
|
|
689
|
+ |
return storeSeedPhrase(stored.phrase, keyStore).protection;
|
|
690
|
+ |
};
|
|
691
|
+ |
|
|
692
|
+ |
/**
|
|
693
|
+ |
* Remove the stored seed, and the wrapping key with it. Idempotent, and it
|
|
694
|
+ |
* deletes nothing else. Leaving the key behind would leave a keychain record for
|
|
695
|
+ |
* an identity that no longer exists.
|
|
696
|
+ |
*/
|
|
697
|
+ |
export const forgetSeedPhrase = (keyStore: SeedKeyStore = defaultSeedKeyStore()): boolean => {
|
| 196 |
698
|
|
const path = seedPath();
|
| 197 |
|
- |
if (!existsSync(path)) return false;
|
|
699
|
+ |
rmSync(seedTempPath(), { force: true });
|
|
700
|
+ |
if (!existsSync(path)) {
|
|
701
|
+ |
keyStore.delete();
|
|
702
|
+ |
return false;
|
|
703
|
+ |
}
|
| 198 |
704
|
|
rmSync(path);
|
|
705
|
+ |
keyStore.delete();
|
| 199 |
706
|
|
return true;
|
| 200 |
707
|
|
};
|