tenjin-cli 0.1.0-alpha.4 → 0.1.0-alpha.7

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 (135) hide show
  1. package/README.md +269 -38
  2. package/dist/{buy-OOOLUDND.js → buy-XVOMNWKN.js} +21 -18
  3. package/dist/{candidate-TWCWTFGA.js → candidate-DJB2NNTG.js} +7 -8
  4. package/dist/{chunk-KXIX7YDV.js → chunk-2KIDDWQO.js} +5 -5
  5. package/dist/{chunk-NXCJN2FJ.js → chunk-2L73UI6T.js} +51 -42
  6. package/dist/chunk-2L73UI6T.js.map +1 -0
  7. package/dist/{chunk-OJD54DIU.js → chunk-2YX6LTCD.js} +5 -5
  8. package/dist/{chunk-H5ETJRQD.js → chunk-5X4EBGGU.js} +22 -14
  9. package/dist/chunk-5X4EBGGU.js.map +1 -0
  10. package/dist/chunk-6S44OLND.js +699 -0
  11. package/dist/chunk-6S44OLND.js.map +1 -0
  12. package/dist/{chunk-FU6MCSLG.js → chunk-7WDY4AXV.js} +2 -64
  13. package/dist/chunk-7WDY4AXV.js.map +1 -0
  14. package/dist/{chunk-VV4P5RVK.js → chunk-BBUYCDSG.js} +16 -4
  15. package/dist/chunk-BBUYCDSG.js.map +1 -0
  16. package/dist/chunk-CYRYVZPN.js +213 -0
  17. package/dist/chunk-CYRYVZPN.js.map +1 -0
  18. package/dist/{chunk-FHB3VKZW.js → chunk-DAJ56EUU.js} +5 -3
  19. package/dist/chunk-DAJ56EUU.js.map +1 -0
  20. package/dist/chunk-DH6D6QIO.js +239 -0
  21. package/dist/chunk-DH6D6QIO.js.map +1 -0
  22. package/dist/chunk-E6BNARCS.js +614 -0
  23. package/dist/chunk-E6BNARCS.js.map +1 -0
  24. package/dist/chunk-GABYDXWL.js +190 -0
  25. package/dist/chunk-GABYDXWL.js.map +1 -0
  26. package/dist/{chunk-EUQN3L5X.js → chunk-GM4RZUVU.js} +21 -9
  27. package/dist/chunk-GM4RZUVU.js.map +1 -0
  28. package/dist/{chunk-C4TIWOAM.js → chunk-GXYNLMUQ.js} +28 -11
  29. package/dist/chunk-GXYNLMUQ.js.map +1 -0
  30. package/dist/{chunk-6WWVYYSB.js → chunk-J6CVKC4M.js} +86 -4
  31. package/dist/chunk-J6CVKC4M.js.map +1 -0
  32. package/dist/{chunk-5JH7ZB6Z.js → chunk-KT2DGKFT.js} +76 -10
  33. package/dist/chunk-KT2DGKFT.js.map +1 -0
  34. package/dist/chunk-L6AV2Q73.js +105 -0
  35. package/dist/chunk-L6AV2Q73.js.map +1 -0
  36. package/dist/{chunk-333FOTUJ.js → chunk-MJZZTKCC.js} +108 -2
  37. package/dist/chunk-MJZZTKCC.js.map +1 -0
  38. package/dist/{chunk-XNNOR7F7.js → chunk-OTDI5FXG.js} +3 -5
  39. package/dist/{chunk-XNNOR7F7.js.map → chunk-OTDI5FXG.js.map} +1 -1
  40. package/dist/chunk-PIIWLEEG.js +337 -0
  41. package/dist/chunk-PIIWLEEG.js.map +1 -0
  42. package/dist/{chunk-ULLWHHIT.js → chunk-PLU3E63S.js} +468 -559
  43. package/dist/chunk-PLU3E63S.js.map +1 -0
  44. package/dist/chunk-QW2Q2KAH.js +27 -0
  45. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  46. package/dist/{chunk-S3KZ3PPK.js → chunk-RGFBBNGP.js} +291 -59
  47. package/dist/chunk-RGFBBNGP.js.map +1 -0
  48. package/dist/chunk-SGK2B724.js +67 -0
  49. package/dist/chunk-SGK2B724.js.map +1 -0
  50. package/dist/chunk-UYP7G3GZ.js +412 -0
  51. package/dist/chunk-UYP7G3GZ.js.map +1 -0
  52. package/dist/{chunk-DPUMEMGM.js → chunk-VZ3AJCO5.js} +3 -5
  53. package/dist/{chunk-DPUMEMGM.js.map → chunk-VZ3AJCO5.js.map} +1 -1
  54. package/dist/{chunk-QH6677FJ.js → chunk-WDJTGVKN.js} +2 -2
  55. package/dist/{chunk-QH6677FJ.js.map → chunk-WDJTGVKN.js.map} +1 -1
  56. package/dist/{chunk-4GR7DGD6.js → chunk-WI5EOAQQ.js} +33 -256
  57. package/dist/{chunk-4GR7DGD6.js.map → chunk-WI5EOAQQ.js.map} +1 -1
  58. package/dist/{chunk-DPET3TW5.js → chunk-WRWCDLVK.js} +13 -12
  59. package/dist/chunk-WRWCDLVK.js.map +1 -0
  60. package/dist/chunk-XBJ3VLWX.js +35 -0
  61. package/dist/chunk-XBJ3VLWX.js.map +1 -0
  62. package/dist/chunk-ZEWY3RJ3.js +149 -0
  63. package/dist/chunk-ZEWY3RJ3.js.map +1 -0
  64. package/dist/chunk-ZFE7STX7.js +143 -0
  65. package/dist/chunk-ZFE7STX7.js.map +1 -0
  66. package/dist/{cli-AFSLAKR6.js → cli-7B2QNJG3.js} +247 -26
  67. package/dist/cli-7B2QNJG3.js.map +1 -0
  68. package/dist/{config-DBEEM3UA.js → config-SAQEQRFB.js} +7 -6
  69. package/dist/{doctor-XDA3YU6H.js → doctor-ENJ22XWN.js} +10 -8
  70. package/dist/{publish-IH7RJXGB.js → edit-2QO5GQDU.js} +19 -17
  71. package/dist/index.js +1 -1
  72. package/dist/{inspect-YBGDAG47.js → inspect-IPKKQB2S.js} +16 -15
  73. package/dist/{install-7J6KKEEP.js → install-7ZIYISQ7.js} +180 -133
  74. package/dist/install-7ZIYISQ7.js.map +1 -0
  75. package/dist/outcome-NSDE2KAJ.js +20 -0
  76. package/dist/publish-7WIFFNFG.js +40 -0
  77. package/dist/read-5TQR7LCF.js +158 -0
  78. package/dist/read-5TQR7LCF.js.map +1 -0
  79. package/dist/{run-DCZFEW2C.js → run-NPKIP26Y.js} +109 -34
  80. package/dist/{run-DCZFEW2C.js.map → run-NPKIP26Y.js.map} +1 -1
  81. package/dist/search-63ELMRZH.js +24 -0
  82. package/dist/send-ENE47KQE.js +222 -0
  83. package/dist/send-ENE47KQE.js.map +1 -0
  84. package/dist/session-FZU4VFFE.js +87 -0
  85. package/dist/session-FZU4VFFE.js.map +1 -0
  86. package/dist/{usdc-AU6ZIKA6.js → usdc-4VCDHFWX.js} +20 -4
  87. package/dist/{wallet-UWHSHWC6.js → wallet-OCCGEH6H.js} +8 -8
  88. package/dist/{wallet-HKG3GSTX.js → wallet-RBDVNZVR.js} +17 -7
  89. package/dist/wallet-RBDVNZVR.js.map +1 -0
  90. package/package.json +1 -1
  91. package/skills/tenjin/SKILL.md +32 -7
  92. package/skills/tenjin-publish/SKILL.md +109 -16
  93. package/skills/tenjin-search/SKILL.md +174 -15
  94. package/dist/chunk-333FOTUJ.js.map +0 -1
  95. package/dist/chunk-5JH7ZB6Z.js.map +0 -1
  96. package/dist/chunk-6WWVYYSB.js.map +0 -1
  97. package/dist/chunk-BXUS5UCT.js +0 -212
  98. package/dist/chunk-BXUS5UCT.js.map +0 -1
  99. package/dist/chunk-C4TIWOAM.js.map +0 -1
  100. package/dist/chunk-CJU555P5.js +0 -333
  101. package/dist/chunk-CJU555P5.js.map +0 -1
  102. package/dist/chunk-DPET3TW5.js.map +0 -1
  103. package/dist/chunk-EUQN3L5X.js.map +0 -1
  104. package/dist/chunk-FHB3VKZW.js.map +0 -1
  105. package/dist/chunk-FU6MCSLG.js.map +0 -1
  106. package/dist/chunk-H5ETJRQD.js.map +0 -1
  107. package/dist/chunk-MM4TGTST.js +0 -59
  108. package/dist/chunk-MM4TGTST.js.map +0 -1
  109. package/dist/chunk-MUBUQVC3.js +0 -67
  110. package/dist/chunk-MUBUQVC3.js.map +0 -1
  111. package/dist/chunk-NXCJN2FJ.js.map +0 -1
  112. package/dist/chunk-R7BMDJZM.js +0 -167
  113. package/dist/chunk-R7BMDJZM.js.map +0 -1
  114. package/dist/chunk-S3KZ3PPK.js.map +0 -1
  115. package/dist/chunk-ULLWHHIT.js.map +0 -1
  116. package/dist/chunk-VV4P5RVK.js.map +0 -1
  117. package/dist/chunk-YFREUEUI.js +0 -78
  118. package/dist/chunk-YFREUEUI.js.map +0 -1
  119. package/dist/cli-AFSLAKR6.js.map +0 -1
  120. package/dist/install-7J6KKEEP.js.map +0 -1
  121. package/dist/outcome-ZFGHX2XW.js +0 -20
  122. package/dist/search-R6NIQFXI.js +0 -24
  123. /package/dist/{buy-OOOLUDND.js.map → buy-XVOMNWKN.js.map} +0 -0
  124. /package/dist/{candidate-TWCWTFGA.js.map → candidate-DJB2NNTG.js.map} +0 -0
  125. /package/dist/{chunk-KXIX7YDV.js.map → chunk-2KIDDWQO.js.map} +0 -0
  126. /package/dist/{chunk-OJD54DIU.js.map → chunk-2YX6LTCD.js.map} +0 -0
  127. /package/dist/{config-DBEEM3UA.js.map → config-SAQEQRFB.js.map} +0 -0
  128. /package/dist/{doctor-XDA3YU6H.js.map → doctor-ENJ22XWN.js.map} +0 -0
  129. /package/dist/{inspect-YBGDAG47.js.map → edit-2QO5GQDU.js.map} +0 -0
  130. /package/dist/{outcome-ZFGHX2XW.js.map → inspect-IPKKQB2S.js.map} +0 -0
  131. /package/dist/{publish-IH7RJXGB.js.map → outcome-NSDE2KAJ.js.map} +0 -0
  132. /package/dist/{search-R6NIQFXI.js.map → publish-7WIFFNFG.js.map} +0 -0
  133. /package/dist/{usdc-AU6ZIKA6.js.map → search-63ELMRZH.js.map} +0 -0
  134. /package/dist/{wallet-HKG3GSTX.js.map → usdc-4VCDHFWX.js.map} +0 -0
  135. /package/dist/{wallet-UWHSHWC6.js.map → wallet-OCCGEH6H.js.map} +0 -0
@@ -4,22 +4,30 @@ import {
4
4
  readWalletRecord,
5
5
  walletFileMode,
6
6
  writeWalletRecord
7
- } from "./chunk-DPET3TW5.js";
7
+ } from "./chunk-WRWCDLVK.js";
8
+ import {
9
+ hasCode
10
+ } from "./chunk-2I4QTOLB.js";
11
+ import {
12
+ emitNotice
13
+ } from "./chunk-BBUYCDSG.js";
8
14
  import {
9
15
  withFileLock
10
16
  } from "./chunk-YBMMV4Y4.js";
11
17
  import {
12
18
  evaluateSpendPolicy
13
19
  } from "./chunk-UO22YNY4.js";
14
- import {
15
- writeFileAtomic
16
- } from "./chunk-MUBUQVC3.js";
17
20
  import {
18
21
  CliError,
22
+ archivedWalletPath,
19
23
  external_exports,
24
+ fsyncDir,
20
25
  passphraseBlobPath,
21
- walletPath
22
- } from "./chunk-6WWVYYSB.js";
26
+ passphraseBlobPathFor,
27
+ spendLedgerPath,
28
+ walletPath,
29
+ writeFileAtomic
30
+ } from "./chunk-J6CVKC4M.js";
23
31
  import {
24
32
  hashAuthorization,
25
33
  hashMessage,
@@ -62,6 +70,9 @@ import {
62
70
  u32
63
71
  } from "./chunk-KYQVEKP5.js";
64
72
 
73
+ // src/lib/wallet/local.ts
74
+ import { link, readdir, unlink as unlink2 } from "fs/promises";
75
+
65
76
  // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
66
77
  function pbkdf2Init(hash, _password, _salt, _opts) {
67
78
  ahash(hash);
@@ -761,10 +772,18 @@ function defineKey(key, options) {
761
772
  // src/lib/wallet/passphrase.ts
762
773
  import { execFile } from "child_process";
763
774
  import { randomBytes } from "crypto";
764
- import { readFile } from "fs/promises";
775
+ import { readFile, unlink } from "fs/promises";
765
776
  var KEYCHAIN_SERVICE = "tenjin-cli";
766
- var KEYCHAIN_ACCOUNT = "wallet";
777
+ var LEGACY_ACCOUNT = "wallet";
778
+ var ACCOUNT_ADDRESS_RE = /^0x[0-9a-f]{40}$/;
767
779
  var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
780
+ function walletStoreAccount(address) {
781
+ const account = address.toLowerCase();
782
+ if (!ACCOUNT_ADDRESS_RE.test(account)) {
783
+ throw new CliError("INTERNAL", `Not a valid wallet address for passphrase storage: ${address}`);
784
+ }
785
+ return account;
786
+ }
768
787
  var defaultExec = (file, args, stdin) => new Promise((resolve, reject) => {
769
788
  const child = execFile(file, args, { encoding: "utf8" }, (err, stdout, stderr) => {
770
789
  if (err) reject(err);
@@ -787,13 +806,22 @@ function storeFor(deps) {
787
806
  return null;
788
807
  }
789
808
  }
790
- async function resolvePassphrase(deps) {
809
+ async function resolvePassphrase(deps, address) {
791
810
  const fromEnv = envPassphrase(deps.env);
792
811
  if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
793
812
  const store = storeFor(deps);
794
813
  if (store !== null) {
795
- const fromStore = await store.read();
796
- if (fromStore !== null) return { passphrase: fromStore, source: store.source };
814
+ const account = walletStoreAccount(address);
815
+ const own = await store.read(account);
816
+ if (own !== null) return { passphrase: own, source: store.source };
817
+ const legacy = await store.read(LEGACY_ACCOUNT);
818
+ if (legacy !== null) {
819
+ return {
820
+ passphrase: legacy,
821
+ source: store.source,
822
+ migrateLegacy: () => migrateLegacyEntry(store, account, legacy)
823
+ };
824
+ }
797
825
  }
798
826
  if (canPrompt(deps)) {
799
827
  const entered = await promptOf(deps)("Wallet passphrase: ");
@@ -802,13 +830,29 @@ async function resolvePassphrase(deps) {
802
830
  }
803
831
  throw noPassphraseError();
804
832
  }
805
- async function resolvePassphraseForCreate(deps) {
833
+ async function migrateLegacyEntry(store, account, passphrase) {
834
+ if (!await store.store(account, passphrase)) return false;
835
+ if (await store.read(account) !== passphrase) return false;
836
+ await store.remove(LEGACY_ACCOUNT);
837
+ return true;
838
+ }
839
+ async function storePassphraseForWallet(deps, address, passphrase) {
840
+ const store = storeFor(deps);
841
+ if (store === null) return "no-store";
842
+ const account = walletStoreAccount(address);
843
+ if (await store.read(account) === passphrase) return "stored";
844
+ if (store.storable !== void 0 && !store.storable(passphrase)) return "rejected-characters";
845
+ if (!await store.store(account, passphrase)) return "store-failed";
846
+ return await store.read(account) === passphrase ? "stored" : "store-failed";
847
+ }
848
+ async function resolvePassphraseForCreate(deps, address) {
806
849
  const fromEnv = envPassphrase(deps.env);
807
850
  if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
808
851
  const store = storeFor(deps);
809
852
  if (store !== null) {
853
+ const account = walletStoreAccount(address);
810
854
  const generated = randomBytes(32).toString("base64url");
811
- if (await store.store(generated)) {
855
+ if (await store.store(account, generated) && await store.read(account) === generated) {
812
856
  return { passphrase: generated, source: store.source };
813
857
  }
814
858
  }
@@ -834,14 +878,14 @@ function keychainStore(deps) {
834
878
  const exec = deps.exec ?? defaultExec;
835
879
  return {
836
880
  source: "keychain",
837
- async read() {
881
+ async read(account) {
838
882
  try {
839
883
  const { stdout } = await exec("security", [
840
884
  "find-generic-password",
841
885
  "-s",
842
886
  KEYCHAIN_SERVICE,
843
887
  "-a",
844
- KEYCHAIN_ACCOUNT,
888
+ account,
845
889
  "-w"
846
890
  ]);
847
891
  return trimmedNonEmpty(stdout);
@@ -849,16 +893,28 @@ function keychainStore(deps) {
849
893
  return null;
850
894
  }
851
895
  },
852
- async store(passphrase) {
853
- if (!BASE64URL_RE.test(passphrase)) return false;
896
+ // The one backend that interpolates into a command line, so only base64url
897
+ // values pass; escaping is NOT a safe alternative (backslash bites even
898
+ // inside single quotes there).
899
+ storable: (passphrase) => BASE64URL_RE.test(passphrase),
900
+ async store(account, passphrase) {
901
+ if (!BASE64URL_RE.test(passphrase) || !BASE64URL_RE.test(account)) return false;
854
902
  try {
855
- const command = `add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${KEYCHAIN_ACCOUNT} -w '${passphrase}'
903
+ const command = `add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} -w '${passphrase}'
856
904
  `;
857
905
  await exec("security", ["-i"], command);
858
906
  return true;
859
907
  } catch {
860
908
  return false;
861
909
  }
910
+ },
911
+ async remove(account) {
912
+ try {
913
+ await exec("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account]);
914
+ return true;
915
+ } catch {
916
+ return false;
917
+ }
862
918
  }
863
919
  };
864
920
  }
@@ -881,13 +937,13 @@ function powershellArgs(script) {
881
937
  }
882
938
  function dpapiStore(deps) {
883
939
  const exec = deps.exec ?? defaultExec;
884
- const blobPath = passphraseBlobPath(deps.dir);
940
+ const blobPathFor = (account) => account === LEGACY_ACCOUNT ? passphraseBlobPath(deps.dir) : passphraseBlobPathFor(account, deps.dir);
885
941
  return {
886
942
  source: "dpapi",
887
- async read() {
943
+ async read(account) {
888
944
  let blob;
889
945
  try {
890
- blob = await readFile(blobPath, "utf8");
946
+ blob = await readFile(blobPathFor(account), "utf8");
891
947
  } catch {
892
948
  return null;
893
949
  }
@@ -903,7 +959,7 @@ function dpapiStore(deps) {
903
959
  return null;
904
960
  }
905
961
  },
906
- async store(passphrase) {
962
+ async store(account, passphrase) {
907
963
  try {
908
964
  const { stdout } = await exec(
909
965
  "powershell.exe",
@@ -912,7 +968,15 @@ function dpapiStore(deps) {
912
968
  );
913
969
  const blob = stdout.replace(/\r?\n$/, "").trim();
914
970
  if (blob.length === 0) return false;
915
- await writeFileAtomic(blobPath, blob, { mode: 384 });
971
+ await writeFileAtomic(blobPathFor(account), blob, { mode: 384 });
972
+ return true;
973
+ } catch {
974
+ return false;
975
+ }
976
+ },
977
+ async remove(account) {
978
+ try {
979
+ await unlink(blobPathFor(account));
916
980
  return true;
917
981
  } catch {
918
982
  return false;
@@ -924,31 +988,31 @@ function secretServiceStore(deps) {
924
988
  const exec = deps.exec ?? defaultExec;
925
989
  return {
926
990
  source: "secret-service",
927
- async read() {
991
+ async read(account) {
928
992
  try {
929
993
  const { stdout } = await exec("secret-tool", [
930
994
  "lookup",
931
995
  "service",
932
996
  KEYCHAIN_SERVICE,
933
997
  "account",
934
- KEYCHAIN_ACCOUNT
998
+ account
935
999
  ]);
936
1000
  return trimmedNonEmpty(stdout);
937
1001
  } catch {
938
1002
  return null;
939
1003
  }
940
1004
  },
941
- async store(passphrase) {
1005
+ async store(account, passphrase) {
942
1006
  try {
943
1007
  await exec(
944
1008
  "secret-tool",
945
1009
  [
946
1010
  "store",
947
- "--label=tenjin-cli-wallet",
1011
+ `--label=tenjin-cli wallet ${account}`,
948
1012
  "service",
949
1013
  KEYCHAIN_SERVICE,
950
1014
  "account",
951
- KEYCHAIN_ACCOUNT
1015
+ account
952
1016
  ],
953
1017
  passphrase
954
1018
  );
@@ -956,6 +1020,14 @@ function secretServiceStore(deps) {
956
1020
  } catch {
957
1021
  return false;
958
1022
  }
1023
+ },
1024
+ async remove(account) {
1025
+ try {
1026
+ await exec("secret-tool", ["clear", "service", KEYCHAIN_SERVICE, "account", account]);
1027
+ return true;
1028
+ } catch {
1029
+ return false;
1030
+ }
959
1031
  }
960
1032
  };
961
1033
  }
@@ -1034,7 +1106,7 @@ function createLocalProvider(deps) {
1034
1106
  return {
1035
1107
  id: "local",
1036
1108
  async describe() {
1037
- const cred = resolveCredentialOrThrow(await loadCredential(deps));
1109
+ const cred = await credentialOrThrow(deps);
1038
1110
  return {
1039
1111
  // A file credential's address is stored cleartext and returned as-is —
1040
1112
  // no decryption. An env credential derives (and thereby validates) its
@@ -1046,12 +1118,13 @@ function createLocalProvider(deps) {
1046
1118
  };
1047
1119
  },
1048
1120
  async getSigner() {
1049
- const cred = resolveCredentialOrThrow(await loadCredential(deps));
1121
+ const cred = await credentialOrThrow(deps);
1050
1122
  const account = await accountForSigning(cred, deps);
1051
1123
  return {
1052
1124
  address: account.address,
1053
1125
  signMessage: (args) => account.signMessage({ message: args.message }),
1054
- signTypedData: (args) => account.signTypedData(args)
1126
+ signTypedData: (args) => account.signTypedData(args),
1127
+ signTransaction: (tx) => account.signTransaction(tx)
1055
1128
  };
1056
1129
  },
1057
1130
  diagnostics() {
@@ -1079,18 +1152,133 @@ async function localWalletDiagnostics(deps) {
1079
1152
  }
1080
1153
  }
1081
1154
  const passphraseSource = deps.env.TENJIN_WALLET_PASSPHRASE !== void 0 && deps.env.TENJIN_WALLET_PASSPHRASE.length > 0 ? "TENJIN_WALLET_PASSPHRASE" : void 0;
1155
+ const archivedWallets = await listArchivedWallets(deps.dir);
1082
1156
  return {
1083
1157
  ...fileExists ? { walletPath: path, keyStorage: KEY_STORAGE } : {},
1084
1158
  ...fileExists && passphraseSource !== void 0 ? { passphraseSource } : {},
1159
+ ...archivedWallets.length > 0 ? { archivedWallets } : {},
1085
1160
  warnings
1086
1161
  };
1087
1162
  }
1088
- async function createLocalWallet(dir, passphrase) {
1163
+ var ARCHIVED_WALLET_RE = /^wallet\.(0x[0-9a-f]{40})\.json\.bak$/;
1164
+ async function listArchivedWallets(dir) {
1165
+ let names;
1166
+ try {
1167
+ names = await readdir(dir);
1168
+ } catch {
1169
+ return [];
1170
+ }
1171
+ return names.map((name) => ARCHIVED_WALLET_RE.exec(name)?.[1]).filter((address) => address !== void 0).sort();
1172
+ }
1173
+ async function prepareLocalWallet(passphrase) {
1089
1174
  const key = generatePrivateKey();
1090
1175
  const address = privateKeyToAccount(key).address;
1091
- const keystore = await encryptToKeystore(key, passphrase);
1092
- await writeWalletRecord(dir, walletRecord(address, keystore));
1093
- return { address, walletPath: walletPath(dir) };
1176
+ const resolved = typeof passphrase === "string" ? passphrase : await passphrase(address);
1177
+ const keystore = await encryptToKeystore(key, resolved);
1178
+ return { address, record: walletRecord(address, keystore) };
1179
+ }
1180
+ async function commitLocalWallet(dir, prepared) {
1181
+ await writeWalletRecord(dir, prepared.record);
1182
+ return { address: prepared.address, walletPath: walletPath(dir) };
1183
+ }
1184
+ async function createLocalWallet(dir, passphrase) {
1185
+ return commitLocalWallet(dir, await prepareLocalWallet(passphrase));
1186
+ }
1187
+ async function verifyAndPreserveOutgoingWallet(deps) {
1188
+ const record = await readWalletRecord(deps.dir);
1189
+ if (record === null) {
1190
+ throw new CliError("WALLET_MISSING", "No wallet found to archive.", {
1191
+ fix: "Run `tenjin wallet create` without --replace."
1192
+ });
1193
+ }
1194
+ const address = record.address;
1195
+ const account = walletStoreAccount(address);
1196
+ const passphraseDeps = { env: deps.env, dir: deps.dir, ...deps.passphrase };
1197
+ const resolved = await resolvePassphrase(passphraseDeps, address);
1198
+ let key;
1199
+ try {
1200
+ const derived = await toKeyAsync(record.keystore, { password: resolved.passphrase });
1201
+ key = decrypt(record.keystore, derived);
1202
+ } catch (err) {
1203
+ const escape = resolved.source === "prompt" ? "Retry and enter that wallet's correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it" : resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase" : `Set TENJIN_WALLET_PASSPHRASE to its passphrase, or fix its OS credential store entry (service tenjin-cli, account ${account})`;
1204
+ throw new CliError(
1205
+ "REFUSED",
1206
+ `Cannot verify the passphrase of the existing wallet ${address}; --replace refused.`,
1207
+ {
1208
+ fix: `Replacing now could strand that wallet's funds. ${escape}, then retry.`,
1209
+ cause: err
1210
+ }
1211
+ );
1212
+ }
1213
+ if (privateKeyToAccount(key).address.toLowerCase() !== account) {
1214
+ throw new CliError(
1215
+ "REFUSED",
1216
+ `The wallet file's stored address ${address} does not match its key; --replace refused.`,
1217
+ { fix: "The wallet file may be tampered. Resolve that before replacing it." }
1218
+ );
1219
+ }
1220
+ if (resolved.source === "env") {
1221
+ return { address, account, passphraseLocation: "env" };
1222
+ }
1223
+ if (resolved.migrateLegacy !== void 0) {
1224
+ if (!await resolved.migrateLegacy()) {
1225
+ throw new CliError(
1226
+ "REFUSED",
1227
+ `Could not archive the existing wallet's passphrase under its own address; --replace refused.`,
1228
+ {
1229
+ fix: `The passphrase currently lives only in the legacy shared slot (service tenjin-cli, account "wallet"), and copying it to account ${account} failed. Retry, or check OS credential store access.`
1230
+ }
1231
+ );
1232
+ }
1233
+ return { address, account, passphraseLocation: "store" };
1234
+ }
1235
+ if (resolved.source === "prompt") {
1236
+ const outcome = await storePassphraseForWallet(passphraseDeps, address, resolved.passphrase);
1237
+ return outcome === "stored" ? { address, account, passphraseLocation: "store" } : { address, account, passphraseLocation: "unarchived", unarchivedReason: outcome };
1238
+ }
1239
+ return { address, account, passphraseLocation: "store" };
1240
+ }
1241
+ async function parkOutgoingWallet(dir, account) {
1242
+ const src = walletPath(dir);
1243
+ const dst = archivedWalletPath(account, dir);
1244
+ try {
1245
+ await link(src, dst);
1246
+ } catch (err) {
1247
+ if (hasCode(err, "EEXIST")) {
1248
+ throw new CliError("REFUSED", `An archived wallet already exists at ${dst}.`, {
1249
+ fix: `Move ${dst} aside, then retry \`tenjin wallet create --replace\`. Nothing has moved; the current wallet is still active.`,
1250
+ cause: err
1251
+ });
1252
+ }
1253
+ throw new CliError("INTERNAL", `Could not park the outgoing keystore at ${dst}.`, {
1254
+ fix: `Nothing has moved; the current wallet is still active at ${src}. Fix the underlying filesystem error and retry.`,
1255
+ cause: err
1256
+ });
1257
+ }
1258
+ try {
1259
+ await unlink2(src);
1260
+ } catch (err) {
1261
+ await unlink2(dst).catch(() => void 0);
1262
+ throw new CliError(
1263
+ "INTERNAL",
1264
+ `Could not clear the active wallet slot ${src} while parking the outgoing wallet.`,
1265
+ {
1266
+ fix: "The previous wallet is still active and nothing was lost. Fix the underlying filesystem error (on Windows, close any process holding the wallet file open) and retry.",
1267
+ cause: err
1268
+ }
1269
+ );
1270
+ }
1271
+ await syncWalletDir(dir);
1272
+ return dst;
1273
+ }
1274
+ async function restoreParkedWallet(dir, archivedPath) {
1275
+ await link(archivedPath, walletPath(dir));
1276
+ await unlink2(archivedPath).catch(() => void 0);
1277
+ await syncWalletDir(dir);
1278
+ }
1279
+ async function syncWalletDir(dir) {
1280
+ if (isWindows) return;
1281
+ await fsyncDir(dir);
1094
1282
  }
1095
1283
  async function loadCredential(deps) {
1096
1284
  const envKey = deps.env.TENJIN_WALLET_KEY;
@@ -1113,18 +1301,32 @@ async function accountForSigning(cred, deps) {
1113
1301
  if (cred.source === "env") return accountFromKey(cred.key, "env");
1114
1302
  const cached = signerCache.get(cred.keystore.id);
1115
1303
  if (cached !== void 0) return cached;
1116
- const { passphrase } = await resolvePassphrase({
1117
- env: deps.env,
1118
- dir: deps.dir,
1119
- ...deps.passphrase
1120
- });
1304
+ const resolved = await resolvePassphrase(
1305
+ {
1306
+ env: deps.env,
1307
+ dir: deps.dir,
1308
+ ...deps.passphrase
1309
+ },
1310
+ cred.address
1311
+ );
1121
1312
  let key;
1122
1313
  try {
1123
- const derived = await toKeyAsync(cred.keystore, { password: passphrase });
1314
+ const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1124
1315
  key = decrypt(cred.keystore, derived);
1125
1316
  } catch (err) {
1317
+ if (resolved.migrateLegacy !== void 0) {
1318
+ throw new CliError(
1319
+ "WALLET_INVALID_KEY",
1320
+ 'The legacy shared passphrase entry (service tenjin-cli, account "wallet") does not decrypt this wallet.',
1321
+ {
1322
+ fix: "That entry likely belongs to a different wallet created later and was left untouched. If you know this wallet's passphrase, set TENJIN_WALLET_PASSPHRASE to it (a store-served passphrase is never re-asked at a prompt).",
1323
+ cause: err
1324
+ }
1325
+ );
1326
+ }
1327
+ const escape = resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase" : resolved.source === "prompt" ? "Retry and enter the correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it" : `The OS credential store entry (service tenjin-cli, account ${cred.address.toLowerCase()}) does not decrypt it; set TENJIN_WALLET_PASSPHRASE to the correct passphrase`;
1126
1328
  throw new CliError("WALLET_INVALID_KEY", "Could not decrypt the wallet keystore.", {
1127
- fix: "Check the passphrase: TENJIN_WALLET_PASSPHRASE, the macOS keychain (service tenjin-cli), or the one you enter when prompted.",
1329
+ fix: `${escape}.`,
1128
1330
  cause: err
1129
1331
  });
1130
1332
  }
@@ -1138,6 +1340,7 @@ async function accountForSigning(cred, deps) {
1138
1340
  }
1139
1341
  );
1140
1342
  }
1343
+ if (resolved.migrateLegacy !== void 0) await resolved.migrateLegacy();
1141
1344
  signerCache.set(cred.keystore.id, account);
1142
1345
  return account;
1143
1346
  }
@@ -1155,13 +1358,14 @@ async function encryptToKeystore(key, passphrase) {
1155
1358
  const [derivedKey, opts] = await scryptAsync2({ password: passphrase });
1156
1359
  return encrypt2(key, derivedKey, opts);
1157
1360
  }
1158
- function resolveCredentialOrThrow(cred) {
1159
- if (cred === null) {
1160
- throw new CliError("WALLET_MISSING", "No wallet found.", {
1161
- fix: "Run `tenjin wallet create` to create one."
1162
- });
1163
- }
1164
- return cred;
1361
+ async function credentialOrThrow(deps) {
1362
+ const cred = await loadCredential(deps);
1363
+ if (cred !== null) return cred;
1364
+ const archived = await listArchivedWallets(deps.dir);
1365
+ const hint = archived.length > 0 ? ` Archived wallets exist (${archived.join(", ")}); restore one with \`mv ${archivedWalletPath("<address>", deps.dir)} ${walletPath(deps.dir)}\`.` : "";
1366
+ throw new CliError("WALLET_MISSING", "No wallet found.", {
1367
+ fix: `Run \`tenjin wallet create\` to create one.${hint}`
1368
+ });
1165
1369
  }
1166
1370
  function walletRecord(address, keystore) {
1167
1371
  return {
@@ -1176,7 +1380,6 @@ function walletRecord(address, keystore) {
1176
1380
  // src/lib/wallet/spend.ts
1177
1381
  import { mkdir, readFile as readFile2 } from "fs/promises";
1178
1382
  import { randomUUID } from "crypto";
1179
- import { join } from "path";
1180
1383
  var DEFAULT_WINDOW_MS = 864e5;
1181
1384
  var RESERVATION_TTL_MS = 6e5;
1182
1385
  var ReservationSchema = external_exports.object({
@@ -1196,8 +1399,9 @@ function emptyLedger(nowMs) {
1196
1399
  function createLocalSpendAuthorizer(deps) {
1197
1400
  const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;
1198
1401
  const now = deps.now ?? Date.now;
1199
- const path = join(deps.dir, "session.json");
1402
+ const path = spendLedgerPath(deps.dir);
1200
1403
  const lockPath = `${path}.lock`;
1404
+ let warnedCorrupt = false;
1201
1405
  const freshen = (ledger, nowMs) => {
1202
1406
  if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);
1203
1407
  return {
@@ -1220,7 +1424,12 @@ function createLocalSpendAuthorizer(deps) {
1220
1424
  await mkdir(deps.dir, { recursive: true, mode: 448 });
1221
1425
  return withFileLock(lockPath, async () => {
1222
1426
  const nowMs = now();
1223
- const ledger = freshen(await readLedger(path), nowMs);
1427
+ const read = await readLedger(path);
1428
+ if (read.corrupt !== void 0 && !warnedCorrupt) {
1429
+ warnedCorrupt = true;
1430
+ deps.onCorrupt?.(read.corrupt);
1431
+ }
1432
+ const ledger = freshen(read.ledger, nowMs);
1224
1433
  return fn(ledger, nowMs);
1225
1434
  });
1226
1435
  }
@@ -1281,15 +1490,25 @@ async function readLedger(path) {
1281
1490
  let raw;
1282
1491
  try {
1283
1492
  raw = await readFile2(path, "utf8");
1284
- } catch {
1285
- return null;
1493
+ } catch (err) {
1494
+ if (hasCode(err, "ENOENT")) return { ledger: null };
1495
+ return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };
1286
1496
  }
1497
+ let json;
1287
1498
  try {
1288
- const parsed = LedgerSchema.safeParse(JSON.parse(raw));
1289
- return parsed.success ? parsed.data : null;
1499
+ json = JSON.parse(raw);
1290
1500
  } catch {
1291
- return null;
1501
+ return { ledger: null, corrupt: "not valid JSON" };
1292
1502
  }
1503
+ const parsed = LedgerSchema.safeParse(json);
1504
+ if (parsed.success) return { ledger: parsed.data };
1505
+ const issue = parsed.error.issues[0];
1506
+ const field = issue?.path.join(".");
1507
+ const message = issue?.message ?? "schema mismatch";
1508
+ return {
1509
+ ledger: null,
1510
+ corrupt: field !== void 0 && field.length > 0 ? `${field}: ${message}` : message
1511
+ };
1293
1512
  }
1294
1513
 
1295
1514
  // src/lib/wallet/index.ts
@@ -1303,7 +1522,15 @@ function resolveWalletProvider(ctx, opts = {}) {
1303
1522
  }
1304
1523
  function resolveSpendAuthorizer(ctx, policy, opts = {}) {
1305
1524
  if (opts.authorizer !== void 0) return opts.authorizer;
1306
- return createLocalSpendAuthorizer({ dir: ctx.dataDir, policy });
1525
+ return createLocalSpendAuthorizer({
1526
+ dir: ctx.dataDir,
1527
+ policy,
1528
+ onCorrupt: (reason) => emitNotice(
1529
+ ctx.io,
1530
+ `spend ledger at ${spendLedgerPath(ctx.dataDir)} was unreadable (${reason}); spending window restarted`,
1531
+ { json: ctx.flags.json }
1532
+ )
1533
+ });
1307
1534
  }
1308
1535
  async function describeWallet(provider) {
1309
1536
  try {
@@ -1320,7 +1547,12 @@ async function describeWallet(provider) {
1320
1547
 
1321
1548
  export {
1322
1549
  resolvePassphraseForCreate,
1550
+ prepareLocalWallet,
1551
+ commitLocalWallet,
1323
1552
  createLocalWallet,
1553
+ verifyAndPreserveOutgoingWallet,
1554
+ parkOutgoingWallet,
1555
+ restoreParkedWallet,
1324
1556
  createLocalSpendAuthorizer,
1325
1557
  resolveWalletProvider,
1326
1558
  resolveSpendAuthorizer,
@@ -1331,4 +1563,4 @@ export {
1331
1563
  @noble/ciphers/esm/utils.js:
1332
1564
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1333
1565
  */
1334
- //# sourceMappingURL=chunk-S3KZ3PPK.js.map
1566
+ //# sourceMappingURL=chunk-RGFBBNGP.js.map