@trazum/cli 3.0.0 → 3.0.2

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 (109) hide show
  1. package/README.md +4 -1
  2. package/assets/trazum-statusline.sh +45 -0
  3. package/dist/base-cost.d.ts +173 -0
  4. package/dist/base-cost.d.ts.map +1 -0
  5. package/dist/base-cost.js +244 -0
  6. package/dist/base-cost.js.map +1 -0
  7. package/dist/bill-range.d.ts +118 -0
  8. package/dist/bill-range.d.ts.map +1 -0
  9. package/dist/bill-range.js +122 -0
  10. package/dist/bill-range.js.map +1 -0
  11. package/dist/command-help.d.ts +17 -0
  12. package/dist/command-help.d.ts.map +1 -0
  13. package/dist/command-help.js +69 -0
  14. package/dist/command-help.js.map +1 -0
  15. package/dist/filter.d.ts +7 -1
  16. package/dist/filter.d.ts.map +1 -1
  17. package/dist/filter.js +10 -18
  18. package/dist/filter.js.map +1 -1
  19. package/dist/gateway-metrics.d.ts +83 -0
  20. package/dist/gateway-metrics.d.ts.map +1 -0
  21. package/dist/gateway-metrics.js +181 -0
  22. package/dist/gateway-metrics.js.map +1 -0
  23. package/dist/gateway-server.d.ts +23 -5
  24. package/dist/gateway-server.d.ts.map +1 -1
  25. package/dist/gateway-server.js +26 -1
  26. package/dist/gateway-server.js.map +1 -1
  27. package/dist/gateway-spend.d.ts +11 -1
  28. package/dist/gateway-spend.d.ts.map +1 -1
  29. package/dist/gateway-spend.js +44 -32
  30. package/dist/gateway-spend.js.map +1 -1
  31. package/dist/git.d.ts +70 -0
  32. package/dist/git.d.ts.map +1 -1
  33. package/dist/git.js +145 -0
  34. package/dist/git.js.map +1 -1
  35. package/dist/i18n/en.d.ts.map +1 -1
  36. package/dist/i18n/en.js +358 -6
  37. package/dist/i18n/en.js.map +1 -1
  38. package/dist/i18n/es.d.ts +0 -1
  39. package/dist/i18n/es.d.ts.map +1 -1
  40. package/dist/i18n/es.js +456 -35
  41. package/dist/i18n/es.js.map +1 -1
  42. package/dist/i18n/types.d.ts +205 -0
  43. package/dist/i18n/types.d.ts.map +1 -1
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +942 -59
  46. package/dist/index.js.map +1 -1
  47. package/dist/loopback-guard.d.ts +37 -0
  48. package/dist/loopback-guard.d.ts.map +1 -0
  49. package/dist/loopback-guard.js +65 -0
  50. package/dist/loopback-guard.js.map +1 -0
  51. package/dist/markdown.d.ts +23 -0
  52. package/dist/markdown.d.ts.map +1 -1
  53. package/dist/markdown.js +105 -0
  54. package/dist/markdown.js.map +1 -1
  55. package/dist/plan-edits.d.ts +63 -0
  56. package/dist/plan-edits.d.ts.map +1 -0
  57. package/dist/plan-edits.js +96 -0
  58. package/dist/plan-edits.js.map +1 -0
  59. package/dist/proactive.d.ts +17 -2
  60. package/dist/proactive.d.ts.map +1 -1
  61. package/dist/proactive.js +16 -9
  62. package/dist/proactive.js.map +1 -1
  63. package/dist/receipt-send.d.ts +44 -0
  64. package/dist/receipt-send.d.ts.map +1 -0
  65. package/dist/receipt-send.js +71 -0
  66. package/dist/receipt-send.js.map +1 -0
  67. package/dist/serve.d.ts +7 -0
  68. package/dist/serve.d.ts.map +1 -1
  69. package/dist/serve.js +22 -1
  70. package/dist/serve.js.map +1 -1
  71. package/dist/session-guard.d.ts +210 -0
  72. package/dist/session-guard.d.ts.map +1 -0
  73. package/dist/session-guard.js +463 -0
  74. package/dist/session-guard.js.map +1 -0
  75. package/dist/task.d.ts +7 -1
  76. package/dist/task.d.ts.map +1 -1
  77. package/dist/task.js +7 -26
  78. package/dist/task.js.map +1 -1
  79. package/dist/waste.d.ts +25 -0
  80. package/dist/waste.d.ts.map +1 -0
  81. package/dist/waste.js +39 -0
  82. package/dist/waste.js.map +1 -0
  83. package/dist/zone.d.ts +27 -0
  84. package/dist/zone.d.ts.map +1 -0
  85. package/dist/zone.js +96 -0
  86. package/dist/zone.js.map +1 -0
  87. package/package.json +2 -2
  88. package/src/base-cost.ts +384 -0
  89. package/src/bill-range.ts +206 -0
  90. package/src/command-help.ts +65 -0
  91. package/src/filter.ts +11 -18
  92. package/src/gateway-metrics.ts +209 -0
  93. package/src/gateway-server.ts +43 -6
  94. package/src/gateway-spend.ts +45 -33
  95. package/src/git.ts +158 -0
  96. package/src/i18n/en.ts +424 -6
  97. package/src/i18n/es.ts +542 -35
  98. package/src/i18n/types.ts +208 -0
  99. package/src/index.ts +952 -58
  100. package/src/loopback-guard.ts +74 -0
  101. package/src/markdown.ts +117 -0
  102. package/src/plan-edits.ts +120 -0
  103. package/src/proactive.ts +22 -13
  104. package/src/receipt-send.ts +89 -0
  105. package/src/serve.ts +23 -1
  106. package/src/session-guard.ts +541 -0
  107. package/src/task.ts +8 -26
  108. package/src/waste.ts +42 -0
  109. package/src/zone.ts +95 -0
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The two checks that keep a loopback server from answering a web page.
3
+ *
4
+ * Binding to 127.0.0.1 keeps other machines out. It does not keep out a page
5
+ * open in a browser on this machine: a page can point its own hostname at
6
+ * 127.0.0.1 (DNS rebinding) and then talk to the server as its own origin,
7
+ * reading the answers. Two refusals close that, and neither needs a secret:
8
+ *
9
+ * - **The `Host` header must name this server.** A rebinding page sends its
10
+ * own hostname, because that is what the browser believes it is talking to.
11
+ * Only `localhost`, `127.0.0.1` and `[::1]`, on the port the server is
12
+ * bound to, are accepted.
13
+ * - **A POST must say `content-type: application/json`.** A page can send
14
+ * `text/plain` without asking permission; it cannot send `application/json`
15
+ * cross-origin without a CORS preflight, and nothing here answers one.
16
+ *
17
+ * A server bound to a Unix socket has no port and no hostname for a page to
18
+ * rebind, so the Host check does not apply there. The content-type check does.
19
+ */
20
+
21
+ import type { IncomingMessage, Server } from 'node:http';
22
+
23
+ const LOOPBACK_NAMES: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);
24
+
25
+ /** True when `Host` names a loopback address on the port the server is bound to. */
26
+ export function hostIsLoopback(host: string | undefined, port: number): boolean {
27
+ if (host === undefined) return false;
28
+ const match = /^(\[[0-9a-f:]+\]|[a-z0-9.-]+)(?::(\d{1,5}))?$/i.exec(host.trim());
29
+ if (match === null) return false;
30
+ const name = match[1]!.toLowerCase();
31
+ if (!LOOPBACK_NAMES.has(name)) return false;
32
+ // A Host with no port means port 80, which is not this server's.
33
+ return match[2] !== undefined && Number(match[2]) === port;
34
+ }
35
+
36
+ /** True when the header's media type is `application/json`, parameters aside. */
37
+ export function isJsonContentType(value: string | undefined): boolean {
38
+ return value !== undefined && value.split(';')[0]!.trim().toLowerCase() === 'application/json';
39
+ }
40
+
41
+ export interface GuardRefusal {
42
+ status: 403 | 415;
43
+ error: 'forbidden-host' | 'unsupported-media-type';
44
+ detail: string;
45
+ }
46
+
47
+ /** The refusal for a request addressed to a host that is not this server's own, or null. */
48
+ export function refuseHost(server: Server, request: IncomingMessage): GuardRefusal | null {
49
+ const address = server.address();
50
+ // A Unix socket has no port and no hostname to rebind: nothing to check.
51
+ if (typeof address === 'object' && address !== null && !hostIsLoopback(request.headers.host, address.port)) {
52
+ return {
53
+ status: 403,
54
+ error: 'forbidden-host',
55
+ detail: 'This server answers only requests addressed to localhost, 127.0.0.1 or [::1] on its own port.',
56
+ };
57
+ }
58
+ return null;
59
+ }
60
+
61
+ /**
62
+ * The refusal for a POST that does not say it is JSON, or null. Checked after
63
+ * routing, so a path that does not exist still answers 404 whatever it sent.
64
+ */
65
+ export function refuseContentType(request: IncomingMessage): GuardRefusal | null {
66
+ if (request.method === 'POST' && !isJsonContentType(request.headers['content-type'])) {
67
+ return {
68
+ status: 415,
69
+ error: 'unsupported-media-type',
70
+ detail: 'A POST must send content-type: application/json.',
71
+ };
72
+ }
73
+ return null;
74
+ }
package/src/markdown.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { CliMessages } from './i18n/index.js';
2
2
  import type { Revision } from './git.js';
3
+ import type { BaseCostPrice, BaseCostReport, BaseCostRow, PricedSide } from './base-cost.js';
3
4
  import type {
4
5
  BaselineBreach,
5
6
  BaselineComparison,
@@ -181,9 +182,124 @@ export interface CheckMarkdownInput {
181
182
  truncated: boolean;
182
183
  /** Absent when no baseline governed the run. */
183
184
  baseline?: BaselineMarkdown;
185
+ /** Absent unless the run was given `--base`. */
186
+ againstBase?: BaseCostReport;
184
187
  t: CliMessages;
185
188
  }
186
189
 
190
+ /** A price per million tokens as the catalogue holds it, never rounded. */
191
+ export function perMTokText(value: number): string {
192
+ return Number(value.toFixed(2)) === value ? `$${value.toFixed(2)}` : `$${value}`;
193
+ }
194
+
195
+ /**
196
+ * The price a row was computed at, with its source and the day it was read.
197
+ *
198
+ * In every row rather than once under the table, because a row is what gets
199
+ * quoted: a figure lifted out of a comment carries its price and its date
200
+ * with it, or it carries a number nobody can check.
201
+ */
202
+ export function basePriceText(row: BaseCostRow, price: BaseCostPrice, t: CliMessages): string {
203
+ const rates = [row.base?.inputPerMTok, row.head?.inputPerMTok].filter((r): r is number => r !== undefined);
204
+ const shown =
205
+ rates.length === 2 && rates[0] !== rates[1]
206
+ ? `${perMTokText(rates[0]!)} → ${perMTokText(rates[1]!)}`
207
+ : perMTokText(rates[0] ?? 0);
208
+ const text = price.overlaid
209
+ ? t.againstBase.priceOverlay(shown, price.displayName, price.readOn)
210
+ : t.againstBase.price(shown, price.displayName, price.provider ?? price.model, price.readOn);
211
+ return price.promoUntil === null ? text : `${text}; ${t.againstBase.promo(price.promoUntil)}`;
212
+ }
213
+
214
+ /** One side's cost, a month when the volume was stated and a call when it was not. */
215
+ export function baseSideText(side: PricedSide | null, t: CliMessages): string {
216
+ if (side === null) return '–';
217
+ return side.monthlyUsd === null
218
+ ? t.againstBase.perCall(formatUsd(side.perCallUsd))
219
+ : t.againstBase.perMonth(formatUsd(side.monthlyUsd));
220
+ }
221
+
222
+ export function baseChangeText(row: BaseCostRow, t: CliMessages): string {
223
+ return row.monthlyChangeUsd === null
224
+ ? t.againstBase.perCall(formatSignedUsd(row.perCallChangeUsd))
225
+ : t.againstBase.perMonth(formatSignedUsd(row.monthlyChangeUsd));
226
+ }
227
+
228
+ /**
229
+ * The base comparison (#785): what this change does to each prompt's cost
230
+ * against the base branch. It leads the check report, above the budgets,
231
+ * for the reason the baseline block does: it is what the pull request is
232
+ * proposing.
233
+ */
234
+ export function baseCostBlock(report: BaseCostReport, t: CliMessages): string[] {
235
+ const n = (value: number): string => value.toLocaleString(t.numberLocale);
236
+ const ab = t.againstBase;
237
+ const lines: string[] = [];
238
+
239
+ if (report.status === 'unavailable') {
240
+ lines.push('> [!WARNING]');
241
+ lines.push(`> ${ab.unavailable(report.why, mdCell(report.ref))}`);
242
+ lines.push('');
243
+ if (report.gate !== null) {
244
+ lines.push('> [!CAUTION]');
245
+ lines.push(`> **${ab.gateUnavailable(formatUsd(report.gate.maxIncreaseUsd))}**`);
246
+ lines.push('');
247
+ }
248
+ return lines;
249
+ }
250
+
251
+ lines.push(`#### ${ab.heading(mdCell(report.ref), mdCell(report.sha.slice(0, 7)))}`);
252
+ lines.push('');
253
+
254
+ if (report.gate !== null) {
255
+ const change = formatSignedUsd(report.totals?.changeUsd ?? 0);
256
+ const limit = formatUsd(report.gate.maxIncreaseUsd);
257
+ if (report.gate.breached) {
258
+ lines.push('> [!CAUTION]');
259
+ lines.push(`> **${ab.gateBreached(change, limit)}**`);
260
+ } else {
261
+ lines.push(`**${ab.gateWithin(change, limit)}**`);
262
+ }
263
+ lines.push('');
264
+ }
265
+
266
+ if (report.rows.length === 0) {
267
+ lines.push(ab.nothingChanged());
268
+ lines.push('');
269
+ } else {
270
+ lines.push(
271
+ `| | ${t.markdown.columnFile()} | ${ab.columnTokens()} | ${ab.columnCalls()} | ${ab.columnBase()} | ${ab.columnHead()} | ${t.markdown.columnChange()} | ${ab.columnPrice()} |`,
272
+ );
273
+ lines.push('|:--:|---|--:|--:|--:|--:|--:|---|');
274
+ for (const row of report.rows) {
275
+ const mark =
276
+ row.base === null ? '🆕' : row.head === null ? '🗑️' : row.perCallChangeUsd > 0 ? '📈' : row.perCallChangeUsd < 0 ? '📉' : '·';
277
+ const tokens = `${row.base === null ? '–' : n(row.base.tokens)} → ${row.head === null ? '–' : n(row.head.tokens)}`;
278
+ const calls = row.callsPerMonth === null ? ab.notStated() : n(row.callsPerMonth);
279
+ lines.push(
280
+ `| ${mark} | ${mdCell(row.id)} | ${tokens} | ${calls} | ${baseSideText(row.base, t)} | ${baseSideText(row.head, t)} | ${baseChangeText(row, t)} | ${mdTextCell(basePriceText(row, report.price, t))} |`,
281
+ );
282
+ }
283
+ lines.push('');
284
+ }
285
+
286
+ if (report.totals !== null) {
287
+ lines.push(
288
+ `**${ab.totals(formatUsd(report.totals.baseUsd), formatUsd(report.totals.headUsd), formatSignedUsd(report.totals.changeUsd))}**`,
289
+ );
290
+ lines.push('');
291
+ }
292
+ const notes: string[] = [];
293
+ if (report.gate !== null && report.perCallOnly > 0) notes.push(ab.gateNotJudged(report.perCallOnly));
294
+ if (report.perCallOnly > 0) notes.push(ab.perCallNote(report.perCallOnly));
295
+ if (report.unchanged > 0) notes.push(ab.unchanged(report.unchanged));
296
+ if (report.modelFrom === 'default') notes.push(ab.modelDefault(mdText(report.price.displayName)));
297
+ notes.push(ab.inputOnly());
298
+ for (const note of notes) lines.push(`- ${note}`);
299
+ lines.push('');
300
+ return lines;
301
+ }
302
+
187
303
  const overBudget = (v: MarkdownFileVerdict): boolean =>
188
304
  v.maxTokens !== null && v.tokens > v.maxTokens;
189
305
 
@@ -302,6 +418,7 @@ export function renderCheckMarkdown(input: CheckMarkdownInput): string {
302
418
  * "did this branch make the repository more expensive" is what the pull request
303
419
  * is actually proposing, so it goes above the table rather than under it.
304
420
  */
421
+ if (input.againstBase) lines.push(...baseCostBlock(input.againstBase, t));
305
422
  if (input.baseline) lines.push(...baselineBlock(input.baseline, t));
306
423
 
307
424
  lines.push(
@@ -0,0 +1,120 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
4
+
5
+ import { isEditableFile, planEdits, planFileEdit } from '@trazum/core';
6
+ import type { PlanAction, PlanDocument, PlanEditStep, PricingCatalogue, UsageProfileReport } from '@trazum/core';
7
+
8
+ import { isTracked, pathInRepository, repositoryRoot } from './git.js';
9
+
10
+ /**
11
+ * The file side of `trazum plan --edits` and of `trazum verify` (#796).
12
+ *
13
+ * `plan --edits` reads each prompt file `trazum.config.json` maps a label to
14
+ * (`labels`), and asks the core for the edit the deterministic steps would
15
+ * make to it. This module owns the reading and the hashing; the core owns
16
+ * what an edit is. It writes nothing: the plan names the edit, and the
17
+ * Action's pull-request step is the only thing that ever makes it.
18
+ */
19
+
20
+ /** SHA-256 of a text as UTF-8, lowercase hex: the digest every edit is held to. */
21
+ export const sha256 = (text: string): string => createHash('sha256').update(text, 'utf8').digest('hex');
22
+
23
+ /** Why a mapped label produced no edit. */
24
+ export type EditSkip =
25
+ | { why: 'no-traffic'; label: string; path: string }
26
+ | { why: 'unreadable'; label: string; path: string }
27
+ | { why: 'not-tracked'; label: string; path: string }
28
+ | { why: 'source-file'; label: string; path: string }
29
+ | { why: 'unchanged'; label: string; path: string };
30
+
31
+ export interface PlannedEdits {
32
+ actions: PlanAction[];
33
+ skipped: EditSkip[];
34
+ }
35
+
36
+ /**
37
+ * The `edit-file` actions for every label the configuration maps to a file.
38
+ *
39
+ * A path is read as the configuration gives it, from the working directory,
40
+ * the way `profile` reads it, and recorded relative to the repository root,
41
+ * which is where a pull request names it. A file git does not track is
42
+ * skipped and said: an edit to a file the repository does not hold could
43
+ * never be proposed to it.
44
+ */
45
+ export async function planEditsFor(options: {
46
+ report: UsageProfileReport;
47
+ labels: Record<string, string>;
48
+ steps: PlanEditStep[];
49
+ disabledRules: string[];
50
+ pricing: PricingCatalogue;
51
+ cwd?: string;
52
+ }): Promise<PlannedEdits> {
53
+ const cwd = options.cwd ?? process.cwd();
54
+ const actions: PlanAction[] = [];
55
+ const skipped: EditSkip[] = [];
56
+ const traffic = new Set(options.report.byLabelAndModel.filter((s) => s.breakdown.calls > 0).map((s) => s.label));
57
+
58
+ for (const [label, given] of Object.entries(options.labels).sort((a, b) => a[0].localeCompare(b[0]))) {
59
+ if (!traffic.has(label)) {
60
+ skipped.push({ why: 'no-traffic', label, path: given });
61
+ continue;
62
+ }
63
+ const absolute = resolve(cwd, given);
64
+ let text: string;
65
+ try {
66
+ text = await readFile(absolute, 'utf8');
67
+ } catch {
68
+ skipped.push({ why: 'unreadable', label, path: given });
69
+ continue;
70
+ }
71
+ const root = repositoryRoot(dirname(absolute));
72
+ const repoPath = root === null ? null : pathInRepository(root, absolute);
73
+ if (root === null || repoPath === null || !isTracked(root, repoPath)) {
74
+ skipped.push({ why: 'not-tracked', label, path: given });
75
+ continue;
76
+ }
77
+ if (!isEditableFile(repoPath)) {
78
+ skipped.push({ why: 'source-file', label, path: repoPath });
79
+ continue;
80
+ }
81
+ const action = planFileEdit({
82
+ report: options.report,
83
+ label,
84
+ path: repoPath,
85
+ text,
86
+ steps: options.steps,
87
+ disabledRules: options.disabledRules,
88
+ pricing: options.pricing,
89
+ digest: sha256,
90
+ });
91
+ if (action === null) skipped.push({ why: 'unchanged', label, path: repoPath });
92
+ else actions.push(action);
93
+ }
94
+ return { actions, skipped };
95
+ }
96
+
97
+ /**
98
+ * The SHA-256 of each file a plan's edits name, as it is now in the
99
+ * repository holding the working directory, or null for one that is not
100
+ * there. Outside a repository the map is empty and every edit reads as
101
+ * `file-not-read`, which is what it is.
102
+ */
103
+ export async function currentFileDigests(
104
+ plan: Pick<PlanDocument, 'actions'>,
105
+ cwd: string = process.cwd(),
106
+ ): Promise<Map<string, string | null>> {
107
+ const digests = new Map<string, string | null>();
108
+ const edits = planEdits(plan);
109
+ if (edits.length === 0) return digests;
110
+ const root = repositoryRoot(cwd);
111
+ if (root === null) return digests;
112
+ for (const edit of edits) {
113
+ try {
114
+ digests.set(edit.path, sha256(await readFile(join(root, ...edit.path.split('/')), 'utf8')));
115
+ } catch {
116
+ digests.set(edit.path, null);
117
+ }
118
+ }
119
+ return digests;
120
+ }
package/src/proactive.ts CHANGED
@@ -204,7 +204,7 @@ export function shown(ctx: Ctx, path: string): string {
204
204
  // --------------------------------------------------------------------------
205
205
 
206
206
  export interface Change {
207
- item: Item | 'manifest';
207
+ item: Item | 'manifest' | 'session-guard';
208
208
  /** An absolute path, or `CRONTAB`. */
209
209
  target: string;
210
210
  /** What the caller read: `null` when the file was not there. */
@@ -356,7 +356,7 @@ async function writeBackup(ctx: Ctx, path: string, text: string, mode: number):
356
356
  }
357
357
 
358
358
  /** A directory this command made, removed once it is empty. Never anything else. */
359
- async function removeEmptyDir(ctx: Ctx, dir: string): Promise<void> {
359
+ export async function removeEmptyDir(ctx: Ctx, dir: string): Promise<void> {
360
360
  const p = pathsFor(ctx);
361
361
  if (dir !== p.scriptDir && dir !== p.stateDir) return;
362
362
  await rmdir(dir).catch(() => undefined);
@@ -382,8 +382,8 @@ export function serialise(value: unknown, format: Format): string {
382
382
  return (format.eol === '\r\n' ? text.replace(/\n/g, '\r\n') : text) + (format.final ? format.eol : '');
383
383
  }
384
384
 
385
- type Obj = Record<string, unknown>;
386
- const isObject = (value: unknown): value is Obj =>
385
+ export type Obj = Record<string, unknown>;
386
+ export const isObject = (value: unknown): value is Obj =>
387
387
  typeof value === 'object' && value !== null && !Array.isArray(value);
388
388
 
389
389
  export type JsonRead =
@@ -522,11 +522,13 @@ export interface Manifest {
522
522
  */
523
523
  statusline?: { createdFile: boolean; created: string[]; script?: string };
524
524
  mcp?: Record<string, { createdFile: boolean; createdKey: boolean }>;
525
+ /** What `session-guard install` created in the settings file, so `uninstall` leaves what was the person's. */
526
+ guard?: { createdFile: boolean; created: string[] };
525
527
  }
526
528
 
527
- const emptyManifest = (): Manifest => ({ v: 1 });
529
+ export const emptyManifest = (): Manifest => ({ v: 1 });
528
530
 
529
- function manifestFrom(value: Obj): Manifest {
531
+ export function manifestFrom(value: Obj): Manifest {
530
532
  const out = emptyManifest();
531
533
  const s = value.statusline;
532
534
  if (isObject(s)) {
@@ -536,6 +538,13 @@ function manifestFrom(value: Obj): Manifest {
536
538
  ...(typeof s.script === 'string' ? { script: s.script } : {}),
537
539
  };
538
540
  }
541
+ const g = value.guard;
542
+ if (isObject(g)) {
543
+ out.guard = {
544
+ createdFile: g.createdFile === true,
545
+ created: Array.isArray(g.created) ? g.created.filter((x): x is string => typeof x === 'string') : [],
546
+ };
547
+ }
539
548
  if (isObject(value.mcp)) {
540
549
  out.mcp = {};
541
550
  for (const [path, record] of Object.entries(value.mcp)) {
@@ -547,14 +556,14 @@ function manifestFrom(value: Obj): Manifest {
547
556
 
548
557
  const digest = (text: string): string => createHash('sha256').update(text).digest('hex');
549
558
 
550
- const manifestEmpty = (m: Manifest): boolean =>
551
- m.statusline === undefined && (m.mcp === undefined || Object.keys(m.mcp).length === 0);
559
+ export const manifestEmpty = (m: Manifest): boolean =>
560
+ m.statusline === undefined && m.guard === undefined && (m.mcp === undefined || Object.keys(m.mcp).length === 0);
552
561
 
553
562
  // --------------------------------------------------------------------------
554
563
  // The CLI this will keep running
555
564
  // --------------------------------------------------------------------------
556
565
 
557
- const q = (text: string): string => `'${text}'`;
566
+ export const q = (text: string): string => `'${text}'`;
558
567
 
559
568
  /** A path that can sit inside single quotes, in a shell string and in a crontab. */
560
569
  export function quotable(path: string): boolean {
@@ -861,10 +870,10 @@ const inspected = (s: ItemStatus, install: Plan | null = null, uninstall: Plan |
861
870
  uninstall,
862
871
  });
863
872
 
864
- const NEW_FORMAT: Format = { indent: ' ', eol: '\n', final: true };
873
+ export const NEW_FORMAT: Format = { indent: ' ', eol: '\n', final: true };
865
874
 
866
- function jsonChange(
867
- item: Item,
875
+ export function jsonChange(
876
+ item: Item | 'session-guard',
868
877
  target: string,
869
878
  read: JsonRead,
870
879
  next: Obj | null,
@@ -1242,7 +1251,7 @@ export interface RunOptions {
1242
1251
  decide: (item: Item, changes: Change[]) => boolean | Promise<boolean>;
1243
1252
  }
1244
1253
 
1245
- function failure(ctx: Ctx, error: unknown): Finding {
1254
+ export function failure(ctx: Ctx, error: unknown): Finding {
1246
1255
  if (error instanceof RefusedWrite) {
1247
1256
  return {
1248
1257
  code: `write.${error.reason}` as ProactiveCode,
@@ -0,0 +1,89 @@
1
+ /**
2
+ * `trazum bill --receipt --send <url>`: the receipt, posted to the endpoint
3
+ * an organisation named, and nothing else.
4
+ *
5
+ * Three properties, each held by `packages/cli/test/bill-send.test.js`:
6
+ *
7
+ * - **Only the receipt leaves.** `sendReceipt` takes the bytes the same run
8
+ * wrote and posts them as they are. It is handed no log line, no path and no
9
+ * prompt, so there is nothing else for it to send.
10
+ * - **The key is read here and goes nowhere but the header.** It comes from
11
+ * `TRAZUM_RECEIPT_KEY`, never from a flag, and this module has no `console`:
12
+ * what it returns is already scrubbed of the key, and the caller prints that.
13
+ * - **The URL is `watch --webhook`'s.** `checkWebhook` is imported, not copied:
14
+ * https except on loopback, no credentials in the URL. Redirects are refused
15
+ * by `SAFE_FETCH_INIT`, so a response from somewhere else never arrives.
16
+ *
17
+ * One request, one attempt, awaited: no retry and nothing in the background.
18
+ */
19
+
20
+ import { SAFE_FETCH_INIT } from '@trazum/core/node';
21
+ import { redact } from './connect.js';
22
+ import { checkWebhook, type WebhookRejection } from './watch-run.js';
23
+
24
+ /** The environment variable the key is read from. A flag would end up in shell history. */
25
+ export const RECEIPT_KEY_ENV = 'TRAZUM_RECEIPT_KEY';
26
+
27
+ /** How much of a response body is shown. An endpoint's error page is not ours to print whole. */
28
+ const BODY_LIMIT = 2000;
29
+
30
+ export type ReceiptTarget =
31
+ | { ok: true; url: URL; key: string | undefined }
32
+ | { ok: false; reason: WebhookRejection | 'bad-key' };
33
+
34
+ /**
35
+ * Whether this URL and this key are ones a receipt may be sent with.
36
+ * Checked before any log is read, so a refusal costs nothing.
37
+ */
38
+ export function checkReceiptTarget(raw: string, env: NodeJS.ProcessEnv = process.env): ReceiptTarget {
39
+ const checked = checkWebhook(raw);
40
+ if (!checked.ok) return checked;
41
+ const key = env[RECEIPT_KEY_ENV];
42
+ if (key === undefined || key === '') return { ok: true, url: checked.url, key: undefined };
43
+ // A header value with a space, a control character or a non-ASCII byte is
44
+ // one the HTTP client refuses by quoting it back in its error.
45
+ if (!/^[\x21-\x7e]+$/.test(key)) return { ok: false, reason: 'bad-key' };
46
+ return { ok: true, url: checked.url, key };
47
+ }
48
+
49
+ export interface SendResult {
50
+ /** The endpoint answered 2xx. */
51
+ ok: boolean;
52
+ /** The status, or null when no answer arrived. */
53
+ status: number | null;
54
+ /** What the endpoint said, or why no answer arrived. Never carries the key. */
55
+ detail: string;
56
+ }
57
+
58
+ const scrub = (text: string, key: string | undefined): string => {
59
+ let out = text;
60
+ if (key !== undefined && key !== '') out = out.split(key).join('[redacted]');
61
+ return redact(out);
62
+ };
63
+
64
+ export async function sendReceipt(
65
+ url: URL,
66
+ key: string | undefined,
67
+ body: string,
68
+ fetchImpl: typeof fetch = fetch,
69
+ ): Promise<SendResult> {
70
+ try {
71
+ const response = await fetchImpl(url.toString(), {
72
+ ...SAFE_FETCH_INIT,
73
+ method: 'POST',
74
+ headers: {
75
+ 'content-type': 'application/json',
76
+ ...(key !== undefined ? { authorization: `Bearer ${key}` } : {}),
77
+ },
78
+ body,
79
+ signal: AbortSignal.timeout(10_000),
80
+ });
81
+ // Scrubbed before it is cut, so a key that straddles the limit is not left half shown.
82
+ const text = scrub(await response.text(), key).slice(0, BODY_LIMIT).trim();
83
+ return { ok: response.ok, status: response.status, detail: text };
84
+ } catch (error) {
85
+ const cause = error instanceof Error && error.cause instanceof Error ? ` (${error.cause.message})` : '';
86
+ const message = error instanceof Error ? error.message : String(error);
87
+ return { ok: false, status: null, detail: scrub(`${message}${cause}`, key) };
88
+ }
89
+ }
package/src/serve.ts CHANGED
@@ -10,6 +10,13 @@
10
10
  * being no way to say otherwise. `127.0.0.1` is compiled in. A Unix socket is
11
11
  * offered for callers that would rather not use a port at all.
12
12
  *
13
+ * **A web page on this machine is not "only the local machine".** A page can
14
+ * rebind its own hostname to 127.0.0.1 and read what this answers. So a
15
+ * request whose `Host` is not a loopback name on the bound port is refused
16
+ * with 403, and a POST without `content-type: application/json` with 415,
17
+ * which a page cannot send cross-origin without a preflight nothing answers.
18
+ * See `loopback-guard.ts`.
19
+ *
13
20
  * **No auth, on purpose.** Anything reachable only from the machine it runs on
14
21
  * is already behind the operating system's own boundary, and a token checked
15
22
  * over loopback is theatre: whoever can reach the socket can read the token
@@ -24,6 +31,7 @@
24
31
  */
25
32
 
26
33
  import { createServer } from 'node:http';
34
+ import { refuseContentType, refuseHost } from './loopback-guard.js';
27
35
  import { importUsage, validateImportPayload } from './serve-import.js';
28
36
  import { planSavings, verifySavings, validateSavingsPayload } from './serve-savings.js';
29
37
  import { SERVE_OPENAPI, validateCostPayload } from './serve-schema.js';
@@ -92,8 +100,15 @@ const send = (response: ServerResponse, status: number, body: unknown): void =>
92
100
  };
93
101
 
94
102
  export function buildServer(context: ServeContext): Server {
95
- return createServer((request, response) => {
103
+ const server: Server = createServer((request, response) => {
96
104
  void (async () => {
105
+ // Before anything is routed: a page that rebound its own hostname to
106
+ // this address must not read an answer, not even a 404.
107
+ const refused = refuseHost(server, request);
108
+ if (refused !== null) {
109
+ send(response, refused.status, { error: refused.error, detail: refused.detail });
110
+ return;
111
+ }
97
112
  const url = new URL(request.url ?? '/', `http://${BIND_HOST}`);
98
113
 
99
114
  if (request.method === 'GET' && url.pathname === '/capabilities') {
@@ -121,6 +136,12 @@ export function buildServer(context: ServeContext): Server {
121
136
  return;
122
137
  }
123
138
 
139
+ const untyped = refuseContentType(request);
140
+ if (untyped !== null) {
141
+ send(response, untyped.status, { error: untyped.error, detail: untyped.detail });
142
+ return;
143
+ }
144
+
124
145
  let payload: Record<string, unknown>;
125
146
  try {
126
147
  const raw = await readBody(request);
@@ -216,6 +237,7 @@ export function buildServer(context: ServeContext): Server {
216
237
  send(response, 200, { ...answer, policy });
217
238
  })();
218
239
  });
240
+ return server;
219
241
  }
220
242
 
221
243
  export interface ListenTarget {