tenjin-cli 0.1.0-alpha.17 → 0.1.0-alpha.18

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 (61) hide show
  1. package/README.md +3 -0
  2. package/dist/chunk-3KKKB2AQ.js +40 -0
  3. package/dist/chunk-3KKKB2AQ.js.map +1 -0
  4. package/dist/{chunk-56MOAIP5.js → chunk-BTX2QE2Y.js} +9 -6
  5. package/dist/chunk-BTX2QE2Y.js.map +1 -0
  6. package/dist/{chunk-2JGT3KDW.js → chunk-EPCOMXLF.js} +2 -2
  7. package/dist/{chunk-O4ZNKFRU.js → chunk-F3FUGWPZ.js} +5 -5
  8. package/dist/{chunk-LJ4DMVFI.js → chunk-FGR734LZ.js} +2 -2
  9. package/dist/{chunk-QDD2RN7G.js → chunk-N44H5TFB.js} +55 -33
  10. package/dist/chunk-N44H5TFB.js.map +1 -0
  11. package/dist/{chunk-5UDD5VSY.js → chunk-NRQMOVKM.js} +2 -2
  12. package/dist/{chunk-5UDD5VSY.js.map → chunk-NRQMOVKM.js.map} +1 -1
  13. package/dist/{chunk-KK4YGYTV.js → chunk-ON6C6WOX.js} +2 -2
  14. package/dist/{chunk-XZOEUYMX.js → chunk-TJMCBIZU.js} +2 -2
  15. package/dist/{chunk-5QHHRMRA.js → chunk-WUHY2AXD.js} +2 -2
  16. package/dist/{chunk-WGQVJM56.js → chunk-YPQSMIDH.js} +2 -2
  17. package/dist/{chunk-MRGADYDD.js → chunk-ZG7SFI34.js} +2 -2
  18. package/dist/{cli-VHYYYYXM.js → cli-MP3RAYHL.js} +19 -19
  19. package/dist/{config-5ADBAAXU.js → config-BJK6U5VY.js} +4 -4
  20. package/dist/{doctor-Q35VQW3S.js → doctor-KJROWE5V.js} +8 -8
  21. package/dist/{fund-GDDPL2BB.js → fund-I5COXPEJ.js} +5 -4
  22. package/dist/{fund-GDDPL2BB.js.map → fund-I5COXPEJ.js.map} +1 -1
  23. package/dist/{hook-command-PBERPRE3.js → hook-command-EJO2564A.js} +77 -19
  24. package/dist/hook-command-EJO2564A.js.map +1 -0
  25. package/dist/index.js +1 -1
  26. package/dist/{install-OKDKGUXM.js → install-NUQLLHS2.js} +6 -6
  27. package/dist/{install-wallet-SI4LZ73K.js → install-wallet-JPFTEC6H.js} +4 -3
  28. package/dist/{install-wallet-SI4LZ73K.js.map → install-wallet-JPFTEC6H.js.map} +1 -1
  29. package/dist/{mcp-XX3WRQEZ.js → mcp-I5XMVE64.js} +19 -8
  30. package/dist/{mcp-XX3WRQEZ.js.map → mcp-I5XMVE64.js.map} +1 -1
  31. package/dist/{pay-3SYKHKWJ.js → pay-WA3JSCNB.js} +10 -5
  32. package/dist/{send-LQRKTEJT.js → send-KVUH5WDO.js} +3 -2
  33. package/dist/{send-LQRKTEJT.js.map → send-KVUH5WDO.js.map} +1 -1
  34. package/dist/{status-line-wiring-L2WYIYBM.js → status-line-wiring-DQZCWIUO.js} +4 -4
  35. package/dist/tenjin-daemon.mjs +1 -1
  36. package/dist/{uninstall-OACH27UV.js → uninstall-SWICHBTF.js} +29 -9
  37. package/dist/uninstall-SWICHBTF.js.map +1 -0
  38. package/dist/{update-4W6EKLGZ.js → update-W572AMXG.js} +3 -3
  39. package/dist/{wallet-BMEXRR3P.js → wallet-L2YLAJFN.js} +4 -3
  40. package/docs/agent-permissions.md +1 -1
  41. package/package.json +1 -1
  42. package/dist/chunk-56MOAIP5.js.map +0 -1
  43. package/dist/chunk-QDD2RN7G.js.map +0 -1
  44. package/dist/hook-command-PBERPRE3.js.map +0 -1
  45. package/dist/uninstall-OACH27UV.js.map +0 -1
  46. /package/dist/{chunk-2JGT3KDW.js.map → chunk-EPCOMXLF.js.map} +0 -0
  47. /package/dist/{chunk-O4ZNKFRU.js.map → chunk-F3FUGWPZ.js.map} +0 -0
  48. /package/dist/{chunk-LJ4DMVFI.js.map → chunk-FGR734LZ.js.map} +0 -0
  49. /package/dist/{chunk-KK4YGYTV.js.map → chunk-ON6C6WOX.js.map} +0 -0
  50. /package/dist/{chunk-XZOEUYMX.js.map → chunk-TJMCBIZU.js.map} +0 -0
  51. /package/dist/{chunk-5QHHRMRA.js.map → chunk-WUHY2AXD.js.map} +0 -0
  52. /package/dist/{chunk-WGQVJM56.js.map → chunk-YPQSMIDH.js.map} +0 -0
  53. /package/dist/{chunk-MRGADYDD.js.map → chunk-ZG7SFI34.js.map} +0 -0
  54. /package/dist/{cli-VHYYYYXM.js.map → cli-MP3RAYHL.js.map} +0 -0
  55. /package/dist/{config-5ADBAAXU.js.map → config-BJK6U5VY.js.map} +0 -0
  56. /package/dist/{doctor-Q35VQW3S.js.map → doctor-KJROWE5V.js.map} +0 -0
  57. /package/dist/{install-OKDKGUXM.js.map → install-NUQLLHS2.js.map} +0 -0
  58. /package/dist/{pay-3SYKHKWJ.js.map → pay-WA3JSCNB.js.map} +0 -0
  59. /package/dist/{status-line-wiring-L2WYIYBM.js.map → status-line-wiring-DQZCWIUO.js.map} +0 -0
  60. /package/dist/{update-4W6EKLGZ.js.map → update-W572AMXG.js.map} +0 -0
  61. /package/dist/{wallet-BMEXRR3P.js.map → wallet-L2YLAJFN.js.map} +0 -0
@@ -3,7 +3,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
3
3
  // package.json
4
4
  var package_default = {
5
5
  name: "tenjin-cli",
6
- version: "0.1.0-alpha.17",
6
+ version: "0.1.0-alpha.18",
7
7
  mcpName: "blog.tenjin/tenjin",
8
8
  type: "module",
9
9
  description: "x402 router for coding agents: one paid decision per lookup, a local wallet that pays each provider per call in USDC on Base.",
@@ -80,4 +80,4 @@ var package_default = {
80
80
  export {
81
81
  package_default
82
82
  };
83
- //# sourceMappingURL=chunk-5UDD5VSY.js.map
83
+ //# sourceMappingURL=chunk-NRQMOVKM.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.17\",\n \"mcpName\": \"blog.tenjin/tenjin\",\n \"type\": \"module\",\n \"description\": \"x402 router for coding agents: one paid decision per lookup, a local wallet that pays each provider per call in USDC on Base.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.blog/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"x402\",\n \"usdc\",\n \"base\",\n \"ai-agents\",\n \"agent-payments\",\n \"mcp\",\n \"knowledge-marketplace\",\n \"micropayments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=24\"\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"rm -rf dist && tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"sync:skill\": \"node scripts/sync-skill.mjs\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"githooks\": \"git config core.hooksPath .githooks\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.31.1\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.29.0\",\n \"@types/node\": \"^25\",\n \"@x402/core\": \"2.17.0\",\n \"@x402/evm\": \"2.17.0\",\n \"@x402/extensions\": \"2.17.0\",\n \"ajv\": \"^8.20.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\n \"viem\": \"^2.53.1\",\n \"vitest\": \"^4.1.9\",\n \"zod\": \"^4.4.3\"\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,EACR,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,gBAAkB;AAAA,EAClB,SAAW;AAAA,IACT,OAAS;AAAA,IACT,MAAQ;AAAA,IACR,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,OAAS;AAAA,IACT,cAAc;AAAA,IACd,cAAc;AAAA,IACd,WAAa;AAAA,IACb,gBAAkB;AAAA,IAClB,UAAY;AAAA,EACd;AAAA,EACA,iBAAmB;AAAA,IACjB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,6BAA6B;AAAA,IAC7B,eAAe;AAAA,IACf,cAAc;AAAA,IACd,aAAa;AAAA,IACb,oBAAoB;AAAA,IACpB,KAAO;AAAA,IACP,eAAe;AAAA,IACf,WAAa;AAAA,IACb,QAAU;AAAA,IACV,0BAA0B;AAAA,IAC1B,IAAM;AAAA,IACN,UAAY;AAAA,IACZ,MAAQ;AAAA,IACR,YAAc;AAAA,IACd,qBAAqB;AAAA,IACrB,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,KAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.18\",\n \"mcpName\": \"blog.tenjin/tenjin\",\n \"type\": \"module\",\n \"description\": \"x402 router for coding agents: one paid decision per lookup, a local wallet that pays each provider per call in USDC on Base.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.blog/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"x402\",\n \"usdc\",\n \"base\",\n \"ai-agents\",\n \"agent-payments\",\n \"mcp\",\n \"knowledge-marketplace\",\n \"micropayments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=24\"\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"rm -rf dist && tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"sync:skill\": \"node scripts/sync-skill.mjs\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"githooks\": \"git config core.hooksPath .githooks\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.31.1\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.29.0\",\n \"@types/node\": \"^25\",\n \"@x402/core\": \"2.17.0\",\n \"@x402/evm\": \"2.17.0\",\n \"@x402/extensions\": \"2.17.0\",\n \"ajv\": \"^8.20.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\n \"viem\": \"^2.53.1\",\n \"vitest\": \"^4.1.9\",\n \"zod\": \"^4.4.3\"\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,EACR,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,gBAAkB;AAAA,EAClB,SAAW;AAAA,IACT,OAAS;AAAA,IACT,MAAQ;AAAA,IACR,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,OAAS;AAAA,IACT,cAAc;AAAA,IACd,cAAc;AAAA,IACd,WAAa;AAAA,IACb,gBAAkB;AAAA,IAClB,UAAY;AAAA,EACd;AAAA,EACA,iBAAmB;AAAA,IACjB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,6BAA6B;AAAA,IAC7B,eAAe;AAAA,IACf,cAAc;AAAA,IACd,aAAa;AAAA,IACb,oBAAoB;AAAA,IACpB,KAAO;AAAA,IACP,eAAe;AAAA,IACf,WAAa;AAAA,IACb,QAAU;AAAA,IACV,0BAA0B;AAAA,IAC1B,IAAM;AAAA,IACN,UAAY;AAAA,IACZ,MAAQ;AAAA,IACR,YAAc;AAAA,IACd,qBAAqB;AAAA,IACrB,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,KAAO;AAAA,EACT;AACF;","names":[]}
@@ -56,7 +56,7 @@ import {
56
56
  registeredHooks,
57
57
  retractModeGatedRules,
58
58
  wireFreeVerbAllowlist
59
- } from "./chunk-XZOEUYMX.js";
59
+ } from "./chunk-TJMCBIZU.js";
60
60
  import {
61
61
  CliError,
62
62
  writeFileAtomic
@@ -805,4 +805,4 @@ export {
805
805
  persistInstallHarness,
806
806
  persistGrantDeclined
807
807
  };
808
- //# sourceMappingURL=chunk-KK4YGYTV.js.map
808
+ //# sourceMappingURL=chunk-ON6C6WOX.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
  package_default
4
- } from "./chunk-5UDD5VSY.js";
4
+ } from "./chunk-NRQMOVKM.js";
5
5
  import {
6
6
  CliError,
7
7
  HARNESSES,
@@ -1781,4 +1781,4 @@ export {
1781
1781
  registeredHooks,
1782
1782
  writeHooks
1783
1783
  };
1784
- //# sourceMappingURL=chunk-XZOEUYMX.js.map
1784
+ //# sourceMappingURL=chunk-TJMCBIZU.js.map
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-AR7U7BRG.js";
5
5
  import {
6
6
  package_default
7
- } from "./chunk-5UDD5VSY.js";
7
+ } from "./chunk-NRQMOVKM.js";
8
8
  import {
9
9
  CliError
10
10
  } from "./chunk-JLEF5WHM.js";
@@ -224,4 +224,4 @@ export {
224
224
  httpRequest,
225
225
  fetchFailureToCliError
226
226
  };
227
- //# sourceMappingURL=chunk-5QHHRMRA.js.map
227
+ //# sourceMappingURL=chunk-WUHY2AXD.js.map
@@ -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  fetchFailureToCliError,
4
4
  httpRequest
5
- } from "./chunk-5QHHRMRA.js";
5
+ } from "./chunk-WUHY2AXD.js";
6
6
  import {
7
7
  external_exports
8
8
  } from "./chunk-AR7U7BRG.js";
@@ -162,4 +162,4 @@ export {
162
162
  ROUTER_PATH,
163
163
  requestDecision
164
164
  };
165
- //# sourceMappingURL=chunk-WGQVJM56.js.map
165
+ //# sourceMappingURL=chunk-YPQSMIDH.js.map
@@ -8,7 +8,7 @@ import {
8
8
  } from "./chunk-AR7U7BRG.js";
9
9
  import {
10
10
  package_default
11
- } from "./chunk-5UDD5VSY.js";
11
+ } from "./chunk-NRQMOVKM.js";
12
12
  import {
13
13
  writeFileAtomic
14
14
  } from "./chunk-JLEF5WHM.js";
@@ -191,4 +191,4 @@ export {
191
191
  fetchDistTags,
192
192
  isNewer
193
193
  };
194
- //# sourceMappingURL=chunk-MRGADYDD.js.map
194
+ //# sourceMappingURL=chunk-ZG7SFI34.js.map
@@ -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  maybeUpdate,
4
4
  readUpdateSignal
5
- } from "./chunk-MRGADYDD.js";
5
+ } from "./chunk-ZG7SFI34.js";
6
6
  import {
7
7
  defaultIo,
8
8
  emitFailure,
@@ -16,7 +16,7 @@ import {
16
16
  } from "./chunk-AR7U7BRG.js";
17
17
  import {
18
18
  package_default
19
- } from "./chunk-5UDD5VSY.js";
19
+ } from "./chunk-NRQMOVKM.js";
20
20
  import {
21
21
  CliError
22
22
  } from "./chunk-JLEF5WHM.js";
@@ -3506,8 +3506,8 @@ Learn more:
3506
3506
  ).action(async function() {
3507
3507
  await runCommand("install", this, async (ctx) => {
3508
3508
  const o = this.opts();
3509
- const { runRouterInstall } = await import("./install-OKDKGUXM.js");
3510
- const { statusLineMode } = await import("./status-line-wiring-L2WYIYBM.js");
3509
+ const { runRouterInstall } = await import("./install-NUQLLHS2.js");
3510
+ const { statusLineMode } = await import("./status-line-wiring-DQZCWIUO.js");
3511
3511
  return runRouterInstall(
3512
3512
  {
3513
3513
  ...o.project === true ? { project: true } : {},
@@ -3524,7 +3524,7 @@ Learn more:
3524
3524
  ).option("--project", "remove from this project's .claude/settings.json").action(async function() {
3525
3525
  await runCommand("uninstall", this, async (ctx) => {
3526
3526
  const o = this.opts();
3527
- const { runRouterUninstall } = await import("./uninstall-OACH27UV.js");
3527
+ const { runRouterUninstall } = await import("./uninstall-SWICHBTF.js");
3528
3528
  return runRouterUninstall({ ...o.project === true ? { project: true } : {} }, ctx);
3529
3529
  });
3530
3530
  });
@@ -3540,7 +3540,7 @@ Examples:
3540
3540
  `
3541
3541
  ).action(async function() {
3542
3542
  await runCommand("doctor", this, async (ctx) => {
3543
- const { runRouterDoctor } = await import("./doctor-Q35VQW3S.js");
3543
+ const { runRouterDoctor } = await import("./doctor-KJROWE5V.js");
3544
3544
  return runRouterDoctor(ctx, this.opts().project === true ? { project: true } : {});
3545
3545
  });
3546
3546
  });
@@ -3548,7 +3548,7 @@ Examples:
3548
3548
  "Update tenjin-cli to the newest version npm publishes on the latest tag. It then runs `install --refresh` on the new binary, so every profile on this machine gets the skills and hook scripts of the build that just landed."
3549
3549
  ).option("--check", "report whether a newer version exists without installing it").action(async function() {
3550
3550
  await runCommand("update", this, async (ctx) => {
3551
- const { runUpdate } = await import("./update-4W6EKLGZ.js");
3551
+ const { runUpdate } = await import("./update-W572AMXG.js");
3552
3552
  return runUpdate({ check: this.opts().check === true }, ctx);
3553
3553
  });
3554
3554
  });
@@ -3567,7 +3567,7 @@ Examples:
3567
3567
  );
3568
3568
  config.action(async function() {
3569
3569
  await runCommand("config", this, async (ctx) => {
3570
- const { runConfigList } = await import("./config-5ADBAAXU.js");
3570
+ const { runConfigList } = await import("./config-BJK6U5VY.js");
3571
3571
  return runConfigList(ctx);
3572
3572
  });
3573
3573
  });
@@ -3575,7 +3575,7 @@ Examples:
3575
3575
  "Print one effective config value by key. The effective value is what the command would use, defaults and environment overrides included."
3576
3576
  ).action(async function(key) {
3577
3577
  await runCommand("config.get", this, async (ctx) => {
3578
- const { runConfigGet } = await import("./config-5ADBAAXU.js");
3578
+ const { runConfigGet } = await import("./config-BJK6U5VY.js");
3579
3579
  return runConfigGet({ key }, ctx);
3580
3580
  });
3581
3581
  });
@@ -3587,7 +3587,7 @@ Examples:
3587
3587
  ).option("--local", "with --project, write .tenjin/config.local.json instead, which is yours").action(async function(key, value) {
3588
3588
  const o = this.opts();
3589
3589
  await runCommand("config.set", this, async (ctx) => {
3590
- const { runConfigSet } = await import("./config-5ADBAAXU.js");
3590
+ const { runConfigSet } = await import("./config-BJK6U5VY.js");
3591
3591
  return runConfigSet(
3592
3592
  { key, value, project: o.project === true, local: o.local === true },
3593
3593
  ctx
@@ -3609,7 +3609,7 @@ Examples:
3609
3609
  ).action(async function() {
3610
3610
  await runCommand("wallet.create", this, async (ctx) => {
3611
3611
  const o = this.opts();
3612
- const { runWalletCreate } = await import("./wallet-BMEXRR3P.js");
3612
+ const { runWalletCreate } = await import("./wallet-L2YLAJFN.js");
3613
3613
  return runWalletCreate(ctx, o.replace === true ? { replace: true } : {});
3614
3614
  });
3615
3615
  });
@@ -3617,7 +3617,7 @@ Examples:
3617
3617
  "Print the active wallet address and where its key comes from. The private key is never printed, by any flag."
3618
3618
  ).action(async function() {
3619
3619
  await runCommand("wallet.show", this, async (ctx) => {
3620
- const { runWalletShow } = await import("./wallet-BMEXRR3P.js");
3620
+ const { runWalletShow } = await import("./wallet-L2YLAJFN.js");
3621
3621
  return runWalletShow(ctx);
3622
3622
  });
3623
3623
  });
@@ -3625,7 +3625,7 @@ Examples:
3625
3625
  "Read the wallet USDC balance on Base. It is a chain read: no key is unlocked and nothing is spent."
3626
3626
  ).action(async function() {
3627
3627
  await runCommand("wallet.balance", this, async (ctx) => {
3628
- const { runWalletBalance } = await import("./wallet-BMEXRR3P.js");
3628
+ const { runWalletBalance } = await import("./wallet-L2YLAJFN.js");
3629
3629
  return runWalletBalance(ctx);
3630
3630
  });
3631
3631
  });
@@ -3637,7 +3637,7 @@ Examples:
3637
3637
  ).action(async function(amountUsd) {
3638
3638
  await runCommand("wallet.fund", this, async (ctx) => {
3639
3639
  const o = this.opts();
3640
- const { runFund } = await import("./fund-GDDPL2BB.js");
3640
+ const { runFund } = await import("./fund-I5COXPEJ.js");
3641
3641
  return runFund(ctx, {
3642
3642
  ...amountUsd !== void 0 ? { amountUsd } : {},
3643
3643
  ...o.open === false ? { open: false } : {},
@@ -3656,7 +3656,7 @@ Examples:
3656
3656
  ).action(async function(amount, token, to) {
3657
3657
  await runCommand("wallet.send", this, async (ctx) => {
3658
3658
  const o = this.opts();
3659
- const { runSend } = await import("./send-LQRKTEJT.js");
3659
+ const { runSend } = await import("./send-KVUH5WDO.js");
3660
3660
  return runSend({ amount, token, to, ...o.yes === true ? { yes: true } : {} }, ctx);
3661
3661
  });
3662
3662
  });
@@ -3672,7 +3672,7 @@ Examples:
3672
3672
  ).action(async function(url) {
3673
3673
  await runCommand("pay", this, async (ctx) => {
3674
3674
  const o = this.opts();
3675
- const { runPay } = await import("./pay-3SYKHKWJ.js");
3675
+ const { runPay } = await import("./pay-WA3JSCNB.js");
3676
3676
  return runPay(
3677
3677
  {
3678
3678
  url,
@@ -3705,7 +3705,7 @@ function registerRouter(reg) {
3705
3705
  ]) {
3706
3706
  addGlobalFlags2(hook.command(name)).summary(summary).action(async function() {
3707
3707
  const ctx = buildContext2(this);
3708
- const { runHookCommand } = await import("./hook-command-PBERPRE3.js");
3708
+ const { runHookCommand } = await import("./hook-command-EJO2564A.js");
3709
3709
  await runHookCommand(name, io, {
3710
3710
  dataDir: ctx.dataDir,
3711
3711
  ...ctx.flags.baseUrl !== void 0 ? { baseUrl: ctx.flags.baseUrl } : {}
@@ -3718,7 +3718,7 @@ function registerRouter(reg) {
3718
3718
  "Run the local stdio MCP server that carries the `request` tool: one paid routing decision per lookup, then the provider call, under your local spend policy. It speaks on stdin and stdout and runs until the client disconnects, so it prints no envelope of its own."
3719
3719
  ).action(async function() {
3720
3720
  const ctx = buildContext2(this);
3721
- const { runRouterMcpServer } = await import("./mcp-XX3WRQEZ.js");
3721
+ const { runRouterMcpServer } = await import("./mcp-I5XMVE64.js");
3722
3722
  await runRouterMcpServer({ dataDir: ctx.dataDir, flags: ctx.flags });
3723
3723
  });
3724
3724
  leaf2(INTEGRATION, "status-line", "the live footer, for Claude Code's status line").description(
@@ -3881,4 +3881,4 @@ export {
3881
3881
  buildProgram,
3882
3882
  main
3883
3883
  };
3884
- //# sourceMappingURL=cli-VHYYYYXM.js.map
3884
+ //# sourceMappingURL=cli-MP3RAYHL.js.map
@@ -11,7 +11,7 @@ import {
11
11
  runConfigGet,
12
12
  runConfigList,
13
13
  runConfigSet
14
- } from "./chunk-KK4YGYTV.js";
14
+ } from "./chunk-ON6C6WOX.js";
15
15
  import "./chunk-WXC57XGG.js";
16
16
  import "./chunk-2QYORQBF.js";
17
17
  import "./chunk-MEFB5KHA.js";
@@ -21,8 +21,8 @@ import "./chunk-2I4QTOLB.js";
21
21
  import "./chunk-PDA2BVFY.js";
22
22
  import "./chunk-U2DZISAH.js";
23
23
  import "./chunk-AR7U7BRG.js";
24
- import "./chunk-XZOEUYMX.js";
25
- import "./chunk-5UDD5VSY.js";
24
+ import "./chunk-TJMCBIZU.js";
25
+ import "./chunk-NRQMOVKM.js";
26
26
  import "./chunk-JLEF5WHM.js";
27
27
  import "./chunk-2BKS2FVE.js";
28
28
  import "./chunk-ZXTAQYNA.js";
@@ -39,4 +39,4 @@ export {
39
39
  runConfigList,
40
40
  runConfigSet
41
41
  };
42
- //# sourceMappingURL=config-5ADBAAXU.js.map
42
+ //# sourceMappingURL=config-BJK6U5VY.js.map
@@ -4,10 +4,10 @@ import {
4
4
  } from "./chunk-S2NRVRPF.js";
5
5
  import {
6
6
  ROUTER_PATH
7
- } from "./chunk-WGQVJM56.js";
7
+ } from "./chunk-YPQSMIDH.js";
8
8
  import {
9
9
  httpRequest
10
- } from "./chunk-5QHHRMRA.js";
10
+ } from "./chunk-WUHY2AXD.js";
11
11
  import {
12
12
  describeWallet,
13
13
  resolveWalletProvider,
@@ -28,13 +28,13 @@ import {
28
28
  readMcpEntry,
29
29
  routerHookPlan,
30
30
  routerSettingsPath
31
- } from "./chunk-O4ZNKFRU.js";
31
+ } from "./chunk-F3FUGWPZ.js";
32
32
  import {
33
33
  MCP_SERVER_NAME,
34
34
  REQUEST_TOOL
35
35
  } from "./chunk-TGLKKLQG.js";
36
36
  import "./chunk-WLMJE3GJ.js";
37
- import "./chunk-KK4YGYTV.js";
37
+ import "./chunk-ON6C6WOX.js";
38
38
  import "./chunk-WXC57XGG.js";
39
39
  import "./chunk-2QYORQBF.js";
40
40
  import "./chunk-MEFB5KHA.js";
@@ -57,13 +57,13 @@ import {
57
57
  import {
58
58
  STATUS_LINE_COMMAND,
59
59
  inspectStatusLine
60
- } from "./chunk-2JGT3KDW.js";
60
+ } from "./chunk-EPCOMXLF.js";
61
61
  import {
62
62
  inspectHooksFile,
63
63
  ownsHookEntry,
64
64
  pruneOurHandlers
65
- } from "./chunk-XZOEUYMX.js";
66
- import "./chunk-5UDD5VSY.js";
65
+ } from "./chunk-TJMCBIZU.js";
66
+ import "./chunk-NRQMOVKM.js";
67
67
  import {
68
68
  CliError
69
69
  } from "./chunk-JLEF5WHM.js";
@@ -433,4 +433,4 @@ async function routerCheck(baseUrl, timeoutMs, fetchImpl) {
433
433
  export {
434
434
  runRouterDoctor
435
435
  };
436
- //# sourceMappingURL=doctor-Q35VQW3S.js.map
436
+ //# sourceMappingURL=doctor-KJROWE5V.js.map
@@ -6,14 +6,15 @@ import {
6
6
  import {
7
7
  fetchFailureToCliError,
8
8
  httpRequest
9
- } from "./chunk-5QHHRMRA.js";
9
+ } from "./chunk-WUHY2AXD.js";
10
10
  import "./chunk-TTNESUPQ.js";
11
11
  import "./chunk-HPWO4O6S.js";
12
12
  import "./chunk-POUWHWID.js";
13
13
  import "./chunk-XZKD7DIF.js";
14
14
  import {
15
15
  getUsdcBalance
16
- } from "./chunk-56MOAIP5.js";
16
+ } from "./chunk-BTX2QE2Y.js";
17
+ import "./chunk-3KKKB2AQ.js";
17
18
  import {
18
19
  describeWallet,
19
20
  resolveWalletProvider
@@ -46,7 +47,7 @@ import {
46
47
  loadRawConfig,
47
48
  resolveSettings
48
49
  } from "./chunk-AR7U7BRG.js";
49
- import "./chunk-5UDD5VSY.js";
50
+ import "./chunk-NRQMOVKM.js";
50
51
  import {
51
52
  CliError
52
53
  } from "./chunk-JLEF5WHM.js";
@@ -294,4 +295,4 @@ async function pollForFunds(ctx, desc, rpcUrl, startBalance, opts) {
294
295
  export {
295
296
  runFund
296
297
  };
297
- //# sourceMappingURL=fund-GDDPL2BB.js.map
298
+ //# sourceMappingURL=fund-I5COXPEJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.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 a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\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: the read path 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","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 earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * 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 or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; 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 (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\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. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\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","import { execFile } from 'node:child_process';\n\n/**\n * Open a URL in the platform's default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: 'open', args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n return { cmd: 'xdg-open', args: [] };\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const { cmd, args } = openerFor(opts.platform ?? process.platform);\n const run = opts.execFileImpl ?? execFile;\n return await new Promise((resolve) => {\n run(cmd, [...args, url], { timeout: OPEN_TIMEOUT_MS, windowsHide: true }, (err) =>\n resolve(err === null),\n );\n });\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: card-fund THIS wallet via Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend to mint a\n * Coinbase-hosted checkout URL for that same address (the server refuses any\n * other address, per Coinbase's onboarding-verified auth model). The money\n * moves entirely on Coinbase's side; the minted session grants no spending\n * power over the wallet. Two Coinbase properties shape the UX here: the URL is\n * single-use and expires in ~5 minutes (mint fresh per run, open immediately,\n * never persist), and it is bound to this machine's public IP at mint time, so\n * it must be opened in a browser on this machine/network.\n */\n\n/** The only host a minted checkout URL may point at; anything else is refused unopened. */\nconst CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/** Matches the server's presetAmount bound (app/api/cdp/session bodySchema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n mode: 'onramp',\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/cdp/session`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.',\n );\n\n let opened = false;\n if (opts.open !== false && ctx.io.isTTY) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on Coinbase's\n * checkout host before anything else sees it: a compromised or misconfigured\n * server must not be able to steer the user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && parsed.protocol === 'https:' && parsed.host === CHECKOUT_HOST) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,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;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AQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,OAAQ,IAA2B;AACzC,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAEA,eAAe,mBACb,MACA,QAC6B;AAC7B,MAAI;AACF,WAAO,MAAM,eAAe,KAAK,SAA0B,MAAM;AAAA,EACnE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASA,eAAe,aACb,KACA,MACA,QACA,cACA,MAC6B;AAC7B,QAAM,QACJ,KAAK,UAAU,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACvF,QAAM,WAAW,KAAK,kBAAkB;AACxC,QAAM,WAAW,KAAK,IAAI,KAAK,KAAK,iBAAiB;AACrD,aAAW,IAAI,IAAI,yEAAyE;AAAA,IAC1F,MAAM,IAAI,MAAM;AAAA,EAClB,CAAC;AACD,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,UAAM,MAAM,QAAQ;AACpB,UAAM,UAAU,MAAM,mBAAmB,MAAM,MAAM;AACrD,QAAI,YAAY,UAAa,UAAU,aAAc,QAAO;AAAA,EAC9D;AACA,SAAO;AACT;","names":["webcrypto","subtle","webcrypto"]}
1
+ {"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.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 a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\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: the read path 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","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 earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * 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 or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; 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 (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\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. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\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","import { execFile } from 'node:child_process';\n\n/**\n * Open a URL in the platform's default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: 'open', args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n return { cmd: 'xdg-open', args: [] };\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const { cmd, args } = openerFor(opts.platform ?? process.platform);\n const run = opts.execFileImpl ?? execFile;\n return await new Promise((resolve) => {\n run(cmd, [...args, url], { timeout: OPEN_TIMEOUT_MS, windowsHide: true }, (err) =>\n resolve(err === null),\n );\n });\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: card-fund THIS wallet via Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend to mint a\n * Coinbase-hosted checkout URL for that same address (the server refuses any\n * other address, per Coinbase's onboarding-verified auth model). The money\n * moves entirely on Coinbase's side; the minted session grants no spending\n * power over the wallet. Two Coinbase properties shape the UX here: the URL is\n * single-use and expires in ~5 minutes (mint fresh per run, open immediately,\n * never persist), and it is bound to this machine's public IP at mint time, so\n * it must be opened in a browser on this machine/network.\n */\n\n/** The only host a minted checkout URL may point at; anything else is refused unopened. */\nconst CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/** Matches the server's presetAmount bound (app/api/cdp/session bodySchema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n mode: 'onramp',\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/cdp/session`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.',\n );\n\n let opened = false;\n if (opts.open !== false && ctx.io.isTTY) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on Coinbase's\n * checkout host before anything else sees it: a compromised or misconfigured\n * server must not be able to steer the user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && parsed.protocol === 'https:' && parsed.host === CHECKOUT_HOST) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,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,YAA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