bugxhunter 0.13.0 → 0.14.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.
@@ -20,6 +20,11 @@ import { audit, followOpencode, LOG_DIR } from "./audit.js";
20
20
  import { saveAttachments } from "./attachments.js";
21
21
  import * as vault from "./vault.js";
22
22
  import * as playground from "./playground-store.js";
23
+ import * as reconMemory from "./recon-memory.js";
24
+ import * as reconSession from "./recon-session.js";
25
+ import { batchDirectory, batchState, parseTargets, startBatch, stopBatch } from "./recon-batch.js";
26
+ import { resolveHarness } from "./recon-driver.js";
27
+ import { zip } from "./zip.js";
23
28
  import * as nvidiaHealth from "./nvidia-health.js";
24
29
  import * as render from "./render.js";
25
30
  import { VERSION } from "./version.js";
@@ -870,24 +875,210 @@ app.post("/api/agent/recon", async (req, res) => {
870
875
  ? "The agent container has no recon agent. Rebuild or pull the agent image for this version."
871
876
  : "OpenCode has no recon agent. Restart BugXHunter." } });
872
877
  }
873
- setAnthropicAvailable(configured("anthropic"));
874
- const state = await startRecon({
875
- sessionID: b.sessionID,
876
- scope: String(b.scope ?? ""),
877
- objective: String(b.objective ?? ""),
878
- env: parseEnvFidelity(b.env),
879
- harness: parseReconHarness({ maxRounds: b.maxRounds, budgetTokens: b.budgetTokens, chainPass: b.chainPass }),
880
- backend: await reconBackend(directory),
881
- log: (event, data) => audit(event, { directory, ...data }),
878
+ res.json({ recon: await launchRecon(directory, b.sessionID, b) });
879
+ }
880
+ catch (e) {
881
+ sendError(res, e);
882
+ }
883
+ });
884
+ /**
885
+ * Start one recon run on a session: what the start route does once the request is checked,
886
+ * and what a batch does for each of its targets.
887
+ */
888
+ async function launchRecon(directory, sessionID, b, onFinished) {
889
+ const scope = String(b.scope ?? "");
890
+ // Retest mode re-checks what is remembered about the target; with nothing remembered there is nothing to do.
891
+ const retest = b.mode === "retest" ? reconMemory.recall(scope)?.findings ?? [] : undefined;
892
+ if (retest && !retest.length)
893
+ throw httpError(400, "Nothing is remembered about this target to retest (or the vault is locked).");
894
+ setAnthropicAvailable(configured("anthropic"));
895
+ // The captured session becomes two files in the project folder for this run; startRecon removes them when it ends.
896
+ const session = b.useSession === false ? undefined : reconSession.materialise(scope, directory);
897
+ return startRecon({
898
+ session,
899
+ sessionID,
900
+ scope,
901
+ objective: String(b.objective ?? ""),
902
+ env: parseEnvFidelity(b.env),
903
+ harness: parseReconHarness({ maxRounds: b.maxRounds, budgetTokens: b.budgetTokens, chainPass: b.chainPass }),
904
+ backend: await reconBackend(directory),
905
+ log: (event, data) => audit(event, { directory, ...data }),
906
+ // What earlier runs verified here, unless this run is to start cold. It is always kept for the next one.
907
+ retest,
908
+ prior: retest || b.useMemory === false ? undefined : reconMemory.recall(scope),
909
+ remember: reconMemory.remember,
910
+ onFinished,
911
+ }).catch((e) => { session?.cleanup(); throw e; }); // the run never started: do not leave the session lying in the project
912
+ }
913
+ // --- Concurrency mode: several targets, one worker each (recon-batch.ts) ---
914
+ /** Start a batch: a recon run per target, a few at a time. */
915
+ app.post("/api/agent/recon/batch", async (req, res) => {
916
+ try {
917
+ const b = (req.body ?? {});
918
+ if (b.authorised !== true)
919
+ return res.status(400).json({ error: { message: "Confirm that you are authorised to test every target listed." } });
920
+ const targets = parseTargets(b.targets);
921
+ parseEnvFidelity(b.env); // refuse a bad environment now, not once per worker
922
+ if (!String(b.objective ?? "").trim())
923
+ return res.status(400).json({ error: { message: "objective is required" } });
924
+ const directory = await resolveDirectory(b.directory);
925
+ const agents = await oc(`/agent${query({ directory })}`).catch(() => []);
926
+ if (!agents.some((a) => a?.name === EXECUTOR_AGENT)) {
927
+ return res.status(409).json({ error: { message: "The agent has no recon agent. Rebuild or pull the agent image for this version, or restart BugXHunter." } });
928
+ }
929
+ const client = await getClient(directory);
930
+ const total = Number(b.totalBudgetTokens);
931
+ const batch = startBatch({
932
+ targets, directory, maxWorkers: b.maxWorkers,
933
+ workerBudgetTokens: resolveHarness(parseReconHarness({ budgetTokens: b.budgetTokens })).budgetTokens,
934
+ ...(Number.isFinite(total) && total > 0 ? { totalBudgetTokens: Math.floor(total) } : {}),
935
+ deps: {
936
+ async startWorker(target, budgetTokens, onFinished) {
937
+ const session = unwrap(await client.session.create({ body: { title: `recon ${target}`.slice(0, 120) }, query: { directory } }));
938
+ // A batch explores: retest stays a single-target choice.
939
+ await launchRecon(directory, session.id, { ...b, scope: target, budgetTokens, mode: undefined }, onFinished);
940
+ return { sessionID: session.id };
941
+ },
942
+ stopWorker: (sessionID) => stopRecon(sessionID),
943
+ workerState: (sessionID) => reconState(sessionID),
944
+ log: (event, data) => audit(event, { directory, ...data }),
945
+ },
882
946
  });
883
- res.json({ recon: state });
947
+ res.json({ batch });
948
+ }
949
+ catch (e) {
950
+ sendError(res, e);
951
+ }
952
+ });
953
+ /** A batch (by id, or the latest), and the approvals its workers are waiting on, each with its target. */
954
+ app.get("/api/agent/recon/batch", async (req, res) => {
955
+ try {
956
+ const batch = batchState(typeof req.query.id === "string" && req.query.id ? req.query.id : undefined);
957
+ if (!batch)
958
+ return res.json({ batch: null, approvals: [] });
959
+ const directory = batchDirectory(batch.id);
960
+ const running = batch.workers.filter((w) => (w.status === "running" || w.status === "starting") && w.sessionID);
961
+ const approvals = [];
962
+ if (running.length) {
963
+ const permsRaw = await oc(`/permission${query({ directory })}`).catch(() => []);
964
+ for (const w of running) {
965
+ const family = new SessionFamily(w.sessionID, await childSessions(directory, w.sessionID).catch(() => []));
966
+ for (const p of permsRaw) {
967
+ if (!family.has(p.sessionID))
968
+ continue;
969
+ approvals.push({
970
+ kind: "permission", sessionID: p.sessionID, permissionID: p.id, permType: p.permission ?? p.type,
971
+ title: p.metadata?.command ?? p.title, pattern: p.patterns ?? p.pattern, callID: p.callID,
972
+ subagent: family.subagent(p.sessionID), target: w.target,
973
+ });
974
+ }
975
+ }
976
+ }
977
+ res.json({ batch, approvals, directory });
978
+ }
979
+ catch (e) {
980
+ sendError(res, e);
981
+ }
982
+ });
983
+ app.post("/api/agent/recon/batch/stop", async (req, res) => {
984
+ try {
985
+ const id = String(req.body?.id || "");
986
+ const batch = await stopBatch(id);
987
+ if (batch)
988
+ audit("recon.batch.stop", { batch: id });
989
+ res.json({ batch });
990
+ }
991
+ catch (e) {
992
+ sendError(res, e);
993
+ }
994
+ });
995
+ // --- A logged-in session for a recon target (recon-session.ts) ---
996
+ /** The session held for a target (counts and dates only). */
997
+ app.get("/api/agent/recon/session", (req, res) => {
998
+ try {
999
+ res.json({ session: reconSession.sessionInfo(typeof req.query.scope === "string" ? req.query.scope : "") });
1000
+ }
1001
+ catch (e) {
1002
+ sendError(res, e);
1003
+ }
1004
+ });
1005
+ app.delete("/api/agent/recon/session", (req, res) => {
1006
+ try {
1007
+ res.json({ deleted: reconSession.forgetSession(typeof req.query.scope === "string" ? req.query.scope : "") });
1008
+ }
1009
+ catch (e) {
1010
+ sendError(res, e);
1011
+ }
1012
+ });
1013
+ /** A single-use pairing code for the browser extension, good for this target for ten minutes. */
1014
+ app.post("/api/agent/recon/session/pair", (req, res) => {
1015
+ try {
1016
+ res.json(reconSession.issuePairing(String(req.body?.scope ?? "")));
1017
+ }
1018
+ catch (e) {
1019
+ sendError(res, e);
1020
+ }
1021
+ });
1022
+ /**
1023
+ * The browser extension posts the session here with the pairing code as a bearer token.
1024
+ * This is the one route under /api that is reachable without a sign-in (see auth.ts): the
1025
+ * code is what authorises it, once.
1026
+ */
1027
+ app.post("/api/capture/session", (req, res) => {
1028
+ try {
1029
+ const m = /^Bearer\s+(\S+)$/i.exec(String(req.headers.authorization ?? ""));
1030
+ res.json({ session: reconSession.redeem(m?.[1], req.body) });
1031
+ }
1032
+ catch (e) {
1033
+ sendError(res, e);
1034
+ }
1035
+ });
1036
+ /** The browser extension as a zip, to unpack and load (chrome://extensions → Load unpacked). */
1037
+ app.get("/api/agent/recon/extension.zip", (_req, res) => {
1038
+ try {
1039
+ const dir = [path.join(REPO_ROOT, "web", "dist", "bxh-extension"), path.join(REPO_ROOT, "web", "public", "bxh-extension")].find((d) => fs.existsSync(d));
1040
+ if (!dir)
1041
+ return res.status(404).json({ error: { message: "The extension is not part of this build." } });
1042
+ const entries = fs.readdirSync(dir).filter((n) => /^[\w.-]+\.(?:json|js|html|css|png|md)$/.test(n)).sort()
1043
+ .map((name) => ({ name: `bugxhunter-extension/${name}`, data: fs.readFileSync(path.join(dir, name)) }));
1044
+ res.setHeader("Content-Type", "application/zip");
1045
+ res.setHeader("Content-Disposition", 'attachment; filename="bugxhunter-extension.zip"');
1046
+ res.send(zip(entries));
884
1047
  }
885
1048
  catch (e) {
886
1049
  sendError(res, e);
887
1050
  }
888
1051
  });
889
1052
  app.get("/api/agent/recon", (req, res) => {
890
- res.json({ recon: reconState(String(req.query.sessionID || "")) });
1053
+ const sessionID = String(req.query.sessionID || "");
1054
+ // After a restart the run is gone from this process: show what was kept of it.
1055
+ res.json({ recon: reconState(sessionID) ?? reconMemory.lastForSession(sessionID) });
1056
+ });
1057
+ /** What is remembered: about one target (`?scope=`), or the list of targets. */
1058
+ app.get("/api/agent/recon/memory", (req, res) => {
1059
+ try {
1060
+ const scope = typeof req.query.scope === "string" ? req.query.scope : "";
1061
+ const all = reconMemory.targets();
1062
+ if (!scope)
1063
+ return res.json({ targets: all });
1064
+ const key = reconMemory.targetKey(scope);
1065
+ res.json({ memory: all.find((t) => t.target === key) ?? null });
1066
+ }
1067
+ catch (e) {
1068
+ sendError(res, e);
1069
+ }
1070
+ });
1071
+ /** Forget every run on one target. */
1072
+ app.delete("/api/agent/recon/memory", (req, res) => {
1073
+ try {
1074
+ const scope = typeof req.query.scope === "string" ? req.query.scope : "";
1075
+ if (!reconMemory.targetKey(scope))
1076
+ return res.status(400).json({ error: { message: "scope must be one host or URL" } });
1077
+ res.json({ deleted: reconMemory.forget(scope) });
1078
+ }
1079
+ catch (e) {
1080
+ sendError(res, e);
1081
+ }
891
1082
  });
892
1083
  app.post("/api/agent/recon/stop", async (req, res) => {
893
1084
  try {
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Concurrency mode: one supervised recon run per target, several at a time.
3
+ *
4
+ * A batch is a queue of targets and a cap on how many are tested at once. Each worker is
5
+ * an ordinary recon run on a session of its own (recon-run.ts): its own gate bound to its
6
+ * own target, its own rounds, budget, evidence, leads, memory and logged-in session. The
7
+ * workers do not talk to each other. All this file adds is the queue, a token ceiling
8
+ * across the workers, and one place to see and stop them.
9
+ *
10
+ * The coordinator is plain code. It starts a worker, waits to be told it finished, and
11
+ * starts the next; how a worker is started and stopped is injected, so the queue can be
12
+ * tested without OpenCode. A batch lives in the runner's memory, like a run that is still
13
+ * going: what each worker found is kept by the worker itself, per target.
14
+ */
15
+ import crypto from "node:crypto";
16
+ import { httpError } from "./errors.js";
17
+ import { originOf } from "./recon.js";
18
+ export const BATCH_DEFAULTS = { maxWorkers: 3 };
19
+ export const BATCH_LIMITS = { maxWorkers: 5, targets: 50 };
20
+ /** A worker is not started on less than this: it could not finish a round. */
21
+ export const MIN_WORKER_BUDGET = 20_000;
22
+ const batches = new Map();
23
+ /**
24
+ * The targets of a batch, from a list or from text with one per line (commas work too):
25
+ * each one host or URL, repeats of the same host and port dropped, order kept.
26
+ */
27
+ export function parseTargets(raw) {
28
+ const items = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(/[\r\n,]+/) : [];
29
+ const seen = new Set();
30
+ const out = [];
31
+ for (const item of items) {
32
+ const scope = typeof item === "string" ? item.trim() : "";
33
+ if (!scope)
34
+ continue;
35
+ const { host, port } = originOf(scope);
36
+ if (!host)
37
+ throw httpError(400, `Not a host or URL: ${scope.slice(0, 80)}`);
38
+ const key = `${host}:${port}`;
39
+ if (seen.has(key))
40
+ continue;
41
+ seen.add(key);
42
+ out.push(scope);
43
+ }
44
+ if (!out.length)
45
+ throw httpError(400, "Give at least one target, one host or URL per line.");
46
+ if (out.length > BATCH_LIMITS.targets)
47
+ throw httpError(400, `Up to ${BATCH_LIMITS.targets} targets in one batch.`);
48
+ return out;
49
+ }
50
+ /** How many workers at once: the default, or what was asked for within the limit. */
51
+ export function resolveWorkers(raw) {
52
+ const n = Number(raw);
53
+ return Number.isInteger(n) && n >= 1 ? Math.min(n, BATCH_LIMITS.maxWorkers) : BATCH_DEFAULTS.maxWorkers;
54
+ }
55
+ const active = (w) => w.status === "starting" || w.status === "running";
56
+ /** Tokens the batch has spent: what finished workers used, and what running ones have used so far. */
57
+ function spent(b) {
58
+ let n = 0;
59
+ for (const w of b.state.workers) {
60
+ const live = w.status === "running" && w.sessionID ? b.deps.workerState(w.sessionID) : null;
61
+ n += (live ?? w.recon)?.tokens ?? 0;
62
+ }
63
+ return n;
64
+ }
65
+ /**
66
+ * What a new worker may be given: its own budget, or less if the total ceiling leaves
67
+ * less. Running workers count for their whole budget, not what they have used so far, so
68
+ * the ceiling holds whatever they go on to spend.
69
+ */
70
+ function budgetForNext(b) {
71
+ const total = b.state.budgetTokens;
72
+ if (total === undefined)
73
+ return b.workerBudget;
74
+ let committed = 0;
75
+ for (const w of b.state.workers) {
76
+ if (active(w))
77
+ committed += b.reserved.get(w.target) ?? 0;
78
+ else
79
+ committed += w.recon?.tokens ?? 0;
80
+ }
81
+ return Math.min(b.workerBudget, total - committed);
82
+ }
83
+ function finishIfDone(b) {
84
+ if (b.state.status !== "running" || b.state.workers.some((w) => w.status === "queued" || active(w)))
85
+ return;
86
+ b.state.status = "finished";
87
+ b.state.finishedAt = Date.now();
88
+ b.state.tokens = spent(b);
89
+ const count = (s) => b.state.workers.filter((w) => w.status === s).length;
90
+ b.deps.log?.("recon.batch.finished", {
91
+ batch: b.state.id, finished: count("finished"), failed: count("failed"), skipped: count("skipped"), tokens: b.state.tokens, stopped: Boolean(b.state.stopped),
92
+ });
93
+ }
94
+ /** Start queued targets until the cap on workers is reached, the queue is empty or the ceiling is. */
95
+ function pump(b) {
96
+ if (b.state.status !== "running")
97
+ return;
98
+ while (!b.stopping) {
99
+ const next = b.state.workers.find((w) => w.status === "queued");
100
+ if (!next || b.state.workers.filter(active).length >= b.state.maxWorkers)
101
+ break;
102
+ const budget = budgetForNext(b);
103
+ if (budget < MIN_WORKER_BUDGET) {
104
+ // Tokens reserved for running workers may come back when they finish under budget: wait for them.
105
+ if (b.state.workers.some(active))
106
+ break;
107
+ for (const w of b.state.workers)
108
+ if (w.status === "queued") {
109
+ w.status = "skipped";
110
+ w.reason = "the batch's token budget was spent";
111
+ }
112
+ break;
113
+ }
114
+ start(b, next, budget);
115
+ }
116
+ finishIfDone(b);
117
+ }
118
+ function start(b, w, budget) {
119
+ w.status = "starting";
120
+ b.reserved.set(w.target, budget);
121
+ const onFinished = (state) => {
122
+ w.status = "finished";
123
+ w.recon = state;
124
+ b.reserved.delete(w.target);
125
+ pump(b);
126
+ };
127
+ b.deps.startWorker(w.target, budget, onFinished).then(({ sessionID }) => {
128
+ w.sessionID = sessionID;
129
+ if (w.status === "starting")
130
+ w.status = "running"; // it may have finished already
131
+ if (b.stopping && w.status === "running")
132
+ void b.deps.stopWorker(sessionID).catch(() => { });
133
+ }).catch((e) => {
134
+ w.status = "failed";
135
+ w.reason = String(e?.message ?? e).slice(0, 300);
136
+ b.reserved.delete(w.target);
137
+ pump(b);
138
+ });
139
+ }
140
+ function snapshot(b) {
141
+ for (const w of b.state.workers) {
142
+ if (w.status === "running" && w.sessionID)
143
+ w.recon = b.deps.workerState(w.sessionID) ?? w.recon;
144
+ }
145
+ if (b.state.status === "running")
146
+ b.state.tokens = spent(b);
147
+ return b.state;
148
+ }
149
+ /** Start a batch. One at a time: the workers share one agent, and its memory and CPU. */
150
+ export function startBatch(o) {
151
+ for (const b of batches.values())
152
+ if (b.state.status === "running")
153
+ throw httpError(409, "A batch is already running. Stop it, or wait for it to finish.");
154
+ const targets = parseTargets([...o.targets]);
155
+ if (o.totalBudgetTokens !== undefined && o.totalBudgetTokens < MIN_WORKER_BUDGET) {
156
+ throw httpError(400, `The batch's token budget must be at least ${MIN_WORKER_BUDGET}.`);
157
+ }
158
+ const state = {
159
+ id: crypto.randomBytes(8).toString("hex"), status: "running", maxWorkers: resolveWorkers(o.maxWorkers),
160
+ ...(o.totalBudgetTokens !== undefined ? { budgetTokens: o.totalBudgetTokens } : {}),
161
+ tokens: 0, workers: targets.map((target) => ({ target, status: "queued" })), startedAt: Date.now(),
162
+ };
163
+ const b = { state, directory: o.directory, deps: o.deps, workerBudget: o.workerBudgetTokens, reserved: new Map(), stopping: false };
164
+ batches.set(state.id, b);
165
+ o.deps.log?.("recon.batch.started", { batch: state.id, targets: targets.length, maxWorkers: state.maxWorkers, budgetTokens: state.budgetTokens });
166
+ pump(b);
167
+ return snapshot(b);
168
+ }
169
+ /** A batch by id, or the most recent one when no id is given. */
170
+ export function batchState(id) {
171
+ const b = id ? batches.get(id) : [...batches.values()].pop();
172
+ return b ? snapshot(b) : null;
173
+ }
174
+ /** The project folder a batch's sessions live in. */
175
+ export function batchDirectory(id) {
176
+ return batches.get(id)?.directory;
177
+ }
178
+ /** Stop a batch: nothing queued is started, and every running worker is stopped. */
179
+ export async function stopBatch(id) {
180
+ const b = batches.get(id);
181
+ if (!b)
182
+ return null;
183
+ if (b.state.status === "running") {
184
+ b.stopping = true;
185
+ b.state.stopped = true;
186
+ for (const w of b.state.workers)
187
+ if (w.status === "queued") {
188
+ w.status = "skipped";
189
+ w.reason = "the batch was stopped";
190
+ }
191
+ await Promise.all(b.state.workers.filter((w) => w.status === "running" && w.sessionID).map((w) => b.deps.stopWorker(w.sessionID).catch(() => { })));
192
+ finishIfDone(b); // workers still starting are stopped as they come up, and end the batch then
193
+ }
194
+ return snapshot(b);
195
+ }
196
+ /** Forget finished batches (tests, and a tidy map). */
197
+ export function clearBatches() {
198
+ for (const [id, b] of batches)
199
+ if (b.state.status === "finished")
200
+ batches.delete(id);
201
+ }
202
+ //# sourceMappingURL=recon-batch.js.map