@agent-corpus/policy-manager 0.9.0 → 0.10.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 CHANGED
@@ -215,6 +215,38 @@ Under the permissive profile, a harness tool that is not a shell, file, patch or
215
215
 
216
216
  Each default approval's audit `decision` record carries `defaultTool` with the tool name. `review-classifications` lists these tools newest first by when each was first seen, so a tool a harness newly added is noticed and can be put in `toolsDeny`.
217
217
 
218
+ #### Credential helpers
219
+
220
+ Reading a credential always goes to a person, except through a script listed in `credentialHelpers` (permissive profile only). A helper reads a secret for one narrow job, such as posting a review as a GitHub App:
221
+
222
+ ```json
223
+ "credentialHelpers": [
224
+ {
225
+ "path": "tools/review-bot.mjs",
226
+ "remotes": ["github.com/example-org/"],
227
+ "args": [
228
+ ["--repo", "<repo>", "check"],
229
+ ["--repo", "<repo>", "gh", "api", "repos/<repo>/pulls/<int>/reviews", "--input", "<file>"],
230
+ ["--repo", "<repo>", "gh", "pr", "review", "<int>", "-R", "<repo>", ["--approve", "--comment"], "--body-file", "<file>"]
231
+ ]
232
+ }
233
+ ]
234
+ ```
235
+
236
+ `node <script> <args>` is approved, and named in the audit `decision` record as `credentialHelpers: ["<path>#<shape index>"]`, only when all of these hold:
237
+
238
+ - The checkout comes from a listed remote. `remotes` (required) lists normalized prefixes such as `github.com/example-org/`: a lowercase host, then at least an owner, where a trailing `/` makes it a prefix. The checkout's `remote.origin.url` (https, ssh or `git@host:` form, normalized to lowercase `host/owner/repo` without `.git`) must match one. It must equal what `git remote get-url origin` resolves, so no `url.*.insteadOf` rewrite applies, and there must be no `remote.origin.pushurl`. A clone of a local or other repository, or a `git init`, has an origin that does not match.
239
+ - The script, however it is named (relative, absolute, from another directory), is the regular file at `<checkout>/<path>` with no symlink on the way, tracked, and identical to the committed file on the default branch of `origin`. The branch is found by full ref name only (`refs/remotes/origin/HEAD` when it points into `refs/remotes/origin/`, else `refs/remotes/origin/main`), so a tag or branch named `origin/HEAD` cannot stand in for it, and every lookup ignores replace refs. The committed blob's bytes are compared in Node with the working file: an exact match, or, when the blob has no CR, a match once the file's CRLF line ends become LF (a `core.autocrlf` checkout). No clean filter or `.gitattributes` setting applies. A local edit makes it a different script.
240
+ - The arguments match one listed shape exactly, word for word. A token is a literal, a list of literal alternatives, or a word with placeholders: `<repo>` (`owner/name`, each part starting with a letter or digit), `<int>`, `<sha>` (7 to 40 hex digits), `<word>` (a letter or digit, then letters, digits, `_.-`), `<url>` (a `https://github.com/` URL), `<file>` (a path with no pattern or `~` characters and not under `/dev/`, inside the working checkout or a temp or scratch root, that passes the usual read check), or `<text>` (any one argument, only as a whole word). Profiles hold no regular expressions.
241
+ - No argument the shell would expand: an unquoted `*`, `?` or `[`, or a leading `~`. Quote a literal pattern (`--reason '*'`).
242
+ - No environment prefix, wrapper (`env`, `command`), input redirect, standard input or pipe into it.
243
+
244
+ The default-branch check trusts the local remote-tracking refs, so the engine refuses local writes that could move them or what they show: `git update-ref` on anything but a plain `refs/heads/*` or `refs/tags/*` name that is not a symbolic ref (so not `refs/remotes/*`, `refs/replace/*` or `HEAD`), `update-ref --stdin` or `--no-deref`, `symbolic-ref` with a name or target under `refs/remotes/`, a fetch from `.`, a path or a `file:` URL, a fetch whose refspec writes `refs/remotes/<remote>/<branch>` from anything but that branch of that configured remote, `--refmap`, and a push to `.` or a local path. (`remotes/<r>/<b>` counts as `refs/remotes/<r>/<b>`.) To keep the origin honest it also refuses `git remote add`, `set-url`, `rename`, `set-branches`, `remove` and `set-head`; `git config` writes outside a short list of safe keys, which covers `remote.*`, `url.*` and `include*`; `git clone` with `-c`/`--config`, `-o`/`--origin`, `--template`, `--separate-git-dir` or `--upload-pack`; and `git init --template` or `--separate-git-dir`. Direct writes into `.git/config`, `.git/worktrees/*/config` and `config.worktree` are refused as protected paths. A normal `git fetch origin [main | +pull/N/head:prN]`, and a plain clone from the listed remote, stay approved.
245
+
246
+ **This is an audit label, not yet a security boundary.** In a worktree the engine approves `node <script>` for a script it does not list without reading it ([#48](https://github.com/agent-corpus/tools/issues/48)), so an agent could run an unlisted script that reads the same secret. Until #48 lands, a helper approval records which listed helper ran; it does not stop an unlisted one.
247
+
248
+ Every other command in the same script is judged as usual. A script with a listed file name that fails any check (changed, untracked, outside a checkout, a symlink, other arguments) goes to a person as a credential read. A listed helper counts as creating no symlink, so a later temp write in the same script stays approvable. An entry's path must be repository-relative with `/` separators and no `.` or `..` segments; the list holds at most 20 helpers of 50 shapes each, and an invalid entry makes the profile invalid (strict).
249
+
218
250
  #### MCP read-only tools
219
251
 
220
252
  `mcpReadOnly` lists MCP tools that run without a prompt, in any `mode`. Each entry is an exact `mcp__<server>__<tool>` name, or a name whose tool segment ends in `*` (`mcp__docs__search_*`). Neither segment may contain `__`, and a wildcard approves only a tool whose whole tool segment (after `mcp__<server>__`) is free of `__`, so it cannot reach another server such as `github__get`. Whole-server wildcards (`mcp__github__*`), regular expressions and other tool names are rejected, and the list holds at most 200 entries of 128 characters. List only tools that cannot change anything and cannot return credentials: the tool name is all the engine checks, not the arguments. Prefer exact names. A prefix also covers tools that a server adds later, and read-looking prefixes can include secret readers: the GitHub server's `get_*` and `list_*` cover its secret-scanning alert tools, which return the detected secret.
package/dist/flow.js CHANGED
@@ -18,8 +18,12 @@ const MAX_VARIANTS = 16;
18
18
  const MAX_SUBSTITUTION_DEPTH = 3;
19
19
  /** Commands one script may be judged as; past this it is too large to verify in time. */
20
20
  const MAX_JUDGEMENTS = 400;
21
- /** No whitespace, glob, quote, expansion or tilde characters: the value is exactly one word. */
22
- const SIMPLE_VALUE = /^[A-Za-z0-9_@%+=:,./-]+$/;
21
+ /**
22
+ * No whitespace, glob, quote or expansion characters: the value is exactly one word. A `~` is
23
+ * allowed only right after a letter or digit, where no shell expands it (a Windows short name
24
+ * such as `RUNNER~1`); at the start or after `=` or `:` it would become a home directory.
25
+ */
26
+ const SIMPLE_VALUE = /^(?:[A-Za-z0-9_@%+=:,./-]|(?<=[A-Za-z0-9])~)+$/;
23
27
  const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
24
28
  const UNSUPPORTED = "Unsupported shell syntax; expansions and subshells need human review";
25
29
  const MAX_CALL_DEPTH = 4;
@@ -557,6 +561,7 @@ function runSimple(ctx, node, state, stage, piped) {
557
561
  redirects,
558
562
  subs: [],
559
563
  loose,
564
+ glob: node.argv.map((word) => word.glob === true),
560
565
  ...(stdin === undefined ? {} : { stdin }),
561
566
  };
562
567
  };
@@ -646,7 +651,13 @@ function runSimple(ctx, node, state, stage, piped) {
646
651
  if (decision.decision !== "approve")
647
652
  return decision;
648
653
  ctx.box.last = decision;
649
- if (!symlinkFree(unwrap(command.argv).argv)) {
654
+ if (decision.credentialHelpers?.length) {
655
+ ctx.box.helpers ??= new Set();
656
+ for (const helper of decision.credentialHelpers)
657
+ ctx.box.helpers.add(helper);
658
+ }
659
+ // A listed credential helper only reads a secret and talks to its service.
660
+ if (!decision.credentialHelpers?.length && !symlinkFree(unwrap(command.argv).argv)) {
650
661
  if (ctx.box.script.approved)
651
662
  return human(request, "unknown", "A command that can create symlinks may run before an approved temp path");
652
663
  ctx.box.script.tainted = true;
@@ -1420,7 +1431,9 @@ function cannotFail(ctx, node, state) {
1420
1431
  if (program !== "cd" || argv.length !== 2 || target === undefined || node !== ctx.box.first)
1421
1432
  return false;
1422
1433
  const path = target === "~" || target.startsWith("~/") ? join(homedir(), target.slice(1)) : target;
1423
- if (!path.startsWith("/") || /[*?[\]]/.test(path))
1434
+ // On Windows an absolute path starts with a drive (`C:/x` or `C:\x`), including the home directory.
1435
+ const absolute = path.startsWith("/") || (process.platform === "win32" && /^[A-Za-z]:[\\/]/.test(path));
1436
+ if (!absolute || /[*?[\]]/.test(path))
1424
1437
  return false;
1425
1438
  try {
1426
1439
  if (!statSync(path).isDirectory())
@@ -1541,6 +1554,11 @@ export function commandDecision(request, command, profile, depth = 0, start = [r
1541
1554
  vars: new Map(),
1542
1555
  funcs: new Map(),
1543
1556
  });
1544
- return refusal ?? ctx.box.last ?? human(request, "unknown", "Empty command");
1557
+ if (refusal)
1558
+ return refusal;
1559
+ const last = ctx.box.last ?? human(request, "unknown", "Empty command");
1560
+ return ctx.box.helpers?.size && last.decision === "approve"
1561
+ ? { ...last, credentialHelpers: [...ctx.box.helpers] }
1562
+ : last;
1545
1563
  }
1546
1564
  //# sourceMappingURL=flow.js.map
package/dist/grants.js CHANGED
@@ -143,7 +143,12 @@ export function grantScope(request, decision, profile) {
143
143
  /** What a session scope covers, in words the user can check before approving it. */
144
144
  export function scopeLabel(scope, profile) {
145
145
  if (scope.startsWith("protected:"))
146
- return `writes under ${scope.slice("protected:".length).split("\u0000").join(", ")}`;
146
+ return `writes ${scope
147
+ .slice("protected:".length)
148
+ .split("\u0000")
149
+ // A root that is a file (`AGENTS.md`) is written to; a directory, or one not made yet, under.
150
+ .map((root) => (existsSync(root) && !statSync(root).isDirectory() ? "to " : "under ") + root)
151
+ .join(", ")}`;
147
152
  if (scope.startsWith("pattern:")) {
148
153
  const [, indexes = "", ...checkout] = scope.split(":");
149
154
  const patterns = indexes
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Whether the working file is the committed blob: the same bytes, or, when the blob has no CR,
3
+ * the same bytes once the working file's CRLF line ends become LF (a `core.autocrlf` checkout).
4
+ * No clean filter or `.gitattributes` setting is applied.
5
+ */
6
+ export declare function sameContent(working: Buffer, blob: Buffer): boolean;
7
+ /**
8
+ * A script allowed to read a credential for one narrow job, such as posting a review as a GitHub
9
+ * App. It is trusted only as committed on the default branch and only with the argument shapes
10
+ * listed for it; anything else stays with a person.
11
+ */
12
+ export interface CredentialHelper {
13
+ /** Repository-relative path with `/` separators, such as `tools/review-bot.mjs`. */
14
+ path: string;
15
+ /**
16
+ * Accepted argument lists after the script. Each token is a literal, a list of literal
17
+ * alternatives, or a string with placeholders (`repos/<repo>/pulls/<int>/reviews`).
18
+ */
19
+ args: Array<Array<string | string[]>>;
20
+ /**
21
+ * Where the helper's checkout must come from: normalized `host/owner/` prefixes (or a whole
22
+ * `host/owner/repo`) that `remote.origin.url` must match, such as `github.com/example-org/`.
23
+ */
24
+ remotes: string[];
25
+ }
26
+ export declare class HelperError extends Error {
27
+ }
28
+ /**
29
+ * `host/path` for an https, ssh or scp-style (`git@host:path`) URL, with the host and path in
30
+ * lower case and any `.git` and trailing `/` removed. Anything else (a local path, `file:`) is
31
+ * undefined: its content does not come from a hosted remote.
32
+ */
33
+ export declare function normalizeRemote(url: string): string | undefined;
34
+ export declare const MAX_HELPERS = 20;
35
+ /** Index of the first shape `args` matches, with the `<file>` values it named. */
36
+ export declare function matchShape(helper: CredentialHelper, args: string[]): {
37
+ index: number;
38
+ files: string[];
39
+ } | undefined;
40
+ /** Validates the profile's `credentialHelpers`. */
41
+ export declare function parseCredentialHelpers(raw: unknown): CredentialHelper[];
42
+ export type HelperMatch = {
43
+ kind: "none";
44
+ } | {
45
+ kind: "match";
46
+ helper: CredentialHelper;
47
+ shape: number;
48
+ files: string[];
49
+ } | {
50
+ kind: "refused";
51
+ reason: string;
52
+ };
53
+ /**
54
+ * Whether `node <script> args...` runs a listed helper. `none`: the script is not a listed helper.
55
+ * `refused`: it is at a listed helper's path but is changed, untracked, linked or run with other
56
+ * arguments, so a person decides. `match`: the committed helper with an accepted shape.
57
+ */
58
+ export declare function helperMatch(helpers: CredentialHelper[], cwd: string, argv: string[]): HelperMatch;
59
+ //# sourceMappingURL=helpers.d.ts.map
@@ -0,0 +1,304 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { git } from "./evidence.js";
5
+ /** Git with replace refs ignored, so `refs/replace/*` cannot change what is read. */
6
+ const exact = (top, args) => git(top, ["--no-replace-objects", ...args]);
7
+ /** The raw bytes of a blob, with replace refs ignored and no filters applied. */
8
+ function blobBytes(top, oid) {
9
+ return execFileSync("git", ["-c", "core.fsmonitor=false", "-C", top, "--no-replace-objects", "cat-file", "blob", oid], {
10
+ timeout: 3000,
11
+ maxBuffer: 4 * 1024 * 1024,
12
+ stdio: ["ignore", "pipe", "ignore"],
13
+ env: Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))),
14
+ });
15
+ }
16
+ /**
17
+ * Whether the working file is the committed blob: the same bytes, or, when the blob has no CR,
18
+ * the same bytes once the working file's CRLF line ends become LF (a `core.autocrlf` checkout).
19
+ * No clean filter or `.gitattributes` setting is applied.
20
+ */
21
+ export function sameContent(working, blob) {
22
+ if (working.equals(blob))
23
+ return true;
24
+ if (blob.includes(0x0d))
25
+ return false;
26
+ return Buffer.from(working.toString("latin1").replace(/\r\n/g, "\n"), "latin1").equals(blob);
27
+ }
28
+ export class HelperError extends Error {
29
+ }
30
+ /** A remote prefix: a lowercase host, then at least an owner; a trailing `/` makes it a prefix. */
31
+ const REMOTE_PREFIX = /^[a-z0-9][a-z0-9.-]*(?::[0-9]{1,5})?(?:\/[a-z0-9][a-z0-9_.-]*)+\/?$/;
32
+ /**
33
+ * `host/path` for an https, ssh or scp-style (`git@host:path`) URL, with the host and path in
34
+ * lower case and any `.git` and trailing `/` removed. Anything else (a local path, `file:`) is
35
+ * undefined: its content does not come from a hosted remote.
36
+ */
37
+ export function normalizeRemote(url) {
38
+ let host;
39
+ let path;
40
+ const full = /^(?:https|ssh|git\+ssh):\/\/(?:[^@/\s]+@)?([^/:\s]+)(?::[0-9]{1,5})?\/(.+)$/i.exec(url);
41
+ const scp = /^(?:[^@/\s:]+@)?([^/:\s]+):(?!\/)(.+)$/.exec(url);
42
+ if (full?.[1] && full[2])
43
+ [host, path] = [full[1], full[2]];
44
+ else if (scp?.[1] && scp[2] && !/^[A-Za-z]$/.test(scp[1]))
45
+ [host, path] = [scp[1], scp[2]];
46
+ else
47
+ return undefined;
48
+ path = path
49
+ .replace(/\/+$/, "")
50
+ .replace(/\.git$/i, "")
51
+ .replace(/\/+$/, "");
52
+ const segments = path.split("/");
53
+ if (!segments.length || segments.some((s) => !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(s)))
54
+ return undefined;
55
+ return `${host}/${path}`.toLowerCase();
56
+ }
57
+ function remoteMatches(remotes, normalized) {
58
+ return remotes.some((prefix) => prefix.endsWith("/") ? normalized.startsWith(prefix) : normalized === prefix);
59
+ }
60
+ export const MAX_HELPERS = 20;
61
+ const MAX_SHAPES = 50;
62
+ const MAX_TOKENS = 40;
63
+ const MAX_WORD = 1024;
64
+ /** Placeholder values. Each is checked whole; none may contain whitespace. */
65
+ const PLACEHOLDERS = {
66
+ // Each segment starts with a letter or digit, so neither is `.` or `..`.
67
+ repo: (v) => /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(v),
68
+ int: (v) => /^[0-9]{1,12}$/.test(v),
69
+ sha: (v) => /^[0-9a-f]{7,40}$/.test(v),
70
+ word: (v) => /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(v),
71
+ url: (v) => /^https:\/\/github\.com\/[A-Za-z0-9_./#-]{1,300}$/.test(v),
72
+ // No pattern characters, no tilde the shell expands, and no device file such as /dev/stdin. The caller also checks
73
+ // where the file is and that it may be read.
74
+ file: (v) => v.length > 0 &&
75
+ !/[*?[\]{}]/.test(v) &&
76
+ // `~` only right after a letter or digit (a Windows short name such as RUNNER~1).
77
+ !/(?:^|[^A-Za-z0-9])~/.test(v) &&
78
+ !/^\/dev\//.test(v),
79
+ // Any one argument; the caller refuses one the shell would expand.
80
+ text: () => true,
81
+ };
82
+ function parts(token) {
83
+ const out = [];
84
+ let rest = token;
85
+ while (rest.length) {
86
+ const open = rest.indexOf("<");
87
+ const close = open < 0 ? -1 : rest.indexOf(">", open);
88
+ const name = close < 0 ? undefined : rest.slice(open + 1, close);
89
+ if (open < 0 || name === undefined || !(name in PLACEHOLDERS)) {
90
+ if (open >= 0 && close >= 0)
91
+ throw new HelperError(`unknown placeholder in ${token}`);
92
+ out.push({ literal: rest });
93
+ break;
94
+ }
95
+ if (open > 0)
96
+ out.push({ literal: rest.slice(0, open) });
97
+ out.push({ placeholder: name });
98
+ rest = rest.slice(close + 1);
99
+ }
100
+ if (out.some((part, i) => i > 0 && "placeholder" in part && "placeholder" in (out[i - 1] ?? {})))
101
+ throw new HelperError(`adjacent placeholders in ${token}`);
102
+ if (out.some((p) => "placeholder" in p && p.placeholder === "text") && out.length > 1)
103
+ throw new HelperError(`<text> must be a whole argument in ${token}`);
104
+ return out;
105
+ }
106
+ /** Matches `word` against a token's parts; `files` collects the values of `<file>` placeholders. */
107
+ function matchParts(list, word, files) {
108
+ const [head, ...rest] = list;
109
+ if (!head)
110
+ return word.length === 0;
111
+ if ("literal" in head)
112
+ return (word.startsWith(head.literal) && matchParts(rest, word.slice(head.literal.length), files));
113
+ const check = PLACEHOLDERS[head.placeholder];
114
+ if (!check)
115
+ return false;
116
+ const next = rest[0];
117
+ // A placeholder ends at the end of the word or right before the next literal.
118
+ for (let end = word.length; end >= 1; end--) {
119
+ if (next && "literal" in next && !word.startsWith(next.literal, end))
120
+ continue;
121
+ if (!next && end !== word.length)
122
+ continue;
123
+ const value = word.slice(0, end);
124
+ if (!check(value))
125
+ continue;
126
+ const found = [];
127
+ if (matchParts(rest, word.slice(end), found)) {
128
+ if (head.placeholder === "file")
129
+ files.push(value);
130
+ files.push(...found);
131
+ return true;
132
+ }
133
+ }
134
+ return false;
135
+ }
136
+ function matchToken(token, word, files) {
137
+ if (Array.isArray(token))
138
+ return token.includes(word);
139
+ return matchParts(parts(token), word, files);
140
+ }
141
+ /** Index of the first shape `args` matches, with the `<file>` values it named. */
142
+ export function matchShape(helper, args) {
143
+ if (args.some((word) => word.length > MAX_WORD))
144
+ return undefined;
145
+ for (const [index, shape] of helper.args.entries()) {
146
+ if (shape.length !== args.length)
147
+ continue;
148
+ const files = [];
149
+ if (shape.every((token, i) => matchToken(token, args[i] ?? "", files)))
150
+ return { index, files };
151
+ }
152
+ return undefined;
153
+ }
154
+ /** Validates the profile's `credentialHelpers`. */
155
+ export function parseCredentialHelpers(raw) {
156
+ if (raw === undefined)
157
+ return [];
158
+ if (!Array.isArray(raw) || raw.length > MAX_HELPERS)
159
+ throw new HelperError(`credentialHelpers must list at most ${MAX_HELPERS} helpers`);
160
+ return raw.map((entry) => {
161
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
162
+ throw new HelperError("each credential helper must be an object");
163
+ const { path, args, remotes, ...extra } = entry;
164
+ if (!Array.isArray(remotes) ||
165
+ remotes.length === 0 ||
166
+ remotes.length > 20 ||
167
+ remotes.some((r) => typeof r !== "string" || r.length > 200 || !REMOTE_PREFIX.test(r)))
168
+ throw new HelperError("each credential helper needs remotes: lowercase host/owner/ prefixes such as github.com/org/");
169
+ if (Object.keys(extra).length)
170
+ throw new HelperError(`unknown credential helper key: ${Object.keys(extra)[0]}`);
171
+ if (typeof path !== "string" ||
172
+ path.length > 300 ||
173
+ !/^[A-Za-z0-9_.@-]+(?:\/[A-Za-z0-9_.@-]+)*$/.test(path) ||
174
+ path.split("/").some((part) => part === "." || part === ".."))
175
+ throw new HelperError("a credential helper path must be repository-relative, with / separators");
176
+ if (!Array.isArray(args) || args.length === 0 || args.length > MAX_SHAPES)
177
+ throw new HelperError(`credential helper ${path} must list 1 to ${MAX_SHAPES} argument shapes`);
178
+ for (const shape of args) {
179
+ if (!Array.isArray(shape) || shape.length === 0 || shape.length > MAX_TOKENS)
180
+ throw new HelperError(`each argument shape of ${path} must list 1 to ${MAX_TOKENS} tokens`);
181
+ for (const token of shape) {
182
+ if (Array.isArray(token)) {
183
+ if (token.length === 0 ||
184
+ token.some((t) => typeof t !== "string" || t.length === 0 || t.length > 200))
185
+ throw new HelperError(`alternatives in ${path} must be non-empty strings`);
186
+ }
187
+ else if (typeof token !== "string" || token.length === 0 || token.length > 300)
188
+ throw new HelperError(`a token in ${path} must be a non-empty string`);
189
+ else
190
+ parts(token);
191
+ }
192
+ }
193
+ return { path, args: args, remotes: remotes };
194
+ });
195
+ }
196
+ /**
197
+ * The default branch on `origin`, by full ref name only, so a tag or branch called `origin/HEAD`
198
+ * cannot stand in for it: `refs/remotes/origin/HEAD` when it points into `refs/remotes/origin/`,
199
+ * else `refs/remotes/origin/main`.
200
+ */
201
+ function defaultRef(top) {
202
+ const candidates = [];
203
+ try {
204
+ const target = exact(top, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]);
205
+ if (/^refs\/remotes\/origin\/[^\s]+$/.test(target) && target !== "refs/remotes/origin/HEAD")
206
+ candidates.push(target);
207
+ }
208
+ catch {
209
+ /* no origin/HEAD */
210
+ }
211
+ candidates.push("refs/remotes/origin/main");
212
+ for (const ref of candidates)
213
+ try {
214
+ // `show-ref --verify` takes only a full name and never falls back to a shorter match.
215
+ exact(top, ["show-ref", "--verify", "--quiet", ref]);
216
+ return ref;
217
+ }
218
+ catch {
219
+ /* try the next */
220
+ }
221
+ return undefined;
222
+ }
223
+ /**
224
+ * Whether `node <script> args...` runs a listed helper. `none`: the script is not a listed helper.
225
+ * `refused`: it is at a listed helper's path but is changed, untracked, linked or run with other
226
+ * arguments, so a person decides. `match`: the committed helper with an accepted shape.
227
+ */
228
+ export function helperMatch(helpers, cwd, argv) {
229
+ const program = basename(argv[0] ?? "").toLowerCase();
230
+ const script = argv[1];
231
+ if (!helpers.length || (program !== "node" && program !== "node.exe") || script === undefined)
232
+ return { kind: "none" };
233
+ // Matched by file name first, then by where it really is, so any way of naming it is checked.
234
+ const named = helpers.filter((h) => basename(script) === basename(h.path));
235
+ if (!named.length)
236
+ return { kind: "none" };
237
+ const refused = (reason) => ({ kind: "refused", reason });
238
+ let real;
239
+ let top;
240
+ try {
241
+ const lexical = resolve(cwd, script);
242
+ if (lstatSync(lexical).isSymbolicLink())
243
+ return refused("Credential helper is a symlink");
244
+ real = realpathSync.native(lexical);
245
+ if (!lstatSync(real).isFile())
246
+ return refused("Credential helper is not a regular file");
247
+ top = realpathSync.native(git(dirname(real), ["rev-parse", "--show-toplevel"]));
248
+ }
249
+ catch {
250
+ return refused("Credential helper is not inside a Git checkout");
251
+ }
252
+ const helper = named.find((h) => join(top, ...h.path.split("/")) === real);
253
+ if (!helper)
254
+ return refused("Credential helper is not at its listed path in the checkout");
255
+ try {
256
+ git(top, ["ls-files", "--error-unmatch", "--", helper.path]);
257
+ }
258
+ catch {
259
+ return refused("Credential helper is not tracked");
260
+ }
261
+ // A clone or `git init` anywhere has its own origin; only a checkout whose origin is a listed
262
+ // hosted remote, read as configured and as git resolves it, can vouch for the helper.
263
+ let origin;
264
+ try {
265
+ const configured = git(top, ["config", "--get", "remote.origin.url"]);
266
+ const resolved = git(top, ["remote", "get-url", "origin"]);
267
+ let pushUrl = "";
268
+ try {
269
+ pushUrl = git(top, ["config", "--get", "remote.origin.pushurl"]);
270
+ }
271
+ catch {
272
+ /* no push URL */
273
+ }
274
+ if (configured === resolved && !pushUrl)
275
+ origin = normalizeRemote(configured);
276
+ }
277
+ catch {
278
+ origin = undefined;
279
+ }
280
+ if (!origin || !remoteMatches(helper.remotes, origin))
281
+ return refused("Credential helper's checkout does not come from a listed remote");
282
+ const ref = defaultRef(top);
283
+ if (!ref)
284
+ return refused("Credential helper's default branch is unknown");
285
+ let committed;
286
+ let current;
287
+ try {
288
+ const oid = exact(top, ["rev-parse", "--verify", "--quiet", `${ref}:${helper.path}`]);
289
+ if (!/^[0-9a-f]{40,64}$/.test(oid))
290
+ throw new Error("not a blob id");
291
+ committed = blobBytes(top, oid);
292
+ current = readFileSync(real);
293
+ }
294
+ catch {
295
+ return refused("Credential helper is not on the default branch");
296
+ }
297
+ if (!sameContent(current, committed))
298
+ return refused("Credential helper differs from the default branch");
299
+ const shape = matchShape(helper, argv.slice(2));
300
+ if (!shape)
301
+ return refused("Credential helper run with arguments outside its allowed shapes");
302
+ return { kind: "match", helper, shape: shape.index, files: shape.files };
303
+ }
304
+ //# sourceMappingURL=helpers.js.map
@@ -2,6 +2,7 @@ import { lstatSync, readdirSync, statSync } from "node:fs";
2
2
  import { basename, delimiter, dirname, join, resolve } from "node:path";
3
3
  import { branchEvidence, canonical, disposable, git, inside, isProtectedPath, OUTSIDE_REPOSITORY, pathEvidence, policyState, protectedPath, resolveWord, sensitive, tempRoots, tempWrite, } from "./evidence.js";
4
4
  import { commandDecision } from "./flow.js";
5
+ import { helperMatch } from "./helpers.js";
5
6
  import { mergedEvidence, remoteTipMatches } from "./merged.js";
6
7
  import { evaluateArgv, result } from "./policy.js";
7
8
  import { deletesProtected, deletionScriptCwd, gitRmRecoverable, resetRecoverable, restoreRecoverable, rmRecoverable, soleEffect, worktreeDeletion, } from "./recoverable.js";
@@ -867,6 +868,14 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
867
868
  const ok = (reason = "Permissive profile: Git operation has no destructive effect") => result(request, "impactful-write", reason, true);
868
869
  if (!sub)
869
870
  return ok();
871
+ const refWrite = remoteRefWrite(cwd, sub, rest);
872
+ if (refWrite)
873
+ return human(request, "sensitive", refWrite);
874
+ if ((sub === "clone" || sub === "init") &&
875
+ rest.some((word) => CLONE_CONFIG.some((option) => word === option || abbreviates(word, option)) ||
876
+ /^-c./.test(word) ||
877
+ (sub === "clone" && /^-[A-Za-z]*[cou]/.test(word) && !word.startsWith("--"))))
878
+ return human(request, "sensitive", `git ${sub} with a configuration, origin, template or separate git directory requires human approval`);
870
879
  if (sub === "push")
871
880
  return gitPush(request, cwd, rest);
872
881
  if (sub === "branch" && (has("-d", "-D", "--delete") || cluster("d") || cluster("D"))) {
@@ -934,10 +943,119 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
934
943
  !safeConfigWrite(rest))
935
944
  return human(request, "sensitive", "Git configuration can install hooks or credential helpers");
936
945
  if (sub === "remote" &&
937
- ["set-url", "remove", "rm", "rename", "set-head"].includes(positional[0] ?? ""))
946
+ ["add", "set-url", "remove", "rm", "rename", "set-head", "set-branches"].includes(positional[0] ?? ""))
938
947
  return human(request, "impactful-write", "Changing remotes requires human approval");
939
948
  return ok();
940
949
  }
950
+ /**
951
+ * `git clone`/`init` options that set the new repository's configuration or origin, or run a
952
+ * program: a credential helper trusts a checkout by its configured origin.
953
+ */
954
+ const CLONE_CONFIG = ["--config", "--origin", "--template", "--separate-git-dir", "--upload-pack"];
955
+ /** Whether a credential helper's file argument lies in the working checkout or a temp/scratch root. */
956
+ function helperFileAllowed(cwd, file, profile) {
957
+ let path;
958
+ try {
959
+ path = canonical(resolveWord(cwd, file));
960
+ }
961
+ catch {
962
+ return false;
963
+ }
964
+ const roots = [...profile.scratchRoots, ...tempRoots()];
965
+ try {
966
+ roots.push(canonical(git(cwd, ["rev-parse", "--show-toplevel"])));
967
+ }
968
+ catch {
969
+ /* not in a checkout: temp and scratch roots only */
970
+ }
971
+ return roots.some((root) => inside(canonical(root), path));
972
+ }
973
+ /** A fetch or push target that is this machine, not a remote: `.`, a path, or a `file:` URL. */
974
+ function localRepository(word) {
975
+ return (word === "." ||
976
+ word === ".." ||
977
+ word.startsWith("/") ||
978
+ word.startsWith("./") ||
979
+ word.startsWith("../") ||
980
+ word.startsWith("~") ||
981
+ word.startsWith("\\") ||
982
+ /^[A-Za-z]:/.test(word) ||
983
+ /^file:/i.test(word) ||
984
+ (!word.includes(":") && word.includes("/")));
985
+ }
986
+ /** Remote names configured in the repository, read locally. */
987
+ function configuredRemotes(cwd) {
988
+ try {
989
+ return new Set(git(cwd, ["remote"]).split("\n").filter(Boolean));
990
+ }
991
+ catch {
992
+ return undefined;
993
+ }
994
+ }
995
+ /**
996
+ * A local write that moves a remote-tracking ref. Remote-tracking refs are this policy's evidence
997
+ * of what a remote holds (merged branches, unchanged credential helpers), so only fetching the
998
+ * same branch from its own configured remote may move them.
999
+ */
1000
+ function remoteRefWrite(cwd, sub, rest) {
1001
+ const positional = rest.filter((word) => !word.startsWith("-"));
1002
+ const remoteRef = (word) => /^(?:\+)?refs\/remotes\//.test(word);
1003
+ const why = "Moving a remote-tracking ref locally requires human approval";
1004
+ if (sub === "update-ref") {
1005
+ // Only a plain branch or tag, named in full, that is not a symbolic ref: anything else could
1006
+ // move a remote-tracking ref, a replace ref, or whatever HEAD points to.
1007
+ const name = positional[0] ?? "";
1008
+ if (rest.some((w) => w === "--stdin" || w.startsWith("--no-deref")) ||
1009
+ positional.some(remoteRef) ||
1010
+ !/^refs\/(?:heads|tags)\/[^\s]+$/.test(name))
1011
+ return "Updating a ref other than a plain branch or tag requires human approval";
1012
+ try {
1013
+ git(cwd, ["symbolic-ref", "--quiet", name]);
1014
+ return "Updating a ref through a symbolic ref requires human approval";
1015
+ }
1016
+ catch {
1017
+ return undefined;
1018
+ }
1019
+ }
1020
+ if (sub === "symbolic-ref") {
1021
+ const writes = positional.length > 1 || rest.some((w) => w === "-d" || w === "--delete");
1022
+ return writes && positional.some((w) => /^(?:refs\/)?remotes\//.test(w)) ? why : undefined;
1023
+ }
1024
+ if (sub === "push") {
1025
+ const remote = positional[0];
1026
+ return remote !== undefined && localRepository(remote)
1027
+ ? "Pushing to a local repository requires human approval"
1028
+ : undefined;
1029
+ }
1030
+ if (sub !== "fetch" && sub !== "pull")
1031
+ return undefined;
1032
+ if (rest.some((w) => w.startsWith("--refmap") || w === "--stdin"))
1033
+ return "A fetch with a custom ref map requires human approval";
1034
+ const remote = positional[0];
1035
+ if (remote === undefined)
1036
+ return undefined;
1037
+ if (localRepository(remote))
1038
+ return `A ${sub} from a local repository requires human approval`;
1039
+ const remotes = configuredRemotes(cwd);
1040
+ for (const spec of positional.slice(1)) {
1041
+ const colon = spec.indexOf(":");
1042
+ if (colon < 0)
1043
+ continue;
1044
+ const source = spec.slice(spec.startsWith("+") ? 1 : 0, colon);
1045
+ // Git also takes `remotes/<r>/<b>` as a short name for `refs/remotes/<r>/<b>`.
1046
+ const raw = spec.slice(colon + 1);
1047
+ const destination = raw.startsWith("remotes/") ? `refs/${raw}` : raw;
1048
+ if (!destination.startsWith("refs/remotes/"))
1049
+ continue;
1050
+ const [owner = "", ...branch] = destination.slice("refs/remotes/".length).split("/");
1051
+ const name = branch.join("/");
1052
+ if (owner !== remote ||
1053
+ !remotes?.has(remote) ||
1054
+ (source !== name && source !== `refs/heads/${name}`))
1055
+ return why;
1056
+ }
1057
+ return undefined;
1058
+ }
941
1059
  /**
942
1060
  * `git worktree add` from any clone is approved, except that the main checkout's working tree
943
1061
  * stays protected: a new worktree inside it must go under `.worktrees/` or `.claude/worktrees/`.
@@ -1633,6 +1751,34 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
1633
1751
  return human(request, "unknown", "wait with options requires human review");
1634
1752
  if (program === "set" && !args.every((word) => /^[-+][B-Za-z]+$|^pipefail$/.test(word)))
1635
1753
  return human(request, "unknown", "Changing shell settings requires human review");
1754
+ // A listed credential helper reads a secret for one narrow job. It runs only as committed on the
1755
+ // default branch, with an accepted argument shape, and with nothing changing its environment.
1756
+ const helper = helperMatch(profile.credentialHelpers, cwd, argv);
1757
+ if (helper.kind === "refused")
1758
+ return human(request, "sensitive", helper.reason);
1759
+ if (helper.kind === "match") {
1760
+ if (stageIndex > 0 ||
1761
+ command.stdin !== undefined ||
1762
+ command.redirects.some((r) => r.op === "<" || r.fd === "0") ||
1763
+ command.env.length > 0 ||
1764
+ unwrapped.env.length > 0 ||
1765
+ argv.length !== command.argv.length)
1766
+ return human(request, "sensitive", "A credential helper with a changed environment or input requires a person");
1767
+ // A pattern or `~` would let the shell turn one checked word into other words or files.
1768
+ if (argv.some((word, index) => index > 0 && (command.glob?.[index] === true || word.startsWith("~"))))
1769
+ return human(request, "sensitive", "A credential helper argument the shell would expand requires a person");
1770
+ for (const file of helper.files) {
1771
+ const check = permissiveRead(cwd, file);
1772
+ if (!check.allowed)
1773
+ return human(request, check.category, check.reason);
1774
+ if (!helperFileAllowed(cwd, file, profile))
1775
+ return human(request, "sensitive", "A credential helper may only send a file from this checkout or a temp directory");
1776
+ }
1777
+ return {
1778
+ ...result(request, "impactful-write", "Listed credential helper", true),
1779
+ credentialHelpers: [`${helper.helper.path}#${helper.shape}`],
1780
+ };
1781
+ }
1636
1782
  if (SHELLS.has(program) || INTERPRETERS.has(program)) {
1637
1783
  if (stageIndex > 0)
1638
1784
  return human(request, "unknown", "Piping into a shell or interpreter requires human review");
package/dist/profile.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type CredentialHelper } from "./helpers.js";
1
2
  /**
2
3
  * A profile is policy *data*. The engine's checks (protected paths, secret retrieval, verified
3
4
  * effects) are code and cannot be relaxed by a profile; a profile only chooses how much of the
@@ -25,6 +26,8 @@ export interface Profile {
25
26
  codex: string[];
26
27
  copilot: string[];
27
28
  };
29
+ /** Scripts that may read a credential for one narrow job, as committed on the default branch. */
30
+ credentialHelpers: CredentialHelper[];
28
31
  /** SHA-256 of the file the profile came from, for the audit log. */
29
32
  digest?: string;
30
33
  }
package/dist/profile.js CHANGED
@@ -3,6 +3,7 @@ import { lstatSync, readFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, isAbsolute, join } from "node:path";
5
5
  import { canonical, git } from "./evidence.js";
6
+ import { HelperError, parseCredentialHelpers } from "./helpers.js";
6
7
  import { TOOL_NAME } from "./tools.js";
7
8
  export const strictProfile = {
8
9
  mode: "strict",
@@ -11,6 +12,7 @@ export const strictProfile = {
11
12
  scratchRoots: [],
12
13
  mcpReadOnly: [],
13
14
  toolsDeny: { claude: [], codex: [], copilot: [] },
15
+ credentialHelpers: [],
14
16
  };
15
17
  export const MAX_MCP_READ_ONLY = 200;
16
18
  /**
@@ -96,6 +98,7 @@ export function parseProfile(text) {
96
98
  "scratchRoots",
97
99
  "mcpReadOnly",
98
100
  "toolsDeny",
101
+ "credentialHelpers",
99
102
  "description",
100
103
  ]);
101
104
  for (const key of Object.keys(value))
@@ -120,6 +123,15 @@ export function parseProfile(text) {
120
123
  mcp.some((entry) => typeof entry !== "string" || entry.length > 128 || !MCP_ENTRY.test(entry)))
121
124
  throw new ProfileError(`mcpReadOnly must list at most ${MAX_MCP_READ_ONLY} names like mcp__server__tool, optionally ending in *`);
122
125
  const toolsDeny = parseToolsDeny(value.toolsDeny);
126
+ let credentialHelpers;
127
+ try {
128
+ credentialHelpers = parseCredentialHelpers(value.credentialHelpers);
129
+ }
130
+ catch (error) {
131
+ if (error instanceof HelperError)
132
+ throw new ProfileError(error.message);
133
+ throw error;
134
+ }
123
135
  let humanPatterns;
124
136
  try {
125
137
  humanPatterns = patterns.map((p) => new RegExp(p));
@@ -143,6 +155,7 @@ export function parseProfile(text) {
143
155
  scratchRoots: value.mode === "permissive" ? [...scratchRoots] : [],
144
156
  mcpReadOnly: [...new Set(mcp)],
145
157
  toolsDeny,
158
+ credentialHelpers: value.mode === "permissive" ? credentialHelpers : [],
146
159
  digest: createHash("sha256").update(text).digest("hex"),
147
160
  };
148
161
  }
package/dist/shell.d.ts CHANGED
@@ -12,6 +12,8 @@ export interface SimpleCommand {
12
12
  subs: string[];
13
13
  /** For each argv word, whether it contains an unquoted unknown value (it could split). */
14
14
  loose?: boolean[];
15
+ /** For each argv word, whether it has an unquoted `*`, `?` or `[` the shell may expand. */
16
+ glob?: boolean[];
15
17
  /** Literal text fed to standard input by a heredoc or here-string, when there is one. */
16
18
  stdin?: string;
17
19
  }
package/dist/shell.js CHANGED
@@ -56,7 +56,7 @@ function plainSimple(command) {
56
56
  redirects.push(plain);
57
57
  subs.push(...(redir.target?.subs ?? []));
58
58
  }
59
- return { env, argv, redirects, subs, loose };
59
+ return { env, argv, redirects, subs, loose, glob: simple.argv.map((w) => w.glob === true) };
60
60
  }
61
61
  function flatten(andOr) {
62
62
  const pipelines = [];
package/dist/types.d.ts CHANGED
@@ -44,6 +44,8 @@ export interface Decision {
44
44
  sessionScopeLabel?: string;
45
45
  /** A harness tool approved by default (not a shell, file, patch or MCP tool), by name. */
46
46
  defaultTool?: string;
47
+ /** Listed credential helpers this request runs, as `<path>#<shape index>`. */
48
+ credentialHelpers?: string[];
47
49
  /** The agent tried to approve a request itself: no approval instruction is offered for it. */
48
50
  userOnly?: boolean;
49
51
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-corpus/policy-manager",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Deterministic, session-scoped permission decisions with audit logs and bounded AI classification.",
5
5
  "keywords": [
6
6
  "coding-agent",