bugxhunter 0.0.0-stage → 0.4.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,154 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The `bugxhunter` command (npx bugxhunter / npm i -g bugxhunter).
4
+ *
5
+ * bugxhunter run the runner here, UI on http://localhost:8790
6
+ * bugxhunter [--port N] [--dir P] [--no-open]
7
+ * bugxhunter docker [compose args] the sandboxed stack: writes ~/.config/bugxhunter/docker
8
+ * (compose file + .env secrets), pulls the signed images
9
+ * matching this version, starts it, opens the UI.
10
+ * With args, runs `docker compose <args>` there (down, logs…).
11
+ * bugxhunter vault reset break-glass: delete the key vault (see scripts/vault-reset.mjs)
12
+ *
13
+ * Local mode runs the agent on this machine: OpenCode is a dependency of this
14
+ * package, so nothing else needs installing. Its binary is found by putting
15
+ * this package's node_modules/.bin on PATH before the server starts.
16
+ */
17
+ import { spawn, spawnSync } from "node:child_process";
18
+ import crypto from "node:crypto";
19
+ import fs from "node:fs";
20
+ import os from "node:os";
21
+ import path from "node:path";
22
+ import { fileURLToPath, pathToFileURL } from "node:url";
23
+
24
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
25
+ const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"));
26
+ const CONFIG_DIR = path.join(os.homedir(), ".config", "bugxhunter");
27
+
28
+ const args = process.argv.slice(2);
29
+ const flag = (name) => { const i = args.indexOf(name); return i >= 0 ? (args.splice(i, 1), true) : false; };
30
+ const opt = (name) => { const i = args.indexOf(name); if (i < 0) return undefined; const v = args[i + 1]; args.splice(i, 2); return v; };
31
+
32
+ if (flag("--version") || flag("-v")) { console.log(pkg.version); process.exit(0); }
33
+ if (flag("--help") || flag("-h")) {
34
+ console.log(`bugxhunter ${pkg.version}
35
+
36
+ bugxhunter run the runner here (agent on this machine), UI on http://localhost:8790
37
+ --port <n> UI port (default 8790, or PORT)
38
+ --dir <path> default project folder (default: the current folder)
39
+ --no-open don't open the browser
40
+ bugxhunter docker the sandboxed stack via Docker (writes ~/.config/bugxhunter/docker, pulls the
41
+ signed images for v${pkg.version}, starts, opens the UI)
42
+ bugxhunter docker <args> docker compose <args> in that folder, e.g. down, logs -f, ps
43
+ bugxhunter vault reset delete the key vault when every unlock factor is lost
44
+
45
+ Docs: https://github.com/cintelis/bugxhunter-runner`);
46
+ process.exit(0);
47
+ }
48
+
49
+ const cmd = args[0];
50
+ if (cmd === "docker") await dockerMode(args.slice(1));
51
+ else if (cmd === "vault" && args[1] === "reset") await vaultReset(args.slice(2));
52
+ else if (cmd && !cmd.startsWith("-")) { console.error(`unknown command: ${cmd} (try --help)`); process.exit(2); }
53
+ else await localMode();
54
+
55
+ // --- local mode -----------------------------------------------------------------------
56
+
57
+ async function localMode() {
58
+ const port = Number(opt("--port") ?? process.env.PORT ?? 8790);
59
+ const dir = path.resolve(opt("--dir") ?? process.env.OPEN_RUNNER_DIR ?? process.cwd());
60
+ const open = !flag("--no-open");
61
+
62
+ // Settings: ~/.config/bugxhunter/.env, then ./.env (both optional; never printed).
63
+ const { default: dotenv } = await import("dotenv");
64
+ for (const f of [path.join(CONFIG_DIR, ".env"), path.join(process.cwd(), ".env")]) {
65
+ if (fs.existsSync(f)) dotenv.config({ path: f });
66
+ }
67
+ process.env.NODE_ENV ??= "production";
68
+ process.env.PORT = String(port);
69
+ process.env.OPEN_RUNNER_DIR = dir;
70
+
71
+ // OpenCode's binary lives in this package's dependencies.
72
+ const bins = [path.join(ROOT, "node_modules", ".bin"), path.resolve(ROOT, "..", ".bin")];
73
+ process.env.PATH = [...bins.filter((b) => fs.existsSync(b)), process.env.PATH ?? ""].join(path.delimiter);
74
+ if (!hasOpencode()) {
75
+ console.error("OpenCode was not found. It is installed with this package; try `npm i -g bugxhunter` again, or `npm i -g opencode-ai`.");
76
+ process.exit(1);
77
+ }
78
+
79
+ const major = Number(process.versions.node.split(".")[0]);
80
+ if (major < 22) { console.error(`Node ${process.versions.node} is too old: BugXHunter needs Node 22+.`); process.exit(1); }
81
+
82
+ await import(pathToFileURL(path.join(ROOT, "server", "dist", "index.js")).href);
83
+ if (open) {
84
+ const url = `http://localhost:${port}`;
85
+ if (await waitFor(`http://127.0.0.1:${port}/api/health`, 15_000)) openBrowser(url);
86
+ }
87
+ }
88
+
89
+ /** Is `opencode` on PATH? A file check, since Windows .cmd shims cannot be spawned without a shell. */
90
+ function hasOpencode() {
91
+ const names = process.platform === "win32" ? ["opencode.cmd", "opencode.exe", "opencode"] : ["opencode"];
92
+ return (process.env.PATH ?? "").split(path.delimiter).some((d) => d && names.some((n) => fs.existsSync(path.join(d, n))));
93
+ }
94
+
95
+ async function waitFor(url, ms) {
96
+ const until = Date.now() + ms;
97
+ while (Date.now() < until) {
98
+ try { const r = await fetch(url, { signal: AbortSignal.timeout(1000) }); if (r.ok) return true; } catch { /* not yet */ }
99
+ await new Promise((r) => setTimeout(r, 250));
100
+ }
101
+ return false;
102
+ }
103
+
104
+ function openBrowser(url) {
105
+ const [bin, a] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
106
+ : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
107
+ try { spawn(bin, a, { stdio: "ignore", detached: true }).unref(); } catch { /* headless: the URL is printed by the server */ }
108
+ }
109
+
110
+ // --- docker mode ----------------------------------------------------------------------
111
+
112
+ async function dockerMode(rest) {
113
+ const dir = path.join(CONFIG_DIR, "docker");
114
+ if (spawnSync("docker", ["compose", "version"], { stdio: "ignore" }).error) {
115
+ console.error("Docker is not installed or not running. Install Docker Desktop (https://docs.docker.com/get-docker/) and try again.");
116
+ process.exit(1);
117
+ }
118
+ fs.mkdirSync(dir, { recursive: true });
119
+ // The compose file of this version, verbatim: the images it names are the
120
+ // signed release images; BXH_VERSION in .env pins them to this version.
121
+ fs.copyFileSync(path.join(ROOT, "docker-compose.yml"), path.join(dir, "docker-compose.yml"));
122
+ const envFile = path.join(dir, ".env");
123
+ const vals = new Map();
124
+ if (fs.existsSync(envFile)) {
125
+ for (const line of fs.readFileSync(envFile, "utf8").split(/\r?\n/)) {
126
+ const m = /^\s*([A-Z0-9_]+)=(.*)$/.exec(line);
127
+ if (m) vals.set(m[1], m[2]);
128
+ }
129
+ }
130
+ const fresh = !vals.size;
131
+ if (!vals.get("OPEN_RUNNER_SECRET")) vals.set("OPEN_RUNNER_SECRET", crypto.randomBytes(32).toString("base64url"));
132
+ if (!vals.get("SCX_PROXY_TOKEN")) vals.set("SCX_PROXY_TOKEN", crypto.randomBytes(32).toString("base64url"));
133
+ vals.set("BXH_VERSION", `v${pkg.version}`);
134
+ fs.writeFileSync(envFile, [...vals].map(([k, v]) => `${k}=${v}`).join("\n") + "\n", { mode: 0o600 });
135
+ console.log(`${fresh ? "Created" : "Updated"} ${dir} (compose file + .env; secrets are random and never printed)`);
136
+
137
+ const compose = (a) => spawnSync("docker", ["compose", ...a], { cwd: dir, stdio: "inherit" }).status ?? 1;
138
+ if (rest.length) process.exit(compose(rest));
139
+ console.log(`Pulling the signed images for v${pkg.version} (the agent image is large the first time)…`);
140
+ if (compose(["pull"]) !== 0) process.exit(1);
141
+ if (compose(["up", "-d"]) !== 0) process.exit(1);
142
+ const port = vals.get("OPEN_RUNNER_PORT") ?? "8790";
143
+ const url = `http://localhost:${port}`;
144
+ console.log(`BugXHunter is starting at ${url}. Set up the vault in the sidebar, add your model key, connect GitHub.`);
145
+ console.log(`Later: bugxhunter docker logs -f · bugxhunter docker down · re-run after \`npm i -g bugxhunter@latest\` to upgrade.`);
146
+ if (await waitFor(`http://127.0.0.1:${port}/api/health`, 60_000)) openBrowser(url);
147
+ }
148
+
149
+ // --- vault reset ----------------------------------------------------------------------
150
+
151
+ async function vaultReset(rest) {
152
+ const r = spawnSync(process.execPath, [path.join(ROOT, "scripts", "vault-reset.mjs"), ...rest], { stdio: "inherit" });
153
+ process.exit(r.status ?? 1);
154
+ }
@@ -0,0 +1,118 @@
1
+ # BugXHunter in Docker: UI + passkey sign-in in `runner`, the agent in `agent`.
2
+ #
3
+ # powershell -File docker/setup.ps1 # once: writes .env (secrets)
4
+ # docker compose up -d --build
5
+ # open http://localhost:8790
6
+ #
7
+ # Isolation model:
8
+ # - `agent` has direct internet so scan tools run at full speed (nmap, ping
9
+ # and raw DNS work too via NET_RAW). Outbound traffic is logged, not gated.
10
+ # - `agent` holds NO SCX key: model calls go to runner's /scx/v1 proxy, which
11
+ # injects the key, so the key never enters the sandbox. Same for the GitHub
12
+ # sign-in: `runner` clones into /workspace, the agent gets a credential-free copy.
13
+ # - No host folders are mounted: projects live in the `workspace` volume.
14
+ # - Both run as non-root with no-new-privileges; the agent drops all caps
15
+ # except NET_RAW, and bash/edit actions are approved in the UI.
16
+ #
17
+ # ⚠ The agent has unrestricted outbound. Only point it at targets you are
18
+ # authorised to test, and run this on a trusted machine/VM.
19
+
20
+ name: bugxhunter
21
+
22
+ # Images: `docker compose pull` fetches the published images (BXH_VERSION in
23
+ # .env picks a signed release, e.g. v1.2.3; default latest); `docker compose
24
+ # up -d --build` builds them locally instead. See SECURITY.md to verify a
25
+ # release's image digests before pulling.
26
+ services:
27
+ runner:
28
+ image: ghcr.io/cintelis/bugxhunter-runner:${BXH_VERSION:-latest}
29
+ build:
30
+ context: .
31
+ dockerfile: docker/runner.Dockerfile
32
+ environment:
33
+ # Model key: prefer the vault (set up in the UI, sealed in the runner-data
34
+ # volume). SCX_API in .env still works but sits in the clear.
35
+ SCX_API: ${SCX_API:-}
36
+ # Optional second provider (https://openrouter.ai/models): key in the vault
37
+ # (OPENROUTER_API_KEY) or here; OPENROUTER_MODELS lists the ids the agent may use.
38
+ OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
39
+ OPENROUTER_MODELS: ${OPENROUTER_MODELS:-}
40
+ OPEN_RUNNER_VAULT_FILE: /data/vault.json
41
+ OPEN_RUNNER_VAULT_IDLE_MINUTES: ${OPEN_RUNNER_VAULT_IDLE_MINUTES:-120}
42
+ OPEN_RUNNER_SECRET: ${OPEN_RUNNER_SECRET:-}
43
+ SCX_PROXY_TOKEN: ${SCX_PROXY_TOKEN:?run docker/setup.ps1 first}
44
+ OPENCODE_URL: http://agent:4096
45
+ OPEN_RUNNER_WORKSPACE: /workspace
46
+ OPEN_RUNNER_LOG_DIR: /logs # audit log, one JSONL file per day
47
+ volumes:
48
+ - workspace:/workspace # same volume as the agent: attachments
49
+ - logs:/logs # audit + egress logs; NOT mounted in the agent, so it can't edit them
50
+ - runner-data:/data # the sealed key vault (ciphertext only; see SECURITY.md)
51
+ ports:
52
+ - "127.0.0.1:${OPEN_RUNNER_PORT:-8790}:8790" # localhost only; put TLS in front before exposing
53
+ networks: [net]
54
+ depends_on:
55
+ agent:
56
+ condition: service_healthy
57
+ read_only: true
58
+ tmpfs: [/tmp]
59
+ cap_drop: [ALL]
60
+ security_opt: ["no-new-privileges:true"]
61
+ restart: unless-stopped
62
+
63
+ agent:
64
+ image: ghcr.io/cintelis/bugxhunter-agent:${BXH_VERSION:-latest}
65
+ build:
66
+ context: .
67
+ dockerfile: docker/agent.Dockerfile
68
+ environment:
69
+ SCX_PROXY_TOKEN: ${SCX_PROXY_TOKEN:?run docker/setup.ps1 first}
70
+ OPENCODE_ENABLE_EXA: "1" # turns on OpenCode's websearch tool (Exa)
71
+ OPENROUTER_MODELS: ${OPENROUTER_MODELS:-} # same list as runner: becomes an OpenCode provider via runner's proxy
72
+ networks: [net]
73
+ volumes:
74
+ - workspace:/workspace
75
+ - agent-data:/home/node/.local/share/opencode
76
+ cap_drop: [ALL]
77
+ cap_add: [NET_RAW] # raw sockets for nmap / ping / traceroute
78
+ security_opt: ["no-new-privileges:true"]
79
+ pids_limit: 512
80
+ mem_limit: 4g
81
+ cpus: 2
82
+ healthcheck:
83
+ test: ["CMD", "curl", "-fsS", "http://127.0.0.1:4096/global/health"]
84
+ interval: 10s
85
+ timeout: 3s
86
+ retries: 12
87
+ start_period: 20s
88
+ restart: unless-stopped
89
+
90
+ # Passive egress logger: shares the agent's network namespace and sniffs its
91
+ # outbound traffic (tcpdump), recording distinct destinations + DNS lookups to
92
+ # /logs/egress-<date>.jsonl. Log-only — it never blocks traffic and
93
+ # is not in the data path, so scans keep full speed.
94
+ egress-logger:
95
+ image: ghcr.io/cintelis/bugxhunter-agent:${BXH_VERSION:-latest}
96
+ command: ["node", "/usr/local/lib/egress-logger.mjs"]
97
+ network_mode: "service:agent" # see the agent's connections
98
+ user: root # needs CAP_NET_RAW effective (agent image defaults to non-root)
99
+ environment:
100
+ OPEN_RUNNER_LOG_DIR: /logs
101
+ volumes:
102
+ - logs:/logs
103
+ cap_drop: [ALL]
104
+ # NET_RAW: capture; SETUID/SETGID: tcpdump drops to its own user;
105
+ # DAC_OVERRIDE: write into /logs (owned by the runner's user).
106
+ cap_add: [NET_RAW, SETUID, SETGID, DAC_OVERRIDE]
107
+ security_opt: ["no-new-privileges:true"]
108
+ depends_on: [agent]
109
+ restart: unless-stopped
110
+
111
+ networks:
112
+ net: {} # normal bridge: agent + runner share it, agent reaches the internet via NAT
113
+
114
+ volumes:
115
+ workspace: {}
116
+ agent-data: {}
117
+ logs: {} # read with: docker compose cp runner:/logs ./logs
118
+ runner-data: {} # vault.json: wrapped keys + ciphertext, useless without an unlock
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "bugxhunter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "BugXHunter: an AI security-testing agent with a sandboxed runner, a passkey-sealed key vault and read-only GitHub access. `npx bugxhunter` runs it on your machine.",
5
+ "license": "MIT",
6
+ "homepage": "https://bugxhunter.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/cintelis/bugxhunter-runner.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/cintelis/bugxhunter-runner/issues"
13
+ },
14
+ "keywords": [
15
+ "security",
16
+ "pentest",
17
+ "bug-bounty",
18
+ "ai-agent",
19
+ "opencode",
20
+ "vulnerability-scanner",
21
+ "code-review"
22
+ ],
23
+ "type": "module",
24
+ "bin": {
25
+ "bugxhunter": "bin/bugxhunter.mjs"
26
+ },
27
+ "engines": {
28
+ "node": ">=22"
29
+ },
30
+ "dependencies": {
31
+ "@opencode-ai/sdk": "^1.17.11",
32
+ "dotenv": "^16.4.7",
33
+ "express": "^4.21.2",
34
+ "opencode-ai": "^1.18.35"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ }
39
+ }
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ // Break-glass: delete the key vault when every unlock factor is lost (passkey
3
+ // and recovery code). Must be run on the server, by someone with access to
4
+ // its files — that is the point: nothing on the network can do this.
5
+ //
6
+ // npm run vault:reset # local; asks for confirmation
7
+ // npm run vault:reset -- --yes # no prompt
8
+ // docker compose exec runner node server/dist/../../scripts/vault-reset.mjs --yes (or: rm /data/vault.json)
9
+ //
10
+ // Afterwards the app is open again (no sign-in) and offers the setup wizard.
11
+ // Secrets that were in the vault are gone: add the SCX key again when
12
+ // recreating it. The backend notices the deletion without a restart.
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import readline from "node:readline";
17
+
18
+ const file = process.env.OPEN_RUNNER_VAULT_FILE ?? path.join(os.homedir(), ".config", "bugxhunter", "vault.json");
19
+ if (!fs.existsSync(file)) {
20
+ console.log(`no vault at ${file} — nothing to reset`);
21
+ process.exit(0);
22
+ }
23
+ if (!process.argv.includes("--yes")) {
24
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
25
+ const answer = await new Promise((r) => rl.question(`Delete the vault at ${file}? Its secrets are unrecoverable. Type RESET to confirm: `, r));
26
+ rl.close();
27
+ if (answer.trim() !== "RESET") { console.log("aborted"); process.exit(1); }
28
+ }
29
+ fs.rmSync(file, { force: true });
30
+ console.log(`deleted ${file}. The app is open again; set up a new vault in the sidebar.`);
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Prompt attachments.
3
+ *
4
+ * Every attached file is saved into `<project>/attachments/` so the agent's
5
+ * tools can work with it. On top of that:
6
+ * - images go to the model inline (data URL) — for models that accept images;
7
+ * - small text files are passed as file:// parts, which OpenCode reads into
8
+ * the prompt;
9
+ * - anything else (PDFs, archives, …) is just mentioned by path.
10
+ *
11
+ * In Docker the runner mounts the same workspace volume as the agent, so the
12
+ * paths are identical in both containers.
13
+ */
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { pathToFileURL } from "node:url";
17
+ const MAX_FILE_BYTES = 25 * 1024 * 1024;
18
+ const INLINE_TEXT_BYTES = 512 * 1024;
19
+ const TEXT_EXT = /\.(txt|md|markdown|json|jsonl|ya?ml|toml|ini|cfg|conf|csv|tsv|log|xml|html?|css|scss|js|mjs|cjs|jsx|ts|tsx|py|rb|go|rs|java|kt|c|h|cc|cpp|hpp|cs|php|sh|bash|zsh|ps1|sql|env|gitignore|dockerfile|tf|gradle|swift|lua|r|pl)$/i;
20
+ const isText = (name, mime) => mime.startsWith("text/") || /json|xml|yaml|javascript|typescript|x-sh|x-python|sql/.test(mime) || TEXT_EXT.test(name);
21
+ /** A file name that is safe to create inside the project: basename only, no odd characters. */
22
+ export function safeName(name) {
23
+ // Last segment after either separator style: the browser may be on Windows
24
+ // while this server runs on Linux, where path.basename ignores backslashes.
25
+ const last = name.split(/[\\/]/).pop() ?? "";
26
+ const base = last.replace(/[^\w.\- ()]+/g, "_").replace(/^\.+/, "").slice(0, 120);
27
+ return base || "file";
28
+ }
29
+ function uniquePath(dir, name) {
30
+ const ext = path.extname(name);
31
+ const stem = name.slice(0, name.length - ext.length);
32
+ let candidate = path.join(dir, name);
33
+ for (let i = 1; fs.existsSync(candidate); i++)
34
+ candidate = path.join(dir, `${stem}-${i}${ext}`);
35
+ return candidate;
36
+ }
37
+ export function saveAttachments(directory, files, inlineImages = true) {
38
+ const dir = path.join(directory, "attachments");
39
+ fs.mkdirSync(dir, { recursive: true });
40
+ const parts = [];
41
+ const saved = [];
42
+ for (const f of files) {
43
+ const bytes = Buffer.from(f.data ?? "", "base64");
44
+ if (bytes.length > MAX_FILE_BYTES) {
45
+ throw Object.assign(new Error(`${f.name} is larger than 25 MB`), { status: 413 });
46
+ }
47
+ const name = safeName(f.name);
48
+ const mime = f.mime || "application/octet-stream";
49
+ const abs = uniquePath(dir, name);
50
+ fs.writeFileSync(abs, bytes);
51
+ const rel = path.relative(directory, abs).split(path.sep).join("/");
52
+ saved.push({ name: path.basename(abs), path: rel, bytes: bytes.length, mime });
53
+ if (mime.startsWith("image/")) {
54
+ if (!inlineImages)
55
+ continue; // model can't see images: it gets the saved path only
56
+ parts.push({ type: "file", mime, filename: path.basename(abs), url: `data:${mime};base64,${f.data}` });
57
+ }
58
+ else if (isText(name, mime) && bytes.length <= INLINE_TEXT_BYTES) {
59
+ parts.push({ type: "file", mime: "text/plain", filename: path.basename(abs), url: pathToFileURL(abs).href });
60
+ }
61
+ }
62
+ const note = saved.length
63
+ ? `\n\n[Attached file${saved.length > 1 ? "s" : ""}, saved in the project: ${saved.map((s) => s.path).join(", ")}]`
64
+ : "";
65
+ return { parts, note, saved };
66
+ }
67
+ //# sourceMappingURL=attachments.js.map
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Audit log: one JSON line per event, one file per day, e.g.
3
+ * /workspace/logs/2026-10-06.jsonl
4
+ *
5
+ * Records what the agent was asked and what it did: prompts and commands,
6
+ * completed tool calls (inputs + truncated output), permission and question
7
+ * requests and answers, internet-access decisions, and errors. Fed by our own
8
+ * routes plus a subscription to OpenCode's all-projects event stream, so it
9
+ * captures activity even when no browser is open.
10
+ *
11
+ * Note: in Docker this folder is inside the agent's workspace, so the agent
12
+ * could edit it. It is a working log, not tamper-proof evidence.
13
+ */
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ export const LOG_DIR = process.env.OPEN_RUNNER_LOG_DIR ?? "";
17
+ let ready = false;
18
+ function ensureDir() {
19
+ if (ready || !LOG_DIR)
20
+ return ready;
21
+ try {
22
+ fs.mkdirSync(LOG_DIR, { recursive: true });
23
+ // Keep logs out of git status / the Changes view.
24
+ const ignore = path.join(LOG_DIR, ".gitignore");
25
+ if (!fs.existsSync(ignore))
26
+ fs.writeFileSync(ignore, "*\n");
27
+ ready = true;
28
+ }
29
+ catch (e) {
30
+ console.error("[audit] cannot create log folder:", e.message);
31
+ }
32
+ return ready;
33
+ }
34
+ export function audit(event, data = {}) {
35
+ if (!ensureDir())
36
+ return;
37
+ const now = new Date();
38
+ const line = JSON.stringify({ ts: now.toISOString(), event, ...data }) + "\n";
39
+ fs.appendFile(path.join(LOG_DIR, `${now.toISOString().slice(0, 10)}.jsonl`), line, (err) => {
40
+ if (err)
41
+ console.error("[audit] write failed:", err.message);
42
+ });
43
+ }
44
+ const clip = (v, n = 4000) => (typeof v === "string" && v.length > n ? v.slice(0, n) + `… (${v.length} chars)` : v);
45
+ /** Follow OpenCode's global event stream and log the events that matter. */
46
+ export function followOpencode(url) {
47
+ if (!LOG_DIR)
48
+ return;
49
+ const seenTools = new Set();
50
+ const run = async () => {
51
+ while (true) {
52
+ try {
53
+ const r = await fetch(`${url}/global/event`);
54
+ if (!r.ok || !r.body)
55
+ throw new Error(`HTTP ${r.status}`);
56
+ const dec = new TextDecoder();
57
+ let buf = "";
58
+ for await (const chunk of r.body) {
59
+ buf += dec.decode(chunk, { stream: true });
60
+ let nl;
61
+ while ((nl = buf.indexOf("\n")) !== -1) {
62
+ const line = buf.slice(0, nl).trim();
63
+ buf = buf.slice(nl + 1);
64
+ if (!line.startsWith("data:"))
65
+ continue;
66
+ try {
67
+ const { directory, payload } = JSON.parse(line.slice(5));
68
+ record(directory, payload, seenTools);
69
+ }
70
+ catch { /* partial / non-JSON */ }
71
+ }
72
+ }
73
+ }
74
+ catch { /* reconnect */ }
75
+ await new Promise((res) => setTimeout(res, 3000));
76
+ }
77
+ };
78
+ run();
79
+ }
80
+ function record(directory, evt, seenTools) {
81
+ const p = evt?.properties ?? {};
82
+ switch (evt?.type) {
83
+ case "message.part.updated": {
84
+ const part = p.part;
85
+ if (part?.type !== "tool")
86
+ return;
87
+ const st = part.state ?? {};
88
+ if (st.status !== "completed" && st.status !== "error")
89
+ return;
90
+ const key = `${part.callID}:${st.status}`;
91
+ if (seenTools.has(key))
92
+ return;
93
+ seenTools.add(key);
94
+ if (seenTools.size > 5000)
95
+ seenTools.clear();
96
+ audit("tool", {
97
+ directory, session: part.sessionID, tool: part.tool, status: st.status,
98
+ input: st.input, output: clip(st.output), error: st.error,
99
+ });
100
+ return;
101
+ }
102
+ case "permission.asked":
103
+ case "permission.updated":
104
+ audit("permission.asked", { directory, session: p.sessionID, id: p.id, type: p.type ?? p.permission, pattern: p.pattern ?? p.patterns, title: p.title });
105
+ return;
106
+ case "permission.replied":
107
+ audit("permission.replied", { directory, session: p.sessionID, id: p.permissionID ?? p.requestID, response: p.response ?? p.reply });
108
+ return;
109
+ case "question.asked":
110
+ audit("question.asked", { directory, session: p.sessionID, id: p.id, questions: p.questions });
111
+ return;
112
+ case "question.replied":
113
+ audit("question.replied", { directory, session: p.sessionID, id: p.requestID, answers: p.answers });
114
+ return;
115
+ case "question.rejected":
116
+ audit("question.dismissed", { directory, session: p.sessionID, id: p.requestID });
117
+ return;
118
+ case "session.error":
119
+ audit("error", { directory, session: p.sessionID, error: p.error });
120
+ return;
121
+ }
122
+ }
123
+ //# sourceMappingURL=audit.js.map