tenjin-cli 0.1.0-alpha.8 → 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 (124) hide show
  1. package/README.md +26 -0
  2. package/dist/{buy-K2G6XQY2.js → buy-3PPC2SRQ.js} +23 -21
  3. package/dist/{candidate-DJB2NNTG.js → candidate-FCBWDN4Y.js} +10 -8
  4. package/dist/{chunk-NVHQCTIC.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-DQDGBWWH.js → chunk-6L34JW52.js} +3 -2
  9. package/dist/chunk-6L34JW52.js.map +1 -0
  10. package/dist/{chunk-XFHZWORF.js → chunk-6RODLWPQ.js} +101 -35
  11. package/dist/chunk-6RODLWPQ.js.map +1 -0
  12. package/dist/{chunk-VZ3AJCO5.js → chunk-75G4REUY.js} +2 -2
  13. package/dist/{chunk-C3S6725N.js → chunk-7MJCZ2OX.js} +12 -12
  14. package/dist/{chunk-PCLPVJ3J.js → chunk-7WDY4AXV.js} +15 -15
  15. package/dist/{chunk-RGTTACP3.js → chunk-ATSCQETF.js} +5 -5
  16. package/dist/{chunk-QB2NNV6C.js → chunk-AX5WQ3H5.js} +8 -6
  17. package/dist/{chunk-QB2NNV6C.js.map → chunk-AX5WQ3H5.js.map} +1 -1
  18. package/dist/{chunk-WRWCDLVK.js → chunk-BFAFOBO3.js} +23 -4
  19. package/dist/chunk-BFAFOBO3.js.map +1 -0
  20. package/dist/{chunk-DAJ56EUU.js → chunk-CTFFFQFH.js} +3 -3
  21. package/dist/{chunk-B7YB4MMU.js → chunk-E5PZEPUO.js} +9 -9
  22. package/dist/{chunk-GABYDXWL.js → chunk-FFTWWJRW.js} +21 -5
  23. package/dist/{chunk-GABYDXWL.js.map → chunk-FFTWWJRW.js.map} +1 -1
  24. package/dist/{chunk-6OE2IJMH.js → chunk-G7ECLIN6.js} +22 -22
  25. package/dist/{chunk-CYRYVZPN.js → chunk-GJKDWZ6X.js} +3 -3
  26. package/dist/{chunk-RGFBBNGP.js → chunk-I4WQXOEL.js} +16 -13
  27. package/dist/chunk-I4WQXOEL.js.map +1 -0
  28. package/dist/{chunk-OTDI5FXG.js → chunk-JURZ2T2I.js} +3 -3
  29. package/dist/{chunk-UYP7G3GZ.js → chunk-KRHUDEIQ.js} +10 -172
  30. package/dist/chunk-KRHUDEIQ.js.map +1 -0
  31. package/dist/{chunk-P3FBESBB.js → chunk-MHRREGGN.js} +5 -10
  32. package/dist/chunk-MHRREGGN.js.map +1 -0
  33. package/dist/chunk-OQXHNWM3.js +47 -0
  34. package/dist/chunk-OQXHNWM3.js.map +1 -0
  35. package/dist/chunk-P74I3WH4.js +204 -0
  36. package/dist/chunk-P74I3WH4.js.map +1 -0
  37. package/dist/{chunk-6ZBZCBR7.js → chunk-PT2NJUGG.js} +6 -6
  38. package/dist/{chunk-J6CVKC4M.js → chunk-PZRAAAY2.js} +4 -46
  39. package/dist/chunk-PZRAAAY2.js.map +1 -0
  40. package/dist/{chunk-XBJ3VLWX.js → chunk-PZSUWDF2.js} +2 -2
  41. package/dist/{chunk-BBUYCDSG.js → chunk-R2VLGNFD.js} +7 -2
  42. package/dist/chunk-R2VLGNFD.js.map +1 -0
  43. package/dist/{chunk-ZA3RFDAV.js → chunk-S4IKXAUA.js} +6 -10
  44. package/dist/chunk-S4IKXAUA.js.map +1 -0
  45. package/dist/{chunk-EDENZN2Q.js → chunk-TMZIXYPL.js} +7 -7
  46. package/dist/{chunk-YBMMV4Y4.js → chunk-TYVLXAB5.js} +26 -4
  47. package/dist/chunk-TYVLXAB5.js.map +1 -0
  48. package/dist/{chunk-URSGGRO4.js → chunk-V7BWPOKT.js} +38 -19
  49. package/dist/chunk-V7BWPOKT.js.map +1 -0
  50. package/dist/{chunk-L6AV2Q73.js → chunk-VE5BALOI.js} +5 -5
  51. package/dist/{chunk-GM4RZUVU.js → chunk-WGXUVCUF.js} +8 -6
  52. package/dist/{chunk-GM4RZUVU.js.map → chunk-WGXUVCUF.js.map} +1 -1
  53. package/dist/chunk-X3OOVSPX.js +154 -0
  54. package/dist/chunk-X3OOVSPX.js.map +1 -0
  55. package/dist/{chunk-2YX6LTCD.js → chunk-XDW6GOHO.js} +5 -5
  56. package/dist/{cli-KNCYWMAG.js → cli-ATFP3O6Y.js} +36 -27
  57. package/dist/{cli-KNCYWMAG.js.map → cli-ATFP3O6Y.js.map} +1 -1
  58. package/dist/{config-SAQEQRFB.js → config-VT5WU47R.js} +9 -6
  59. package/dist/doctor-6PEYDTB5.js +24 -0
  60. package/dist/{edit-IZZ2HIMR.js → edit-GKI37CRM.js} +21 -19
  61. package/dist/index.js +1 -1
  62. package/dist/{inspect-BFWZ5XOP.js → inspect-ITZIRZDV.js} +19 -16
  63. package/dist/{install-QXZCHIBT.js → install-BMMUPFOK.js} +217 -118
  64. package/dist/install-BMMUPFOK.js.map +1 -0
  65. package/dist/outcome-F5KN3K3Y.js +23 -0
  66. package/dist/{publish-5NTCRF2V.js → publish-F5G5WIFI.js} +22 -20
  67. package/dist/{read-T6OTMU72.js → read-II2ZO4II.js} +20 -18
  68. package/dist/{read-T6OTMU72.js.map → read-II2ZO4II.js.map} +1 -1
  69. package/dist/{run-5OGX64IY.js → run-FJWMRXZ7.js} +65 -42
  70. package/dist/run-FJWMRXZ7.js.map +1 -0
  71. package/dist/search-Z2YALF6S.js +26 -0
  72. package/dist/{send-ENE47KQE.js → send-RWOBFOBK.js} +20 -18
  73. package/dist/{send-ENE47KQE.js.map → send-RWOBFOBK.js.map} +1 -1
  74. package/dist/{session-HY4QIWHV.js → session-DJV5T3BG.js} +16 -14
  75. package/dist/{session-HY4QIWHV.js.map → session-DJV5T3BG.js.map} +1 -1
  76. package/dist/skill-heal-OK6YALW6.js +85 -0
  77. package/dist/skill-heal-OK6YALW6.js.map +1 -0
  78. package/dist/{wallet-RBDVNZVR.js → wallet-AB4ISFMY.js} +8 -7
  79. package/dist/{wallet-OCCGEH6H.js → wallet-XVRLJZ63.js} +12 -10
  80. package/package.json +2 -1
  81. package/skills/tenjin/SKILL.md +76 -41
  82. package/skills/tenjin-search/SKILL.md +10 -6
  83. package/dist/chunk-BBUYCDSG.js.map +0 -1
  84. package/dist/chunk-DQDGBWWH.js.map +0 -1
  85. package/dist/chunk-J6CVKC4M.js.map +0 -1
  86. package/dist/chunk-NVHQCTIC.js.map +0 -1
  87. package/dist/chunk-P3FBESBB.js.map +0 -1
  88. package/dist/chunk-RGFBBNGP.js.map +0 -1
  89. package/dist/chunk-URSGGRO4.js.map +0 -1
  90. package/dist/chunk-UYP7G3GZ.js.map +0 -1
  91. package/dist/chunk-WRWCDLVK.js.map +0 -1
  92. package/dist/chunk-XFHZWORF.js.map +0 -1
  93. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  94. package/dist/chunk-ZA3RFDAV.js.map +0 -1
  95. package/dist/doctor-FBRQNOUQ.js +0 -22
  96. package/dist/install-QXZCHIBT.js.map +0 -1
  97. package/dist/outcome-VXCBEGNC.js +0 -20
  98. package/dist/run-5OGX64IY.js.map +0 -1
  99. package/dist/search-LIIWUMWV.js +0 -24
  100. /package/dist/{buy-K2G6XQY2.js.map → buy-3PPC2SRQ.js.map} +0 -0
  101. /package/dist/{candidate-DJB2NNTG.js.map → candidate-FCBWDN4Y.js.map} +0 -0
  102. /package/dist/{chunk-VZ3AJCO5.js.map → chunk-75G4REUY.js.map} +0 -0
  103. /package/dist/{chunk-C3S6725N.js.map → chunk-7MJCZ2OX.js.map} +0 -0
  104. /package/dist/{chunk-PCLPVJ3J.js.map → chunk-7WDY4AXV.js.map} +0 -0
  105. /package/dist/{chunk-RGTTACP3.js.map → chunk-ATSCQETF.js.map} +0 -0
  106. /package/dist/{chunk-DAJ56EUU.js.map → chunk-CTFFFQFH.js.map} +0 -0
  107. /package/dist/{chunk-B7YB4MMU.js.map → chunk-E5PZEPUO.js.map} +0 -0
  108. /package/dist/{chunk-6OE2IJMH.js.map → chunk-G7ECLIN6.js.map} +0 -0
  109. /package/dist/{chunk-CYRYVZPN.js.map → chunk-GJKDWZ6X.js.map} +0 -0
  110. /package/dist/{chunk-OTDI5FXG.js.map → chunk-JURZ2T2I.js.map} +0 -0
  111. /package/dist/{chunk-6ZBZCBR7.js.map → chunk-PT2NJUGG.js.map} +0 -0
  112. /package/dist/{chunk-XBJ3VLWX.js.map → chunk-PZSUWDF2.js.map} +0 -0
  113. /package/dist/{chunk-EDENZN2Q.js.map → chunk-TMZIXYPL.js.map} +0 -0
  114. /package/dist/{chunk-L6AV2Q73.js.map → chunk-VE5BALOI.js.map} +0 -0
  115. /package/dist/{chunk-2YX6LTCD.js.map → chunk-XDW6GOHO.js.map} +0 -0
  116. /package/dist/{config-SAQEQRFB.js.map → config-VT5WU47R.js.map} +0 -0
  117. /package/dist/{doctor-FBRQNOUQ.js.map → doctor-6PEYDTB5.js.map} +0 -0
  118. /package/dist/{edit-IZZ2HIMR.js.map → edit-GKI37CRM.js.map} +0 -0
  119. /package/dist/{inspect-BFWZ5XOP.js.map → inspect-ITZIRZDV.js.map} +0 -0
  120. /package/dist/{outcome-VXCBEGNC.js.map → outcome-F5KN3K3Y.js.map} +0 -0
  121. /package/dist/{publish-5NTCRF2V.js.map → publish-F5G5WIFI.js.map} +0 -0
  122. /package/dist/{search-LIIWUMWV.js.map → search-Z2YALF6S.js.map} +0 -0
  123. /package/dist/{wallet-OCCGEH6H.js.map → wallet-AB4ISFMY.js.map} +0 -0
  124. /package/dist/{wallet-RBDVNZVR.js.map → wallet-XVRLJZ63.js.map} +0 -0
@@ -1,18 +1,4 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- a,
4
- c,
5
- h,
6
- i,
7
- i2,
8
- m,
9
- n,
10
- p,
11
- r,
12
- s,
13
- t2 as t,
14
- u
15
- } from "./chunk-YLYINX2H.js";
16
2
  import {
17
3
  AbiDecodingDataSizeTooSmallError,
18
4
  AbiDecodingZeroDataError,
@@ -165,6 +151,20 @@ import {
165
151
  validate2,
166
152
  withResolvers
167
153
  } from "./chunk-KZAAWQNP.js";
154
+ import {
155
+ a,
156
+ c,
157
+ h,
158
+ i,
159
+ i2,
160
+ m,
161
+ n,
162
+ p,
163
+ r,
164
+ s,
165
+ t2 as t,
166
+ u
167
+ } from "./chunk-YLYINX2H.js";
168
168
  import {
169
169
  sha256
170
170
  } from "./chunk-UHTVXQ2O.js";
@@ -14617,4 +14617,4 @@ export {
14617
14617
  SIWX_HEADER,
14618
14618
  buildSiwxHeader
14619
14619
  };
14620
- //# sourceMappingURL=chunk-PCLPVJ3J.js.map
14620
+ //# sourceMappingURL=chunk-7WDY4AXV.js.map
@@ -1,17 +1,17 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  latestSearch
4
- } from "./chunk-OTDI5FXG.js";
4
+ } from "./chunk-JURZ2T2I.js";
5
5
  import {
6
6
  buildOutcomeItem,
7
7
  postOutcomes
8
- } from "./chunk-P3FBESBB.js";
8
+ } from "./chunk-MHRREGGN.js";
9
9
  import {
10
10
  resolveContextSettings
11
- } from "./chunk-DAJ56EUU.js";
11
+ } from "./chunk-CTFFFQFH.js";
12
12
  import {
13
13
  CliError
14
- } from "./chunk-J6CVKC4M.js";
14
+ } from "./chunk-PZRAAAY2.js";
15
15
 
16
16
  // src/commands/outcome.ts
17
17
  async function runOutcome(args, ctx, deps = {}) {
@@ -56,4 +56,4 @@ async function resolveSearchId(args, ctx) {
56
56
  export {
57
57
  runOutcome
58
58
  };
59
- //# sourceMappingURL=chunk-RGTTACP3.js.map
59
+ //# sourceMappingURL=chunk-ATSCQETF.js.map
@@ -1,19 +1,21 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  buildSiwxHeader
4
- } from "./chunk-PCLPVJ3J.js";
4
+ } from "./chunk-7WDY4AXV.js";
5
5
  import {
6
6
  isSessionUsable,
7
7
  loadSessionFile,
8
8
  signWithSession
9
- } from "./chunk-GABYDXWL.js";
9
+ } from "./chunk-FFTWWJRW.js";
10
10
  import {
11
11
  originOf
12
- } from "./chunk-XBJ3VLWX.js";
12
+ } from "./chunk-PZSUWDF2.js";
13
+ import {
14
+ sessionPath
15
+ } from "./chunk-OQXHNWM3.js";
13
16
  import {
14
- sessionPath,
15
17
  writeFileAtomic
16
- } from "./chunk-J6CVKC4M.js";
18
+ } from "./chunk-PZRAAAY2.js";
17
19
 
18
20
  // src/lib/session-key.ts
19
21
  import { webcrypto } from "crypto";
@@ -140,4 +142,4 @@ export {
140
142
  createSessionKeyAuth,
141
143
  createSiwxAuth
142
144
  };
143
- //# sourceMappingURL=chunk-QB2NNV6C.js.map
145
+ //# sourceMappingURL=chunk-AX5WQ3H5.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/session-key.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while `read` can import the present half ALONE and\n * stay structurally unable to open a keystore. Do not move a signer-touching\n * function down into `session-present.ts`: read's import-graph pin is what makes\n * \"read cannot mint and cannot pay\" a property of the code rather than a promise.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: `session start` and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAyEnB,IAAM,mBAAmB;AAEhC,IAAM,iBAAiB,KAAK,KAAK,KAAK;AA0BtC,IAAM,SAAS,UAAU;AAEzB,SAAS,sBAAwD;AAC/D,SAAO,OAAO,YAAY,EAAE,MAAM,SAAS,YAAY,QAAQ,GAAG,MAAM;AAAA,IACtE;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAGA,SAAS,YAAY,OAA2B;AAC9C,SAAO,OAAO,KAAK,KAAK,EAAE,SAAS,WAAW;AAChD;AAGO,SAAS,oBACd,cACA,QACA,OACU;AACV,SAAO;AAAA,IACL,kCAAkC,YAAY;AAAA,IAC9C,0BAA0B,MAAM;AAAA,IAChC,4BAA4B,KAAK;AAAA,EACnC;AACF;A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":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while `read` can import the present half ALONE and\n * stay structurally unable to open a keystore. Do not move a signer-touching\n * function down into `session-present.ts`: read's import-graph pin is what makes\n * \"read cannot mint and cannot pay\" a property of the code rather than a promise.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: `session start` and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === '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YAAY,IAAI;AACjC,UAAI,aAAa,QAAS,QAAO;AACjC,UAAI,aAAa,eAAe;AAC9B,iBAAS;AACT,2BAAmB;AAAA,MACrB;AAGA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAOO,SAAS,eAAe,QAAqC;AAClE,SAAO;AAAA,IACL,MAAM,aAAa;AACjB,YAAM,SAAS,MAAM,gBAAgB,OAAO,QAAQ;AAAA,QAClD,SAAS,OAAO;AAAA,QAChB,SAAS,OAAO;AAAA,MAClB,CAAC;AACD,aAAO,EAAE,kBAAkB,OAAO;AAAA,IACpC;AAAA,IACA,MAAM,QAAQ,MAAM;AAGlB,aAAO,SAAS,wBAAwB,SAAS,mBAAmB,SAAS;AAAA,IAC/E;AAAA,EACF;AACF;","names":[]}
@@ -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,SAAS,iBAAE,QAAQ,CAAC;AACtB,CAAC;AAIM,IAAM,wBAAwB;AAY9B,IAAM,qBAAqB,iBAAE,OAAO;AAAA,EACzC,eAAe,iBAAE,QAAQ,qBAAqB;AAAA,EAC9C,UAAU,iBAAE,QAAQ,OAAO;AAAA,EAC3B,SAAS,iBAAE,OAAO,EAAE,MAAM,YAAY,wCAAwC;AAAA,EAC9E,UAAU;AAAA,EACV,WAAW,iBAAE,OAAO;AACtB,CAAC;AAKD,eAAsB,iBAAiB,KAA+B;AACpE,SAAQ,MAAM,eAAe,GAAG,MAAO;AACzC;AAGA,eAAsB,eAAe,KAAqC;AACxE,MAAI;AACF,YAAQ,MAAM,KAAK,WAAW,GAAG,CAAC,GAAG,OAAO;AAAA,EAC9C,SAAS,KAAK;AACZ,QAAI,WAAW,GAAG,EAAG,QAAO;AAC5B,UAAM;AAAA,EACR;AACF;AAGA,eAAsB,iBAAiB,KAA2C;AAChF,QAAM,OAAO,WAAW,GAAG;AA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,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;AAAA,EACzC,CAAC;AACH;AASA,eAAsB,kBAAkB,KAAa,QAAqC;AACxF,QAAM,YAAY,mBAAmB,MAAM,MAAM;AACjD,QAAM,OAAO,WAAW,GAAG;AAC3B,MAAI;AACF,UAAM,yBAAyB,MAAM,GAAG,KAAK,UAAU,WAAW,MAAM,CAAC,CAAC;AAAA,GAAM;AAAA,MAC9E,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,QAAI,QAAQ,KAAK,QAAQ,EAAG,OAAM,kBAAkB,KAAK,GAAG;AAC5D,UAAM;AAAA,EACR;AACF;AAGA,SAAS,mBAAmB,MAA8B;AACxD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,IAAK,KAAiC;AAK5C,SAAO,OAAO,MAAM,YAAY,OAAO,UAAU,CAAC,KAAK,IAAI,wBAAwB,IAAI;AACzF;AAGA,SAAS,sBAAsB,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";
4
+ } from "./chunk-GJKDWZ6X.js";
5
5
  import {
6
6
  recordSearch
7
- } from "./chunk-OTDI5FXG.js";
7
+ } from "./chunk-JURZ2T2I.js";
8
8
  import {
9
9
  listCandidates
10
- } from "./chunk-VZ3AJCO5.js";
10
+ } from "./chunk-75G4REUY.js";
11
11
  import {
12
12
  MAX_LIMIT,
13
13
  buildSearchRequest,
14
14
  postSearch
15
- } from "./chunk-P3FBESBB.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-B7YB4MMU.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,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,MAAM,SAAS,IAAI,GAAG,KAAK,KAAK,OAAO,KAAK;AAAA,IAC7E;AAAA,EACF;AACA,SAAO,EAAE,MAAM,MAAM,MAAM,OAAO,KAAK;AACzC;AAGA,eAAsB,gBAAgB,KAA0C;AAC9E,QAAM,QAAQ,MAAM,gBAAgB,GAAG;AACvC,MAAI,MAAM,SAAS,KAAM,QAAO,MAAM;AAItC,MAAI,MAAM,SAAS,cAAc;AAC/B,UAAM,IAAI,SAAS,YAAY,uCAAuC,YAAY,GAAG,CAAC,IAAI;AAAA,MACxF,KAAK,6BAA6B,YAAY,GAAG,CAAC;AAAA,MAClD,OAAO,MAAM;AAAA,IACf,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEA,SAAS,UAAU,KAAsB;AACvC,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AASO,SAAS,qBACd,MACA,KACA,UACA,QACS;AACT,MAAI,KAAK,WAAW,OAAQ,QAAO;AACnC,MAAI,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,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,SAAS,QAAQ;AAC7C;AAGO,SAAS,cAAc,MAAsB;AAClD,QAAM,OAAO,WAAW,QAAQ,EAAE,OAAO,MAAM,MAAM,EAAE,OAAO;AAC9D,SAAO,YAAY,K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QAAQ,MAAM,gBAAgB,GAAG;AACvC,MAAI,MAAM,SAAS,KAAM,QAAO,MAAM;AAItC,MAAI,MAAM,SAAS,cAAc;AAC/B,UAAM,IAAI,SAAS,YAAY,uCAAuC,YAAY,GAAG,CAAC,IAAI;AAAA,MACxF,KAAK,6BAA6B,YAAY,GAAG,CAAC;AAAA,MAClD,OAAO,MAAM;AAAA,IACf,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEA,SAAS,UAAU,KAAsB;AACvC,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AASO,SAAS,qBACd,MACA,KACA,UACA,QACS;AACT,MAAI,KAAK,WAAW,OAAQ,QAAO;AACnC,MAAI,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":[]}
@@ -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-ZA3RFDAV.js";
9
+ } from "./chunk-S4IKXAUA.js";
10
10
  import {
11
11
  buildSiwxHeader,
12
12
  createPublicClient,
@@ -15,47 +15,47 @@ import {
15
15
  http,
16
16
  x402HTTPClient,
17
17
  x402Version
18
- } from "./chunk-PCLPVJ3J.js";
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-6OE2IJMH.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