audit-my-agents 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Agentic Control Plane
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # audit-my-agents
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ What did your coding agents actually do?
4
+
5
+ Paste this into Claude Code or Codex:
6
+
7
+ ```text
8
+ Run `npx audit-my-agents` and walk me through what it found.
9
+ ```
10
+
11
+ Or run it yourself:
12
+
13
+ ```bash
14
+ npx audit-my-agents
15
+ ```
16
+
17
+ It reads the session logs Claude Code and Codex already keep on your machine, and reports the calls you'd want to know about:
18
+
19
+ ```text
20
+ What your coding agents did in the last 30 days
21
+ Claude Code 48 sessions · Codex 6 sessions · 4,120 tool calls · 2,980 shell commands · $412 spent
22
+ ────────────────────────────────────────────────────────────────
23
+ ✓ Catastrophic commands none
24
+ ✗ Destructive commands 3 in 3 sessions
25
+ 2026-11-02 Claude Code: force-pushes over shared git history
26
+ git push --force origin main
27
+ ✗ Live secrets in tool calls 1 in 1 session
28
+ 2026-10-29 Codex: GitHub token
29
+ curl -H "Authorization: token [GitHub token]" https://api.github.com/…
30
+ ! Personal data the model read 6 in 2 sessions
31
+ 2026-10-30 Claude Code: card number in tool output
32
+ Visa card ending 8431
33
+ ! Credential files read 14 in 9 sessions
34
+ ! Your email sent to a site 2 in 1 session
35
+ ✓ Local data sent out none
36
+ · Pushes to a git remote 61 in 22 sessions
37
+ ────────────────────────────────────────────────────────────────
38
+ Reached 58 hosts. Most often: github.com (210), npmjs.org (96), pypi.org (40) …
39
+ ```
40
+
41
+ *(Illustrative output.)*
42
+
43
+ It's read-only. It makes no network calls, needs no account and installs no hooks. Nothing leaves your machine. It has no dependencies and needs Node 18 or later.
44
+
45
+ No npm? Clone the repo and run `node bin/agent-audit.mjs`. There is no install step.
46
+
47
+ ## What it looks for
48
+
49
+ | Finding | Examples |
50
+ |---|---|
51
+ | Catastrophic commands | `rm -rf` on `/`, `~` or `.`, `mkfs`, raw disk writes |
52
+ | Destructive commands | force-push, `DROP TABLE` / `TRUNCATE` / `DELETE` without `WHERE`, `curl … \| sh`, a recursive delete outside the project |
53
+ | Live secrets in tool calls | an API key or token passed in a command or tool input |
54
+ | Personal data the model read | a card number, a US Social Security number or someone else's email address in a prompt or in what a tool returned |
55
+ | Credential files read | `.env`, SSH keys, `~/.aws/credentials`, `.npmrc`, keychain reads |
56
+ | Local data sent out | `curl -d @file`, uploads, `scp` / `rsync` to a remote |
57
+ | Your email sent to a site | your git email in a User-Agent, From header or contact field |
58
+ | Sensitive files changed | shell startup files, SSH config and authorized_keys, git hooks, crontab, login items |
59
+ | Sessions with no approval prompts | Claude Code bypass mode, Codex never-ask with a full-access sandbox |
60
+
61
+ The destructive and catastrophic rules are the same open rules [Agentic Control Plane](https://agenticcontrolplane.com) enforces before a call runs. They're vendored from [acp-install](https://github.com/agentic-control-plane/acp-install). A finding here is a call that check would have held for your approval.
62
+
63
+ It skips text that's only written, searched for or described, not run. That covers a `curl | sh` inside an issue body, a `grep` for `git push --force`, a heredoc writing a test file, or a commit message. A heredoc fed to a shell or a SQL client is still checked. Placeholder keys like `sk-test-xxxx` aren't reported.
64
+
65
+ Personal data is counted once per distinct value, however many times the model read it. The rules lean toward missing something over flagging something that isn't personal:
66
+
67
+ - Not counted as someone's email: your own git email, role addresses like `support@` and `noreply@`, authors in a git log or a package manifest, ssh logins, and placeholder domains like `example.com`.
68
+ - A card number needs a real brand prefix, the right length and a valid checksum. Written without spaces, it also needs a word like "card" or "visa" nearby. Test cards published by payment providers aren't counted.
69
+ - A Social Security number is counted only when written with dashes and a nearby word says what it is.
70
+ - Phone numbers and street addresses aren't detected.
71
+
72
+ ## Running it from an agent
73
+
74
+ When a coding agent runs the audit, the agent is the reader. Inside Claude Code the report ends with a few plain notes for it: what to lead with, that the commands shown already ran and shouldn't be run again, and that the examples are redacted on purpose. Pass `--agent` to get the same notes anywhere else.
75
+
76
+ The agent only ever sees the redacted report. Personal data is shown as `d***@gmail.com`, `Visa card ending 8431` or `***-**-****`, with or without `--raw`.
77
+
78
+ ## Options
79
+
80
+ ```text
81
+ --days N look back N days (default 30)
82
+ --harness NAME claude or codex (repeatable)
83
+ --email ADDR also flag this address in outbound headers (git user.email is automatic)
84
+ --html FILE write a shareable HTML report
85
+ --json print the summary as JSON
86
+ --examples N examples per finding (default 3)
87
+ --raw show examples unredacted (local only; don't screenshot)
88
+ --agent add short notes for a coding agent relaying the report
89
+ ```
90
+
91
+ ## Privacy
92
+
93
+ - Examples are redacted by default, and the redaction errs toward hiding too much:
94
+ - Known key shapes become labels like `[GitHub token]`.
95
+ - Passwords in `-u`, `-p`, `--password` and URL userinfo, `NAME_TOKEN=`-style values, and long opaque strings become `[redacted]`.
96
+ - Email addresses become `[email]`, usernames become `[user]`, and home paths become `~`.
97
+ - Intranet and `.local` hostnames are never listed.
98
+ - The HTML export is always redacted.
99
+ - `--raw` prints full commands to your own terminal only. If an agent runs it, those commands go to the model, so leave it off there.
100
+ - Personal data is never printed in full, even with `--raw`.
101
+ - Redaction is pattern-based, so glance over a report before you post it.
102
+
103
+ ## Coverage
104
+
105
+ | Harness | Where it reads | Status |
106
+ |---|---|---|
107
+ | Claude Code | `~/.claude/projects/**/*.jsonl` | covered, including subagents |
108
+ | Codex CLI | `~/.codex/sessions/**/*.jsonl` | covered: shell, exec code mode, apply_patch |
109
+ | OpenCode | `~/.local/share/opencode/opencode.db` | not yet (SQLite) |
110
+ | Cursor, Copilot, Gemini CLI | — | not yet |
111
+
112
+ The session formats aren't documented by their vendors and can change. If a harness update breaks parsing, please open an issue.
113
+
114
+ ## Next step
115
+
116
+ This shows what already happened. To be asked before the next force-push, `DROP TABLE` or `curl | sh` runs, with the same rules in every harness, see [Agentic Control Plane](https://agenticcontrolplane.com/getting-started?ref=audit).
117
+
118
+ MIT licensed.
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ // audit-my-agents — what did your coding agents actually do?
3
+ //
4
+ // Reads the session logs Claude Code and Codex already keep on your
5
+ // machine and reports the risky calls. Read-only. Nothing leaves your
6
+ // machine.
7
+
8
+ import { writeFileSync } from "node:fs";
9
+ import { scan, SOURCES } from "../src/scan.mjs";
10
+ import { summarise, renderTerminal, renderHtml, renderAgentNotes } from "../src/report.mjs";
11
+
12
+ const HELP = `audit-my-agents — what did your coding agents actually do?
13
+
14
+ Usage: npx audit-my-agents [options]
15
+
16
+ --days N look back N days (default 30)
17
+ --harness NAME only scan one harness: ${Object.keys(SOURCES).join(", ")} (repeatable)
18
+ --email ADDR also flag this address in outbound headers (repeatable; git user.email is automatic)
19
+ --html FILE also write a shareable HTML report
20
+ --json print the summary as JSON
21
+ --examples N examples per finding (default 3)
22
+ --raw show examples unredacted (stays on your machine; don't screenshot)
23
+ --agent add short notes for a coding agent relaying the report (automatic inside Claude Code)
24
+ -h, --help this help
25
+ `;
26
+
27
+ const argv = process.argv.slice(2);
28
+ const opts = { days: 30, harnesses: [], emails: [], html: null, json: false, raw: false, examples: 3, agent: false };
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const a = argv[i];
31
+ const next = () => argv[++i];
32
+ if (a === "-h" || a === "--help") { process.stdout.write(HELP); process.exit(0); }
33
+ else if (a === "--days") {
34
+ const v = Number(next());
35
+ if (!Number.isFinite(v) || v <= 0) { process.stderr.write("--days needs a positive number\n"); process.exit(2); }
36
+ opts.days = v;
37
+ }
38
+ else if (a === "--harness") opts.harnesses.push(next());
39
+ else if (a === "--email") opts.emails.push(next());
40
+ else if (a === "--html") opts.html = next();
41
+ else if (a === "--json") opts.json = true;
42
+ else if (a === "--raw") opts.raw = true;
43
+ else if (a === "--agent") opts.agent = true;
44
+ else if (a === "--examples") opts.examples = Math.max(0, Number(next()) || 0);
45
+ else { process.stderr.write(`unknown option: ${a}\n\n${HELP}`); process.exit(2); }
46
+ }
47
+ const bad = opts.harnesses.filter((h) => !SOURCES[h]);
48
+ if (bad.length) { process.stderr.write(`unknown harness: ${bad.join(", ")}\n`); process.exit(2); }
49
+
50
+ const result = await scan({ days: opts.days, harnesses: opts.harnesses.length ? opts.harnesses : undefined, emails: opts.emails });
51
+ const summary = summarise(result, { raw: opts.raw, examples: opts.examples });
52
+ if (opts.json) process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
53
+ else {
54
+ process.stdout.write(renderTerminal(summary) + "\n");
55
+ // Inside a coding agent the reader is the agent; tell it how to relay this.
56
+ const inAgent = opts.agent || Boolean(process.env.CLAUDECODE || process.env.AI_AGENT || process.env.CODEX_SANDBOX || process.env.CURSOR_AGENT);
57
+ if (inAgent) process.stdout.write(renderAgentNotes(summary) + "\n");
58
+ }
59
+ if (opts.html) {
60
+ writeFileSync(opts.html, renderHtml(summarise(result, { raw: false, examples: opts.examples })));
61
+ process.stderr.write(`HTML report written to ${opts.html} (redacted)\n`);
62
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "audit-my-agents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "What did your coding agents actually do? One command reads your local Claude Code and Codex sessions and reports force-pushes, destructive commands, credential reads, leaked secrets and more.",
5
+ "type": "module",
6
+ "bin": {
7
+ "audit-my-agents": "bin/agent-audit.mjs",
8
+ "agent-audit": "bin/agent-audit.mjs"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test test/*.test.mjs"
21
+ },
22
+ "keywords": [
23
+ "claude-code",
24
+ "codex",
25
+ "coding-agent",
26
+ "audit",
27
+ "security",
28
+ "ai-agents"
29
+ ],
30
+ "license": "MIT",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/agentic-control-plane/agent-audit.git"
34
+ },
35
+ "homepage": "https://github.com/agentic-control-plane/agent-audit#readme",
36
+ "bugs": {
37
+ "url": "https://github.com/agentic-control-plane/agent-audit/issues"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }
@@ -0,0 +1,257 @@
1
+ // What counts as worth showing. Every rule is the replay of something a
2
+ // pre-tool check could have stopped; the floors come straight from ACP's
3
+ // open decision engine so a finding here is exactly a call ACP holds.
4
+
5
+ import { hardlineFloor, destructiveFloor, stripDataHeredocs } from "./vendor/decide.mjs";
6
+ import { detectIdentityEgress, identityTokens } from "./vendor/identity.mjs";
7
+ import { classifyHost, isInternalHostClass, displayHost } from "./vendor/net.mjs";
8
+ import { secretTypes } from "./redact.mjs";
9
+
10
+ export const CATEGORIES = [
11
+ { id: "catastrophic", title: "Catastrophic commands", severity: 3, blurb: "rm -rf on /, ~ or ., mkfs, raw disk writes" },
12
+ { id: "destructive", title: "Destructive commands", severity: 3, blurb: "force-push, destructive SQL, curl | sh, recursive delete outside the project" },
13
+ { id: "secret-in-args", title: "Live secrets in tool calls", severity: 3, blurb: "a real-looking key or token passed in a command or tool input" },
14
+ { id: "pii", title: "Personal data the model read", severity: 2, blurb: "card numbers, US Social Security numbers and other people's email addresses in prompts and tool output" },
15
+ { id: "credential-read", title: "Credential files read", severity: 2, blurb: ".env, SSH keys, cloud and registry credentials" },
16
+ { id: "upload", title: "Local data sent out", severity: 2, blurb: "a file or body uploaded to a host outside your machine" },
17
+ { id: "identity", title: "Your email sent to a site", severity: 2, blurb: "your address in a User-Agent, From header or contact field" },
18
+ { id: "sensitive-write", title: "Sensitive files changed", severity: 2, blurb: "shell startup files, SSH config, CI workflows, git hooks" },
19
+ { id: "unattended", title: "Sessions with no approval prompts", severity: 1, blurb: "Claude Code bypass mode, Codex never-ask + full-access sandbox" },
20
+ { id: "push", title: "Pushes to a git remote", severity: 1, blurb: "every git push the agent ran" },
21
+ ];
22
+
23
+ /** Commands longer than this are scanned on their first part only. */
24
+ const MAX_CMD = 50_000;
25
+
26
+ const SHELL = new Set(["Bash", "run_terminal_cmd", "shell"]);
27
+ const READ_TOOLS = new Set(["Read", "read_file", "View", "view"]);
28
+ const WRITE_TOOLS = new Set(["Write", "Edit", "MultiEdit", "create_file", "edit_file", "NotebookEdit"]);
29
+
30
+ const CREDENTIAL_PATH_RE = /(?:^|[\s/"'=])(?:\.env(?:\.(?!example\b|sample\b|template\b|dist\b)[\w.-]+)?|\.npmrc|\.pypirc|\.netrc|\.pgpass|\.git-credentials|\.aws\/credentials|\.aws\/config|\.ssh\/id_[a-z0-9]+(?!\.pub)|\.kube\/config|\.docker\/config\.json|\.config\/gcloud\/[\w./-]*credentials[\w.-]*|\.config\/gh\/hosts\.yml|[\w.-]*(?:key|private|id_)[\w.-]*\.pem|[\w.-]+\.p12|[\w.-]+\.pfx|[\w.-]+\.key|(?:gcp|google|firebase|aws)?[-_]?credentials\.json|service[-_]account[\w-]*\.json)(?=$|[\s"'`;|&)])/;
31
+ const NOT_A_SECRET_RE = /\.(?:example|sample|template|dist|tmpl|defaults?)(?=$|[\s"'`;|&)])/;
32
+ function credentialIn(text) {
33
+ const m = CREDENTIAL_PATH_RE.exec(text);
34
+ if (!m) return false;
35
+ const tail = text.slice(m.index, m.index + m[0].length + 40);
36
+ return !NOT_A_SECRET_RE.test(tail.split(/[\s"'`;|&)]/).filter(Boolean)[0] ?? "");
37
+ }
38
+ const DUMP_BINS = new Set(["cat", "head", "tail", "less", "more", "bat", "grep", "rg", "awk", "sed", "cp", "scp", "base64", "xxd", "strings", "source", ".", "open", "code", "vim", "nano"]);
39
+ const KEYCHAIN_RE = /\bsecurity\s+find-(?:generic|internet)-password\b[^|;&\n]*\s-w\b|\bgcloud\s+auth\s+print-access-token\b|\baws\s+configure\s+get\s+\S*secret/;
40
+ const SENSITIVE_WRITE_RE = /(?:^|\/)(?:\.(?:zshrc|bashrc|bash_profile|profile|zprofile|zshenv|bash_login)|\.ssh\/(?:config|authorized_keys|rc)|\.git\/hooks\/[^/]+|crontab|Library\/LaunchAgents\/[^/]+\.plist|\.config\/autostart\/[^/]+)$/;
41
+ const UPLOAD_RE = /\bcurl\b[^|;&\n]*(?:\s-(?:d|F|T)\s*@|\s--data(?:-binary|-raw)?[=\s]+@|\s--upload-file\b|\s-F\s+\S*=@)|\b(?:scp|rsync)\b[^|;&\n]*\s[\w.-]+@?[\w.-]+:\S|\bnc\s+[\w.-]+\s+\d+\s*<|\bgh\s+gist\s+create\b/;
42
+ const PUSH_RE = /\bgit\b(?:\s+-[cC]\s+\S+)*\s+push\b/;
43
+
44
+ /** What the shell would RUN: heredoc bodies and message-style arguments
45
+ * (--body, --title, -m …) are text being written or described, so a
46
+ * `curl | sh` inside an issue body or a test fixture is not a finding.
47
+ * Precision beats recall in a report people screenshot. */
48
+ export function executableText(cmd) {
49
+ // Data heredocs (cat > file <<EOF …) are content; heredocs fed to a shell
50
+ // or SQL client (bash <<EOF, psql <<SQL) stay, so their commands count.
51
+ let t = stripDataHeredocs(String(cmd ?? "").slice(0, MAX_CMD));
52
+ t = t.replace(/(--(?:body|title|notes|message|description|subject|comment|text|msg)|-[mb])(?:=|\s+)(?:"(?:[^"\\]|\\.){0,20000}"|'[^']{0,20000}'|\$\([^)]{0,20000}\)|\S+)/g, "$1 MSG");
53
+ return t;
54
+ }
55
+
56
+ /** Shell segments split at ; && || | and newlines, outside quotes (approx). */
57
+ function segments(t, depth = 0) {
58
+ const out = [];
59
+ for (const seg of splitOutsideQuotes(t, true)) {
60
+ out.push(seg);
61
+ // A quoted string handed to a shell runs: bash -c "…", ssh host "…",
62
+ // docker exec app sh -c "…".
63
+ if (depth < 2 && runsQuotedText(seg)) {
64
+ for (const q of quotedStrings(seg)) out.push(...segments(q, depth + 1));
65
+ }
66
+ }
67
+ return out;
68
+ }
69
+
70
+ const SHELL_RUNNERS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ssh", "eval", "xargs", "watch", "timeout", "su"]);
71
+ const SHELL_DASH_C_RE = /(?:^|[\s/])(?:ba|z|da|k)?sh\s+(?:-[A-Za-z]+\s+)*-[A-Za-z]*c\b/;
72
+ const REMOTE_RUN_RE = /(?:^|\s)(?:ssh|tmux\s+send-keys|screen\s+-\S*X)\s/;
73
+ function runsQuotedText(seg) {
74
+ return SHELL_RUNNERS.has(firstWord(seg)) || SHELL_DASH_C_RE.test(seg) || REMOTE_RUN_RE.test(seg);
75
+ }
76
+
77
+ /** Split at ; && || newline (and | when asked), ignoring separators inside
78
+ * single or double quotes. A `|` in a grep pattern is not a pipe.
79
+ * Comments are dropped first, so an apostrophe in `# don't` opens nothing.
80
+ * If the quotes still don't balance, the text is split the plain way: a
81
+ * stray quote must never hide the command after it. */
82
+ function splitOutsideQuotes(t, pipes) {
83
+ const s = String(t);
84
+ const out = [];
85
+ let cur = "";
86
+ let quote = "";
87
+ let ansi = false; // inside $'…', where backslash escapes
88
+ for (let i = 0; i < s.length; i++) {
89
+ const c = s[i];
90
+ if (quote) {
91
+ if (c === "\\" && (quote === '"' || ansi) && i + 1 < s.length) { cur += c + s[++i]; continue; }
92
+ if (c === quote) { quote = ""; ansi = false; }
93
+ cur += c;
94
+ continue;
95
+ }
96
+ if (c === "\\" && i + 1 < s.length) { cur += c + s[++i]; continue; }
97
+ if (c === "#" && (i === 0 || /\s/.test(s[i - 1]))) {
98
+ const nl = s.indexOf("\n", i);
99
+ if (nl === -1) break;
100
+ i = nl - 1;
101
+ continue;
102
+ }
103
+ if (c === '"' || c === "'") { quote = c; ansi = c === "'" && s[i - 1] === "$"; cur += c; continue; }
104
+ const two = s.slice(i, i + 2);
105
+ if (two === "&&" || two === "||") { out.push(cur); cur = ""; i++; continue; }
106
+ if (c === "\n" || c === ";" || (pipes && c === "|")) { out.push(cur); cur = ""; continue; }
107
+ cur += c;
108
+ }
109
+ if (quote) return s.split(pipes ? /\n|;|&&|\|\||\|/ : /\n|;|&&|\|\|/).map((x) => x.trim()).filter(Boolean);
110
+ out.push(cur);
111
+ return out.map((x) => x.trim()).filter(Boolean);
112
+ }
113
+
114
+ function quotedStrings(seg) {
115
+ const out = [];
116
+ const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'/g;
117
+ let m;
118
+ while ((m = re.exec(seg)) !== null) out.push(m[1] !== undefined ? m[1].replace(/\\(["\\$`])/g, "$1") : m[2]);
119
+ return out;
120
+ }
121
+
122
+ function firstWord(seg) {
123
+ const toks = seg.split(/\s+/);
124
+ let i = 0;
125
+ while (i < toks.length && (/^[A-Za-z_]\w*=/.test(toks[i]) || /^(?:sudo|env|command|exec|nohup|time)$/.test(toks[i]))) i++;
126
+ const w = toks[i] ?? "";
127
+ return w.slice(w.lastIndexOf("/") + 1);
128
+ }
129
+
130
+ /** The engine reads the whole command line; a report people screenshot
131
+ * needs the matching command to be the one actually run. A force-push
132
+ * needs a git segment that pushes with force; a pipe-to-shell needs a
133
+ * curl/wget segment piped into a shell. `grep 'git push --force'` and
134
+ * `echo "curl x | sh"` are not findings. */
135
+ function backedBySegment(reason, run) {
136
+ if (/force-push/.test(reason)) return Boolean(forcePushSegment(run));
137
+ return backedByPipe(reason, run);
138
+ }
139
+
140
+ /** The segment that pushes with force, or null. A repository created by
141
+ * the same command has no shared history to overwrite. */
142
+ function forcePushSegment(run) {
143
+ const segs = segments(run);
144
+ if (segs.some((seg) => firstWord(seg) === "git" && /\sinit(?:\s|$)/.test(seg))) return null;
145
+ return segs.find((seg) => firstWord(seg) === "git" && /\bpush\b/.test(seg) && /(?:\s--force(?!-with-lease|-if-includes)\b|\s-[a-eg-zA-Z]*f[a-zA-Z]*(?=\s|$)|\s\+[^\s:]+)/.test(seg)) ?? null;
146
+ }
147
+
148
+ function backedByPipe(reason, run) {
149
+ if (/pipes a remote download/.test(reason)) {
150
+ const parts = splitOutsideQuotes(run, false).flatMap((p) => (runsQuotedText(p) ? [p, ...quotedStrings(p)] : [p]));
151
+ return parts.some((p) => {
152
+ const piped = splitOutsideQuotes(p, true);
153
+ for (let i = 0; i + 1 < piped.length; i++) {
154
+ if (/^(?:curl|wget)$/.test(firstWord(piped[i])) && /^(?:sudo\s+)?(?:\S*\/)?(?:ba|z|da|k)?sh\b/.test(piped[i + 1])) return true;
155
+ }
156
+ return /(?:^|\s)(?:ba|z)?sh\s+(?:-\w+\s+)*(?:-c\s+["']?\$\(\s*(?:curl|wget)|<\s*<?\s*\(\s*(?:curl|wget))/.test(p);
157
+ });
158
+ }
159
+ return true;
160
+ }
161
+
162
+ /** A segment without quoted arguments that cannot be a file path: a sed
163
+ * program, an awk script or a search pattern has regex characters, and `u.key)` inside one is code, not a key file. */
164
+ function pathArgs(seg) {
165
+ return seg.replace(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g, (m, dq, sq) => (/[|(){}*^\\]/.test(dq ?? sq ?? "") ? '""' : m));
166
+ }
167
+
168
+ function commandOf(ev) {
169
+ const i = ev.input;
170
+ if (i && typeof i === "object") {
171
+ if (typeof i.command === "string") return i.command;
172
+ if (typeof i.cmd === "string") return i.cmd;
173
+ }
174
+ return "";
175
+ }
176
+
177
+ function hostsIn(text) {
178
+ const out = [];
179
+ const re = /\bhttps?:\/\/(?:[^\s/?#@"'`]*@)?(\[[^\]\s]+\]|[^\s/:?#"'`)]+)/gi;
180
+ let m;
181
+ while ((m = re.exec(text)) !== null) {
182
+ const h = m[1].replace(/^\[|\]$/g, "").toLowerCase();
183
+ // A host the shell computes ($VAR, ${…}) or a placeholder is not a destination we know.
184
+ if (/[$`{}]/.test(h) || !h.includes(".")) continue;
185
+ if (!isInternalHostClass(classifyHost(h))) out.push(h);
186
+ }
187
+ return out;
188
+ }
189
+
190
+ /**
191
+ * Findings for one tool call. Returns [{ category, why, example }]; the
192
+ * example is the raw text, redacted later by the report.
193
+ */
194
+ export function findingsFor(ev, ctx) {
195
+ const out = [];
196
+ const cmd = commandOf(ev).slice(0, MAX_CMD);
197
+ const shellLike = SHELL.has(ev.tool) || (cmd && !READ_TOOLS.has(ev.tool) && !WRITE_TOOLS.has(ev.tool));
198
+ const shellInput = { command: cmd };
199
+
200
+ const run = executableText(cmd);
201
+ const runInput = { command: run };
202
+ if (shellLike && cmd) {
203
+ const hard = hardlineFloor("Bash", runInput);
204
+ if (hard) out.push({ category: "catastrophic", why: hard, example: cmd });
205
+ const destr = hard ? null : destructiveFloor("Bash", runInput, { cwd: ev.cwd });
206
+ // ACP records a variable-named rm without asking; so does this report.
207
+ if (destr && !/variable-named path/.test(destr) && backedBySegment(destr, run)) out.push({ category: "destructive", why: destr.replace(/:\s.*$/, ""), example: (/force-push/.test(destr) && forcePushSegment(run)) || cmd });
208
+ if (segments(run).some((seg) => DUMP_BINS.has(firstWord(seg)) && credentialIn(` ${pathArgs(seg)}`))) {
209
+ out.push({ category: "credential-read", why: "read a credential file in the shell", example: cmd });
210
+ }
211
+ if (KEYCHAIN_RE.test(run)) out.push({ category: "credential-read", why: "pulled a secret from the keychain or a cloud CLI", example: cmd });
212
+ const up = segments(run).find((seg) => UPLOAD_RE.test(seg));
213
+ if (up) {
214
+ const ext = hostsIn(up);
215
+ const remoteCopy = /^(?:scp|rsync)$/.test(firstWord(up));
216
+ if (ext.length || remoteCopy || /gh\s+gist/.test(up)) out.push({ category: "upload", why: ext.length ? `uploaded to ${displayHost(ext[0])}` : "copied files to a remote machine", example: cmd });
217
+ }
218
+ if (segments(run).some((seg) => firstWord(seg) === "git" && PUSH_RE.test(seg))) out.push({ category: "push", why: "git push", example: cmd });
219
+ }
220
+
221
+ if (READ_TOOLS.has(ev.tool)) {
222
+ const p = String(ev.input?.file_path ?? ev.input?.path ?? "");
223
+ if (p && credentialIn(` ${p}`)) out.push({ category: "credential-read", why: "read a credential file", example: p });
224
+ }
225
+ if (WRITE_TOOLS.has(ev.tool)) {
226
+ const p = String(ev.input?.file_path ?? ev.input?.path ?? "");
227
+ if (p && SENSITIVE_WRITE_RE.test(p)) out.push({ category: "sensitive-write", why: "changed a file that runs or authenticates on its own", example: p });
228
+ }
229
+
230
+ // Secrets: anything the call carries. Write/Edit content is the user's
231
+ // own code more often than a leak, so only commands and non-file tools.
232
+ if (!WRITE_TOOLS.has(ev.tool)) {
233
+ let blob = run;
234
+ if (!blob) { try { blob = JSON.stringify(ev.input ?? ""); } catch { blob = ""; } }
235
+ const types = secretTypes(blob.slice(0, 200_000));
236
+ if (types.length) out.push({ category: "secret-in-args", why: types.join(", "), example: blob });
237
+ }
238
+
239
+ if (ctx.tokens.length || cmd) {
240
+ const id = detectIdentityEgress(ev.tool, ev.input, ctx.tokens);
241
+ if (id) out.push({ category: "identity", why: `${id.what} to ${id.where}`, example: cmd || JSON.stringify(ev.input ?? "") });
242
+ }
243
+ return out;
244
+ }
245
+
246
+ /** Hosts this call talked to (for the "where it went" line). */
247
+ export function hostsFor(ev) {
248
+ const cmd = commandOf(ev);
249
+ if (cmd && /\b(?:curl|wget|http|xh|Invoke-WebRequest|iwr|git\s+clone)\b/.test(cmd)) return hostsIn(cmd);
250
+ const url = ev.input?.url;
251
+ if (typeof url === "string") return hostsIn(url);
252
+ return [];
253
+ }
254
+
255
+ export function tokensFor(emails) {
256
+ return identityTokens(undefined, [], emails);
257
+ }