@agent-corpus/policy-manager 0.4.0 → 0.6.0
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/README.md +95 -10
- package/dist/adapters.d.ts +14 -2
- package/dist/adapters.js +86 -7
- package/dist/audit.js +16 -2
- package/dist/cli.js +27 -3
- package/dist/config.js +11 -3
- package/dist/created.d.ts +44 -0
- package/dist/created.js +236 -0
- package/dist/evidence.d.ts +53 -1
- package/dist/evidence.js +201 -6
- package/dist/flow.d.ts +2 -1
- package/dist/flow.js +856 -76
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/permissive.d.ts +11 -3
- package/dist/permissive.js +648 -28
- package/dist/policy.d.ts +5 -1
- package/dist/policy.js +132 -30
- package/dist/principle.d.ts +8 -0
- package/dist/principle.js +8 -0
- package/dist/profile.d.ts +8 -0
- package/dist/profile.js +26 -0
- package/dist/recoverable.d.ts +41 -0
- package/dist/recoverable.js +391 -0
- package/dist/redact.d.ts +3 -0
- package/dist/redact.js +140 -0
- package/dist/replay.d.ts +2 -0
- package/dist/replay.js +9 -1
- package/dist/review.d.ts +55 -0
- package/dist/review.js +231 -0
- package/dist/script.d.ts +35 -1
- package/dist/script.js +215 -17
- package/dist/service.d.ts +1 -0
- package/dist/service.js +3 -3
- package/dist/session.d.ts +17 -2
- package/dist/session.js +156 -20
- package/dist/setup.js +3 -1
- package/dist/types.d.ts +21 -3
- package/dist/types.js +12 -1
- package/package.json +2 -2
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { lstatSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { createdBySession } from "./created.js";
|
|
5
|
+
import { canonical, inside, isProtectedPath, protectedPath, sensitive } from "./evidence.js";
|
|
6
|
+
import { parseScript } from "./script.js";
|
|
7
|
+
import { parseShell } from "./shell.js";
|
|
8
|
+
/**
|
|
9
|
+
* Deletions and resets that Git can undo: tracked content that is unmodified against HEAD, in a
|
|
10
|
+
* linked worktree on a feature branch. Evidence is read from Git at decision time and never cached.
|
|
11
|
+
* Any doubt returns false, which leaves the caller's human decision in place.
|
|
12
|
+
*/
|
|
13
|
+
const INERT = new Set(["cd", "pwd", "echo", "ls", "true"]);
|
|
14
|
+
const DESTRUCTIVE_GIT = new Set(["rm", "reset", "checkout", "restore"]);
|
|
15
|
+
/**
|
|
16
|
+
* Evidence holds only when nothing else in the script can change the files first (`mv u t; rm t`).
|
|
17
|
+
* The script may contain these deletions plus `cd` and a few inert commands, without redirections,
|
|
18
|
+
* assignments, wrappers, variables or substitutions.
|
|
19
|
+
*/
|
|
20
|
+
/** Words of a plain simple command: no assignment, redirection, variable or substitution. */
|
|
21
|
+
function plainWords(command) {
|
|
22
|
+
if (command?.kind !== "simple" || command.assigns.length || command.redirects.length)
|
|
23
|
+
return undefined;
|
|
24
|
+
const text = (word) => word.subs.length || !word.parts.every((part) => typeof part === "string")
|
|
25
|
+
? undefined
|
|
26
|
+
: word.parts.join("");
|
|
27
|
+
const words = command.argv.map(text);
|
|
28
|
+
return words.every((word) => word !== undefined) ? words : undefined;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The one directory a script deletes in when its whole effect is `rm` inside linked feature
|
|
32
|
+
* worktrees, or undefined. The script may hold only `rm` and inert commands, with no redirection,
|
|
33
|
+
* assignment, variable or substitution, and at most a leading `cd <dir>` whose list is joined by
|
|
34
|
+
* `&&` alone: if the cd fails nothing else runs. Every `rm` must be a worktree deletion, so one
|
|
35
|
+
* classifier verdict on the first cannot carry an unjudged later command.
|
|
36
|
+
*/
|
|
37
|
+
export function deletionScriptCwd(request) {
|
|
38
|
+
const text = request.input.command ?? request.input.cmd;
|
|
39
|
+
const script = typeof text === "string" ? parseScript(text) : undefined;
|
|
40
|
+
if (!script?.items.length)
|
|
41
|
+
return undefined;
|
|
42
|
+
let cwd = request.cwd;
|
|
43
|
+
const deletions = [];
|
|
44
|
+
for (const [i, item] of script.items.entries()) {
|
|
45
|
+
if (item.background)
|
|
46
|
+
return undefined;
|
|
47
|
+
const nodes = [item.node.first, ...item.node.rest.map((r) => r.node)];
|
|
48
|
+
for (const [j, node] of nodes.entries()) {
|
|
49
|
+
if (node.negated || node.stages.length !== 1)
|
|
50
|
+
return undefined;
|
|
51
|
+
const [program, ...args] = plainWords(node.stages[0]) ?? [];
|
|
52
|
+
if (program === "cd") {
|
|
53
|
+
const only = i === 0 && j === 0 && script.items.length === 1;
|
|
54
|
+
const anded = item.node.rest.every((r) => r.op === "&&");
|
|
55
|
+
if (!only || !anded || args.length !== 1 || /^[~-]/.test(args[0]))
|
|
56
|
+
return undefined;
|
|
57
|
+
cwd = resolve(cwd, args[0]);
|
|
58
|
+
}
|
|
59
|
+
else if (program === "rm")
|
|
60
|
+
deletions.push(args);
|
|
61
|
+
else if (!program || !INERT.has(program))
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return deletions.length && deletions.every((args) => worktreeDeletion(cwd, args))
|
|
66
|
+
? cwd
|
|
67
|
+
: undefined;
|
|
68
|
+
}
|
|
69
|
+
export function soleEffect(request) {
|
|
70
|
+
const command = request.input.command ?? request.input.cmd;
|
|
71
|
+
if (typeof command !== "string")
|
|
72
|
+
return false;
|
|
73
|
+
const pipelines = parseShell(command);
|
|
74
|
+
if (!pipelines)
|
|
75
|
+
return false;
|
|
76
|
+
return pipelines.every((stages) => stages.length === 1 &&
|
|
77
|
+
stages.every((c) => !c.env.length &&
|
|
78
|
+
!c.redirects.length &&
|
|
79
|
+
!c.subs.length &&
|
|
80
|
+
c.stdin === undefined &&
|
|
81
|
+
(INERT.has(c.argv[0] ?? "") ||
|
|
82
|
+
c.argv[0] === "rm" ||
|
|
83
|
+
(c.argv[0] === "git" && DESTRUCTIVE_GIT.has(c.argv[1] ?? "")))));
|
|
84
|
+
}
|
|
85
|
+
/** Like evidence.git, with room for whole-repository listings. */
|
|
86
|
+
function git(cwd, args, raw = false) {
|
|
87
|
+
const out = execFileSync("git", ["-c", "core.fsmonitor=false", "-C", cwd, ...args], {
|
|
88
|
+
encoding: "utf8",
|
|
89
|
+
timeout: 5000,
|
|
90
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
91
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
92
|
+
env: Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))),
|
|
93
|
+
});
|
|
94
|
+
// Porcelain status starts with a meaningful space (` M`), so -z output is never trimmed.
|
|
95
|
+
return raw ? out : out.trim();
|
|
96
|
+
}
|
|
97
|
+
/** The linked worktree on a feature branch that contains `dir`, or undefined. */
|
|
98
|
+
function featureWorktree(dir) {
|
|
99
|
+
const root = canonical(git(dir, ["rev-parse", "--show-toplevel"]));
|
|
100
|
+
const gitDir = canonical(git(dir, ["rev-parse", "--absolute-git-dir"]));
|
|
101
|
+
const common = canonical(resolve(dir, git(dir, ["rev-parse", "--git-common-dir"])));
|
|
102
|
+
const branch = git(dir, ["branch", "--show-current"]);
|
|
103
|
+
if (gitDir === common || !branch || /^(?:main|master)$/.test(branch))
|
|
104
|
+
return undefined;
|
|
105
|
+
let fallback = "";
|
|
106
|
+
try {
|
|
107
|
+
fallback = git(dir, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
/* no remote default recorded */
|
|
111
|
+
}
|
|
112
|
+
if (fallback && fallback.replace(/^origin\//, "") === branch)
|
|
113
|
+
return undefined;
|
|
114
|
+
return { root };
|
|
115
|
+
}
|
|
116
|
+
function status(root, paths, untracked) {
|
|
117
|
+
const out = git(root, [
|
|
118
|
+
"--literal-pathspecs",
|
|
119
|
+
"status",
|
|
120
|
+
"--porcelain=v1",
|
|
121
|
+
"-z",
|
|
122
|
+
"--ignore-submodules=none",
|
|
123
|
+
untracked ? "--untracked-files=all" : "--untracked-files=no",
|
|
124
|
+
...(untracked ? ["--ignored=matching"] : []),
|
|
125
|
+
"--",
|
|
126
|
+
...paths,
|
|
127
|
+
], true);
|
|
128
|
+
const fields = out.split("\0").filter(Boolean);
|
|
129
|
+
const entries = [];
|
|
130
|
+
for (let i = 0; i < fields.length; i++) {
|
|
131
|
+
const field = fields[i];
|
|
132
|
+
const xy = field.slice(0, 2);
|
|
133
|
+
entries.push({ xy, path: field.slice(3) });
|
|
134
|
+
// Renames and copies carry the original path in the next field.
|
|
135
|
+
if (/[RC]/.test(xy))
|
|
136
|
+
i++;
|
|
137
|
+
}
|
|
138
|
+
return entries;
|
|
139
|
+
}
|
|
140
|
+
/** Index flags that hide modifications from status: assume-unchanged, skip-worktree, unmerged. */
|
|
141
|
+
function hiddenFlags(root, paths) {
|
|
142
|
+
const flags = git(root, ["--literal-pathspecs", "ls-files", "-v", "-z", "--", ...paths]);
|
|
143
|
+
return flags.split("\0").some((line) => line && (/^[a-z]/.test(line) || /^[SM] /.test(line)));
|
|
144
|
+
}
|
|
145
|
+
/** Hidden flags, or a submodule anywhere under the paths. */
|
|
146
|
+
function hiddenState(root, paths) {
|
|
147
|
+
if (hiddenFlags(root, paths))
|
|
148
|
+
return true;
|
|
149
|
+
const stage = git(root, ["--literal-pathspecs", "ls-files", "-s", "-z", "--", ...paths]);
|
|
150
|
+
if (stage.split("\0").some((line) => line.startsWith("160000 ")))
|
|
151
|
+
return true;
|
|
152
|
+
const head = git(root, ["--literal-pathspecs", "ls-tree", "-r", "-z", "HEAD", "--", ...paths]);
|
|
153
|
+
return head.split("\0").some((line) => line.startsWith("160000 "));
|
|
154
|
+
}
|
|
155
|
+
function tracked(root, path) {
|
|
156
|
+
return git(root, ["--literal-pathspecs", "ls-files", "-z", "--", path]) !== "";
|
|
157
|
+
}
|
|
158
|
+
// zsh expands a leading `~` and `=name` (the path of command `name`); `-` is an option and `:`
|
|
159
|
+
// a Git pathspec magic. `./=name` stays a plain file.
|
|
160
|
+
const PLAIN_OPERAND = /^[^~:=-]/;
|
|
161
|
+
/**
|
|
162
|
+
* Resolves an operand to what the command removes, inside a feature worktree, or undefined.
|
|
163
|
+
* Parent symlinks are followed; a final symlink is the link itself unless a trailing slash
|
|
164
|
+
* follows it.
|
|
165
|
+
*/
|
|
166
|
+
function locate(cwd, operand) {
|
|
167
|
+
if (!operand || !PLAIN_OPERAND.test(operand) || /[*?[\]\\]/.test(operand))
|
|
168
|
+
return undefined;
|
|
169
|
+
const parts = operand.split("/");
|
|
170
|
+
const trailing = parts.at(-1) === "";
|
|
171
|
+
const segments = parts.filter((part, index) => part !== "" && !(index === 0 && part === "."));
|
|
172
|
+
if (!segments.length || segments.some((part) => part === "." || part === ".."))
|
|
173
|
+
return undefined;
|
|
174
|
+
const lexical = resolve(cwd, operand);
|
|
175
|
+
if (sensitive(lexical) || isProtectedPath(lexical))
|
|
176
|
+
return undefined;
|
|
177
|
+
const target = trailing
|
|
178
|
+
? canonical(lexical)
|
|
179
|
+
: join(canonical(dirname(lexical)), basename(lexical));
|
|
180
|
+
if (sensitive(target) || isProtectedPath(target))
|
|
181
|
+
return undefined;
|
|
182
|
+
const parent = canonical(dirname(target));
|
|
183
|
+
const tree = featureWorktree(parent);
|
|
184
|
+
if (!tree || !inside(tree.root, target) || target === tree.root)
|
|
185
|
+
return undefined;
|
|
186
|
+
const rel = relative(tree.root, target).split(sep).join("/");
|
|
187
|
+
if (!rel || protectedPath(rel))
|
|
188
|
+
return undefined;
|
|
189
|
+
return { root: tree.root, rel, target, trailing };
|
|
190
|
+
}
|
|
191
|
+
/** A deletion operand that names a credential or protected path, as written or resolved. */
|
|
192
|
+
export function deletesProtected(cwd, args) {
|
|
193
|
+
return args
|
|
194
|
+
.filter((word) => !word.startsWith("-"))
|
|
195
|
+
.some((word) => {
|
|
196
|
+
try {
|
|
197
|
+
const lexical = resolve(cwd, word);
|
|
198
|
+
const real = canonical(lexical);
|
|
199
|
+
return [lexical, real].some((path) => sensitive(path) || isProtectedPath(path));
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
function exists(path) {
|
|
207
|
+
try {
|
|
208
|
+
lstatSync(path);
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/** Operands and -r of an `rm` with only -f, -r, -R, -d and -v, or undefined. */
|
|
216
|
+
function rmOperands(args) {
|
|
217
|
+
const operands = [];
|
|
218
|
+
let options = true;
|
|
219
|
+
let recursive = false;
|
|
220
|
+
for (const word of args) {
|
|
221
|
+
if (options && word === "--")
|
|
222
|
+
options = false;
|
|
223
|
+
else if (options && word.startsWith("-")) {
|
|
224
|
+
// BSD rm stops at the first operand, so a later `-x` is a file name the checks never saw.
|
|
225
|
+
if (operands.length)
|
|
226
|
+
return undefined;
|
|
227
|
+
if (!/^-[frRdv]+$/.test(word) &&
|
|
228
|
+
!["--force", "--recursive", "--dir", "--verbose"].includes(word))
|
|
229
|
+
return undefined;
|
|
230
|
+
if (/^-[a-zA-Z]*[rR]/.test(word) || word === "--recursive")
|
|
231
|
+
recursive = true;
|
|
232
|
+
}
|
|
233
|
+
else
|
|
234
|
+
operands.push(word);
|
|
235
|
+
}
|
|
236
|
+
return operands.length ? { operands, recursive } : undefined;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* `rm` that removes only tracked content identical to HEAD (no untracked, ignored, modified or
|
|
240
|
+
* staged path under any operand, no submodule): "tracked". Or, without -r, also untracked files
|
|
241
|
+
* this session created and nothing has changed since: "session". Otherwise undefined.
|
|
242
|
+
*/
|
|
243
|
+
export function rmRecoverable(cwd, args) {
|
|
244
|
+
const parsed = rmOperands(args);
|
|
245
|
+
if (!parsed)
|
|
246
|
+
return undefined;
|
|
247
|
+
let kind = "tracked";
|
|
248
|
+
try {
|
|
249
|
+
for (const operand of parsed.operands) {
|
|
250
|
+
const found = locate(cwd, operand);
|
|
251
|
+
if (!found || !exists(found.target))
|
|
252
|
+
return undefined;
|
|
253
|
+
if (!tracked(found.root, found.rel)) {
|
|
254
|
+
if (parsed.recursive || found.trailing || !createdBySession(found.target))
|
|
255
|
+
return undefined;
|
|
256
|
+
kind = "session";
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (status(found.root, [found.rel], true).length)
|
|
260
|
+
return undefined;
|
|
261
|
+
if (hiddenState(found.root, [found.rel]))
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
return kind;
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* An `rm` whose every operand is a plain path inside a linked feature worktree (not the worktree
|
|
272
|
+
* itself, nothing protected): local file deletion the classifier may judge. Anything else that is
|
|
273
|
+
* destructive stays a person's decision.
|
|
274
|
+
*/
|
|
275
|
+
export function worktreeDeletion(cwd, args) {
|
|
276
|
+
const parsed = rmOperands(args);
|
|
277
|
+
try {
|
|
278
|
+
return !!parsed && parsed.operands.every((operand) => locate(cwd, operand) !== undefined);
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* `git rm -f`: the same evidence as rm, but a path already deleted from the working tree is fine,
|
|
286
|
+
* since only the index changes.
|
|
287
|
+
*/
|
|
288
|
+
export function gitRmRecoverable(cwd, rest) {
|
|
289
|
+
const paths = [];
|
|
290
|
+
let options = true;
|
|
291
|
+
for (const word of rest) {
|
|
292
|
+
if (options && word === "--")
|
|
293
|
+
options = false;
|
|
294
|
+
else if (options && word.startsWith("-")) {
|
|
295
|
+
if (!/^-[frqn]+$/.test(word) &&
|
|
296
|
+
!["--force", "--quiet", "--cached", "--dry-run", "--ignore-unmatch"].includes(word))
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
else
|
|
300
|
+
paths.push(word);
|
|
301
|
+
}
|
|
302
|
+
if (!paths.length)
|
|
303
|
+
return false;
|
|
304
|
+
try {
|
|
305
|
+
for (const path of paths) {
|
|
306
|
+
const found = locate(cwd, path);
|
|
307
|
+
if (!found || !tracked(found.root, found.rel))
|
|
308
|
+
return false;
|
|
309
|
+
if (status(found.root, [found.rel], true).some((e) => e.xy !== " D"))
|
|
310
|
+
return false;
|
|
311
|
+
if (hiddenState(found.root, [found.rel]))
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
return true;
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
return false;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* `git checkout [--] <paths>` and `git restore [-W|-SW] <paths>`: the working tree loses nothing
|
|
322
|
+
* when it already matches the source (index, or HEAD for --staged --worktree), or the file is only
|
|
323
|
+
* missing from it.
|
|
324
|
+
*/
|
|
325
|
+
export function restoreRecoverable(cwd, paths, fromHead) {
|
|
326
|
+
if (!paths.length)
|
|
327
|
+
return false;
|
|
328
|
+
try {
|
|
329
|
+
for (const path of paths) {
|
|
330
|
+
if (path === ".") {
|
|
331
|
+
const here = canonical(cwd);
|
|
332
|
+
const tree = featureWorktree(here);
|
|
333
|
+
if (!tree)
|
|
334
|
+
return false;
|
|
335
|
+
const rel = relative(tree.root, here).split(sep).join("/");
|
|
336
|
+
if (protectedPath(rel) || sensitive(here) || !check(tree.root, rel || ".", fromHead))
|
|
337
|
+
return false;
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
const found = locate(cwd, path);
|
|
341
|
+
if (!found || !check(found.root, found.rel, fromHead))
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function check(root, rel, fromHead) {
|
|
351
|
+
if (!tracked(root, rel))
|
|
352
|
+
return false;
|
|
353
|
+
const allowed = (xy) => (fromHead ? xy === " D" : xy[1] === " " || xy[1] === "D");
|
|
354
|
+
if (!status(root, [rel], false).every((e) => allowed(e.xy) && !e.xy.includes("U")))
|
|
355
|
+
return false;
|
|
356
|
+
// Without --recurse-submodules these leave a submodule's own files alone.
|
|
357
|
+
return !hiddenFlags(root, [rel]);
|
|
358
|
+
}
|
|
359
|
+
const REVISION = /^[A-Za-z0-9][A-Za-z0-9/_.~^-]*$/;
|
|
360
|
+
/**
|
|
361
|
+
* `git reset --hard [<commit>]` with no uncommitted tracked change, every commit it drops from the
|
|
362
|
+
* branch still on a remote-tracking ref, and no untracked or ignored file where the target writes.
|
|
363
|
+
*/
|
|
364
|
+
export function resetRecoverable(cwd, target = "HEAD") {
|
|
365
|
+
if (!REVISION.test(target))
|
|
366
|
+
return false;
|
|
367
|
+
try {
|
|
368
|
+
const tree = featureWorktree(canonical(cwd));
|
|
369
|
+
if (!tree)
|
|
370
|
+
return false;
|
|
371
|
+
const { root } = tree;
|
|
372
|
+
if (status(root, [], false).length || hiddenFlags(root, []))
|
|
373
|
+
return false;
|
|
374
|
+
const commit = git(root, ["rev-parse", "--verify", "--end-of-options", `${target}^{commit}`]);
|
|
375
|
+
if (git(root, ["rev-list", "--count", "HEAD", "--not", commit, "--remotes"]) !== "0")
|
|
376
|
+
return false;
|
|
377
|
+
const written = git(root, ["diff", "--name-only", "--no-renames", "-z", "HEAD", commit])
|
|
378
|
+
.split("\0")
|
|
379
|
+
.filter(Boolean);
|
|
380
|
+
if (!written.length)
|
|
381
|
+
return true;
|
|
382
|
+
if (written.some((path) => protectedPath(path)))
|
|
383
|
+
return false;
|
|
384
|
+
const loose = status(root, [], true).map((e) => e.path.replace(/\/$/, ""));
|
|
385
|
+
return !written.some((path) => loose.some((u) => path === u || path.startsWith(`${u}/`) || u.startsWith(`${path}/`)));
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
return false;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
//# sourceMappingURL=recoverable.js.map
|
package/dist/redact.d.ts
ADDED
package/dist/redact.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Redaction for text that is written to the audit log: the exact command of an ambiguous request
|
|
2
|
+
// and the classifier's free-text rationale. The audit log is private, but it is also what a human
|
|
3
|
+
// reads in a risk review, so values that look like secrets never reach it.
|
|
4
|
+
//
|
|
5
|
+
// Text is split into words by hand (quotes keep a quoted value together) and every pattern is
|
|
6
|
+
// anchored or linear, so hostile input cannot make the redaction slow.
|
|
7
|
+
/** Names that carry a secret as a substring: `DB_PASSWORD`, `--api-key`, `x-auth-token`. */
|
|
8
|
+
const SECRET_NAME = /(?:token|secret|pass(?:word|wd|phrase)?|pwd|api[-_]?key|apikey|credential|bearer|cookie|private[-_]?key|access[-_]?key|signature)/i;
|
|
9
|
+
/** `auth` only as a whole word, so `--author` is not a secret but `--auth` and `Authorization` are. */
|
|
10
|
+
const AUTH_NAME = /(?:^|[^a-z])auth(?:orization)?(?:[^a-z]|$)/i;
|
|
11
|
+
const TOKEN_PREFIX = /^(?:gh[pousr]_|github_pat_|sk-|xox[baprs]-|AKIA|ASIA|AIza|eyJ|glpat-|npm_|shpat_)/;
|
|
12
|
+
const LONG_OPAQUE = /^[A-Za-z0-9+/=_-]{32,}$/;
|
|
13
|
+
/** Programs whose `-pPASSWORD` attaches the password to the flag. Elsewhere `-p…` is not secret. */
|
|
14
|
+
const ATTACHED_PASSWORD = /^(?:mysql|mysqldump|mysqladmin|mysqlcheck|mariadb|mariadb-dump)$/;
|
|
15
|
+
/** Flags whose next word is a credential, whatever the word looks like. */
|
|
16
|
+
const CREDENTIAL_FLAG = /^(?:-u|-U|--user|--proxy-user|--oauth2-bearer)$/;
|
|
17
|
+
const isSecretName = (name) => SECRET_NAME.test(name) || AUTH_NAME.test(name);
|
|
18
|
+
function words(text) {
|
|
19
|
+
const out = [];
|
|
20
|
+
let current = "";
|
|
21
|
+
let quote = "";
|
|
22
|
+
let inWord = false;
|
|
23
|
+
const flush = () => {
|
|
24
|
+
if (inWord)
|
|
25
|
+
out.push(current);
|
|
26
|
+
current = "";
|
|
27
|
+
inWord = false;
|
|
28
|
+
};
|
|
29
|
+
for (const char of text) {
|
|
30
|
+
if (quote) {
|
|
31
|
+
current += char;
|
|
32
|
+
if (char === quote)
|
|
33
|
+
quote = "";
|
|
34
|
+
}
|
|
35
|
+
else if (char === '"' || char === "'") {
|
|
36
|
+
quote = char;
|
|
37
|
+
current += char;
|
|
38
|
+
inWord = true;
|
|
39
|
+
}
|
|
40
|
+
else if (/\s/.test(char)) {
|
|
41
|
+
flush();
|
|
42
|
+
out.push(char);
|
|
43
|
+
inWord = false;
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
current += char;
|
|
47
|
+
inWord = true;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
flush();
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
/** `https://user:pass@host/x?token=1` keeps host and path but loses userinfo and query values. */
|
|
54
|
+
function redactUrl(word) {
|
|
55
|
+
const scheme = word.match(/^["']?[a-z][a-z0-9+.-]*:\/\//i)?.[0];
|
|
56
|
+
if (!scheme)
|
|
57
|
+
return word;
|
|
58
|
+
const rest = word.slice(scheme.length);
|
|
59
|
+
const cut = rest.search(/[?#]/);
|
|
60
|
+
const head = cut < 0 ? rest : rest.slice(0, cut);
|
|
61
|
+
const slash = head.indexOf("/");
|
|
62
|
+
const authority = slash < 0 ? head : head.slice(0, slash);
|
|
63
|
+
const path = slash < 0 ? "" : head.slice(slash);
|
|
64
|
+
const at = authority.lastIndexOf("@");
|
|
65
|
+
const host = at < 0 ? authority : `[REDACTED]@${authority.slice(at + 1)}`;
|
|
66
|
+
return `${scheme}${host}${path}${cut >= 0 && rest[cut] === "?" ? "?[REDACTED]" : ""}`;
|
|
67
|
+
}
|
|
68
|
+
/** `-H "X-Api-Key: abc"` and `"Authorization: Bearer abc"`, one quoted word. */
|
|
69
|
+
function redactHeader(word) {
|
|
70
|
+
const colon = word.indexOf(":");
|
|
71
|
+
if (colon <= 0 || word.startsWith("//", colon + 1))
|
|
72
|
+
return undefined;
|
|
73
|
+
const name = word.slice(0, colon).replace(/^["']/, "");
|
|
74
|
+
if (!/^[A-Za-z][\w-]*$/.test(name) || !isSecretName(name))
|
|
75
|
+
return undefined;
|
|
76
|
+
const quote = /["']$/.test(word) ? word.at(-1) : "";
|
|
77
|
+
return `${word.slice(0, colon + 1)} [REDACTED]${quote}`;
|
|
78
|
+
}
|
|
79
|
+
/** Redacts a shell command or other free text, keeping it recognisable and at most `max` long. */
|
|
80
|
+
export function redactText(text, max = 300) {
|
|
81
|
+
let hideNext = false;
|
|
82
|
+
let program = "";
|
|
83
|
+
let atStart = true;
|
|
84
|
+
const out = words(text).map((raw) => {
|
|
85
|
+
if (/^\s$/.test(raw))
|
|
86
|
+
return raw;
|
|
87
|
+
if (/^(?:\||\|\||&&|;|&)$/.test(raw)) {
|
|
88
|
+
atStart = true;
|
|
89
|
+
return raw;
|
|
90
|
+
}
|
|
91
|
+
if (atStart && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(raw)) {
|
|
92
|
+
program =
|
|
93
|
+
raw
|
|
94
|
+
.replace(/^["']|["']$/g, "")
|
|
95
|
+
.split(/[\\/]/)
|
|
96
|
+
.pop() ?? "";
|
|
97
|
+
atStart = false;
|
|
98
|
+
}
|
|
99
|
+
if (hideNext) {
|
|
100
|
+
// `Authorization: Bearer abc` carries the secret in the word after the scheme.
|
|
101
|
+
hideNext = /^["']?(?:bearer|basic|token)["']?$/i.test(raw);
|
|
102
|
+
return hideNext ? raw : "[REDACTED]";
|
|
103
|
+
}
|
|
104
|
+
// URL credentials first: a `?token=` in the query must not hide userinfo before it.
|
|
105
|
+
const piece = redactUrl(raw);
|
|
106
|
+
if (CREDENTIAL_FLAG.test(piece)) {
|
|
107
|
+
hideNext = true;
|
|
108
|
+
return piece;
|
|
109
|
+
}
|
|
110
|
+
// `Authorization:` alone: the value, and a scheme before it, are the words that follow.
|
|
111
|
+
if (/^["']?[A-Za-z][\w-]*:["']?$/.test(piece) && isSecretName(piece.replace(/[:"']/g, ""))) {
|
|
112
|
+
hideNext = true;
|
|
113
|
+
return piece;
|
|
114
|
+
}
|
|
115
|
+
const header = redactHeader(piece);
|
|
116
|
+
if (header)
|
|
117
|
+
return header;
|
|
118
|
+
const eq = piece.indexOf("=");
|
|
119
|
+
const name = eq >= 0 ? piece.slice(0, eq) : piece;
|
|
120
|
+
// `mysql -pSECRET`: a short option with its value attached.
|
|
121
|
+
if (/^-p./.test(piece) && eq < 0 && ATTACHED_PASSWORD.test(program))
|
|
122
|
+
return "-p[REDACTED]";
|
|
123
|
+
if (/^-[A-Za-z]./.test(piece) && eq < 0 && isSecretName(piece))
|
|
124
|
+
return `${piece.slice(0, 2)}[REDACTED]`;
|
|
125
|
+
if (isSecretName(name)) {
|
|
126
|
+
if (eq >= 0)
|
|
127
|
+
return `${name}=[REDACTED]`;
|
|
128
|
+
// A bare flag takes its value from the next word; a header name waits for its value.
|
|
129
|
+
if (/^-{1,2}[A-Za-z]/.test(piece) || /:["']?$/.test(piece))
|
|
130
|
+
hideNext = true;
|
|
131
|
+
return piece;
|
|
132
|
+
}
|
|
133
|
+
// A quoted token is still a token: judge the word without its surrounding quote.
|
|
134
|
+
const bare = piece.replace(/^["']|["']$/g, "");
|
|
135
|
+
return TOKEN_PREFIX.test(bare) || LONG_OPAQUE.test(bare) ? "[REDACTED]" : piece;
|
|
136
|
+
});
|
|
137
|
+
const joined = out.join("");
|
|
138
|
+
return joined.length > max ? `${joined.slice(0, max)}…` : joined;
|
|
139
|
+
}
|
|
140
|
+
//# sourceMappingURL=redact.js.map
|
package/dist/replay.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ export interface ReplayReport {
|
|
|
3
3
|
commands: number;
|
|
4
4
|
approved: number;
|
|
5
5
|
strictApproved: number;
|
|
6
|
+
/** Escalations the AI classifier handles instead of a person (permissive profile only). */
|
|
7
|
+
classified: number;
|
|
6
8
|
reasons: Array<{
|
|
7
9
|
reason: string;
|
|
8
10
|
count: number;
|
package/dist/replay.js
CHANGED
|
@@ -27,7 +27,13 @@ function transcriptFiles(paths, limit) {
|
|
|
27
27
|
export function replayTranscripts(paths, profile, files = 50) {
|
|
28
28
|
const seen = new Set();
|
|
29
29
|
const reasons = new Map();
|
|
30
|
-
const report = {
|
|
30
|
+
const report = {
|
|
31
|
+
commands: 0,
|
|
32
|
+
approved: 0,
|
|
33
|
+
strictApproved: 0,
|
|
34
|
+
classified: 0,
|
|
35
|
+
reasons: [],
|
|
36
|
+
};
|
|
31
37
|
for (const file of transcriptFiles(paths, files))
|
|
32
38
|
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
33
39
|
if (!line.includes('"tool_use"'))
|
|
@@ -66,6 +72,8 @@ export function replayTranscripts(paths, profile, files = 50) {
|
|
|
66
72
|
report.approved++;
|
|
67
73
|
continue;
|
|
68
74
|
}
|
|
75
|
+
if (decision.tier === "ambiguous")
|
|
76
|
+
report.classified++;
|
|
69
77
|
const bucket = reasons.get(decision.reason) ?? { count: 0, examples: [] };
|
|
70
78
|
bucket.count++;
|
|
71
79
|
if (bucket.examples.length < 3)
|
package/dist/review.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** One classification the AI gave for a request. A request can have several (a replay). */
|
|
2
|
+
export interface Attempt {
|
|
3
|
+
time: string;
|
|
4
|
+
category?: string;
|
|
5
|
+
confidence?: number;
|
|
6
|
+
recoverable?: boolean;
|
|
7
|
+
rationale?: string;
|
|
8
|
+
/** `invalid` when the answer was rejected before it could decide anything. */
|
|
9
|
+
outcome: "approved" | "denied" | "invalid";
|
|
10
|
+
}
|
|
11
|
+
/** One ambiguous request, followed through classification to its outcome. */
|
|
12
|
+
export interface ClassifiedRequest {
|
|
13
|
+
session: string;
|
|
14
|
+
requestHash: string;
|
|
15
|
+
time: string;
|
|
16
|
+
command?: string;
|
|
17
|
+
reason?: string;
|
|
18
|
+
/** Every classification, in order. Later ones never overwrite earlier ones. */
|
|
19
|
+
attempts: Attempt[];
|
|
20
|
+
/** What happened to the request: `approved`/`denied` by the AI, `human` after a fallback. */
|
|
21
|
+
outcome: "approved" | "denied" | "fallback" | "unresolved";
|
|
22
|
+
fallbackReason?: string;
|
|
23
|
+
execution?: {
|
|
24
|
+
status?: string;
|
|
25
|
+
exitCode?: number;
|
|
26
|
+
};
|
|
27
|
+
humanResponse?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface ClassificationReview {
|
|
30
|
+
sessions: number;
|
|
31
|
+
requested: number;
|
|
32
|
+
approved: number;
|
|
33
|
+
denied: number;
|
|
34
|
+
fallback: number;
|
|
35
|
+
fallbackReasons: Record<string, number>;
|
|
36
|
+
unresolved: number;
|
|
37
|
+
/** Share of requested ambiguous requests that reached a person. */
|
|
38
|
+
fallbackRate: number;
|
|
39
|
+
histogram: Array<{
|
|
40
|
+
range: string;
|
|
41
|
+
count: number;
|
|
42
|
+
}>;
|
|
43
|
+
aiApproved: ClassifiedRequest[];
|
|
44
|
+
aiDenied: ClassifiedRequest[];
|
|
45
|
+
approvedButFailed: ClassifiedRequest[];
|
|
46
|
+
humanDenied: ClassifiedRequest[];
|
|
47
|
+
/** Requests classified more than once. A replay is the signal a risk review looks for first. */
|
|
48
|
+
reclassified: ClassifiedRequest[];
|
|
49
|
+
/** Requests the AI denied and later approved. */
|
|
50
|
+
deniedThenApproved: ClassifiedRequest[];
|
|
51
|
+
}
|
|
52
|
+
export declare function sessionDirectories(extra?: string[]): string[];
|
|
53
|
+
export declare function reviewClassifications(directories: string[], since?: string): Promise<ClassificationReview>;
|
|
54
|
+
export declare function formatReview(review: ClassificationReview): string;
|
|
55
|
+
//# sourceMappingURL=review.d.ts.map
|