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

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 (126) hide show
  1. package/README.md +158 -236
  2. package/dist/{buy-XVOMNWKN.js → buy-3PPC2SRQ.js} +24 -22
  3. package/dist/{candidate-DJB2NNTG.js → candidate-FCBWDN4Y.js} +10 -8
  4. package/dist/{chunk-PLU3E63S.js → chunk-3MQSXDWS.js} +10 -11
  5. package/dist/chunk-3MQSXDWS.js.map +1 -0
  6. package/dist/{chunk-DH6D6QIO.js → chunk-6DWKU4RH.js} +11 -9
  7. package/dist/{chunk-DH6D6QIO.js.map → chunk-6DWKU4RH.js.map} +1 -1
  8. package/dist/{chunk-WDJTGVKN.js → chunk-6L34JW52.js} +5 -2
  9. package/dist/chunk-6L34JW52.js.map +1 -0
  10. package/dist/{chunk-6S44OLND.js → chunk-6RODLWPQ.js} +101 -36
  11. package/dist/chunk-6RODLWPQ.js.map +1 -0
  12. package/dist/{chunk-VZ3AJCO5.js → chunk-75G4REUY.js} +2 -2
  13. package/dist/{chunk-PIIWLEEG.js → chunk-7MJCZ2OX.js} +12 -12
  14. package/dist/{chunk-2KIDDWQO.js → chunk-ATSCQETF.js} +5 -5
  15. package/dist/{chunk-ZFE7STX7.js → chunk-AX5WQ3H5.js} +7 -5
  16. package/dist/{chunk-ZFE7STX7.js.map → chunk-AX5WQ3H5.js.map} +1 -1
  17. package/dist/{chunk-WRWCDLVK.js → chunk-BFAFOBO3.js} +23 -4
  18. package/dist/chunk-BFAFOBO3.js.map +1 -0
  19. package/dist/{chunk-DAJ56EUU.js → chunk-CTFFFQFH.js} +3 -3
  20. package/dist/{chunk-5X4EBGGU.js → chunk-E5PZEPUO.js} +11 -11
  21. package/dist/{chunk-GABYDXWL.js → chunk-FFTWWJRW.js} +21 -5
  22. package/dist/{chunk-GABYDXWL.js.map → chunk-FFTWWJRW.js.map} +1 -1
  23. package/dist/{chunk-WI5EOAQQ.js → chunk-G7ECLIN6.js} +21 -21
  24. package/dist/{chunk-CYRYVZPN.js → chunk-GJKDWZ6X.js} +3 -3
  25. package/dist/{chunk-RGFBBNGP.js → chunk-I4WQXOEL.js} +16 -13
  26. package/dist/chunk-I4WQXOEL.js.map +1 -0
  27. package/dist/{chunk-OTDI5FXG.js → chunk-JURZ2T2I.js} +3 -3
  28. package/dist/{chunk-UYP7G3GZ.js → chunk-KRHUDEIQ.js} +10 -172
  29. package/dist/chunk-KRHUDEIQ.js.map +1 -0
  30. package/dist/{chunk-2L73UI6T.js → chunk-MHRREGGN.js} +5 -10
  31. package/dist/chunk-MHRREGGN.js.map +1 -0
  32. package/dist/chunk-OQXHNWM3.js +47 -0
  33. package/dist/chunk-OQXHNWM3.js.map +1 -0
  34. package/dist/chunk-P74I3WH4.js +204 -0
  35. package/dist/chunk-P74I3WH4.js.map +1 -0
  36. package/dist/{chunk-ZEWY3RJ3.js → chunk-PT2NJUGG.js} +6 -6
  37. package/dist/{chunk-J6CVKC4M.js → chunk-PZRAAAY2.js} +4 -46
  38. package/dist/chunk-PZRAAAY2.js.map +1 -0
  39. package/dist/{chunk-XBJ3VLWX.js → chunk-PZSUWDF2.js} +2 -2
  40. package/dist/{chunk-BBUYCDSG.js → chunk-R2VLGNFD.js} +7 -2
  41. package/dist/chunk-R2VLGNFD.js.map +1 -0
  42. package/dist/{chunk-KT2DGKFT.js → chunk-S4IKXAUA.js} +5 -9
  43. package/dist/chunk-S4IKXAUA.js.map +1 -0
  44. package/dist/{chunk-E6BNARCS.js → chunk-TMZIXYPL.js} +7 -7
  45. package/dist/{chunk-YBMMV4Y4.js → chunk-TYVLXAB5.js} +26 -4
  46. package/dist/chunk-TYVLXAB5.js.map +1 -0
  47. package/dist/{chunk-GXYNLMUQ.js → chunk-V7BWPOKT.js} +38 -19
  48. package/dist/chunk-V7BWPOKT.js.map +1 -0
  49. package/dist/{chunk-L6AV2Q73.js → chunk-VE5BALOI.js} +5 -5
  50. package/dist/{chunk-GM4RZUVU.js → chunk-WGXUVCUF.js} +8 -6
  51. package/dist/{chunk-GM4RZUVU.js.map → chunk-WGXUVCUF.js.map} +1 -1
  52. package/dist/chunk-X3OOVSPX.js +154 -0
  53. package/dist/chunk-X3OOVSPX.js.map +1 -0
  54. package/dist/{chunk-2YX6LTCD.js → chunk-XDW6GOHO.js} +5 -5
  55. package/dist/{cli-7B2QNJG3.js → cli-ATFP3O6Y.js} +42 -29
  56. package/dist/{cli-7B2QNJG3.js.map → cli-ATFP3O6Y.js.map} +1 -1
  57. package/dist/{config-SAQEQRFB.js → config-VT5WU47R.js} +9 -6
  58. package/dist/dist-U4M6QCKE.js +2842 -0
  59. package/dist/dist-U4M6QCKE.js.map +1 -0
  60. package/dist/doctor-6PEYDTB5.js +24 -0
  61. package/dist/{edit-2QO5GQDU.js → edit-GKI37CRM.js} +21 -19
  62. package/dist/index.js +1 -1
  63. package/dist/{inspect-IPKKQB2S.js → inspect-ITZIRZDV.js} +19 -16
  64. package/dist/install-BMMUPFOK.js +922 -0
  65. package/dist/install-BMMUPFOK.js.map +1 -0
  66. package/dist/outcome-F5KN3K3Y.js +23 -0
  67. package/dist/{publish-7WIFFNFG.js → publish-F5G5WIFI.js} +22 -20
  68. package/dist/{read-5TQR7LCF.js → read-II2ZO4II.js} +21 -19
  69. package/dist/{read-5TQR7LCF.js.map → read-II2ZO4II.js.map} +1 -1
  70. package/dist/{run-NPKIP26Y.js → run-FJWMRXZ7.js} +68 -45
  71. package/dist/run-FJWMRXZ7.js.map +1 -0
  72. package/dist/search-Z2YALF6S.js +26 -0
  73. package/dist/{send-ENE47KQE.js → send-RWOBFOBK.js} +20 -18
  74. package/dist/{send-ENE47KQE.js.map → send-RWOBFOBK.js.map} +1 -1
  75. package/dist/{session-FZU4VFFE.js → session-DJV5T3BG.js} +17 -15
  76. package/dist/{session-FZU4VFFE.js.map → session-DJV5T3BG.js.map} +1 -1
  77. package/dist/skill-heal-OK6YALW6.js +85 -0
  78. package/dist/skill-heal-OK6YALW6.js.map +1 -0
  79. package/dist/{wallet-RBDVNZVR.js → wallet-AB4ISFMY.js} +8 -7
  80. package/dist/{wallet-OCCGEH6H.js → wallet-XVRLJZ63.js} +12 -10
  81. package/docs/agent-permissions.md +255 -0
  82. package/package.json +4 -1
  83. package/skills/tenjin/SKILL.md +126 -47
  84. package/skills/tenjin-search/SKILL.md +10 -6
  85. package/dist/chunk-2L73UI6T.js.map +0 -1
  86. package/dist/chunk-6S44OLND.js.map +0 -1
  87. package/dist/chunk-BBUYCDSG.js.map +0 -1
  88. package/dist/chunk-GXYNLMUQ.js.map +0 -1
  89. package/dist/chunk-J6CVKC4M.js.map +0 -1
  90. package/dist/chunk-KT2DGKFT.js.map +0 -1
  91. package/dist/chunk-PLU3E63S.js.map +0 -1
  92. package/dist/chunk-RGFBBNGP.js.map +0 -1
  93. package/dist/chunk-UYP7G3GZ.js.map +0 -1
  94. package/dist/chunk-WDJTGVKN.js.map +0 -1
  95. package/dist/chunk-WRWCDLVK.js.map +0 -1
  96. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  97. package/dist/doctor-ENJ22XWN.js +0 -22
  98. package/dist/install-7ZIYISQ7.js +0 -589
  99. package/dist/install-7ZIYISQ7.js.map +0 -1
  100. package/dist/outcome-NSDE2KAJ.js +0 -20
  101. package/dist/run-NPKIP26Y.js.map +0 -1
  102. package/dist/search-63ELMRZH.js +0 -24
  103. /package/dist/{buy-XVOMNWKN.js.map → buy-3PPC2SRQ.js.map} +0 -0
  104. /package/dist/{candidate-DJB2NNTG.js.map → candidate-FCBWDN4Y.js.map} +0 -0
  105. /package/dist/{chunk-VZ3AJCO5.js.map → chunk-75G4REUY.js.map} +0 -0
  106. /package/dist/{chunk-PIIWLEEG.js.map → chunk-7MJCZ2OX.js.map} +0 -0
  107. /package/dist/{chunk-2KIDDWQO.js.map → chunk-ATSCQETF.js.map} +0 -0
  108. /package/dist/{chunk-DAJ56EUU.js.map → chunk-CTFFFQFH.js.map} +0 -0
  109. /package/dist/{chunk-5X4EBGGU.js.map → chunk-E5PZEPUO.js.map} +0 -0
  110. /package/dist/{chunk-WI5EOAQQ.js.map → chunk-G7ECLIN6.js.map} +0 -0
  111. /package/dist/{chunk-CYRYVZPN.js.map → chunk-GJKDWZ6X.js.map} +0 -0
  112. /package/dist/{chunk-OTDI5FXG.js.map → chunk-JURZ2T2I.js.map} +0 -0
  113. /package/dist/{chunk-ZEWY3RJ3.js.map → chunk-PT2NJUGG.js.map} +0 -0
  114. /package/dist/{chunk-XBJ3VLWX.js.map → chunk-PZSUWDF2.js.map} +0 -0
  115. /package/dist/{chunk-E6BNARCS.js.map → chunk-TMZIXYPL.js.map} +0 -0
  116. /package/dist/{chunk-L6AV2Q73.js.map → chunk-VE5BALOI.js.map} +0 -0
  117. /package/dist/{chunk-2YX6LTCD.js.map → chunk-XDW6GOHO.js.map} +0 -0
  118. /package/dist/{config-SAQEQRFB.js.map → config-VT5WU47R.js.map} +0 -0
  119. /package/dist/{doctor-ENJ22XWN.js.map → doctor-6PEYDTB5.js.map} +0 -0
  120. /package/dist/{edit-2QO5GQDU.js.map → edit-GKI37CRM.js.map} +0 -0
  121. /package/dist/{inspect-IPKKQB2S.js.map → inspect-ITZIRZDV.js.map} +0 -0
  122. /package/dist/{outcome-NSDE2KAJ.js.map → outcome-F5KN3K3Y.js.map} +0 -0
  123. /package/dist/{publish-7WIFFNFG.js.map → publish-F5G5WIFI.js.map} +0 -0
  124. /package/dist/{search-63ELMRZH.js.map → search-Z2YALF6S.js.map} +0 -0
  125. /package/dist/{wallet-OCCGEH6H.js.map → wallet-AB4ISFMY.js.map} +0 -0
  126. /package/dist/{wallet-RBDVNZVR.js.map → wallet-XVRLJZ63.js.map} +0 -0
@@ -1,13 +1,15 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ walletPath
4
+ } from "./chunk-OQXHNWM3.js";
2
5
  import {
3
6
  hasCode
4
7
  } from "./chunk-2I4QTOLB.js";
5
8
  import {
6
9
  CliError,
7
10
  external_exports,
8
- walletPath,
9
11
  writeFileAtomicExclusive
10
- } from "./chunk-J6CVKC4M.js";
12
+ } from "./chunk-PZRAAAY2.js";
11
13
 
12
14
  // src/lib/wallet/store.ts
13
15
  import { readFile, stat } from "fs/promises";
@@ -25,8 +27,9 @@ var KeystoreV3Schema = external_exports.object({
25
27
  id: external_exports.string(),
26
28
  version: external_exports.literal(3)
27
29
  });
30
+ var WALLET_SCHEMA_VERSION = 2;
28
31
  var WalletRecordSchema = external_exports.object({
29
- schemaVersion: external_exports.literal(2),
32
+ schemaVersion: external_exports.literal(WALLET_SCHEMA_VERSION),
30
33
  provider: external_exports.literal("local"),
31
34
  address: external_exports.string().regex(ADDRESS_RE, "expected a 0x-prefixed 20-byte address"),
32
35
  keystore: KeystoreV3Schema,
@@ -73,6 +76,16 @@ async function readWalletRecord(dir) {
73
76
  }
74
77
  );
75
78
  }
79
+ const newer = newerSchemaVersion(json);
80
+ if (newer !== null) {
81
+ throw new CliError(
82
+ "CONTRACT_MISMATCH",
83
+ `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,
84
+ {
85
+ fix: "Upgrade with `npm i -g tenjin-cli`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds."
86
+ }
87
+ );
88
+ }
76
89
  const parsed = WalletRecordSchema.safeParse(json);
77
90
  if (!parsed.success) {
78
91
  throw new CliError(
@@ -107,6 +120,11 @@ async function writeWalletRecord(dir, record) {
107
120
  throw err;
108
121
  }
109
122
  }
123
+ function newerSchemaVersion(json) {
124
+ if (typeof json !== "object" || json === null) return null;
125
+ const v = json.schemaVersion;
126
+ return typeof v === "number" && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;
127
+ }
110
128
  function isPreEncryptionRecord(json) {
111
129
  if (typeof json !== "object" || json === null) return false;
112
130
  const rec = json;
@@ -118,10 +136,11 @@ function isNotFound(err) {
118
136
 
119
137
  export {
120
138
  PRIVATE_KEY_RE,
139
+ WALLET_SCHEMA_VERSION,
121
140
  walletFileExists,
122
141
  walletFileMode,
123
142
  readWalletRecord,
124
143
  walletExistsError,
125
144
  writeWalletRecord
126
145
  };
127
- //# sourceMappingURL=chunk-WRWCDLVK.js.map
146
+ //# sourceMappingURL=chunk-BFAFOBO3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/wallet/store.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport * as Keystore from 'ox/Keystore';\nimport { CliError } from '../errors';\nimport { writeFileAtomicExclusive } from '../atomic-json';\nimport { hasCode } from '../errno';\nimport { walletPath } from '../paths';\n\n/** A 0x-prefixed 32-byte hex private key (case-insensitive). */\nexport const PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * The at-rest shape of a Keystore v3 document (Web3 Secret Storage). Validated\n * structurally on read so an obviously-corrupt keystore fails as\n * WALLET_INVALID_KEY before we ever ask for a passphrase; the real integrity\n * check is the keystore's own MAC, verified by ox at decrypt time. `kdfparams`\n * stays an open object because scrypt and pbkdf2 carry different fields and only\n * ox needs to interpret them.\n */\nconst KeystoreV3Schema = z.object({\n crypto: z.object({\n cipher: z.literal('aes-128-ctr'),\n ciphertext: z.string(),\n cipherparams: z.object({ iv: z.string() }),\n kdf: z.enum(['scrypt', 'pbkdf2']),\n kdfparams: z.record(z.string(), z.unknown()),\n mac: z.string(),\n }),\n id: z.string(),\n version: z.literal(3),\n});\n\n/** The wallet-record schema this build writes and reads. Anything higher on disk\n * was written by a newer CLI; see `readWalletRecord`. */\nexport const WALLET_SCHEMA_VERSION = 2;\n\n/**\n * The persisted wallet record (schema v2). The private key is NEVER stored in\n * cleartext: `keystore` is a Keystore v3 document (scrypt + AES-128-CTR) and the\n * key is recovered only by decrypting it with the wallet passphrase. `address`\n * stays top-level in cleartext ON PURPOSE so `show`/`balance`/`doctor` keep\n * working without a passphrase; only signing decrypts. The `provider`\n * discriminator keeps the schema from implying every future wallet embeds a\n * keystore. Validated on read (a corrupt file is WALLET_INVALID_KEY, never a\n * silent partial parse).\n */\nexport const WalletRecordSchema = z.object({\n schemaVersion: z.literal(WALLET_SCHEMA_VERSION),\n provider: z.literal('local'),\n address: z.string().regex(ADDRESS_RE, 'expected a 0x-prefixed 20-byte address'),\n keystore: KeystoreV3Schema,\n createdAt: z.string(),\n});\nexport type WalletRecord = Omit<z.infer<typeof WalletRecordSchema>, 'keystore'> & {\n keystore: Keystore.Keystore;\n};\n\nexport async function walletFileExists(dir: string): Promise<boolean> {\n return (await walletFileMode(dir)) !== null;\n}\n\n/** File permission bits (`mode & 0o777`), or null when the wallet file is absent. */\nexport async function walletFileMode(dir: string): Promise<number | null> {\n try {\n return (await stat(walletPath(dir))).mode & 0o777;\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n}\n\n/** Read + validate the wallet record; null when absent, WALLET_INVALID_KEY when corrupt. */\nexport async function readWalletRecord(dir: string): Promise<WalletRecord | null> {\n const path = walletPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNotFound(err)) return null;\n throw new CliError('WALLET_INVALID_KEY', `Could not read the wallet file at ${path}.`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('WALLET_INVALID_KEY', `The wallet file at ${path} is not valid JSON.`, {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n cause: err,\n });\n }\n // A pre-encryption record (schema v1 stored the raw key). There is no in-place\n // migration: the old key must be swept and a fresh encrypted wallet created.\n if (isPreEncryptionRecord(json)) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} predates encrypted storage.`,\n {\n fix: `Move ${path} aside and run \\`tenjin wallet create\\`; sweep any funds from the old address first.`,\n },\n );\n }\n // A NEWER CLI's record is a downgrade, not a corruption, and must be caught\n // BEFORE the generic parse failure below: that failure says to move the file\n // aside and run `wallet create`, which on a downgrade abandons a funded wallet.\n // CONTRACT_MISMATCH is the API layer's code for a schema version skew.\n const newer = newerSchemaVersion(json);\n if (newer !== null) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,\n {\n fix: 'Upgrade with `npm i -g tenjin-cli`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds.',\n },\n );\n }\n const parsed = WalletRecordSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} is not a valid wallet record.`,\n {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n details: parsed.error.issues,\n },\n );\n }\n return parsed.data as WalletRecord;\n}\n\n/**\n * The one WALLET_EXISTS error, shared by the create pre-check and the exclusive\n * write's race loser so the two surfaces can never drift apart.\n */\nexport function walletExistsError(dir: string, cause?: unknown): CliError {\n const path = walletPath(dir);\n return new CliError('WALLET_EXISTS', `A wallet already exists at ${path}.`, {\n fix: `Run \\`tenjin wallet create --replace\\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable — never delete the credential-store entry, or the wallet's funds are stranded.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n/**\n * Persist a validated record at 0600 in a 0700 dir, NO-CLOBBER. The exclusive\n * write — not an earlier existence check — is the authority: two concurrent\n * `create` runs can both pass a pre-check, but only one can win the atomic\n * commit; the loser surfaces as WALLET_EXISTS instead of silently overwriting\n * (and losing) a non-recoverable key.\n */\nexport async function writeWalletRecord(dir: string, record: WalletRecord): Promise<void> {\n const validated = WalletRecordSchema.parse(record);\n const path = walletPath(dir);\n try {\n await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n if (hasCode(err, 'EEXIST')) throw walletExistsError(dir, err);\n throw err;\n }\n}\n\n/** The schema version of a record from a future CLI, or null when this build reads it. */\nfunction newerSchemaVersion(json: unknown): number | null {\n if (typeof json !== 'object' || json === null) return null;\n const v = (json as Record<string, unknown>).schemaVersion;\n // Integral only: `2.5` is not a schema we will ship, and calling it \"from the\n // future\" would send the operator into an upgrade loop. Integrality rather than\n // SAFE integrality, because an absurd-but-whole version is still a version, and\n // the alternative branch tells them to move the wallet aside and recreate it.\n return typeof v === 'number' && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;\n}\n\n/** A cleartext-key record from before encrypted storage: schema v1 or a bare `privateKey`. */\nfunction isPreEncryptionRecord(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) return false;\n const rec = json as Record<string, unknown>;\n return rec.schemaVersion === 1 || 'privateKey' in rec;\n}\n\nfunction isNotFound(err: unknown): boolean {\n return hasCode(err, 'ENOENT');\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AASxB,IAAM,iBAAiB;AAC9B,IAAM,aAAa;AAUnB,IAAM,mBAAmB,iBAAE,OAAO;AAAA,EAChC,QAAQ,iBAAE,OAAO;AAAA,IACf,QAAQ,iBAAE,QAAQ,aAAa;AAAA,IAC/B,YAAY,iBAAE,OAAO;AAAA,IACrB,cAAc,iBAAE,OAAO,EAAE,IAAI,iBAAE,OAAO,EAAE,CAAC;AAAA,IACzC,KAAK,iBAAE,KAAK,CAAC,UAAU,QAAQ,CAAC;AAAA,IAChC,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC;AAAA,IAC3C,KAAK,iBAAE,OAAO;AAAA,EAChB,CAAC;AAAA,EACD,IAAI,iBAAE,OAAO;AAAA,EACb,S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AAsB,MAAwB;AACrD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAM;AACZ,SAAO,IAAI,kBAAkB,KAAK,gBAAgB;AACpD;AAEA,SAAS,WAAW,KAAuB;AACzC,SAAO,QAAQ,KAAK,QAAQ;AAC9B;","names":[]}
@@ -10,11 +10,11 @@ import {
10
10
  resolvePublishDefaultPrice,
11
11
  resolvePublishMode,
12
12
  resolveSettings
13
- } from "./chunk-UYP7G3GZ.js";
13
+ } from "./chunk-KRHUDEIQ.js";
14
14
  import {
15
15
  CliError,
16
16
  external_exports
17
- } from "./chunk-J6CVKC4M.js";
17
+ } from "./chunk-PZRAAAY2.js";
18
18
 
19
19
  // src/lib/settings.ts
20
20
  import { execFile } from "child_process";
@@ -159,4 +159,4 @@ export {
159
159
  loadProjectConfig,
160
160
  pathExists
161
161
  };
162
- //# sourceMappingURL=chunk-DAJ56EUU.js.map
162
+ //# sourceMappingURL=chunk-CTFFFQFH.js.map
@@ -1,31 +1,31 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  assertOnBaseOrigin
4
- } from "./chunk-CYRYVZPN.js";
5
- import {
6
- listCandidates
7
- } from "./chunk-VZ3AJCO5.js";
4
+ } from "./chunk-GJKDWZ6X.js";
8
5
  import {
9
6
  recordSearch
10
- } from "./chunk-OTDI5FXG.js";
7
+ } from "./chunk-JURZ2T2I.js";
8
+ import {
9
+ listCandidates
10
+ } from "./chunk-75G4REUY.js";
11
11
  import {
12
12
  MAX_LIMIT,
13
13
  buildSearchRequest,
14
14
  postSearch
15
- } from "./chunk-2L73UI6T.js";
15
+ } from "./chunk-MHRREGGN.js";
16
16
  import {
17
17
  sanitizeForTerminal
18
- } from "./chunk-BBUYCDSG.js";
18
+ } from "./chunk-R2VLGNFD.js";
19
19
  import {
20
20
  resolveContextSettings
21
- } from "./chunk-DAJ56EUU.js";
21
+ } from "./chunk-CTFFFQFH.js";
22
22
  import {
23
23
  formatUsdDisplay,
24
24
  parseUsdToAtomic
25
- } from "./chunk-UYP7G3GZ.js";
25
+ } from "./chunk-KRHUDEIQ.js";
26
26
  import {
27
27
  CliError
28
- } from "./chunk-J6CVKC4M.js";
28
+ } from "./chunk-PZRAAAY2.js";
29
29
 
30
30
  // src/commands/search.ts
31
31
  async function runSearch(args, ctx, deps = {}) {
@@ -143,4 +143,4 @@ function parseAppliesTo(pairs) {
143
143
  export {
144
144
  runSearch
145
145
  };
146
- //# sourceMappingURL=chunk-5X4EBGGU.js.map
146
+ //# sourceMappingURL=chunk-E5PZEPUO.js.map
@@ -1,12 +1,14 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ sessionPath
4
+ } from "./chunk-OQXHNWM3.js";
2
5
  import {
3
6
  hasCode
4
7
  } from "./chunk-2I4QTOLB.js";
5
8
  import {
6
9
  CliError,
7
- external_exports,
8
- sessionPath
9
- } from "./chunk-J6CVKC4M.js";
10
+ external_exports
11
+ } from "./chunk-PZRAAAY2.js";
10
12
 
11
13
  // src/lib/session-present.ts
12
14
  import { createHash, randomBytes, webcrypto } from "crypto";
@@ -118,6 +120,7 @@ async function signWithSession(file, req, deps = {}) {
118
120
  ...digest !== void 0 ? { "Content-Digest": digest } : {}
119
121
  };
120
122
  }
123
+ var LATER_ADDED_FIELDS = ["origin"];
121
124
  async function readSessionFile(dir) {
122
125
  const path = sessionPath(dir);
123
126
  if (process.platform !== "win32") {
@@ -144,9 +147,13 @@ async function readSessionFile(dir) {
144
147
  }
145
148
  const parsed = SessionFileSchema.safeParse(json);
146
149
  if (!parsed.success) {
147
- const issue = parsed.error.issues[0];
150
+ const issues = parsed.error.issues;
151
+ const legacy = (i) => LATER_ADDED_FIELDS.includes(i.path.join(".")) && !hasPath(json, i.path);
152
+ const issue = issues.find((i) => !legacy(i)) ?? issues[0];
148
153
  const field = issue?.path.join(".");
149
154
  const message = issue?.message ?? "schema mismatch";
155
+ const legacyOnly = issues.length > 0 && issues.every(legacy);
156
+ if (legacyOnly && field !== void 0) return { kind: "outdated", field };
150
157
  return {
151
158
  kind: "corrupt",
152
159
  reason: field !== void 0 && field.length > 0 ? `${field}: ${message}` : message
@@ -154,6 +161,15 @@ async function readSessionFile(dir) {
154
161
  }
155
162
  return { kind: "ok", file: parsed.data };
156
163
  }
164
+ function hasPath(value, path) {
165
+ let cur = value;
166
+ for (const key of path) {
167
+ if (typeof cur !== "object" || cur === null) return false;
168
+ if (!Object.hasOwn(cur, key)) return false;
169
+ cur = cur[key];
170
+ }
171
+ return true;
172
+ }
157
173
  async function loadSessionFile(dir) {
158
174
  const state = await readSessionFile(dir);
159
175
  if (state.kind === "ok") return state.file;
@@ -187,4 +203,4 @@ export {
187
203
  isSessionPresentable,
188
204
  isSessionUsable
189
205
  };
190
- //# sourceMappingURL=chunk-GABYDXWL.js.map
206
+ //# sourceMappingURL=chunk-FFTWWJRW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/session-present.ts"],"sourcesContent":["import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split exists so `tenjin read` can present an owner's session key on a cold\n * 402 while its import graph stays test-pinned clear of the wallet. What that\n * pin establishes is exactly two things: read cannot mint a session, and read\n * cannot pay (a P-256 key cannot produce the secp256k1/EIP-712 signature an\n * EIP-3009 transfer authorization needs). It says nothing about what an\n * already-minted delegation is worth to whoever holds it — see `origin` below,\n * and the tier note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET has no body to cover at all,\n * so content-digest drops out of the covered set. As a union, \"GET with a body\"\n * and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache and run `tenjin session start --scope read`; a write command re-establishes on its own.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends.\n const digest = req.method === 'GET' ? undefined : contentDigest(req.body);\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issue = parsed.error.issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // Field-qualified, because \"expected string, received undefined\" names no\n // field and the migration case (a pre-origin file) is exactly that message.\n // zod never echoes the received VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY,aAAa,iBAAiB;AACnD,SAAS,UAAU,YAAY;AAgCxB,SAAS,eAAe,QAAgB,UAAiC;AAC9E,MAAI,WAAW,SAAU,QAAO;AAChC,SAAO,aAAa,UAAU,WAAW;AAC3C;AAGA,IAAM,cAAc;AAcpB,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AACrB,CAAC,EACA,YAAY;AAGf,IAAM,oBAAoB,iBAAE,OAAO;AAAA;AAAA,EAEjC,SAAS,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAalB,QAAQ,iBAAE,OAAO;AAAA;AAAA,EAEjB,YAAY,iBAAE,OAAO;AAAA;AAAA,EAErB,KAAK,iBAAE,OAAO;AAAA,EACd,OAAO,iBAAE,OAAO;AAAA;AAAA,EAEhB,cAAc,iBAAE,OAAO;AAAA,EACvB,eAAe;AACjB,CAAC;AAmBD,IAAM,SAAS,UAAU;AAMzB,SAAS,SAAS,OAA2B;AAC3C,SAAO,OAAO,KAAK,KAAK,EAAE,S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I,CAAC,eAAe,KAAK,OAAO,QAAQ,EAAG,QAAO;AAClD,QAAM,QAAQ,KAAK,MAAM,KAAK,GAAG;AACjC,MAAI,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACpC,SAAO,MAAM,QAAQ;AACvB;AAGO,SAAS,gBACd,MACA,SACA,KACA,UACA,QACS;AACT,MAAI,KAAK,YAAY,QAAQ,YAAY,EAAG,QAAO;AACnD,SAAO,qBAAqB,MAAM,KAAK,UAAU,MAAM;AACzD;","names":[]}
1
+ {"version":3,"sources":["../src/lib/session-present.ts"],"sourcesContent":["import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split exists so `tenjin read` can present an owner's session key on a cold\n * 402 while its import graph stays test-pinned clear of the wallet. What that\n * pin establishes is exactly two things: read cannot mint a session, and read\n * cannot pay (a P-256 key cannot produce the secp256k1/EIP-712 signature an\n * EIP-3009 transfer authorization needs). It says nothing about what an\n * already-minted delegation is worth to whoever holds it — see `origin` below,\n * and the tier note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET has no body to cover at all,\n * so content-digest drops out of the covered set. As a union, \"GET with a body\"\n * and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache and run `tenjin session start --scope read`; a write command re-establishes on its own.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends.\n const digest = req.method === 'GET' ? undefined : contentDigest(req.body);\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,YAAY,aAAa,iBAAiB;AACnD,SAAS,UAAU,YAAY;AAgCxB,SAAS,eAAe,QAAgB,UAAiC;AAC9E,MAAI,WAAW,SAAU,QAAO;AAChC,SAAO,aAAa,UAAU,WAAW;AAC3C;AAGA,IAAM,cAAc;AAcpB,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iB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AAGO,SAAS,gBACd,MACA,SACA,KACA,UACA,QACS;AACT,MAAI,KAAK,YAAY,QAAQ,YAAY,EAAG,QAAO;AACnD,SAAO,qBAAqB,MAAM,KAAK,UAAU,MAAM;AACzD;","names":[]}
@@ -3,10 +3,10 @@ import {
3
3
  deliverExisting,
4
4
  deliverFresh,
5
5
  parseSectionsBudget
6
- } from "./chunk-L6AV2Q73.js";
6
+ } from "./chunk-VE5BALOI.js";
7
7
  import {
8
8
  fetchRead
9
- } from "./chunk-KT2DGKFT.js";
9
+ } from "./chunk-S4IKXAUA.js";
10
10
  import {
11
11
  buildSiwxHeader,
12
12
  createPublicClient,
@@ -16,46 +16,46 @@ import {
16
16
  x402HTTPClient,
17
17
  x402Version
18
18
  } from "./chunk-7WDY4AXV.js";
19
+ import {
20
+ encodeFunctionData,
21
+ getAddress as getAddress2,
22
+ keccak256,
23
+ maxUint256,
24
+ toBytes,
25
+ toHex
26
+ } from "./chunk-KZAAWQNP.js";
19
27
  import {
20
28
  promptYesNo
21
29
  } from "./chunk-QW2Q2KAH.js";
30
+ import {
31
+ USDC_ADDRESS
32
+ } from "./chunk-MJZZTKCC.js";
22
33
  import {
23
34
  describeWallet,
24
35
  resolveSpendAuthorizer,
25
36
  resolveWalletProvider
26
- } from "./chunk-RGFBBNGP.js";
37
+ } from "./chunk-I4WQXOEL.js";
27
38
  import {
28
39
  findDelivered,
29
40
  findDeliveredByUrl,
30
41
  resolveResourceRef
31
- } from "./chunk-CYRYVZPN.js";
42
+ } from "./chunk-GJKDWZ6X.js";
32
43
  import {
33
44
  findSearchForResource
34
- } from "./chunk-OTDI5FXG.js";
45
+ } from "./chunk-JURZ2T2I.js";
35
46
  import {
36
47
  sanitizeForTerminal
37
- } from "./chunk-BBUYCDSG.js";
38
- import {
39
- encodeFunctionData,
40
- getAddress as getAddress2,
41
- keccak256,
42
- maxUint256,
43
- toBytes,
44
- toHex
45
- } from "./chunk-KZAAWQNP.js";
48
+ } from "./chunk-R2VLGNFD.js";
46
49
  import {
47
50
  resolveContextSettings
48
- } from "./chunk-DAJ56EUU.js";
51
+ } from "./chunk-CTFFFQFH.js";
49
52
  import {
50
53
  parseUsdToAtomic,
51
54
  toMoney
52
- } from "./chunk-UYP7G3GZ.js";
55
+ } from "./chunk-KRHUDEIQ.js";
53
56
  import {
54
57
  CliError
55
- } from "./chunk-J6CVKC4M.js";
56
- import {
57
- USDC_ADDRESS
58
- } from "./chunk-MJZZTKCC.js";
58
+ } from "./chunk-PZRAAAY2.js";
59
59
  import {
60
60
  getAddress
61
61
  } from "./chunk-47PP7TAG.js";
@@ -1354,4 +1354,4 @@ async function confirmSpend(ctx, deps, yes, amountAtomic, creator) {
1354
1354
  export {
1355
1355
  runBuy
1356
1356
  };
1357
- //# sourceMappingURL=chunk-WI5EOAQQ.js.map
1357
+ //# sourceMappingURL=chunk-G7ECLIN6.js.map
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  findStoredCandidate
4
- } from "./chunk-OTDI5FXG.js";
4
+ } from "./chunk-JURZ2T2I.js";
5
5
  import {
6
6
  SLUG_RE,
7
7
  UUID_RE
@@ -10,7 +10,7 @@ import {
10
10
  CliError,
11
11
  external_exports,
12
12
  writeFileAtomic
13
- } from "./chunk-J6CVKC4M.js";
13
+ } from "./chunk-PZRAAAY2.js";
14
14
 
15
15
  // src/lib/library.ts
16
16
  import { createHash } from "crypto";
@@ -210,4 +210,4 @@ export {
210
210
  assertOnBaseOrigin,
211
211
  resolveResourceRef
212
212
  };
213
- //# sourceMappingURL=chunk-CYRYVZPN.js.map
213
+ //# sourceMappingURL=chunk-GJKDWZ6X.js.map
@@ -1,33 +1,36 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  PRIVATE_KEY_RE,
4
+ WALLET_SCHEMA_VERSION,
4
5
  readWalletRecord,
5
6
  walletFileMode,
6
7
  writeWalletRecord
7
- } from "./chunk-WRWCDLVK.js";
8
- import {
9
- hasCode
10
- } from "./chunk-2I4QTOLB.js";
8
+ } from "./chunk-BFAFOBO3.js";
11
9
  import {
12
10
  emitNotice
13
- } from "./chunk-BBUYCDSG.js";
11
+ } from "./chunk-R2VLGNFD.js";
14
12
  import {
15
13
  withFileLock
16
- } from "./chunk-YBMMV4Y4.js";
14
+ } from "./chunk-TYVLXAB5.js";
17
15
  import {
18
16
  evaluateSpendPolicy
19
17
  } from "./chunk-UO22YNY4.js";
20
18
  import {
21
- CliError,
22
19
  archivedWalletPath,
23
- external_exports,
24
- fsyncDir,
25
20
  passphraseBlobPath,
26
21
  passphraseBlobPathFor,
27
22
  spendLedgerPath,
28
- walletPath,
23
+ walletPath
24
+ } from "./chunk-OQXHNWM3.js";
25
+ import {
26
+ hasCode
27
+ } from "./chunk-2I4QTOLB.js";
28
+ import {
29
+ CliError,
30
+ external_exports,
31
+ fsyncDir,
29
32
  writeFileAtomic
30
- } from "./chunk-J6CVKC4M.js";
33
+ } from "./chunk-PZRAAAY2.js";
31
34
  import {
32
35
  hashAuthorization,
33
36
  hashMessage,
@@ -1369,7 +1372,7 @@ async function credentialOrThrow(deps) {
1369
1372
  }
1370
1373
  function walletRecord(address, keystore) {
1371
1374
  return {
1372
- schemaVersion: 2,
1375
+ schemaVersion: WALLET_SCHEMA_VERSION,
1373
1376
  provider: "local",
1374
1377
  address,
1375
1378
  keystore,
@@ -1563,4 +1566,4 @@ export {
1563
1566
  @noble/ciphers/esm/utils.js:
1564
1567
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1565
1568
  */
1566
- //# sourceMappingURL=chunk-RGFBBNGP.js.map
1569
+ //# sourceMappingURL=chunk-I4WQXOEL.js.map