felix-mcp 2.0.134 → 2.0.136

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.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { constants as fsConstants, chmodSync, closeSync, copyFileSync, existsSync, fstatSync, fsyncSync, linkSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, } from "node:fs";
3
- import { homedir, userInfo } from "node:os";
3
+ import { homedir } from "node:os";
4
4
  import { basename, delimiter, dirname, join, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { createCipheriv, createDecipheriv, randomBytes, scrypt, } from "node:crypto";
@@ -9,6 +9,8 @@ import { spawnSync } from "node:child_process";
9
9
  import { getAddress, isAddress } from "viem";
10
10
  import { privateKeyToAccount } from "viem/accounts";
11
11
  import { markFreshWorkflowIdentity } from "./money-journal-identity.js";
12
+ import { credentialStoreDescription, credentialStoreKind, credentialStoreLabel, deleteCredential, linuxKeyringMayBeHidden, readCredential, writeCredential, openReadNoFollow, } from "./credential-store.js";
13
+ import { askHidden, askVisible, confirmHuman, showToHuman } from "./human-prompt.js";
12
14
  export const OWNER_KEYCHAIN_SERVICE = "trade.felix.owner-key.v1";
13
15
  export const API_KEYCHAIN_SERVICE = "trade.felix.api-key.v1";
14
16
  export const BACKUP_RECOVERY_KEYCHAIN_SERVICE = "trade.felix.backup-recovery.v1";
@@ -122,6 +124,7 @@ export function parseBackupEnvelope(encoded) {
122
124
  || value.format !== BACKUP_FORMAT
123
125
  || value.version !== BACKUP_VERSION
124
126
  || typeof value.created_at !== "string"
127
+ || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/.test(value.created_at)
125
128
  || !Number.isFinite(Date.parse(value.created_at))
126
129
  || typeof value.owner_address !== "string"
127
130
  || !isAddress(value.owner_address)
@@ -244,7 +247,7 @@ export function parseCliArgs(argv) {
244
247
  if (commandValue === "--help" || commandValue === "-h" || commandValue === "help") {
245
248
  return { command: "help" };
246
249
  }
247
- if (!["onboard", "setup", "set-api-key", "register", "backup", "restore", "replace", "verify", "inspect", "status", "export-recovery-code"].includes(commandValue)) {
250
+ if (!["onboard", "setup", "set-api-key", "register", "renew-key", "backup", "restore", "replace", "verify", "inspect", "status", "export-recovery-code"].includes(commandValue)) {
248
251
  throw new Error("Unknown command. Use felix-keys --help.");
249
252
  }
250
253
  const parsed = { command: commandValue };
@@ -312,107 +315,53 @@ export function parseCliArgs(argv) {
312
315
  if (parsed.command === "onboard" && !parsed.acceptTerms) {
313
316
  throw new Error(`onboard requires --accept-terms after the user reviews https://felix.trade/legal (${FELIX_LEGAL_BUNDLE_VERSION}). No Felix credential was changed.`);
314
317
  }
315
- if (["setup", "set-api-key", "status"].includes(parsed.command) && (parsed.input || parsed.output)) {
318
+ if (["setup", "set-api-key", "status", "renew-key"].includes(parsed.command) && (parsed.input || parsed.output)) {
316
319
  throw new Error(`${parsed.command} does not accept file arguments.`);
317
320
  }
318
321
  return parsed;
319
322
  }
320
- function security(args) {
321
- const result = spawnSync("/usr/bin/security", args, {
322
- encoding: "utf8",
323
- maxBuffer: 16 * 1024,
324
- stdio: ["ignore", "pipe", "pipe"],
325
- });
326
- if (result.status !== 0)
327
- throw new Error("macOS Keychain operation failed.");
328
- return String(result.stdout || "").replace(/\r?\n$/, "");
329
- }
330
- function keychainExists(service) {
331
- const result = spawnSync("/usr/bin/security", [
332
- "find-generic-password", "-a", userInfo().username, "-s", service,
333
- ], { encoding: "utf8", stdio: ["ignore", "ignore", "ignore"] });
334
- return result.status === 0;
335
- }
323
+ // CROSS_PLATFORM_KEYS_20261123: names kept for the call sites; storage is macOS Keychain, Windows protected
324
+ // storage, or the Linux keyring / sealed file (see credential-store.ts).
336
325
  function readKeychainPassword(service) {
337
- if (!keychainExists(service))
338
- return undefined;
339
- return security([
340
- "find-generic-password", "-a", userInfo().username, "-s", service, "-w",
341
- ]);
326
+ return readCredential(service);
342
327
  }
343
- function writeKeychainPassword(service, label, value) {
344
- const helper = resolve(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "keychain-write.exp");
345
- const result = spawnSync("/usr/bin/expect", [
346
- helper, userInfo().username, service, label,
347
- ], {
348
- encoding: "utf8",
349
- input: value,
350
- maxBuffer: 16 * 1024,
351
- stdio: ["pipe", "ignore", "ignore"],
352
- });
353
- if (result.status !== 0)
354
- throw new Error("macOS Keychain write failed.");
328
+ function writeKeychainPassword(service, label, value, options = {}) {
329
+ writeCredential(service, label, value, options);
355
330
  }
356
- function deleteKeychainPassword(service) {
357
- if (!keychainExists(service))
358
- return;
359
- const result = spawnSync("/usr/bin/security", [
360
- "delete-generic-password", "-a", userInfo().username, "-s", service,
361
- ], { encoding: "utf8", stdio: ["ignore", "ignore", "ignore"] });
362
- if (result.status !== 0)
363
- throw new Error("macOS Keychain rollback failed.");
331
+ // QA r18: a new owner key is written create-only, and a failed or unverified write never deletes what is there:
332
+ // the item may be an existing identity that holds money.
333
+ function createOwnerKeyEntry(ownerKey) {
334
+ writeKeychainPassword(OWNER_KEYCHAIN_SERVICE, "Felix root owner key", ownerKey, { createOnly: true });
335
+ if (readKeychainPassword(OWNER_KEYCHAIN_SERVICE) !== ownerKey) {
336
+ throw new Error("The new owner key did not verify in local key storage. Nothing was deleted; run felix-keys status before retrying.");
337
+ }
364
338
  }
365
- function appleScript(lines) {
366
- const args = lines.flatMap((line) => ["-e", line]);
367
- const result = spawnSync("/usr/bin/osascript", args, {
368
- encoding: "utf8",
369
- maxBuffer: 16 * 1024,
370
- stdio: ["ignore", "pipe", "pipe"],
371
- });
372
- if (result.status !== 0)
373
- throw new Error("Human confirmation was cancelled.");
374
- return String(result.stdout || "").replace(/\r?\n$/, "");
339
+ function refuseIfKeyringHidden() {
340
+ if (linuxKeyringMayBeHidden()) {
341
+ throw new Error("A system keyring is installed but this session cannot reach it (no D-Bus session), so Felix cannot tell whether you already have keys there. Nothing was created. Run this from your desktop session, or choose file storage deliberately with FELIX_CREDENTIAL_STORE=file (or secret-service).");
342
+ }
375
343
  }
376
- function appleScriptStdin(script) {
377
- const result = spawnSync("/usr/bin/osascript", ["-"], {
378
- encoding: "utf8",
379
- input: script,
380
- maxBuffer: 16 * 1024,
381
- stdio: ["pipe", "pipe", "pipe"],
382
- });
383
- if (result.status !== 0)
384
- throw new Error("Human confirmation was cancelled.");
385
- return String(result.stdout || "").replace(/\r?\n$/, "");
344
+ function deleteKeychainPassword(service) {
345
+ deleteCredential(service);
386
346
  }
387
347
  function confirmDialog(message, continueLabel = "Continue") {
388
- appleScript([
389
- `display alert ${JSON.stringify("Felix credential recovery")} message ${JSON.stringify(message)} buttons {"Cancel", ${JSON.stringify(continueLabel)}} default button ${JSON.stringify(continueLabel)} cancel button "Cancel" as critical`,
390
- ]);
348
+ confirmHuman(message, continueLabel);
391
349
  }
392
350
  function hiddenAnswer(prompt) {
393
- return appleScript([
394
- `set response to display dialog ${JSON.stringify(prompt)} default answer "" with hidden answer buttons {"Cancel", "Continue"} default button "Continue" cancel button "Cancel" with title "Felix credential recovery"`,
395
- "return text returned of response",
396
- ]);
351
+ return askHidden(prompt);
397
352
  }
398
353
  function visibleAnswer(prompt) {
399
- return appleScript([
400
- `set response to display dialog ${JSON.stringify(prompt)} default answer "" buttons {"Cancel", "Restore"} default button "Restore" cancel button "Cancel" with title "Felix credential recovery"`,
401
- "return text returned of response",
402
- ]);
354
+ return askVisible(prompt);
403
355
  }
404
356
  function requireInteractiveMac() {
405
- if (process.platform !== "darwin") {
406
- throw new Error("Felix Keychain backup currently requires macOS.");
407
- }
357
+ credentialStoreKind();
408
358
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
409
- throw new Error("This optional owner-recovery command requires an interactive macOS session.");
359
+ throw new Error("This optional owner-recovery command must be run by the owner in an interactive terminal.");
410
360
  }
411
361
  }
412
362
  function requireNativeMacSession() {
413
- if (process.platform !== "darwin") {
414
- throw new Error("Felix guided onboarding currently requires macOS Keychain.");
415
- }
363
+ // Throws only for an invalid FELIX_CREDENTIAL_STORE override; every OS has a store.
364
+ credentialStoreKind();
416
365
  }
417
366
  function expandPath(value) {
418
367
  if (value === "~")
@@ -456,7 +405,7 @@ function recoveryStatus(status, overrides = {}) {
456
405
  const ready = status === "ready";
457
406
  const nextSteps = {
458
407
  ready: "none",
459
- unsupported: "Run guided onboarding on a supported macOS device with Keychain available.",
408
+ unsupported: "Run guided onboarding on a computer where Felix can store keys securely (macOS, Windows or Linux).",
460
409
  identity_incomplete: "Run the pinned felix-keys onboard command; it creates and verifies the missing local identity and recovery file automatically.",
461
410
  recovery_material_missing: "Do not fund this identity. Preserve any existing recovery file and restore its matching recovery material before continuing.",
462
411
  backup_missing: "Run the pinned felix-keys onboard command again; it will create and authenticate the encrypted recovery file automatically.",
@@ -526,8 +475,12 @@ export async function assessCustodyRecoveryArtifacts(input) {
526
475
  });
527
476
  }
528
477
  export async function getCustodyRecoveryStatus() {
529
- if (process.platform !== "darwin")
478
+ try {
479
+ credentialStoreKind();
480
+ }
481
+ catch {
530
482
  return recoveryStatus("unsupported");
483
+ }
531
484
  const ownerKey = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
532
485
  const apiKey = readKeychainPassword(API_KEYCHAIN_SERVICE);
533
486
  const recoveryCode = readKeychainPassword(BACKUP_RECOVERY_KEYCHAIN_SERVICE);
@@ -582,7 +535,7 @@ export function writePrivateFile(pathValue, contents) {
582
535
  }
583
536
  }
584
537
  chmodSync(targetResolved, 0o600);
585
- finalDescriptor = openSync(targetResolved, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
538
+ finalDescriptor = openReadNoFollow(targetResolved);
586
539
  fsyncSync(finalDescriptor);
587
540
  closeSync(finalDescriptor);
588
541
  finalDescriptor = undefined;
@@ -629,7 +582,7 @@ export function writePrivateFile(pathValue, contents) {
629
582
  }
630
583
  function readPrivateFile(pathValue) {
631
584
  const target = expandPath(pathValue);
632
- const descriptor = openSync(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
585
+ const descriptor = openReadNoFollow(target);
633
586
  try {
634
587
  const status = fstatSync(descriptor);
635
588
  if (!status.isFile() || status.size <= 0 || status.size > MAX_BACKUP_BYTES) {
@@ -655,10 +608,10 @@ async function backupCommand(output) {
655
608
  const ownerKey = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
656
609
  const apiKey = readKeychainPassword(API_KEYCHAIN_SERVICE);
657
610
  if (!ownerKey || !PRIVATE_KEY_RE.test(ownerKey)) {
658
- throw new Error("A valid Felix root owner key was not found in macOS Keychain.");
611
+ throw new Error(`A valid Felix root owner key was not found in ${credentialStoreLabel()}.`);
659
612
  }
660
613
  if (!apiKey || !API_KEY_RE.test(apiKey)) {
661
- throw new Error("A valid Felix launcher API key was not found in macOS Keychain.");
614
+ throw new Error(`A valid Felix launcher API key was not found in ${credentialStoreLabel()}.`);
662
615
  }
663
616
  const first = hiddenAnswer(`Choose a backup passphrase of at least ${MIN_PASSPHRASE_LENGTH} characters.`);
664
617
  if (first.length < MIN_PASSPHRASE_LENGTH) {
@@ -687,11 +640,8 @@ function showRecoveryCode(recoveryCode) {
687
640
  if (!isValidBackupRecoveryCode(recoveryCode)) {
688
641
  throw new Error("The stored Felix recovery code is invalid.");
689
642
  }
690
- const title = JSON.stringify("Felix recovery code");
691
- const prompt = JSON.stringify("Store this code separately from the encrypted backup for off-device recovery. "
692
- + "It is shown only in this native dialog and is never printed or returned to an AI agent.");
693
- const code = JSON.stringify(recoveryCode);
694
- appleScriptStdin(`display dialog ${prompt} default answer ${code} buttons {"Done"} default button "Done" with title ${title}`);
643
+ showToHuman("Felix recovery code", "Store this code separately from the encrypted backup for off-device recovery. "
644
+ + "It is shown only here and is never printed or returned to an AI agent.", recoveryCode);
695
645
  }
696
646
  function installedPackageVersion() {
697
647
  const manifest = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
@@ -701,6 +651,16 @@ function installedPackageVersion() {
701
651
  return value;
702
652
  }
703
653
  function runClaude(args) {
654
+ if (process.platform === "win32") {
655
+ // CROSS_PLATFORM_KEYS_20261123: the Claude CLI is a .cmd shim on Windows, which Node only starts through a
656
+ // shell. Every argument here is a fixed token or a version number, so nothing needs quoting.
657
+ if (args.some((arg) => !/^[A-Za-z0-9@._\/:-]+$/.test(arg)))
658
+ throw new Error("Unexpected Claude CLI argument.");
659
+ return spawnSync("claude", args, {
660
+ encoding: "utf8", maxBuffer: 64 * 1024, stdio: ["ignore", "pipe", "pipe"], shell: true, windowsHide: true,
661
+ cwd: homedir(), env: { ...process.env, NoDefaultCurrentDirectoryInExePath: "1" },
662
+ });
663
+ }
704
664
  return spawnSync("claude", args, {
705
665
  encoding: "utf8",
706
666
  maxBuffer: 64 * 1024,
@@ -730,11 +690,14 @@ function configureClaudeMcp(agentManaged = false) {
730
690
  const nodeDirectory = dirname(process.execPath);
731
691
  const pathParts = [nodeDirectory, ...(process.env.PATH || "").split(delimiter)]
732
692
  .filter((value, index, values) => value && values.indexOf(value) === index);
733
- const added = runClaude([
734
- "mcp", "add", "-s", "user", "felix",
735
- "-e", `PATH=${pathParts.join(delimiter)}`,
736
- "--", "npx", "-y", `felix-mcp@${version}`,
737
- ]);
693
+ const added = runClaude(process.platform === "win32"
694
+ // Windows: Claude Code starts npx through cmd, and desktop apps already inherit the user's PATH.
695
+ ? ["mcp", "add", "-s", "user", "felix", "--", "cmd", "/c", "npx", "-y", `felix-mcp@${version}`]
696
+ : [
697
+ "mcp", "add", "-s", "user", "felix",
698
+ "-e", `PATH=${pathParts.join(delimiter)}`,
699
+ "--", "npx", "-y", `felix-mcp@${version}`,
700
+ ]);
738
701
  if (added.status !== 0)
739
702
  throw new Error("Claude Code could not register the Felix MCP entry.");
740
703
  const verified = runClaude(["mcp", "get", "felix"]);
@@ -750,9 +713,6 @@ function inspectCommand(input) {
750
713
  console.log("This command reads public metadata only and does not decrypt the backup.");
751
714
  }
752
715
  function statusCommand() {
753
- if (process.platform !== "darwin") {
754
- throw new Error("Felix Keychain status currently requires macOS.");
755
- }
756
716
  const owner = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
757
717
  const apiKey = readKeychainPassword(API_KEYCHAIN_SERVICE);
758
718
  const recoveryCode = readKeychainPassword(BACKUP_RECOVERY_KEYCHAIN_SERVICE);
@@ -762,6 +722,7 @@ function statusCommand() {
762
722
  launcher_api_key_configured: Boolean(apiKey && API_KEY_RE.test(apiKey)),
763
723
  launcher_api_key_prefix: apiKey && API_KEY_RE.test(apiKey) ? apiKey.slice(0, 12) : null,
764
724
  backup_recovery_key_configured: Boolean(recoveryCode && isValidBackupRecoveryCode(recoveryCode)),
725
+ credential_store: credentialStoreDescription(),
765
726
  secrets_displayed: false,
766
727
  }));
767
728
  }
@@ -769,7 +730,7 @@ function exportRecoveryCodeCommand() {
769
730
  requireInteractiveMac();
770
731
  const recoveryCode = readKeychainPassword(BACKUP_RECOVERY_KEYCHAIN_SERVICE);
771
732
  if (!recoveryCode || !isValidBackupRecoveryCode(recoveryCode)) {
772
- throw new Error("No valid guided-backup recovery code was found in macOS Keychain.");
733
+ throw new Error(`No valid guided-backup recovery code was found in ${credentialStoreLabel()}.`);
773
734
  }
774
735
  showRecoveryCode(recoveryCode);
775
736
  console.log("The Felix recovery code was shown only in a native dialog. No secret was printed.");
@@ -792,35 +753,24 @@ function setupCommand() {
792
753
  const existing = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
793
754
  if (existing) {
794
755
  if (!PRIVATE_KEY_RE.test(existing)) {
795
- throw new Error("The existing Felix owner Keychain item is invalid; it was not replaced.");
756
+ throw new Error("The existing Felix owner stored key is invalid; it was not replaced.");
796
757
  }
797
758
  console.log(`Felix owner key is already configured for ${canonicalAddress(existing)}.`);
798
759
  console.log("No private key was printed or changed.");
799
760
  return;
800
761
  }
801
- confirmDialog("Create a new Felix root owner key in macOS Keychain? This establishes a new custody identity. Back it up before funding any account.", "Create owner key");
762
+ confirmDialog(`Create a new Felix root owner key in ${credentialStoreLabel()}? This establishes a new custody identity. Back it up before funding any account.`, "Create owner key");
763
+ refuseIfKeyringHidden();
802
764
  const ownerKey = generateOwnerPrivateKey();
803
- try {
804
- writeKeychainPassword(OWNER_KEYCHAIN_SERVICE, "Felix root owner key", ownerKey);
805
- const verified = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
806
- if (verified !== ownerKey)
807
- throw new Error("Owner Keychain write did not verify.");
808
- console.log(`Felix owner key created for ${canonicalAddress(ownerKey)}.`);
809
- console.log("No private key was printed. Run guided onboarding to register and create the encrypted recovery file automatically.");
810
- }
811
- catch {
812
- try {
813
- deleteKeychainPassword(OWNER_KEYCHAIN_SERVICE);
814
- }
815
- catch { /* best effort */ }
816
- throw new Error("Owner-key setup failed; no unverified credential was retained.");
817
- }
765
+ createOwnerKeyEntry(ownerKey);
766
+ console.log(`Felix owner key created for ${canonicalAddress(ownerKey)}.`);
767
+ console.log("No private key was printed. Run guided onboarding to register and create the encrypted recovery file automatically.");
818
768
  }
819
769
  function setApiKeyCommand() {
820
770
  requireInteractiveMac();
821
771
  const previous = readKeychainPassword(API_KEYCHAIN_SERVICE);
822
772
  if (previous && !API_KEY_RE.test(previous)) {
823
- throw new Error("The existing Felix launcher API Keychain item is invalid; it was not replaced.");
773
+ throw new Error("The existing Felix launcher API stored key is invalid; it was not replaced.");
824
774
  }
825
775
  if (previous) {
826
776
  confirmDialog(`Replace the installed Felix launcher API key ${previous.slice(0, 12)}? The complete key will remain hidden.`, "Replace API key");
@@ -837,7 +787,7 @@ function setApiKeyCommand() {
837
787
  try {
838
788
  writeKeychainPassword(API_KEYCHAIN_SERVICE, "Felix launcher API key", apiKey);
839
789
  if (readKeychainPassword(API_KEYCHAIN_SERVICE) !== apiKey) {
840
- throw new Error("Launcher API Keychain write did not verify.");
790
+ throw new Error("Launcher API key storage write did not verify.");
841
791
  }
842
792
  }
843
793
  catch {
@@ -845,11 +795,11 @@ function setApiKeyCommand() {
845
795
  rollbackItem(API_KEYCHAIN_SERVICE, "Felix launcher API key", previous);
846
796
  }
847
797
  catch {
848
- throw new Error("API-key setup failed and Keychain rollback requires immediate human inspection.");
798
+ throw new Error("API-key setup failed and key storage rollback requires immediate human inspection.");
849
799
  }
850
800
  throw new Error("API-key setup failed; the previous launcher credential was restored.");
851
801
  }
852
- console.log(`Felix launcher API key ${apiKey.slice(0, 12)} stored in macOS Keychain.`);
802
+ console.log(`Felix launcher API key ${apiKey.slice(0, 12)} stored in ${credentialStoreLabel()}.`);
853
803
  console.log("No complete API key was printed. Restart the local Felix MCP process.");
854
804
  }
855
805
  export function compareInstalledCredentials(credentials, currentOwner, currentApiKey) {
@@ -887,7 +837,7 @@ function rollbackItem(service, label, previous) {
887
837
  async function verifyCommand(input) {
888
838
  requireInteractiveMac();
889
839
  const envelope = parseBackupEnvelope(readPrivateFile(input));
890
- const passphrase = hiddenAnswer("Enter the backup passphrase to verify this identity without changing Keychain.");
840
+ const passphrase = hiddenAnswer("Enter the backup passphrase to verify this identity without changing stored keys.");
891
841
  const credentials = await openBackupEnvelope(envelope, passphrase);
892
842
  const comparison = compareInstalledCredentials(credentials, readKeychainPassword(OWNER_KEYCHAIN_SERVICE), readKeychainPassword(API_KEYCHAIN_SERVICE));
893
843
  console.log(JSON.stringify({
@@ -908,12 +858,21 @@ async function verifyCommand(input) {
908
858
  async function restoreCommand(input, allowReplacement = false) {
909
859
  requireInteractiveMac();
910
860
  const envelope = parseBackupEnvelope(readPrivateFile(input));
911
- confirmDialog(`Restore this encrypted Felix backup?\n\n${publicBackupSummary(envelope)}\n\nThis can replace credentials already stored on this Mac.`, "Verify backup");
861
+ confirmDialog(`Restore this encrypted Felix backup?\n\n${publicBackupSummary(envelope)}\n\nThis can replace credentials already stored on this computer.`, "Verify backup");
912
862
  const passphrase = hiddenAnswer("Enter the backup passphrase.");
913
863
  const credentials = await openBackupEnvelope(envelope, passphrase);
914
864
  const restoredAddress = canonicalAddress(credentials.root_owner_private_key);
915
- const previousOwner = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
916
- const previousApi = readKeychainPassword(API_KEYCHAIN_SERVICE);
865
+ let previousOwner;
866
+ let previousApi;
867
+ try {
868
+ previousOwner = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
869
+ previousApi = readKeychainPassword(API_KEYCHAIN_SERVICE);
870
+ }
871
+ catch (error) {
872
+ // QA r18 #1: restore must not dead-end on a store it cannot open. Nothing is overwritten blind: the owner
873
+ // moves the unreadable store aside (kept), and restore then runs into an empty store.
874
+ throw new Error(`${error instanceof Error ? error.message : "Local key storage could not be read."} Restore did not change anything.`);
875
+ }
917
876
  const comparison = compareInstalledCredentials(credentials, previousOwner, previousApi);
918
877
  if (comparison.state === "exact") {
919
878
  console.log(`Felix credentials already match backup owner ${restoredAddress}.`);
@@ -936,7 +895,7 @@ async function restoreCommand(input, allowReplacement = false) {
936
895
  if (verifiedApi !== credentials.launcher_api_key
937
896
  || verifiedOwner !== credentials.root_owner_private_key
938
897
  || canonicalAddress(verifiedOwner) !== envelope.owner_address) {
939
- throw new Error("Restored Keychain values did not verify.");
898
+ throw new Error("Restored key values did not verify.");
940
899
  }
941
900
  }
942
901
  catch {
@@ -945,9 +904,9 @@ async function restoreCommand(input, allowReplacement = false) {
945
904
  rollbackItem(OWNER_KEYCHAIN_SERVICE, "Felix root owner key", previousOwner);
946
905
  }
947
906
  catch {
948
- throw new Error("Restore failed and Keychain rollback requires immediate human inspection.");
907
+ throw new Error("Restore failed and key storage rollback requires immediate human inspection.");
949
908
  }
950
- throw new Error("Restore failed; the previous Keychain values were restored.");
909
+ throw new Error("Restore failed; the previous key values were restored.");
951
910
  }
952
911
  console.log(`Felix custody credentials restored for owner ${restoredAddress}.`);
953
912
  console.log("Restart the local Felix MCP process before using the restored identity.");
@@ -991,7 +950,7 @@ async function registerCommand(allowExisting = false, agentManaged = false) {
991
950
  const apiBase = validatedRegistrationApiBase();
992
951
  const installedApiKey = readKeychainPassword(API_KEYCHAIN_SERVICE);
993
952
  if (installedApiKey && !API_KEY_RE.test(installedApiKey)) {
994
- throw new Error("The installed Felix launcher API Keychain item is invalid; registration was not attempted.");
953
+ throw new Error("The installed Felix launcher API stored key is invalid; registration was not attempted.");
995
954
  }
996
955
  if (installedApiKey && allowExisting) {
997
956
  const installedOwnerKey = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
@@ -1008,26 +967,43 @@ async function registerCommand(allowExisting = false, agentManaged = false) {
1008
967
  let ownerKey = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
1009
968
  let ownerCreated = false;
1010
969
  if (ownerKey && !PRIVATE_KEY_RE.test(ownerKey)) {
1011
- throw new Error("The installed Felix owner Keychain item is invalid; registration was not attempted.");
970
+ throw new Error("The installed Felix owner stored key is invalid; registration was not attempted.");
1012
971
  }
1013
972
  if (!ownerKey) {
973
+ refuseIfKeyringHidden();
1014
974
  if (!agentManaged) {
1015
- confirmDialog(`Create a new Felix owner key and register a free launcher? This key controls every dollar held by its accounts. By continuing, you accept the current terms at https://felix.trade/legal (${FELIX_LEGAL_BUNDLE_VERSION}). The key stays in macOS Keychain and is never returned to the calling agent.`, "Create and register");
975
+ confirmDialog(`Create a new Felix owner key and register a free launcher? This key controls every dollar held by its accounts. By continuing, you accept the current terms at https://felix.trade/legal (${FELIX_LEGAL_BUNDLE_VERSION}). The key stays in ${credentialStoreLabel()} on this computer and is never returned to the calling agent.`, "Create and register");
1016
976
  }
1017
977
  ownerKey = generateOwnerPrivateKey();
1018
- writeKeychainPassword(OWNER_KEYCHAIN_SERVICE, "Felix root owner key", ownerKey);
1019
- if (readKeychainPassword(OWNER_KEYCHAIN_SERVICE) !== ownerKey) {
1020
- try {
1021
- deleteKeychainPassword(OWNER_KEYCHAIN_SERVICE);
1022
- }
1023
- catch { /* best effort */ }
1024
- throw new Error("Owner Keychain write did not verify; nothing was registered.");
1025
- }
978
+ createOwnerKeyEntry(ownerKey);
1026
979
  ownerCreated = true;
1027
980
  }
1028
981
  const account = privateKeyToAccount(ownerKey);
982
+ const { apiKey } = await registerOwnerWithFelix(apiBase, ownerKey);
983
+ writeKeychainPassword(API_KEYCHAIN_SERVICE, "Felix API key", apiKey);
984
+ if (readKeychainPassword(API_KEYCHAIN_SERVICE) !== apiKey) {
985
+ try {
986
+ deleteKeychainPassword(API_KEYCHAIN_SERVICE);
987
+ }
988
+ catch { /* best effort */ }
989
+ throw new Error("API-key key storage write did not verify; the key was not retained.");
990
+ }
991
+ if (ownerCreated)
992
+ markFreshWorkflowIdentity(ownerKey);
993
+ console.log("Felix account created.");
994
+ console.log(`Owner address: ${account.address}`);
995
+ console.log(`API key stored in ${credentialStoreLabel()} (prefix ${apiKey.slice(0, 8)}). The key itself was not printed.`);
996
+ console.log("Run guided onboarding to create and authenticate the encrypted recovery file automatically before funding.");
997
+ }
998
+ // KEY_RENEWAL_20261123: one owner-signed registration exchange, shared by register and renew-key.
999
+ // Felix answers a repeat registration for an existing owner with a fresh launcher key for the same
1000
+ // account (no new account, no money touched). Exported so tests can drive it against a loopback mock.
1001
+ export async function registerOwnerWithFelix(apiBase, ownerKey, fetchImpl = fetch) {
1002
+ if (!PRIVATE_KEY_RE.test(ownerKey))
1003
+ throw new Error("The Felix owner key is invalid; nothing was signed.");
1004
+ const account = privateKeyToAccount(ownerKey);
1029
1005
  const post = async (path, body) => {
1030
- const response = await fetch(`${apiBase}${path}`, {
1006
+ const response = await fetchImpl(`${apiBase}${path}`, {
1031
1007
  method: "POST",
1032
1008
  headers: { "Content-Type": "application/json", Accept: "application/json" },
1033
1009
  body: JSON.stringify(body),
@@ -1073,20 +1049,103 @@ async function registerCommand(allowExisting = false, agentManaged = false) {
1073
1049
  || /fk_[0-9a-f]{32}/i.test(registered.prefix))) {
1074
1050
  throw new Error("Felix returned a full credential in the API-key prefix; nothing was stored.");
1075
1051
  }
1052
+ return { apiKey, recoveredExistingAccount: registered.recovered_existing_account === true };
1053
+ }
1054
+ // KEY_RENEWAL_20261123: a launcher key can be revoked server-side (for example from the Felix app's Keys page).
1055
+ // Before this, Keychain kept the dead key and every felix-keys path refused to replace it. renew-key only acts
1056
+ // when Felix itself rejects the installed key, signs with the same owner key, and returns the replacement.
1057
+ export async function renewRejectedLauncherKey(apiBase, ownerKey, installedApiKey, fetchImpl = fetch) {
1058
+ if (!PRIVATE_KEY_RE.test(ownerKey)) {
1059
+ throw new Error("No valid Felix owner key is installed. Restore your encrypted backup with felix-keys restore; nothing was changed.");
1060
+ }
1061
+ if (!API_KEY_RE.test(installedApiKey)) {
1062
+ throw new Error("No valid Felix launcher key is installed. Run felix-keys onboard instead; nothing was changed.");
1063
+ }
1064
+ await assertLauncherKeyRejected(apiBase, installedApiKey, fetchImpl);
1065
+ const { apiKey, recoveredExistingAccount } = await registerOwnerWithFelix(apiBase, ownerKey, fetchImpl);
1066
+ if (!recoveredExistingAccount) {
1067
+ // Never keep a key for a different account than the one this owner already uses.
1068
+ throw new Error("Felix answered with a key for a new account instead of recovering your existing one, so it was not stored and your saved identity is unchanged. Contact Felix support with your owner address; do not fund any new account it lists.");
1069
+ }
1070
+ if (apiKey === installedApiKey) {
1071
+ throw new Error("Felix returned the rejected key again; nothing was stored.");
1072
+ }
1073
+ return { apiKey, previousPrefix: installedApiKey.slice(0, 12) };
1074
+ }
1075
+ async function assertLauncherKeyRejected(apiBase, installedApiKey, fetchImpl = fetch) {
1076
+ let probe;
1077
+ try {
1078
+ probe = await fetchImpl(`${apiBase}/v1/me/subscription`, {
1079
+ method: "GET",
1080
+ headers: { Accept: "application/json", Authorization: `Bearer ${installedApiKey}` },
1081
+ signal: AbortSignal.timeout(30_000),
1082
+ redirect: "error",
1083
+ });
1084
+ }
1085
+ catch {
1086
+ throw new Error("Felix could not be reached to check the installed key. Nothing was changed; retry when you are online.");
1087
+ }
1088
+ if (probe.status !== 401) {
1089
+ throw new Error(probe.ok
1090
+ ? "Felix still accepts the installed launcher key, so it was kept. Nothing was changed."
1091
+ : `Felix did not confirm the installed key is rejected (HTTP ${probe.status}). Nothing was changed; retry shortly.`);
1092
+ }
1093
+ }
1094
+ async function renewKeyCommand() {
1095
+ requireNativeMacSession();
1096
+ const apiBase = validatedRegistrationApiBase();
1097
+ const ownerKey = readKeychainPassword(OWNER_KEYCHAIN_SERVICE) || "";
1098
+ const installedApiKey = readKeychainPassword(API_KEYCHAIN_SERVICE) || "";
1099
+ if (!PRIVATE_KEY_RE.test(ownerKey) || !API_KEY_RE.test(installedApiKey)) {
1100
+ throw new Error("renew-key needs the installed owner key and launcher key. Run felix-keys status; restore your encrypted backup if either is missing. Nothing was changed.");
1101
+ }
1102
+ const ownerAddress = canonicalAddress(ownerKey);
1103
+ await assertLauncherKeyRejected(apiBase, installedApiKey);
1104
+ confirmDialog(`Felix no longer accepts the launcher key saved on this computer. Issue a replacement launcher key for owner ${ownerAddress}? Your accounts, agents and money are unchanged. By continuing you confirm the current terms at https://felix.trade/legal (${FELIX_LEGAL_BUNDLE_VERSION}). The new key stays in ${credentialStoreLabel()} and is never shown to an agent.`, "Replace key");
1105
+ const { apiKey, previousPrefix } = await renewRejectedLauncherKey(apiBase, ownerKey, installedApiKey);
1076
1106
  writeKeychainPassword(API_KEYCHAIN_SERVICE, "Felix API key", apiKey);
1077
1107
  if (readKeychainPassword(API_KEYCHAIN_SERVICE) !== apiKey) {
1078
- try {
1079
- deleteKeychainPassword(API_KEYCHAIN_SERVICE);
1108
+ throw new Error("The replacement key's key storage write did not verify. Run felix-keys renew-key again; the old key was already rejected by Felix.");
1109
+ }
1110
+ // Refresh the encrypted backup so a restore brings back the working key. The previous file is kept: its owner
1111
+ // key is still valid, and restoring it followed by renew-key also recovers.
1112
+ let backup = { refreshed: false, reason: "no_recovery_code_in_keychain" };
1113
+ const recoveryCode = readKeychainPassword(BACKUP_RECOVERY_KEYCHAIN_SERVICE);
1114
+ if (recoveryCode && isValidBackupRecoveryCode(recoveryCode)) {
1115
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..*$/, "");
1116
+ const target = expandPath(defaultBackupPath(ownerAddress).replace(/\.json$/, `-renewed-${stamp}.json`));
1117
+ const envelope = await createBackupEnvelope({
1118
+ root_owner_private_key: ownerKey,
1119
+ launcher_api_key: apiKey,
1120
+ }, recoveryCode);
1121
+ const written = writePrivateFile(target, `${JSON.stringify(envelope, null, 2)}\n`);
1122
+ const verified = await openBackupEnvelope(parseBackupEnvelope(readPrivateFile(written)), recoveryCode);
1123
+ if (verified.root_owner_private_key !== ownerKey || verified.launcher_api_key !== apiKey) {
1124
+ try {
1125
+ unlinkSync(written);
1126
+ }
1127
+ catch { /* best effort */ }
1128
+ backup = { refreshed: false, reason: "verification_failed" };
1129
+ }
1130
+ else {
1131
+ writeKeychainPassword(BACKUP_PATH_KEYCHAIN_SERVICE, "Felix encrypted-backup path", written);
1132
+ backup = {
1133
+ refreshed: true,
1134
+ backup_path: written.startsWith(`${homedir()}/`) ? `~/${written.slice(homedir().length + 1)}` : basename(written),
1135
+ previous_backup_kept: true,
1136
+ };
1080
1137
  }
1081
- catch { /* best effort */ }
1082
- throw new Error("API-key Keychain write did not verify; the key was not retained.");
1083
1138
  }
1084
- if (ownerCreated)
1085
- markFreshWorkflowIdentity(ownerKey);
1086
- console.log("Felix account created.");
1087
- console.log(`Owner address: ${account.address}`);
1088
- console.log(`API key stored in Keychain (prefix ${apiKey.slice(0, 8)}). The key itself was not printed.`);
1089
- console.log("Run guided onboarding to create and authenticate the encrypted recovery file automatically before funding.");
1139
+ console.log(JSON.stringify({
1140
+ ok: true,
1141
+ owner_address: ownerAddress,
1142
+ previous_key_prefix: previousPrefix,
1143
+ new_key_prefix: apiKey.slice(0, 12),
1144
+ encrypted_backup: backup,
1145
+ secrets_displayed: false,
1146
+ money_moved: false,
1147
+ next_step: "In your MCP client, call reload_launcher_key (or restart the client). Account keys reissue themselves on the next use_child_account.",
1148
+ }, null, 2));
1090
1149
  }
1091
1150
  async function onboardCommand(client = "claude", output, confirmOnMac = false) {
1092
1151
  requireNativeMacSession();
@@ -1102,7 +1161,7 @@ async function onboardCommand(client = "claude", output, confirmOnMac = false) {
1102
1161
  let recoveryCode = readKeychainPassword(BACKUP_RECOVERY_KEYCHAIN_SERVICE);
1103
1162
  let recoveryCodeCreated = false;
1104
1163
  if (recoveryCode && !isValidBackupRecoveryCode(recoveryCode)) {
1105
- throw new Error("The Felix backup-recovery Keychain item is invalid. No backup was changed or replaced.");
1164
+ throw new Error("The Felix backup-recovery stored key is invalid. No backup was changed or replaced.");
1106
1165
  }
1107
1166
  if (existsSync(target)) {
1108
1167
  const existing = parseBackupEnvelope(readPrivateFile(target));
@@ -1110,7 +1169,7 @@ async function onboardCommand(client = "claude", output, confirmOnMac = false) {
1110
1169
  throw new Error("The default backup path already contains a different Felix identity. Rerun onboard with --output <new-file>.");
1111
1170
  }
1112
1171
  if (!recoveryCode) {
1113
- throw new Error("A matching encrypted backup exists, but its recovery code is not in Keychain. Preserve the existing backup and use its original recovery code; no credential was changed.");
1172
+ throw new Error("A matching encrypted backup exists, but its recovery code is not in local key storage. Preserve the existing backup and use its original recovery code; no credential was changed.");
1114
1173
  }
1115
1174
  const opened = await openBackupEnvelope(existing, recoveryCode);
1116
1175
  if (opened.root_owner_private_key !== ownerKey || opened.launcher_api_key !== apiKey) {
@@ -1128,7 +1187,7 @@ async function onboardCommand(client = "claude", output, confirmOnMac = false) {
1128
1187
  deleteKeychainPassword(BACKUP_RECOVERY_KEYCHAIN_SERVICE);
1129
1188
  }
1130
1189
  catch { /* best effort */ }
1131
- throw new Error("Backup-recovery Keychain write did not verify; no backup was created.");
1190
+ throw new Error("Backup-recovery key storage write did not verify; no backup was created.");
1132
1191
  }
1133
1192
  recoveryCodeCreated = true;
1134
1193
  }
@@ -1181,12 +1240,16 @@ async function onboardCommand(client = "claude", output, confirmOnMac = false) {
1181
1240
  registration: "ready",
1182
1241
  encrypted_backup: backupState,
1183
1242
  backup_path: publicBackupPath,
1184
- backup_recovery: "macos_keychain",
1243
+ backup_recovery: credentialStoreKind(),
1185
1244
  custody_recovery: custodyRecovery,
1186
1245
  off_device_recovery_copy: "optional_not_required_for_onboarding",
1187
1246
  mcp_client: client,
1188
1247
  mcp_configuration: clientState,
1189
1248
  secrets_displayed: false,
1249
+ ...(credentialStoreKind() === "encrypted_file" ? {
1250
+ off_device_recovery_required: true,
1251
+ off_device_recovery_step: "Keys on this computer are sealed in files, not a system keyring. The owner should run `felix-keys export-recovery-code` in a terminal now and keep the code somewhere off this computer.",
1252
+ } : {}),
1190
1253
  next_step: client === "claude"
1191
1254
  ? "Reconnect Claude's MCP servers, allow the mcp__felix tool namespace, then ask Felix to create the primary account."
1192
1255
  : "Register this pinned felix-mcp package with your MCP host, then call get_status.",
@@ -1199,6 +1262,7 @@ Usage:
1199
1262
  felix-keys onboard --accept-terms [--client claude|none] [--output <file>] [--confirm-on-mac]
1200
1263
  felix-keys setup
1201
1264
  felix-keys register
1265
+ felix-keys renew-key
1202
1266
  felix-keys set-api-key
1203
1267
  felix-keys status
1204
1268
  felix-keys export-recovery-code
@@ -1210,12 +1274,14 @@ Usage:
1210
1274
 
1211
1275
  onboard lets an agent complete registration, encrypted backup, MCP client
1212
1276
  configuration, and verification after the user explicitly accepts the current
1213
- terms. The owner key, API key, and generated recovery code stay in macOS
1214
- Keychain and never enter agent output. No follow-up copy/paste or terminal
1277
+ terms. The owner key, API key, and generated recovery code stay in the
1278
+ computer's key storage (macOS Keychain, Windows protected storage, or the Linux
1279
+ keyring or a sealed owner-only file) and never enter agent output. No follow-up copy/paste or terminal
1215
1280
  backup step is required. Optional disaster-recovery export and restore actions
1216
1281
  remain owner-controlled native dialogs outside the normal agent workflow.
1217
1282
  restore refuses to replace a different installed identity; replace is the
1218
- explicit identity-rotation command. Passphrases and keys cannot be supplied
1283
+ explicit identity-rotation command. renew-key replaces a launcher key that Felix
1284
+ has revoked, for the same owner, after the owner confirms on screen. Passphrases and keys cannot be supplied
1219
1285
  through command-line arguments.`);
1220
1286
  }
1221
1287
  async function main() {
@@ -1231,6 +1297,8 @@ async function main() {
1231
1297
  setApiKeyCommand();
1232
1298
  else if (args.command === "register")
1233
1299
  await registerCommand();
1300
+ else if (args.command === "renew-key")
1301
+ await renewKeyCommand();
1234
1302
  else if (args.command === "status")
1235
1303
  statusCommand();
1236
1304
  else if (args.command === "export-recovery-code")