@flyingrobots/parley-emit 0.1.0 → 0.2.4
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/CHANGELOG.md +295 -0
- package/README.md +517 -15
- package/package.json +1 -1
- package/src/check.ts +198 -0
- package/src/history.ts +229 -0
- package/src/index.ts +7 -1
- package/src/location.ts +47 -4
- package/src/refusal.ts +54 -0
- package/src/run.ts +279 -15
- package/src/schemas.ts +635 -1
- package/src/tool.ts +160 -25
- package/src/transforms/declared.ts +49 -0
- package/src/transforms/secret-patterns.ts +84 -0
- package/src/transforms/secrets.ts +153 -0
package/src/tool.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { closeSync, openSync, readSync, readdirSync, rmSync, statSync, unlinkSync, writeSync } from "node:fs";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { join, resolve } from "node:path";
|
|
6
|
+
import { historyBookkeeping, historyDays, historyProjection, isHistoryFailure, isHistorySink, openHistory, resolveHistory, retainHistory, type HistoryConfig, type HistoryPlan, type HistoryProjection, type HistorySink } from "./history.ts";
|
|
6
7
|
import { computeInv, type InputDecl } from "./inv.ts";
|
|
7
8
|
import { bookkeepingFor, chooseLocation, isLocationFailure, type Bookkeeping } from "./location.ts";
|
|
8
9
|
import { carriesSecret, classifySecrets, collectSecretValues, redactArgv, scrub } from "./redact.ts";
|
|
@@ -19,7 +20,11 @@ export interface CommandSpec {
|
|
|
19
20
|
readonly secrets?: readonly string[];
|
|
20
21
|
/** The result types the command can emit; a tool-owned type carries its JSON Schema for discovery. */
|
|
21
22
|
readonly emits: readonly EmittedType[];
|
|
22
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* The error types the command can produce. Defaults to `parley.error` and
|
|
25
|
+
* `parley.startup.failed`, since every command can produce a startup failure (§3.2, §4.2,
|
|
26
|
+
* flyingrobots/parley#92); a list given here replaces the default, so name both in it.
|
|
27
|
+
*/
|
|
23
28
|
readonly errors?: readonly EmittedType[];
|
|
24
29
|
}
|
|
25
30
|
export interface ToolSpec {
|
|
@@ -59,6 +64,14 @@ export interface MainOptions {
|
|
|
59
64
|
inputs?: (args: string[], command: string) => InputDecl[] | Promise<InputDecl[]>;
|
|
60
65
|
/** The resolved interpretation after defaults (§5): order-normalised and free of volatile values, since it enters inv. The default records the command and its arguments. */
|
|
61
66
|
resolved?: (args: string[], command: string) => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
67
|
+
/**
|
|
68
|
+
* The shared history stream (§8). The default resolves it from the environment; `null` is no
|
|
69
|
+
* stream. The long form, `{ sink?, transform?, name? }`, also configures the projection applied
|
|
70
|
+
* to the stream copy: `{ history: { transform } }` keeps the sink the environment chose and
|
|
71
|
+
* narrows what reaches it. A transform is configured in code and never by an environment
|
|
72
|
+
* variable naming a module to execute.
|
|
73
|
+
*/
|
|
74
|
+
history?: HistorySink | null | HistoryConfig;
|
|
62
75
|
}
|
|
63
76
|
|
|
64
77
|
/**
|
|
@@ -81,6 +94,8 @@ export function fdSink(fd: number): Sink {
|
|
|
81
94
|
}
|
|
82
95
|
const OWN_FLAGS = new Set(["--human", "--humanize", "--dry-run", "--schema", "--help", "-h"]);
|
|
83
96
|
const WRITER_SCHEMAS: SchemaRef[] = Object.values(SCHEMA_IDS);
|
|
97
|
+
/** A command's error types when it declares none: what the writer itself can put on stderr for it (§4.2). */
|
|
98
|
+
const DEFAULT_ERRORS: readonly EmittedType[] = [SCHEMA_IDS.error, SCHEMA_IDS.startupFailed];
|
|
84
99
|
/** Incomplete receipts (no end line) older than this are deletable by retention; younger ones may still be in flight. */
|
|
85
100
|
const INCOMPLETE_GRACE_MS = 24 * 60 * 60 * 1000;
|
|
86
101
|
|
|
@@ -96,12 +111,24 @@ export async function main(spec: ToolSpec, argv: readonly string[], handler: Han
|
|
|
96
111
|
const stdout = opts.stdout ?? fdSink(1), stderr = opts.stderr ?? fdSink(2);
|
|
97
112
|
const now = opts.now ?? Date.now;
|
|
98
113
|
const rawArgs = argv.slice(1);
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
const
|
|
114
|
+
// `--` ends the writer's flags (flyingrobots/parley#103): the writer's own flags are recognised
|
|
115
|
+
// anywhere before the first `--`, that `--` is removed, and every argument after it is the
|
|
116
|
+
// tool's, untouched, a writer flag's text or a second `--` included.
|
|
117
|
+
const dash = rawArgs.indexOf("--");
|
|
118
|
+
const own = dash === -1 ? rawArgs : rawArgs.slice(0, dash);
|
|
119
|
+
const after = dash === -1 ? [] : rawArgs.slice(dash + 1);
|
|
120
|
+
const human = own.some((a) => a === "--human" || a === "--humanize");
|
|
121
|
+
const dryRun = own.includes("--dry-run");
|
|
122
|
+
const discovery = own.includes("--schema") ? "schema" : own.includes("--help") || own.includes("-h") ? "help" : null;
|
|
123
|
+
const args = own.filter((a) => !OWN_FLAGS.has(a));
|
|
103
124
|
const names = Object.keys(spec.commands);
|
|
104
|
-
|
|
125
|
+
// The command is chosen by position (flyingrobots/parley#101): once the writer's flags are set
|
|
126
|
+
// aside, the first remaining argument before any `--` is the command, and only that one argument
|
|
127
|
+
// is removed. A tool with one command may omit it. A later argument with a command's text is the
|
|
128
|
+
// tool's, and nothing after `--` is ever the command.
|
|
129
|
+
const named = args.length > 0 && Object.hasOwn(spec.commands, args[0]!);
|
|
130
|
+
const commandName = named ? args[0]! : names.length === 1 ? names[0]! : undefined;
|
|
131
|
+
const rest = [...(named ? args.slice(1) : args), ...after];
|
|
105
132
|
const command = commandName ? spec.commands[commandName]! : undefined;
|
|
106
133
|
|
|
107
134
|
// Declared secrets of every command: a value passed to the wrong command is still a secret (§5.3).
|
|
@@ -140,10 +167,25 @@ export async function main(spec: ToolSpec, argv: readonly string[], handler: Han
|
|
|
140
167
|
const location = chooseLocation({ cwd, run: id, env, home: opts.home ?? homedir(), secrets: secretValues });
|
|
141
168
|
if (isLocationFailure(location)) return fail(location.code, location.problem, location.remedy);
|
|
142
169
|
|
|
170
|
+
// The shared history stream (§8): opt-in, and unable to fail the run. With none configured
|
|
171
|
+
// nothing below it happens, so the run is the run that existed before the stream did.
|
|
172
|
+
let history: HistorySink | undefined;
|
|
173
|
+
let historyPlan: HistoryPlan | null = null;
|
|
174
|
+
let historyWarning: { code: string; problem: string; remedy: string } | undefined;
|
|
175
|
+
const historyConfig: HistoryConfig = opts.history === undefined ? {} : opts.history === null ? { sink: null } : isHistorySink(opts.history) ? { sink: opts.history } : opts.history;
|
|
176
|
+
if (historyConfig.sink !== undefined) history = historyConfig.sink ?? undefined;
|
|
177
|
+
else {
|
|
178
|
+
historyPlan = resolveHistory(env, opts.home ?? homedir(), now());
|
|
179
|
+
if (historyPlan) {
|
|
180
|
+
const opened = openHistory(historyPlan, secretValues);
|
|
181
|
+
if (isHistoryFailure(opened)) { historyWarning = opened; historyPlan = null; }
|
|
182
|
+
else history = opened;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
143
186
|
// Everything the tool supplies before the bootstrap line can throw; a throw here is a startup failure (§3.2), not a stack trace.
|
|
144
187
|
let resolvedRaw: Record<string, unknown>, inputs: InputDecl[];
|
|
145
188
|
try {
|
|
146
|
-
const rest = args.filter((a) => a !== commandName);
|
|
147
189
|
resolvedRaw = discovery ? { discovery, command: commandName } : await (opts.resolved ?? ((a, c) => ({ command: c, args: a })))(rest, commandName!);
|
|
148
190
|
inputs = discovery || !command ? [] : await (opts.inputs ?? (() => []))(rest, commandName!);
|
|
149
191
|
} catch (e) {
|
|
@@ -169,13 +211,21 @@ export async function main(spec: ToolSpec, argv: readonly string[], handler: Han
|
|
|
169
211
|
const headRedacted = Object.keys(redacted).length > 0;
|
|
170
212
|
const inv = inputs.length === 0 && command ? computeInv({ tool: spec.name, v: spec.version, command: commandName!, resolved, inputs: [] }) : undefined;
|
|
171
213
|
|
|
214
|
+
// The projection of §8 exists only when there is both a stream to narrow and a transform to
|
|
215
|
+
// narrow it with: a transform with no stream configured changes nothing, as the stream itself
|
|
216
|
+
// changes nothing when it is not configured.
|
|
217
|
+
const projection: HistoryProjection | undefined = history !== undefined && historyConfig.transform !== undefined
|
|
218
|
+
? historyProjection({ transform: historyConfig.transform, name: historyConfig.name }, declaredSchemas(spec))
|
|
219
|
+
: undefined;
|
|
220
|
+
|
|
172
221
|
const run = new Run({
|
|
173
222
|
tool: spec.name, v: spec.version, id, session, dryRun, stdout, stderr, receiptFd: location.fd, receiptPath: location.receiptPath, receiptDir: location.receiptDir,
|
|
174
|
-
secretValues, now, cwd, command: commandName ?? discovery!, resolved, inputs, headRedacted, human: human ? spec.human ?? (() => null) : undefined,
|
|
223
|
+
secretValues, now, cwd, command: commandName ?? discovery!, resolved, inputs, headRedacted, human: human ? spec.human ?? (() => null) : undefined, history, projection,
|
|
175
224
|
});
|
|
176
225
|
|
|
177
226
|
run.bootstrap(inv);
|
|
178
|
-
|
|
227
|
+
run.declareProjection();
|
|
228
|
+
const bookkeeping = [...bookkeepingFor(cwd, env, opts.home), ...(history ? historyBookkeeping(history) : [])];
|
|
179
229
|
run.head({
|
|
180
230
|
tool: spec.name, v: spec.version, ...(inv ? { inv } : {}), ...(session ? { session } : {}),
|
|
181
231
|
argv: argvRedacted, resolved, ...(headRedacted ? { redacted } : {}), inputs: inputDescriptors,
|
|
@@ -185,9 +235,12 @@ export async function main(spec: ToolSpec, argv: readonly string[], handler: Han
|
|
|
185
235
|
run.flushDeferredFailures();
|
|
186
236
|
capture.attach(run);
|
|
187
237
|
if (run.sinkFailed) { release(); return run.end(); }
|
|
188
|
-
if (location.warning) run.
|
|
238
|
+
if (location.warning) run.writerWarning(location.warning);
|
|
239
|
+
if (historyWarning) run.writerWarning(historyWarning);
|
|
240
|
+
run.noteProjection();
|
|
189
241
|
|
|
190
242
|
retain(run, location.receiptDir, spec.retention.count, dryRun, now());
|
|
243
|
+
if (history) retainStream(run, history.dir, historyPlan?.days ?? historyDays(env), dryRun, now());
|
|
191
244
|
|
|
192
245
|
if (discovery) {
|
|
193
246
|
try { discover(run, spec, discovery, commandName, bookkeeping); } catch (e) {
|
|
@@ -199,7 +252,7 @@ export async function main(spec: ToolSpec, argv: readonly string[], handler: Han
|
|
|
199
252
|
}
|
|
200
253
|
|
|
201
254
|
try {
|
|
202
|
-
await handler(run,
|
|
255
|
+
await handler(run, [...rest]);
|
|
203
256
|
} catch (e) {
|
|
204
257
|
if (run.ended) { release(); return 4; }
|
|
205
258
|
const err = e instanceof Error ? e : new Error(String(e));
|
|
@@ -210,22 +263,37 @@ export async function main(spec: ToolSpec, argv: readonly string[], handler: Han
|
|
|
210
263
|
return run.ended ? run.status ?? 4 : run.end();
|
|
211
264
|
}
|
|
212
265
|
|
|
266
|
+
/**
|
|
267
|
+
* Every schema document this writer can re-validate a projected line against, by `id@version`:
|
|
268
|
+
* the drafts the package ships (spec §4.5) and the schemas the tool declared on its own emitted
|
|
269
|
+
* and error types (§4.2). A pair outside this map cannot be re-validated, and the stream is not
|
|
270
|
+
* where an unchecked projection goes.
|
|
271
|
+
*/
|
|
272
|
+
function declaredSchemas(spec: ToolSpec): Map<string, Record<string, unknown>> {
|
|
273
|
+
const out = new Map<string, Record<string, unknown>>();
|
|
274
|
+
for (const s of SCHEMAS) out.set(`${s.id}@${s.version}`, s.schema);
|
|
275
|
+
for (const c of Object.values(spec.commands)) {
|
|
276
|
+
for (const t of [...c.emits, ...(c.errors ?? [])]) if (t.schema) out.set(`${t.id}@${t.version}`, t.schema);
|
|
277
|
+
}
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
|
|
213
281
|
function discover(run: Run, spec: ToolSpec, discovery: "schema" | "help", commandName: string | undefined, bookkeeping: Bookkeeping[]): void {
|
|
214
282
|
const names = Object.keys(spec.commands);
|
|
215
283
|
{
|
|
216
284
|
const which = discovery === "help" && commandName ? [commandName] : names;
|
|
217
285
|
for (const name of which) {
|
|
218
286
|
const c = spec.commands[name]!;
|
|
219
|
-
run.describe({ event: "command", name, intent: c.intent, effects: { ...c.effects, bookkeeping }, secrets: [...(c.secrets ?? [])], emits: [...c.emits, ...(c.errors ??
|
|
287
|
+
run.describe({ event: "command", name, intent: c.intent, effects: { ...c.effects, bookkeeping }, secrets: [...(c.secrets ?? [])], emits: [...c.emits, ...(c.errors ?? DEFAULT_ERRORS)].map(({ id, version }) => ({ id, version })) }, SCHEMA_IDS.command);
|
|
220
288
|
}
|
|
221
289
|
const types = new Map<string, EmittedType>();
|
|
222
290
|
const add = (t: EmittedType) => { const k = `${t.id}@${t.version}`; if (!types.has(k)) types.set(k, t); };
|
|
223
|
-
for (const name of which) { const c = spec.commands[name]!; c.emits.forEach(add); (c.errors ??
|
|
291
|
+
for (const name of which) { const c = spec.commands[name]!; c.emits.forEach(add); (c.errors ?? DEFAULT_ERRORS).forEach(add); }
|
|
224
292
|
if (discovery === "schema") WRITER_SCHEMAS.forEach(add);
|
|
225
293
|
for (const t of types.values()) {
|
|
226
294
|
const doc = t.schema ?? SCHEMAS.find((s) => s.id === t.id && s.version === t.version)?.schema;
|
|
227
295
|
if (!doc) { run.warning({ code: "schema.unavailable", problem: `no schema document for ${t.id}@${t.version}`, remedy: "declare the schema on the emitted type" }); continue; }
|
|
228
|
-
run.describe({ event: "schema", id: t.id, version: t.version, schema: doc }, SCHEMA_IDS.schema);
|
|
296
|
+
run.describe({ event: "schema", id: t.id, version: t.version, schema: doc }, SCHEMA_IDS.schema, "schema");
|
|
229
297
|
}
|
|
230
298
|
run.end(0);
|
|
231
299
|
}
|
|
@@ -233,6 +301,11 @@ function discover(run: Run, spec: ToolSpec, discovery: "schema" | "help", comman
|
|
|
233
301
|
|
|
234
302
|
function scrubText(s: string, values: ReadonlySet<string>): string { return scrub(s, values) as string; }
|
|
235
303
|
|
|
304
|
+
/** A receipt's size and mtime, as a comparable key and the mtime in milliseconds, or null when it is gone. */
|
|
305
|
+
function observe(path: string): { key: string; mtime: number } | null {
|
|
306
|
+
try { const st = statSync(path, { bigint: true }); return { key: `${st.size}:${st.mtimeNs}`, mtime: Number(st.mtimeNs / 1_000_000n) }; } catch { return null; }
|
|
307
|
+
}
|
|
308
|
+
|
|
236
309
|
/** True when the receipt's final line is a newline-terminated `end` (§5.4), read from its tail. */
|
|
237
310
|
function hasEnded(path: string): boolean {
|
|
238
311
|
let fd: number | null = null;
|
|
@@ -251,27 +324,89 @@ function hasEnded(path: string): boolean {
|
|
|
251
324
|
} catch { return false; } finally { if (fd !== null) closeSync(fd); }
|
|
252
325
|
}
|
|
253
326
|
|
|
254
|
-
/**
|
|
255
|
-
|
|
327
|
+
/** The head's size past which a receipt's owner is not looked for: a head that large is read as "not readable", and the file is left alone. */
|
|
328
|
+
const HEAD_READ_LIMIT = 1024 * 1024;
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* The `tool` a receipt's head names, from the first line alone, or null when there is no such
|
|
332
|
+
* line: an empty file, a first line that is not JSON or not a `receipt.head`, a head with no
|
|
333
|
+
* string `tool`, or a first line longer than the limit. Null means "not ours" to a caller that
|
|
334
|
+
* deletes, so an unreadable file is never expired.
|
|
335
|
+
*/
|
|
336
|
+
function headTool(path: string): string | null {
|
|
337
|
+
let fd: number | null = null;
|
|
338
|
+
try {
|
|
339
|
+
fd = openSync(path, "r");
|
|
340
|
+
const chunk = Buffer.alloc(8192);
|
|
341
|
+
const parts: Buffer[] = [];
|
|
342
|
+
let total = 0;
|
|
343
|
+
for (;;) {
|
|
344
|
+
const n = readSync(fd, chunk, 0, chunk.length, total);
|
|
345
|
+
if (n <= 0) return null;
|
|
346
|
+
const nl = chunk.subarray(0, n).indexOf(10);
|
|
347
|
+
const take = nl === -1 ? n : nl;
|
|
348
|
+
parts.push(Buffer.from(chunk.subarray(0, take)));
|
|
349
|
+
total += take;
|
|
350
|
+
if (total > HEAD_READ_LIMIT) return null;
|
|
351
|
+
if (nl !== -1) break;
|
|
352
|
+
}
|
|
353
|
+
const obj = JSON.parse(Buffer.concat(parts).toString("utf8")) as { event?: unknown; tool?: unknown };
|
|
354
|
+
return obj.event === "receipt.head" && typeof obj.tool === "string" ? obj.tool : null;
|
|
355
|
+
} catch { return null; } finally { if (fd !== null) closeSync(fd); }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* §5.1: delete the oldest completed bundles of this tool beyond `count` in this location (another
|
|
360
|
+
* tool's receipts are never counted or deleted); never a receipt still in flight; never on a dry
|
|
361
|
+
* run; recorded as a decision. Exported for the package's own tests, not from the index:
|
|
362
|
+
* `afterScan` runs between the listing and the decisions, where another run can append.
|
|
363
|
+
*/
|
|
364
|
+
export function retain(run: Run, receiptDir: string, count: number, dryRun: boolean, at: number, afterScan?: () => void): void {
|
|
256
365
|
let files: { name: string; mtime: number }[];
|
|
257
|
-
try {
|
|
366
|
+
try {
|
|
367
|
+
files = readdirSync(receiptDir).filter((f) => f.endsWith(".jsonl") && headTool(join(receiptDir, f)) === run.tool).map((name) => ({ name, mtime: statSync(join(receiptDir, name)).mtimeMs }));
|
|
368
|
+
} catch { return; }
|
|
369
|
+
afterScan?.();
|
|
258
370
|
const excess = files.length - count;
|
|
259
371
|
if (excess <= 0) return;
|
|
260
372
|
const candidates = files.filter((f) => f.name !== `${run.id}.jsonl`).sort((a, b) => a.mtime - b.mtime || a.name.localeCompare(b.name));
|
|
261
|
-
|
|
373
|
+
// The scan orders the candidates; each decision re-observes its receipt, because another run can
|
|
374
|
+
// append between the scan and here (flyingrobots/parley#112). The observation is compared again
|
|
375
|
+
// just before the unlink.
|
|
376
|
+
const chosen: { name: string; seen: string }[] = [];
|
|
262
377
|
for (const f of candidates) {
|
|
263
|
-
if (
|
|
378
|
+
if (chosen.length >= excess) break;
|
|
264
379
|
const p = join(receiptDir, f.name);
|
|
265
|
-
|
|
380
|
+
const seen = observe(p);
|
|
381
|
+
if (seen === null) continue;
|
|
382
|
+
if (hasEnded(p) || at - seen.mtime > INCOMPLETE_GRACE_MS) chosen.push({ name: f.name, seen: seen.key });
|
|
266
383
|
}
|
|
267
|
-
|
|
268
|
-
if (
|
|
384
|
+
const victims = chosen.map((c) => c.name);
|
|
385
|
+
if (!victims.length) { run.step("retention: nothing to delete", `${files.length} of this tool's receipts exceed the retention count of ${count}, but every excess receipt is still in flight (no end line yet); only completed bundles, or incomplete ones older than a day, are deleted (§5.1)`); return; }
|
|
386
|
+
if (dryRun) { run.step(`retention: would delete ${victims.length} receipt bundle(s)`, `${files.length} of this tool's receipts exceed the retention count of ${count}; a dry run performs no retention deletion (§4.3)`, { receipts: victims }); return; }
|
|
269
387
|
const deleted: string[] = [];
|
|
270
|
-
for (const name of
|
|
388
|
+
for (const { name, seen } of chosen) {
|
|
389
|
+
const p = join(receiptDir, name);
|
|
390
|
+
if (observe(p)?.key !== seen) continue; // it moved since the decision: its run may be alive (flyingrobots/parley#112)
|
|
271
391
|
const base = name.slice(0, -".jsonl".length);
|
|
272
|
-
|
|
392
|
+
// One bundle (§5): rmSync with force ignores only an absent receipt, so a receipt that cannot be
|
|
393
|
+
// unlinked throws here and keeps its sidecars.
|
|
394
|
+
try { rmSync(p, { force: true }); rmSync(join(receiptDir, base), { recursive: true, force: true }); deleted.push(name); } catch { /* a bundle another run is deleting */ }
|
|
273
395
|
}
|
|
274
|
-
run.step(`retention: deleted ${deleted.length} receipt bundle(s)`, `${files.length} receipts exceeded the retention count of ${count}; the oldest completed bundles are deleted with their sidecars (§5.1)`, { receipts: deleted });
|
|
396
|
+
run.step(`retention: deleted ${deleted.length} receipt bundle(s)`, `${files.length} of this tool's receipts exceeded the retention count of ${count}; the oldest completed bundles are deleted with their sidecars (§5.1)`, { receipts: deleted });
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* §5.1 for the shared history stream (§8): keep `days` daily segments, today's included, and
|
|
401
|
+
* delete the rest whole, because an append-only file with concurrent writers can be expired by
|
|
402
|
+
* unlinking a segment nobody is writing to and cannot be expired by rewriting. Recorded as a
|
|
403
|
+
* decision, like the receipt's retention, and skipped on a dry run.
|
|
404
|
+
*/
|
|
405
|
+
function retainStream(run: Run, dir: string, days: number, dryRun: boolean, at: number): void {
|
|
406
|
+
const segments = retainHistory(dir, days, at, dryRun);
|
|
407
|
+
if (!segments.length) return;
|
|
408
|
+
if (dryRun) { run.step(`history retention: would delete ${segments.length} segment(s)`, `the shared history stream keeps ${days} daily segment(s), today's included; a dry run performs no retention deletion (§4.3)`, { segments }); return; }
|
|
409
|
+
run.step(`history retention: deleted ${segments.length} segment(s)`, `the shared history stream keeps ${days} daily segment(s), today's included; older segments are deleted whole, since an append-only file with concurrent writers cannot be rewritten safely (§5.1, §8)`, { segments });
|
|
275
410
|
}
|
|
276
411
|
|
|
277
412
|
// ---- console capture (§1.2) --------------------------------------------------------------
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// A built-in history transform (flyingrobots/parley#59): keep a declared set of strings off the
|
|
2
|
+
// shared timeline that are fine in a local receipt and wrong on a stream other people and tools
|
|
3
|
+
// read — a username in a path, a hostname, a private repository name. Without a built-in, every
|
|
4
|
+
// caller writes the same scrubbing function, and most get longest-first replacement or key
|
|
5
|
+
// renaming subtly wrong (spec §5.3). This is the same code path the receipt's own redaction uses,
|
|
6
|
+
// applied to the body alone with a second declared set, so its behaviour on nested keys,
|
|
7
|
+
// longest-first order and key renaming is already specified and tested in redact.ts.
|
|
8
|
+
import { DIGEST_KEYS } from "../run.ts";
|
|
9
|
+
import type { HistoryTransform } from "../history.ts";
|
|
10
|
+
import { scrub } from "../redact.ts";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A projection that scrubs `values` out of the stream copy's body, exactly as spec §5.3 scrubs a
|
|
14
|
+
* declared secret: longest value first, so one value that contains another is replaced whole, and
|
|
15
|
+
* a key that carries a declared value is renamed. The envelope — `event`, `t`, `seq`, `run` and
|
|
16
|
+
* `_schema` — is never its to touch; it is read off the record and put back untouched, before the
|
|
17
|
+
* writer reattaches its own anyway (§1.3).
|
|
18
|
+
*
|
|
19
|
+
* This runs on whatever record the receipt holds, which may be a writer-built one (`receipt.head`,
|
|
20
|
+
* `end`) and not only a tool's own. A writer-built record's own identity scalars — `tool`, `v`,
|
|
21
|
+
* `inv`, `sha256`, `name`, `id`, `version`, `code` — carry no pattern a validator would reject a
|
|
22
|
+
* corrupted one by, so a declared value that happens to coincide with, say, the tool's own name
|
|
23
|
+
* would otherwise silently rename `tool` on the stream's head with nothing to catch it (the same
|
|
24
|
+
* reason `src/run.ts` exempts these keys, `DIGEST_KEYS`, from the receipt's own redaction of a
|
|
25
|
+
* writer-built record). This exempts them here too, at any depth, the same way.
|
|
26
|
+
*
|
|
27
|
+
* An empty declared set is the identity transform, and this returns `undefined` for it rather
|
|
28
|
+
* than a function that merely behaves like one: `MainOptions.history.transform` is then itself
|
|
29
|
+
* `undefined`, the writer never builds a projection for it, and the stream copy carries no
|
|
30
|
+
* `parley.history.transform` opening line at all — the run that existed before the transform did
|
|
31
|
+
* (§8, informative). The alternative, an identity function, would still open the stream with a
|
|
32
|
+
* transform line; this package chooses no line over an inert one.
|
|
33
|
+
*
|
|
34
|
+
* The transform's name on that opening line is always `declaredProjection`, whatever `values`
|
|
35
|
+
* holds, because the returned function is declared with that name rather than built by string
|
|
36
|
+
* assembly. The digest the line also carries is a SHA-256 of the function's *source text*
|
|
37
|
+
* (`fn.toString()`), and `values` reaches this function only as a closed-over variable — never
|
|
38
|
+
* interpolated into the source — so the digest, the name and the line itself disclose nothing
|
|
39
|
+
* about what was declared.
|
|
40
|
+
*/
|
|
41
|
+
export function declaredProjection(values: readonly string[]): HistoryTransform | undefined {
|
|
42
|
+
const declared = new Set(values);
|
|
43
|
+
if (declared.size === 0) return undefined;
|
|
44
|
+
return function declaredProjection(record: Record<string, unknown>): Record<string, unknown> {
|
|
45
|
+
const { event, t, seq, run, _schema, ...body } = record;
|
|
46
|
+
const scrubbed = scrub(body, declared, "", [], { skipKeys: DIGEST_KEYS }) as Record<string, unknown>;
|
|
47
|
+
return { event, t, seq, run, ...scrubbed, _schema };
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The token shapes `refuseSuspectedSecrets` refuses, as data (flyingrobots/parley#60).
|
|
2
|
+
//
|
|
3
|
+
// This list is the reviewable part of the built-in. It is data so that reviewing it is reading a
|
|
4
|
+
// table rather than reading code, so that a caller can replace it wholesale, and so that a new
|
|
5
|
+
// entry is one row plus the two samples the test walk demands.
|
|
6
|
+
//
|
|
7
|
+
// Three rules every entry holds to:
|
|
8
|
+
//
|
|
9
|
+
// 1. **Conservative and anchored.** A word boundary or a literal prefix at the start, and a
|
|
10
|
+
// fixed length or a floor long enough that prose does not reach it. The cost of a false
|
|
11
|
+
// positive is one withheld stream line, which is cheap but not free, and a shape that fires
|
|
12
|
+
// on ordinary text would make the whole built-in something people switch off.
|
|
13
|
+
// 2. **A published shape, not a guess.** Each is a prefix a vendor assigns and documents, so
|
|
14
|
+
// the match is evidence about the string's provenance rather than about its entropy. There
|
|
15
|
+
// is deliberately no "40 hex characters" entry: it would refuse every SHA-1.
|
|
16
|
+
// 3. **Case-sensitive, matched against one string value at a time.** No flags are applied when
|
|
17
|
+
// these sources are compiled, so there is no `g` and no `lastIndex` to carry between lines.
|
|
18
|
+
//
|
|
19
|
+
// What this list is not is complete. An unlisted shape passes, and that is stated rather than
|
|
20
|
+
// implied: this refuses what it recognises, and recognition is a floor, not a guarantee.
|
|
21
|
+
|
|
22
|
+
/** One reviewable token shape. */
|
|
23
|
+
export interface SecretPattern {
|
|
24
|
+
/** The shape's name, as the warning reports it. Dot-separated, vendor first. */
|
|
25
|
+
readonly name: string;
|
|
26
|
+
/** The source of a `RegExp`, compiled with no flags. */
|
|
27
|
+
readonly regex: string;
|
|
28
|
+
/** One line: what it is, and why this shape can be refused on sight. */
|
|
29
|
+
readonly why: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The shapes the built-in refuses when the caller names none of their own. */
|
|
33
|
+
export const SECRET_PATTERNS: readonly SecretPattern[] = Object.freeze([
|
|
34
|
+
{
|
|
35
|
+
name: "aws.access_key_id",
|
|
36
|
+
regex: "\\bAKIA[0-9A-Z]{16}\\b",
|
|
37
|
+
why: "An AWS access key id: the fixed AKIA prefix and exactly sixteen more upper-case base32 characters, a shape nothing else assigns.",
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
name: "github.token",
|
|
41
|
+
regex: "\\bgh[opsur]_[A-Za-z0-9]{36}\\b",
|
|
42
|
+
why: "A GitHub personal access, OAuth, app, server or refresh token: one of six documented prefixes and exactly thirty-six more characters.",
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: "github.fine_grained_pat",
|
|
46
|
+
regex: "\\bgithub_pat_[A-Za-z0-9]{22}_[A-Za-z0-9]{59}\\b",
|
|
47
|
+
why: "A GitHub fine-grained personal access token, whose two fixed-length segments make the whole string eighty-two characters after the prefix.",
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: "slack.token",
|
|
51
|
+
regex: "\\bxox[abpr]-[0-9A-Za-z]{8,}(?:-[0-9A-Za-z]{8,}){0,3}\\b",
|
|
52
|
+
why: "A Slack bot, app, user or refresh token: the xox prefix, a type letter, and dash-separated segments no shorter than eight characters.",
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
name: "google.api_key",
|
|
56
|
+
regex: "\\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])",
|
|
57
|
+
why: "A Google API key: the AIza prefix and exactly thirty-five more URL-safe characters, thirty-nine in all.",
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
name: "pem.private_key",
|
|
61
|
+
regex: "-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----",
|
|
62
|
+
why: "A PEM private key header, in any of its labelled forms; the header alone means the body is in the same string or the next one.",
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
name: "jwt",
|
|
66
|
+
regex: "\\beyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}(?![A-Za-z0-9_-])",
|
|
67
|
+
why: "A JWT: three base64url segments, the first beginning eyJ because a JSON header always starts with an opening brace and a quote.",
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
name: "http.bearer_token",
|
|
71
|
+
regex: "\\bBearer\\s+[A-Za-z0-9._~+/=-]{20,}",
|
|
72
|
+
why: "An Authorization header's value: the literal Bearer and at least twenty token characters, which is the generic case no vendor prefix catches.",
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: "npm.token",
|
|
76
|
+
regex: "\\bnpm_[A-Za-z0-9]{36}\\b",
|
|
77
|
+
why: "An npm access token: the npm_ prefix and exactly thirty-six more characters.",
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
name: "stripe.live_key",
|
|
81
|
+
regex: "\\b(?:sk|rk)_live_[0-9A-Za-z]{10,}\\b",
|
|
82
|
+
why: "A Stripe live secret or restricted key; the test-mode prefixes are deliberately not listed, because a test key is not a credential worth a gap.",
|
|
83
|
+
},
|
|
84
|
+
] as const satisfies readonly SecretPattern[]);
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// `refuseSuspectedSecrets`: refuse a line that looks like it carries a credential
|
|
2
|
+
// (flyingrobots/parley#60).
|
|
3
|
+
//
|
|
4
|
+
// Declared redaction (spec §5.3) replaces what the program declared. It cannot catch a secret
|
|
5
|
+
// nobody declared, and an undeclared token in a result reaches the shared timeline silently —
|
|
6
|
+
// where, unlike a receipt, it lives for the retention window and is read by more observers than
|
|
7
|
+
// the run that produced it.
|
|
8
|
+
//
|
|
9
|
+
// This is a history transform that withholds such a line. Two things about it are deliberate:
|
|
10
|
+
//
|
|
11
|
+
// - **It refuses; it never rewrites.** A heuristic must not claim the certainty that rewriting
|
|
12
|
+
// implies. Replacing the matched span would put a record on the stream that *looks* checked
|
|
13
|
+
// and differs from the receipt's copy of the same event in a way nothing records. Withholding
|
|
14
|
+
// leaves a `seq` gap on the stream alone, which a reader can see and the doctor reports. So
|
|
15
|
+
// the cost of a false positive is one withheld stream line, never a changed result.
|
|
16
|
+
// - **It scans the body, never the envelope.** `event`, `t`, `seq`, `run` and `_schema` are the
|
|
17
|
+
// writer's, chosen secret-free at startup, and identical on both copies of one event (§1.3).
|
|
18
|
+
// Scanning them would let one unlucky run id withhold every line of a run.
|
|
19
|
+
//
|
|
20
|
+
// The honest limits, all three tested and documented:
|
|
21
|
+
//
|
|
22
|
+
// - An unlisted shape passes. This refuses what it recognises; recognition is a floor.
|
|
23
|
+
// - A token split across two string values passes. The scan is per value and claims nothing
|
|
24
|
+
// about what concatenating two of them would spell.
|
|
25
|
+
// - A token used as an object *key* passes. Keys name fields; a value is what a program carries.
|
|
26
|
+
// (The writer's own §5.3 scrubber does rename keys, because there the value is declared.)
|
|
27
|
+
|
|
28
|
+
import { refuse, type HistoryRefusal } from "../refusal.ts";
|
|
29
|
+
import { SECRET_PATTERNS, type SecretPattern } from "./secret-patterns.ts";
|
|
30
|
+
|
|
31
|
+
/** The code of the warning a refusal by this built-in raises. */
|
|
32
|
+
export const SUSPECTED_SECRET_CODE = "history.suspected_secret";
|
|
33
|
+
|
|
34
|
+
/** Where in a record's body a token shape matched. */
|
|
35
|
+
export interface SuspectedSecret {
|
|
36
|
+
/** The matching pattern's `name`, never the matched text. */
|
|
37
|
+
readonly pattern: string;
|
|
38
|
+
/** A JSON Pointer (RFC 6901) into the record, as a `redaction` event would name one (§5.3). */
|
|
39
|
+
readonly at: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The envelope is the writer's and is never scanned (§1.3). */
|
|
43
|
+
const ENVELOPE = new Set(["event", "t", "seq", "run", "_schema"]);
|
|
44
|
+
|
|
45
|
+
interface Compiled { readonly name: string; readonly re: RegExp }
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* One compile per pattern list, keyed by the list itself: the default list is compiled once for
|
|
49
|
+
* the process, and a caller's list once per list. A per-call compile would be ten `RegExp`
|
|
50
|
+
* constructions per line of a segment.
|
|
51
|
+
*/
|
|
52
|
+
const compiledFor = new WeakMap<readonly SecretPattern[], readonly Compiled[]>();
|
|
53
|
+
|
|
54
|
+
function compile(patterns: readonly SecretPattern[]): readonly Compiled[] {
|
|
55
|
+
const had = compiledFor.get(patterns);
|
|
56
|
+
if (had !== undefined) return had;
|
|
57
|
+
// No flags: no `g`, so no `lastIndex` carried from one line to the next, and case-sensitive,
|
|
58
|
+
// because every shape here is a prefix its vendor assigns in one case.
|
|
59
|
+
const made = patterns.map((p) => ({ name: p.name, re: new RegExp(p.regex) }));
|
|
60
|
+
compiledFor.set(patterns, made);
|
|
61
|
+
return made;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** RFC 6901: `~` is `~0` and `/` is `~1`, so a pointer is unambiguous about which key it names. */
|
|
65
|
+
const token = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
66
|
+
|
|
67
|
+
/** The first shape a string matches, or `null`. */
|
|
68
|
+
function matchOf(value: string, patterns: readonly Compiled[]): string | null {
|
|
69
|
+
for (const p of patterns) if (p.re.test(value)) return p.name;
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function scan(value: unknown, at: string, patterns: readonly Compiled[]): SuspectedSecret | null {
|
|
74
|
+
if (typeof value === "string") {
|
|
75
|
+
const hit = matchOf(value, patterns);
|
|
76
|
+
return hit === null ? null : { pattern: hit, at };
|
|
77
|
+
}
|
|
78
|
+
if (Array.isArray(value)) {
|
|
79
|
+
for (let i = 0; i < value.length; i++) {
|
|
80
|
+
const hit = scan(value[i], `${at}/${i}`, patterns);
|
|
81
|
+
if (hit !== null) return hit;
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
if (typeof value === "object" && value !== null) {
|
|
86
|
+
for (const [k, v] of Object.entries(value)) {
|
|
87
|
+
const hit = scan(v, `${at}/${token(k)}`, patterns);
|
|
88
|
+
if (hit !== null) return hit;
|
|
89
|
+
}
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The first token shape a record's **body** matches, or `null`. Strings are walked recursively
|
|
97
|
+
* through objects and arrays; the five envelope fields are skipped at the top level, and object
|
|
98
|
+
* keys are not scanned. The first match wins: the result says *that* the body looks like it
|
|
99
|
+
* carries a credential, which is all a refusal needs, so there is no reason to keep looking.
|
|
100
|
+
*
|
|
101
|
+
* `at` is built from the record's own keys, so it can itself carry a token-shaped key. It is safe
|
|
102
|
+
* to inspect in the process and is **not** safe to emit as it is; `refuseSuspectedSecrets` checks
|
|
103
|
+
* it before naming it in a warning.
|
|
104
|
+
*/
|
|
105
|
+
export function findSuspectedSecret(record: Record<string, unknown>, patterns: readonly SecretPattern[] = SECRET_PATTERNS): SuspectedSecret | null {
|
|
106
|
+
const compiled = compile(patterns);
|
|
107
|
+
if (compiled.length === 0) return null;
|
|
108
|
+
for (const [k, v] of Object.entries(record)) {
|
|
109
|
+
if (ENVELOPE.has(k)) continue;
|
|
110
|
+
const hit = scan(v, `/${token(k)}`, compiled);
|
|
111
|
+
if (hit !== null) return hit;
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A transform that withholds any line whose body matches one of `patterns`, and raises one
|
|
118
|
+
* `history.suspected_secret` warning naming the withheld `seq`, the shape and the pointer — never
|
|
119
|
+
* the matched text, which would put the suspected credential on stderr and in the receipt copy of
|
|
120
|
+
* the warning, and from there on the stream.
|
|
121
|
+
*
|
|
122
|
+
* ```ts
|
|
123
|
+
* await main(tool, argv, handler, { history: { transform: refuseSuspectedSecrets() } });
|
|
124
|
+
* ```
|
|
125
|
+
*
|
|
126
|
+
* `patterns` replaces the default list entirely rather than extending it, so a caller who passes
|
|
127
|
+
* one is reviewing exactly what they refuse on; pass `[...SECRET_PATTERNS, ...mine]` to add. An
|
|
128
|
+
* empty list is the identity transform. Pass `name` to `history` alongside it when the list is
|
|
129
|
+
* customised: the digest on the stream's opening line is of this function's source text, which
|
|
130
|
+
* does not change when the list it closes over does.
|
|
131
|
+
*/
|
|
132
|
+
export function refuseSuspectedSecrets(patterns: readonly SecretPattern[] = SECRET_PATTERNS): (record: Record<string, unknown>) => Record<string, unknown> | HistoryRefusal {
|
|
133
|
+
// Compiled here rather than on the first record, so a pattern that will not compile is a throw
|
|
134
|
+
// where the list was configured instead of one withheld line per line of the run.
|
|
135
|
+
const compiled = compile(patterns);
|
|
136
|
+
return function refuseSuspectedSecrets(record: Record<string, unknown>) {
|
|
137
|
+
const hit = findSuspectedSecret(record, patterns);
|
|
138
|
+
if (hit === null) return record;
|
|
139
|
+
const seq = typeof record.seq === "number" ? String(record.seq) : "?";
|
|
140
|
+
// The pointer is made of the record's keys, and a key can be a token too. Naming it would put
|
|
141
|
+
// a *different* suspected secret on stderr, in the receipt and on the stream through this
|
|
142
|
+
// warning's own copy — which is the one thing this transform exists to prevent.
|
|
143
|
+
const inKey = matchOf(hit.at, compiled);
|
|
144
|
+
const where = inKey === null
|
|
145
|
+
? `at ${hit.at}`
|
|
146
|
+
: `under a key this warning will not repeat, because the key itself matches the ${inKey} shape`;
|
|
147
|
+
return refuse(
|
|
148
|
+
SUSPECTED_SECRET_CODE,
|
|
149
|
+
`the body of seq ${seq} matches the ${hit.pattern} shape ${where}, so that line is not on the shared stream; the receipt is unaffected and still carries the value`,
|
|
150
|
+
`declare the value as a secret in the command's secrets list (spec §5.3) so it is replaced in the receipt too, or keep it out of the record; an unlisted shape passes, and a legitimate value that matches costs this one stream line`,
|
|
151
|
+
);
|
|
152
|
+
};
|
|
153
|
+
}
|