@agent-corpus/policy-manager 0.5.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.
@@ -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