@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.
@@ -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
+ }
package/src/ulid.ts ADDED
@@ -0,0 +1,13 @@
1
+ // A ULID: 10 characters of millisecond time and 16 of randomness, Crockford base32, so run ids
2
+ // sort lexicographically by creation time (spec §2.1).
3
+ const ENC = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
4
+
5
+ export function ulid(time: number = Date.now()): string {
6
+ let t = Math.max(0, Math.floor(time));
7
+ let head = "";
8
+ for (let i = 0; i < 10; i++) { head = ENC[t % 32] + head; t = Math.floor(t / 32); }
9
+ const rnd = crypto.getRandomValues(new Uint8Array(16));
10
+ let tail = "";
11
+ for (let i = 0; i < 16; i++) tail += ENC[rnd[i]! & 31];
12
+ return head + tail;
13
+ }