@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.
@@ -0,0 +1,236 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { canonical } from "./evidence.js";
5
+ import { parseShell } from "./shell.js";
6
+ export const pathKey = (path) => createHash("sha256").update(path).digest("hex");
7
+ /** Coarse filesystem clocks can stamp a new file slightly before the approval was given. */
8
+ const BIRTH_SLACK_MS = 100;
9
+ /** `path` with its parent symlinks resolved; the last component stays as written. */
10
+ export function located(cwd, path) {
11
+ try {
12
+ const lexical = resolve(cwd, path);
13
+ return join(canonical(dirname(lexical)), basename(lexical));
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ /** Identity of a regular file (not a symlink), or undefined. */
20
+ export function stamp(path) {
21
+ try {
22
+ const s = lstatSync(path);
23
+ return s.isFile() ? { dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs } : undefined;
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
29
+ function exists(path) {
30
+ try {
31
+ lstatSync(path);
32
+ return true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ let current;
39
+ /** Runs `fn` with this session's created files visible to `createdBySession`. */
40
+ export function withCreated(created, fn) {
41
+ const previous = current;
42
+ current = created;
43
+ try {
44
+ return fn();
45
+ }
46
+ finally {
47
+ current = previous;
48
+ }
49
+ }
50
+ /** True when this session created `path` and nothing has replaced or changed it since. */
51
+ export function createdBySession(path) {
52
+ return current !== undefined && owns(current, path);
53
+ }
54
+ /** The session's recorded stamp for `path`, if the file there still matches it exactly. */
55
+ function owned(created, path) {
56
+ const recorded = path === undefined ? undefined : created.get(pathKey(path));
57
+ const now = recorded && stamp(path);
58
+ return recorded &&
59
+ now &&
60
+ now.dev === recorded.dev &&
61
+ now.ino === recorded.ino &&
62
+ now.size === recorded.size &&
63
+ now.mtimeMs === recorded.mtimeMs
64
+ ? recorded
65
+ : undefined;
66
+ }
67
+ function owns(created, path) {
68
+ return owned(created, path) !== undefined;
69
+ }
70
+ const WRITE_TOOLS = new Set(["Write", "create", "write_file", "Edit", "edit"]);
71
+ /**
72
+ * The allowlist for shell scripts that record creations. A new inode proves nothing about its
73
+ * content (`gzip notes.md && touch notes.md.gz`, `git stash pop && touch x`), so every simple
74
+ * command must be one of these, in the form the checks below accept, or nothing is recorded.
75
+ * No `cd` (nor `pushd`, `popd`, `chdir`): whether a skipped `true || cd sub` runs cannot be told
76
+ * from the text, so a directory change makes the script record nothing.
77
+ */
78
+ const CREATING = new Set(["touch", "tee", "cp", "mv", "pwd", "echo", "printf", "ls", "true"]);
79
+ /** Absolute directories whose `touch`, `cp`, ... are the system tools, not a lookalike script. */
80
+ const SYSTEM_BIN = /^\/(?:usr\/(?:local\/)?)?bin\/[^/]+$|^\/opt\/homebrew\/bin\/[^/]+$/;
81
+ /**
82
+ * A path word the shell passes through unchanged. A leading `~` or `=` (zsh's command path) and a
83
+ * `$`, glob or brace anywhere could expand to something else, so such a word is unprovable.
84
+ */
85
+ function literal(word) {
86
+ return (word.length > 0 &&
87
+ !/^[~=]/.test(word) &&
88
+ !/[$*?[\]{}\\]/.test(word) &&
89
+ // `link/../x` is resolved from the link's target by the kernel but as `./x` by `resolve()`.
90
+ !word.split("/").some((part, i) => part === ".." || (part === "." && i > 0)));
91
+ }
92
+ /** The allowlisted program `word` names, or undefined (a relative path may be any script). */
93
+ function program(word) {
94
+ if (!word || (word.includes("/") && !SYSTEM_BIN.test(word)))
95
+ return undefined;
96
+ const name = basename(word);
97
+ return CREATING.has(name) ? name : undefined;
98
+ }
99
+ /**
100
+ * Creation targets of a plain script, or undefined when any command is not provably on the
101
+ * allowlist. A substitution, process substitution, heredoc, input or descriptor redirect,
102
+ * expandable path word, assignment, wrapper (`env`, `xargs`, `time`, `nice`, `command`), nested
103
+ * shell or unknown option makes the whole script record
104
+ * nothing; so does `mv` or `cp` from a file the session does not own when the hook runs (an
105
+ * earlier command in the same script cannot confer ownership).
106
+ */
107
+ function shellTargets(pipelines, start, created) {
108
+ const found = [];
109
+ const cwd = start;
110
+ const add = (path, prior) => {
111
+ const at = literal(path) ? located(cwd, path) : undefined;
112
+ if (!at)
113
+ return false;
114
+ found.push({ path: at, ...(prior ? { prior } : {}) });
115
+ return true;
116
+ };
117
+ for (const stages of pipelines)
118
+ for (const c of stages) {
119
+ // parseShell already refuses heredocs and here-strings, so `subs` and `env` are what remain.
120
+ if (c.subs.length || c.env.length)
121
+ return undefined;
122
+ const name = program(c.argv[0]);
123
+ if (!name)
124
+ return undefined;
125
+ const args = c.argv.slice(1);
126
+ const flags = args.filter((word) => word.startsWith("-"));
127
+ const words = args.filter((word) => !word.startsWith("-"));
128
+ // Only output redirects to the script's own targets: `tee y < notes.md` reads a user's file,
129
+ // and `<`, `>&` and the like may carry content the session did not write.
130
+ for (const r of c.redirects) {
131
+ if (r.op !== ">" && r.op !== ">>")
132
+ return undefined;
133
+ if (r.target !== "/dev/null" && !add(r.target))
134
+ return undefined;
135
+ }
136
+ if (name === "touch") {
137
+ if (flags.length)
138
+ return undefined;
139
+ for (const word of words)
140
+ if (!add(word))
141
+ return undefined;
142
+ }
143
+ else if (name === "tee") {
144
+ if (flags.some((flag) => flag !== "-a"))
145
+ return undefined;
146
+ for (const word of words)
147
+ if (!add(word))
148
+ return undefined;
149
+ }
150
+ else if (name === "cp" || name === "mv") {
151
+ if (flags.some((flag) => flag !== "-f" && flag !== "-v") || words.length !== 2)
152
+ return undefined;
153
+ // Only from a file the session owns now: `mv` keeps its inode, `cp` copies its content.
154
+ const from = words[0];
155
+ const source = literal(from) ? owned(created, located(cwd, from)) : undefined;
156
+ if (!source || !add(words[1], name === "mv" ? source : undefined))
157
+ return undefined;
158
+ }
159
+ }
160
+ return found;
161
+ }
162
+ /**
163
+ * Paths an approved request may create or rewrite: those that do not exist yet, or that are still
164
+ * the session's own file. Best effort; a path it misses only means a later deletion is classified
165
+ * instead of approved.
166
+ */
167
+ export function creationTargets(request, created) {
168
+ const input = request.input;
169
+ const found = [];
170
+ const add = (cwd, path, prior) => {
171
+ const at = located(cwd, path);
172
+ if (at)
173
+ found.push({ path: at, ...(prior ? { prior } : {}) });
174
+ };
175
+ if (WRITE_TOOLS.has(request.tool)) {
176
+ const file = input.file_path ?? input.path;
177
+ if (typeof file === "string")
178
+ add(request.cwd, file);
179
+ }
180
+ else if (request.tool === "apply_patch" && typeof input.command === "string") {
181
+ let source;
182
+ for (const line of input.command.split("\n")) {
183
+ if (line.startsWith("*** Add File: "))
184
+ add(request.cwd, line.slice(14));
185
+ if (line.startsWith("*** Update File: ")) {
186
+ source = located(request.cwd, line.slice(17));
187
+ if (source)
188
+ found.push({ path: source });
189
+ }
190
+ // A move keeps the source's content, so the target is the session's only if the source was.
191
+ const moved = owned(created, source);
192
+ if (line.startsWith("*** Move to: ") && moved)
193
+ add(request.cwd, line.slice(13), moved);
194
+ }
195
+ }
196
+ else {
197
+ const command = input.command ?? input.cmd;
198
+ const pipelines = typeof command === "string" ? parseShell(command) : undefined;
199
+ const targets = pipelines && shellTargets(pipelines, request.cwd, created);
200
+ if (!targets)
201
+ return [];
202
+ found.push(...targets);
203
+ }
204
+ const unique = new Map();
205
+ for (const target of found) {
206
+ // Only a path that is new, or still exactly the session's file, can become or stay its own.
207
+ const own = owned(created, target.path);
208
+ if (exists(target.path) && !own)
209
+ continue;
210
+ const prior = target.prior ?? own ?? unique.get(target.path)?.prior;
211
+ unique.set(target.path, { path: target.path, ...(prior ? { prior } : {}) });
212
+ }
213
+ return [...unique.values()];
214
+ }
215
+ /**
216
+ * The session's stamp for a target after its tool ran, or undefined. A file is the session's only
217
+ * if it is the prior inode (its own file, edited or moved there) or a new inode born after the
218
+ * approval. A rename keeps the birth time, so `mv notes.md x && touch x` does not qualify. Without
219
+ * a birth time from the platform, nothing new is recorded.
220
+ */
221
+ export function settle(target, approvedAt) {
222
+ let s;
223
+ try {
224
+ s = lstatSync(target.path);
225
+ }
226
+ catch {
227
+ return undefined;
228
+ }
229
+ if (!s.isFile())
230
+ return undefined;
231
+ const now = { dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs };
232
+ if (target.prior && now.dev === target.prior.dev && now.ino === target.prior.ino)
233
+ return now;
234
+ return s.birthtimeMs > 0 && s.birthtimeMs >= approvedAt - BIRTH_SLACK_MS ? now : undefined;
235
+ }
236
+ //# sourceMappingURL=created.js.map
@@ -1,5 +1,18 @@
1
+ /**
2
+ * The working directory after a `cd` whose destination is unknown. It cannot exist (a NUL byte),
3
+ * and a relative path against it never resolves, so nothing relative is approved there.
4
+ */
5
+ export declare const UNKNOWN_CWD: string;
6
+ /**
7
+ * A shell word as an absolute path, with a leading `~` expanded as the shell does. `~user`, `~+`,
8
+ * `~-` and zsh's `=name` (the path of an executable) cannot be resolved here and throw.
9
+ *
10
+ * `..` is applied the way the kernel does, to the directory a symlink points to: `link/../x` names
11
+ * `x` beside the link's target, not beside the link.
12
+ */
13
+ export declare function resolveWord(cwd: string, word: string): string;
1
14
  export declare function git(cwd: string, args: string[]): string;
2
- export declare function canonical(path: string): string;
15
+ export declare function canonical(path: string, links?: number): string;
3
16
  export declare function inside(root: string, path: string): boolean;
4
17
  export declare function sensitive(path: string): boolean;
5
18
  export declare function protectedPath(path: string): boolean;
@@ -10,6 +23,45 @@ export declare function protectedPath(path: string): boolean;
10
23
  * stays protected.
11
24
  */
12
25
  export declare function isProtectedPath(path: string): boolean;
26
+ /** The policy service's own session directories (audit log, token, socket) under the temp dir. */
27
+ export declare function policyState(path: string): boolean;
28
+ /**
29
+ * Canonical system temp roots. A root that is the filesystem root or contains the home directory
30
+ * (a misconfigured TMPDIR) grants nothing.
31
+ */
32
+ export declare function tempRoots(): string[];
33
+ /**
34
+ * A recoverable write in the system temp directory: strictly below a temp root once symlinks and
35
+ * `..` are resolved, outside the policy service's own state, and not a hard link that could alias
36
+ * a file elsewhere.
37
+ */
38
+ export declare function tempWrite(lexical: string, path: string): boolean;
39
+ /**
40
+ * A deletion target that is disposable: strictly inside one of `roots` once symlinks and `..` are
41
+ * resolved, not policy state, protected or credential paths, and not in or holding a Git
42
+ * repository (unpushed work). A glob is allowed only in the last component, and then its
43
+ * directory must itself be strictly inside a root.
44
+ */
45
+ export declare function disposable(cwd: string, input: string, roots: string[], fill?: Fill): boolean;
46
+ /**
47
+ * Paths are resolved when the hook runs, before the script does. A command that can create a
48
+ * symlink (a recursive copy, a move, an extract, an unknown program) may plant one anywhere, so
49
+ * after it no temp write or scratch deletion in the same script is approved.
50
+ */
51
+ export interface Fill {
52
+ /** Shared by the whole script, nested `bash -c` scripts included. */
53
+ script: {
54
+ /** An earlier command may have created a symlink. */
55
+ tainted: boolean;
56
+ /** A temp path was approved where a later command can run first. */
57
+ approved: boolean;
58
+ /** Background jobs started so far; one may outlive the loop or pipeline that started it. */
59
+ jobs: number;
60
+ };
61
+ /** In a loop, a pipeline or a background job a later command can run first. */
62
+ reorder: boolean;
63
+ }
64
+ export declare const OUTSIDE_REPOSITORY = "Cannot verify repository and path evidence";
13
65
  export declare function pathEvidence(cwd: string, input: string, write: boolean): {
14
66
  allowed: boolean;
15
67
  category: "code-read" | "worktree-write" | "sensitive";
package/dist/evidence.js CHANGED
@@ -1,6 +1,55 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { existsSync, realpathSync, statSync } from "node:fs";
3
- import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
2
+ import { existsSync, lstatSync, readdirSync, readlinkSync, realpathSync, statSync, } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
5
+ /** Path separators: `/`, and `\` only on Windows; on POSIX `\` is a file-name character. */
6
+ const SEPARATOR = process.platform === "win32" ? /[\\/]/ : /\//;
7
+ const SEPARATORS = process.platform === "win32" ? /[\\/]+/ : /\/+/;
8
+ /**
9
+ * The working directory after a `cd` whose destination is unknown. It cannot exist (a NUL byte),
10
+ * and a relative path against it never resolves, so nothing relative is approved there.
11
+ */
12
+ export const UNKNOWN_CWD = resolve("/", "\u0000unknown-directory");
13
+ /**
14
+ * A shell word as an absolute path, with a leading `~` expanded as the shell does. `~user`, `~+`,
15
+ * `~-` and zsh's `=name` (the path of an executable) cannot be resolved here and throw.
16
+ *
17
+ * `..` is applied the way the kernel does, to the directory a symlink points to: `link/../x` names
18
+ * `x` beside the link's target, not beside the link.
19
+ */
20
+ export function resolveWord(cwd, word) {
21
+ let base;
22
+ let rest;
23
+ if (word === "~" || (SEPARATOR.test(word.slice(1, 2)) && word.startsWith("~"))) {
24
+ base = homedir();
25
+ rest = word.slice(2);
26
+ }
27
+ else if (word.startsWith("~") || word.startsWith("=")) {
28
+ throw new Error("Unresolvable expansion");
29
+ }
30
+ else if (isAbsolute(word)) {
31
+ const root = parse(word).root;
32
+ // On Windows a drive-less root (`/etc`) is on the cwd's drive, not the process's.
33
+ base = resolve(cwd, root);
34
+ rest = word.slice(root.length);
35
+ }
36
+ else {
37
+ if (cwd === UNKNOWN_CWD)
38
+ throw new Error("Unknown working directory");
39
+ base = cwd;
40
+ rest = word;
41
+ }
42
+ const parts = rest.split(SEPARATORS);
43
+ if (!parts.includes(".."))
44
+ return resolve(base, rest);
45
+ let current = resolve(base);
46
+ for (const part of parts) {
47
+ if (part === "" || part === ".")
48
+ continue;
49
+ current = part === ".." ? dirname(canonical(current)) : join(current, part);
50
+ }
51
+ return current;
52
+ }
4
53
  export function git(cwd, args) {
5
54
  return execFileSync("git", ["-c", "core.fsmonitor=false", "-C", cwd, ...args], {
6
55
  encoding: "utf8",
@@ -10,15 +59,29 @@ export function git(cwd, args) {
10
59
  env: Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))),
11
60
  }).trim();
12
61
  }
13
- export function canonical(path) {
62
+ export function canonical(path, links = 0) {
14
63
  // Native resolution expands Windows 8.3 aliases as well as symlinks, so
15
64
  // paths supplied by Node and Git describe the same repository boundaries.
16
65
  if (existsSync(path))
17
66
  return realpathSync.native(path);
67
+ // A dangling symlink is followed: writing through it creates its target.
68
+ let link;
69
+ try {
70
+ if (lstatSync(path).isSymbolicLink())
71
+ link = readlinkSync(path);
72
+ }
73
+ catch {
74
+ /* missing */
75
+ }
76
+ if (link !== undefined) {
77
+ if (links >= 40)
78
+ throw new Error("Too many symbolic links");
79
+ return canonical(resolve(dirname(path), link), links + 1);
80
+ }
18
81
  const parent = dirname(path);
19
82
  if (parent === path)
20
83
  throw new Error("Cannot resolve path");
21
- return resolve(canonical(parent), basename(path));
84
+ return resolve(canonical(parent, links), basename(path));
22
85
  }
23
86
  export function inside(root, path) {
24
87
  const rel = relative(root, path);
@@ -65,9 +128,141 @@ export function isProtectedPath(path) {
65
128
  return protectedPath(path);
66
129
  }
67
130
  }
131
+ /** The policy service's own session directories (audit log, token, socket) under the temp dir. */
132
+ export function policyState(path) {
133
+ return path.split(/[\\/]/).some((part) => /^acp-/i.test(part));
134
+ }
135
+ let temps;
136
+ /**
137
+ * Canonical system temp roots. A root that is the filesystem root or contains the home directory
138
+ * (a misconfigured TMPDIR) grants nothing.
139
+ */
140
+ export function tempRoots() {
141
+ if (temps)
142
+ return temps;
143
+ const candidates = [tmpdir(), ...(process.platform === "win32" ? [] : ["/tmp", "/private/tmp"])];
144
+ const roots = new Set();
145
+ let home;
146
+ try {
147
+ home = canonical(homedir());
148
+ }
149
+ catch {
150
+ /* no home directory to protect */
151
+ }
152
+ for (const candidate of candidates) {
153
+ try {
154
+ if (!isAbsolute(candidate) || !existsSync(candidate))
155
+ continue;
156
+ const root = canonical(candidate);
157
+ if (dirname(root) === root || (home && inside(root, home)))
158
+ continue;
159
+ roots.add(root);
160
+ }
161
+ catch {
162
+ /* an unresolvable root grants nothing */
163
+ }
164
+ }
165
+ temps = [...roots];
166
+ return temps;
167
+ }
168
+ /**
169
+ * A recoverable write in the system temp directory: strictly below a temp root once symlinks and
170
+ * `..` are resolved, outside the policy service's own state, and not a hard link that could alias
171
+ * a file elsewhere.
172
+ */
173
+ export function tempWrite(lexical, path) {
174
+ if (policyState(lexical) || policyState(path))
175
+ return false;
176
+ if (!tempRoots().some((root) => root !== path && inside(root, path)))
177
+ return false;
178
+ try {
179
+ const stat = lstatSync(path);
180
+ if (!stat.isDirectory() && stat.nlink > 1)
181
+ return false;
182
+ }
183
+ catch (error) {
184
+ if (error.code !== "ENOENT")
185
+ return false;
186
+ }
187
+ return true;
188
+ }
189
+ /** Whether a directory tree holds a Git repository; too large to inspect counts as yes. */
190
+ function holdsRepository(path) {
191
+ let budget = 5000;
192
+ const pending = [path];
193
+ while (pending.length) {
194
+ const dir = pending.pop();
195
+ let entries;
196
+ try {
197
+ if (!lstatSync(dir).isDirectory())
198
+ continue;
199
+ entries = readdirSync(dir, { withFileTypes: true });
200
+ }
201
+ catch (error) {
202
+ if (error.code === "ENOENT")
203
+ continue;
204
+ return true;
205
+ }
206
+ for (const entry of entries) {
207
+ if (--budget < 0 || entry.name.toLowerCase() === ".git")
208
+ return true;
209
+ if (entry.isDirectory())
210
+ pending.push(resolve(dir, entry.name));
211
+ }
212
+ }
213
+ return false;
214
+ }
215
+ /**
216
+ * A deletion target that is disposable: strictly inside one of `roots` once symlinks and `..` are
217
+ * resolved, not policy state, protected or credential paths, and not in or holding a Git
218
+ * repository (unpushed work). A glob is allowed only in the last component, and then its
219
+ * directory must itself be strictly inside a root.
220
+ */
221
+ export function disposable(cwd, input, roots, fill) {
222
+ try {
223
+ let target = input;
224
+ if (/[*?[]/.test(input)) {
225
+ const parts = input.split(SEPARATOR);
226
+ const last = parts.pop() ?? "";
227
+ if (!last || last.startsWith(".") || parts.some((part) => /[*?[]/.test(part)))
228
+ return false;
229
+ target = parts.join("/") || (parts.length ? "/" : ".");
230
+ }
231
+ const lexical = resolveWord(cwd, target);
232
+ const path = canonical(lexical);
233
+ if (fill?.script.tainted ||
234
+ policyState(lexical) ||
235
+ policyState(path) ||
236
+ sensitive(lexical) ||
237
+ sensitive(path) ||
238
+ protectedPath(lexical) ||
239
+ protectedPath(path) ||
240
+ !roots.some((root) => root !== path && inside(root, path)))
241
+ return false;
242
+ let parent = existsSync(path) && statSync(path).isDirectory() ? path : dirname(path);
243
+ while (!existsSync(parent))
244
+ parent = dirname(parent);
245
+ try {
246
+ git(parent, ["rev-parse", "--show-toplevel"]);
247
+ return false;
248
+ }
249
+ catch {
250
+ /* not inside a repository */
251
+ }
252
+ if (holdsRepository(path))
253
+ return false;
254
+ if (fill?.reorder)
255
+ fill.script.approved = true;
256
+ return true;
257
+ }
258
+ catch {
259
+ return false;
260
+ }
261
+ }
262
+ export const OUTSIDE_REPOSITORY = "Cannot verify repository and path evidence";
68
263
  export function pathEvidence(cwd, input, write) {
69
264
  try {
70
- const lexical = resolve(cwd, input);
265
+ const lexical = resolveWord(cwd, input);
71
266
  const path = canonical(lexical);
72
267
  if (sensitive(path) ||
73
268
  sensitive(lexical) ||
@@ -104,7 +299,7 @@ export function pathEvidence(cwd, input, write) {
104
299
  return {
105
300
  allowed: false,
106
301
  category: write ? "worktree-write" : "code-read",
107
- reason: "Cannot verify repository and path evidence",
302
+ reason: OUTSIDE_REPOSITORY,
108
303
  };
109
304
  }
110
305
  }
package/dist/flow.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type Fill } from "./evidence.js";
1
2
  import type { Profile } from "./profile.js";
2
3
  import type { Decision, Request } from "./types.js";
3
4
  /**
@@ -5,5 +6,5 @@ import type { Decision, Request } from "./types.js";
5
6
  * directory it could run in (before and after the `cd`, since `cd x || ...` may fail), so a command
6
7
  * that only looks safe relative to the starting directory cannot hide behind a `cd`.
7
8
  */
8
- export declare function commandDecision(request: Request, command: string, profile: Profile, depth?: number, start?: string[]): Decision;
9
+ export declare function commandDecision(request: Request, command: string, profile: Profile, depth?: number, start?: string[], fill?: Fill): Decision;
9
10
  //# sourceMappingURL=flow.d.ts.map