tenjin-cli 0.1.0-alpha.5 → 0.1.0-alpha.8
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 +169 -199
- package/dist/{buy-YMXXVNFH.js → buy-K2G6XQY2.js} +20 -18
- package/dist/{candidate-H7FR4AU5.js → candidate-DJB2NNTG.js} +7 -8
- package/dist/{chunk-ZW3B5LWX.js → chunk-2YX6LTCD.js} +5 -5
- package/dist/{chunk-4WVKXKDK.js → chunk-6OE2IJMH.js} +29 -238
- package/dist/chunk-6OE2IJMH.js.map +1 -0
- package/dist/{chunk-ADJYSM45.js → chunk-6ZBZCBR7.js} +27 -13
- package/dist/chunk-6ZBZCBR7.js.map +1 -0
- package/dist/{chunk-HTDALK7M.js → chunk-B7YB4MMU.js} +15 -12
- package/dist/{chunk-HTDALK7M.js.map → chunk-B7YB4MMU.js.map} +1 -1
- package/dist/{chunk-NFSOVL3C.js → chunk-BBUYCDSG.js} +12 -3
- package/dist/chunk-BBUYCDSG.js.map +1 -0
- package/dist/chunk-C3S6725N.js +337 -0
- package/dist/chunk-C3S6725N.js.map +1 -0
- package/dist/chunk-CYRYVZPN.js +213 -0
- package/dist/chunk-CYRYVZPN.js.map +1 -0
- package/dist/{chunk-MDDGEGSW.js → chunk-DAJ56EUU.js} +3 -3
- package/dist/{chunk-IOPWPMT2.js → chunk-DH6D6QIO.js} +5 -5
- package/dist/{chunk-NJF2WENW.js → chunk-DQDGBWWH.js} +4 -2
- package/dist/chunk-DQDGBWWH.js.map +1 -0
- package/dist/chunk-EDENZN2Q.js +614 -0
- package/dist/chunk-EDENZN2Q.js.map +1 -0
- package/dist/chunk-GABYDXWL.js +190 -0
- package/dist/chunk-GABYDXWL.js.map +1 -0
- package/dist/{chunk-LAM66WFJ.js → chunk-GM4RZUVU.js} +6 -8
- package/dist/{chunk-LAM66WFJ.js.map → chunk-GM4RZUVU.js.map} +1 -1
- package/dist/{chunk-PAUXMRSF.js → chunk-J6CVKC4M.js} +73 -2
- package/dist/chunk-J6CVKC4M.js.map +1 -0
- package/dist/chunk-L6AV2Q73.js +105 -0
- package/dist/chunk-L6AV2Q73.js.map +1 -0
- package/dist/{chunk-PYNSGYBE.js → chunk-NVHQCTIC.js} +249 -552
- package/dist/chunk-NVHQCTIC.js.map +1 -0
- package/dist/{chunk-CVX6JNGD.js → chunk-OTDI5FXG.js} +3 -5
- package/dist/{chunk-CVX6JNGD.js.map → chunk-OTDI5FXG.js.map} +1 -1
- package/dist/{chunk-3IRDP7TN.js → chunk-P3FBESBB.js} +6 -4
- package/dist/{chunk-3IRDP7TN.js.map → chunk-P3FBESBB.js.map} +1 -1
- package/dist/{chunk-FU6MCSLG.js → chunk-PCLPVJ3J.js} +16 -78
- package/dist/chunk-PCLPVJ3J.js.map +1 -0
- package/dist/chunk-QB2NNV6C.js +143 -0
- package/dist/chunk-QB2NNV6C.js.map +1 -0
- package/dist/{chunk-C444K6MI.js → chunk-RGFBBNGP.js} +42 -17
- package/dist/{chunk-C444K6MI.js.map → chunk-RGFBBNGP.js.map} +1 -1
- package/dist/{chunk-TXPPMK4L.js → chunk-RGTTACP3.js} +5 -5
- package/dist/chunk-SGK2B724.js +67 -0
- package/dist/chunk-SGK2B724.js.map +1 -0
- package/dist/{chunk-ZDY2KY5X.js → chunk-URSGGRO4.js} +28 -11
- package/dist/chunk-URSGGRO4.js.map +1 -0
- package/dist/{chunk-5SCU253N.js → chunk-UYP7G3GZ.js} +2 -2
- package/dist/{chunk-ZIYVN4CD.js → chunk-VZ3AJCO5.js} +3 -5
- package/dist/{chunk-ZIYVN4CD.js.map → chunk-VZ3AJCO5.js.map} +1 -1
- package/dist/{chunk-QONTBYQW.js → chunk-WRWCDLVK.js} +4 -6
- package/dist/{chunk-QONTBYQW.js.map → chunk-WRWCDLVK.js.map} +1 -1
- package/dist/chunk-XBJ3VLWX.js +35 -0
- package/dist/chunk-XBJ3VLWX.js.map +1 -0
- package/dist/{chunk-RTJLLPFA.js → chunk-XFHZWORF.js} +123 -24
- package/dist/chunk-XFHZWORF.js.map +1 -0
- package/dist/{chunk-BIKAUVC2.js → chunk-ZA3RFDAV.js} +40 -6
- package/dist/chunk-ZA3RFDAV.js.map +1 -0
- package/dist/{cli-IW76QTN3.js → cli-KNCYWMAG.js} +237 -25
- package/dist/cli-KNCYWMAG.js.map +1 -0
- package/dist/{config-VCOS7P5K.js → config-SAQEQRFB.js} +5 -6
- package/dist/dist-U4M6QCKE.js +2842 -0
- package/dist/dist-U4M6QCKE.js.map +1 -0
- package/dist/{doctor-WS65JG3V.js → doctor-FBRQNOUQ.js} +10 -9
- package/dist/{publish-DSFWQRUN.js → edit-IZZ2HIMR.js} +20 -18
- package/dist/index.js +1 -1
- package/dist/{inspect-SFJWUQHO.js → inspect-BFWZ5XOP.js} +17 -16
- package/dist/{install-RVPQPCKH.js → install-QXZCHIBT.js} +400 -166
- package/dist/install-QXZCHIBT.js.map +1 -0
- package/dist/outcome-VXCBEGNC.js +20 -0
- package/dist/publish-5NTCRF2V.js +40 -0
- package/dist/read-T6OTMU72.js +158 -0
- package/dist/read-T6OTMU72.js.map +1 -0
- package/dist/{run-OMPKA43G.js → run-5OGX64IY.js} +106 -32
- package/dist/{run-OMPKA43G.js.map → run-5OGX64IY.js.map} +1 -1
- package/dist/search-LIIWUMWV.js +24 -0
- package/dist/{send-3G4C64HJ.js → send-ENE47KQE.js} +7 -7
- package/dist/session-HY4QIWHV.js +87 -0
- package/dist/session-HY4QIWHV.js.map +1 -0
- package/dist/{wallet-PP22LAX7.js → wallet-OCCGEH6H.js} +7 -7
- package/dist/{wallet-B7KJS2R5.js → wallet-RBDVNZVR.js} +5 -5
- package/dist/wallet-RBDVNZVR.js.map +1 -0
- package/docs/agent-permissions.md +255 -0
- package/package.json +3 -1
- package/skills/tenjin/SKILL.md +57 -13
- package/skills/tenjin-publish/SKILL.md +12 -4
- package/skills/tenjin-search/SKILL.md +68 -12
- package/dist/chunk-2JQ5JSG6.js +0 -68
- package/dist/chunk-2JQ5JSG6.js.map +0 -1
- package/dist/chunk-4WVKXKDK.js.map +0 -1
- package/dist/chunk-ADJYSM45.js.map +0 -1
- package/dist/chunk-BIKAUVC2.js.map +0 -1
- package/dist/chunk-FU6MCSLG.js.map +0 -1
- package/dist/chunk-L4IHCN6B.js +0 -63
- package/dist/chunk-L4IHCN6B.js.map +0 -1
- package/dist/chunk-NFSOVL3C.js.map +0 -1
- package/dist/chunk-NJF2WENW.js.map +0 -1
- package/dist/chunk-PAUXMRSF.js.map +0 -1
- package/dist/chunk-PYNSGYBE.js.map +0 -1
- package/dist/chunk-RTJLLPFA.js.map +0 -1
- package/dist/chunk-ZDY2KY5X.js.map +0 -1
- package/dist/cli-IW76QTN3.js.map +0 -1
- package/dist/install-RVPQPCKH.js.map +0 -1
- package/dist/outcome-GNYCSZ7J.js +0 -20
- package/dist/search-KOI6Y7P6.js +0 -24
- /package/dist/{buy-YMXXVNFH.js.map → buy-K2G6XQY2.js.map} +0 -0
- /package/dist/{candidate-H7FR4AU5.js.map → candidate-DJB2NNTG.js.map} +0 -0
- /package/dist/{chunk-ZW3B5LWX.js.map → chunk-2YX6LTCD.js.map} +0 -0
- /package/dist/{chunk-MDDGEGSW.js.map → chunk-DAJ56EUU.js.map} +0 -0
- /package/dist/{chunk-IOPWPMT2.js.map → chunk-DH6D6QIO.js.map} +0 -0
- /package/dist/{chunk-TXPPMK4L.js.map → chunk-RGTTACP3.js.map} +0 -0
- /package/dist/{chunk-5SCU253N.js.map → chunk-UYP7G3GZ.js.map} +0 -0
- /package/dist/{config-VCOS7P5K.js.map → config-SAQEQRFB.js.map} +0 -0
- /package/dist/{doctor-WS65JG3V.js.map → doctor-FBRQNOUQ.js.map} +0 -0
- /package/dist/{inspect-SFJWUQHO.js.map → edit-IZZ2HIMR.js.map} +0 -0
- /package/dist/{outcome-GNYCSZ7J.js.map → inspect-BFWZ5XOP.js.map} +0 -0
- /package/dist/{publish-DSFWQRUN.js.map → outcome-VXCBEGNC.js.map} +0 -0
- /package/dist/{search-KOI6Y7P6.js.map → publish-5NTCRF2V.js.map} +0 -0
- /package/dist/{wallet-B7KJS2R5.js.map → search-LIIWUMWV.js.map} +0 -0
- /package/dist/{send-3G4C64HJ.js.map → send-ENE47KQE.js.map} +0 -0
- /package/dist/{wallet-PP22LAX7.js.map → wallet-OCCGEH6H.js.map} +0 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
headingOutline
|
|
4
|
+
} from "./chunk-SGK2B724.js";
|
|
5
|
+
import {
|
|
6
|
+
PUBLISH_STATUSES,
|
|
7
|
+
dedupeFindings,
|
|
8
|
+
deriveCard,
|
|
9
|
+
deriveProjectMarkers,
|
|
10
|
+
describeFindings,
|
|
11
|
+
localCardEligibility,
|
|
12
|
+
missingSentences,
|
|
13
|
+
needsConfirmation,
|
|
14
|
+
parseAppliesToFlags,
|
|
15
|
+
parseFrontmatter,
|
|
16
|
+
publicFinding,
|
|
17
|
+
publishPost,
|
|
18
|
+
resolveWriteAuth,
|
|
19
|
+
scan,
|
|
20
|
+
writeModeNotices
|
|
21
|
+
} from "./chunk-NVHQCTIC.js";
|
|
22
|
+
import {
|
|
23
|
+
describeWallet,
|
|
24
|
+
resolveWalletProvider
|
|
25
|
+
} from "./chunk-RGFBBNGP.js";
|
|
26
|
+
import {
|
|
27
|
+
dropCandidate,
|
|
28
|
+
readCandidate
|
|
29
|
+
} from "./chunk-VZ3AJCO5.js";
|
|
30
|
+
import {
|
|
31
|
+
UUID_RE
|
|
32
|
+
} from "./chunk-WWX32ML4.js";
|
|
33
|
+
import {
|
|
34
|
+
trimSlash
|
|
35
|
+
} from "./chunk-XBJ3VLWX.js";
|
|
36
|
+
import {
|
|
37
|
+
sanitizeForTerminal
|
|
38
|
+
} from "./chunk-BBUYCDSG.js";
|
|
39
|
+
import {
|
|
40
|
+
resolveContextSettings,
|
|
41
|
+
resolvePublishSettings
|
|
42
|
+
} from "./chunk-DAJ56EUU.js";
|
|
43
|
+
import {
|
|
44
|
+
parsePublishModeFlag,
|
|
45
|
+
parseUsdToAtomic,
|
|
46
|
+
toMoney
|
|
47
|
+
} from "./chunk-UYP7G3GZ.js";
|
|
48
|
+
import {
|
|
49
|
+
CliError
|
|
50
|
+
} from "./chunk-J6CVKC4M.js";
|
|
51
|
+
|
|
52
|
+
// src/commands/publish.ts
|
|
53
|
+
import { readFile } from "fs/promises";
|
|
54
|
+
import { dirname, resolve } from "path";
|
|
55
|
+
async function runPublish(args, ctx, deps = {}) {
|
|
56
|
+
const env = deps.env ?? process.env;
|
|
57
|
+
const cwd = deps.cwd ?? process.cwd();
|
|
58
|
+
if (args.mode !== void 0) parsePublishModeFlag(args.mode, "--mode");
|
|
59
|
+
const { raw, candidate } = await resolveSource(args, ctx.dataDir);
|
|
60
|
+
const { frontmatter, body } = parseFrontmatter(raw);
|
|
61
|
+
const status = resolveStatus(args, frontmatter);
|
|
62
|
+
const title = resolveTitle(frontmatter, body);
|
|
63
|
+
const tags = resolveTags(frontmatter);
|
|
64
|
+
const excerpt = expectString(frontmatter, "excerpt");
|
|
65
|
+
const handle = expectString(frontmatter, "handle");
|
|
66
|
+
const cardFlags = cardFlagsFrom(args);
|
|
67
|
+
if (candidate?.meta.question !== void 0 && cardFlags.question === void 0 && frontmatter.questionsAnswered === void 0) {
|
|
68
|
+
cardFlags.question = [candidate.meta.question];
|
|
69
|
+
}
|
|
70
|
+
const card = deriveCard(frontmatter, cardFlags);
|
|
71
|
+
const settings = await resolvePublishSettings({
|
|
72
|
+
dataDir: ctx.dataDir,
|
|
73
|
+
cwd,
|
|
74
|
+
...args.mode !== void 0 ? { flag: args.mode } : {},
|
|
75
|
+
env
|
|
76
|
+
});
|
|
77
|
+
writeModeNotices(
|
|
78
|
+
ctx.io.stderr,
|
|
79
|
+
settings,
|
|
80
|
+
env,
|
|
81
|
+
"each publish asks you once. Set auto to publish clean scans automatically"
|
|
82
|
+
);
|
|
83
|
+
const priceAtomic = resolvePrice(args, frontmatter, settings.defaultPriceAtomic);
|
|
84
|
+
const markerRoot = candidate !== void 0 ? candidate.meta.sourceProject : args.file !== void 0 ? dirname(resolve(cwd, args.file)) : cwd;
|
|
85
|
+
const scanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };
|
|
86
|
+
const findings = dedupeFindings([
|
|
87
|
+
...scan(raw, scanContext),
|
|
88
|
+
...scan(cardScanText(card), scanContext)
|
|
89
|
+
]);
|
|
90
|
+
const blocking = findings.filter((f) => f.severity === "block");
|
|
91
|
+
const warns = findings.filter((f) => f.severity === "warn");
|
|
92
|
+
const eligibility = localCardEligibility(card);
|
|
93
|
+
const price = toMoney(priceAtomic);
|
|
94
|
+
if (blocking.length > 0) {
|
|
95
|
+
throw new CliError("PUBLISH_BLOCKED", blockMessage(blocking), {
|
|
96
|
+
fix: "Remove the secret from the file (it is never masked away by --yes), then re-run.",
|
|
97
|
+
details: {
|
|
98
|
+
mode: settings.mode,
|
|
99
|
+
findings: blocking.map(publicFinding),
|
|
100
|
+
price: { atomic: price.atomic, usd: price.usd }
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {
|
|
105
|
+
throw new CliError("NEEDS_CONFIRMATION", confirmMessage(warns.length, price.usd), {
|
|
106
|
+
fix: "Review the findings, then re-run with --yes (or resolve the source and re-run).",
|
|
107
|
+
details: {
|
|
108
|
+
mode: settings.mode,
|
|
109
|
+
price: { atomic: price.atomic, usd: price.usd },
|
|
110
|
+
findings: warns.map(publicFinding),
|
|
111
|
+
card: eligibility,
|
|
112
|
+
target: { status, titlePreview: sanitizeForTerminal(title ?? "(untitled draft)") }
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const runtime = await resolveContextSettings(ctx);
|
|
117
|
+
const provider = resolveWalletProvider(
|
|
118
|
+
ctx,
|
|
119
|
+
deps.provider !== void 0 ? { provider: deps.provider } : {}
|
|
120
|
+
);
|
|
121
|
+
await describeWallet(provider);
|
|
122
|
+
const signer = await provider.getSigner();
|
|
123
|
+
const auth = resolveWriteAuth({
|
|
124
|
+
signer,
|
|
125
|
+
baseUrl: runtime.baseUrl,
|
|
126
|
+
dataDir: ctx.dataDir,
|
|
127
|
+
// A publish always writes.
|
|
128
|
+
scope: "read+write",
|
|
129
|
+
...deps.useSession !== void 0 ? { useSession: deps.useSession } : {},
|
|
130
|
+
env
|
|
131
|
+
});
|
|
132
|
+
const input = {
|
|
133
|
+
...title !== void 0 ? { title } : {},
|
|
134
|
+
bodyMd: body,
|
|
135
|
+
...excerpt !== void 0 ? { excerpt } : {},
|
|
136
|
+
...tags !== void 0 ? { tags } : {},
|
|
137
|
+
priceAtomic,
|
|
138
|
+
...handle !== void 0 ? { handle } : {},
|
|
139
|
+
status,
|
|
140
|
+
...card !== void 0 ? { resource: card } : {}
|
|
141
|
+
};
|
|
142
|
+
const result = await publishPost(input, auth, {
|
|
143
|
+
baseUrl: runtime.baseUrl,
|
|
144
|
+
timeoutMs: ctx.flags.timeout,
|
|
145
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
|
|
146
|
+
});
|
|
147
|
+
const candidateInfo = candidate !== void 0 ? await clearPublishedCandidate(ctx, candidate.id) : void 0;
|
|
148
|
+
return receipt(result, runtime.baseUrl, candidateInfo);
|
|
149
|
+
}
|
|
150
|
+
async function clearPublishedCandidate(ctx, id) {
|
|
151
|
+
try {
|
|
152
|
+
if (await dropCandidate(ctx.dataDir, id)) return { id, cleared: true };
|
|
153
|
+
const warning = `Published, but candidate ${id} was already gone; nothing to clear.`;
|
|
154
|
+
ctx.io.stderr.write(`${warning}
|
|
155
|
+
`);
|
|
156
|
+
return { id, cleared: false, warning };
|
|
157
|
+
} catch (err) {
|
|
158
|
+
const warning = `Published successfully, but could not clear candidate ${id}: ${errorMessage(err)}. Remove it with \`tenjin candidate drop ${id}\`.`;
|
|
159
|
+
ctx.io.stderr.write(`${warning}
|
|
160
|
+
`);
|
|
161
|
+
return { id, cleared: false, warning };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function errorMessage(err) {
|
|
165
|
+
return err instanceof Error ? err.message : String(err);
|
|
166
|
+
}
|
|
167
|
+
async function resolveSource(args, dataDir) {
|
|
168
|
+
if (args.candidate !== void 0) {
|
|
169
|
+
if (args.file !== void 0) {
|
|
170
|
+
throw new CliError("USAGE", "Pass EITHER a file or --candidate, not both.", {
|
|
171
|
+
fix: "Publish a file with `tenjin publish post.md`, or a candidate with `--candidate <id>`."
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
if (!UUID_RE.test(args.candidate)) {
|
|
175
|
+
throw new CliError("USAGE", `Invalid candidate id: ${JSON.stringify(args.candidate)}`, {
|
|
176
|
+
fix: "Pass a candidate id from `tenjin candidate list`."
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const record = await readCandidate(dataDir, args.candidate);
|
|
180
|
+
if (record === null) {
|
|
181
|
+
throw new CliError("USAGE", `Unknown candidate: ${JSON.stringify(args.candidate)}`, {
|
|
182
|
+
fix: "List parked candidates with `tenjin candidate list`."
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return { raw: await readDraft(record), candidate: record };
|
|
186
|
+
}
|
|
187
|
+
if (args.file === void 0) {
|
|
188
|
+
throw new CliError("USAGE", "Nothing to publish.", {
|
|
189
|
+
fix: "Pass a Markdown file (`tenjin publish post.md`) or `--candidate <id>`."
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
return { raw: await readMarkdown(args.file) };
|
|
193
|
+
}
|
|
194
|
+
async function readDraft(record) {
|
|
195
|
+
try {
|
|
196
|
+
return await readFile(record.draftPath, "utf8");
|
|
197
|
+
} catch (err) {
|
|
198
|
+
throw new CliError("INTERNAL", `Candidate ${record.id} is missing its draft.`, {
|
|
199
|
+
fix: `Drop it with \`tenjin candidate drop ${record.id}\` and re-add the draft.`,
|
|
200
|
+
cause: err
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function receipt(result, baseUrl, candidateInfo) {
|
|
205
|
+
const price = toMoney(result.priceAtomic);
|
|
206
|
+
const missing = missingSentences(result.cacheEligibleMissing).map(sanitizeForTerminal);
|
|
207
|
+
const cacheEligible = result.cacheEligible ?? false;
|
|
208
|
+
const deskUrl = `${trimSlash(baseUrl)}/desk`;
|
|
209
|
+
const title = sanitizeForTerminal(result.title);
|
|
210
|
+
const human = [
|
|
211
|
+
`Published ${title} (${sanitizeForTerminal(result.status)}) for ${price.usd} USD \u2192 ${sanitizeForTerminal(result.url)}`,
|
|
212
|
+
cacheEligible ? "Answer card is search-eligible." : missing.length > 0 ? `Answer card not search-eligible yet: ${missing.join(" ")}` : "Published as a browse-only document (no answer card).",
|
|
213
|
+
...candidateInfo?.cleared === true ? [`Cleared candidate ${candidateInfo.id}.`] : [],
|
|
214
|
+
...result.warnings.map((w) => `warning: ${sanitizeForTerminal(w)}`)
|
|
215
|
+
];
|
|
216
|
+
return {
|
|
217
|
+
data: {
|
|
218
|
+
resourceId: result.resourceId,
|
|
219
|
+
url: result.url,
|
|
220
|
+
status: result.status,
|
|
221
|
+
price,
|
|
222
|
+
cacheEligible,
|
|
223
|
+
missing,
|
|
224
|
+
deskUrl,
|
|
225
|
+
...candidateInfo !== void 0 ? { candidate: candidateInfo } : {},
|
|
226
|
+
...result.warnings.length > 0 ? { warnings: result.warnings } : {}
|
|
227
|
+
},
|
|
228
|
+
humanLines: human
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
async function readMarkdown(file) {
|
|
232
|
+
try {
|
|
233
|
+
return await readFile(file, "utf8");
|
|
234
|
+
} catch (err) {
|
|
235
|
+
throw new CliError("USAGE", `Could not read ${JSON.stringify(file)}`, {
|
|
236
|
+
fix: "Pass a path to a readable Markdown file, e.g. `tenjin publish post.md`.",
|
|
237
|
+
cause: err
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function resolveStatus(args, frontmatter) {
|
|
242
|
+
if (args.draft === true) return "draft";
|
|
243
|
+
const fm = frontmatter.status;
|
|
244
|
+
if (fm === void 0) return "published";
|
|
245
|
+
if (typeof fm !== "string" || !PUBLISH_STATUSES.includes(fm)) {
|
|
246
|
+
throw new CliError("USAGE", `Invalid status ${JSON.stringify(fm)} in frontmatter.`, {
|
|
247
|
+
fix: "Use status: draft | published | unlisted, or pass --draft."
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
return fm;
|
|
251
|
+
}
|
|
252
|
+
function resolveTitle(frontmatter, body) {
|
|
253
|
+
const fm = frontmatter.title;
|
|
254
|
+
if (fm !== void 0) {
|
|
255
|
+
if (typeof fm !== "string") {
|
|
256
|
+
throw new CliError("USAGE", "frontmatter title must be a single string.");
|
|
257
|
+
}
|
|
258
|
+
return fm.trim();
|
|
259
|
+
}
|
|
260
|
+
const headings = headingOutline(body);
|
|
261
|
+
const h1 = headings.find((h) => h.level === 1) ?? headings[0];
|
|
262
|
+
return h1?.text;
|
|
263
|
+
}
|
|
264
|
+
function resolveTags(frontmatter) {
|
|
265
|
+
const fm = frontmatter.tags;
|
|
266
|
+
if (fm === void 0) return void 0;
|
|
267
|
+
if (typeof fm === "string") return [fm];
|
|
268
|
+
if (Array.isArray(fm)) return fm;
|
|
269
|
+
throw new CliError("USAGE", "frontmatter tags must be a list of strings.");
|
|
270
|
+
}
|
|
271
|
+
function expectString(frontmatter, key) {
|
|
272
|
+
const fm = frontmatter[key];
|
|
273
|
+
if (fm === void 0) return void 0;
|
|
274
|
+
if (typeof fm !== "string") {
|
|
275
|
+
throw new CliError("USAGE", `frontmatter ${key} must be a single string.`);
|
|
276
|
+
}
|
|
277
|
+
return fm;
|
|
278
|
+
}
|
|
279
|
+
function resolvePrice(args, frontmatter, defaultAtomic) {
|
|
280
|
+
if (args.price !== void 0) return parseUsdToAtomic(args.price);
|
|
281
|
+
const fm = frontmatter.price;
|
|
282
|
+
if (fm !== void 0) {
|
|
283
|
+
if (typeof fm !== "string") {
|
|
284
|
+
throw new CliError("USAGE", 'frontmatter price must be a decimal-USD string, e.g. "0.10".');
|
|
285
|
+
}
|
|
286
|
+
return parseUsdToAtomic(fm);
|
|
287
|
+
}
|
|
288
|
+
return defaultAtomic;
|
|
289
|
+
}
|
|
290
|
+
function cardFlagsFrom(args) {
|
|
291
|
+
return {
|
|
292
|
+
...args.question !== void 0 && args.question.length > 0 ? { question: args.question } : {},
|
|
293
|
+
...args.task !== void 0 && args.task.length > 0 ? { task: args.task } : {},
|
|
294
|
+
...args.scope !== void 0 ? { scope: args.scope } : {},
|
|
295
|
+
...args.exclusions !== void 0 ? { exclusions: args.exclusions } : {},
|
|
296
|
+
...args.asOf !== void 0 ? { asOf: args.asOf } : {},
|
|
297
|
+
...args.validUntil !== void 0 ? { validUntil: args.validUntil } : {},
|
|
298
|
+
...args.artifactType !== void 0 ? { artifactType: args.artifactType } : {},
|
|
299
|
+
...args.temporalMode !== void 0 ? { temporalMode: args.temporalMode } : {},
|
|
300
|
+
...args.provenance !== void 0 ? { provenance: args.provenance } : {},
|
|
301
|
+
...args.methodology !== void 0 ? { methodology: args.methodology } : {},
|
|
302
|
+
...args.appliesTo !== void 0 && args.appliesTo.length > 0 ? { appliesTo: parseAppliesToFlags(args.appliesTo) } : {}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
function cardScanText(card) {
|
|
306
|
+
if (card === void 0) return "";
|
|
307
|
+
const parts = [];
|
|
308
|
+
const add = (v) => {
|
|
309
|
+
if (v !== void 0) parts.push(v);
|
|
310
|
+
};
|
|
311
|
+
add(card.scope);
|
|
312
|
+
add(card.exclusions);
|
|
313
|
+
add(card.provenanceSummary);
|
|
314
|
+
add(card.methodologySummary);
|
|
315
|
+
add(card.mediaType);
|
|
316
|
+
add(card.maintenanceCadence);
|
|
317
|
+
add(card.asOf);
|
|
318
|
+
add(card.validUntil);
|
|
319
|
+
add(card.estimatedPaidInputCost);
|
|
320
|
+
if (card.questionsAnswered !== void 0) parts.push(...card.questionsAnswered);
|
|
321
|
+
if (card.tasksSupported !== void 0) parts.push(...card.tasksSupported);
|
|
322
|
+
if (card.appliesTo !== void 0) {
|
|
323
|
+
for (const values of Object.values(card.appliesTo)) parts.push(...values);
|
|
324
|
+
}
|
|
325
|
+
return parts.join("\n");
|
|
326
|
+
}
|
|
327
|
+
function blockMessage(blocking) {
|
|
328
|
+
return `Publish blocked: the file contains ${describeFindings(blocking)}.`;
|
|
329
|
+
}
|
|
330
|
+
function confirmMessage(warnCount, priceUsd) {
|
|
331
|
+
return warnCount > 0 ? `Publish needs confirmation: ${warnCount} finding(s), price $${priceUsd}.` : `Publish needs confirmation: price $${priceUsd}.`;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export {
|
|
335
|
+
runPublish
|
|
336
|
+
};
|
|
337
|
+
//# sourceMappingURL=chunk-C3S6725N.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/publish.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { resolveContextSettings, resolvePublishSettings } from '../lib/settings';\nimport { parsePublishModeFlag } from '../lib/config';\nimport { readCandidate, dropCandidate, type CandidateRecord } from '../lib/candidate-store';\nimport { UUID_RE } from '../lib/ids';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { headingOutline } from '../lib/markdown';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { trimSlash } from '../lib/url';\nimport {\n deriveCard,\n localCardEligibility,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type Frontmatter,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n publishPost,\n PUBLISH_STATUSES,\n type PublishInput,\n type PublishStatus,\n} from '../lib/posts-api';\nimport {\n dedupeFindings,\n describeFindings,\n needsConfirmation,\n publicFinding,\n resolveWriteAuth,\n writeModeNotices,\n} from '../lib/consent';\nimport { describeWallet, resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin publish <file.md>` (or `--candidate <id>`): read the Markdown, parse\n * frontmatter for post + answer-card fields, run the deterministic scan (every\n * mode), gate on the D38\n * consent cascade, then write via the session key (minted on first use) or the\n * plain-SIWX fallback and return a compact receipt. The ordering is the point and\n * is enforced here: scan and consent BEFORE any wallet touch or network write.\n *\n * Exit codes: 0 success (incl. an ineligible-but-published card), 2 usage, 3\n * needs_confirmation / non-bypassable publish_blocked, 4 a write failure after\n * approval.\n */\n\nexport interface PublishArgs {\n /** The Markdown file to publish; mutually exclusive with --candidate. */\n file?: string;\n /** A parked candidate id to publish (its draft.md); mutually exclusive with <file>. */\n candidate?: string;\n draft?: boolean;\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n /** Top-level post price, decimal USD at the edge (O1). */\n price?: string;\n question?: string[];\n task?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: string[];\n asOf?: string;\n validUntil?: string;\n artifactType?: string;\n temporalMode?: string;\n provenance?: string;\n methodology?: string;\n}\n\nexport interface PublishDeps {\n fetchImpl?: typeof fetch;\n provider?: WalletProvider;\n /** Force the plain-SIWX write path (default: session key unless TENJIN_NO_SESSION=1). */\n useSession?: boolean;\n /** Environment seam (mode, base-url, TENJIN_NO_SESSION); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Working directory for the `.tenjin.json` walk; defaults to process.cwd(). */\n cwd?: string;\n}\n\nexport async function runPublish(\n args: PublishArgs,\n ctx: CommandContext,\n deps: PublishDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n // Validate --mode at the edge (USAGE, exit 2) BEFORE any consent resolution: a\n // typo like `--mode Review` must never be silently dropped onto a looser mode\n // and publish unconfirmed. Mirrors install's --publish-mode edge check.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n\n // The content comes from EITHER a <file> or a parked --candidate, never both,\n // never neither. A candidate resolves to its draft.md (and prefills its question).\n const { raw, candidate } = await resolveSource(args, ctx.dataDir);\n const { frontmatter, body } = parseFrontmatter(raw);\n\n const status = resolveStatus(args, frontmatter);\n const title = resolveTitle(frontmatter, body);\n const tags = resolveTags(frontmatter);\n const excerpt = expectString(frontmatter, 'excerpt');\n const handle = expectString(frontmatter, 'handle');\n // A candidate's stored question prefills questionsAnswered, but only as a\n // fallback: an explicit --question OR a frontmatter questionsAnswered still wins.\n const cardFlags = cardFlagsFrom(args);\n if (\n candidate?.meta.question !== undefined &&\n cardFlags.question === undefined &&\n frontmatter.questionsAnswered === undefined\n ) {\n cardFlags.question = [candidate.meta.question];\n }\n const card = deriveCard(frontmatter, cardFlags);\n\n // The consent cascade + resolved price (global < project < env < flag), with the\n // full-auto loosening gate. Its downgrade warnings go to stderr, not the receipt.\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n // The resolver's downgrade warnings, a mistyped env mode, and the one-line\n // explainer for an unconfigured mode: all stderr, all invisible to --json.\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each publish asks you once. Set auto to publish clean scans automatically',\n );\n const priceAtomic = resolvePrice(args, frontmatter, settings.defaultPriceAtomic);\n\n // The scan runs in EVERY mode (D38): it gates the gate, it does not replace it.\n // Scan the whole file AND the derived card's text, so a secret reaches the same\n // gates whether it arrives in the body, in frontmatter, or via a card-authoring\n // flag (--provenance, --scope, …) — the card ships to the PUBLIC card, so a flag\n // secret must block exactly like an in-file one. Dedupe by check+excerpt so a\n // frontmatter value (present in both raw and the card) is not double-counted.\n // The scan context carries the source project's git remote slugs (offline FS\n // read, best-effort): a draft quoting its own project's repo/org warns as a\n // private-by-default reference (open-questions publishing-safety check-set).\n // Markers derive from the DRAFT's project, not the shell's cwd (review r5): a\n // file publish walks up from the file's own directory, and a parked candidate\n // uses the source project recorded in its meta at park time — the pen lives\n // under ~/.tenjin, so the process cwd is unrelated to the draft on both paths.\n const markerRoot =\n candidate !== undefined\n ? candidate.meta.sourceProject\n : args.file !== undefined\n ? dirname(resolve(cwd, args.file))\n : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n const findings = dedupeFindings([\n ...scan(raw, scanContext),\n ...scan(cardScanText(card), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n\n const eligibility = localCardEligibility(card);\n const price = toMoney(priceAtomic);\n\n // A hard-block finding refuses in EVERY mode and is never clearable by --yes or\n // full-auto — the same non-bypassable posture as buy's price cap.\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the file (it is never masked away by --yes), then re-run.',\n details: {\n mode: settings.mode,\n findings: blocking.map(publicFinding),\n price: { atomic: price.atomic, usd: price.usd },\n },\n });\n }\n\n // --yes clears the soft findings and the review confirm alike.\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, price.usd), {\n fix: 'Review the findings, then re-run with --yes (or resolve the source and re-run).',\n details: {\n mode: settings.mode,\n price: { atomic: price.atomic, usd: price.usd },\n findings: warns.map(publicFinding),\n card: eligibility,\n target: { status, titlePreview: sanitizeForTerminal(title ?? '(untitled draft)') },\n },\n });\n }\n\n // Approved (or nothing to confirm): from here a wallet is required. The write\n // base URL is resolved through the shared settings seam and used for BOTH the\n // SIWX/session header domain and the POST host, so the two never diverge.\n const runtime = await resolveContextSettings(ctx);\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n await describeWallet(provider); // surfaces WALLET_MISSING with its own fix\n const signer = await provider.getSigner();\n const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n // A publish always writes.\n scope: 'read+write',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n\n const input: PublishInput = {\n ...(title !== undefined ? { title } : {}),\n bodyMd: body,\n ...(excerpt !== undefined ? { excerpt } : {}),\n ...(tags !== undefined ? { tags } : {}),\n priceAtomic,\n ...(handle !== undefined ? { handle } : {}),\n status,\n ...(card !== undefined ? { resource: card } : {}),\n };\n\n const result = await publishPost(input, auth, {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n // ONLY on a successful publish is the candidate cleared from the pending store\n // (a refusal or a write failure left it parked, above). The clear is BEST-EFFORT:\n // the piece is already published, so a failing drop must NOT report the publish as\n // failed — that would invite a retry and double-publish. Keep ok:true, report\n // cleared:false with a warning, and let the human drop it manually.\n const candidateInfo =\n candidate !== undefined ? await clearPublishedCandidate(ctx, candidate.id) : undefined;\n return receipt(result, runtime.baseUrl, candidateInfo);\n}\n\ninterface CandidateReceipt {\n id: string;\n cleared: boolean;\n warning?: string;\n}\n\nasync function clearPublishedCandidate(ctx: CommandContext, id: string): Promise<CandidateReceipt> {\n try {\n if (await dropCandidate(ctx.dataDir, id)) return { id, cleared: true };\n // The dir was already gone (a concurrent drop): nothing to clear, not an error.\n const warning = `Published, but candidate ${id} was already gone; nothing to clear.`;\n ctx.io.stderr.write(`${warning}\\n`);\n return { id, cleared: false, warning };\n } catch (err) {\n const warning = `Published successfully, but could not clear candidate ${id}: ${errorMessage(err)}. Remove it with \\`tenjin candidate drop ${id}\\`.`;\n ctx.io.stderr.write(`${warning}\\n`);\n return { id, cleared: false, warning };\n }\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Resolve the publish source: a <file>, or a --candidate's draft.md, exclusively.\n * Both or neither is USAGE, and a malformed/unknown candidate id is USAGE before\n * any wallet touch — the whole point of parking it locally is to fail cheap here.\n */\nasync function resolveSource(\n args: PublishArgs,\n dataDir: string,\n): Promise<{ raw: string; candidate?: CandidateRecord }> {\n if (args.candidate !== undefined) {\n if (args.file !== undefined) {\n throw new CliError('USAGE', 'Pass EITHER a file or --candidate, not both.', {\n fix: 'Publish a file with `tenjin publish post.md`, or a candidate with `--candidate <id>`.',\n });\n }\n if (!UUID_RE.test(args.candidate)) {\n throw new CliError('USAGE', `Invalid candidate id: ${JSON.stringify(args.candidate)}`, {\n fix: 'Pass a candidate id from `tenjin candidate list`.',\n });\n }\n // Read-then-act (read here, drop after a successful publish) is not atomic, but\n // the candidate store is a single-user local dir; a concurrent drop between the\n // two is accepted, and the post-success clear is best-effort anyway.\n const record = await readCandidate(dataDir, args.candidate);\n if (record === null) {\n throw new CliError('USAGE', `Unknown candidate: ${JSON.stringify(args.candidate)}`, {\n fix: 'List parked candidates with `tenjin candidate list`.',\n });\n }\n return { raw: await readDraft(record), candidate: record };\n }\n if (args.file === undefined) {\n throw new CliError('USAGE', 'Nothing to publish.', {\n fix: 'Pass a Markdown file (`tenjin publish post.md`) or `--candidate <id>`.',\n });\n }\n return { raw: await readMarkdown(args.file) };\n}\n\n/** Read a candidate's draft.md; a readable dir with an unreadable draft is a torn\n * candidate (INTERNAL), not the caller's usage error. */\nasync function readDraft(record: CandidateRecord): Promise<string> {\n try {\n return await readFile(record.draftPath, 'utf8');\n } catch (err) {\n throw new CliError('INTERNAL', `Candidate ${record.id} is missing its draft.`, {\n fix: `Drop it with \\`tenjin candidate drop ${record.id}\\` and re-add the draft.`,\n cause: err,\n });\n }\n}\n\nfunction receipt(\n result: Awaited<ReturnType<typeof publishPost>>,\n baseUrl: string,\n candidateInfo?: CandidateReceipt,\n): CommandResult {\n const price = toMoney(result.priceAtomic);\n const missing = missingSentences(result.cacheEligibleMissing).map(sanitizeForTerminal);\n const cacheEligible = result.cacheEligible ?? false;\n const deskUrl = `${trimSlash(baseUrl)}/desk`;\n const title = sanitizeForTerminal(result.title);\n // status and url are server-sent open strings (posts-api declares both as bare\n // z.string()), so they get the same treatment as the title beside them: this\n // line is what an author reads to learn where their piece went.\n const human = [\n `Published ${title} (${sanitizeForTerminal(result.status)}) for ${price.usd} USD → ${sanitizeForTerminal(result.url)}`,\n cacheEligible\n ? 'Answer card is search-eligible.'\n : missing.length > 0\n ? `Answer card not search-eligible yet: ${missing.join(' ')}`\n : 'Published as a browse-only document (no answer card).',\n ...(candidateInfo?.cleared === true ? [`Cleared candidate ${candidateInfo.id}.`] : []),\n ...result.warnings.map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n data: {\n resourceId: result.resourceId,\n url: result.url,\n status: result.status,\n price,\n cacheEligible,\n missing,\n deskUrl,\n ...(candidateInfo !== undefined ? { candidate: candidateInfo } : {}),\n ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}),\n },\n humanLines: human,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Field resolution.\n// ---------------------------------------------------------------------------\n\nasync function readMarkdown(file: string): Promise<string> {\n try {\n return await readFile(file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Could not read ${JSON.stringify(file)}`, {\n fix: 'Pass a path to a readable Markdown file, e.g. `tenjin publish post.md`.',\n cause: err,\n });\n }\n}\n\nfunction resolveStatus(args: PublishArgs, frontmatter: Frontmatter): PublishStatus {\n if (args.draft === true) return 'draft';\n const fm = frontmatter.status;\n if (fm === undefined) return 'published';\n if (typeof fm !== 'string' || !(PUBLISH_STATUSES as readonly string[]).includes(fm)) {\n throw new CliError('USAGE', `Invalid status ${JSON.stringify(fm)} in frontmatter.`, {\n fix: 'Use status: draft | published | unlisted, or pass --draft.',\n });\n }\n return fm as PublishStatus;\n}\n\nfunction resolveTitle(frontmatter: Frontmatter, body: string): string | undefined {\n const fm = frontmatter.title;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter title must be a single string.');\n }\n return fm.trim();\n }\n // Fall back to the first heading (level 1 preferred) so a plain `# Title` post\n // needs no frontmatter.\n const headings = headingOutline(body);\n const h1 = headings.find((h) => h.level === 1) ?? headings[0];\n return h1?.text;\n}\n\nfunction resolveTags(frontmatter: Frontmatter): string[] | undefined {\n const fm = frontmatter.tags;\n if (fm === undefined) return undefined;\n if (typeof fm === 'string') return [fm];\n if (Array.isArray(fm)) return fm;\n throw new CliError('USAGE', 'frontmatter tags must be a list of strings.');\n}\n\nfunction expectString(frontmatter: Frontmatter, key: string): string | undefined {\n const fm = frontmatter[key];\n if (fm === undefined) return undefined;\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', `frontmatter ${key} must be a single string.`);\n }\n return fm;\n}\n\nfunction resolvePrice(args: PublishArgs, frontmatter: Frontmatter, defaultAtomic: string): string {\n if (args.price !== undefined) return parseUsdToAtomic(args.price);\n const fm = frontmatter.price;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter price must be a decimal-USD string, e.g. \"0.10\".');\n }\n return parseUsdToAtomic(fm);\n }\n return defaultAtomic;\n}\n\nfunction cardFlagsFrom(args: PublishArgs): CardFlags {\n return {\n ...(args.question !== undefined && args.question.length > 0 ? { question: args.question } : {}),\n ...(args.task !== undefined && args.task.length > 0 ? { task: args.task } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n ...(args.exclusions !== undefined ? { exclusions: args.exclusions } : {}),\n ...(args.asOf !== undefined ? { asOf: args.asOf } : {}),\n ...(args.validUntil !== undefined ? { validUntil: args.validUntil } : {}),\n ...(args.artifactType !== undefined ? { artifactType: args.artifactType } : {}),\n ...(args.temporalMode !== undefined ? { temporalMode: args.temporalMode } : {}),\n ...(args.provenance !== undefined ? { provenance: args.provenance } : {}),\n ...(args.methodology !== undefined ? { methodology: args.methodology } : {}),\n ...(args.appliesTo !== undefined && args.appliesTo.length > 0\n ? { appliesTo: parseAppliesToFlags(args.appliesTo) }\n : {}),\n };\n}\n\n/**\n * The derived card's free-text values as one newline-joined document, so the scan\n * covers card-flag input (which never touches the file) at the same severity as\n * the body. Empty when there is no card.\n */\nfunction cardScanText(card: ResourceCardInput | undefined): string {\n if (card === undefined) return '';\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n add(card.scope);\n add(card.exclusions);\n add(card.provenanceSummary);\n add(card.methodologySummary);\n add(card.mediaType);\n add(card.maintenanceCadence);\n add(card.asOf);\n add(card.validUntil);\n add(card.estimatedPaidInputCost);\n if (card.questionsAnswered !== undefined) parts.push(...card.questionsAnswered);\n if (card.tasksSupported !== undefined) parts.push(...card.tasksSupported);\n if (card.appliesTo !== undefined) {\n for (const values of Object.values(card.appliesTo)) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Finding + message shaping.\n// ---------------------------------------------------------------------------\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Publish blocked: the file contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, priceUsd: string): string {\n return warnCount > 0\n ? `Publish needs confirmation: ${warnCount} finding(s), price $${priceUsd}.`\n : `Publish needs confirmation: price $${priceUsd}.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,eAAe;AAuFjC,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AAIpC,MAAI,KAAK,SAAS,OAAW,sBAAqB,KAAK,MAAM,QAAQ;AAIrE,QAAM,EAAE,KAAK,UAAU,IAAI,MAAM,cAAc,MAAM,IAAI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,eAAW,UAAU,OAAO,OAAO,KAAK,SAAS,EAAG,OAAM,KAAK,GAAG,MAAM;AAAA,EAC1E;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;AAMA,SAAS,aAAa,UAAiC;AACrD,SAAO,sCAAsC,iBAAiB,QAAQ,CAAC;AACzE;AAEA,SAAS,eAAe,WAAmB,UAA0B;AACnE,SAAO,YAAY,IACf,+BAA+B,SAAS,uBAAuB,QAAQ,MACvE,sCAAsC,QAAQ;AACpD;","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,MACL,SAAS,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