@flyingrobots/parley-emit 0.0.0-stage → 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 +336 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +669 -2
- package/package.json +34 -4
- package/src/check.ts +198 -0
- package/src/history.ts +229 -0
- package/src/index.ts +14 -0
- package/src/inv.ts +72 -0
- package/src/location.ts +154 -0
- package/src/redact.ts +108 -0
- package/src/refusal.ts +54 -0
- package/src/run.ts +568 -0
- package/src/schemas.ts +2042 -0
- package/src/tool.ts +463 -0
- package/src/transforms/declared.ts +49 -0
- package/src/transforms/secret-patterns.ts +84 -0
- package/src/transforms/secrets.ts +153 -0
- package/src/ulid.ts +13 -0
package/src/tool.ts
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
// A tool: its commands, their declarations, and the entry point that turns argv and a handler
|
|
2
|
+
// into a conforming run (spec §3, §4, §6).
|
|
3
|
+
import { closeSync, openSync, readSync, readdirSync, rmSync, statSync, unlinkSync, writeSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
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";
|
|
7
|
+
import { computeInv, type InputDecl } from "./inv.ts";
|
|
8
|
+
import { bookkeepingFor, chooseLocation, isLocationFailure, type Bookkeeping } from "./location.ts";
|
|
9
|
+
import { carriesSecret, classifySecrets, collectSecretValues, redactArgv, scrub } from "./redact.ts";
|
|
10
|
+
import { Run, SCHEMA_IDS, type Record_, type SchemaRef, type Sink } from "./run.ts";
|
|
11
|
+
import { SCHEMAS } from "./schemas.ts";
|
|
12
|
+
import { ulid } from "./ulid.ts";
|
|
13
|
+
|
|
14
|
+
export interface Effects { reads: string[]; writes: string[]; network: boolean; idempotent: boolean }
|
|
15
|
+
export interface EmittedType extends SchemaRef { readonly schema?: Record<string, unknown> }
|
|
16
|
+
export interface CommandSpec {
|
|
17
|
+
readonly intent: string;
|
|
18
|
+
readonly effects: Effects;
|
|
19
|
+
/** Flags (`--token`), environment variables (`APP_TOKEN`) and logical credential sources (`netrc`). */
|
|
20
|
+
readonly secrets?: readonly string[];
|
|
21
|
+
/** The result types the command can emit; a tool-owned type carries its JSON Schema for discovery. */
|
|
22
|
+
readonly emits: readonly EmittedType[];
|
|
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
|
+
*/
|
|
28
|
+
readonly errors?: readonly EmittedType[];
|
|
29
|
+
}
|
|
30
|
+
export interface ToolSpec {
|
|
31
|
+
readonly name: string;
|
|
32
|
+
readonly version: string;
|
|
33
|
+
readonly commands: Readonly<Record<string, CommandSpec>>;
|
|
34
|
+
/** §5.1: a stated policy. Completed receipts beyond `count` in a location are deleted, oldest first. */
|
|
35
|
+
readonly retention: { readonly count: number };
|
|
36
|
+
/** Resolvers for declared credential sources, called before the head is written (§5.3). */
|
|
37
|
+
readonly sources?: Readonly<Record<string, () => boolean | Promise<boolean>>>;
|
|
38
|
+
/** Prose for `--human`: return a string for a line, or null for the default rendering. */
|
|
39
|
+
readonly human?: (line: Record_) => string | null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function defineTool(spec: ToolSpec): ToolSpec {
|
|
43
|
+
if (!spec.name) throw new TypeError("tool name is never empty");
|
|
44
|
+
if (!spec.version) throw new TypeError("tool version is never empty");
|
|
45
|
+
if (!Object.keys(spec.commands).length) throw new TypeError("a tool has at least one command");
|
|
46
|
+
if (!Number.isInteger(spec.retention?.count) || spec.retention.count < 1) throw new TypeError("retention.count must be a positive integer (spec §5.1)");
|
|
47
|
+
for (const [name, c] of Object.entries(spec.commands)) {
|
|
48
|
+
if (!c.intent) throw new TypeError(`command ${name} needs an intent`);
|
|
49
|
+
for (const e of c.emits) if (!e.id || !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(e.version)) throw new TypeError(`command ${name} emits an invalid type ${e.id}@${e.version}`);
|
|
50
|
+
}
|
|
51
|
+
return spec;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export type { InputDecl };
|
|
55
|
+
export interface MainOptions {
|
|
56
|
+
cwd?: string;
|
|
57
|
+
env?: Record<string, string | undefined>;
|
|
58
|
+
home?: string;
|
|
59
|
+
stdout?: Sink;
|
|
60
|
+
stderr?: Sink;
|
|
61
|
+
session?: string;
|
|
62
|
+
now?: () => number;
|
|
63
|
+
/** The declared inputs of this invocation, from the command's arguments. */
|
|
64
|
+
inputs?: (args: string[], command: string) => InputDecl[] | Promise<InputDecl[]>;
|
|
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. */
|
|
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;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* A sink on a file descriptor that delivers the whole line: a partial write continues from where
|
|
79
|
+
* it stopped, and EAGAIN (a full pipe on a descriptor the runtime left non-blocking) waits a
|
|
80
|
+
* millisecond and tries again, which is what a blocking write would have done.
|
|
81
|
+
*/
|
|
82
|
+
export function fdSink(fd: number): Sink {
|
|
83
|
+
const pause = new Int32Array(new SharedArrayBuffer(4));
|
|
84
|
+
return {
|
|
85
|
+
write(line) {
|
|
86
|
+
const buf = Buffer.from(line, "utf8");
|
|
87
|
+
let off = 0;
|
|
88
|
+
while (off < buf.length) {
|
|
89
|
+
try { off += writeSync(fd, buf, off, buf.length - off); }
|
|
90
|
+
catch (e) { if ((e as NodeJS.ErrnoException).code === "EAGAIN") { Atomics.wait(pause, 0, 0, 1); continue; } throw e; }
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const OWN_FLAGS = new Set(["--human", "--humanize", "--dry-run", "--schema", "--help", "-h"]);
|
|
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];
|
|
99
|
+
/** Incomplete receipts (no end line) older than this are deletable by retention; younger ones may still be in flight. */
|
|
100
|
+
const INCOMPLETE_GRACE_MS = 24 * 60 * 60 * 1000;
|
|
101
|
+
|
|
102
|
+
export type Handler = (run: Run, args: string[]) => void | Promise<void>;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Run a tool: parse the writer-owned flags, bootstrap, write the receipt, run the handler under
|
|
106
|
+
* the top-level handler of §6, and close with `end`. Returns the exit status (§3.4).
|
|
107
|
+
*/
|
|
108
|
+
export async function main(spec: ToolSpec, argv: readonly string[], handler: Handler, opts: MainOptions = {}): Promise<number> {
|
|
109
|
+
const env = opts.env ?? process.env;
|
|
110
|
+
const cwd = resolve(opts.cwd ?? process.cwd());
|
|
111
|
+
const stdout = opts.stdout ?? fdSink(1), stderr = opts.stderr ?? fdSink(2);
|
|
112
|
+
const now = opts.now ?? Date.now;
|
|
113
|
+
const rawArgs = argv.slice(1);
|
|
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));
|
|
124
|
+
const names = Object.keys(spec.commands);
|
|
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];
|
|
132
|
+
const command = commandName ? spec.commands[commandName]! : undefined;
|
|
133
|
+
|
|
134
|
+
// Declared secrets of every command: a value passed to the wrong command is still a secret (§5.3).
|
|
135
|
+
const allNames = classifySecrets(names.flatMap((n) => spec.commands[n]!.secrets ?? []));
|
|
136
|
+
const secretValues = collectSecretValues(argv, allNames, env);
|
|
137
|
+
const ownNames = classifySecrets(command?.secrets ?? []);
|
|
138
|
+
|
|
139
|
+
let id = ulid(now());
|
|
140
|
+
for (let i = 0; i < 16 && carriesSecret(id, secretValues); i++) id = ulid(now());
|
|
141
|
+
|
|
142
|
+
const startupFailed = (code: string, problem: string, remedy: string): number => {
|
|
143
|
+
const line = { event: "startup.failed", t: now(), seq: 0, run: id, tool: spec.name, v: spec.version, code, problem: scrubText(problem, secretValues), remedy, _schema: SCHEMA_IDS.startupFailed };
|
|
144
|
+
try { stderr.write(human ? `startup failed ${code}: ${line.problem} (${remedy})\n` : JSON.stringify(line) + "\n"); } catch { /* nothing else can be said */ }
|
|
145
|
+
return 3;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
if (carriesSecret(id, secretValues)) return startupFailed("startup.secret_in_path", "no run id free of a declared secret value could be chosen", "do not pass a value this short as a declared secret");
|
|
149
|
+
// The bootstrap line's identity fields are never scrubbed. The tool's name and version are public
|
|
150
|
+
// and printed on every startup line regardless, so a secret inside them is not protectable and
|
|
151
|
+
// the run proceeds; a session is caller-supplied and can be withheld, so one carrying a secret
|
|
152
|
+
// is a startup failure (the startup line omits it).
|
|
153
|
+
const sessionEarly = opts.session ?? env.PARLEY_SESSION;
|
|
154
|
+
if (sessionEarly && carriesSecret(sessionEarly, secretValues)) return startupFailed("startup.secret_in_identity", "the session id contains a declared secret value and cannot be printed", "supply a session id that does not contain the secret");
|
|
155
|
+
if (!commandName && discovery === null) return startupFailed("startup.unknown_command", `no command named; commands are ${names.join(", ")}`, `name one of: ${names.join(", ")}`);
|
|
156
|
+
|
|
157
|
+
// Console capture starts here, before any tool code runs; captured text is buffered until the receipt exists (§1.2).
|
|
158
|
+
const capture = captureConsole();
|
|
159
|
+
const release = capture.release;
|
|
160
|
+
const fail = (code: string, problem: string, remedy: string): number => { release(); return startupFailed(code, problem, remedy); };
|
|
161
|
+
|
|
162
|
+
// Declared credential sources, resolved before the head (§5.3); a throwing resolver means "not present".
|
|
163
|
+
const presentSources: string[] = [];
|
|
164
|
+
for (const s of ownNames.sources) { try { if (await spec.sources?.[s]?.()) presentSources.push(s); } catch { /* not present */ } }
|
|
165
|
+
const presentEnv = allNames.env.filter((n) => env[n] !== undefined);
|
|
166
|
+
|
|
167
|
+
const location = chooseLocation({ cwd, run: id, env, home: opts.home ?? homedir(), secrets: secretValues });
|
|
168
|
+
if (isLocationFailure(location)) return fail(location.code, location.problem, location.remedy);
|
|
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
|
+
|
|
186
|
+
// Everything the tool supplies before the bootstrap line can throw; a throw here is a startup failure (§3.2), not a stack trace.
|
|
187
|
+
let resolvedRaw: Record<string, unknown>, inputs: InputDecl[];
|
|
188
|
+
try {
|
|
189
|
+
resolvedRaw = discovery ? { discovery, command: commandName } : await (opts.resolved ?? ((a, c) => ({ command: c, args: a })))(rest, commandName!);
|
|
190
|
+
inputs = discovery || !command ? [] : await (opts.inputs ?? (() => []))(rest, commandName!);
|
|
191
|
+
} catch (e) {
|
|
192
|
+
try { closeSync(location.fd); unlinkSync(location.receiptPath); } catch { /* the reservation is gone either way */ }
|
|
193
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
194
|
+
return fail("startup.arguments_invalid", `the arguments could not be interpreted: ${err.message || err.name}`, "fix the arguments; see the command's --help");
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const sessionRaw = opts.session ?? env.PARLEY_SESSION;
|
|
198
|
+
const session = sessionRaw ? sessionRaw : undefined;
|
|
199
|
+
const resolvedPointers: string[] = [];
|
|
200
|
+
const resolved = scrub(resolvedRaw, secretValues, "", resolvedPointers);
|
|
201
|
+
const { argv: argvRedacted, indexes: argvIndexes } = redactArgv(argv, secretValues, allNames.flags);
|
|
202
|
+
const inputPointers: string[] = [];
|
|
203
|
+
const inputDescriptors = scrub(inputs.map((i) => ({ path: i.path, ...(i.role ? { role: i.role } : {}) })), secretValues, "", inputPointers) as { path: string; role?: string }[];
|
|
204
|
+
const inputIndexes = inputPointers.map((p) => Number(p.split("/")[1]));
|
|
205
|
+
const redacted: Record<string, unknown> = {};
|
|
206
|
+
if (argvIndexes.length) redacted.argv = argvIndexes;
|
|
207
|
+
if (resolvedPointers.length) redacted.resolved = resolvedPointers;
|
|
208
|
+
if (inputIndexes.length) redacted.inputs = [...new Set(inputIndexes)];
|
|
209
|
+
if (presentEnv.length) redacted.env = presentEnv;
|
|
210
|
+
if (presentSources.length) redacted.sources = presentSources;
|
|
211
|
+
const headRedacted = Object.keys(redacted).length > 0;
|
|
212
|
+
const inv = inputs.length === 0 && command ? computeInv({ tool: spec.name, v: spec.version, command: commandName!, resolved, inputs: [] }) : undefined;
|
|
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
|
+
|
|
221
|
+
const run = new Run({
|
|
222
|
+
tool: spec.name, v: spec.version, id, session, dryRun, stdout, stderr, receiptFd: location.fd, receiptPath: location.receiptPath, receiptDir: location.receiptDir,
|
|
223
|
+
secretValues, now, cwd, command: commandName ?? discovery!, resolved, inputs, headRedacted, human: human ? spec.human ?? (() => null) : undefined, history, projection,
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
run.bootstrap(inv);
|
|
227
|
+
run.declareProjection();
|
|
228
|
+
const bookkeeping = [...bookkeepingFor(cwd, env, opts.home), ...(history ? historyBookkeeping(history) : [])];
|
|
229
|
+
run.head({
|
|
230
|
+
tool: spec.name, v: spec.version, ...(inv ? { inv } : {}), ...(session ? { session } : {}),
|
|
231
|
+
argv: argvRedacted, resolved, ...(headRedacted ? { redacted } : {}), inputs: inputDescriptors,
|
|
232
|
+
effects: command ? { ...command.effects, bookkeeping } : { reads: [], writes: [], network: false, idempotent: true, bookkeeping },
|
|
233
|
+
...(dryRun ? { dry_run: true } : {}),
|
|
234
|
+
});
|
|
235
|
+
run.flushDeferredFailures();
|
|
236
|
+
capture.attach(run);
|
|
237
|
+
if (run.sinkFailed) { release(); return run.end(); }
|
|
238
|
+
if (location.warning) run.writerWarning(location.warning);
|
|
239
|
+
if (historyWarning) run.writerWarning(historyWarning);
|
|
240
|
+
run.noteProjection();
|
|
241
|
+
|
|
242
|
+
retain(run, location.receiptDir, spec.retention.count, dryRun, now());
|
|
243
|
+
if (history) retainStream(run, history.dir, historyPlan?.days ?? historyDays(env), dryRun, now());
|
|
244
|
+
|
|
245
|
+
if (discovery) {
|
|
246
|
+
try { discover(run, spec, discovery, commandName, bookkeeping); } catch (e) {
|
|
247
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
248
|
+
if (!run.ended) run.error({ code: "uncaught.exception", problem: `uncaught ${err.name} during discovery: ${err.message || "(no message)"}`, remedy: `this is a defect in the tool's declaration; report it with the receipt at ${run.receiptPath}` }, { detail: { stack: err.stack } });
|
|
249
|
+
}
|
|
250
|
+
release();
|
|
251
|
+
return run.ended ? run.status ?? 4 : run.end();
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
try {
|
|
255
|
+
await handler(run, [...rest]);
|
|
256
|
+
} catch (e) {
|
|
257
|
+
if (run.ended) { release(); return 4; }
|
|
258
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
259
|
+
run.error({ code: "uncaught.exception", problem: `uncaught ${err.name}: ${err.message || "(no message)"}`, remedy: `this is a defect in the tool; report it with the receipt at ${run.receiptPath}` }, { detail: { stack: err.stack } });
|
|
260
|
+
} finally {
|
|
261
|
+
release();
|
|
262
|
+
}
|
|
263
|
+
return run.ended ? run.status ?? 4 : run.end();
|
|
264
|
+
}
|
|
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
|
+
|
|
281
|
+
function discover(run: Run, spec: ToolSpec, discovery: "schema" | "help", commandName: string | undefined, bookkeeping: Bookkeeping[]): void {
|
|
282
|
+
const names = Object.keys(spec.commands);
|
|
283
|
+
{
|
|
284
|
+
const which = discovery === "help" && commandName ? [commandName] : names;
|
|
285
|
+
for (const name of which) {
|
|
286
|
+
const c = spec.commands[name]!;
|
|
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);
|
|
288
|
+
}
|
|
289
|
+
const types = new Map<string, EmittedType>();
|
|
290
|
+
const add = (t: EmittedType) => { const k = `${t.id}@${t.version}`; if (!types.has(k)) types.set(k, t); };
|
|
291
|
+
for (const name of which) { const c = spec.commands[name]!; c.emits.forEach(add); (c.errors ?? DEFAULT_ERRORS).forEach(add); }
|
|
292
|
+
if (discovery === "schema") WRITER_SCHEMAS.forEach(add);
|
|
293
|
+
for (const t of types.values()) {
|
|
294
|
+
const doc = t.schema ?? SCHEMAS.find((s) => s.id === t.id && s.version === t.version)?.schema;
|
|
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; }
|
|
296
|
+
run.describe({ event: "schema", id: t.id, version: t.version, schema: doc }, SCHEMA_IDS.schema, "schema");
|
|
297
|
+
}
|
|
298
|
+
run.end(0);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function scrubText(s: string, values: ReadonlySet<string>): string { return scrub(s, values) as string; }
|
|
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
|
+
|
|
309
|
+
/** True when the receipt's final line is a newline-terminated `end` (§5.4), read from its tail. */
|
|
310
|
+
function hasEnded(path: string): boolean {
|
|
311
|
+
let fd: number | null = null;
|
|
312
|
+
try {
|
|
313
|
+
const size = statSync(path).size;
|
|
314
|
+
if (size === 0) return false;
|
|
315
|
+
fd = openSync(path, "r");
|
|
316
|
+
const len = Math.min(size, 8192);
|
|
317
|
+
const buf = Buffer.alloc(len);
|
|
318
|
+
readSync(fd, buf, 0, len, size - len);
|
|
319
|
+
const text = buf.toString("utf8");
|
|
320
|
+
if (!text.endsWith("\n")) return false;
|
|
321
|
+
const last = text.slice(0, -1).split("\n").pop() ?? "";
|
|
322
|
+
const obj = JSON.parse(last) as { event?: string };
|
|
323
|
+
return obj.event === "end";
|
|
324
|
+
} catch { return false; } finally { if (fd !== null) closeSync(fd); }
|
|
325
|
+
}
|
|
326
|
+
|
|
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 {
|
|
365
|
+
let files: { name: string; mtime: number }[];
|
|
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?.();
|
|
370
|
+
const excess = files.length - count;
|
|
371
|
+
if (excess <= 0) return;
|
|
372
|
+
const candidates = files.filter((f) => f.name !== `${run.id}.jsonl`).sort((a, b) => a.mtime - b.mtime || a.name.localeCompare(b.name));
|
|
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 }[] = [];
|
|
377
|
+
for (const f of candidates) {
|
|
378
|
+
if (chosen.length >= excess) break;
|
|
379
|
+
const p = join(receiptDir, f.name);
|
|
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 });
|
|
383
|
+
}
|
|
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; }
|
|
387
|
+
const deleted: string[] = [];
|
|
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)
|
|
391
|
+
const base = name.slice(0, -".jsonl".length);
|
|
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 */ }
|
|
395
|
+
}
|
|
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 });
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// ---- console capture (§1.2) --------------------------------------------------------------
|
|
413
|
+
// One saved copy of the real console, taken when the first capture starts; a stack of captures,
|
|
414
|
+
// each bound to a run once that run's receipt exists and buffering until then. Every function
|
|
415
|
+
// on console is routed into the receipt of the most recent capture that is still open. The real
|
|
416
|
+
// console returns when the last capture releases. Direct writes to a file descriptor and timers
|
|
417
|
+
// that fire after end are outside this net; the README names them as exceptions.
|
|
418
|
+
|
|
419
|
+
type ConsoleFn = (...a: unknown[]) => unknown;
|
|
420
|
+
interface Capture { run: Run | null; pending: { method: string; text: string }[]; released: boolean }
|
|
421
|
+
const active: Capture[] = [];
|
|
422
|
+
let saved: Map<string, ConsoleFn> | null = null;
|
|
423
|
+
|
|
424
|
+
function record(c: Capture, method: string, text: string): void {
|
|
425
|
+
if (c.run === null) { c.pending.push({ method, text }); return; }
|
|
426
|
+
if (c.run.ended) return;
|
|
427
|
+
try { c.run.step("captured console output", `a library called console.${method}; stdout and stderr carry only protocol lines (§1.2), so the text is kept here`, { method, text }); } catch { /* the run ended between the check and the write */ }
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function captureConsole(): { attach: (run: Run) => void; release: () => void } {
|
|
431
|
+
const c: Capture = { run: null, pending: [], released: false };
|
|
432
|
+
active.push(c);
|
|
433
|
+
if (saved === null) {
|
|
434
|
+
saved = new Map();
|
|
435
|
+
const con = console as unknown as Record<string, unknown>;
|
|
436
|
+
for (const key of Object.getOwnPropertyNames(console)) {
|
|
437
|
+
const fn = con[key];
|
|
438
|
+
if (typeof fn !== "function") continue;
|
|
439
|
+
saved.set(key, fn as ConsoleFn);
|
|
440
|
+
con[key] = (...a: unknown[]) => {
|
|
441
|
+
const target = [...active].reverse().find((x) => !x.released && (x.run === null || !x.run.ended));
|
|
442
|
+
if (!target) return;
|
|
443
|
+
record(target, key, a.map((x) => (typeof x === "string" ? x : safeJson(x))).join(" "));
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return {
|
|
448
|
+
attach(run) { c.run = run; for (const p of c.pending) record(c, p.method, p.text); c.pending = []; },
|
|
449
|
+
release() {
|
|
450
|
+
if (c.released) return; c.released = true;
|
|
451
|
+
const i = active.indexOf(c); if (i >= 0) active.splice(i, 1);
|
|
452
|
+
if (active.length === 0 && saved !== null) {
|
|
453
|
+
const con = console as unknown as Record<string, unknown>;
|
|
454
|
+
for (const [key, fn] of saved) con[key] = fn;
|
|
455
|
+
saved = null;
|
|
456
|
+
}
|
|
457
|
+
},
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function safeJson(x: unknown): string { try { return JSON.stringify(x) ?? String(x); } catch { return String(x); } }
|
|
462
|
+
|
|
463
|
+
export type { Bookkeeping };
|
|
@@ -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[]);
|