tenjin-cli 0.1.0-alpha.4 → 0.1.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +269 -38
- package/dist/{buy-OOOLUDND.js → buy-XVOMNWKN.js} +21 -18
- package/dist/{candidate-TWCWTFGA.js → candidate-DJB2NNTG.js} +7 -8
- package/dist/{chunk-KXIX7YDV.js → chunk-2KIDDWQO.js} +5 -5
- package/dist/{chunk-NXCJN2FJ.js → chunk-2L73UI6T.js} +51 -42
- package/dist/chunk-2L73UI6T.js.map +1 -0
- package/dist/{chunk-OJD54DIU.js → chunk-2YX6LTCD.js} +5 -5
- package/dist/{chunk-H5ETJRQD.js → chunk-5X4EBGGU.js} +22 -14
- package/dist/chunk-5X4EBGGU.js.map +1 -0
- package/dist/chunk-6S44OLND.js +699 -0
- package/dist/chunk-6S44OLND.js.map +1 -0
- package/dist/{chunk-FU6MCSLG.js → chunk-7WDY4AXV.js} +2 -64
- package/dist/chunk-7WDY4AXV.js.map +1 -0
- package/dist/{chunk-VV4P5RVK.js → chunk-BBUYCDSG.js} +16 -4
- package/dist/chunk-BBUYCDSG.js.map +1 -0
- package/dist/chunk-CYRYVZPN.js +213 -0
- package/dist/chunk-CYRYVZPN.js.map +1 -0
- package/dist/{chunk-FHB3VKZW.js → chunk-DAJ56EUU.js} +5 -3
- package/dist/chunk-DAJ56EUU.js.map +1 -0
- package/dist/chunk-DH6D6QIO.js +239 -0
- package/dist/chunk-DH6D6QIO.js.map +1 -0
- package/dist/chunk-E6BNARCS.js +614 -0
- package/dist/chunk-E6BNARCS.js.map +1 -0
- package/dist/chunk-GABYDXWL.js +190 -0
- package/dist/chunk-GABYDXWL.js.map +1 -0
- package/dist/{chunk-EUQN3L5X.js → chunk-GM4RZUVU.js} +21 -9
- package/dist/chunk-GM4RZUVU.js.map +1 -0
- package/dist/{chunk-C4TIWOAM.js → chunk-GXYNLMUQ.js} +28 -11
- package/dist/chunk-GXYNLMUQ.js.map +1 -0
- package/dist/{chunk-6WWVYYSB.js → chunk-J6CVKC4M.js} +86 -4
- package/dist/chunk-J6CVKC4M.js.map +1 -0
- package/dist/{chunk-5JH7ZB6Z.js → chunk-KT2DGKFT.js} +76 -10
- package/dist/chunk-KT2DGKFT.js.map +1 -0
- package/dist/chunk-L6AV2Q73.js +105 -0
- package/dist/chunk-L6AV2Q73.js.map +1 -0
- package/dist/{chunk-333FOTUJ.js → chunk-MJZZTKCC.js} +108 -2
- package/dist/chunk-MJZZTKCC.js.map +1 -0
- package/dist/{chunk-XNNOR7F7.js → chunk-OTDI5FXG.js} +3 -5
- package/dist/{chunk-XNNOR7F7.js.map → chunk-OTDI5FXG.js.map} +1 -1
- package/dist/chunk-PIIWLEEG.js +337 -0
- package/dist/chunk-PIIWLEEG.js.map +1 -0
- package/dist/{chunk-ULLWHHIT.js → chunk-PLU3E63S.js} +468 -559
- package/dist/chunk-PLU3E63S.js.map +1 -0
- package/dist/chunk-QW2Q2KAH.js +27 -0
- package/dist/chunk-QW2Q2KAH.js.map +1 -0
- package/dist/{chunk-S3KZ3PPK.js → chunk-RGFBBNGP.js} +291 -59
- package/dist/chunk-RGFBBNGP.js.map +1 -0
- package/dist/chunk-SGK2B724.js +67 -0
- package/dist/chunk-SGK2B724.js.map +1 -0
- package/dist/chunk-UYP7G3GZ.js +412 -0
- package/dist/chunk-UYP7G3GZ.js.map +1 -0
- package/dist/{chunk-DPUMEMGM.js → chunk-VZ3AJCO5.js} +3 -5
- package/dist/{chunk-DPUMEMGM.js.map → chunk-VZ3AJCO5.js.map} +1 -1
- package/dist/{chunk-QH6677FJ.js → chunk-WDJTGVKN.js} +2 -2
- package/dist/{chunk-QH6677FJ.js.map → chunk-WDJTGVKN.js.map} +1 -1
- package/dist/{chunk-4GR7DGD6.js → chunk-WI5EOAQQ.js} +33 -256
- package/dist/{chunk-4GR7DGD6.js.map → chunk-WI5EOAQQ.js.map} +1 -1
- package/dist/{chunk-DPET3TW5.js → chunk-WRWCDLVK.js} +13 -12
- package/dist/chunk-WRWCDLVK.js.map +1 -0
- package/dist/chunk-XBJ3VLWX.js +35 -0
- package/dist/chunk-XBJ3VLWX.js.map +1 -0
- package/dist/chunk-ZEWY3RJ3.js +149 -0
- package/dist/chunk-ZEWY3RJ3.js.map +1 -0
- package/dist/chunk-ZFE7STX7.js +143 -0
- package/dist/chunk-ZFE7STX7.js.map +1 -0
- package/dist/{cli-AFSLAKR6.js → cli-7B2QNJG3.js} +247 -26
- package/dist/cli-7B2QNJG3.js.map +1 -0
- package/dist/{config-DBEEM3UA.js → config-SAQEQRFB.js} +7 -6
- package/dist/{doctor-XDA3YU6H.js → doctor-ENJ22XWN.js} +10 -8
- package/dist/{publish-IH7RJXGB.js → edit-2QO5GQDU.js} +19 -17
- package/dist/index.js +1 -1
- package/dist/{inspect-YBGDAG47.js → inspect-IPKKQB2S.js} +16 -15
- package/dist/{install-7J6KKEEP.js → install-7ZIYISQ7.js} +180 -133
- package/dist/install-7ZIYISQ7.js.map +1 -0
- package/dist/outcome-NSDE2KAJ.js +20 -0
- package/dist/publish-7WIFFNFG.js +40 -0
- package/dist/read-5TQR7LCF.js +158 -0
- package/dist/read-5TQR7LCF.js.map +1 -0
- package/dist/{run-DCZFEW2C.js → run-NPKIP26Y.js} +109 -34
- package/dist/{run-DCZFEW2C.js.map → run-NPKIP26Y.js.map} +1 -1
- package/dist/search-63ELMRZH.js +24 -0
- package/dist/send-ENE47KQE.js +222 -0
- package/dist/send-ENE47KQE.js.map +1 -0
- package/dist/session-FZU4VFFE.js +87 -0
- package/dist/session-FZU4VFFE.js.map +1 -0
- package/dist/{usdc-AU6ZIKA6.js → usdc-4VCDHFWX.js} +20 -4
- package/dist/{wallet-UWHSHWC6.js → wallet-OCCGEH6H.js} +8 -8
- package/dist/{wallet-HKG3GSTX.js → wallet-RBDVNZVR.js} +17 -7
- package/dist/wallet-RBDVNZVR.js.map +1 -0
- package/package.json +1 -1
- package/skills/tenjin/SKILL.md +32 -7
- package/skills/tenjin-publish/SKILL.md +109 -16
- package/skills/tenjin-search/SKILL.md +174 -15
- package/dist/chunk-333FOTUJ.js.map +0 -1
- package/dist/chunk-5JH7ZB6Z.js.map +0 -1
- package/dist/chunk-6WWVYYSB.js.map +0 -1
- package/dist/chunk-BXUS5UCT.js +0 -212
- package/dist/chunk-BXUS5UCT.js.map +0 -1
- package/dist/chunk-C4TIWOAM.js.map +0 -1
- package/dist/chunk-CJU555P5.js +0 -333
- package/dist/chunk-CJU555P5.js.map +0 -1
- package/dist/chunk-DPET3TW5.js.map +0 -1
- package/dist/chunk-EUQN3L5X.js.map +0 -1
- package/dist/chunk-FHB3VKZW.js.map +0 -1
- package/dist/chunk-FU6MCSLG.js.map +0 -1
- package/dist/chunk-H5ETJRQD.js.map +0 -1
- package/dist/chunk-MM4TGTST.js +0 -59
- package/dist/chunk-MM4TGTST.js.map +0 -1
- package/dist/chunk-MUBUQVC3.js +0 -67
- package/dist/chunk-MUBUQVC3.js.map +0 -1
- package/dist/chunk-NXCJN2FJ.js.map +0 -1
- package/dist/chunk-R7BMDJZM.js +0 -167
- package/dist/chunk-R7BMDJZM.js.map +0 -1
- package/dist/chunk-S3KZ3PPK.js.map +0 -1
- package/dist/chunk-ULLWHHIT.js.map +0 -1
- package/dist/chunk-VV4P5RVK.js.map +0 -1
- package/dist/chunk-YFREUEUI.js +0 -78
- package/dist/chunk-YFREUEUI.js.map +0 -1
- package/dist/cli-AFSLAKR6.js.map +0 -1
- package/dist/install-7J6KKEEP.js.map +0 -1
- package/dist/outcome-ZFGHX2XW.js +0 -20
- package/dist/search-R6NIQFXI.js +0 -24
- /package/dist/{buy-OOOLUDND.js.map → buy-XVOMNWKN.js.map} +0 -0
- /package/dist/{candidate-TWCWTFGA.js.map → candidate-DJB2NNTG.js.map} +0 -0
- /package/dist/{chunk-KXIX7YDV.js.map → chunk-2KIDDWQO.js.map} +0 -0
- /package/dist/{chunk-OJD54DIU.js.map → chunk-2YX6LTCD.js.map} +0 -0
- /package/dist/{config-DBEEM3UA.js.map → config-SAQEQRFB.js.map} +0 -0
- /package/dist/{doctor-XDA3YU6H.js.map → doctor-ENJ22XWN.js.map} +0 -0
- /package/dist/{inspect-YBGDAG47.js.map → edit-2QO5GQDU.js.map} +0 -0
- /package/dist/{outcome-ZFGHX2XW.js.map → inspect-IPKKQB2S.js.map} +0 -0
- /package/dist/{publish-IH7RJXGB.js.map → outcome-NSDE2KAJ.js.map} +0 -0
- /package/dist/{search-R6NIQFXI.js.map → publish-7WIFFNFG.js.map} +0 -0
- /package/dist/{usdc-AU6ZIKA6.js.map → search-63ELMRZH.js.map} +0 -0
- /package/dist/{wallet-HKG3GSTX.js.map → usdc-4VCDHFWX.js.map} +0 -0
- /package/dist/{wallet-UWHSHWC6.js.map → wallet-OCCGEH6H.js.map} +0 -0
|
@@ -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
2
2
|
import {
|
|
3
3
|
CliError,
|
|
4
4
|
external_exports
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-J6CVKC4M.js";
|
|
6
6
|
|
|
7
7
|
// src/lib/output.ts
|
|
8
8
|
import { styleText } from "util";
|
|
@@ -43,7 +43,10 @@ var ErrorCodeSchema = external_exports.enum([
|
|
|
43
43
|
// mirroring PAYMENT_FAILED's post-decision failure class.
|
|
44
44
|
"NEEDS_CONFIRMATION",
|
|
45
45
|
"PUBLISH_BLOCKED",
|
|
46
|
-
"PUBLISH_FAILED"
|
|
46
|
+
"PUBLISH_FAILED",
|
|
47
|
+
// A send that reverted or produced no receipt AFTER the human approved it and
|
|
48
|
+
// it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.
|
|
49
|
+
"SEND_FAILED"
|
|
47
50
|
]);
|
|
48
51
|
var MoneySchema = external_exports.object({
|
|
49
52
|
atomic: external_exports.string(),
|
|
@@ -113,8 +116,16 @@ function emitFailure(io, command, err, opts = {}) {
|
|
|
113
116
|
writeJson(io.stdout, buildFailureEnvelope(command, cliErr));
|
|
114
117
|
return cliErr;
|
|
115
118
|
}
|
|
119
|
+
function emitNotice(io, text, opts = {}) {
|
|
120
|
+
if (!humanMode(io, opts)) return;
|
|
121
|
+
io.stderr.write(`${paint(io, "dim", sanitizeForTerminal(text))}
|
|
122
|
+
`);
|
|
123
|
+
}
|
|
116
124
|
function sanitizeForTerminal(text) {
|
|
117
|
-
return text.replace(/\x1b(?:\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g, "").replace(/[\x00-\x08\x0a-\x1f\x7f-\x9f]/g, "")
|
|
125
|
+
return text.replace(/\x1b(?:\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g, "").replace(/[\x00-\x08\x0a-\x1f\x7f-\x9f]/g, "").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(
|
|
126
|
+
/(\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F})|[\u{E0000}-\u{E007F}\u{FEFF}]/gu,
|
|
127
|
+
(_match, rgiFlag) => rgiFlag ?? ""
|
|
128
|
+
);
|
|
118
129
|
}
|
|
119
130
|
function normalizeError(err) {
|
|
120
131
|
if (err instanceof CliError) return err;
|
|
@@ -158,7 +169,8 @@ export {
|
|
|
158
169
|
buildFailureEnvelope,
|
|
159
170
|
emitSuccess,
|
|
160
171
|
emitFailure,
|
|
172
|
+
emitNotice,
|
|
161
173
|
sanitizeForTerminal,
|
|
162
174
|
normalizeError
|
|
163
175
|
};
|
|
164
|
-
//# sourceMappingURL=chunk-
|
|
176
|
+
//# sourceMappingURL=chunk-BBUYCDSG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { CliError } from './errors';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY fact. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` is the real terminal fact; the separate `--json` flag (passed to the\n * emit functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output.\n */\nexport interface Io {\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(command: string, data: unknown): SuccessEnvelope {\n return { schemaVersion: SCHEMA_VERSION, command, ok: true, data };\n}\n\nexport function buildFailureEnvelope(command: string, err: CliError): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return { schemaVersion: SCHEMA_VERSION, command, ok: false, error };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them an\n // interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees the\n // count but not WHICH lines tripped. Every other details shape stays machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n // eslint-disable-next-line no-control-regex\n .replace(/\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt } = f as { check?: unknown; line?: unknown; excerpt?: unknown };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n rendered.push(paint(io, 'dim', ` ${check} (line ${line}): ${sanitizeForTerminal(excerpt)}`));\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\n/**\n * Color a human line for stdout (the human surface now). styleText emits ANSI only\n * when the target stream is color-capable (a real TTY with color depth) and honors\n * NO_COLOR/FORCE_COLOR natively. The `stream` option is passed only when stdout is\n * a genuine Stream; a test/redirected sink is not one, so it falls back to the\n * default capability check and comes out plain.\n */\nfunction paint(io: Io, format: Parameters<typeof styleText>[0], text: string): string {\n if (io.stdout instanceof Stream) return styleText(format, text, { stream: io.stdout });\n return styleText(format, text);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,cAAc;;;ACMhB,IAAM,iBAAiB;AAQv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AAC;AAAA,CAAI;AACpD;AAEA,SAAS,WAAW,QAA+B,OAAuB;AACxE,MAAI,MAAM,SAAS,EAAG,QAAO,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC;AAAA,CAAI;AAC5D;AASA,SAAS,MAAM,IAAQ,QAAyC,MAAsB;AACpF,MAAI,GAAG,kBAAkB,OAAQ,QAAO,UAAU,QAAQ,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC;AACrF,SAAO,UAAU,QAAQ,IAAI;AAC/B;","names":[]}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
findStoredCandidate
|
|
4
|
+
} from "./chunk-OTDI5FXG.js";
|
|
5
|
+
import {
|
|
6
|
+
SLUG_RE,
|
|
7
|
+
UUID_RE
|
|
8
|
+
} from "./chunk-WWX32ML4.js";
|
|
9
|
+
import {
|
|
10
|
+
CliError,
|
|
11
|
+
external_exports,
|
|
12
|
+
writeFileAtomic
|
|
13
|
+
} from "./chunk-J6CVKC4M.js";
|
|
14
|
+
|
|
15
|
+
// src/lib/library.ts
|
|
16
|
+
import { createHash } from "crypto";
|
|
17
|
+
import { readFile, readdir } from "fs/promises";
|
|
18
|
+
import { isAbsolute, join, relative, resolve } from "path";
|
|
19
|
+
var ReceiptSchema = external_exports.object({
|
|
20
|
+
schemaVersion: external_exports.literal(1),
|
|
21
|
+
resourceId: external_exports.string(),
|
|
22
|
+
slug: external_exports.string(),
|
|
23
|
+
title: external_exports.string(),
|
|
24
|
+
handle: external_exports.string(),
|
|
25
|
+
url: external_exports.string(),
|
|
26
|
+
priceAtomic: external_exports.string(),
|
|
27
|
+
entitlement: external_exports.enum(["free", "entitled", "purchased"]),
|
|
28
|
+
contentHash: external_exports.string(),
|
|
29
|
+
settlementTxHash: external_exports.string().optional(),
|
|
30
|
+
savedAt: external_exports.string()
|
|
31
|
+
});
|
|
32
|
+
function libraryDir(dataDir) {
|
|
33
|
+
return join(dataDir, "library");
|
|
34
|
+
}
|
|
35
|
+
function resourceDir(dataDir, resourceId) {
|
|
36
|
+
return join(libraryDir(dataDir), resourceId);
|
|
37
|
+
}
|
|
38
|
+
function isSafeIdentity(resourceId, slug) {
|
|
39
|
+
return UUID_RE.test(resourceId) && slug.length <= 80 && SLUG_RE.test(slug);
|
|
40
|
+
}
|
|
41
|
+
function assertContained(dataDir, resourceId, slug) {
|
|
42
|
+
if (!isSafeIdentity(resourceId, slug)) {
|
|
43
|
+
throw new CliError("CONTRACT_MISMATCH", "The server returned an unsafe resource identity.", {
|
|
44
|
+
fix: "Update tenjin-cli or report the resource; the id/slug is not a valid identity.",
|
|
45
|
+
details: { resourceId, slug }
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const root = resolve(libraryDir(dataDir));
|
|
49
|
+
const target = resolve(bodyPath(dataDir, resourceId, slug));
|
|
50
|
+
const rel = relative(root, target);
|
|
51
|
+
if (rel.startsWith("..") || isAbsolute(rel) || rel.split(/[\\/]/).includes("..")) {
|
|
52
|
+
throw new CliError("CONTRACT_MISMATCH", "The delivery path escapes the library directory.", {
|
|
53
|
+
fix: "Update tenjin-cli; the resource identity is unsafe."
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function bodyPath(dataDir, resourceId, slug) {
|
|
58
|
+
return join(resourceDir(dataDir, resourceId), `${slug}.md`);
|
|
59
|
+
}
|
|
60
|
+
function receiptPath(dataDir, resourceId) {
|
|
61
|
+
return join(resourceDir(dataDir, resourceId), "receipt.json");
|
|
62
|
+
}
|
|
63
|
+
function contentHash(bodyMd) {
|
|
64
|
+
return `sha256:${createHash("sha256").update(bodyMd, "utf8").digest("hex")}`;
|
|
65
|
+
}
|
|
66
|
+
async function findDelivered(dataDir, resourceId) {
|
|
67
|
+
if (!UUID_RE.test(resourceId)) return null;
|
|
68
|
+
let receiptRaw;
|
|
69
|
+
try {
|
|
70
|
+
receiptRaw = await readFile(receiptPath(dataDir, resourceId), "utf8");
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
const parsed = ReceiptSchema.safeParse(safeJson(receiptRaw));
|
|
75
|
+
if (!parsed.success) return null;
|
|
76
|
+
const path = bodyPath(dataDir, resourceId, parsed.data.slug);
|
|
77
|
+
let bodyMd;
|
|
78
|
+
try {
|
|
79
|
+
bodyMd = await readFile(path, "utf8");
|
|
80
|
+
} catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
return { receipt: parsed.data, bodyMd, bodyPath: path };
|
|
84
|
+
}
|
|
85
|
+
var READ_PATH_RE = /\/api\/read\/([^/]+)\/([^/]+)\/?$/;
|
|
86
|
+
function parseReadPath(url) {
|
|
87
|
+
let pathname;
|
|
88
|
+
try {
|
|
89
|
+
pathname = new URL(url).pathname;
|
|
90
|
+
} catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
const m = READ_PATH_RE.exec(pathname);
|
|
94
|
+
if (m === null || m[1] === void 0 || m[2] === void 0) return null;
|
|
95
|
+
return { handle: decodeURIComponent(m[1]), slug: decodeURIComponent(m[2]) };
|
|
96
|
+
}
|
|
97
|
+
function canonicalReadUrl(url) {
|
|
98
|
+
if (parseReadPath(url) === null) return url;
|
|
99
|
+
const mark = url.search(/[?#]/);
|
|
100
|
+
const path = mark === -1 ? url : url.slice(0, mark);
|
|
101
|
+
if (!path.endsWith("/")) return url;
|
|
102
|
+
return path.slice(0, -1) + (mark === -1 ? "" : url.slice(mark));
|
|
103
|
+
}
|
|
104
|
+
async function findDeliveredByUrl(dataDir, url) {
|
|
105
|
+
const target = parseReadPath(url);
|
|
106
|
+
if (target === null) return null;
|
|
107
|
+
let entries;
|
|
108
|
+
try {
|
|
109
|
+
entries = await readdir(libraryDir(dataDir));
|
|
110
|
+
} catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
for (const resourceId of entries) {
|
|
114
|
+
if (!UUID_RE.test(resourceId)) continue;
|
|
115
|
+
const delivered = await findDelivered(dataDir, resourceId);
|
|
116
|
+
if (delivered === null) continue;
|
|
117
|
+
const saved = parseReadPath(delivered.receipt.url);
|
|
118
|
+
if (saved !== null && saved.handle === target.handle && saved.slug === target.slug) {
|
|
119
|
+
return delivered;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
async function saveDelivery(dataDir, input) {
|
|
125
|
+
assertContained(dataDir, input.resourceId, input.slug);
|
|
126
|
+
const path = bodyPath(dataDir, input.resourceId, input.slug);
|
|
127
|
+
const receipt = {
|
|
128
|
+
schemaVersion: 1,
|
|
129
|
+
resourceId: input.resourceId,
|
|
130
|
+
slug: input.slug,
|
|
131
|
+
title: input.title,
|
|
132
|
+
handle: input.handle,
|
|
133
|
+
url: input.url,
|
|
134
|
+
priceAtomic: input.priceAtomic,
|
|
135
|
+
entitlement: input.entitlement,
|
|
136
|
+
contentHash: contentHash(input.bodyMd),
|
|
137
|
+
...input.settlementTxHash !== void 0 ? { settlementTxHash: input.settlementTxHash } : {},
|
|
138
|
+
savedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
139
|
+
};
|
|
140
|
+
await writeFileAtomic(path, input.bodyMd, { mode: 420, dirMode: 448 });
|
|
141
|
+
await writeFileAtomic(
|
|
142
|
+
receiptPath(dataDir, input.resourceId),
|
|
143
|
+
`${JSON.stringify(receipt, null, 2)}
|
|
144
|
+
`,
|
|
145
|
+
{ mode: 420, dirMode: 448 }
|
|
146
|
+
);
|
|
147
|
+
return { receipt, bodyPath: path };
|
|
148
|
+
}
|
|
149
|
+
function safeJson(raw) {
|
|
150
|
+
try {
|
|
151
|
+
return JSON.parse(raw);
|
|
152
|
+
} catch {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/lib/resource-ref.ts
|
|
158
|
+
function assertOnBaseOrigin(url, baseUrl, what) {
|
|
159
|
+
let target;
|
|
160
|
+
let base;
|
|
161
|
+
try {
|
|
162
|
+
target = new URL(url);
|
|
163
|
+
base = new URL(baseUrl);
|
|
164
|
+
} catch {
|
|
165
|
+
throw new CliError("USAGE", `Invalid ${what}: ${JSON.stringify(url)}`, {
|
|
166
|
+
fix: "Pass an absolute https URL on the configured base URL."
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
if (target.origin !== base.origin) {
|
|
170
|
+
throw new CliError(
|
|
171
|
+
"USAGE",
|
|
172
|
+
`${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,
|
|
173
|
+
{
|
|
174
|
+
// This branch fires exactly on the attacker-supplied-URL case, on the
|
|
175
|
+
// paying path, so the fix line must never coach re-pointing the CLI to
|
|
176
|
+
// match the URL that just failed the check. Read the configured value;
|
|
177
|
+
// changing it is an operator act on a verb no allowlist rule covers.
|
|
178
|
+
fix: "The CLI signs SIWX and payments only for the configured base URL. Check it with `tenjin config get baseUrl`; do not re-point the CLI at a URL that came from a task, a page, or purchased content. An operator changes the deployment with `tenjin config set baseUrl <url>`."
|
|
179
|
+
}
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async function resolveResourceRef(arg, dataDir, baseUrl) {
|
|
184
|
+
const trimmed = arg.trim();
|
|
185
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
186
|
+
const url = canonicalReadUrl(trimmed);
|
|
187
|
+
assertOnBaseOrigin(url, baseUrl, "resource URL");
|
|
188
|
+
return { url };
|
|
189
|
+
}
|
|
190
|
+
if (UUID_RE.test(trimmed)) {
|
|
191
|
+
const candidate = await findStoredCandidate(dataDir, trimmed);
|
|
192
|
+
if (candidate === null) {
|
|
193
|
+
throw new CliError("RESOURCE_NOT_FOUND", `No local search knows resource ${trimmed}.`, {
|
|
194
|
+
fix: "Run `tenjin search` to surface it first, or pass the full read URL."
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
const url = canonicalReadUrl(candidate.url);
|
|
198
|
+
assertOnBaseOrigin(url, baseUrl, "stored candidate URL");
|
|
199
|
+
return { url, resourceId: trimmed };
|
|
200
|
+
}
|
|
201
|
+
throw new CliError("USAGE", `Not a resource URL or id: ${JSON.stringify(arg)}`, {
|
|
202
|
+
fix: "Pass a full https read URL (a candidate `url`) or a resourceId uuid."
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export {
|
|
207
|
+
findDelivered,
|
|
208
|
+
findDeliveredByUrl,
|
|
209
|
+
saveDelivery,
|
|
210
|
+
assertOnBaseOrigin,
|
|
211
|
+
resolveResourceRef
|
|
212
|
+
};
|
|
213
|
+
//# sourceMappingURL=chunk-CYRYVZPN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/library.ts","../src/lib/resource-ref.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { writeFileAtomic } from './atomic-json';\n\n/**\n * Filesystem identity is server-controlled (the read body's id + slug), so it is\n * hostile input to a path. resourceId must be a uuid and slug must match the\n * server's slug charset (lib/posts.ts slugify: lowercase a-z0-9 groups joined by\n * single hyphens, no leading/trailing hyphen, <=80 chars). This is the primary\n * guard; assertContained is the defense-in-depth backstop.\n */\nimport { SLUG_RE, UUID_RE as RESOURCE_ID_RE } from './ids';\n\n/**\n * Local library delivery (spec 10): purchased or freely-read bodies are saved\n * under `<dataDir>/library/<resourceId>/<slug>.md` with a sidecar `receipt.json`\n * carrying the entitlement + payment identity. A `buy` on already-delivered\n * content re-delivers FROM DISK, the receipt is the local entitlement record, so\n * a repeat buy never re-pays and never re-fetches. `contentHash` is the sha256 the\n * outcome endpoint expects, computed over the exact saved bytes.\n */\n\nexport type Entitlement = 'free' | 'entitled' | 'purchased';\n\nexport const ReceiptSchema = z.object({\n schemaVersion: z.literal(1),\n resourceId: z.string(),\n slug: z.string(),\n title: z.string(),\n handle: z.string(),\n url: z.string(),\n priceAtomic: z.string(),\n entitlement: z.enum(['free', 'entitled', 'purchased']),\n contentHash: z.string(),\n settlementTxHash: z.string().optional(),\n savedAt: z.string(),\n});\nexport type Receipt = z.infer<typeof ReceiptSchema>;\n\nexport function libraryDir(dataDir: string): string {\n return join(dataDir, 'library');\n}\n\nexport function resourceDir(dataDir: string, resourceId: string): string {\n return join(libraryDir(dataDir), resourceId);\n}\n\n/** True when `resourceId` is a uuid and `slug` matches the server's slug charset,\n * so neither can carry a path separator or `..`. */\nexport function isSafeIdentity(resourceId: string, slug: string): boolean {\n return RESOURCE_ID_RE.test(resourceId) && slug.length <= 80 && SLUG_RE.test(slug);\n}\n\n/**\n * Defense-in-depth: refuse a delivery whose identity is malformed OR whose\n * resolved write path escapes the library root. A malicious server returning\n * id='../../etc' or slug='../../evil' is rejected as a contract violation before\n * any bytes (or directories) are written.\n */\nfunction assertContained(dataDir: string, resourceId: string, slug: string): void {\n if (!isSafeIdentity(resourceId, slug)) {\n throw new CliError('CONTRACT_MISMATCH', 'The server returned an unsafe resource identity.', {\n fix: 'Update tenjin-cli or report the resource; the id/slug is not a valid identity.',\n details: { resourceId, slug },\n });\n }\n const root = resolve(libraryDir(dataDir));\n const target = resolve(bodyPath(dataDir, resourceId, slug));\n const rel = relative(root, target);\n if (rel.startsWith('..') || isAbsolute(rel) || rel.split(/[\\\\/]/).includes('..')) {\n throw new CliError('CONTRACT_MISMATCH', 'The delivery path escapes the library directory.', {\n fix: 'Update tenjin-cli; the resource identity is unsafe.',\n });\n }\n}\n\nexport function bodyPath(dataDir: string, resourceId: string, slug: string): string {\n return join(resourceDir(dataDir, resourceId), `${slug}.md`);\n}\n\nexport function receiptPath(dataDir: string, resourceId: string): string {\n return join(resourceDir(dataDir, resourceId), 'receipt.json');\n}\n\n/** sha256 over the UTF-8 bytes of `bodyMd`, \"sha256:<64 hex>\" (server contract). */\nexport function contentHash(bodyMd: string): string {\n return `sha256:${createHash('sha256').update(bodyMd, 'utf8').digest('hex')}`;\n}\n\nexport interface DeliveredResource {\n receipt: Receipt;\n bodyMd: string;\n bodyPath: string;\n}\n\n/** Return the on-disk delivery for a resource, or null when nothing is saved yet\n * (or the sidecar is unreadable/corrupt, treated as absent, never a hard error). */\nexport async function findDelivered(\n dataDir: string,\n resourceId: string,\n): Promise<DeliveredResource | null> {\n // A non-uuid resourceId can never have been a saved directory; treat it as\n // absent rather than probing an attacker-shaped path.\n if (!RESOURCE_ID_RE.test(resourceId)) return null;\n let receiptRaw: string;\n try {\n receiptRaw = await readFile(receiptPath(dataDir, resourceId), 'utf8');\n } catch {\n return null;\n }\n const parsed = ReceiptSchema.safeParse(safeJson(receiptRaw));\n if (!parsed.success) return null;\n const path = bodyPath(dataDir, resourceId, parsed.data.slug);\n let bodyMd: string;\n try {\n bodyMd = await readFile(path, 'utf8');\n } catch {\n return null;\n }\n return { receipt: parsed.data, bodyMd, bodyPath: path };\n}\n\n/**\n * The read route's path shape. The trailing slash is OPTIONAL here, which is a\n * deliberate tolerance: a URL a human pasted with one addresses the same piece.\n * `parseReadPath` and `canonicalReadUrl` share this regex so the shape they\n * tolerate and the shape one of them removes can never drift apart.\n */\nconst READ_PATH_RE = /\\/api\\/read\\/([^/]+)\\/([^/]+)\\/?$/;\n\n/** The (handle, slug) a read URL points at, path-only so base-url/trailing-slash\n * differences never matter. Null when the URL is not a read-route URL. */\nexport function parseReadPath(url: string): { handle: string; slug: string } | null {\n let pathname: string;\n try {\n pathname = new URL(url).pathname;\n } catch {\n return null;\n }\n const m = READ_PATH_RE.exec(pathname);\n if (m === null || m[1] === undefined || m[2] === undefined) return null;\n return { handle: decodeURIComponent(m[1]), slug: decodeURIComponent(m[2]) };\n}\n\n/**\n * A read URL in the spelling the transport should ask for: the same URL with\n * `parseReadPath`'s optional trailing slash removed.\n *\n * This exists because the tolerance above and the transport disagree without it.\n * `fetchRead` pins `blockRedirects`, so a 3xx anywhere on the read path is a hard\n * failure rather than a hop — and the read route legitimately canonicalizes\n * `/api/read/<handle>/<slug>/` to the no-slash form. Left un-normalized, a URL a\n * user pasted with a trailing slash therefore dies at the FIRST probe of both\n * `read` and `buy`, on a redirect the pin is not there to catch: it is\n * same-origin, so no other host's bytes are in play.\n *\n * Removing the slash instead of relaxing the pin keeps the two concerns apart.\n * Canonicalizing a URL is this function's job; refusing to follow a redirect\n * stays the transport's, unconditionally.\n *\n * Path-only and conservative: a non-read URL is returned untouched, the query and\n * fragment are preserved byte-for-byte, and only the ONE slash the regex tolerates\n * is removed (so `/api/read/h/s//`, which `parseReadPath` already rejects, is left\n * exactly as it came in). It cannot change the origin, which is why callers may\n * origin-check the result rather than the input.\n */\nexport function canonicalReadUrl(url: string): string {\n if (parseReadPath(url) === null) return url;\n const mark = url.search(/[?#]/);\n const path = mark === -1 ? url : url.slice(0, mark);\n if (!path.endsWith('/')) return url;\n return path.slice(0, -1) + (mark === -1 ? '' : url.slice(mark));\n}\n\n/**\n * Find a delivered resource by its READ URL (handle/slug), for the double-pay\n * guard on a `buy <url>` where the resourceId isn't known up front. Scans the\n * library's receipts and matches on the URL's handle+slug path, so a repeat buy\n * of an owned resource re-delivers from disk before any network or payment.\n */\nexport async function findDeliveredByUrl(\n dataDir: string,\n url: string,\n): Promise<DeliveredResource | null> {\n const target = parseReadPath(url);\n if (target === null) return null;\n let entries: string[];\n try {\n entries = await readdir(libraryDir(dataDir));\n } catch {\n return null;\n }\n for (const resourceId of entries) {\n if (!RESOURCE_ID_RE.test(resourceId)) continue;\n const delivered = await findDelivered(dataDir, resourceId);\n if (delivered === null) continue;\n const saved = parseReadPath(delivered.receipt.url);\n if (saved !== null && saved.handle === target.handle && saved.slug === target.slug) {\n return delivered;\n }\n }\n return null;\n}\n\nexport interface SaveDeliveryInput {\n resourceId: string;\n slug: string;\n title: string;\n handle: string;\n url: string;\n priceAtomic: string;\n entitlement: Entitlement;\n bodyMd: string;\n settlementTxHash?: string;\n}\n\nexport interface SavedDelivery {\n receipt: Receipt;\n bodyPath: string;\n}\n\n/** Persist the body + receipt atomically. Idempotent by path: re-saving the same\n * resource overwrites the sidecar (e.g. a free read later becomes a purchase). */\nexport async function saveDelivery(\n dataDir: string,\n input: SaveDeliveryInput,\n): Promise<SavedDelivery> {\n assertContained(dataDir, input.resourceId, input.slug);\n const path = bodyPath(dataDir, input.resourceId, input.slug);\n const receipt: Receipt = {\n schemaVersion: 1,\n resourceId: input.resourceId,\n slug: input.slug,\n title: input.title,\n handle: input.handle,\n url: input.url,\n priceAtomic: input.priceAtomic,\n entitlement: input.entitlement,\n contentHash: contentHash(input.bodyMd),\n ...(input.settlementTxHash !== undefined ? { settlementTxHash: input.settlementTxHash } : {}),\n savedAt: new Date().toISOString(),\n };\n await writeFileAtomic(path, input.bodyMd, { mode: 0o644, dirMode: 0o700 });\n await writeFileAtomic(\n receiptPath(dataDir, input.resourceId),\n `${JSON.stringify(receipt, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n return { receipt, bodyPath: path };\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { CliError } from './errors';\nimport { findStoredCandidate } from './search-store';\nimport { canonicalReadUrl } from './library';\nimport { UUID_RE } from './ids';\n\n/**\n * Resolve a `<resource-url-or-id>` CLI argument to the payable read URL. A full\n * http(s) URL must live on the configured base URL's origin; a bare uuid is a\n * resourceId, resolved to its URL through the local search store (the read route\n * is keyed by handle/slug, so an id alone cannot build the URL). Anything else is\n * a usage error with a clear fix.\n *\n * The origin pin is a MONEY-PATH trust boundary, not pedantry: `buy` sends a\n * wallet-signed SIWX header (a bearer credential scoped to the configured\n * domain) and an EIP-3009 payment authorization to whatever host the resolved\n * URL names. An off-origin URL, whether typed by hand or planted in a search\n * candidate, would hand both to that host. Nothing signed may leave for a host\n * the user did not configure.\n *\n * This is also the one place a read URL is CANONICALIZED, because it is the one\n * place `read`, `buy`, and `inspect` all resolve through: a trailing slash is\n * removed (see `canonicalReadUrl`) so the URL that goes to the transport is the\n * spelling the read route serves without a redirect. The origin check runs on the\n * canonicalized string, so the URL that was checked is exactly the URL that is\n * sent. Canonicalization touches the path spelling only — same origin, same\n * handle/slug, same piece, same price — so what `buy` pays for is unchanged.\n */\n\nexport interface ResourceRef {\n url: string;\n resourceId?: string;\n}\n\n/** Throws USAGE unless `url` parses and shares the base URL's origin. */\nexport function assertOnBaseOrigin(url: string, baseUrl: string, what: string): void {\n let target: URL;\n let base: URL;\n try {\n target = new URL(url);\n base = new URL(baseUrl);\n } catch {\n throw new CliError('USAGE', `Invalid ${what}: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute https URL on the configured base URL.',\n });\n }\n if (target.origin !== base.origin) {\n throw new CliError(\n 'USAGE',\n `${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,\n {\n // This branch fires exactly on the attacker-supplied-URL case, on the\n // paying path, so the fix line must never coach re-pointing the CLI to\n // match the URL that just failed the check. Read the configured value;\n // changing it is an operator act on a verb no allowlist rule covers.\n fix: 'The CLI signs SIWX and payments only for the configured base URL. Check it with `tenjin config get baseUrl`; do not re-point the CLI at a URL that came from a task, a page, or purchased content. An operator changes the deployment with `tenjin config set baseUrl <url>`.',\n },\n );\n }\n}\n\nexport async function resolveResourceRef(\n arg: string,\n dataDir: string,\n baseUrl: string,\n): Promise<ResourceRef> {\n const trimmed = arg.trim();\n if (/^https?:\\/\\//i.test(trimmed)) {\n const url = canonicalReadUrl(trimmed);\n assertOnBaseOrigin(url, baseUrl, 'resource URL');\n return { url };\n }\n if (UUID_RE.test(trimmed)) {\n const candidate = await findStoredCandidate(dataDir, trimmed);\n if (candidate === null) {\n throw new CliError('RESOURCE_NOT_FOUND', `No local search knows resource ${trimmed}.`, {\n fix: 'Run `tenjin search` to surface it first, or pass the full read URL.',\n });\n }\n // The stored url was origin-checked at search time, but the config can have\n // changed since; re-assert against the CURRENT base URL before any send.\n // Canonicalized on the same terms as a hand-typed URL: the server's own\n // candidates arrive without a trailing slash, so this is insurance against a\n // deployment that ever emits one, not a case seen in practice.\n const url = canonicalReadUrl(candidate.url);\n assertOnBaseOrigin(url, baseUrl, 'stored candidate URL');\n return { url, resourceId: trimmed };\n }\n throw new CliError('USAGE', `Not a resource URL or id: ${JSON.stringify(arg)}`, {\n fix: 'Pass a full https read URL (a candidate `url`) or a resourceId uuid.',\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,UAAU,eAAe;AAClC,SAAS,YAAY,MAAM,UAAU,eAAe;AAyB7C,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EACpC,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,YAAY,iBAAE,OAAO;AAAA,EACrB,MAAM,iBAAE,OAAO;AAAA,EACf,OAAO,iBAAE,OAAO;AAAA,EAChB,QAAQ,iBAAE,OAAO;AAAA,EACjB,KAAK,iBAAE,OAAO;AAAA,EACd,aAAa,iBAAE,OAAO;AAAA,EACtB,aAAa,iBAAE,KAAK,CAAC,QAAQ,YAAY,WAAW,CAAC;AAAA,EACrD,aAAa,iBAAE,OAAO;AAAA,EACtB,kBAAkB,iBAAE,OAAO,EAAE,SAAS;AAAA,EACtC,SAAS,iBAAE,OAAO;AACpB,CAAC;AAGM,SAAS,WAAW,SAAyB;AAClD,SAAO,KAAK,SAAS,SAAS;AAChC;AAEO,SAAS,YAAY,SAAiB,YAA4B;AACvE,SAAO,KAAK,WAAW,OAAO,GAAG,UAAU;AAC7C;AAIO,SAAS,eAAe,YAAoB,MAAuB;AACxE,SAAO,QAAe,KAAK,UAAU,KAAK,KAAK,UAAU,MAAM,QAAQ,KAAK,IAAI;AAClF;AAQA,SAAS,gBAAgB,SAAiB,YAAoB,MAAoB;AAChF,MAAI,CAAC,eAAe,YAAY,IAAI,GAAG;AACrC,UAAM,IAAI,SAAS,qBAAqB,oDAAoD;AAAA,MAC1F,KAAK;AAAA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AA,QAKE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAsB,mBACpB,KACA,SACA,SACsB;AACtB,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,gBAAgB,KAAK,OAAO,GAAG;AACjC,UAAM,MAAM,iBAAiB,OAAO;AACpC,uBAAmB,KAAK,SAAS,cAAc;AAC/C,WAAO,EAAE,IAAI;AAAA,EACf;AACA,MAAI,QAAQ,KAAK,OAAO,GAAG;AACzB,UAAM,YAAY,MAAM,oBAAoB,SAAS,OAAO;AAC5D,QAAI,cAAc,MAAM;AACtB,YAAM,IAAI,SAAS,sBAAsB,kCAAkC,OAAO,KAAK;AAAA,QACrF,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAMA,UAAM,MAAM,iBAAiB,UAAU,GAAG;AAC1C,uBAAmB,KAAK,SAAS,sBAAsB;AACvD,WAAO,EAAE,KAAK,YAAY,QAAQ;AAAA,EACpC;AACA,QAAM,IAAI,SAAS,SAAS,6BAA6B,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,IAC9E,KAAK;AAAA,EACP,CAAC;AACH;","names":[]}
|
|
@@ -4,16 +4,17 @@ import {
|
|
|
4
4
|
} from "./chunk-UO22YNY4.js";
|
|
5
5
|
import {
|
|
6
6
|
PublishModeSchema,
|
|
7
|
+
SEND_MAX_UNSET,
|
|
7
8
|
loadRawConfig,
|
|
8
9
|
parseUsdToAtomic,
|
|
9
10
|
resolvePublishDefaultPrice,
|
|
10
11
|
resolvePublishMode,
|
|
11
12
|
resolveSettings
|
|
12
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-UYP7G3GZ.js";
|
|
13
14
|
import {
|
|
14
15
|
CliError,
|
|
15
16
|
external_exports
|
|
16
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-J6CVKC4M.js";
|
|
17
18
|
|
|
18
19
|
// src/lib/settings.ts
|
|
19
20
|
import { execFile } from "child_process";
|
|
@@ -27,6 +28,7 @@ async function resolveContextSettings(ctx) {
|
|
|
27
28
|
baseUrl: s.baseUrl.value,
|
|
28
29
|
rpcUrl: s.rpcUrl.value,
|
|
29
30
|
evalCohort: s.evalCohort.value,
|
|
31
|
+
sendMaxAmountAtomic: s.sendMaxAmount.value === SEND_MAX_UNSET ? SEND_MAX_UNSET : s.sendMaxAmount.value === "none" ? null : BigInt(s.sendMaxAmount.value),
|
|
30
32
|
policy: {
|
|
31
33
|
maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),
|
|
32
34
|
sessionBudgetAtomic: BigInt(s.sessionBudget.value),
|
|
@@ -157,4 +159,4 @@ export {
|
|
|
157
159
|
loadProjectConfig,
|
|
158
160
|
pathExists
|
|
159
161
|
};
|
|
160
|
-
//# sourceMappingURL=chunk-
|
|
162
|
+
//# sourceMappingURL=chunk-DAJ56EUU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type { Provenance, ProjectPublishLayer, PublishMode } from './config';\nimport { parseUsdToAtomic } from './money';\nimport { parseConfirmPolicy, type SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /**\n * Hard per-send cap for `tenjin send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n return {\n baseUrl: s.baseUrl.value,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: BigInt(s.sessionBudget.value),\n confirm: parseConfirmPolicy(s.confirm.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const homeDir = deps.homeDir ?? homedir();\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n const candidate = join(dir, PROJECT_CONFIG_FILE);\n if (await pathExists(candidate)) {\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n return candidate;\n }\n }\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). Shared with the candidate command's\n * repo-root walk so the two `.git`/file probes stay one implementation. */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err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T,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQ,QAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
commitLocalWallet,
|
|
4
|
+
createLocalWallet,
|
|
5
|
+
describeWallet,
|
|
6
|
+
parkOutgoingWallet,
|
|
7
|
+
prepareLocalWallet,
|
|
8
|
+
resolvePassphraseForCreate,
|
|
9
|
+
resolveWalletProvider,
|
|
10
|
+
restoreParkedWallet,
|
|
11
|
+
verifyAndPreserveOutgoingWallet
|
|
12
|
+
} from "./chunk-RGFBBNGP.js";
|
|
13
|
+
import {
|
|
14
|
+
walletExistsError,
|
|
15
|
+
walletFileExists
|
|
16
|
+
} from "./chunk-WRWCDLVK.js";
|
|
17
|
+
import {
|
|
18
|
+
LockTimeoutError,
|
|
19
|
+
withFileLock
|
|
20
|
+
} from "./chunk-YBMMV4Y4.js";
|
|
21
|
+
import {
|
|
22
|
+
loadRawConfig,
|
|
23
|
+
resolveSettings,
|
|
24
|
+
toMoney
|
|
25
|
+
} from "./chunk-UYP7G3GZ.js";
|
|
26
|
+
import {
|
|
27
|
+
CliError,
|
|
28
|
+
walletPath
|
|
29
|
+
} from "./chunk-J6CVKC4M.js";
|
|
30
|
+
import {
|
|
31
|
+
getUsdcBalance
|
|
32
|
+
} from "./chunk-MJZZTKCC.js";
|
|
33
|
+
|
|
34
|
+
// src/commands/wallet.ts
|
|
35
|
+
import { mkdir } from "fs/promises";
|
|
36
|
+
import { join } from "path";
|
|
37
|
+
var FUNDING_LINE = "Send USDC on Base. $5 covers ~50 typical resources.";
|
|
38
|
+
var KEY_STORAGE = "encrypted (keystore v3, scrypt)";
|
|
39
|
+
var isWindows = process.platform === "win32";
|
|
40
|
+
async function runWalletCreate(ctx, opts = {}) {
|
|
41
|
+
const {
|
|
42
|
+
address,
|
|
43
|
+
walletPath: path,
|
|
44
|
+
source,
|
|
45
|
+
replaced
|
|
46
|
+
} = await createWalletLocked(ctx.dataDir, opts);
|
|
47
|
+
const warnings = custodyWarnings();
|
|
48
|
+
return {
|
|
49
|
+
data: {
|
|
50
|
+
address,
|
|
51
|
+
walletPath: path,
|
|
52
|
+
provider: "local",
|
|
53
|
+
policyEnforcement: "client-only",
|
|
54
|
+
keyStorage: KEY_STORAGE,
|
|
55
|
+
passphraseSource: source,
|
|
56
|
+
...replaced !== void 0 ? {
|
|
57
|
+
replaced: {
|
|
58
|
+
address: replaced.address,
|
|
59
|
+
archivedWalletPath: replaced.archivedPath,
|
|
60
|
+
passphrasePreserved: replaced.passphraseLocation,
|
|
61
|
+
...replaced.unarchivedReason !== void 0 ? { unarchivedReason: replaced.unarchivedReason } : {}
|
|
62
|
+
}
|
|
63
|
+
} : {},
|
|
64
|
+
warnings
|
|
65
|
+
},
|
|
66
|
+
humanLines: [
|
|
67
|
+
`Wallet created: ${address}`,
|
|
68
|
+
`Key stored ${KEY_STORAGE}.`,
|
|
69
|
+
passphraseNote(source, address),
|
|
70
|
+
...replaced !== void 0 ? replacedNote(replaced, path) : [],
|
|
71
|
+
FUNDING_LINE,
|
|
72
|
+
...warnings
|
|
73
|
+
]
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function replacedNote(replaced, activeWalletPath) {
|
|
77
|
+
const passphraseLine = replaced.passphraseLocation === "store" ? `its passphrase is preserved in the OS credential store (service tenjin-cli, account ${replaced.account}).` : replaced.passphraseLocation === "env" ? "its passphrase is TENJIN_WALLET_PASSPHRASE \u2014 keep that value." : replaced.unarchivedReason === "rejected-characters" ? "its passphrase was NOT archived: the macOS keychain writer only stores machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it." : replaced.unarchivedReason === "no-store" ? "its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it." : "its passphrase was NOT archived: the OS credential store write failed. It exists only where you keep it.";
|
|
78
|
+
return [
|
|
79
|
+
`Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,
|
|
80
|
+
`Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,
|
|
81
|
+
`To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \`mv ${replaced.archivedPath} ${activeWalletPath}\`.`
|
|
82
|
+
];
|
|
83
|
+
}
|
|
84
|
+
async function createWalletLocked(dir, opts) {
|
|
85
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
86
|
+
const lockPath = join(dir, "wallet.create.lock");
|
|
87
|
+
try {
|
|
88
|
+
return await withFileLock(lockPath, async () => {
|
|
89
|
+
let source = "env";
|
|
90
|
+
const passphraseFor = async (forAddress) => {
|
|
91
|
+
const resolved = await resolvePassphraseForCreate(
|
|
92
|
+
{ env: process.env, dir, ...opts.passphrase },
|
|
93
|
+
forAddress
|
|
94
|
+
);
|
|
95
|
+
source = resolved.source;
|
|
96
|
+
return resolved.passphrase;
|
|
97
|
+
};
|
|
98
|
+
if (!await walletFileExists(dir)) {
|
|
99
|
+
const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);
|
|
100
|
+
return { address, walletPath: path, source };
|
|
101
|
+
}
|
|
102
|
+
if (opts.replace !== true) throw walletExistsError(dir);
|
|
103
|
+
const preserved = await verifyAndPreserveOutgoingWallet({
|
|
104
|
+
dir,
|
|
105
|
+
env: process.env,
|
|
106
|
+
...opts.passphrase !== void 0 ? { passphrase: opts.passphrase } : {}
|
|
107
|
+
});
|
|
108
|
+
const prepared = await prepareLocalWallet(passphraseFor);
|
|
109
|
+
const archivedPath = await parkOutgoingWallet(dir, preserved.account);
|
|
110
|
+
try {
|
|
111
|
+
const { address, walletPath: path } = await commitLocalWallet(dir, prepared);
|
|
112
|
+
return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };
|
|
113
|
+
} catch (err) {
|
|
114
|
+
try {
|
|
115
|
+
await restoreParkedWallet(dir, archivedPath);
|
|
116
|
+
} catch (restoreErr) {
|
|
117
|
+
throw new CliError(
|
|
118
|
+
"INTERNAL",
|
|
119
|
+
"Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.",
|
|
120
|
+
{
|
|
121
|
+
fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it \u2014 move it aside first. Then restore with \`mv ${archivedPath} ${walletPath(dir)}\`.`,
|
|
122
|
+
cause: restoreErr
|
|
123
|
+
}
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
throw new CliError(
|
|
127
|
+
"INTERNAL",
|
|
128
|
+
"Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.",
|
|
129
|
+
{
|
|
130
|
+
fix: "Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.",
|
|
131
|
+
cause: err
|
|
132
|
+
}
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
} catch (err) {
|
|
137
|
+
if (err instanceof LockTimeoutError) {
|
|
138
|
+
throw new CliError("INTERNAL", err.message, {
|
|
139
|
+
fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
|
|
140
|
+
cause: err
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
throw err;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function passphraseNote(source, address) {
|
|
147
|
+
const account = address.toLowerCase();
|
|
148
|
+
switch (source) {
|
|
149
|
+
case "keychain":
|
|
150
|
+
return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;
|
|
151
|
+
case "dpapi":
|
|
152
|
+
return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;
|
|
153
|
+
case "secret-service":
|
|
154
|
+
return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;
|
|
155
|
+
case "env":
|
|
156
|
+
return "Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.";
|
|
157
|
+
case "prompt":
|
|
158
|
+
return "Remember your passphrase: it is required to sign and cannot be recovered.";
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async function runWalletShow(ctx, opts = {}) {
|
|
162
|
+
const provider = resolveWalletProvider(ctx, opts);
|
|
163
|
+
const desc = await describeWallet(provider);
|
|
164
|
+
const {
|
|
165
|
+
walletPath: path,
|
|
166
|
+
keyStorage,
|
|
167
|
+
passphraseSource,
|
|
168
|
+
archivedWallets,
|
|
169
|
+
warnings
|
|
170
|
+
} = await provider.diagnostics();
|
|
171
|
+
const humanLines = [`Address: ${desc.address}`, `Key source: ${desc.credentialSource}`];
|
|
172
|
+
if (keyStorage !== void 0) humanLines.push(`Key storage: ${keyStorage}`);
|
|
173
|
+
if (passphraseSource !== void 0) humanLines.push(`Passphrase: ${passphraseSource}`);
|
|
174
|
+
if (archivedWallets !== void 0 && archivedWallets.length > 0) {
|
|
175
|
+
humanLines.push(
|
|
176
|
+
`Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(", ")}`
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
humanLines.push(...warnings);
|
|
180
|
+
return {
|
|
181
|
+
data: {
|
|
182
|
+
address: desc.address,
|
|
183
|
+
provider: desc.provider,
|
|
184
|
+
credentialSource: desc.credentialSource,
|
|
185
|
+
policyEnforcement: desc.policyEnforcement,
|
|
186
|
+
...path !== void 0 ? { walletPath: path } : {},
|
|
187
|
+
...keyStorage !== void 0 ? { keyStorage } : {},
|
|
188
|
+
...passphraseSource !== void 0 ? { passphraseSource } : {},
|
|
189
|
+
...archivedWallets !== void 0 && archivedWallets.length > 0 ? { archivedWallets } : {},
|
|
190
|
+
warnings
|
|
191
|
+
},
|
|
192
|
+
humanLines
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
async function runWalletBalance(ctx, opts = {}) {
|
|
196
|
+
const provider = resolveWalletProvider(ctx, opts);
|
|
197
|
+
const desc = await describeWallet(provider);
|
|
198
|
+
const config = await loadRawConfig(ctx.dataDir);
|
|
199
|
+
const rpcUrl = resolveSettings({
|
|
200
|
+
config,
|
|
201
|
+
flags: { baseUrl: ctx.flags.baseUrl },
|
|
202
|
+
env: process.env
|
|
203
|
+
}).rpcUrl.value;
|
|
204
|
+
let atomic;
|
|
205
|
+
try {
|
|
206
|
+
atomic = await getUsdcBalance(desc.address, rpcUrl);
|
|
207
|
+
} catch (err) {
|
|
208
|
+
throw new CliError("RPC_ERROR", `Could not read the USDC balance from ${rpcUrl}.`, {
|
|
209
|
+
fix: "Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.",
|
|
210
|
+
cause: err
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
const balance = toMoney(atomic.toString());
|
|
214
|
+
return {
|
|
215
|
+
data: { address: desc.address, balance },
|
|
216
|
+
humanLines: [`Balance: ${balance.usd} USDC on Base`]
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function custodyWarnings() {
|
|
220
|
+
const warnings = [];
|
|
221
|
+
if (hasEnvKey()) {
|
|
222
|
+
warnings.push("TENJIN_WALLET_KEY is set and shadows this file at runtime.");
|
|
223
|
+
}
|
|
224
|
+
if (isWindows) {
|
|
225
|
+
warnings.push("File permissions are not enforced on Windows; the key file is not restricted.");
|
|
226
|
+
}
|
|
227
|
+
return warnings;
|
|
228
|
+
}
|
|
229
|
+
function hasEnvKey() {
|
|
230
|
+
const envKey = process.env.TENJIN_WALLET_KEY;
|
|
231
|
+
return envKey !== void 0 && envKey.length > 0;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export {
|
|
235
|
+
runWalletCreate,
|
|
236
|
+
runWalletShow,
|
|
237
|
+
runWalletBalance
|
|
238
|
+
};
|
|
239
|
+
//# sourceMappingURL=chunk-DH6D6QIO.js.map
|