@tpsdev-ai/flair 0.63.0 → 0.63.1

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 (63) hide show
  1. package/README.md +8 -7
  2. package/SECURITY.md +55 -33
  3. package/dist/bridges/runtime/import-runner.js +4 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +243 -83
  6. package/dist/commands/agent.js +298 -72
  7. package/dist/commands/attention.js +2 -0
  8. package/dist/commands/bootstrap.js +2 -0
  9. package/dist/commands/bridge.js +10 -0
  10. package/dist/commands/doctor.js +87 -42
  11. package/dist/commands/export.js +141 -11
  12. package/dist/commands/import.js +36 -15
  13. package/dist/commands/init.js +373 -157
  14. package/dist/commands/keys.js +12 -8
  15. package/dist/commands/mcp.js +146 -62
  16. package/dist/commands/memory.js +5 -2
  17. package/dist/commands/migrate-harness-memory.js +9 -3
  18. package/dist/commands/principal.js +19 -14
  19. package/dist/commands/quality.js +23 -3
  20. package/dist/commands/reembed.js +468 -111
  21. package/dist/commands/search.js +2 -0
  22. package/dist/commands/service.js +25 -0
  23. package/dist/commands/status.js +130 -107
  24. package/dist/doctor-client.js +2 -23
  25. package/dist/federation/scheduler.js +148 -12
  26. package/dist/keystore.js +77 -10
  27. package/dist/lib/agent-key-file.js +509 -0
  28. package/dist/lib/agent-rotation-lock.js +249 -0
  29. package/dist/lib/atomic-write.js +2 -2
  30. package/dist/lib/auth-resolve.js +14 -14
  31. package/dist/lib/key-dir.js +203 -0
  32. package/dist/lib/launchd-management.js +7 -3
  33. package/dist/lib/local-instance-pair.js +8 -1
  34. package/dist/lib/node-alias-path.js +50 -2
  35. package/dist/lib/remote-admin-pass.js +157 -0
  36. package/dist/lib/scheduler-platform.js +13 -0
  37. package/dist/lib/service-repoint.js +13 -4
  38. package/dist/lib/skill-seed.js +35 -3
  39. package/dist/lib/terminal-text.js +32 -0
  40. package/dist/mcp-client-assertion.js +5 -4
  41. package/dist/resources/Memory.js +47 -3
  42. package/dist/resources/health.js +39 -22
  43. package/dist/resources/in-process-api.js +74 -11
  44. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  45. package/dist/resources/mcp-handler.js +40 -1
  46. package/dist/resources/mcp-oauth.js +17 -1
  47. package/dist/resources/mcp-tool-scopes.js +69 -0
  48. package/dist/resources/mcp-tools.js +10 -0
  49. package/dist/resources/skill-version-write.js +16 -0
  50. package/dist/src/keystore.js +77 -10
  51. package/dist/src/lib/atomic-write.js +2 -2
  52. package/dist/src/lib/key-dir.js +203 -0
  53. package/dist/src/lib/scheduler-platform.js +13 -0
  54. package/docs/access-control.md +21 -12
  55. package/docs/api-reference.md +35 -24
  56. package/docs/auth.md +31 -22
  57. package/docs/deploying-on-fabric.md +10 -2
  58. package/docs/embedding-in-a-harper-app.md +7 -7
  59. package/docs/entity-vocabulary.md +4 -5
  60. package/docs/hosted-on-fabric.md +1 -1
  61. package/docs/secrets-and-keys.md +8 -13
  62. package/docs/upgrade.md +15 -5
  63. package/package.json +1 -1
@@ -1,10 +1,13 @@
1
1
  import nacl from "tweetnacl";
2
- import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync, unlinkSync, realpathSync } from "node:fs";
3
- import { join } from "node:path";
2
+ import { existsSync, writeFileSync, unlinkSync, realpathSync, readdirSync } from "node:fs";
3
+ import { join, basename } from "node:path";
4
4
  import * as render from "../render.js";
5
5
  import { addAdminPassOptions, credentialsInHeader, defaultKeysDir, describeHttpFailure, resolveLocalAdminPass, resolveAdminUser, resolveKeyPath, authFetch, authFetchWithSentCredentials, } from "../lib/auth-resolve.js";
6
6
  import { encodeRecordId } from "../lib/record-id-path.js";
7
7
  import { resolveLocalDeleteInstance } from "../lib/local-delete-instance.js";
8
+ import { AgentKeyFileRefusal, createAgentKeyBackup, ensureAgentKeysDir, isAgentKeyRotationBackup, readAgentKeyForRotation, readOrCreateAgentKey, replaceAgentKeyFile, rotationBackupStamp, stageAgentKeyFile, } from "../lib/agent-key-file.js";
9
+ import { acquireAgentRotationLock, agentRotationTestPause } from "../lib/agent-rotation-lock.js";
10
+ import { agentKeyPath, agentPubKeyPath } from "../lib/key-dir.js";
8
11
  import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
9
12
  import { agentHomeEndpoint, resolveTargetInstanceId, runAgentHomeStamp, stampLeftoverLines, } from "../lib/agent-home.js";
10
13
  import { confirmedPurgeIds } from "../lib/memory-purge-response.js";
@@ -32,7 +35,8 @@ export function removeAgentKeyFiles(agentId, keysDir) {
32
35
  return { removed: [], manual: false }; // directory resolution failed
33
36
  }
34
37
  const removed = [];
35
- for (const name of [`${agentId}.key`, `${agentId}.pub`, `${agentId}.key.bak`]) {
38
+ const keyName = basename(agentKeyPath(keysDir, agentId));
39
+ for (const name of [keyName, basename(agentPubKeyPath(keysDir, agentId)), `${keyName}.bak`]) {
36
40
  let real;
37
41
  try {
38
42
  real = realpathSync(join(keysDir, name));
@@ -48,6 +52,29 @@ export function removeAgentKeyFiles(agentId, keysDir) {
48
52
  }
49
53
  catch { /* best effort */ }
50
54
  }
55
+ // Rotation retains timestamped backups and staged replacement keys.
56
+ let backups = [];
57
+ try {
58
+ backups = readdirSync(keysDir).filter((name) => isAgentKeyRotationBackup(name, keyName) ||
59
+ (name.startsWith(`.${keyName}.tmp-`) && /^[0-9a-f]{16}$/.test(name.slice(`.${keyName}.tmp-`.length))));
60
+ }
61
+ catch { /* keys directory resolution failed */ }
62
+ for (const name of backups) {
63
+ let real;
64
+ try {
65
+ real = realpathSync(join(keysDir, name));
66
+ }
67
+ catch {
68
+ continue;
69
+ }
70
+ if (real !== join(root, name))
71
+ continue;
72
+ try {
73
+ unlinkSync(real);
74
+ removed.push(real);
75
+ }
76
+ catch { /* best effort */ }
77
+ }
51
78
  return { removed, manual: false };
52
79
  }
53
80
  const shouldShowInlineSecretWarning = (optValue, fromEnv, secretFlagNames, flagName) => cli.shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagName);
@@ -202,6 +229,87 @@ async function readStoredAgent(opsPortOrUrl, id, adminUser, adminPass) {
202
229
  }
203
230
  return parsed.row;
204
231
  }
232
+ /**
233
+ * Read the Agent row's stored public key after a rotation update without
234
+ * exiting: a failed read is a rotation failure that keeps the staged key.
235
+ */
236
+ async function readAgentPublicKeyAfterUpdate(opsPortOrUrl, id, adminUser, adminPass) {
237
+ const auth = Buffer.from(`${adminUser}:${adminPass}`).toString("base64");
238
+ let res;
239
+ try {
240
+ res = await fetch(opsApiUrl(opsPortOrUrl), {
241
+ method: "POST",
242
+ headers: { "Content-Type": "application/json", Authorization: `Basic ${auth}` },
243
+ body: JSON.stringify({
244
+ operation: "search_by_value",
245
+ database: "flair",
246
+ table: "Agent",
247
+ search_attribute: "id",
248
+ search_value: id,
249
+ get_attributes: ["id", "publicKey"],
250
+ }),
251
+ signal: AbortSignal.timeout(10_000),
252
+ });
253
+ }
254
+ catch (err) {
255
+ const message = err instanceof Error ? err.message : String(err);
256
+ return { ok: false, reason: `the read request failed (${message})` };
257
+ }
258
+ let text;
259
+ try {
260
+ text = await res.text();
261
+ }
262
+ catch (err) {
263
+ const message = err instanceof Error ? err.message : String(err);
264
+ return { ok: false, reason: `the read response could not be read (${message})` };
265
+ }
266
+ if (!res.ok)
267
+ return { ok: false, reason: `the read returned ${res.status}` };
268
+ if (text.trim().length === 0)
269
+ return { ok: false, reason: "the read returned an empty body" };
270
+ let body;
271
+ try {
272
+ body = JSON.parse(text);
273
+ }
274
+ catch {
275
+ return { ok: false, reason: "the read returned a body that is not JSON" };
276
+ }
277
+ if (!Array.isArray(body))
278
+ return { ok: false, reason: "the read returned an unexpected body" };
279
+ if (body.length === 0)
280
+ return { ok: false, reason: "the read found no Agent row" };
281
+ if (body.length !== 1)
282
+ return { ok: false, reason: `the read returned ${body.length} rows` };
283
+ const row = body[0];
284
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
285
+ return { ok: false, reason: "the read returned a malformed Agent row" };
286
+ }
287
+ if (typeof row.id !== "string")
288
+ return { ok: false, reason: "the read returned a non-string Agent id" };
289
+ if (row.id !== id)
290
+ return { ok: false, reason: `the read returned Agent '${row.id}' while looking up '${id}'` };
291
+ if (typeof row.publicKey !== "string" || row.publicKey.length === 0) {
292
+ return { ok: false, reason: "the read returned no public key" };
293
+ }
294
+ return { ok: true, publicKey: row.publicKey };
295
+ }
296
+ function quotePosixPath(path) {
297
+ return "'" + path.replace(/'/g, "'\\''") + "'";
298
+ }
299
+ /** A kept staged key after the update request was sent but the rename did not run. */
300
+ function rotationStagedKeyMessage(id, stagedPath, currentPath, detail) {
301
+ return (`Error: ${detail} Flair may now hold the new public key for '${id}'. ` +
302
+ `The current private key ${currentPath} is unchanged. The new private key is kept at ${stagedPath}. ` +
303
+ `If Flair holds the new public key, move it into place: mv -- ${quotePosixPath(stagedPath)} ${quotePosixPath(currentPath)}, then chmod -- 600 ${quotePosixPath(currentPath)}. ` +
304
+ `If it does not, delete the staged file: rm -- ${quotePosixPath(stagedPath)}.`);
305
+ }
306
+ /** A failure after the rename: the private key on disk is the new one. */
307
+ function rotationReplacedKeyMessage(currentPath, detail, backupPath) {
308
+ const backup = backupPath
309
+ ? `The old key backup is ${backupPath}.`
310
+ : "No key existed before this rotation, so there is no backup.";
311
+ return `Error: ${detail} The private key at ${currentPath} was already replaced. ${backup}`;
312
+ }
205
313
  /** Register the `flair agent` command group (flair#1630). */
206
314
  export function register(program) {
207
315
  // ─── flair agent ─────────────────────────────────────────────────────────────
@@ -276,25 +384,30 @@ export function register(program) {
276
384
  console.error(agentAlreadyExistsMessage(id));
277
385
  process.exit(1);
278
386
  }
279
- mkdirSync(keysDir, { recursive: true });
280
387
  const privPath = privKeyPath(id, keysDir);
281
388
  const pubPath = pubKeyPath(id, keysDir);
282
389
  let pubKeyB64url;
283
- if (existsSync(privPath)) {
284
- console.log(`Reusing existing key: ${privPath}`);
285
- const seed = new Uint8Array(readFileSync(privPath));
286
- const kp = nacl.sign.keyPair.fromSeed(seed);
287
- pubKeyB64url = b64url(kp.publicKey);
390
+ let keyFile;
391
+ try {
392
+ ensureAgentKeysDir(keysDir);
393
+ keyFile = readOrCreateAgentKey(privPath, () => {
394
+ const kp = nacl.sign.keyPair();
395
+ return Buffer.from(kp.secretKey.slice(0, 32));
396
+ });
288
397
  }
289
- else {
290
- const kp = nacl.sign.keyPair();
291
- const seed = kp.secretKey.slice(0, 32);
292
- writeFileSync(privPath, Buffer.from(seed));
293
- chmodSync(privPath, 0o600);
398
+ catch (err) {
399
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
400
+ process.exit(1);
401
+ }
402
+ const kp = nacl.sign.keyPair.fromSeed(new Uint8Array(keyFile.bytes));
403
+ pubKeyB64url = b64url(kp.publicKey);
404
+ if (keyFile.created) {
294
405
  writeFileSync(pubPath, Buffer.from(kp.publicKey));
295
- pubKeyB64url = b64url(kp.publicKey);
296
406
  console.log(`Keypair written: ${privPath}`);
297
407
  }
408
+ else {
409
+ console.log(`Reusing existing key: ${privPath}`);
410
+ }
298
411
  await seedAgentWithLocalHome(seedOpsTarget, id, pubKeyB64url, adminUser, adminPass);
299
412
  const stored = await readStoredAgent(seedOpsTarget, id, adminUser, adminPass);
300
413
  if (!stored || stored.publicKey !== pubKeyB64url) {
@@ -358,11 +471,15 @@ export function register(program) {
358
471
  // the principal table for discovery, so sign the request with its key.
359
472
  const baseUrl = `http://127.0.0.1:${port}`;
360
473
  const agentId = opts.agent ?? process.env.FLAIR_AGENT_ID;
474
+ if (agentId && !isValidAgentId(agentId)) {
475
+ console.error(`Error: ${invalidAgentIdMessage(agentId)}`);
476
+ process.exit(1);
477
+ }
361
478
  const keysDir = opts.keysDir ?? process.env.FLAIR_KEY_DIR ?? defaultKeysDir();
362
479
  let res;
363
480
  let sent = { values: [], withhold: false };
364
481
  if (agentId) {
365
- const keyPath = resolveKeyPath(agentId) ?? join(keysDir, `${agentId}.key`);
482
+ const keyPath = resolveKeyPath(agentId) ?? agentKeyPath(keysDir, agentId);
366
483
  if (!existsSync(keyPath)) {
367
484
  console.error(`${render.icons.error} no key for agent '${agentId}' (looked in ${keysDir}). Pass --admin-pass, --keys-dir, or a registered --agent.`);
368
485
  process.exit(1);
@@ -454,6 +571,12 @@ export function register(program) {
454
571
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
455
572
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
456
573
  .action(async (id, opts) => {
574
+ // flair#2359 — the ONE agent-ID rule, before any key file is read or
575
+ // written, and before any `fetch` call made by the command action.
576
+ if (!isValidAgentId(id)) {
577
+ console.error(`Error: ${invalidAgentIdMessage(id)}`);
578
+ process.exit(1);
579
+ }
457
580
  const httpPort = resolveHttpPort(opts);
458
581
  const opsPort = resolveOpsPort(opts);
459
582
  if (shouldShowInlineSecretWarning(opts.inlineAdminPass, false, new Set(["--admin-pass"]), "--admin-pass")) {
@@ -466,64 +589,167 @@ export function register(program) {
466
589
  console.error("Error: --admin-pass or FLAIR_ADMIN_PASS required for key rotation");
467
590
  process.exit(1);
468
591
  }
469
- mkdirSync(keysDir, { recursive: true });
470
- const currentPrivPath = privKeyPath(id, keysDir);
471
- const currentPubPath = pubKeyPath(id, keysDir);
472
- const backupPrivPath = currentPrivPath + ".bak";
473
- // Generate new keypair
474
- console.log(`Generating new keypair for agent '${id}'...`);
475
- const kp = nacl.sign.keyPair();
476
- const newSeed = kp.secretKey.slice(0, 32);
477
- const newPubKeyB64url = b64url(kp.publicKey);
478
- // Back up old key if it exists
479
- if (existsSync(currentPrivPath)) {
480
- writeFileSync(backupPrivPath, readFileSync(currentPrivPath));
481
- chmodSync(backupPrivPath, 0o600);
482
- console.log(`Old key backed up to: ${backupPrivPath}`);
483
- }
484
- // Update publicKey in Flair via operations API
485
- console.log(`Updating public key in Flair via operations API...`);
486
- const opsUrl = `http://127.0.0.1:${opsPort}/`;
487
- const auth = Buffer.from(`${adminUser}:${adminPass}`).toString("base64");
488
- const updateBody = {
489
- operation: "update",
490
- database: "flair",
491
- table: "Agent",
492
- records: [{ id, publicKey: newPubKeyB64url, updatedAt: new Date().toISOString() }],
493
- };
494
- const updateRes = await fetch(opsUrl, {
495
- method: "POST",
496
- headers: { "Content-Type": "application/json", Authorization: `Basic ${auth}` },
497
- body: JSON.stringify(updateBody),
498
- signal: AbortSignal.timeout(10_000),
499
- });
500
- if (!updateRes.ok) {
501
- const text = await updateRes.text().catch(() => "");
502
- // Roll back: keep old key in place (don't write new key yet)
503
- if (existsSync(backupPrivPath)) {
504
- // Restore not needed — we haven't written new key yet
505
- }
506
- throw new Error(`Failed to update public key in Flair (${updateRes.status}): ${text}`);
507
- }
508
- console.log(`Public key updated in Flair ✓`);
509
- // Write new private key (only after Flair update succeeds)
510
- writeFileSync(currentPrivPath, Buffer.from(newSeed));
511
- chmodSync(currentPrivPath, 0o600);
512
- writeFileSync(currentPubPath, Buffer.from(kp.publicKey));
513
- console.log(`New private key written: ${currentPrivPath} ✓`);
514
- // Verify new key works
515
- console.log(`Verifying new Ed25519 auth...`);
516
- const httpUrl = `http://127.0.0.1:${httpPort}`;
517
- const verifyRes = await authFetch(httpUrl, id, currentPrivPath, "GET", `/Agent/${encodeRecordId(id)}`);
518
- if (!verifyRes.ok) {
519
- console.error(`⚠️ Auth verification failed (${verifyRes.status}). Old key is backed up at: ${backupPrivPath}`);
592
+ try {
593
+ ensureAgentKeysDir(keysDir);
594
+ }
595
+ catch (err) {
596
+ if (err instanceof AgentKeyFileRefusal) {
597
+ console.error(`Error: ${err.message}`);
598
+ process.exit(1);
599
+ }
600
+ throw err;
601
+ }
602
+ // flair#3151 — the lock serializes rotations of this agent that use this
603
+ // keys directory on a filesystem with reliable exclusive create. It is
604
+ // taken before the current key is read and held through the read-back
605
+ // check, the rename and the public-key write. A
606
+ // second rotation of this agent in this keys directory retries and, if the
607
+ // lock still exists, refuses here; a rotation in a different keys
608
+ // directory uses a different lock file.
609
+ const lockResult = acquireAgentRotationLock({ id, keysDir });
610
+ if (lockResult.ok === false) {
611
+ console.error(`Error: ${lockResult.message}`);
520
612
  process.exit(1);
521
613
  }
522
- console.log(`Ed25519 auth verified ✓`);
523
- console.log(`\n✅ Key rotation complete for agent '${id}'`);
524
- console.log(` New public key: ${newPubKeyB64url}`);
525
- console.log(` Private key: ${currentPrivPath}`);
526
- console.log(` Old key backup: ${backupPrivPath}`);
614
+ const rotationLock = lockResult.lock;
615
+ try {
616
+ const currentPrivPath = privKeyPath(id, keysDir);
617
+ const currentPubPath = pubKeyPath(id, keysDir);
618
+ // Read before writing: POSIX uses a no-follow descriptor; Windows reads by path.
619
+ // A wide POSIX mode is reported; successful rotation replaces the file.
620
+ let current;
621
+ try {
622
+ current = readAgentKeyForRotation(currentPrivPath);
623
+ }
624
+ catch (err) {
625
+ if (err instanceof AgentKeyFileRefusal) {
626
+ console.error(`Error: ${err.message}`);
627
+ process.exit(1);
628
+ }
629
+ throw err;
630
+ }
631
+ if (current?.widerThanOwnerOnly) {
632
+ console.log(`Old key ${currentPrivPath} has group or world permission bits and is being replaced.`);
633
+ }
634
+ // Generate new keypair
635
+ console.log(`Generating new keypair for agent '${id}'...`);
636
+ const kp = nacl.sign.keyPair();
637
+ const newSeed = kp.secretKey.slice(0, 32);
638
+ const newPubKeyB64url = b64url(kp.publicKey);
639
+ // Back up the current key to a NEW timestamped file. An existing backup
640
+ // is never replaced or written into.
641
+ let backupPrivPath;
642
+ if (current) {
643
+ backupPrivPath = `${currentPrivPath}.bak.${rotationBackupStamp()}`;
644
+ try {
645
+ createAgentKeyBackup(backupPrivPath, current.bytes);
646
+ }
647
+ catch (err) {
648
+ if (err?.code === "EEXIST") {
649
+ console.error(`Error: backup path ${backupPrivPath} already exists; move it aside and run again.`);
650
+ process.exit(1);
651
+ }
652
+ throw err;
653
+ }
654
+ console.log(`Old key backed up to: ${backupPrivPath}`);
655
+ }
656
+ // Stage the new private key before the update is sent. A staging failure
657
+ // sends nothing and leaves the current key unchanged.
658
+ let stagedPrivPath;
659
+ try {
660
+ stagedPrivPath = stageAgentKeyFile(currentPrivPath, newSeed);
661
+ }
662
+ catch (err) {
663
+ const message = err instanceof Error ? err.message : String(err);
664
+ console.error(`Error: could not stage the new private key next to ${currentPrivPath}: ${message}. No update was sent; the current key is unchanged.`);
665
+ process.exit(1);
666
+ }
667
+ // Update publicKey in Flair via operations API
668
+ console.log(`Updating public key in Flair via operations API...`);
669
+ const opsUrl = `http://127.0.0.1:${opsPort}/`;
670
+ const auth = Buffer.from(`${adminUser}:${adminPass}`).toString("base64");
671
+ const updateBody = {
672
+ operation: "update",
673
+ database: "flair",
674
+ table: "Agent",
675
+ records: [{ id, publicKey: newPubKeyB64url, updatedAt: new Date().toISOString() }],
676
+ };
677
+ let updateRes;
678
+ try {
679
+ updateRes = await fetch(opsUrl, {
680
+ method: "POST",
681
+ headers: { "Content-Type": "application/json", Authorization: `Basic ${auth}` },
682
+ body: JSON.stringify(updateBody),
683
+ signal: AbortSignal.timeout(10_000),
684
+ });
685
+ }
686
+ catch (err) {
687
+ const message = err instanceof Error ? err.message : String(err);
688
+ console.error(rotationStagedKeyMessage(id, stagedPrivPath, currentPrivPath, `the update request failed (${message}).`));
689
+ process.exit(1);
690
+ }
691
+ if (!updateRes.ok) {
692
+ const text = await updateRes.text().catch(() => "");
693
+ console.error(rotationStagedKeyMessage(id, stagedPrivPath, currentPrivPath, `Flair refused the update (${updateRes.status}): ${text}`));
694
+ process.exit(1);
695
+ }
696
+ // A 2xx that changed no row is a failure: require the stored public key
697
+ // to match the staged key before the rename.
698
+ const readback = await readAgentPublicKeyAfterUpdate(opsPort, id, adminUser, adminPass);
699
+ if (readback.ok === false) {
700
+ console.error(rotationStagedKeyMessage(id, stagedPrivPath, currentPrivPath, `the update was sent, but reading the Agent row back failed: ${readback.reason}.`));
701
+ process.exit(1);
702
+ }
703
+ if (readback.publicKey !== newPubKeyB64url) {
704
+ console.error(rotationStagedKeyMessage(id, stagedPrivPath, currentPrivPath, "the update was sent, but the Agent row's public key does not match the new key."));
705
+ process.exit(1);
706
+ }
707
+ console.log(`Public key updated in Flair ✓`);
708
+ // Replace the current key by rename. A failed rename keeps the staged file.
709
+ try {
710
+ replaceAgentKeyFile(currentPrivPath, stagedPrivPath);
711
+ }
712
+ catch (err) {
713
+ const message = err instanceof Error ? err.message : String(err);
714
+ console.error(rotationStagedKeyMessage(id, stagedPrivPath, currentPrivPath, `the update was verified, but replacing ${currentPrivPath} failed (${message}).`));
715
+ process.exit(1);
716
+ }
717
+ try {
718
+ writeFileSync(currentPubPath, Buffer.from(kp.publicKey));
719
+ }
720
+ catch (err) {
721
+ const message = err instanceof Error ? err.message : String(err);
722
+ console.error(rotationReplacedKeyMessage(currentPrivPath, `writing the public key to ${currentPubPath} failed (${message}).`, backupPrivPath));
723
+ process.exit(1);
724
+ }
725
+ console.log(`New private key written: ${currentPrivPath} ✓`);
726
+ await agentRotationTestPause();
727
+ // Verify new key works
728
+ console.log(`Verifying new Ed25519 auth...`);
729
+ const httpUrl = `http://127.0.0.1:${httpPort}`;
730
+ let verifyRes;
731
+ try {
732
+ verifyRes = await authFetch(httpUrl, id, currentPrivPath, "GET", `/Agent/${encodeRecordId(id)}`);
733
+ }
734
+ catch (err) {
735
+ const message = err instanceof Error ? err.message : String(err);
736
+ console.error(rotationReplacedKeyMessage(currentPrivPath, `the new key's auth verification failed (${message}).`, backupPrivPath));
737
+ process.exit(1);
738
+ }
739
+ if (!verifyRes.ok) {
740
+ console.error(rotationReplacedKeyMessage(currentPrivPath, `the new key's auth verification failed (${verifyRes.status}).`, backupPrivPath));
741
+ process.exit(1);
742
+ }
743
+ console.log(`Ed25519 auth verified ✓`);
744
+ console.log(`\n✅ Key rotation complete for agent '${id}'`);
745
+ console.log(` New public key: ${newPubKeyB64url}`);
746
+ console.log(` Private key: ${currentPrivPath}`);
747
+ if (backupPrivPath)
748
+ console.log(` Old key backup: ${backupPrivPath}`);
749
+ }
750
+ finally {
751
+ rotationLock.release();
752
+ }
527
753
  });
528
754
  // ─── flair agent remove ──────────────────────────────────────────────────────
529
755
  addAdminPassOptions(agent
@@ -1,4 +1,5 @@
1
1
  import { buildEd25519Auth, requestTarget, requestUrl, resolveKeyPath } from "../lib/auth-resolve.js";
2
+ import { requireAgentId } from "../lib/key-dir.js";
2
3
  import * as render from "../render.js";
3
4
  let cli;
4
5
  /** Bind the cli-locals this module depends on. */
@@ -57,6 +58,7 @@ export function register(program) {
57
58
  console.error("error: --agent <id> required (or set FLAIR_AGENT_ID)");
58
59
  process.exit(2);
59
60
  }
61
+ requireAgentId(agentId);
60
62
  const payload = { entity };
61
63
  if (opts.days !== undefined) {
62
64
  const n = Number.parseInt(opts.days, 10);
@@ -1,4 +1,5 @@
1
1
  import { ApiRequestOutcomeUnknown, authedRequest } from "../lib/auth-resolve.js";
2
+ import { requireAgentId } from "../lib/key-dir.js";
2
3
  import * as render from "../render.js";
3
4
  let cli;
4
5
  /** Bind the cli-locals this module depends on. */
@@ -43,6 +44,7 @@ export function register(program) {
43
44
  console.error(`${render.icons.error} --agent <id> required (or set FLAIR_AGENT_ID)`);
44
45
  process.exit(2);
45
46
  }
47
+ requireAgentId(agentId);
46
48
  const baseUrl = resolveBaseUrl(opts);
47
49
  const mode = render.resolveOutputMode(opts);
48
50
  try {
@@ -1,5 +1,6 @@
1
1
  import * as render from "../render.js";
2
2
  import { resolveKeyPath, buildEd25519Auth, readSecretFileSecure, requestTarget, requestUrl } from "../lib/auth-resolve.js";
3
+ import { AgentKeyPathRefusal, requireAgentId } from "../lib/key-dir.js";
3
4
  import { encodeRecordId } from "../lib/record-id-path.js";
4
5
  import { protoSafeRecord } from "../lib/proto-safe-record.js";
5
6
  let cli;
@@ -215,6 +216,10 @@ export function register(program) {
215
216
  .option("--api-key-file <path>", "For API bridges with an apiKey option, read the key from a file that has no group/world permissions (chmod 600 recommended); or, if the bridge declares an environment variable, set that instead (e.g. MEM0_API_KEY).")
216
217
  .action(async (name, srcArg, opts) => {
217
218
  const agentId = opts.agent ?? process.env.FLAIR_AGENT_ID;
219
+ if (opts.agent !== undefined)
220
+ requireAgentId(opts.agent);
221
+ else if (agentId)
222
+ requireAgentId(agentId);
218
223
  const cwd = opts.cwd ?? srcArg ?? process.cwd();
219
224
  const { discover } = await import("../bridges/discover.js");
220
225
  const { builtinDiscoveryRecords } = await import("../bridges/builtins/index.js");
@@ -382,6 +387,10 @@ export function register(program) {
382
387
  }
383
388
  }
384
389
  catch (err) {
390
+ // The shared agent-ID refusal prints its own message, as it does when
391
+ // the flag or environment id is checked above.
392
+ if (err instanceof AgentKeyPathRefusal)
393
+ throw err;
385
394
  if (err instanceof BridgeRuntimeError) {
386
395
  printBridgeError(err, bridgeApiKey);
387
396
  process.exit(1);
@@ -408,6 +417,7 @@ export function register(program) {
408
417
  console.error("error: --agent <id> required (or set FLAIR_AGENT_ID)");
409
418
  process.exit(1);
410
419
  }
420
+ requireAgentId(agentId);
411
421
  const cwd = opts.cwd ?? dst;
412
422
  const { discover } = await import("../bridges/discover.js");
413
423
  const { builtinDiscoveryRecords } = await import("../bridges/builtins/index.js");