@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/check.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// A bounded JSON Schema (draft 2020-12) checker, written for exactly one job: re-validating the
|
|
2
|
+
// record a history transform returned against the schema for its exact advertised pair (§4.5),
|
|
3
|
+
// inside a package that has no runtime dependencies. It is not a general validator and does not
|
|
4
|
+
// pretend to be one.
|
|
5
|
+
//
|
|
6
|
+
// The honest part is the boundary. It implements the constructs the protocol's own schemas use
|
|
7
|
+
// and **says so** when a schema uses one it does not, rather than ignoring the keyword and
|
|
8
|
+
// reporting a line as checked that was not. A caller that cannot verify a line can then refuse
|
|
9
|
+
// it. `test/parley-emit.test.ts` asserts every schema this package ships is inside the subset,
|
|
10
|
+
// so a new draft that reaches for `$ref` fails a test here rather than silently going unchecked.
|
|
11
|
+
|
|
12
|
+
/** The keywords that carry no assertion; present for readers and ignored here. */
|
|
13
|
+
const ANNOTATIONS = new Set(["$schema", "$id", "$anchor", "$comment", "title", "description", "examples", "default", "deprecated", "readOnly", "writeOnly"]);
|
|
14
|
+
/** Everything this checker understands. A keyword outside it is reported, never ignored. */
|
|
15
|
+
const SUPPORTED = new Set([
|
|
16
|
+
...ANNOTATIONS,
|
|
17
|
+
"type", "const", "enum", "required", "properties", "additionalProperties", "items",
|
|
18
|
+
"minItems", "maxItems", "minLength", "maxLength", "minimum", "maximum",
|
|
19
|
+
"exclusiveMinimum", "exclusiveMaximum", "minProperties", "maxProperties",
|
|
20
|
+
"pattern", "format", "not", "anyOf", "allOf", "oneOf", "if", "then", "else",
|
|
21
|
+
]);
|
|
22
|
+
/** The formats this checker asserts. Any other is reported as unsupported, not waved through. */
|
|
23
|
+
const FORMATS: Record<string, RegExp> = {
|
|
24
|
+
// RFC 6901, as ajv-formats asserts it: empty, or one or more escaped segments.
|
|
25
|
+
"json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/u,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The first construct in `schema` this checker does not implement, or `null` when the whole
|
|
30
|
+
* document is inside the subset. This is a property of the schema and not of any one record, so
|
|
31
|
+
* it is checked **before** a value is walked: a keyword nested under a property the record does
|
|
32
|
+
* not happen to carry would otherwise go unnoticed, and "we checked the parts we understood" is
|
|
33
|
+
* exactly the claim this file exists not to make. Memoised per document.
|
|
34
|
+
*/
|
|
35
|
+
export function schemaSubsetGap(schema: unknown): string | null {
|
|
36
|
+
if (typeof schema !== "object" || schema === null) return walkSchema(schema);
|
|
37
|
+
const cached = gaps.get(schema as object);
|
|
38
|
+
if (cached !== undefined) return cached;
|
|
39
|
+
const gap = walkSchema(schema);
|
|
40
|
+
gaps.set(schema as object, gap);
|
|
41
|
+
return gap;
|
|
42
|
+
}
|
|
43
|
+
const gaps = new WeakMap<object, string | null>();
|
|
44
|
+
|
|
45
|
+
const SUBSCHEMA = ["items", "not", "if", "then", "else", "additionalProperties"] as const;
|
|
46
|
+
const SUBSCHEMA_LISTS = ["anyOf", "allOf", "oneOf"] as const;
|
|
47
|
+
|
|
48
|
+
function walkSchema(node: unknown): string | null {
|
|
49
|
+
if (node === true || node === false || node === undefined) return null;
|
|
50
|
+
if (typeof node !== "object" || node === null || Array.isArray(node)) return "a schema that is not an object or a boolean";
|
|
51
|
+
const s = node as Record<string, unknown>;
|
|
52
|
+
for (const k of Object.keys(s)) {
|
|
53
|
+
if (!SUPPORTED.has(k)) return k;
|
|
54
|
+
if (k === "format" && !Object.hasOwn(FORMATS, String(s[k]))) return `format ${String(s[k])}`;
|
|
55
|
+
}
|
|
56
|
+
if (Array.isArray(s.items)) return "items as a tuple";
|
|
57
|
+
for (const k of SUBSCHEMA) { const gap = walkSchema(s[k]); if (gap !== null) return gap; }
|
|
58
|
+
for (const k of SUBSCHEMA_LISTS) {
|
|
59
|
+
if (!Array.isArray(s[k])) continue;
|
|
60
|
+
for (const sub of s[k] as unknown[]) { const gap = walkSchema(sub); if (gap !== null) return gap; }
|
|
61
|
+
}
|
|
62
|
+
if (s.properties !== null && typeof s.properties === "object" && !Array.isArray(s.properties)) {
|
|
63
|
+
for (const sub of Object.values(s.properties as Record<string, unknown>)) { const gap = walkSchema(sub); if (gap !== null) return gap; }
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type CheckResult =
|
|
69
|
+
/** The record satisfies the schema. */
|
|
70
|
+
| { readonly ok: true }
|
|
71
|
+
/** The record does not satisfy it; `errors` names where, shortest path first. */
|
|
72
|
+
| { readonly ok: false; readonly errors: readonly string[] }
|
|
73
|
+
/** The schema uses a construct this checker does not implement, so nothing was established. */
|
|
74
|
+
| { readonly ok: false; readonly errors: readonly string[]; readonly unsupported: string };
|
|
75
|
+
|
|
76
|
+
/** The same refusal, raised from inside the walk of a value as a guard of last resort. */
|
|
77
|
+
class Unsupported extends Error {
|
|
78
|
+
constructor(readonly keyword: string) { super(`the schema uses ${keyword}, which this checker does not implement`); }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Check `value` against `schema`. Returns `ok` when it satisfies it, an error list when it does
|
|
83
|
+
* not, and an `unsupported` keyword when the schema is outside the subset — in which case the
|
|
84
|
+
* result establishes nothing either way, and a caller that must not guess should refuse.
|
|
85
|
+
*/
|
|
86
|
+
export function checkRecord(value: unknown, schema: unknown): CheckResult {
|
|
87
|
+
const gap = schemaSubsetGap(schema);
|
|
88
|
+
if (gap !== null) return { ok: false, errors: [`the schema uses ${gap}, which this checker does not implement`], unsupported: gap };
|
|
89
|
+
const errors: string[] = [];
|
|
90
|
+
try { validate(schema, value, "", errors); }
|
|
91
|
+
catch (e) {
|
|
92
|
+
if (e instanceof Unsupported) return { ok: false, errors: [e.message], unsupported: e.keyword };
|
|
93
|
+
throw e;
|
|
94
|
+
}
|
|
95
|
+
return errors.length === 0 ? { ok: true } : { ok: false, errors };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function at(path: string): string { return path === "" ? "/" : path; }
|
|
99
|
+
|
|
100
|
+
function kindOf(v: unknown): string {
|
|
101
|
+
if (v === null) return "null";
|
|
102
|
+
if (Array.isArray(v)) return "array";
|
|
103
|
+
const t = typeof v;
|
|
104
|
+
return t === "number" ? (Number.isInteger(v as number) ? "integer" : "number") : t;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function isType(v: unknown, t: string): boolean {
|
|
108
|
+
if (t === "number") return typeof v === "number" && Number.isFinite(v);
|
|
109
|
+
if (t === "integer") return typeof v === "number" && Number.isInteger(v);
|
|
110
|
+
return kindOf(v) === t;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function same(a: unknown, b: unknown): boolean {
|
|
114
|
+
if (a === b) return true;
|
|
115
|
+
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
|
|
116
|
+
if (a && b && typeof a === "object" && typeof b === "object" && !Array.isArray(a) && !Array.isArray(b)) {
|
|
117
|
+
const ka = Object.keys(a as object), kb = Object.keys(b as object);
|
|
118
|
+
return ka.length === kb.length && ka.every((k) => Object.hasOwn(b as object, k) && same((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]));
|
|
119
|
+
}
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function satisfies(schema: unknown, value: unknown): boolean {
|
|
124
|
+
const scratch: string[] = [];
|
|
125
|
+
validate(schema, value, "", scratch);
|
|
126
|
+
return scratch.length === 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function regex(pattern: string): RegExp {
|
|
130
|
+
try { return new RegExp(pattern, "u"); } catch { return new RegExp(pattern); }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function validate(schema: unknown, value: unknown, path: string, errors: string[]): void {
|
|
134
|
+
if (schema === true || schema === undefined) return;
|
|
135
|
+
if (schema === false) { errors.push(`${at(path)} is not allowed here`); return; }
|
|
136
|
+
if (typeof schema !== "object" || Array.isArray(schema)) throw new Unsupported("a schema that is not an object or a boolean");
|
|
137
|
+
const s = schema as Record<string, unknown>;
|
|
138
|
+
for (const k of Object.keys(s)) if (!SUPPORTED.has(k)) throw new Unsupported(k);
|
|
139
|
+
|
|
140
|
+
if (s.type !== undefined) {
|
|
141
|
+
const types = Array.isArray(s.type) ? (s.type as string[]) : [s.type as string];
|
|
142
|
+
if (!types.some((t) => isType(value, t))) errors.push(`${at(path)} is ${kindOf(value)}, not ${types.join(" or ")}`);
|
|
143
|
+
}
|
|
144
|
+
if (s.const !== undefined && !same(value, s.const)) errors.push(`${at(path)} must be ${JSON.stringify(s.const)}`);
|
|
145
|
+
if (s.enum !== undefined) {
|
|
146
|
+
const options = s.enum as unknown[];
|
|
147
|
+
if (!options.some((o) => same(value, o))) errors.push(`${at(path)} must be one of ${JSON.stringify(options)}`);
|
|
148
|
+
}
|
|
149
|
+
if (s.not !== undefined && satisfies(s.not, value)) errors.push(`${at(path)} must not match the excluded shape`);
|
|
150
|
+
if (s.allOf !== undefined) for (const sub of s.allOf as unknown[]) validate(sub, value, path, errors);
|
|
151
|
+
if (s.anyOf !== undefined && !(s.anyOf as unknown[]).some((sub) => satisfies(sub, value))) errors.push(`${at(path)} matches none of the allowed shapes`);
|
|
152
|
+
if (s.oneOf !== undefined && (s.oneOf as unknown[]).filter((sub) => satisfies(sub, value)).length !== 1) errors.push(`${at(path)} must match exactly one of the allowed shapes`);
|
|
153
|
+
if (s.if !== undefined) {
|
|
154
|
+
const branch = satisfies(s.if, value) ? s.then : s.else;
|
|
155
|
+
if (branch !== undefined) validate(branch, value, path, errors);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (typeof value === "string") {
|
|
159
|
+
if (typeof s.minLength === "number" && [...value].length < s.minLength) errors.push(`${at(path)} is shorter than ${s.minLength}`);
|
|
160
|
+
if (typeof s.maxLength === "number" && [...value].length > s.maxLength) errors.push(`${at(path)} is longer than ${s.maxLength}`);
|
|
161
|
+
if (typeof s.pattern === "string" && !regex(s.pattern).test(value)) errors.push(`${at(path)} does not match ${s.pattern}`);
|
|
162
|
+
if (typeof s.format === "string") {
|
|
163
|
+
const f = FORMATS[s.format];
|
|
164
|
+
if (f === undefined) throw new Unsupported(`format ${s.format}`);
|
|
165
|
+
if (!f.test(value)) errors.push(`${at(path)} is not a ${s.format}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (typeof value === "number") {
|
|
170
|
+
if (typeof s.minimum === "number" && value < s.minimum) errors.push(`${at(path)} is below ${s.minimum}`);
|
|
171
|
+
if (typeof s.maximum === "number" && value > s.maximum) errors.push(`${at(path)} is above ${s.maximum}`);
|
|
172
|
+
if (typeof s.exclusiveMinimum === "number" && value <= s.exclusiveMinimum) errors.push(`${at(path)} is not above ${s.exclusiveMinimum}`);
|
|
173
|
+
if (typeof s.exclusiveMaximum === "number" && value >= s.exclusiveMaximum) errors.push(`${at(path)} is not below ${s.exclusiveMaximum}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (Array.isArray(value)) {
|
|
177
|
+
if (typeof s.minItems === "number" && value.length < s.minItems) errors.push(`${at(path)} has fewer than ${s.minItems} items`);
|
|
178
|
+
if (typeof s.maxItems === "number" && value.length > s.maxItems) errors.push(`${at(path)} has more than ${s.maxItems} items`);
|
|
179
|
+
if (s.items !== undefined) {
|
|
180
|
+
if (Array.isArray(s.items)) throw new Unsupported("items as a tuple");
|
|
181
|
+
value.forEach((item, i) => validate(s.items, item, `${path}/${i}`, errors));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
186
|
+
const obj = value as Record<string, unknown>;
|
|
187
|
+
const keys = Object.keys(obj);
|
|
188
|
+
if (Array.isArray(s.required)) for (const k of s.required as string[]) if (!Object.hasOwn(obj, k)) errors.push(`${at(path)} is missing ${k}`);
|
|
189
|
+
if (typeof s.minProperties === "number" && keys.length < s.minProperties) errors.push(`${at(path)} has fewer than ${s.minProperties} properties`);
|
|
190
|
+
if (typeof s.maxProperties === "number" && keys.length > s.maxProperties) errors.push(`${at(path)} has more than ${s.maxProperties} properties`);
|
|
191
|
+
const properties = (s.properties ?? {}) as Record<string, unknown>;
|
|
192
|
+
for (const k of keys) {
|
|
193
|
+
if (Object.hasOwn(properties, k)) { validate(properties[k], obj[k], `${path}/${k}`, errors); continue; }
|
|
194
|
+
if (s.additionalProperties === false) errors.push(`${at(path)} must not carry ${k}`);
|
|
195
|
+
else if (s.additionalProperties !== undefined && s.additionalProperties !== true) validate(s.additionalProperties, obj[k], `${path}/${k}`, errors);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
package/src/history.ts
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// The shared history stream (spec §8, informative). An opt-in second sink that receives the
|
|
2
|
+
// bytes of the local receipt, so a caller gets one timeline across tools, repositories, agents
|
|
3
|
+
// and people. The dependency runs one way: the stream consumes the format and the format never
|
|
4
|
+
// requires the stream, so nothing here can change what a run with no stream configured emits,
|
|
5
|
+
// and a stream that cannot be written is a warning rather than a failure.
|
|
6
|
+
//
|
|
7
|
+
// Scope and expiry (the decision flyingrobots/parley#3 left open): one stream per user per
|
|
8
|
+
// machine, written as dated daily segments, keeping `days` of them. Expiry deletes whole
|
|
9
|
+
// segments, because the stream is append-only with concurrent writers and rewriting a live
|
|
10
|
+
// append-only file to expire a record is the one operation that cannot be made safe. With
|
|
11
|
+
// `days >= 1` today's segment is never a candidate and the newest deletable one is already
|
|
12
|
+
// `days` days old, so no run is holding it open.
|
|
13
|
+
//
|
|
14
|
+
// Redaction (the other decision): none of its own. The sink is handed the same string the
|
|
15
|
+
// receipt was handed, after §5.3 has replaced every declared secret, so a credential cannot
|
|
16
|
+
// reach the stream unless it reached the receipt first. What is left to protect is reach rather
|
|
17
|
+
// than content, so the directory is owner-only, segments are owner-only, a record stored as a
|
|
18
|
+
// sidecar reaches the stream as its `sidecar` event and never as its stored bytes, and nothing
|
|
19
|
+
// is sent anywhere.
|
|
20
|
+
import { closeSync, mkdirSync, openSync, readdirSync, statSync, unlinkSync, writeSync } from "node:fs";
|
|
21
|
+
import { isAbsolute, join } from "node:path";
|
|
22
|
+
import { sha256 } from "./inv.ts";
|
|
23
|
+
import { stateBase } from "./location.ts";
|
|
24
|
+
import { carriesSecret } from "./redact.ts";
|
|
25
|
+
import type { HistoryRefusal } from "./refusal.ts";
|
|
26
|
+
|
|
27
|
+
/** The directory the stream lives in, or an off switch. Absolute when it names a directory. */
|
|
28
|
+
export const HISTORY_ENV = "PARLEY_HISTORY";
|
|
29
|
+
/** How many daily segments to keep, today's included. */
|
|
30
|
+
export const HISTORY_DAYS_ENV = "PARLEY_HISTORY_DAYS";
|
|
31
|
+
export const HISTORY_DEFAULT_DAYS = 14;
|
|
32
|
+
/** A century of daily segments. Beyond this the window's own start date stops being representable. */
|
|
33
|
+
export const HISTORY_MAX_DAYS = 36_500;
|
|
34
|
+
const DIR_MODE = 0o700;
|
|
35
|
+
const FILE_MODE = 0o600;
|
|
36
|
+
const OFF = new Set(["0", "off", "false", "no", "none"]);
|
|
37
|
+
const SEGMENT = /^\d{4}-\d{2}-\d{2}\.jsonl$/;
|
|
38
|
+
const DAY_MS = 86_400_000;
|
|
39
|
+
|
|
40
|
+
export interface HistoryPlan {
|
|
41
|
+
readonly dir: string;
|
|
42
|
+
readonly path: string;
|
|
43
|
+
readonly days: number;
|
|
44
|
+
/** `env` when `PARLEY_HISTORY` named the directory, `state` when the known state path exists. */
|
|
45
|
+
readonly source: "env" | "state";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface HistorySink {
|
|
49
|
+
readonly dir: string;
|
|
50
|
+
readonly path: string;
|
|
51
|
+
/**
|
|
52
|
+
* Append one whole line, newline included, in a single write. Throws the first time the append
|
|
53
|
+
* does not land; the sink is then closed and every later append is a no-op, so one failure is
|
|
54
|
+
* reported once and the run carries on.
|
|
55
|
+
*/
|
|
56
|
+
append(line: string): void;
|
|
57
|
+
close(): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A user-defined projection of one record for the stream copy (flyingrobots#57). It is handed the
|
|
62
|
+
* parsed record the receipt already holds, after §5.3 has replaced every declared secret, and
|
|
63
|
+
* returns a record to put on the stream, nothing to withhold the line, or a `refuse(...)` to
|
|
64
|
+
* withhold it under a code of its own (flyingrobots#60). The envelope is not its to change: the
|
|
65
|
+
* writer reattaches `event`, `t`, `seq`, `run` and `_schema` afterwards and re-validates the
|
|
66
|
+
* returned body against the schema for that exact pair.
|
|
67
|
+
*/
|
|
68
|
+
export type HistoryTransform = (record: Record<string, unknown>) => Record<string, unknown> | HistoryRefusal | undefined | null | void;
|
|
69
|
+
|
|
70
|
+
/** `MainOptions.history` in its long form: the sink, the transform, and what to call it. */
|
|
71
|
+
export interface HistoryConfig {
|
|
72
|
+
/** A sink to use instead of resolving one from the environment; `null` is no stream at all. */
|
|
73
|
+
readonly sink?: HistorySink | null;
|
|
74
|
+
/** The projection applied to the stream copy, and to nothing else. */
|
|
75
|
+
readonly transform?: HistoryTransform;
|
|
76
|
+
/** What the transform is called on the stream; its function name by default. */
|
|
77
|
+
readonly name?: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** What the stream copy's opening line says about the projection that wrote it. */
|
|
81
|
+
export interface HistoryProjection {
|
|
82
|
+
readonly name: string;
|
|
83
|
+
readonly sha256: string;
|
|
84
|
+
readonly fn: HistoryTransform;
|
|
85
|
+
/** Schema documents by `id@version`: this package's drafts and the tool's own declared types. */
|
|
86
|
+
readonly schemas: ReadonlyMap<string, Record<string, unknown>>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The digest the stream names a projection by: SHA-256, hex, of the transform's source text as
|
|
91
|
+
* the runtime renders it (`fn.toString()`). That is honestly what it is — a digest of rendered
|
|
92
|
+
* source, not of a build — and it is enough to tell two projections apart and to pin which one
|
|
93
|
+
* wrote a copy. A function closing over different values has the same source and the same digest;
|
|
94
|
+
* name the configuration, not only the function, when that distinction matters.
|
|
95
|
+
*/
|
|
96
|
+
export function transformDigest(fn: HistoryTransform): string { return sha256(fn.toString()); }
|
|
97
|
+
|
|
98
|
+
/** The transform's name: what the configuration called it, else the function's own name. */
|
|
99
|
+
export function transformName(fn: HistoryTransform, given?: string): string {
|
|
100
|
+
const n = (given ?? fn.name ?? "").trim();
|
|
101
|
+
return n === "" ? "anonymous" : n;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function historyProjection(cfg: { transform: HistoryTransform; name?: string }, schemas: ReadonlyMap<string, Record<string, unknown>>): HistoryProjection {
|
|
105
|
+
return { name: transformName(cfg.transform, cfg.name), sha256: transformDigest(cfg.transform), fn: cfg.transform, schemas };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Whether `MainOptions.history` was given a sink or the long form. */
|
|
109
|
+
export function isHistorySink(h: HistorySink | HistoryConfig): h is HistorySink {
|
|
110
|
+
return typeof (h as HistorySink).append === "function";
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface HistoryFailure { readonly code: "history.unavailable"; readonly problem: string; readonly remedy: string }
|
|
114
|
+
|
|
115
|
+
export function isHistoryFailure(h: HistorySink | HistoryFailure): h is HistoryFailure { return "code" in h; }
|
|
116
|
+
|
|
117
|
+
/** The segment a run started at `t` writes to: the UTC date, so one day is one file everywhere. */
|
|
118
|
+
export function segmentName(t: number): string { return `${new Date(t).toISOString().slice(0, 10)}.jsonl`; }
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* `PARLEY_HISTORY_DAYS` as an integer from 1 to `HISTORY_MAX_DAYS`; anything else, including a
|
|
122
|
+
* window so wide that the date it names is not a date, is the default. A retention window is not
|
|
123
|
+
* worth failing a run over, and an unrepresentable one would throw where nothing can catch it.
|
|
124
|
+
*/
|
|
125
|
+
export function historyDays(env: Record<string, string | undefined>): number {
|
|
126
|
+
const raw = env[HISTORY_DAYS_ENV];
|
|
127
|
+
if (raw === undefined) return HISTORY_DEFAULT_DAYS;
|
|
128
|
+
const n = Number(raw.trim());
|
|
129
|
+
return Number.isInteger(n) && n >= 1 && n <= HISTORY_MAX_DAYS ? n : HISTORY_DEFAULT_DAYS;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Where the stream is, or `null` when none is configured. `PARLEY_HISTORY` names the directory
|
|
134
|
+
* and is created if absent; an off value (`0`, `off`, `false`, `no`, `none`, empty) switches the
|
|
135
|
+
* stream off even when the state directory exists. With the variable unset, the known state path
|
|
136
|
+
* `$XDG_STATE_HOME/parley/history` is used when it already exists, so the stream is opted into by
|
|
137
|
+
* creating that directory once and never by surprise.
|
|
138
|
+
*/
|
|
139
|
+
export function resolveHistory(env: Record<string, string | undefined>, home: string | undefined, t: number): HistoryPlan | null {
|
|
140
|
+
const days = historyDays(env);
|
|
141
|
+
const raw = env[HISTORY_ENV];
|
|
142
|
+
if (raw !== undefined) {
|
|
143
|
+
const trimmed = raw.trim();
|
|
144
|
+
if (trimmed === "" || OFF.has(trimmed.toLowerCase())) return null;
|
|
145
|
+
return { dir: trimmed, path: join(trimmed, segmentName(t)), days, source: "env" };
|
|
146
|
+
}
|
|
147
|
+
let dir: string;
|
|
148
|
+
try { dir = join(stateBase(env, home), "parley", "history"); } catch { return null; }
|
|
149
|
+
try { if (!statSync(dir).isDirectory()) return null; } catch { return null; }
|
|
150
|
+
return { dir, path: join(dir, segmentName(t)), days, source: "state" };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Open the segment for appending, creating the directory owner-only when the environment named
|
|
155
|
+
* it. A failure is described rather than thrown: the caller warns and the run proceeds without a
|
|
156
|
+
* stream (§8 is informative and opt-in; nothing may depend on it).
|
|
157
|
+
*/
|
|
158
|
+
export function openHistory(plan: HistoryPlan, secrets: ReadonlySet<string> = new Set()): HistorySink | HistoryFailure {
|
|
159
|
+
// §5.3, as for the receipt path: a path the bootstrap line cannot print without disclosing a
|
|
160
|
+
// declared secret is never chosen. The receipt has nowhere else to go and fails startup; the
|
|
161
|
+
// stream is optional, so it yields and the run carries on without one. The field name is
|
|
162
|
+
// checked too, since a secret that is a substring of it would rename the key the line prints.
|
|
163
|
+
if (carriesSecret(plan.path, secrets) || carriesSecret("history", secrets)) {
|
|
164
|
+
return { code: "history.unavailable", problem: `the shared history stream's path or field name would carry a declared secret value, so no stream was used; the receipt is unaffected`, remedy: `point ${HISTORY_ENV} at a path that does not contain the secret, or do not pass that value as a declared secret` };
|
|
165
|
+
}
|
|
166
|
+
if (!isAbsolute(plan.dir)) {
|
|
167
|
+
return { code: "history.unavailable", problem: `${HISTORY_ENV} is ${JSON.stringify(plan.dir)}, which is not an absolute path, so no shared history stream was written`, remedy: `set ${HISTORY_ENV} to an absolute directory path, or unset it to use $XDG_STATE_HOME/parley/history` };
|
|
168
|
+
}
|
|
169
|
+
let fd: number;
|
|
170
|
+
try {
|
|
171
|
+
if (plan.source === "env") mkdirSync(plan.dir, { recursive: true, mode: DIR_MODE });
|
|
172
|
+
fd = openSync(plan.path, "a", FILE_MODE);
|
|
173
|
+
} catch (e) {
|
|
174
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
175
|
+
return { code: "history.unavailable", problem: `the shared history stream at ${plan.path} could not be opened: ${msg}; this run wrote its receipt and nothing else`, remedy: `make the directory writable, point ${HISTORY_ENV} somewhere writable, or set ${HISTORY_ENV}=off` };
|
|
176
|
+
}
|
|
177
|
+
let open = true;
|
|
178
|
+
return {
|
|
179
|
+
dir: plan.dir,
|
|
180
|
+
path: plan.path,
|
|
181
|
+
append(line) {
|
|
182
|
+
if (!open) return;
|
|
183
|
+
try { writeWholeLine(fd, line); }
|
|
184
|
+
catch (e) { open = false; try { closeSync(fd); } catch { /* already gone */ } throw e; }
|
|
185
|
+
},
|
|
186
|
+
close() { if (!open) return; open = false; try { closeSync(fd); } catch { /* already gone */ } },
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* One line, one write. The file is opened `O_APPEND`, so a single write of a whole line is
|
|
192
|
+
* ordered against every other writer's whole-line write and the line cannot be split by them.
|
|
193
|
+
* A write that reports fewer bytes is abandoned rather than continued: continuing would let
|
|
194
|
+
* another writer's append land in the middle of this line, which is the failure mode worth
|
|
195
|
+
* designing out. The caller then reports one failure and stops using the stream.
|
|
196
|
+
*/
|
|
197
|
+
export function writeWholeLine(fd: number, line: string, write: (fd: number, b: Uint8Array) => number = writeSync): number {
|
|
198
|
+
const buf = Buffer.from(line, "utf8");
|
|
199
|
+
const n = write(fd, buf);
|
|
200
|
+
if (n !== buf.length) throw new Error(`the append was truncated at ${n} of ${buf.length} bytes and was not continued, because continuing would interleave with another writer`);
|
|
201
|
+
return n;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* §5.1 for the stream: keep `days` daily segments, today's included, and delete the rest whole.
|
|
206
|
+
* Files that are not dated segments are left alone. Returns the names deleted, or the names that
|
|
207
|
+
* would be deleted when `dryRun`.
|
|
208
|
+
*/
|
|
209
|
+
export function retainHistory(dir: string, days: number, now: number, dryRun = false): string[] {
|
|
210
|
+
const keepFrom = segmentName(now - (Math.max(1, days) - 1) * DAY_MS);
|
|
211
|
+
let names: string[];
|
|
212
|
+
try { names = readdirSync(dir).filter((n) => SEGMENT.test(n)); } catch { return []; }
|
|
213
|
+
const stale = names.filter((n) => n < keepFrom).sort();
|
|
214
|
+
if (dryRun) return stale;
|
|
215
|
+
const gone: string[] = [];
|
|
216
|
+
for (const n of stale) {
|
|
217
|
+
try { unlinkSync(join(dir, n)); gone.push(n); } catch { /* another run deleted it first */ }
|
|
218
|
+
}
|
|
219
|
+
return gone;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The bookkeeping a run with a stream declares, beside the receipt's (§4.3). */
|
|
223
|
+
export function historyBookkeeping(sink: Pick<HistorySink, "dir" | "path">): { op: "create" | "append" | "delete"; scope: string }[] {
|
|
224
|
+
return [
|
|
225
|
+
{ op: "create", scope: `${sink.dir}/` },
|
|
226
|
+
{ op: "append", scope: sink.path },
|
|
227
|
+
{ op: "delete", scope: `${sink.dir}/` },
|
|
228
|
+
];
|
|
229
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
export { defineTool, main, type CommandSpec, type Effects, type EmittedType, type Handler, type InputDecl, type MainOptions, type ToolSpec } from "./tool.ts";
|
|
2
|
-
export { Run, ParleyClosed, SCHEMA_IDS, SIDECAR_THRESHOLD, type Diagnostic, type SchemaRef, type Sink } from "./run.ts";
|
|
2
|
+
export { DIGEST_KEYS, Run, ParleyClosed, SCHEMA_IDS, SIDECAR_THRESHOLD, type Diagnostic, type SchemaRef, type Sink } from "./run.ts";
|
|
3
|
+
export { checkRecord, schemaSubsetGap, type CheckResult } from "./check.ts";
|
|
3
4
|
export { REDACTED } from "./redact.ts";
|
|
4
5
|
export { SCHEMAS, SCHEMA_SOURCE } from "./schemas.ts";
|
|
5
6
|
export { ulid } from "./ulid.ts";
|
|
6
7
|
export { canonical, computeInv, digestTree, sha256, type InputDescriptor } from "./inv.ts";
|
|
7
8
|
export { chooseLocation, isLocationFailure, repoRoot, stateBase, bookkeepingFor } from "./location.ts";
|
|
9
|
+
export { HISTORY_DAYS_ENV, HISTORY_DEFAULT_DAYS, HISTORY_ENV, HISTORY_MAX_DAYS, historyBookkeeping, historyDays, historyProjection, isHistoryFailure, isHistorySink, openHistory, resolveHistory, retainHistory, segmentName, transformDigest, transformName, writeWholeLine, type HistoryConfig, type HistoryFailure, type HistoryPlan, type HistoryProjection, type HistorySink, type HistoryTransform } from "./history.ts";
|
|
8
10
|
export { carriesSecret, classifySecrets, collectSecretValues, redactArgv, scrub } from "./redact.ts";
|
|
11
|
+
export { declaredProjection } from "./transforms/declared.ts";
|
|
12
|
+
export { isHistoryRefusal, refuse, type HistoryRefusal } from "./refusal.ts";
|
|
13
|
+
export { SECRET_PATTERNS, type SecretPattern } from "./transforms/secret-patterns.ts";
|
|
14
|
+
export { findSuspectedSecret, refuseSuspectedSecrets, SUSPECTED_SECRET_CODE, type SuspectedSecret } from "./transforms/secrets.ts";
|
package/src/location.ts
CHANGED
|
@@ -51,11 +51,51 @@ export function bookkeepingFor(cwd: string, env: Record<string, string | undefin
|
|
|
51
51
|
];
|
|
52
52
|
}
|
|
53
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
|
+
|
|
54
92
|
/**
|
|
55
93
|
* §5.2: `.parley/.gitignore` containing `*`, create-if-absent and never overwrite. The file is
|
|
56
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).
|
|
57
97
|
*/
|
|
58
|
-
function hygiene(parleyDir: string, nonce: string):
|
|
98
|
+
function hygiene(parleyDir: string, nonce: string): string | null {
|
|
59
99
|
mkdirSync(parleyDir, { recursive: true });
|
|
60
100
|
const file = join(parleyDir, ".gitignore");
|
|
61
101
|
if (!existsSync(file)) {
|
|
@@ -65,7 +105,9 @@ function hygiene(parleyDir: string, nonce: string): "ok" | "users_file" {
|
|
|
65
105
|
try { linkSync(tmp, file); } catch (e) { if ((e as NodeJS.ErrnoException).code !== "EEXIST") { unlinkSafe(tmp); throw e; } } finally { unlinkSafe(tmp); }
|
|
66
106
|
}
|
|
67
107
|
const lines = readFileSync(file, "utf8").split(/\r?\n/);
|
|
68
|
-
|
|
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`;
|
|
69
111
|
}
|
|
70
112
|
|
|
71
113
|
function reserve(receiptDir: string, run: string): { receiptPath: string; fd: number } {
|
|
@@ -83,8 +125,9 @@ export function chooseLocation(opts: { cwd: string; run: string; env: Record<str
|
|
|
83
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" };
|
|
84
126
|
} else {
|
|
85
127
|
try {
|
|
86
|
-
|
|
87
|
-
|
|
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" };
|
|
88
131
|
} catch {
|
|
89
132
|
// The working directory is not usable; fall back silently (the bootstrap line says where).
|
|
90
133
|
}
|
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
|
+
}
|