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.
Files changed (135) hide show
  1. package/README.md +269 -38
  2. package/dist/{buy-OOOLUDND.js → buy-XVOMNWKN.js} +21 -18
  3. package/dist/{candidate-TWCWTFGA.js → candidate-DJB2NNTG.js} +7 -8
  4. package/dist/{chunk-KXIX7YDV.js → chunk-2KIDDWQO.js} +5 -5
  5. package/dist/{chunk-NXCJN2FJ.js → chunk-2L73UI6T.js} +51 -42
  6. package/dist/chunk-2L73UI6T.js.map +1 -0
  7. package/dist/{chunk-OJD54DIU.js → chunk-2YX6LTCD.js} +5 -5
  8. package/dist/{chunk-H5ETJRQD.js → chunk-5X4EBGGU.js} +22 -14
  9. package/dist/chunk-5X4EBGGU.js.map +1 -0
  10. package/dist/chunk-6S44OLND.js +699 -0
  11. package/dist/chunk-6S44OLND.js.map +1 -0
  12. package/dist/{chunk-FU6MCSLG.js → chunk-7WDY4AXV.js} +2 -64
  13. package/dist/chunk-7WDY4AXV.js.map +1 -0
  14. package/dist/{chunk-VV4P5RVK.js → chunk-BBUYCDSG.js} +16 -4
  15. package/dist/chunk-BBUYCDSG.js.map +1 -0
  16. package/dist/chunk-CYRYVZPN.js +213 -0
  17. package/dist/chunk-CYRYVZPN.js.map +1 -0
  18. package/dist/{chunk-FHB3VKZW.js → chunk-DAJ56EUU.js} +5 -3
  19. package/dist/chunk-DAJ56EUU.js.map +1 -0
  20. package/dist/chunk-DH6D6QIO.js +239 -0
  21. package/dist/chunk-DH6D6QIO.js.map +1 -0
  22. package/dist/chunk-E6BNARCS.js +614 -0
  23. package/dist/chunk-E6BNARCS.js.map +1 -0
  24. package/dist/chunk-GABYDXWL.js +190 -0
  25. package/dist/chunk-GABYDXWL.js.map +1 -0
  26. package/dist/{chunk-EUQN3L5X.js → chunk-GM4RZUVU.js} +21 -9
  27. package/dist/chunk-GM4RZUVU.js.map +1 -0
  28. package/dist/{chunk-C4TIWOAM.js → chunk-GXYNLMUQ.js} +28 -11
  29. package/dist/chunk-GXYNLMUQ.js.map +1 -0
  30. package/dist/{chunk-6WWVYYSB.js → chunk-J6CVKC4M.js} +86 -4
  31. package/dist/chunk-J6CVKC4M.js.map +1 -0
  32. package/dist/{chunk-5JH7ZB6Z.js → chunk-KT2DGKFT.js} +76 -10
  33. package/dist/chunk-KT2DGKFT.js.map +1 -0
  34. package/dist/chunk-L6AV2Q73.js +105 -0
  35. package/dist/chunk-L6AV2Q73.js.map +1 -0
  36. package/dist/{chunk-333FOTUJ.js → chunk-MJZZTKCC.js} +108 -2
  37. package/dist/chunk-MJZZTKCC.js.map +1 -0
  38. package/dist/{chunk-XNNOR7F7.js → chunk-OTDI5FXG.js} +3 -5
  39. package/dist/{chunk-XNNOR7F7.js.map → chunk-OTDI5FXG.js.map} +1 -1
  40. package/dist/chunk-PIIWLEEG.js +337 -0
  41. package/dist/chunk-PIIWLEEG.js.map +1 -0
  42. package/dist/{chunk-ULLWHHIT.js → chunk-PLU3E63S.js} +468 -559
  43. package/dist/chunk-PLU3E63S.js.map +1 -0
  44. package/dist/chunk-QW2Q2KAH.js +27 -0
  45. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  46. package/dist/{chunk-S3KZ3PPK.js → chunk-RGFBBNGP.js} +291 -59
  47. package/dist/chunk-RGFBBNGP.js.map +1 -0
  48. package/dist/chunk-SGK2B724.js +67 -0
  49. package/dist/chunk-SGK2B724.js.map +1 -0
  50. package/dist/chunk-UYP7G3GZ.js +412 -0
  51. package/dist/chunk-UYP7G3GZ.js.map +1 -0
  52. package/dist/{chunk-DPUMEMGM.js → chunk-VZ3AJCO5.js} +3 -5
  53. package/dist/{chunk-DPUMEMGM.js.map → chunk-VZ3AJCO5.js.map} +1 -1
  54. package/dist/{chunk-QH6677FJ.js → chunk-WDJTGVKN.js} +2 -2
  55. package/dist/{chunk-QH6677FJ.js.map → chunk-WDJTGVKN.js.map} +1 -1
  56. package/dist/{chunk-4GR7DGD6.js → chunk-WI5EOAQQ.js} +33 -256
  57. package/dist/{chunk-4GR7DGD6.js.map → chunk-WI5EOAQQ.js.map} +1 -1
  58. package/dist/{chunk-DPET3TW5.js → chunk-WRWCDLVK.js} +13 -12
  59. package/dist/chunk-WRWCDLVK.js.map +1 -0
  60. package/dist/chunk-XBJ3VLWX.js +35 -0
  61. package/dist/chunk-XBJ3VLWX.js.map +1 -0
  62. package/dist/chunk-ZEWY3RJ3.js +149 -0
  63. package/dist/chunk-ZEWY3RJ3.js.map +1 -0
  64. package/dist/chunk-ZFE7STX7.js +143 -0
  65. package/dist/chunk-ZFE7STX7.js.map +1 -0
  66. package/dist/{cli-AFSLAKR6.js → cli-7B2QNJG3.js} +247 -26
  67. package/dist/cli-7B2QNJG3.js.map +1 -0
  68. package/dist/{config-DBEEM3UA.js → config-SAQEQRFB.js} +7 -6
  69. package/dist/{doctor-XDA3YU6H.js → doctor-ENJ22XWN.js} +10 -8
  70. package/dist/{publish-IH7RJXGB.js → edit-2QO5GQDU.js} +19 -17
  71. package/dist/index.js +1 -1
  72. package/dist/{inspect-YBGDAG47.js → inspect-IPKKQB2S.js} +16 -15
  73. package/dist/{install-7J6KKEEP.js → install-7ZIYISQ7.js} +180 -133
  74. package/dist/install-7ZIYISQ7.js.map +1 -0
  75. package/dist/outcome-NSDE2KAJ.js +20 -0
  76. package/dist/publish-7WIFFNFG.js +40 -0
  77. package/dist/read-5TQR7LCF.js +158 -0
  78. package/dist/read-5TQR7LCF.js.map +1 -0
  79. package/dist/{run-DCZFEW2C.js → run-NPKIP26Y.js} +109 -34
  80. package/dist/{run-DCZFEW2C.js.map → run-NPKIP26Y.js.map} +1 -1
  81. package/dist/search-63ELMRZH.js +24 -0
  82. package/dist/send-ENE47KQE.js +222 -0
  83. package/dist/send-ENE47KQE.js.map +1 -0
  84. package/dist/session-FZU4VFFE.js +87 -0
  85. package/dist/session-FZU4VFFE.js.map +1 -0
  86. package/dist/{usdc-AU6ZIKA6.js → usdc-4VCDHFWX.js} +20 -4
  87. package/dist/{wallet-UWHSHWC6.js → wallet-OCCGEH6H.js} +8 -8
  88. package/dist/{wallet-HKG3GSTX.js → wallet-RBDVNZVR.js} +17 -7
  89. package/dist/wallet-RBDVNZVR.js.map +1 -0
  90. package/package.json +1 -1
  91. package/skills/tenjin/SKILL.md +32 -7
  92. package/skills/tenjin-publish/SKILL.md +109 -16
  93. package/skills/tenjin-search/SKILL.md +174 -15
  94. package/dist/chunk-333FOTUJ.js.map +0 -1
  95. package/dist/chunk-5JH7ZB6Z.js.map +0 -1
  96. package/dist/chunk-6WWVYYSB.js.map +0 -1
  97. package/dist/chunk-BXUS5UCT.js +0 -212
  98. package/dist/chunk-BXUS5UCT.js.map +0 -1
  99. package/dist/chunk-C4TIWOAM.js.map +0 -1
  100. package/dist/chunk-CJU555P5.js +0 -333
  101. package/dist/chunk-CJU555P5.js.map +0 -1
  102. package/dist/chunk-DPET3TW5.js.map +0 -1
  103. package/dist/chunk-EUQN3L5X.js.map +0 -1
  104. package/dist/chunk-FHB3VKZW.js.map +0 -1
  105. package/dist/chunk-FU6MCSLG.js.map +0 -1
  106. package/dist/chunk-H5ETJRQD.js.map +0 -1
  107. package/dist/chunk-MM4TGTST.js +0 -59
  108. package/dist/chunk-MM4TGTST.js.map +0 -1
  109. package/dist/chunk-MUBUQVC3.js +0 -67
  110. package/dist/chunk-MUBUQVC3.js.map +0 -1
  111. package/dist/chunk-NXCJN2FJ.js.map +0 -1
  112. package/dist/chunk-R7BMDJZM.js +0 -167
  113. package/dist/chunk-R7BMDJZM.js.map +0 -1
  114. package/dist/chunk-S3KZ3PPK.js.map +0 -1
  115. package/dist/chunk-ULLWHHIT.js.map +0 -1
  116. package/dist/chunk-VV4P5RVK.js.map +0 -1
  117. package/dist/chunk-YFREUEUI.js +0 -78
  118. package/dist/chunk-YFREUEUI.js.map +0 -1
  119. package/dist/cli-AFSLAKR6.js.map +0 -1
  120. package/dist/install-7J6KKEEP.js.map +0 -1
  121. package/dist/outcome-ZFGHX2XW.js +0 -20
  122. package/dist/search-R6NIQFXI.js +0 -24
  123. /package/dist/{buy-OOOLUDND.js.map → buy-XVOMNWKN.js.map} +0 -0
  124. /package/dist/{candidate-TWCWTFGA.js.map → candidate-DJB2NNTG.js.map} +0 -0
  125. /package/dist/{chunk-KXIX7YDV.js.map → chunk-2KIDDWQO.js.map} +0 -0
  126. /package/dist/{chunk-OJD54DIU.js.map → chunk-2YX6LTCD.js.map} +0 -0
  127. /package/dist/{config-DBEEM3UA.js.map → config-SAQEQRFB.js.map} +0 -0
  128. /package/dist/{doctor-XDA3YU6H.js.map → doctor-ENJ22XWN.js.map} +0 -0
  129. /package/dist/{inspect-YBGDAG47.js.map → edit-2QO5GQDU.js.map} +0 -0
  130. /package/dist/{outcome-ZFGHX2XW.js.map → inspect-IPKKQB2S.js.map} +0 -0
  131. /package/dist/{publish-IH7RJXGB.js.map → outcome-NSDE2KAJ.js.map} +0 -0
  132. /package/dist/{search-R6NIQFXI.js.map → publish-7WIFFNFG.js.map} +0 -0
  133. /package/dist/{usdc-AU6ZIKA6.js.map → search-63ELMRZH.js.map} +0 -0
  134. /package/dist/{wallet-HKG3GSTX.js.map → usdc-4VCDHFWX.js.map} +0 -0
  135. /package/dist/{wallet-UWHSHWC6.js.map → wallet-OCCGEH6H.js.map} +0 -0
@@ -1,68 +1,74 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
- buildSiwxHeader,
4
- headingOutline
5
- } from "./chunk-FU6MCSLG.js";
6
- import {
7
- describeWallet,
8
- resolveWalletProvider
9
- } from "./chunk-S3KZ3PPK.js";
3
+ SESSION_CHAIN_ID,
4
+ createSessionKeyAuth,
5
+ createSiwxAuth
6
+ } from "./chunk-ZFE7STX7.js";
10
7
  import {
11
8
  rateLimitError
12
- } from "./chunk-NXCJN2FJ.js";
13
- import {
14
- dropCandidate,
15
- readCandidate
16
- } from "./chunk-DPUMEMGM.js";
9
+ } from "./chunk-2L73UI6T.js";
17
10
  import {
18
11
  ATOMIC_RE,
19
12
  UUID_RE
20
13
  } from "./chunk-WWX32ML4.js";
21
- import {
22
- sanitizeForTerminal
23
- } from "./chunk-VV4P5RVK.js";
24
14
  import {
25
15
  CLIENT_HEADER,
26
- httpRequest,
27
- trimSlash
28
- } from "./chunk-C4TIWOAM.js";
29
- import {
30
- hasCode
31
- } from "./chunk-2I4QTOLB.js";
16
+ httpRequest
17
+ } from "./chunk-GXYNLMUQ.js";
32
18
  import {
33
- resolveContextSettings,
34
- resolvePublishSettings
35
- } from "./chunk-FHB3VKZW.js";
36
- import {
37
- PublishModeSchema,
38
- parsePublishModeFlag,
39
- parseUsdToAtomic,
40
- toMoney
41
- } from "./chunk-BXUS5UCT.js";
19
+ trimSlash
20
+ } from "./chunk-XBJ3VLWX.js";
42
21
  import {
43
- writeFileAtomic
44
- } from "./chunk-MUBUQVC3.js";
22
+ PublishModeSchema
23
+ } from "./chunk-UYP7G3GZ.js";
45
24
  import {
46
25
  CliError,
47
- external_exports,
48
- sessionPath
49
- } from "./chunk-6WWVYYSB.js";
50
-
51
- // src/commands/publish.ts
52
- import { readFile as readFile2 } from "fs/promises";
26
+ external_exports
27
+ } from "./chunk-J6CVKC4M.js";
53
28
 
54
29
  // src/lib/scan.ts
55
30
  var LONG_QUOTE_WORDS = 80;
56
- function scan(text) {
31
+ function scan(text, context = {}) {
57
32
  const lines = text.split("\n");
58
33
  const findings = [
59
34
  ...scanHex64(lines),
60
35
  ...scanLineDetectors(lines),
61
36
  ...scanPemBlocks(lines),
62
- ...scanLongVerbatim(lines)
37
+ ...scanLongVerbatim(lines),
38
+ ...scanProjectMarkers(lines, context.projectMarkers ?? [])
63
39
  ];
64
40
  return dedupeAndSort(suppressEmailsInDbUris(findings));
65
41
  }
42
+ function scanProjectMarkers(lines, markers) {
43
+ const cleaned = [...new Set(markers.filter((m) => m.trim().length >= 3))];
44
+ if (cleaned.length === 0) return [];
45
+ const needles = cleaned.map((marker) => ({
46
+ marker,
47
+ re: new RegExp(`(?<![A-Za-z0-9._-])${escapeRegExp(marker)}(?![A-Za-z0-9_-])`, "gi")
48
+ }));
49
+ const out = [];
50
+ for (let i = 0; i < lines.length; i++) {
51
+ const line = lines[i] ?? "";
52
+ for (const { marker, re } of needles) {
53
+ re.lastIndex = 0;
54
+ let m;
55
+ while ((m = re.exec(line)) !== null) {
56
+ out.push({
57
+ check: "private-repo-reference",
58
+ severity: "warn",
59
+ line: i + 1,
60
+ span: [m.index, m.index + m[0].length],
61
+ excerpt: marker
62
+ });
63
+ }
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+ function escapeRegExp(s) {
69
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
70
+ }
71
+ var PLACEHOLDER_USERNAME = /^(?:user(?:name)?|you(?:rname)?|example|foo|me|myuser|somebody)$/i;
66
72
  function suppressEmailsInDbUris(findings) {
67
73
  const uris = findings.filter((f) => f.check === "db-connection-uri");
68
74
  if (uris.length === 0) return findings;
@@ -177,8 +183,10 @@ var LINE_DETECTORS = [
177
183
  },
178
184
  // Generic secret-named assignment — WARN, not block (review): a keyword match is
179
185
  // lower-confidence than a structured shape, and a warn still forces confirmation
180
- // in auto mode (and review always asks), so nothing publishes unseen while benign
181
- // config (SECRET_NAME=…, MYSQL_ROOT_PASSWORD=…) is not permanently non-bypassable. The
186
+ // under `review` and `auto`, while benign config (SECRET_NAME=…,
187
+ // MYSQL_ROOT_PASSWORD=…) is not permanently non-bypassable. `full-auto` and a bare
188
+ // `--yes` DO clear it unseen, which is the price of that choice; the publish skill
189
+ // says so rather than implying keys and tokens are all in the blocking tier. The
182
190
  // excerpt stays masked. Placeholder and structural (path/URL/regex) values are
183
191
  // skipped entirely.
184
192
  {
@@ -189,12 +197,7 @@ var LINE_DETECTORS = [
189
197
  // (interior spaces allowed) or an unquoted run, ≥6 chars. Value is masked.
190
198
  re: /\b([A-Za-z0-9_]*(?:API[_-]?KEY|SECRET|ACCESS[_-]?KEY|PRIVATE[_-]?KEY|PASSW(?:OR)?D|TOKEN|CREDENTIALS?|AUTH[_-]?TOKEN)[A-Za-z0-9_]*)\s*[:=]\s*("[^"]{6,}"|'[^']{6,}'|[^\s"']{6,})/gi,
191
199
  excerpt: (m) => `${m[1]}=[redacted ${dequote(m[2] ?? "").length} chars]`,
192
- skip: (m) => {
193
- const raw = m[2] ?? "";
194
- const value = dequote(raw);
195
- if (isPlaceholder(value) || isStructural(value)) return true;
196
- return raw === value && isCodeExpression(value);
197
- }
200
+ skip: skipNonLiteralValue
198
201
  },
199
202
  // Wallet addresses — warn (a contract address may be intentional). Not a secret,
200
203
  // shown abbreviated. viem's checksum validation is deliberately NOT used to gate
@@ -206,11 +209,34 @@ var LINE_DETECTORS = [
206
209
  re: /(?<![0-9a-fx])0x[0-9a-fA-F]{40}(?![0-9a-fA-F])/gi,
207
210
  excerpt: (m) => `${m[0].slice(0, 6)}\u2026${m[0].slice(-4)}`
208
211
  },
209
- // Employer-internal markers — warn.
212
+ // Employer-internal markers — warn. Marker-SHAPED, not word-in-phrase (#36):
213
+ // the detector targets the classification legend a document stamp carries
214
+ // (CONFIDENTIAL, CONFIDENTIAL DRAFT/INFORMATION, STRICTLY/COMPANY
215
+ // CONFIDENTIAL, "Acme Inc. Confidential", INTERNAL (USE) ONLY, DO NOT
216
+ // DISTRIBUTE), so it is case-SENSITIVE — prose about "confidential computing"
217
+ // never fires. The phrase-vs-legend split is positional, not a blanket
218
+ // next-word lookahead (review r5: the old lookahead lost CONFIDENTIAL
219
+ // INFORMATION and every title-case legend):
220
+ // - all-caps CONFIDENTIAL is suppressed only when all-caps words flank it on
221
+ // BOTH sides — that is what a mid-phrase mention in a shouting heading
222
+ // looks like (A SURVEY OF CONFIDENTIAL COMPUTING …). A legend either leads
223
+ // its line (CONFIDENTIAL DRAFT) or ends it (ACME CONFIDENTIAL, HIGHLY
224
+ // CONFIDENTIAL, PROPRIETARY AND CONFIDENTIAL), so one-sided caps still
225
+ // fire (review r6: the caps-prefixed company stamp is the most common real
226
+ // legend form, and the old left-only rule missed the whole family).
227
+ // Accepted FP: a caps heading that LEADS with the topic word
228
+ // (# CONFIDENTIAL COMPUTING ON AWS) warns — fail-safe direction. Accepted
229
+ // FN: a caps-flanked legend without a whitelisted prefix (ACME
230
+ // CONFIDENTIAL INFORMATION) is indistinguishable from a shouting-heading
231
+ // phrase and misses; STRICTLY/COMPANY/HIGHLY prefixes are legend-only
232
+ // vocabulary and are whitelisted through.
233
+ // - Title-case Confidential fires only before punctuation or end-of-line
234
+ // ("Acme Inc. Confidential", "## Confidential: …"), never mid-title
235
+ // ("Confidential Computing: a TEE survey").
210
236
  {
211
237
  check: "confidential-marker",
212
238
  severity: "warn",
213
- re: /\b(?:CONFIDENTIAL|INTERNAL ONLY)\b/gi,
239
+ re: /\b(?:STRICTLY|COMPANY|HIGHLY)\s+CONFIDENTIAL\b|(?<![A-Z]{2,}[ \t]+)\bCONFIDENTIAL\b|\bCONFIDENTIAL\b(?![ \t]+[A-Z]{2,})|\bConfidential(?=\s*(?:[-:.,;–—]|$))|\b(?:INTERNAL|Internal)(?:\s+(?:USE|Use))?\s+(?:ONLY|Only)\b|\b(?:DO\s+NOT\s+DISTRIBUTE|Do\s+Not\s+Distribute)\b/g,
214
240
  excerpt: (m) => m[0]
215
241
  },
216
242
  {
@@ -219,6 +245,80 @@ var LINE_DETECTORS = [
219
245
  re: /\b(?:[a-z0-9-]+\.)+(?:internal|corp|local|lan|intranet)\b/gi,
220
246
  excerpt: (m) => m[0]
221
247
  },
248
+ // Home-anchored local filesystem paths — warn (open-questions publishing-safety:
249
+ // private paths). A /Users/<name>/… or /home/<name>/… or C:\Users\<name>\…
250
+ // path leaks the machine username and private project layout. The username
251
+ // segment is masked in the excerpt; obvious placeholder usernames
252
+ // (/home/user/…, /Users/username/…) are docs examples and skip. `~/…` paths
253
+ // deliberately do NOT fire: they are already generalized. The unix branch
254
+ // requires a non-name left boundary so a web-URL path segment
255
+ // (docs.example.com/home/…) is not a local path, and the segment class
256
+ // excludes `?`/`&` so a query string (…?api_key=…) is never swallowed into a
257
+ // verbatim excerpt a sibling detector would have masked (review r5). Windows
258
+ // matches [Uu]sers: the filesystem is case-insensitive.
259
+ {
260
+ check: "local-path",
261
+ severity: "warn",
262
+ re: /(?:(?<![\w.-])\/(?:Users|home)\/([A-Za-z0-9._-]+)(?:\/[^\s"'`)\]}>:,;?&]+)+|\b[A-Za-z]:\\[Uu]sers\\([^\\\s"']+)(?:\\[^\\\s"']+)+)/dg,
263
+ excerpt: (m) => {
264
+ const bounds = m.indices?.[1] ?? m.indices?.[2];
265
+ const masked = bounds === void 0 ? m[0] : `${m[0].slice(0, bounds[0] - m.index)}[user]${m[0].slice(bounds[1] - m.index)}`;
266
+ return masked.length > 60 ? `${masked.slice(0, 57)}\u2026` : masked;
267
+ },
268
+ skip: (m) => PLACEHOLDER_USERNAME.test(m[1] ?? m[2] ?? "")
269
+ },
270
+ // Labeled customer/account identifiers — warn (open-questions publishing-safety:
271
+ // customer identifiers). Fires only on the explicit label + separator + value
272
+ // shape (customer_id: 84213, Account Number: ACME-0042); the value is masked
273
+ // like a secret-assignment value since a customer identifier is third-party
274
+ // data. Chosen tradeoff: an unlabeled identifier (bare CUST-4812) is a false
275
+ // negative — an unlabeled token is indistinguishable from a SKU or version tag.
276
+ {
277
+ check: "customer-identifier",
278
+ severity: "warn",
279
+ re: /\b((?:customer|client|account|tenant|subscriber)[ _-]?(?:id|number|no))\b\s*[:=#]\s*("[^"]{2,}"|'[^']{2,}'|[A-Za-z0-9][A-Za-z0-9._-]{2,})/gi,
280
+ excerpt: (m) => `${m[1]}=[redacted ${dequote(m[2] ?? "").length} chars]`,
281
+ skip: skipNonLiteralValue
282
+ },
283
+ // Third-party paid/licensed-content markers — warn (open-questions
284
+ // publishing-safety: third-party copyrighted inputs). A rights LEGEND in the
285
+ // draft suggests copied licensed material; ambiguity-class (the author may
286
+ // hold the rights), so warn, never block. Legend shapes only — bare paywall
287
+ // vocabulary (paywalled, premium content, subscriber-only, behind a paywall)
288
+ // deliberately does NOT fire: it is this marketplace's own subject matter and
289
+ // measured 100% false-positive on the dogfood corpus (review r5), the exact
290
+ // word-in-phrase failure #36 is about.
291
+ {
292
+ check: "paid-content-marker",
293
+ severity: "warn",
294
+ re: /\ball rights reserved\b|\b(?:reprinted|reproduced|used) with permission\b|\bnot for (?:redistribution|republication)\b|\bdo not (?:redistribute|republish)\b|(?:©|\(c\)|copyright)\s*(?:19|20)\d{2}\b/gi,
295
+ excerpt: (m) => m[0]
296
+ },
297
+ // Embedded prompt/tool-output instruction patterns — warn (open-questions
298
+ // publishing-safety: embedded instructions). Source material captured from
299
+ // prompts or tool output can carry injection-shaped imperatives that would
300
+ // ship to every future buyer. High-precision imperative shapes only: a bare
301
+ // "system prompt" mention, chat-template delimiters (<system>, [INST]), and
302
+ // persona phrases ("you are an assistant", "as an AI") deliberately do NOT
303
+ // fire — legitimate agent-engineering exposition quotes all of them
304
+ // constantly (review r5), and only the imperative shapes are injection-typed.
305
+ // Two entries under one check name: the imperative shapes are case-INsensitive
306
+ // (adversarial text uses any case), while BEGIN SYSTEM/HIDDEN PROMPT is
307
+ // case-SENSITIVE — its signal is that it reads as a document header, and
308
+ // lowercase "begin system prompt" is ordinary prose on this marketplace's own
309
+ // subject matter (greptile r7), the #36 word-in-phrase class again.
310
+ {
311
+ check: "embedded-instruction",
312
+ severity: "warn",
313
+ re: /\b(?:ignore|disregard|forget)\s+(?:all\s+|any\s+)?(?:previous|prior|above|earlier|preceding)\s+(?:instructions?|prompts?|context|messages?)\b|\bdo not (?:reveal|disclose|mention) (?:this|these|the above)\b/gi,
314
+ excerpt: (m) => m[0]
315
+ },
316
+ {
317
+ check: "embedded-instruction",
318
+ severity: "warn",
319
+ re: /\bBEGIN (?:SYSTEM|HIDDEN) (?:PROMPT|INSTRUCTIONS)\b/g,
320
+ excerpt: (m) => m[0]
321
+ },
222
322
  // Personal data — warn. `email` subsumes corp-domain emails (an internal marker).
223
323
  {
224
324
  check: "email",
@@ -255,6 +355,12 @@ function scanLineDetectors(lines) {
255
355
  }
256
356
  return out;
257
357
  }
358
+ function skipNonLiteralValue(m) {
359
+ const raw = m[2] ?? "";
360
+ const value = dequote(raw);
361
+ if (isPlaceholder(value) || isStructural(value)) return true;
362
+ return raw === value && isCodeExpression(value);
363
+ }
258
364
  function dequote(value) {
259
365
  const m = /^"([^"]*)"$|^'([^']*)'$/.exec(value);
260
366
  return m !== null ? m[1] ?? m[2] ?? "" : value;
@@ -401,6 +507,81 @@ function dedupeAndSort(findings) {
401
507
  );
402
508
  }
403
509
 
510
+ // src/lib/scan-context.ts
511
+ import { readFile, stat } from "fs/promises";
512
+ import { dirname, isAbsolute, join, resolve } from "path";
513
+ async function deriveProjectMarkers(cwd) {
514
+ try {
515
+ const configPath = await findGitConfig(resolve(cwd));
516
+ if (configPath === void 0) return [];
517
+ const config = await readSmallFile(configPath);
518
+ return config === void 0 ? [] : extractRemoteSlugs(config);
519
+ } catch {
520
+ return [];
521
+ }
522
+ }
523
+ var MAX_GIT_FILE_BYTES = 1024 * 1024;
524
+ async function readSmallFile(path) {
525
+ const s = await stat(path).catch(() => void 0);
526
+ if (s?.isFile() !== true || s.size > MAX_GIT_FILE_BYTES) return void 0;
527
+ return readFile(path, "utf8").catch(() => void 0);
528
+ }
529
+ async function findGitConfig(dir) {
530
+ for (let current = dir; ; current = dirname(current)) {
531
+ const dotGit = join(current, ".git");
532
+ const s = await stat(dotGit).catch(() => void 0);
533
+ if (s?.isDirectory() === true) return join(dotGit, "config");
534
+ if (s?.isFile() === true) {
535
+ const resolved = await resolveGitFile(dotGit, current);
536
+ if (resolved !== void 0) return resolved;
537
+ }
538
+ if (dirname(current) === current) return void 0;
539
+ }
540
+ }
541
+ async function resolveGitFile(dotGitFile, containingDir) {
542
+ const content = await readSmallFile(dotGitFile);
543
+ if (content === void 0) return void 0;
544
+ const m = /^gitdir:\s*(.+)\s*$/m.exec(content);
545
+ if (m?.[1] === void 0) return void 0;
546
+ const gitdir = isAbsolute(m[1]) ? m[1] : resolve(containingDir, m[1]);
547
+ const commondirFile = await readSmallFile(join(gitdir, "commondir"));
548
+ if (commondirFile !== void 0) {
549
+ const common = commondirFile.trim();
550
+ return join(isAbsolute(common) ? common : resolve(gitdir, common), "config");
551
+ }
552
+ return join(gitdir, "config");
553
+ }
554
+ var SECTION_LINE = /^\s*\[([^\]]*)\]/;
555
+ var URL_LINE = /^\s*url\s*=\s*(.+?)\s*$/i;
556
+ function extractRemoteSlugs(gitConfig) {
557
+ const slugs = /* @__PURE__ */ new Set();
558
+ let inRemoteSection = false;
559
+ for (const line of gitConfig.split("\n")) {
560
+ const section = SECTION_LINE.exec(line);
561
+ if (section !== null) {
562
+ inRemoteSection = /^remote\b/i.test((section[1] ?? "").trim());
563
+ continue;
564
+ }
565
+ if (!inRemoteSection) continue;
566
+ const m = URL_LINE.exec(line);
567
+ if (m === null) continue;
568
+ const value = (m[1] ?? "").split(/[#;]/, 1)[0]?.trim() ?? "";
569
+ const slug = slugFromRemoteUrl(value);
570
+ if (slug !== void 0) slugs.add(slug);
571
+ }
572
+ return [...slugs];
573
+ }
574
+ function slugFromRemoteUrl(url) {
575
+ let path;
576
+ const scheme = /^[a-z][a-z0-9+.-]*:\/\/(?:[^/@\s]+@)?[^/\s]+\/(.+)$/i.exec(url);
577
+ const scp = /^[^/@\s]+@[^:/\s]+:(.+)$/.exec(url);
578
+ if (scheme !== null) path = scheme[1];
579
+ else if (scp !== null) path = scp[1];
580
+ if (path === void 0) return void 0;
581
+ const slug = path.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "");
582
+ return slug.includes("/") && slug.length >= 3 ? slug : void 0;
583
+ }
584
+
404
585
  // src/lib/card.ts
405
586
  var FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
406
587
  function parseFrontmatter(text) {
@@ -766,7 +947,8 @@ function buildPostCreateBody(input) {
766
947
  if (bodyMd !== void 0 && bodyMd.length > 2e5) {
767
948
  throw new CliError("USAGE", "bodyMd must be at most 200000 characters.");
768
949
  }
769
- if (input.excerpt !== void 0 && input.excerpt.length > 500) {
950
+ const excerpt = input.excerpt?.trim();
951
+ if (excerpt !== void 0 && excerpt.length > 500) {
770
952
  throw new CliError("USAGE", "excerpt must be at most 500 characters.");
771
953
  }
772
954
  if (input.tags !== void 0) {
@@ -797,7 +979,7 @@ function buildPostCreateBody(input) {
797
979
  return {
798
980
  ...title !== void 0 && title.length > 0 ? { title } : {},
799
981
  ...bodyMd !== void 0 ? { bodyMd } : {},
800
- ...input.excerpt !== void 0 ? { excerpt: input.excerpt } : {},
982
+ ...excerpt !== void 0 ? { excerpt } : {},
801
983
  ...input.tags !== void 0 && input.tags.length > 0 ? { tags: input.tags } : {},
802
984
  ...input.priceAtomic !== void 0 ? { price: input.priceAtomic } : {},
803
985
  ...input.handle !== void 0 ? { handle: input.handle } : {},
@@ -806,6 +988,22 @@ function buildPostCreateBody(input) {
806
988
  };
807
989
  }
808
990
  var resourceEchoSchema = external_exports.object({
991
+ artifactType: external_exports.string().nullish(),
992
+ mediaType: external_exports.string().nullish(),
993
+ temporalMode: external_exports.string().nullish(),
994
+ asOf: external_exports.string().nullish(),
995
+ validUntil: external_exports.string().nullish(),
996
+ supersedesPostId: external_exports.string().nullish(),
997
+ questionsAnswered: external_exports.array(external_exports.string()).nullish(),
998
+ tasksSupported: external_exports.array(external_exports.string()).nullish(),
999
+ scope: external_exports.string().nullish(),
1000
+ exclusions: external_exports.string().nullish(),
1001
+ appliesTo: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).nullish(),
1002
+ provenanceSummary: external_exports.string().nullish(),
1003
+ methodologySummary: external_exports.string().nullish(),
1004
+ maintenanceCadence: external_exports.string().nullish(),
1005
+ reproductionMinutes: external_exports.number().nullish(),
1006
+ estimatedPaidInputCost: external_exports.string().nullish(),
809
1007
  cacheEligible: external_exports.boolean(),
810
1008
  cacheEligibleMissing: external_exports.array(external_exports.string())
811
1009
  }).passthrough();
@@ -816,6 +1014,9 @@ var ownPostSchema = external_exports.object({
816
1014
  status: external_exports.string(),
817
1015
  price: external_exports.string(),
818
1016
  url: external_exports.string(),
1017
+ excerpt: external_exports.string().nullish(),
1018
+ bodyMd: external_exports.string().nullish(),
1019
+ tags: external_exports.array(external_exports.string()).nullish(),
819
1020
  warnings: external_exports.array(external_exports.string()).optional(),
820
1021
  resource: resourceEchoSchema.optional()
821
1022
  }).passthrough();
@@ -867,6 +1068,179 @@ async function publishPost(input, auth, opts) {
867
1068
  };
868
1069
  }
869
1070
  }
1071
+ function buildPostUpdateBody(input) {
1072
+ const title = input.title?.trim();
1073
+ if (input.title !== void 0 && (title === void 0 || title.length === 0)) {
1074
+ throw new CliError("USAGE", "title cannot be empty.", {
1075
+ fix: "Pass a title, or omit --title to keep the stored one."
1076
+ });
1077
+ }
1078
+ if (title !== void 0 && title.length > 200) {
1079
+ throw new CliError("USAGE", "title must be at most 200 characters.");
1080
+ }
1081
+ if (input.bodyMd !== void 0) {
1082
+ if (input.bodyMd.trim().length === 0) {
1083
+ throw new CliError("USAGE", "bodyMd cannot be empty.", {
1084
+ fix: "Pass a file with Markdown in it, or omit --body to keep the stored body."
1085
+ });
1086
+ }
1087
+ if (input.bodyMd.length > 2e5) {
1088
+ throw new CliError("USAGE", "bodyMd must be at most 200000 characters.");
1089
+ }
1090
+ }
1091
+ const excerpt = input.excerpt?.trim();
1092
+ if (excerpt !== void 0 && excerpt.length > 500) {
1093
+ throw new CliError("USAGE", "excerpt must be at most 500 characters.");
1094
+ }
1095
+ if (input.tags !== void 0) {
1096
+ if (input.tags.length > 5) throw new CliError("USAGE", "at most 5 tags.");
1097
+ for (const tag of input.tags) {
1098
+ if (tag.length === 0 || tag.length > 50) {
1099
+ throw new CliError("USAGE", "each tag is 1 to 50 characters.");
1100
+ }
1101
+ }
1102
+ }
1103
+ if (input.priceAtomic !== void 0 && !PRICE_RE.test(input.priceAtomic)) {
1104
+ throw new CliError("USAGE", `Invalid price: ${JSON.stringify(input.priceAtomic)}`, {
1105
+ fix: "A price is an atomic USDC integer up to 13 digits, e.g. 100000 for $0.10."
1106
+ });
1107
+ }
1108
+ const body = {
1109
+ ...title !== void 0 ? { title } : {},
1110
+ ...input.bodyMd !== void 0 ? { bodyMd: input.bodyMd } : {},
1111
+ ...excerpt !== void 0 ? { excerpt } : {},
1112
+ ...input.tags !== void 0 ? { tags: input.tags } : {},
1113
+ ...input.priceAtomic !== void 0 ? { price: input.priceAtomic } : {},
1114
+ ...input.status !== void 0 ? { status: input.status } : {},
1115
+ ...input.resource !== void 0 ? { resource: input.resource } : {}
1116
+ };
1117
+ if (Object.keys(body).length === 0) {
1118
+ throw new CliError("USAGE", "Nothing to update.", {
1119
+ fix: "Pass at least one field flag, or run `tenjin edit <postId>` with no flags to view the post."
1120
+ });
1121
+ }
1122
+ return body;
1123
+ }
1124
+ async function getOwnPost(id, auth, opts) {
1125
+ const url = `${trimSlash(opts.baseUrl)}/api/posts/${encodeURIComponent(id)}`;
1126
+ let recoveries = 0;
1127
+ for (; ; ) {
1128
+ const authHeaders = await auth.headersFor({ method: "GET", url });
1129
+ const res = await httpRequest(url, {
1130
+ method: "GET",
1131
+ timeoutMs: opts.timeoutMs,
1132
+ headers: { accept: "application/json", "x-tenjin-client": CLIENT_HEADER, ...authHeaders },
1133
+ ...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {}
1134
+ });
1135
+ if (!res.ok) throw writeTransportError(url, res);
1136
+ if (res.status === 401 && recoveries < MAX_RECOVERIES) {
1137
+ const code = auth401Code(res);
1138
+ if (await auth.recover(code)) {
1139
+ recoveries++;
1140
+ continue;
1141
+ }
1142
+ throw readAuthError(code, res);
1143
+ }
1144
+ if (res.status === 401) throw readAuthError(auth401Code(res), res);
1145
+ if (res.status === 404) throw postNotFound(id);
1146
+ if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
1147
+ if (res.status !== 200) {
1148
+ throw new CliError(
1149
+ "API_UNREACHABLE",
1150
+ serverMessage(res.json) ?? `Could not read post ${id} (${res.status}).`,
1151
+ {
1152
+ fix: "Review the server error, then retry.",
1153
+ details: { status: res.status, ...res.json !== void 0 ? { server: res.json } : {} }
1154
+ }
1155
+ );
1156
+ }
1157
+ return parseOwnPost(res.json, "read");
1158
+ }
1159
+ }
1160
+ async function updatePost(id, input, auth, opts) {
1161
+ const body = buildPostUpdateBody(input);
1162
+ const url = `${trimSlash(opts.baseUrl)}/api/posts/${encodeURIComponent(id)}`;
1163
+ const bodyStr = JSON.stringify(body);
1164
+ let recoveries = 0;
1165
+ for (; ; ) {
1166
+ const authHeaders = await auth.headersFor({ method: "PUT", url, body: bodyStr });
1167
+ const res = await httpRequest(url, {
1168
+ method: "PUT",
1169
+ timeoutMs: opts.timeoutMs,
1170
+ headers: { "x-tenjin-client": CLIENT_HEADER, ...authHeaders },
1171
+ jsonBody: body,
1172
+ ...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {}
1173
+ });
1174
+ if (!res.ok) throw writeTransportError(url, res);
1175
+ if (res.status === 401 && recoveries < MAX_RECOVERIES) {
1176
+ const code = auth401Code(res);
1177
+ if (await auth.recover(code)) {
1178
+ recoveries++;
1179
+ continue;
1180
+ }
1181
+ throw authError(code, res);
1182
+ }
1183
+ if (res.status === 401) throw authError(auth401Code(res), res);
1184
+ if (res.status === 404) throw postNotFound(id);
1185
+ if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
1186
+ if (res.status !== 200) throw updateFailed(res);
1187
+ return parseOwnPost(res.json, "update");
1188
+ }
1189
+ }
1190
+ function parseOwnPost(json, what) {
1191
+ const parsed = ownPostSchema.safeParse(json);
1192
+ if (!parsed.success) {
1193
+ throw new CliError(
1194
+ "CONTRACT_MISMATCH",
1195
+ `The post ${what} response did not match the contract.`,
1196
+ {
1197
+ fix: "Update tenjin-cli; the server contract may have changed.",
1198
+ details: parsed.error.issues
1199
+ }
1200
+ );
1201
+ }
1202
+ return parsed.data;
1203
+ }
1204
+ function postNotFound(id) {
1205
+ return new CliError("RESOURCE_NOT_FOUND", `Post ${id} was not found, or is not yours.`, {
1206
+ fix: "Check the post id on your desk; owner-scoped routes do not distinguish the two."
1207
+ });
1208
+ }
1209
+ function readAuthError(code, res) {
1210
+ return new CliError(
1211
+ "API_UNREACHABLE",
1212
+ serverMessage(res.json) ?? `Reading the post was not authorized (${code ?? "401"}).`,
1213
+ {
1214
+ fix: code === "session_key_unbound" ? "Delete ~/.tenjin/session.json to re-establish the session key." : "Check the wallet and retry.",
1215
+ details: {
1216
+ code: code ?? "unauthorized",
1217
+ ...res.json !== void 0 ? { server: res.json } : {}
1218
+ }
1219
+ }
1220
+ );
1221
+ }
1222
+ function updateFailed(res) {
1223
+ const fields = fieldErrorKeys(res.json);
1224
+ const base = serverMessage(res.json) ?? `Update failed (${res.status}).`;
1225
+ return new CliError(
1226
+ "PUBLISH_FAILED",
1227
+ fields.length > 0 ? `${base} (${fields.join(", ")})` : base,
1228
+ {
1229
+ fix: fields.length > 0 ? "Correct the reported fields, then re-run `tenjin edit`." : "Review the server error, then re-run `tenjin edit`.",
1230
+ details: { status: res.status, ...res.json !== void 0 ? { server: res.json } : {} }
1231
+ }
1232
+ );
1233
+ }
1234
+ function fieldErrorKeys(json) {
1235
+ if (typeof json !== "object" || json === null) return [];
1236
+ const err = json.error;
1237
+ if (typeof err !== "object" || err === null) return [];
1238
+ const details = err.details;
1239
+ if (typeof details !== "object" || details === null) return [];
1240
+ const fieldErrors = details.fieldErrors;
1241
+ if (typeof fieldErrors !== "object" || fieldErrors === null) return [];
1242
+ return Object.keys(fieldErrors);
1243
+ }
870
1244
  function auth401Code(res) {
871
1245
  const header = res.header("www-authenticate");
872
1246
  const m = header !== void 0 ? /error="([^"]+)"/.exec(header) : null;
@@ -919,523 +1293,47 @@ function publishFailed(res) {
919
1293
  function writeTransportError(url, result) {
920
1294
  const code = result.kind === "network" || result.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
921
1295
  return new CliError(code, `${url}: ${result.message}`, {
922
- fix: "Check --base-url and your network, then retry."
1296
+ fix: "Check your network and the configured base URL (`tenjin config get baseUrl`), then retry."
923
1297
  });
924
1298
  }
925
1299
 
926
- // src/lib/session-key.ts
927
- import { createHash, randomBytes, webcrypto } from "crypto";
928
- import { readFile, stat } from "fs/promises";
929
- var SESSION_SCOPE = "read+write";
930
- var SESSION_TTL_MS = 24 * 60 * 60 * 1e3;
931
- var EXP_SKEW_MS = 6e4;
932
- var SessionFileSchema = external_exports.object({
933
- /** Lowercased wallet address this delegation is bound to. */
934
- address: external_exports.string(),
935
- /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */
936
- delegation: external_exports.string(),
937
- /** Delegation expiry (ISO 8601); a request is never signed at/after this. */
938
- exp: external_exports.string(),
939
- scope: external_exports.string(),
940
- /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */
941
- publicKeyRaw: external_exports.string(),
942
- /** The P-256 private key as a JWK, re-imported to sign each request. */
943
- privateKeyJwk: external_exports.record(external_exports.string(), external_exports.unknown())
944
- });
945
- var subtle = webcrypto.subtle;
946
- function toBase64(bytes) {
947
- return Buffer.from(bytes).toString("base64");
948
- }
949
- function toBase64Url(bytes) {
950
- return Buffer.from(bytes).toString("base64url");
951
- }
952
- function contentDigest(body) {
953
- const hash = createHash("sha256").update(body, "utf8").digest();
954
- return `sha-256=:${hash.toString("base64")}:`;
955
- }
956
- function targetUri(url) {
957
- const u = new URL(url);
958
- return `${u.protocol}//${u.host}${u.pathname}${u.search}`;
959
- }
960
- function signatureParams(input) {
961
- const covered = input.contentDigest !== void 0 ? '"@method" "@target-uri" "content-digest"' : '"@method" "@target-uri"';
962
- return `(${covered});created=${input.created};nonce="${input.nonce}";keyid="${input.keyid}";alg="ecdsa-p256-sha256"`;
963
- }
964
- function signatureBase(input) {
965
- const params = signatureParams(input);
966
- const lines = [
967
- `"@method": ${input.method.toUpperCase()}`,
968
- `"@target-uri": ${targetUri(input.url)}`,
969
- ...input.contentDigest !== void 0 ? [`"content-digest": ${input.contentDigest}`] : [],
970
- `"@signature-params": ${params}`
971
- ];
972
- return lines.join("\n");
973
- }
974
- function generateP256KeyPair() {
975
- return subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
976
- "sign",
977
- "verify"
978
- ]);
979
- }
980
- async function importSigningKey(jwk) {
981
- return subtle.importKey(
982
- "jwk",
983
- jwk,
984
- { name: "ECDSA", namedCurve: "P-256" },
985
- false,
986
- ["sign"]
987
- );
988
- }
989
- async function signBase(jwk, base) {
990
- const key = await importSigningKey(jwk);
991
- const sig = await subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, Buffer.from(base, "utf8"));
992
- return toBase64(new Uint8Array(sig));
993
- }
994
- function keyidFor(publicKeyRaw) {
995
- return `p256:${publicKeyRaw}`;
996
- }
997
- function delegationResources(publicKeyRaw, expIso) {
998
- return [
999
- `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,
1000
- `urn:tenjin:session:exp:${expIso}`,
1001
- `urn:tenjin:session:scope:${SESSION_SCOPE}`
1002
- ];
1003
- }
1004
- async function establishSession(config, deps = {}) {
1005
- const now = deps.now ?? Date.now;
1006
- const pair = await generateP256KeyPair();
1007
- const rawPub = new Uint8Array(await subtle.exportKey("raw", pair.publicKey));
1008
- const publicKeyRaw = toBase64Url(rawPub);
1009
- const jwk = await subtle.exportKey("jwk", pair.privateKey);
1010
- const expIso = new Date(now() + SESSION_TTL_MS).toISOString();
1011
- const delegation = await buildSiwxHeader(config.signer, {
1012
- baseUrl: config.baseUrl,
1013
- chainId: config.chainId,
1014
- ttlMs: SESSION_TTL_MS,
1015
- statement: "Delegate a Tenjin session key.",
1016
- resources: delegationResources(publicKeyRaw, expIso)
1017
- });
1018
- const file = {
1019
- address: config.signer.address.toLowerCase(),
1020
- delegation,
1021
- exp: expIso,
1022
- scope: SESSION_SCOPE,
1023
- publicKeyRaw,
1024
- privateKeyJwk: jwk
1025
- };
1026
- await saveSessionFile(config.dataDir, file);
1027
- return file;
1028
- }
1029
- async function signWithSession(file, req, deps = {}) {
1030
- const now = deps.now ?? Date.now;
1031
- const nonce = deps.nonce ?? (() => randomBytes(16).toString("hex"));
1032
- const digest = contentDigest(req.body);
1033
- const created = Math.floor(now() / 1e3);
1034
- const params = {
1035
- method: req.method,
1036
- url: req.url,
1037
- contentDigest: digest,
1038
- created,
1039
- nonce: nonce(),
1040
- keyid: keyidFor(file.publicKeyRaw)
1041
- };
1042
- const base = signatureBase(params);
1043
- const signature = await signBase(file.privateKeyJwk, base);
1044
- return {
1045
- "Tenjin-Session-Delegation": file.delegation,
1046
- "Signature-Input": `tenjin=${signatureParams(params)}`,
1047
- Signature: `tenjin=:${signature}:`,
1048
- "Content-Digest": digest
1049
- };
1050
- }
1051
- async function loadSessionFile(dir) {
1052
- const path = sessionPath(dir);
1053
- if (process.platform !== "win32") {
1054
- try {
1055
- const mode = (await stat(path)).mode & 63;
1056
- if (mode !== 0) return null;
1057
- } catch (err) {
1058
- if (hasCode(err, "ENOENT")) return null;
1059
- throw sessionReadError(path, err);
1060
- }
1061
- }
1062
- let raw;
1063
- try {
1064
- raw = await readFile(path, "utf8");
1065
- } catch (err) {
1066
- if (hasCode(err, "ENOENT")) return null;
1067
- throw sessionReadError(path, err);
1068
- }
1069
- let json;
1070
- try {
1071
- json = JSON.parse(raw);
1072
- } catch {
1073
- return null;
1074
- }
1075
- const parsed = SessionFileSchema.safeParse(json);
1076
- return parsed.success ? parsed.data : null;
1077
- }
1078
- function sessionReadError(path, cause) {
1079
- return new CliError("INTERNAL", `Could not read the session cache at ${path}`, {
1080
- fix: `Check file permissions on ${path}, or delete it to re-establish.`,
1081
- cause
1082
- });
1083
- }
1084
- async function saveSessionFile(dir, file) {
1085
- await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}
1086
- `, {
1087
- mode: 384,
1088
- dirMode: 448
1089
- });
1090
- }
1091
- function isSessionUsable(file, address, now) {
1092
- if (file.address !== address.toLowerCase()) return false;
1093
- if (file.scope !== SESSION_SCOPE) return false;
1094
- const expMs = Date.parse(file.exp);
1095
- if (!Number.isFinite(expMs)) return false;
1096
- return now < expMs - EXP_SKEW_MS;
1097
- }
1098
- function recoveryFor(code) {
1099
- switch (code) {
1100
- case "proof_expired":
1101
- return "resign";
1102
- case "session_expired":
1103
- case "proof_revoked":
1104
- case "insufficient_scope":
1105
- return "reestablish";
1106
- case "session_key_unbound":
1107
- return "fatal";
1108
- default:
1109
- return "fatal";
1110
- }
1111
- }
1112
- function createSessionKeyAuth(config, deps = {}) {
1113
- const now = deps.now ?? Date.now;
1114
- let cached = null;
1115
- let forceReestablish = false;
1116
- const ensure = async () => {
1117
- if (!forceReestablish && cached !== null && isSessionUsable(cached, config.signer.address, now())) {
1118
- return cached;
1119
- }
1120
- if (!forceReestablish) {
1121
- const onDisk = await loadSessionFile(config.dataDir);
1122
- if (onDisk !== null && isSessionUsable(onDisk, config.signer.address, now())) {
1123
- cached = onDisk;
1124
- return cached;
1125
- }
1126
- }
1127
- cached = await establishSession(config, deps);
1128
- forceReestablish = false;
1129
- return cached;
1130
- };
1131
- return {
1132
- async headersFor(req) {
1133
- const file = await ensure();
1134
- return signWithSession(file, req, deps);
1135
- },
1136
- async recover(code) {
1137
- const recovery = recoveryFor(code);
1138
- if (recovery === "fatal") return false;
1139
- if (recovery === "reestablish") {
1140
- cached = null;
1141
- forceReestablish = true;
1142
- }
1143
- return true;
1144
- }
1300
+ // src/lib/consent.ts
1301
+ var WRITE_CHAIN_ID = SESSION_CHAIN_ID;
1302
+ function resolveWriteAuth(opts) {
1303
+ const config = {
1304
+ signer: opts.signer,
1305
+ baseUrl: opts.baseUrl,
1306
+ chainId: WRITE_CHAIN_ID,
1307
+ dataDir: opts.dataDir,
1308
+ scope: opts.scope
1145
1309
  };
1310
+ const useSession = opts.useSession ?? opts.env.TENJIN_NO_SESSION !== "1";
1311
+ return useSession ? createSessionKeyAuth(config) : createSiwxAuth(config);
1146
1312
  }
1147
- function createSiwxAuth(config) {
1148
- return {
1149
- async headersFor() {
1150
- const header = await buildSiwxHeader(config.signer, {
1151
- baseUrl: config.baseUrl,
1152
- chainId: config.chainId
1153
- });
1154
- return { "SIGN-IN-WITH-X": header };
1155
- },
1156
- async recover(code) {
1157
- return code === "nonce_already_used" || code === "invalid_proof" || code === "proof_expired";
1158
- }
1159
- };
1313
+ function needsConfirmation(mode, warnCount) {
1314
+ return mode === "review" || mode === "auto" && warnCount > 0;
1160
1315
  }
1161
-
1162
- // src/commands/publish.ts
1163
- var WRITE_CHAIN_ID = "eip155:8453";
1164
- async function runPublish(args, ctx, deps = {}) {
1165
- const env = deps.env ?? process.env;
1166
- const cwd = deps.cwd ?? process.cwd();
1167
- if (args.mode !== void 0) parsePublishModeFlag(args.mode, "--mode");
1168
- const { raw, candidate } = await resolveSource(args, ctx.dataDir);
1169
- const { frontmatter, body } = parseFrontmatter(raw);
1170
- const status = resolveStatus(args, frontmatter);
1171
- const title = resolveTitle(frontmatter, body);
1172
- const tags = resolveTags(frontmatter);
1173
- const excerpt = expectString(frontmatter, "excerpt");
1174
- const handle = expectString(frontmatter, "handle");
1175
- const cardFlags = cardFlagsFrom(args);
1176
- if (candidate?.meta.question !== void 0 && cardFlags.question === void 0 && frontmatter.questionsAnswered === void 0) {
1177
- cardFlags.question = [candidate.meta.question];
1178
- }
1179
- const card = deriveCard(frontmatter, cardFlags);
1180
- const settings = await resolvePublishSettings({
1181
- dataDir: ctx.dataDir,
1182
- cwd,
1183
- ...args.mode !== void 0 ? { flag: args.mode } : {},
1184
- env
1185
- });
1316
+ function writeModeNotices(stderr, settings, env, defaultExplainer) {
1186
1317
  for (const warning of settings.warnings) {
1187
- ctx.io.stderr.write(`${warning}
1318
+ stderr.write(`${warning}
1188
1319
  `);
1189
1320
  }
1190
1321
  const envMode = env.TENJIN_PUBLISH_MODE;
1191
1322
  if (envMode !== void 0 && envMode.length > 0 && !PublishModeSchema.safeParse(envMode).success) {
1192
- ctx.io.stderr.write(
1323
+ stderr.write(
1193
1324
  `Ignoring invalid TENJIN_PUBLISH_MODE=${JSON.stringify(envMode)}; using ${settings.mode} (${settings.modeSource}).
1194
1325
  `
1195
1326
  );
1196
1327
  }
1197
1328
  if (settings.modeSource === "default") {
1198
- ctx.io.stderr.write(
1199
- `publish.mode: ${settings.mode} (default) - each publish asks you once. Set auto to publish clean scans automatically: tenjin config set publish.mode auto.
1329
+ stderr.write(
1330
+ `publish.mode: ${settings.mode} (default) - ${defaultExplainer}: tenjin config set publish.mode auto.
1200
1331
  `
1201
1332
  );
1202
1333
  }
1203
- const priceAtomic = resolvePrice(args, frontmatter, settings.defaultPriceAtomic);
1204
- const findings = dedupeFindings([...scan(raw), ...scan(cardScanText(card))]);
1205
- const blocking = findings.filter((f) => f.severity === "block");
1206
- const warns = findings.filter((f) => f.severity === "warn");
1207
- const eligibility = localCardEligibility(card);
1208
- const price = toMoney(priceAtomic);
1209
- if (blocking.length > 0) {
1210
- throw new CliError("PUBLISH_BLOCKED", blockMessage(blocking), {
1211
- fix: "Remove the secret from the file (it is never masked away by --yes), then re-run.",
1212
- details: {
1213
- mode: settings.mode,
1214
- findings: blocking.map(publicFinding),
1215
- price: { atomic: price.atomic, usd: price.usd }
1216
- }
1217
- });
1218
- }
1219
- const needsConfirm = settings.mode === "review" || settings.mode === "auto" && warns.length > 0;
1220
- if (needsConfirm && args.yes !== true) {
1221
- throw new CliError("NEEDS_CONFIRMATION", confirmMessage(warns.length, price.usd), {
1222
- fix: "Review the findings, then re-run with --yes (or resolve the source and re-run).",
1223
- details: {
1224
- mode: settings.mode,
1225
- price: { atomic: price.atomic, usd: price.usd },
1226
- findings: warns.map(publicFinding),
1227
- card: eligibility,
1228
- target: { status, titlePreview: sanitizeForTerminal(title ?? "(untitled draft)") }
1229
- }
1230
- });
1231
- }
1232
- const runtime = await resolveContextSettings(ctx);
1233
- const provider = resolveWalletProvider(
1234
- ctx,
1235
- deps.provider !== void 0 ? { provider: deps.provider } : {}
1236
- );
1237
- await describeWallet(provider);
1238
- const signer = await provider.getSigner();
1239
- const auth = resolveWriteAuth(signer, runtime.baseUrl, ctx.dataDir, deps, env);
1240
- const input = {
1241
- ...title !== void 0 ? { title } : {},
1242
- bodyMd: body,
1243
- ...excerpt !== void 0 ? { excerpt } : {},
1244
- ...tags !== void 0 ? { tags } : {},
1245
- priceAtomic,
1246
- ...handle !== void 0 ? { handle } : {},
1247
- status,
1248
- ...card !== void 0 ? { resource: card } : {}
1249
- };
1250
- const result = await publishPost(input, auth, {
1251
- baseUrl: runtime.baseUrl,
1252
- timeoutMs: ctx.flags.timeout,
1253
- ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
1254
- });
1255
- const candidateInfo = candidate !== void 0 ? await clearPublishedCandidate(ctx, candidate.id) : void 0;
1256
- return receipt(result, runtime.baseUrl, candidateInfo);
1257
1334
  }
1258
- async function clearPublishedCandidate(ctx, id) {
1259
- try {
1260
- if (await dropCandidate(ctx.dataDir, id)) return { id, cleared: true };
1261
- const warning = `Published, but candidate ${id} was already gone; nothing to clear.`;
1262
- ctx.io.stderr.write(`${warning}
1263
- `);
1264
- return { id, cleared: false, warning };
1265
- } catch (err) {
1266
- const warning = `Published successfully, but could not clear candidate ${id}: ${errorMessage(err)}. Remove it with \`tenjin candidate drop ${id}\`.`;
1267
- ctx.io.stderr.write(`${warning}
1268
- `);
1269
- return { id, cleared: false, warning };
1270
- }
1271
- }
1272
- function errorMessage(err) {
1273
- return err instanceof Error ? err.message : String(err);
1274
- }
1275
- async function resolveSource(args, dataDir) {
1276
- if (args.candidate !== void 0) {
1277
- if (args.file !== void 0) {
1278
- throw new CliError("USAGE", "Pass EITHER a file or --candidate, not both.", {
1279
- fix: "Publish a file with `tenjin publish post.md`, or a candidate with `--candidate <id>`."
1280
- });
1281
- }
1282
- if (!UUID_RE.test(args.candidate)) {
1283
- throw new CliError("USAGE", `Invalid candidate id: ${JSON.stringify(args.candidate)}`, {
1284
- fix: "Pass a candidate id from `tenjin candidate list`."
1285
- });
1286
- }
1287
- const record = await readCandidate(dataDir, args.candidate);
1288
- if (record === null) {
1289
- throw new CliError("USAGE", `Unknown candidate: ${JSON.stringify(args.candidate)}`, {
1290
- fix: "List parked candidates with `tenjin candidate list`."
1291
- });
1292
- }
1293
- return { raw: await readDraft(record), candidate: record };
1294
- }
1295
- if (args.file === void 0) {
1296
- throw new CliError("USAGE", "Nothing to publish.", {
1297
- fix: "Pass a Markdown file (`tenjin publish post.md`) or `--candidate <id>`."
1298
- });
1299
- }
1300
- return { raw: await readMarkdown(args.file) };
1301
- }
1302
- async function readDraft(record) {
1303
- try {
1304
- return await readFile2(record.draftPath, "utf8");
1305
- } catch (err) {
1306
- throw new CliError("INTERNAL", `Candidate ${record.id} is missing its draft.`, {
1307
- fix: `Drop it with \`tenjin candidate drop ${record.id}\` and re-add the draft.`,
1308
- cause: err
1309
- });
1310
- }
1311
- }
1312
- function receipt(result, baseUrl, candidateInfo) {
1313
- const price = toMoney(result.priceAtomic);
1314
- const missing = missingSentences(result.cacheEligibleMissing);
1315
- const cacheEligible = result.cacheEligible ?? false;
1316
- const deskUrl = `${trimSlash(baseUrl)}/desk`;
1317
- const title = sanitizeForTerminal(result.title);
1318
- const human = [
1319
- `Published ${title} (${result.status}) for ${price.usd} USD \u2192 ${result.url}`,
1320
- 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).",
1321
- ...candidateInfo?.cleared === true ? [`Cleared candidate ${candidateInfo.id}.`] : [],
1322
- ...result.warnings.map((w) => `warning: ${sanitizeForTerminal(w)}`)
1323
- ];
1324
- return {
1325
- data: {
1326
- resourceId: result.resourceId,
1327
- url: result.url,
1328
- status: result.status,
1329
- price,
1330
- cacheEligible,
1331
- missing,
1332
- deskUrl,
1333
- ...candidateInfo !== void 0 ? { candidate: candidateInfo } : {},
1334
- ...result.warnings.length > 0 ? { warnings: result.warnings } : {}
1335
- },
1336
- humanLines: human
1337
- };
1338
- }
1339
- async function readMarkdown(file) {
1340
- try {
1341
- return await readFile2(file, "utf8");
1342
- } catch (err) {
1343
- throw new CliError("USAGE", `Could not read ${JSON.stringify(file)}`, {
1344
- fix: "Pass a path to a readable Markdown file, e.g. `tenjin publish post.md`.",
1345
- cause: err
1346
- });
1347
- }
1348
- }
1349
- function resolveStatus(args, frontmatter) {
1350
- if (args.draft === true) return "draft";
1351
- const fm = frontmatter.status;
1352
- if (fm === void 0) return "published";
1353
- if (typeof fm !== "string" || !PUBLISH_STATUSES.includes(fm)) {
1354
- throw new CliError("USAGE", `Invalid status ${JSON.stringify(fm)} in frontmatter.`, {
1355
- fix: "Use status: draft | published | unlisted, or pass --draft."
1356
- });
1357
- }
1358
- return fm;
1359
- }
1360
- function resolveTitle(frontmatter, body) {
1361
- const fm = frontmatter.title;
1362
- if (fm !== void 0) {
1363
- if (typeof fm !== "string") {
1364
- throw new CliError("USAGE", "frontmatter title must be a single string.");
1365
- }
1366
- return fm.trim();
1367
- }
1368
- const headings = headingOutline(body);
1369
- const h1 = headings.find((h) => h.level === 1) ?? headings[0];
1370
- return h1?.text;
1371
- }
1372
- function resolveTags(frontmatter) {
1373
- const fm = frontmatter.tags;
1374
- if (fm === void 0) return void 0;
1375
- if (typeof fm === "string") return [fm];
1376
- if (Array.isArray(fm)) return fm;
1377
- throw new CliError("USAGE", "frontmatter tags must be a list of strings.");
1378
- }
1379
- function expectString(frontmatter, key) {
1380
- const fm = frontmatter[key];
1381
- if (fm === void 0) return void 0;
1382
- if (typeof fm !== "string") {
1383
- throw new CliError("USAGE", `frontmatter ${key} must be a single string.`);
1384
- }
1385
- return fm;
1386
- }
1387
- function resolvePrice(args, frontmatter, defaultAtomic) {
1388
- if (args.price !== void 0) return parseUsdToAtomic(args.price);
1389
- const fm = frontmatter.price;
1390
- if (fm !== void 0) {
1391
- if (typeof fm !== "string") {
1392
- throw new CliError("USAGE", 'frontmatter price must be a decimal-USD string, e.g. "0.10".');
1393
- }
1394
- return parseUsdToAtomic(fm);
1395
- }
1396
- return defaultAtomic;
1397
- }
1398
- function cardFlagsFrom(args) {
1399
- return {
1400
- ...args.question !== void 0 && args.question.length > 0 ? { question: args.question } : {},
1401
- ...args.task !== void 0 && args.task.length > 0 ? { task: args.task } : {},
1402
- ...args.scope !== void 0 ? { scope: args.scope } : {},
1403
- ...args.exclusions !== void 0 ? { exclusions: args.exclusions } : {},
1404
- ...args.asOf !== void 0 ? { asOf: args.asOf } : {},
1405
- ...args.validUntil !== void 0 ? { validUntil: args.validUntil } : {},
1406
- ...args.artifactType !== void 0 ? { artifactType: args.artifactType } : {},
1407
- ...args.temporalMode !== void 0 ? { temporalMode: args.temporalMode } : {},
1408
- ...args.provenance !== void 0 ? { provenance: args.provenance } : {},
1409
- ...args.methodology !== void 0 ? { methodology: args.methodology } : {},
1410
- ...args.appliesTo !== void 0 && args.appliesTo.length > 0 ? { appliesTo: parseAppliesToFlags(args.appliesTo) } : {}
1411
- };
1412
- }
1413
- function resolveWriteAuth(signer, baseUrl, dataDir, deps, env) {
1414
- const config = { signer, baseUrl, chainId: WRITE_CHAIN_ID, dataDir };
1415
- const useSession = deps.useSession ?? env.TENJIN_NO_SESSION !== "1";
1416
- return useSession ? createSessionKeyAuth(config) : createSiwxAuth(config);
1417
- }
1418
- function cardScanText(card) {
1419
- if (card === void 0) return "";
1420
- const parts = [];
1421
- const add = (v) => {
1422
- if (v !== void 0) parts.push(v);
1423
- };
1424
- add(card.scope);
1425
- add(card.exclusions);
1426
- add(card.provenanceSummary);
1427
- add(card.methodologySummary);
1428
- add(card.mediaType);
1429
- add(card.maintenanceCadence);
1430
- add(card.asOf);
1431
- add(card.validUntil);
1432
- add(card.estimatedPaidInputCost);
1433
- if (card.questionsAnswered !== void 0) parts.push(...card.questionsAnswered);
1434
- if (card.tasksSupported !== void 0) parts.push(...card.tasksSupported);
1435
- if (card.appliesTo !== void 0) {
1436
- for (const values of Object.values(card.appliesTo)) parts.push(...values);
1437
- }
1438
- return parts.join("\n");
1335
+ function publicFinding(f) {
1336
+ return { check: f.check, severity: f.severity, line: f.line, excerpt: f.excerpt };
1439
1337
  }
1440
1338
  function dedupeFindings(findings) {
1441
1339
  const seen = /* @__PURE__ */ new Set();
@@ -1446,18 +1344,29 @@ function dedupeFindings(findings) {
1446
1344
  return true;
1447
1345
  });
1448
1346
  }
1449
- function publicFinding(f) {
1450
- return { check: f.check, severity: f.severity, line: f.line, excerpt: f.excerpt };
1451
- }
1452
- function blockMessage(blocking) {
1347
+ function describeFindings(blocking) {
1453
1348
  const checks = [...new Set(blocking.map((f) => f.check))].join(", ");
1454
- return `Publish blocked: the file contains ${blocking.length} secret finding(s) (${checks}).`;
1455
- }
1456
- function confirmMessage(warnCount, priceUsd) {
1457
- return warnCount > 0 ? `Publish needs confirmation: ${warnCount} finding(s), price $${priceUsd}.` : `Publish needs confirmation: price $${priceUsd}.`;
1349
+ return `${blocking.length} secret finding(s) (${checks})`;
1458
1350
  }
1459
1351
 
1460
1352
  export {
1461
- runPublish
1353
+ scan,
1354
+ deriveProjectMarkers,
1355
+ parseFrontmatter,
1356
+ deriveCard,
1357
+ parseAppliesToFlags,
1358
+ missingSentences,
1359
+ localCardEligibility,
1360
+ PUBLISH_STATUSES,
1361
+ publishPost,
1362
+ buildPostUpdateBody,
1363
+ getOwnPost,
1364
+ updatePost,
1365
+ resolveWriteAuth,
1366
+ needsConfirmation,
1367
+ writeModeNotices,
1368
+ publicFinding,
1369
+ dedupeFindings,
1370
+ describeFindings
1462
1371
  };
1463
- //# sourceMappingURL=chunk-ULLWHHIT.js.map
1372
+ //# sourceMappingURL=chunk-PLU3E63S.js.map