@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/location.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Where the receipt goes (spec §5, §5.2). The default is `.parley/receipts/<run>.jsonl` under the
|
|
2
|
+
// initial working directory, once hygiene is established; otherwise the XDG state directory keyed
|
|
3
|
+
// by a digest of the repository root; otherwise nothing, which is a startup failure. A location
|
|
4
|
+
// whose path carries a declared secret value is never chosen (§5.3: the path would print it).
|
|
5
|
+
import { closeSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
8
|
+
import { sha256 } from "./inv.ts";
|
|
9
|
+
import { carriesSecret } from "./redact.ts";
|
|
10
|
+
|
|
11
|
+
export interface Bookkeeping { op: "create" | "append" | "delete"; scope: string }
|
|
12
|
+
export interface Location {
|
|
13
|
+
readonly where: "repo" | "state";
|
|
14
|
+
readonly receiptDir: string;
|
|
15
|
+
readonly receiptPath: string;
|
|
16
|
+
readonly fd: number;
|
|
17
|
+
readonly warning?: { code: string; problem: string; remedy: string };
|
|
18
|
+
}
|
|
19
|
+
export interface LocationFailure { readonly code: "startup.receipt_unwritable" | "startup.secret_in_path"; readonly problem: string; readonly remedy: string }
|
|
20
|
+
|
|
21
|
+
export function repoRoot(cwd: string): string {
|
|
22
|
+
let dir = resolve(cwd);
|
|
23
|
+
for (;;) {
|
|
24
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
25
|
+
const parent = dirname(dir);
|
|
26
|
+
if (parent === dir) return resolve(cwd);
|
|
27
|
+
dir = parent;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function stateBase(env: Record<string, string | undefined>, home = homedir()): string {
|
|
32
|
+
const x = env.XDG_STATE_HOME;
|
|
33
|
+
return x && isAbsolute(x) ? x : join(home, ".local", "state");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function stateReceiptDir(cwd: string, env: Record<string, string | undefined>, home?: string): string {
|
|
37
|
+
const key = sha256(realpathSafe(repoRoot(cwd))).slice(0, 16);
|
|
38
|
+
return join(stateBase(env, home), "parley", key, "receipts");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The bookkeeping a run may perform, declared ahead of time in the command line (§4.3). */
|
|
42
|
+
export function bookkeepingFor(cwd: string, env: Record<string, string | undefined>, home?: string): Bookkeeping[] {
|
|
43
|
+
const repo = join(resolve(cwd), ".parley");
|
|
44
|
+
const state = stateReceiptDir(cwd, env, home);
|
|
45
|
+
return [
|
|
46
|
+
{ op: "create", scope: `${join(repo, "receipts")}/` },
|
|
47
|
+
{ op: "create", scope: join(repo, ".gitignore") },
|
|
48
|
+
{ op: "delete", scope: `${join(repo, "receipts")}/` },
|
|
49
|
+
{ op: "create", scope: `${state}/` },
|
|
50
|
+
{ op: "delete", scope: `${state}/` },
|
|
51
|
+
];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Whether a `.gitignore` line is a negation that can match the directory `receipts` beside it.
|
|
56
|
+
* With `*` in force nothing under `receipts/` can be staged unless the directory itself is
|
|
57
|
+
* re-included, because git cannot re-include a file whose parent directory is excluded
|
|
58
|
+
* (gitignore(5)). Conservative: a pattern this cannot evaluate (an inner `/`, a backslash, a
|
|
59
|
+
* class no regex accepts) is taken to match, and the match ignores case, as git does where
|
|
60
|
+
* `core.ignorecase` is set.
|
|
61
|
+
*/
|
|
62
|
+
function negationReachesReceipts(line: string): boolean {
|
|
63
|
+
if (!line.startsWith("!")) return false;
|
|
64
|
+
let pat = line.slice(1).replace(/ +$/, "");
|
|
65
|
+
if (pat.endsWith("/")) pat = pat.slice(0, -1);
|
|
66
|
+
if (pat.startsWith("/")) pat = pat.slice(1);
|
|
67
|
+
while (pat.startsWith("**/")) pat = pat.slice(3);
|
|
68
|
+
if (pat.includes("/") || pat.includes("\\")) return true;
|
|
69
|
+
try { return new RegExp(`^${globRegex(pat)}$`, "i").test("receipts"); } catch { return true; }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** One path component's glob as a regex source: `*` and `**` any run, `?` one character, a bracket a class (`!` or `^` negating it); everything else literal. The caller has already refused a backslash. */
|
|
73
|
+
function globRegex(pat: string): string {
|
|
74
|
+
let out = "";
|
|
75
|
+
for (let i = 0; i < pat.length; i++) {
|
|
76
|
+
const c = pat[i]!;
|
|
77
|
+
if (c === "*") out += ".*";
|
|
78
|
+
else if (c === "?") out += ".";
|
|
79
|
+
else if (c === "[") {
|
|
80
|
+
const j = pat.indexOf("]", i + 2);
|
|
81
|
+
if (j === -1) { out += "\\["; continue; }
|
|
82
|
+
let body = pat.slice(i + 1, j);
|
|
83
|
+
const neg = body.startsWith("!") || body.startsWith("^");
|
|
84
|
+
if (neg) body = body.slice(1);
|
|
85
|
+
out += `[${neg ? "^" : ""}${body.replace(/[\]\\]/g, "\\$&")}]`;
|
|
86
|
+
i = j;
|
|
87
|
+
} else out += c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* §5.2: `.parley/.gitignore` containing `*`, create-if-absent and never overwrite. The file is
|
|
94
|
+
* written whole to a temporary name and linked into place, so no process can read it empty.
|
|
95
|
+
* Null when the file is ours to rely on; otherwise why it is a user's file: no line `*`, or a
|
|
96
|
+
* negation that can re-include `receipts/` (flyingrobots/parley#109).
|
|
97
|
+
*/
|
|
98
|
+
function hygiene(parleyDir: string, nonce: string): string | null {
|
|
99
|
+
mkdirSync(parleyDir, { recursive: true });
|
|
100
|
+
const file = join(parleyDir, ".gitignore");
|
|
101
|
+
if (!existsSync(file)) {
|
|
102
|
+
const tmp = join(parleyDir, `.gitignore.${nonce}.tmp`);
|
|
103
|
+
const fd = openSync(tmp, "wx");
|
|
104
|
+
try { writeSync(fd, "*\n"); } finally { closeSync(fd); }
|
|
105
|
+
try { linkSync(tmp, file); } catch (e) { if ((e as NodeJS.ErrnoException).code !== "EEXIST") { unlinkSafe(tmp); throw e; } } finally { unlinkSafe(tmp); }
|
|
106
|
+
}
|
|
107
|
+
const lines = readFileSync(file, "utf8").split(/\r?\n/);
|
|
108
|
+
if (!lines.includes("*")) return `${file} exists without a line consisting of *`;
|
|
109
|
+
const negation = lines.find(negationReachesReceipts);
|
|
110
|
+
return negation === undefined ? null : `${file} has a line consisting of *, but its negation ${negation} can re-include receipts/, where git add would stage a receipt`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function reserve(receiptDir: string, run: string): { receiptPath: string; fd: number } {
|
|
114
|
+
mkdirSync(receiptDir, { recursive: true });
|
|
115
|
+
const receiptPath = join(receiptDir, `${run}.jsonl`);
|
|
116
|
+
return { receiptPath, fd: openSync(receiptPath, "wx") };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function chooseLocation(opts: { cwd: string; run: string; env: Record<string, string | undefined>; home?: string; secrets?: ReadonlySet<string> }): Location | LocationFailure {
|
|
120
|
+
const cwd = resolve(opts.cwd);
|
|
121
|
+
const secrets = opts.secrets ?? new Set<string>();
|
|
122
|
+
let warning: Location["warning"];
|
|
123
|
+
const repoDir = join(cwd, ".parley", "receipts");
|
|
124
|
+
if (carriesSecret(join(repoDir, `${opts.run}.jsonl`), secrets)) {
|
|
125
|
+
warning = { code: "receipt.relocated", problem: "the receipt path under the working directory would carry a declared secret value, so the receipt went to the state directory", remedy: "run from a directory whose path does not contain the secret, or leave the receipt where it went" };
|
|
126
|
+
} else {
|
|
127
|
+
try {
|
|
128
|
+
const why = hygiene(join(cwd, ".parley"), opts.run);
|
|
129
|
+
if (why === null) return { where: "repo", receiptDir: repoDir, ...reserve(repoDir, opts.run) };
|
|
130
|
+
warning = { code: "receipt.relocated", problem: `${why}, so it is a user's file and was left alone; the receipt went to the state directory`, remedy: "make .parley/.gitignore a line consisting of * with no negation that can match receipts, or leave the receipt where it went" };
|
|
131
|
+
} catch {
|
|
132
|
+
// The working directory is not usable; fall back silently (the bootstrap line says where).
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
let stateDir: string;
|
|
136
|
+
try { stateDir = stateReceiptDir(cwd, opts.env, opts.home); } catch { return unwritable(cwd); }
|
|
137
|
+
if (carriesSecret(join(stateDir, `${opts.run}.jsonl`), secrets)) {
|
|
138
|
+
return { code: "startup.secret_in_path", problem: "every receipt location this writer can choose has a path carrying a declared secret value; no receipt path can be printed without disclosing it", remedy: "set XDG_STATE_HOME to an absolute path that does not contain the secret, or do not pass that value as a declared secret" };
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
return { where: "state", receiptDir: stateDir, ...reserve(stateDir, opts.run), ...(warning ? { warning } : {}) };
|
|
142
|
+
} catch {
|
|
143
|
+
return unwritable(cwd);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function unwritable(cwd: string): LocationFailure {
|
|
148
|
+
return { code: "startup.receipt_unwritable", problem: `No writable receipt location: ${join(cwd, ".parley")} is not usable and the state directory is not writable`, remedy: "make .parley writable or set XDG_STATE_HOME to a writable absolute path" };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function isLocationFailure(l: Location | LocationFailure): l is LocationFailure { return "code" in l; }
|
|
152
|
+
|
|
153
|
+
function realpathSafe(p: string): string { try { return realpathSync(p); } catch { return p; } }
|
|
154
|
+
function unlinkSafe(p: string): void { try { unlinkSync(p); } catch { /* already gone */ } }
|
package/src/redact.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Redaction (spec §5.3). Declared secrets are named in the command description: an argument by
|
|
2
|
+
// its flag, a variable by its name, a credential source by a logical name. Their values are
|
|
3
|
+
// replaced with the literal `[redacted]` in a record's payload before any copy leaves the
|
|
4
|
+
// process, and the head records where. The envelope and the writer's own identifiers are never
|
|
5
|
+
// scrubbed: the writer refuses, at startup, to choose a run id or receipt path that carries a
|
|
6
|
+
// secret (location.ts, tool.ts), so there is nothing in them to replace.
|
|
7
|
+
export const REDACTED = "[redacted]";
|
|
8
|
+
|
|
9
|
+
export interface SecretNames { readonly flags: string[]; readonly env: string[]; readonly sources: string[] }
|
|
10
|
+
|
|
11
|
+
/** A name starting with `-` is a flag; an upper-case identifier is an environment variable; anything else is a logical source. */
|
|
12
|
+
export function classifySecrets(secrets: readonly string[]): SecretNames {
|
|
13
|
+
const flags: string[] = [], env: string[] = [], sources: string[] = [];
|
|
14
|
+
for (const s of new Set(secrets)) {
|
|
15
|
+
if (s.startsWith("-")) flags.push(s);
|
|
16
|
+
else if (/^[A-Z_][A-Z0-9_]*$/.test(s)) env.push(s);
|
|
17
|
+
else sources.push(s);
|
|
18
|
+
}
|
|
19
|
+
return { flags, env, sources };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The secret values an invocation carries: declared flag values from argv and declared variables from the environment. Empty values are supplied but carry nothing to replace. */
|
|
23
|
+
export function collectSecretValues(argv: readonly string[], names: SecretNames, env: Record<string, string | undefined>): Set<string> {
|
|
24
|
+
const values = new Set<string>();
|
|
25
|
+
for (let i = 0; i < argv.length; i++) {
|
|
26
|
+
const a = argv[i]!;
|
|
27
|
+
for (const flag of names.flags) {
|
|
28
|
+
if (a === flag && i + 1 < argv.length) values.add(argv[i + 1]!);
|
|
29
|
+
else if (a.startsWith(flag + "=")) values.add(a.slice(flag.length + 1));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
for (const name of names.env) { const v = env[name]; if (v !== undefined) values.add(v); }
|
|
33
|
+
values.delete("");
|
|
34
|
+
return values;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Longest value first, so a secret that contains another is replaced whole rather than leaving its tail behind. */
|
|
38
|
+
function ordered(values: ReadonlySet<string>): string[] { return [...values].sort((a, b) => b.length - a.length); }
|
|
39
|
+
|
|
40
|
+
export function replaceSecrets(s: string, values: ReadonlySet<string>): string {
|
|
41
|
+
let out = s;
|
|
42
|
+
for (const v of ordered(values)) if (out.includes(v)) out = out.split(v).join(REDACTED);
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** True when any secret value occurs inside `s`, which disqualifies `s` as a writer-chosen identifier. */
|
|
47
|
+
export function carriesSecret(s: string, values: ReadonlySet<string>): boolean {
|
|
48
|
+
for (const v of values) if (s.includes(v)) return true;
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The raw argv after §5.3: the element after a declared flag becomes `[redacted]` even when
|
|
54
|
+
* empty (it was supplied), `--name=value` keeps its flag, and a secret inside any other element
|
|
55
|
+
* is replaced within it.
|
|
56
|
+
*/
|
|
57
|
+
export function redactArgv(argv: readonly string[], values: ReadonlySet<string>, flags: readonly string[] = []): { argv: string[]; indexes: number[] } {
|
|
58
|
+
const out = argv.map((a) => replaceSecrets(a, values));
|
|
59
|
+
const changed = new Set<number>();
|
|
60
|
+
out.forEach((a, i) => { if (a !== argv[i]) changed.add(i); });
|
|
61
|
+
for (let i = 0; i < argv.length; i++) {
|
|
62
|
+
for (const flag of flags) {
|
|
63
|
+
if (argv[i] === flag && i + 1 < argv.length) { out[i + 1] = REDACTED; changed.add(i + 1); }
|
|
64
|
+
else if (argv[i]!.startsWith(flag + "=")) { out[i] = flag + "=" + REDACTED; changed.add(i); }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { argv: out, indexes: [...changed].sort((a, b) => a - b) };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function escapePointer(key: string): string { return key.replace(/~/g, "~0").replace(/\//g, "~1"); }
|
|
71
|
+
|
|
72
|
+
export interface ScrubOptions {
|
|
73
|
+
/** Keys whose string values are never scrubbed: writer digests, which a secret cannot occur in except by coincidence of hex. */
|
|
74
|
+
readonly skipKeys?: ReadonlySet<string>;
|
|
75
|
+
/** Scrub numbers, booleans and bigints whose decimal form is a secret (default true). A writer-built record passes false: its scalars (`status`, `dry_run`, `network`, `in`) are the writer's own and never a secret. */
|
|
76
|
+
readonly scalars?: boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* A deep copy of `value` with every secret replaced, and the RFC 6901 pointer of each place that
|
|
81
|
+
* changed. Strings are replaced within; a number, boolean or bigint whose decimal form is a
|
|
82
|
+
* secret becomes the string `[redacted]` (a PIN parsed to a number is still the PIN); an object
|
|
83
|
+
* key that carries a secret is renamed, and the pointer recorded is the renamed key's.
|
|
84
|
+
*/
|
|
85
|
+
export function scrub(value: unknown, values: ReadonlySet<string>, pointer = "", found: string[] = [], opts: ScrubOptions = {}): unknown {
|
|
86
|
+
if (values.size === 0) return value;
|
|
87
|
+
if (typeof value === "string") {
|
|
88
|
+
const r = replaceSecrets(value, values);
|
|
89
|
+
if (r !== value) found.push(pointer || "/");
|
|
90
|
+
return r;
|
|
91
|
+
}
|
|
92
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
93
|
+
if (opts.scalars !== false && values.has(String(value))) { found.push(pointer || "/"); return REDACTED; }
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
if (Array.isArray(value)) return value.map((v, i) => scrub(v, values, `${pointer}/${i}`, found, opts));
|
|
97
|
+
if (value && typeof value === "object") {
|
|
98
|
+
const out: Record<string, unknown> = {};
|
|
99
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
100
|
+
const key = replaceSecrets(k, values);
|
|
101
|
+
const p = `${pointer}/${escapePointer(key)}`;
|
|
102
|
+
if (key !== k) found.push(p);
|
|
103
|
+
out[key] = opts.skipKeys?.has(k) && typeof v === "string" ? v : scrub(v, values, p, found, opts);
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
return value;
|
|
108
|
+
}
|
package/src/refusal.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// A history transform's typed refusal (flyingrobots/parley#60).
|
|
2
|
+
//
|
|
3
|
+
// flyingrobots/parley#57 gave a transform two answers: a record to put on the stream, or nothing
|
|
4
|
+
// to withhold the line. "Nothing" is a gap with no reason attached, which is right when the
|
|
5
|
+
// configuration is "the shared timeline does not carry step detail" and wrong when the reason is
|
|
6
|
+
// the point — a line withheld because it looks like it carries a credential has to say so, under
|
|
7
|
+
// a code a reader can match on.
|
|
8
|
+
//
|
|
9
|
+
// So there is a third answer: a refusal. It is a value rather than a throw, because a throw
|
|
10
|
+
// already means something else in #57's contract (`history.transform_failed`: the transform is
|
|
11
|
+
// broken), and because a value composes — a wrapping transform can read a refusal and pass it on
|
|
12
|
+
// without an exception handler.
|
|
13
|
+
//
|
|
14
|
+
// The code is the transform's; everything else stays the writer's. The writer still reattaches
|
|
15
|
+
// the envelope it owns, still leaves the exit status alone, still refuses a code that is not a
|
|
16
|
+
// code (spec §6) and still refuses one carrying a declared secret value, because a diagnostic's
|
|
17
|
+
// `code` is the one string redaction does not touch (§5.3).
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The brand, registered globally rather than module-locally, so a refusal built by one copy of
|
|
21
|
+
* this package is recognised by another. `instanceof` across two copies of a class is not.
|
|
22
|
+
*/
|
|
23
|
+
const REFUSAL = Symbol.for("parley.history.refusal");
|
|
24
|
+
|
|
25
|
+
/** Spec §6's shape for a `code`: two or more dot-separated lowercase segments, never a sentence. */
|
|
26
|
+
const CODE_SHAPE = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* What a transform returns to withhold a line *and say why*. The writer raises one `warning`
|
|
30
|
+
* carrying this `code`, `problem` and `remedy`, names nothing else, and leaves the exit status
|
|
31
|
+
* where it was (§6.1).
|
|
32
|
+
*/
|
|
33
|
+
export interface HistoryRefusal {
|
|
34
|
+
readonly [REFUSAL]: true;
|
|
35
|
+
readonly code: string;
|
|
36
|
+
readonly problem: string;
|
|
37
|
+
readonly remedy?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Withhold this line under a code of your own. `code` is spec §6's shape and `problem` is one
|
|
42
|
+
* non-empty sentence; both are checked here so a transform author sees the mistake at the point
|
|
43
|
+
* they made it rather than as a withheld line with no warning.
|
|
44
|
+
*/
|
|
45
|
+
export function refuse(code: string, problem: string, remedy?: string): HistoryRefusal {
|
|
46
|
+
if (!CODE_SHAPE.test(code)) throw new TypeError(`a refusal's code is two or more dot-separated lowercase segments (spec §6), not ${JSON.stringify(code)}`);
|
|
47
|
+
if (problem === "") throw new TypeError("a refusal's problem is never empty (spec §6)");
|
|
48
|
+
return Object.freeze({ [REFUSAL]: true as const, code, problem, ...(remedy === undefined ? {} : { remedy }) });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Whether a transform's return value is a refusal rather than a record to project. */
|
|
52
|
+
export function isHistoryRefusal(value: unknown): value is HistoryRefusal {
|
|
53
|
+
return typeof value === "object" && value !== null && (value as Record<symbol, unknown>)[REFUSAL] === true;
|
|
54
|
+
}
|