tenjin-cli 0.1.0-alpha.25 → 0.1.0-alpha.27
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.
- package/README.md +16 -43
- package/dist/{chunk-EOGJKIOG.js → chunk-2TYQD22Q.js} +16 -7
- package/dist/chunk-2TYQD22Q.js.map +1 -0
- package/dist/{chunk-SCAE6PW6.js → chunk-4L7KMA7P.js} +6 -6
- package/dist/{chunk-UDWGT4FX.js → chunk-5FGO6TYT.js} +13 -5
- package/dist/chunk-5FGO6TYT.js.map +1 -0
- package/dist/{chunk-IYLECN4D.js → chunk-5NEHH2E5.js} +3 -3
- package/dist/{chunk-EACMJEF3.js → chunk-64SE3QC5.js} +75 -176
- package/dist/chunk-64SE3QC5.js.map +1 -0
- package/dist/chunk-6ZSGER3A.js +52 -0
- package/dist/chunk-6ZSGER3A.js.map +1 -0
- package/dist/{chunk-QF4SSCQV.js → chunk-AWKQSKUL.js} +4 -3
- package/dist/chunk-AWKQSKUL.js.map +1 -0
- package/dist/chunk-B2L53TMK.js +70 -0
- package/dist/chunk-B2L53TMK.js.map +1 -0
- package/dist/chunk-BOAI23CX.js +222 -0
- package/dist/chunk-BOAI23CX.js.map +1 -0
- package/dist/{chunk-OZ3LWLCI.js → chunk-DATCR7AU.js} +3 -3
- package/dist/{chunk-NTYQHAIM.js → chunk-DSNXKUXI.js} +2 -2
- package/dist/{chunk-HII5HOQV.js → chunk-G4AM2SOL.js} +5 -3
- package/dist/{chunk-HII5HOQV.js.map → chunk-G4AM2SOL.js.map} +1 -1
- package/dist/{chunk-VYONGSMQ.js → chunk-GU4GGKYP.js} +85 -6
- package/dist/chunk-GU4GGKYP.js.map +1 -0
- package/dist/{chunk-YSW57KUT.js → chunk-H2L33M7F.js} +31 -27
- package/dist/chunk-H2L33M7F.js.map +1 -0
- package/dist/{chunk-ODH7UXIS.js → chunk-HC3QEZKT.js} +5 -4
- package/dist/chunk-HC3QEZKT.js.map +1 -0
- package/dist/chunk-MAQUL5BD.js +99 -0
- package/dist/chunk-MAQUL5BD.js.map +1 -0
- package/dist/{chunk-EG7P4SM6.js → chunk-O7CUHHYU.js} +4 -4
- package/dist/{chunk-EG7P4SM6.js.map → chunk-O7CUHHYU.js.map} +1 -1
- package/dist/{chunk-CEMXMUIU.js → chunk-OHZYNZSD.js} +36 -7
- package/dist/chunk-OHZYNZSD.js.map +1 -0
- package/dist/{chunk-3ZYPVSIU.js → chunk-PY7MQUKP.js} +238 -43
- package/dist/chunk-PY7MQUKP.js.map +1 -0
- package/dist/chunk-PZ5N6BAL.js +268 -0
- package/dist/chunk-PZ5N6BAL.js.map +1 -0
- package/dist/chunk-S4SAZ7OD.js +30 -0
- package/dist/chunk-S4SAZ7OD.js.map +1 -0
- package/dist/{chunk-NYPFOHSJ.js → chunk-SKQQOEWH.js} +4 -4
- package/dist/{chunk-XICKN3CH.js → chunk-VIOUZW7Z.js} +2 -46
- package/dist/chunk-VIOUZW7Z.js.map +1 -0
- package/dist/{chunk-YTM7OURD.js → chunk-VNNXAYJE.js} +2 -2
- package/dist/{chunk-CKDD554V.js → chunk-VXIBZ6W5.js} +5 -3
- package/dist/{chunk-CKDD554V.js.map → chunk-VXIBZ6W5.js.map} +1 -1
- package/dist/{chunk-GT6W3VJM.js → chunk-X7I343ZY.js} +3 -53
- package/dist/chunk-X7I343ZY.js.map +1 -0
- package/dist/{chunk-KGTQRJGS.js → chunk-XVYATBKD.js} +5 -10
- package/dist/{chunk-KGTQRJGS.js.map → chunk-XVYATBKD.js.map} +1 -1
- package/dist/{chunk-DRXDTITB.js → chunk-YKM2ZTA2.js} +59 -25
- package/dist/chunk-YKM2ZTA2.js.map +1 -0
- package/dist/{chunk-CP7O6M55.js → chunk-YQOQ6XEI.js} +109 -27
- package/dist/chunk-YQOQ6XEI.js.map +1 -0
- package/dist/{cli-4WMGZPBP.js → cli-6JNIPZQ6.js} +43 -39
- package/dist/{cli-4WMGZPBP.js.map → cli-6JNIPZQ6.js.map} +1 -1
- package/dist/{config-VU6U7QOU.js → config-G75YT6NC.js} +15 -10
- package/dist/{doctor-26JS2SG3.js → doctor-3GMDOW4Y.js} +140 -98
- package/dist/doctor-3GMDOW4Y.js.map +1 -0
- package/dist/env-proxy-XL4P73MZ.js +15 -0
- package/dist/{fund-JJN3FRRF.js → fund-3IPR5YRJ.js} +26 -14
- package/dist/{fund-JJN3FRRF.js.map → fund-3IPR5YRJ.js.map} +1 -1
- package/dist/hook-command-ZXX4FT4N.js +32 -0
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/{install-GXQ33J4G.js → install-6OROTYHZ.js} +20 -14
- package/dist/{install-identity-HFQUXPSI.js → install-identity-PM4AGFFX.js} +7 -6
- package/dist/{install-wallet-27LTEHBI.js → install-wallet-6756NOB5.js} +11 -8
- package/dist/{install-wallet-27LTEHBI.js.map → install-wallet-6756NOB5.js.map} +1 -1
- package/dist/{mcp-AHCZVD2U.js → mcp-33FAAZ7F.js} +723 -123
- package/dist/mcp-33FAAZ7F.js.map +1 -0
- package/dist/{pay-3TCOPGCX.js → pay-XOYR4PCH.js} +14 -12
- package/dist/{payments-H3LSBGSL.js → payments-UTQDBO7H.js} +8 -6
- package/dist/{payments-H3LSBGSL.js.map → payments-UTQDBO7H.js.map} +1 -1
- package/dist/{send-LKCLN5GA.js → send-CVGNOQW3.js} +12 -9
- package/dist/{send-LKCLN5GA.js.map → send-CVGNOQW3.js.map} +1 -1
- package/dist/{status-2FDGI4LQ.js → status-NACN4DGX.js} +10 -7
- package/dist/{status-2FDGI4LQ.js.map → status-NACN4DGX.js.map} +1 -1
- package/dist/{status-line-QKDJYZGV.js → status-line-3IQKGRUH.js} +6 -5
- package/dist/{status-line-QKDJYZGV.js.map → status-line-3IQKGRUH.js.map} +1 -1
- package/dist/{status-line-wiring-ZDBYHNYR.js → status-line-wiring-QXBOOY2T.js} +4 -4
- package/dist/{uninstall-ZXWABDHS.js → uninstall-NYFKSYW4.js} +22 -16
- package/dist/{uninstall-ZXWABDHS.js.map → uninstall-NYFKSYW4.js.map} +1 -1
- package/dist/{update-HEIWVOP5.js → update-RJDA5ZY3.js} +11 -13
- package/dist/update-RJDA5ZY3.js.map +1 -0
- package/dist/{wallet-T7JYWI6O.js → wallet-B3FVHNTS.js} +11 -8
- package/dist/wallet-B3FVHNTS.js.map +1 -0
- package/docs/agent-permissions.md +18 -7
- package/docs/troubleshooting.md +13 -0
- package/package.json +4 -3
- package/dist/chunk-3ZYPVSIU.js.map +0 -1
- package/dist/chunk-CEMXMUIU.js.map +0 -1
- package/dist/chunk-CP7O6M55.js.map +0 -1
- package/dist/chunk-DRXDTITB.js.map +0 -1
- package/dist/chunk-EACMJEF3.js.map +0 -1
- package/dist/chunk-EOGJKIOG.js.map +0 -1
- package/dist/chunk-GT6W3VJM.js.map +0 -1
- package/dist/chunk-ODH7UXIS.js.map +0 -1
- package/dist/chunk-QF4SSCQV.js.map +0 -1
- package/dist/chunk-UDWGT4FX.js.map +0 -1
- package/dist/chunk-VYONGSMQ.js.map +0 -1
- package/dist/chunk-XICKN3CH.js.map +0 -1
- package/dist/chunk-YSW57KUT.js.map +0 -1
- package/dist/doctor-26JS2SG3.js.map +0 -1
- package/dist/hook-command-S2V4UNB3.js +0 -28
- package/dist/mcp-AHCZVD2U.js.map +0 -1
- package/dist/update-HEIWVOP5.js.map +0 -1
- /package/dist/{chunk-SCAE6PW6.js.map → chunk-4L7KMA7P.js.map} +0 -0
- /package/dist/{chunk-IYLECN4D.js.map → chunk-5NEHH2E5.js.map} +0 -0
- /package/dist/{chunk-OZ3LWLCI.js.map → chunk-DATCR7AU.js.map} +0 -0
- /package/dist/{chunk-NTYQHAIM.js.map → chunk-DSNXKUXI.js.map} +0 -0
- /package/dist/{chunk-NYPFOHSJ.js.map → chunk-SKQQOEWH.js.map} +0 -0
- /package/dist/{chunk-YTM7OURD.js.map → chunk-VNNXAYJE.js.map} +0 -0
- /package/dist/{config-VU6U7QOU.js.map → config-G75YT6NC.js.map} +0 -0
- /package/dist/{hook-command-S2V4UNB3.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
- /package/dist/{install-GXQ33J4G.js.map → hook-command-ZXX4FT4N.js.map} +0 -0
- /package/dist/{install-identity-HFQUXPSI.js.map → install-6OROTYHZ.js.map} +0 -0
- /package/dist/{pay-3TCOPGCX.js.map → install-identity-PM4AGFFX.js.map} +0 -0
- /package/dist/{status-line-wiring-ZDBYHNYR.js.map → pay-XOYR4PCH.js.map} +0 -0
- /package/dist/{wallet-T7JYWI6O.js.map → status-line-wiring-QXBOOY2T.js.map} +0 -0
|
@@ -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.sh/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.sh/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;AAAA;AAAA;AAAA;AAAA;AAAA,EAalB,QAAQ,iBAAE,OAAO;AAAA;AAAA,EAEjB,YAAY,iBAAE,OAAO;AAAA;AAAA,EAErB,KAAK,iBAAE,OAAO;AAAA,EACd,OAAO,iBAAE,OAAO;AAAA;AAAA,EAEhB,cAAc,iBAAE,OAAO;AAAA,EACvB,eAAe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AA,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.sh/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.sh/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 { addressQrLines } from '../lib/qr';\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 /** `--no-qr`: skip the QR block a TTY otherwise gets for sending USDC from a phone. */\n qr?: 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 // Human mode only, and before the wait: the poll below also sees USDC sent\n // straight to the address, so a phone wallet is a second way to finish.\n const qrLines =\n opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(address, ctx.io.stderr)\n : [];\n if (qrLines.length > 0) {\n ctx.io.stderr.write(\n [`Or send USDC from a phone wallet to ${address}:`, ...qrLines].join('\\n') + '\\n',\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;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to","subtle","webcrypto"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
STDIN_TIMEOUT_MS,
|
|
4
|
+
runHookCommand,
|
|
5
|
+
runHookKind
|
|
6
|
+
} from "./chunk-YQOQ6XEI.js";
|
|
7
|
+
import "./chunk-LAIZ2AQA.js";
|
|
8
|
+
import "./chunk-BOAI23CX.js";
|
|
9
|
+
import "./chunk-64SE3QC5.js";
|
|
10
|
+
import "./chunk-X7I343ZY.js";
|
|
11
|
+
import "./chunk-7QKHZQKW.js";
|
|
12
|
+
import "./chunk-AWKQSKUL.js";
|
|
13
|
+
import "./chunk-S4SAZ7OD.js";
|
|
14
|
+
import "./chunk-OHZYNZSD.js";
|
|
15
|
+
import "./chunk-GU4GGKYP.js";
|
|
16
|
+
import "./chunk-TGLKKLQG.js";
|
|
17
|
+
import "./chunk-B2L53TMK.js";
|
|
18
|
+
import "./chunk-DATCR7AU.js";
|
|
19
|
+
import "./chunk-HC3QEZKT.js";
|
|
20
|
+
import "./chunk-2I4QTOLB.js";
|
|
21
|
+
import "./chunk-G4AM2SOL.js";
|
|
22
|
+
import "./chunk-6ZSGER3A.js";
|
|
23
|
+
import "./chunk-VIOUZW7Z.js";
|
|
24
|
+
import "./chunk-JLEF5WHM.js";
|
|
25
|
+
import "./chunk-K6AXXYCG.js";
|
|
26
|
+
import "./chunk-ZXTAQYNA.js";
|
|
27
|
+
export {
|
|
28
|
+
STDIN_TIMEOUT_MS,
|
|
29
|
+
runHookCommand,
|
|
30
|
+
runHookKind
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=hook-command-ZXX4FT4N.js.map
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
3
3
|
|
|
4
4
|
// src/index.ts
|
|
5
|
-
var MIN_NODE_MAJOR =
|
|
5
|
+
var MIN_NODE_MAJOR = 22;
|
|
6
6
|
var nodeMajor = Number.parseInt(process.versions.node.split(".")[0] ?? "", 10);
|
|
7
7
|
if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
|
|
8
8
|
const envelope = {
|
|
@@ -12,7 +12,7 @@ if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
|
|
|
12
12
|
error: {
|
|
13
13
|
code: "NODE_UNSUPPORTED",
|
|
14
14
|
message: `Tenjin CLI requires Node ${MIN_NODE_MAJOR} or newer (found ${process.versions.node}).`,
|
|
15
|
-
fix:
|
|
15
|
+
fix: `Install Node ${MIN_NODE_MAJOR} or newer`
|
|
16
16
|
}
|
|
17
17
|
};
|
|
18
18
|
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
|
|
@@ -22,12 +22,14 @@ if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
|
|
|
22
22
|
process.exit(1);
|
|
23
23
|
}
|
|
24
24
|
if (process.argv.length === 3 && process.argv[2] === "status-line") {
|
|
25
|
-
const { statusLineMain } = await import("./status-line-
|
|
25
|
+
const { statusLineMain } = await import("./status-line-3IQKGRUH.js");
|
|
26
26
|
await statusLineMain();
|
|
27
27
|
process.exit(0);
|
|
28
28
|
}
|
|
29
|
-
var {
|
|
30
|
-
|
|
29
|
+
var { useEnvProxy } = await import("./env-proxy-XL4P73MZ.js");
|
|
30
|
+
useEnvProxy(process.env);
|
|
31
|
+
var { main } = await import("./cli-6JNIPZQ6.js");
|
|
32
|
+
var { enableCliIdentity } = await import("./install-identity-PM4AGFFX.js");
|
|
31
33
|
var { dataDir } = await import("./paths-MUXHUOCM.js");
|
|
32
34
|
enableCliIdentity(dataDir(process.env));
|
|
33
35
|
process.exit(await main(process.argv.slice(2)));
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n// Bin entry. The Node version guard runs BEFORE importing anything else — no\n// static imports above it — so an out-of-support runtime gets one JSON error\n// envelope plus a human stderr line instead of a syntax/parse crash from a\n// lazily-loaded module written in newer syntax. Kept in conservative syntax.\nconst MIN_NODE_MAJOR =
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n// Bin entry. The Node version guard runs BEFORE importing anything else — no\n// static imports above it — so an out-of-support runtime gets one JSON error\n// envelope plus a human stderr line instead of a syntax/parse crash from a\n// lazily-loaded module written in newer syntax. Kept in conservative syntax.\nconst MIN_NODE_MAJOR = 22;\n\nconst nodeMajor = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10);\n\nif (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {\n const envelope = {\n schemaVersion: 1,\n command: 'preflight',\n ok: false,\n error: {\n code: 'NODE_UNSUPPORTED',\n message: `Tenjin CLI requires Node ${MIN_NODE_MAJOR} or newer (found ${process.versions.node}).`,\n fix: `Install Node ${MIN_NODE_MAJOR} or newer`,\n },\n };\n process.stdout.write(`${JSON.stringify(envelope, null, 2)}\\n`);\n process.stderr.write(`error: Node ${MIN_NODE_MAJOR}+ required, found ${process.versions.node}\\n`);\n process.exit(1);\n}\n\n// THE STATUS LINE NEVER LOADS THE CLI. Claude Code runs it once a second for as\n// long as a session is open, and commander, zod and the command tree are parse\n// cost it has no use for. Only the bare invocation is diverted; `--help` and\n// every flag fall through to the command tree, which registers it like any verb.\nif (process.argv.length === 3 && process.argv[2] === 'status-line') {\n const { statusLineMain } = await import('./router/status-line');\n await statusLineMain();\n process.exit(0);\n}\n\n// After the status line, which sends no request: every other process from this\n// bin (the CLI, the hooks, `tenjin mcp`) honours HTTPS_PROXY and NO_PROXY.\nconst { useEnvProxy } = await import('./lib/env-proxy');\nuseEnvProxy(process.env);\n\nconst { main } = await import('./cli');\n// Here and not in `main`, so an in-process test of the command tree sends no\n// telemetry and mints no install id; see lib/install-identity.\nconst { enableCliIdentity } = await import('./lib/install-identity');\nconst { dataDir } = await import('./lib/paths');\nenableCliIdentity(dataDir(process.env));\nprocess.exit(await main(process.argv.slice(2)));\n\n// Marks this file a module so top-level await is legal; emits nothing.\nexport {};\n"],"mappings":";;;;AAKA,IAAM,iBAAiB;AAEvB,IAAM,YAAY,OAAO,SAAS,QAAQ,SAAS,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE;AAE/E,IAAI,OAAO,MAAM,SAAS,KAAK,YAAY,gBAAgB;AACzD,QAAM,WAAW;AAAA,IACf,eAAe;AAAA,IACf,SAAS;AAAA,IACT,IAAI;AAAA,IACJ,OAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,4BAA4B,cAAc,oBAAoB,QAAQ,SAAS,IAAI;AAAA,MAC5F,KAAK,gBAAgB,cAAc;AAAA,IACrC;AAAA,EACF;AACA,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,CAAC;AAAA,CAAI;AAC7D,UAAQ,OAAO,MAAM,eAAe,cAAc,qBAAqB,QAAQ,SAAS,IAAI;AAAA,CAAI;AAChG,UAAQ,KAAK,CAAC;AAChB;AAMA,IAAI,QAAQ,KAAK,WAAW,KAAK,QAAQ,KAAK,CAAC,MAAM,eAAe;AAClE,QAAM,EAAE,eAAe,IAAI,MAAM,OAAO,2BAAsB;AAC9D,QAAM,eAAe;AACrB,UAAQ,KAAK,CAAC;AAChB;AAIA,IAAM,EAAE,YAAY,IAAI,MAAM,OAAO,yBAAiB;AACtD,YAAY,QAAQ,GAAG;AAEvB,IAAM,EAAE,KAAK,IAAI,MAAM,OAAO,mBAAO;AAGrC,IAAM,EAAE,kBAAkB,IAAI,MAAM,OAAO,gCAAwB;AACnE,IAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,qBAAa;AAC9C,kBAAkB,QAAQ,QAAQ,GAAG,CAAC;AACtC,QAAQ,KAAK,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC;","names":[]}
|
|
@@ -18,26 +18,32 @@ import {
|
|
|
18
18
|
routerSettingsPath,
|
|
19
19
|
runRouterInstall,
|
|
20
20
|
statusLineProblems
|
|
21
|
-
} from "./chunk-
|
|
22
|
-
import "./chunk-
|
|
23
|
-
import "./chunk-
|
|
24
|
-
import "./chunk-
|
|
21
|
+
} from "./chunk-PY7MQUKP.js";
|
|
22
|
+
import "./chunk-64SE3QC5.js";
|
|
23
|
+
import "./chunk-MAQUL5BD.js";
|
|
24
|
+
import "./chunk-DSNXKUXI.js";
|
|
25
|
+
import "./chunk-S4SAZ7OD.js";
|
|
26
|
+
import "./chunk-OHZYNZSD.js";
|
|
27
|
+
import "./chunk-H2L33M7F.js";
|
|
28
|
+
import "./chunk-GU4GGKYP.js";
|
|
25
29
|
import "./chunk-A36LQPHV.js";
|
|
26
|
-
import "./chunk-P7LABKCW.js";
|
|
27
|
-
import "./chunk-MEFB5KHA.js";
|
|
28
|
-
import "./chunk-OZ3LWLCI.js";
|
|
29
|
-
import "./chunk-2I4QTOLB.js";
|
|
30
|
-
import "./chunk-HII5HOQV.js";
|
|
31
|
-
import "./chunk-XICKN3CH.js";
|
|
32
|
-
import "./chunk-NTYQHAIM.js";
|
|
33
30
|
import {
|
|
34
31
|
pruneHooks
|
|
35
|
-
} from "./chunk-
|
|
32
|
+
} from "./chunk-XVYATBKD.js";
|
|
36
33
|
import "./chunk-AKWGE6JQ.js";
|
|
37
34
|
import {
|
|
38
35
|
MCP_SERVER_NAME
|
|
39
36
|
} from "./chunk-TGLKKLQG.js";
|
|
40
|
-
import "./chunk-
|
|
37
|
+
import "./chunk-P7LABKCW.js";
|
|
38
|
+
import "./chunk-MEFB5KHA.js";
|
|
39
|
+
import "./chunk-B2L53TMK.js";
|
|
40
|
+
import "./chunk-5FGO6TYT.js";
|
|
41
|
+
import "./chunk-DATCR7AU.js";
|
|
42
|
+
import "./chunk-HC3QEZKT.js";
|
|
43
|
+
import "./chunk-2I4QTOLB.js";
|
|
44
|
+
import "./chunk-G4AM2SOL.js";
|
|
45
|
+
import "./chunk-6ZSGER3A.js";
|
|
46
|
+
import "./chunk-VIOUZW7Z.js";
|
|
41
47
|
import "./chunk-JLEF5WHM.js";
|
|
42
48
|
import "./chunk-K6AXXYCG.js";
|
|
43
49
|
import "./chunk-ZXTAQYNA.js";
|
|
@@ -63,4 +69,4 @@ export {
|
|
|
63
69
|
runRouterInstall,
|
|
64
70
|
statusLineProblems
|
|
65
71
|
};
|
|
66
|
-
//# sourceMappingURL=install-
|
|
72
|
+
//# sourceMappingURL=install-6OROTYHZ.js.map
|
|
@@ -6,12 +6,13 @@ import {
|
|
|
6
6
|
noteBaseUrlFlag,
|
|
7
7
|
readOrCreateInstallId,
|
|
8
8
|
tenjinOrigins
|
|
9
|
-
} from "./chunk-
|
|
10
|
-
import "./chunk-
|
|
9
|
+
} from "./chunk-SKQQOEWH.js";
|
|
10
|
+
import "./chunk-OHZYNZSD.js";
|
|
11
|
+
import "./chunk-HC3QEZKT.js";
|
|
11
12
|
import "./chunk-2I4QTOLB.js";
|
|
12
|
-
import "./chunk-
|
|
13
|
-
import "./chunk-
|
|
14
|
-
import "./chunk-
|
|
13
|
+
import "./chunk-G4AM2SOL.js";
|
|
14
|
+
import "./chunk-6ZSGER3A.js";
|
|
15
|
+
import "./chunk-VIOUZW7Z.js";
|
|
15
16
|
import "./chunk-JLEF5WHM.js";
|
|
16
17
|
import "./chunk-K6AXXYCG.js";
|
|
17
18
|
import "./chunk-ZXTAQYNA.js";
|
|
@@ -23,4 +24,4 @@ export {
|
|
|
23
24
|
readOrCreateInstallId,
|
|
24
25
|
tenjinOrigins
|
|
25
26
|
};
|
|
26
|
-
//# sourceMappingURL=install-identity-
|
|
27
|
+
//# sourceMappingURL=install-identity-PM4AGFFX.js.map
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
runWalletCreate
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import "./chunk-
|
|
4
|
+
} from "./chunk-2TYQD22Q.js";
|
|
5
|
+
import "./chunk-PZ5N6BAL.js";
|
|
6
|
+
import "./chunk-VNNXAYJE.js";
|
|
6
7
|
import {
|
|
7
8
|
describeWallet,
|
|
8
9
|
resolveWalletProvider,
|
|
9
10
|
walletFileExists
|
|
10
|
-
} from "./chunk-
|
|
11
|
-
import "./chunk-
|
|
12
|
-
import "./chunk-
|
|
11
|
+
} from "./chunk-O7CUHHYU.js";
|
|
12
|
+
import "./chunk-VXIBZ6W5.js";
|
|
13
|
+
import "./chunk-X7I343ZY.js";
|
|
13
14
|
import "./chunk-AWQPGIR6.js";
|
|
14
15
|
import "./chunk-N35E6CM2.js";
|
|
15
16
|
import "./chunk-JRGFKVAZ.js";
|
|
@@ -18,13 +19,15 @@ import "./chunk-EGELTSPU.js";
|
|
|
18
19
|
import "./chunk-KG3D7FIF.js";
|
|
19
20
|
import "./chunk-RBJPAZFI.js";
|
|
20
21
|
import "./chunk-BPMWXTFX.js";
|
|
21
|
-
import "./chunk-UDWGT4FX.js";
|
|
22
22
|
import {
|
|
23
23
|
confirmChoice
|
|
24
24
|
} from "./chunk-P7LABKCW.js";
|
|
25
25
|
import "./chunk-MEFB5KHA.js";
|
|
26
|
+
import "./chunk-B2L53TMK.js";
|
|
27
|
+
import "./chunk-5FGO6TYT.js";
|
|
26
28
|
import "./chunk-2I4QTOLB.js";
|
|
27
|
-
import "./chunk-
|
|
29
|
+
import "./chunk-6ZSGER3A.js";
|
|
30
|
+
import "./chunk-VIOUZW7Z.js";
|
|
28
31
|
import {
|
|
29
32
|
CliError
|
|
30
33
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -102,4 +105,4 @@ export {
|
|
|
102
105
|
resolveWallet,
|
|
103
106
|
walletValue
|
|
104
107
|
};
|
|
105
|
-
//# sourceMappingURL=install-wallet-
|
|
108
|
+
//# sourceMappingURL=install-wallet-6756NOB5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/install-wallet.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport { describeWallet, resolveWalletProvider } from '../lib/wallet';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport { walletFileExists } from '../lib/wallet/store';\nimport { runWalletCreate } from './wallet';\nimport type { CommandContext } from '../context';\n\n/**\n * The wallet step `tenjin install` runs: keep the wallet this machine has, or\n * create one. Shared by the router install and the shelf install so the two\n * can never disagree about when a wallet is made or what a skip tells you.\n */\n\n/** The wallet question's literal copy. */\nexport const WALLET_QUESTION = 'Create a wallet now?';\n\n/** The seams the wallet step reads; every one defaults to the real thing. */\nexport interface WalletDeps {\n env?: NodeJS.ProcessEnv;\n /** \"Create a wallet now?\"; defaults to the clack confirm (default yes). */\n confirmWallet?: (label: string) => Promise<boolean>;\n /** Does a wallet already exist? Defaults to walletFileExists(dataDir). */\n walletExists?: (dataDir: string) => Promise<boolean>;\n /** An existing wallet's address. Defaults to the local provider. */\n walletAddress?: (ctx: CommandContext) => Promise<string>;\n /** Create a wallet and return its address. Defaults to runWalletCreate. */\n createWallet?: (ctx: CommandContext) => Promise<string>;\n /**\n * Passphrase-resolution seam forwarded to `wallet create`. Tests MUST set it\n * (or `createWallet`): without it a headless run creates a real wallet, and\n * on macOS that writes to the developer's own login keychain.\n */\n walletPassphrase?: PassphraseOverrides;\n}\n\n/**\n * Why no wallet was created, when none was.\n *\n * `no-passphrase-store` is the one that matters: this machine has no OS\n * credential store that would hold a generated passphrase, and no\n * `TENJIN_WALLET_PASSPHRASE`. There is no fallback here BY DESIGN. A passphrase\n * written to a plain file beside the keystore it unlocks is not a passphrase, so\n * the run creates nothing and says so loudly with both remedies.\n */\nexport type WalletSkipReason = 'no-passphrase-store' | 'create-failed' | 'dry-run' | 'flag';\n\n/**\n * How the wallet step resolved, so rendering stays separate from prompting.\n *\n * `declined` (an answer) and `skipped` (no answer, with a reason) are kept apart\n * deliberately: an install that could not create a key is a different state from\n * one the operator told not to, and only the first needs a remedy.\n */\nexport interface WalletOutcome {\n status: 'existing' | 'created' | 'declined' | 'skipped';\n address?: string;\n /** Only ever set on `skipped`. */\n reason?: WalletSkipReason;\n /** The exact command that changes this outcome, mirroring the CliError contract. */\n fix?: string;\n /** The underlying failure, for a `create-failed` skip. */\n warning?: string;\n}\n\n/** The remedy for each skip, so no skipped state is ever a dead end. */\nfunction walletFix(reason: WalletSkipReason): string {\n switch (reason) {\n case 'no-passphrase-store':\n return 'No OS credential store is available to hold the wallet passphrase. Set TENJIN_WALLET_PASSPHRASE and re-run `tenjin install`, or run `tenjin wallet create` in a terminal to enter one.';\n case 'create-failed':\n return 'Fix the reported problem, then run `tenjin wallet create`.';\n case 'dry-run':\n case 'flag':\n return 'Create one with `tenjin wallet create`.';\n }\n}\n\nexport function walletValue(w: WalletOutcome): string {\n if (w.status === 'existing') return `${w.address} (existing)`;\n if (w.status === 'created') return `${w.address}, $0 - fund with: tenjin wallet fund`;\n if (w.status === 'skipped') return `none (${w.reason}) - ${w.fix}`;\n return 'none - create with: tenjin wallet create';\n}\n\n/**\n * The wallet decision. A wallet is now created BY DEFAULT on both paths, because\n * the loop this command exists to set up does not close without one: `buy` needs\n * a funded key and publish-on-MISS needs a key to sign the write, so a walletless\n * install is a setup that stops at the first useful thing the agent tries.\n *\n * The headless path is the change. It creates without asking, using the\n * passphrase policy `resolvePassphraseForCreate` already enforces: an explicit\n * `TENJIN_WALLET_PASSPHRASE`, else a strong generated passphrase written to the\n * platform's OS credential store and verified by reading it back. When neither is\n * available it creates NOTHING and reports `skipped: no-passphrase-store` with\n * both remedies. There is deliberately no plain-file fallback: a passphrase\n * sitting next to the keystore it unlocks protects nothing, and an install is\n * never the right place to invent one.\n *\n * A creation failure never fails the install. The skills, hooks and permissions\n * this run just wired are all useful without a wallet, so the failure is reported\n * loudly and the command still succeeds.\n */\nexport async function resolveWallet(\n ctx: CommandContext,\n deps: WalletDeps,\n skipReason: 'dry-run' | 'flag' | undefined,\n canPrompt: boolean,\n): Promise<WalletOutcome> {\n const exists = await (deps.walletExists ?? walletFileExists)(ctx.dataDir);\n if (exists) {\n return {\n status: 'existing',\n address: await (deps.walletAddress ?? existingWalletAddress)(ctx),\n };\n }\n if (skipReason !== undefined) {\n return { status: 'skipped', reason: skipReason, fix: walletFix(skipReason) };\n }\n\n // Interactive keeps the question (default yes); headless has nobody to ask and\n // takes the default rather than treating silence as a no.\n if (canPrompt) {\n const confirm = deps.confirmWallet ?? defaultConfirm;\n if (!(await confirm(WALLET_QUESTION))) return { status: 'declined' };\n }\n\n try {\n const create =\n deps.createWallet ??\n ((c: CommandContext) => defaultCreateWallet(c, deps.walletPassphrase, deps.env));\n return { status: 'created', address: await create(ctx) };\n } catch (err) {\n // The one failure with a real remedy: no env passphrase and no OS store, so\n // resolvePassphraseForCreate refused rather than encrypt with a passphrase\n // that has no durable copy. Anything else is reported as itself.\n const reason: WalletSkipReason = isNoPassphraseError(err)\n ? 'no-passphrase-store'\n : 'create-failed';\n return {\n status: 'skipped',\n reason,\n fix: walletFix(reason),\n ...(reason === 'create-failed'\n ? { warning: `The wallet could not be created: ${errorText(err)}` }\n : {}),\n };\n }\n}\n\n/** Is this the passphrase layer refusing because no durable store could serve? */\nfunction isNoPassphraseError(err: unknown): boolean {\n return (\n err instanceof CliError &&\n err.code === 'USAGE' &&\n err.message.includes('No wallet passphrase is available')\n );\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nasync function existingWalletAddress(ctx: CommandContext): Promise<string> {\n return (await describeWallet(resolveWalletProvider(ctx))).address;\n}\n\nasync function defaultCreateWallet(\n ctx: CommandContext,\n passphrase?: PassphraseOverrides,\n env?: NodeJS.ProcessEnv,\n): Promise<string> {\n const result = await runWalletCreate(ctx, {\n ...(passphrase !== undefined ? { passphrase } : {}),\n ...(env !== undefined ? { env } : {}),\n });\n return (result.data as { address: string }).address;\n}\n\n/** The shared confirm, defaulting to YES (setup ergonomics); cancel reads as no. */\nfunction defaultConfirm(label: string): Promise<boolean> {\n return confirmChoice(label, true);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/commands/install-wallet.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport { describeWallet, resolveWalletProvider } from '../lib/wallet';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport { walletFileExists } from '../lib/wallet/store';\nimport { runWalletCreate } from './wallet';\nimport type { CommandContext } from '../context';\n\n/**\n * The wallet step `tenjin install` runs: keep the wallet this machine has, or\n * create one. Shared by the router install and the shelf install so the two\n * can never disagree about when a wallet is made or what a skip tells you.\n */\n\n/** The wallet question's literal copy. */\nexport const WALLET_QUESTION = 'Create a wallet now?';\n\n/** The seams the wallet step reads; every one defaults to the real thing. */\nexport interface WalletDeps {\n env?: NodeJS.ProcessEnv;\n /** \"Create a wallet now?\"; defaults to the clack confirm (default yes). */\n confirmWallet?: (label: string) => Promise<boolean>;\n /** Does a wallet already exist? Defaults to walletFileExists(dataDir). */\n walletExists?: (dataDir: string) => Promise<boolean>;\n /** An existing wallet's address. Defaults to the local provider. */\n walletAddress?: (ctx: CommandContext) => Promise<string>;\n /** Create a wallet and return its address. Defaults to runWalletCreate. */\n createWallet?: (ctx: CommandContext) => Promise<string>;\n /**\n * Passphrase-resolution seam forwarded to `wallet create`. Tests MUST set it\n * (or `createWallet`): without it a headless run creates a real wallet, and\n * on macOS that writes to the developer's own login keychain.\n */\n walletPassphrase?: PassphraseOverrides;\n}\n\n/**\n * Why no wallet was created, when none was.\n *\n * `no-passphrase-store` is the one that matters: this machine has no OS\n * credential store that would hold a generated passphrase, and no\n * `TENJIN_WALLET_PASSPHRASE`. There is no fallback here BY DESIGN. A passphrase\n * written to a plain file beside the keystore it unlocks is not a passphrase, so\n * the run creates nothing and says so loudly with both remedies.\n */\nexport type WalletSkipReason = 'no-passphrase-store' | 'create-failed' | 'dry-run' | 'flag';\n\n/**\n * How the wallet step resolved, so rendering stays separate from prompting.\n *\n * `declined` (an answer) and `skipped` (no answer, with a reason) are kept apart\n * deliberately: an install that could not create a key is a different state from\n * one the operator told not to, and only the first needs a remedy.\n */\nexport interface WalletOutcome {\n status: 'existing' | 'created' | 'declined' | 'skipped';\n address?: string;\n /** Only ever set on `skipped`. */\n reason?: WalletSkipReason;\n /** The exact command that changes this outcome, mirroring the CliError contract. */\n fix?: string;\n /** The underlying failure, for a `create-failed` skip. */\n warning?: string;\n}\n\n/** The remedy for each skip, so no skipped state is ever a dead end. */\nfunction walletFix(reason: WalletSkipReason): string {\n switch (reason) {\n case 'no-passphrase-store':\n return 'No OS credential store is available to hold the wallet passphrase. Set TENJIN_WALLET_PASSPHRASE and re-run `tenjin install`, or run `tenjin wallet create` in a terminal to enter one.';\n case 'create-failed':\n return 'Fix the reported problem, then run `tenjin wallet create`.';\n case 'dry-run':\n case 'flag':\n return 'Create one with `tenjin wallet create`.';\n }\n}\n\nexport function walletValue(w: WalletOutcome): string {\n if (w.status === 'existing') return `${w.address} (existing)`;\n if (w.status === 'created') return `${w.address}, $0 - fund with: tenjin wallet fund`;\n if (w.status === 'skipped') return `none (${w.reason}) - ${w.fix}`;\n return 'none - create with: tenjin wallet create';\n}\n\n/**\n * The wallet decision. A wallet is now created BY DEFAULT on both paths, because\n * the loop this command exists to set up does not close without one: `buy` needs\n * a funded key and publish-on-MISS needs a key to sign the write, so a walletless\n * install is a setup that stops at the first useful thing the agent tries.\n *\n * The headless path is the change. It creates without asking, using the\n * passphrase policy `resolvePassphraseForCreate` already enforces: an explicit\n * `TENJIN_WALLET_PASSPHRASE`, else a strong generated passphrase written to the\n * platform's OS credential store and verified by reading it back. When neither is\n * available it creates NOTHING and reports `skipped: no-passphrase-store` with\n * both remedies. There is deliberately no plain-file fallback: a passphrase\n * sitting next to the keystore it unlocks protects nothing, and an install is\n * never the right place to invent one.\n *\n * A creation failure never fails the install. The skills, hooks and permissions\n * this run just wired are all useful without a wallet, so the failure is reported\n * loudly and the command still succeeds.\n */\nexport async function resolveWallet(\n ctx: CommandContext,\n deps: WalletDeps,\n skipReason: 'dry-run' | 'flag' | undefined,\n canPrompt: boolean,\n): Promise<WalletOutcome> {\n const exists = await (deps.walletExists ?? walletFileExists)(ctx.dataDir);\n if (exists) {\n return {\n status: 'existing',\n address: await (deps.walletAddress ?? existingWalletAddress)(ctx),\n };\n }\n if (skipReason !== undefined) {\n return { status: 'skipped', reason: skipReason, fix: walletFix(skipReason) };\n }\n\n // Interactive keeps the question (default yes); headless has nobody to ask and\n // takes the default rather than treating silence as a no.\n if (canPrompt) {\n const confirm = deps.confirmWallet ?? defaultConfirm;\n if (!(await confirm(WALLET_QUESTION))) return { status: 'declined' };\n }\n\n try {\n const create =\n deps.createWallet ??\n ((c: CommandContext) => defaultCreateWallet(c, deps.walletPassphrase, deps.env));\n return { status: 'created', address: await create(ctx) };\n } catch (err) {\n // The one failure with a real remedy: no env passphrase and no OS store, so\n // resolvePassphraseForCreate refused rather than encrypt with a passphrase\n // that has no durable copy. Anything else is reported as itself.\n const reason: WalletSkipReason = isNoPassphraseError(err)\n ? 'no-passphrase-store'\n : 'create-failed';\n return {\n status: 'skipped',\n reason,\n fix: walletFix(reason),\n ...(reason === 'create-failed'\n ? { warning: `The wallet could not be created: ${errorText(err)}` }\n : {}),\n };\n }\n}\n\n/** Is this the passphrase layer refusing because no durable store could serve? */\nfunction isNoPassphraseError(err: unknown): boolean {\n return (\n err instanceof CliError &&\n err.code === 'USAGE' &&\n err.message.includes('No wallet passphrase is available')\n );\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nasync function existingWalletAddress(ctx: CommandContext): Promise<string> {\n return (await describeWallet(resolveWalletProvider(ctx))).address;\n}\n\nasync function defaultCreateWallet(\n ctx: CommandContext,\n passphrase?: PassphraseOverrides,\n env?: NodeJS.ProcessEnv,\n): Promise<string> {\n const result = await runWalletCreate(ctx, {\n ...(passphrase !== undefined ? { passphrase } : {}),\n ...(env !== undefined ? { env } : {}),\n });\n return (result.data as { address: string }).address;\n}\n\n/** The shared confirm, defaulting to YES (setup ergonomics); cancel reads as no. */\nfunction defaultConfirm(label: string): Promise<boolean> {\n return confirmChoice(label, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,IAAM,kBAAkB;AAmD/B,SAAS,UAAU,QAAkC;AACnD,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,EACX;AACF;AAEO,SAAS,YAAY,GAA0B;AACpD,MAAI,EAAE,WAAW,WAAY,QAAO,GAAG,EAAE,OAAO;AAChD,MAAI,EAAE,WAAW,UAAW,QAAO,GAAG,EAAE,OAAO;AAC/C,MAAI,EAAE,WAAW,UAAW,QAAO,SAAS,EAAE,MAAM,OAAO,EAAE,GAAG;AAChE,SAAO;AACT;AAqBA,eAAsB,cACpB,KACA,MACA,YACA,WACwB;AACxB,QAAM,SAAS,OAAO,KAAK,gBAAgB,kBAAkB,IAAI,OAAO;AACxE,MAAI,QAAQ;AACV,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SAAS,OAAO,KAAK,iBAAiB,uBAAuB,GAAG;AAAA,IAClE;AAAA,EACF;AACA,MAAI,eAAe,QAAW;AAC5B,WAAO,EAAE,QAAQ,WAAW,QAAQ,YAAY,KAAK,UAAU,UAAU,EAAE;AAAA,EAC7E;AAIA,MAAI,WAAW;AACb,UAAM,UAAU,KAAK,iBAAiB;AACtC,QAAI,CAAE,MAAM,QAAQ,eAAe,EAAI,QAAO,EAAE,QAAQ,WAAW;AAAA,EACrE;AAEA,MAAI;AACF,UAAM,SACJ,KAAK,iBACJ,CAAC,MAAsB,oBAAoB,GAAG,KAAK,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