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.
- package/README.md +261 -53
- package/package.json +1 -1
- package/server/dist/auth.js +4 -0
- package/server/dist/index.js +202 -11
- package/server/dist/recon-batch.js +202 -0
- package/server/dist/recon-driver.js +315 -13
- package/server/dist/recon-evidence.js +53 -0
- package/server/dist/recon-memory.js +227 -0
- package/server/dist/recon-run.js +43 -3
- package/server/dist/recon-session.js +260 -0
- package/server/dist/recon.js +47 -6
- package/server/dist/vault.js +11 -0
- package/server/dist/zip.js +54 -0
- package/web/dist/assets/index-DTJE8gwZ.js +303 -0
- package/web/dist/assets/{index-BFQ6vQM0.css → index-Du7TnY-M.css} +1 -1
- package/web/dist/bxh-extension/background.js +21 -0
- package/web/dist/bxh-extension/manifest.json +11 -0
- package/web/dist/bxh-extension/payload.d.ts +12 -0
- package/web/dist/bxh-extension/payload.js +43 -0
- package/web/dist/bxh-extension/popup.css +14 -0
- package/web/dist/bxh-extension/popup.html +24 -0
- package/web/dist/bxh-extension/popup.js +61 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-BK5H1djd.js +0 -303
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What supervised recon runs found, kept between runs and across restarts, encrypted with
|
|
3
|
+
* the vault key.
|
|
4
|
+
*
|
|
5
|
+
* One file per finished run next to the vault: /data/recon in Docker (the runner-only
|
|
6
|
+
* runner-data volume, never the agent's), ~/.config/bugxhunter/recon otherwise. Only an id
|
|
7
|
+
* and the finish time are in the clear; the target, the session and everything the run
|
|
8
|
+
* found are sealed, bound to the record by its AAD. A copied volume shows how many runs
|
|
9
|
+
* there were and when, nothing about what was tested or found.
|
|
10
|
+
*
|
|
11
|
+
* Two things read it back: a new run on the same target starts from what earlier runs
|
|
12
|
+
* verified there (`recall`), and a session shows its last run again after a restart
|
|
13
|
+
* (`lastForSession`). Without a vault nothing is kept; with a locked one a finished run
|
|
14
|
+
* waits in memory and is written when the vault is next unlocked.
|
|
15
|
+
*/
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import crypto from "node:crypto";
|
|
19
|
+
import { VAULT_FILE, isInitialised, isUnsealed, onUnsealed, openData, sealData } from "./vault.js";
|
|
20
|
+
import { httpError } from "./errors.js";
|
|
21
|
+
import { audit } from "./audit.js";
|
|
22
|
+
import { originOf } from "./recon.js";
|
|
23
|
+
const dir = () => process.env.OPEN_RUNNER_RECON_DIR ?? path.join(path.dirname(VAULT_FILE), "recon");
|
|
24
|
+
/** Runs kept in all; the oldest are dropped past this. */
|
|
25
|
+
export const MAX_RUNS = 300;
|
|
26
|
+
/** What one recall hands a new run: enough to start from, not the whole history. */
|
|
27
|
+
const MAX_RECALLED_FINDINGS = 40;
|
|
28
|
+
const MAX_RECALLED_PATHS = 10;
|
|
29
|
+
const MAX_RECALLED_LEADS = 15;
|
|
30
|
+
const MAX_PENDING = 20;
|
|
31
|
+
const ID = /^[0-9]{13}-[a-f0-9]{12}$/;
|
|
32
|
+
const aad = (id) => `recon:${id}:body`;
|
|
33
|
+
const file = (id) => path.join(dir(), `${id}.json`);
|
|
34
|
+
/** The key runs are grouped by: the target's host and port, whatever path or scheme the scope was typed with. */
|
|
35
|
+
export function targetKey(scope) {
|
|
36
|
+
const { host, port } = originOf(scope.trim());
|
|
37
|
+
return host ? `${host}:${port}` : undefined;
|
|
38
|
+
}
|
|
39
|
+
function ids() {
|
|
40
|
+
try {
|
|
41
|
+
return fs.readdirSync(dir()).filter((n) => n.endsWith(".json")).map((n) => n.slice(0, -5)).filter((id) => ID.test(id)).sort();
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Every stored run that opens with the current vault, oldest first. Throws 503 while the vault is locked. */
|
|
48
|
+
function all() {
|
|
49
|
+
// Said even when nothing is stored yet, so "locked" is never shown as "nothing remembered".
|
|
50
|
+
if (isInitialised() && !isUnsealed())
|
|
51
|
+
throw httpError(503, "The vault is sealed (locked). Unlock it to read what earlier runs found.");
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const id of ids()) {
|
|
54
|
+
let r;
|
|
55
|
+
try {
|
|
56
|
+
r = JSON.parse(fs.readFileSync(file(id), "utf8"));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (r?.v !== 1 || r.id !== id)
|
|
62
|
+
continue;
|
|
63
|
+
try {
|
|
64
|
+
const body = JSON.parse(openData(r.body, aad(id)));
|
|
65
|
+
if (typeof body.target === "string" && body.state && Array.isArray(body.state.findings))
|
|
66
|
+
out.push({ id, target: body.target, state: body.state });
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
if (e.status === 503)
|
|
70
|
+
throw e;
|
|
71
|
+
// a record from another vault, or a tampered one: skipped, not fatal
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
/** The same, or nothing when the vault is locked or absent: reading memory never fails a run. */
|
|
77
|
+
function allOrNone() {
|
|
78
|
+
try {
|
|
79
|
+
return all();
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function write(state) {
|
|
86
|
+
const target = targetKey(state.scope);
|
|
87
|
+
if (!target)
|
|
88
|
+
return;
|
|
89
|
+
const finishedAt = state.finishedAt ?? Date.now();
|
|
90
|
+
const id = `${String(finishedAt).padStart(13, "0")}-${crypto.randomBytes(6).toString("hex")}`;
|
|
91
|
+
const record = { v: 1, id, finishedAt: new Date(finishedAt).toISOString(), body: sealData(JSON.stringify({ target, state }), aad(id)) };
|
|
92
|
+
fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
|
|
93
|
+
const tmp = `${file(id)}.${process.pid}.tmp`;
|
|
94
|
+
fs.writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 });
|
|
95
|
+
fs.renameSync(tmp, file(id));
|
|
96
|
+
const have = ids();
|
|
97
|
+
for (const old of have.slice(0, Math.max(0, have.length - MAX_RUNS)))
|
|
98
|
+
fs.rmSync(file(old), { force: true });
|
|
99
|
+
}
|
|
100
|
+
/** Finished runs that could not be written because the vault was locked. Held in this process only. */
|
|
101
|
+
const pending = [];
|
|
102
|
+
/**
|
|
103
|
+
* Keep a finished run. `saved`: written. `pending`: the vault is locked, so it waits in
|
|
104
|
+
* memory until the next unlock (and is lost if the runner restarts first). `off`: there is
|
|
105
|
+
* no vault, or the write failed, and nothing is kept.
|
|
106
|
+
*/
|
|
107
|
+
export function remember(state) {
|
|
108
|
+
if (state.status !== "finished")
|
|
109
|
+
return "off";
|
|
110
|
+
try {
|
|
111
|
+
write(state);
|
|
112
|
+
audit("recon.remembered", { session: state.sessionID, findings: state.findings.length, paths: state.chains?.length ?? 0 });
|
|
113
|
+
return "saved";
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
if (e.status === 503) {
|
|
117
|
+
pending.push(state);
|
|
118
|
+
if (pending.length > MAX_PENDING)
|
|
119
|
+
pending.shift();
|
|
120
|
+
return "pending";
|
|
121
|
+
}
|
|
122
|
+
return "off";
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Write the runs that finished while the vault was locked. */
|
|
126
|
+
export function flushPending() {
|
|
127
|
+
for (const state of pending.splice(0)) {
|
|
128
|
+
try {
|
|
129
|
+
write(state);
|
|
130
|
+
state.kept = "saved";
|
|
131
|
+
audit("recon.remembered", { session: state.sessionID, findings: state.findings.length, paths: state.chains?.length ?? 0, late: true });
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
// still not writable: this run is not kept
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
onUnsealed(flushPending);
|
|
139
|
+
const sameFinding = (title, standardId) => `${title.toLowerCase().replace(/\s+/g, " ").trim()}|${(standardId ?? "").toLowerCase()}`;
|
|
140
|
+
/** What earlier runs on a target verified, newest first and without repeats. */
|
|
141
|
+
export function recallFrom(runs) {
|
|
142
|
+
if (!runs.length)
|
|
143
|
+
return undefined;
|
|
144
|
+
const newestFirst = [...runs].sort((a, b) => (b.finishedAt ?? b.startedAt) - (a.finishedAt ?? a.startedAt));
|
|
145
|
+
const findings = new Map();
|
|
146
|
+
const paths = new Map();
|
|
147
|
+
// A finding a later run retested and found fixed is no longer a lead: older runs' record of it is passed over.
|
|
148
|
+
const fixed = new Set();
|
|
149
|
+
for (const run of newestFirst) {
|
|
150
|
+
const seen = run.finishedAt ?? run.startedAt;
|
|
151
|
+
for (const r of run.retests ?? []) {
|
|
152
|
+
const key = sameFinding(r.title, r.standardId);
|
|
153
|
+
if (r.result === "fixed" && !findings.has(key))
|
|
154
|
+
fixed.add(key);
|
|
155
|
+
}
|
|
156
|
+
for (const f of run.findings) {
|
|
157
|
+
if (f.verdict === "rejected")
|
|
158
|
+
continue;
|
|
159
|
+
const key = sameFinding(f.title, f.standardId);
|
|
160
|
+
if (fixed.has(key))
|
|
161
|
+
continue;
|
|
162
|
+
const known = findings.get(key);
|
|
163
|
+
if (known) {
|
|
164
|
+
known.runs += 1;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
findings.set(key, { title: f.title, severity: f.severity, verdict: f.verdict, standardId: f.standardId, repro: f.repro, env: f.env, seen, runs: 1 });
|
|
168
|
+
}
|
|
169
|
+
for (const c of run.chains ?? []) {
|
|
170
|
+
const key = sameFinding(c.title);
|
|
171
|
+
if (paths.has(key))
|
|
172
|
+
continue;
|
|
173
|
+
paths.set(key, { title: c.title, severity: c.severity, status: c.status, impact: c.impact, steps: c.steps.map((s) => s.action), seen });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const rank = { critical: 3, high: 2, medium: 1, low: 0 };
|
|
177
|
+
// Only the newest exploring run's open leads: an older run's were either followed since or are stale.
|
|
178
|
+
const lastExplored = newestFirst.find((r) => r.mode !== "retest");
|
|
179
|
+
const leads = (lastExplored?.leads ?? []).filter((l) => l.status === "open").map((l) => l.text).slice(0, MAX_RECALLED_LEADS);
|
|
180
|
+
return {
|
|
181
|
+
runs: runs.length,
|
|
182
|
+
...(leads.length ? { leads } : {}),
|
|
183
|
+
lastRun: newestFirst[0].finishedAt ?? newestFirst[0].startedAt,
|
|
184
|
+
findings: [...findings.values()].sort((a, b) => rank[b.severity] - rank[a.severity] || b.seen - a.seen).slice(0, MAX_RECALLED_FINDINGS),
|
|
185
|
+
// Demonstrated paths first: a partial one is only a lead.
|
|
186
|
+
paths: [...paths.values()].sort((a, b) => Number(b.status === "demonstrated") - Number(a.status === "demonstrated") || b.seen - a.seen).slice(0, MAX_RECALLED_PATHS),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/** What earlier runs verified on this target, or undefined when there is nothing (or the vault is locked). */
|
|
190
|
+
export function recall(scope) {
|
|
191
|
+
const target = targetKey(scope);
|
|
192
|
+
if (!target)
|
|
193
|
+
return undefined;
|
|
194
|
+
return recallFrom(allOrNone().filter((r) => r.target === target).map((r) => r.state));
|
|
195
|
+
}
|
|
196
|
+
/** The last finished run on a session, so its results are still there after a restart. */
|
|
197
|
+
export function lastForSession(sessionID) {
|
|
198
|
+
if (!sessionID)
|
|
199
|
+
return null;
|
|
200
|
+
const mine = allOrNone().filter((r) => r.state.sessionID === sessionID);
|
|
201
|
+
return mine.length ? { ...mine[mine.length - 1].state, kept: "saved" } : null;
|
|
202
|
+
}
|
|
203
|
+
/** The targets something is remembered about, most recent first. Throws 503 while the vault is locked. */
|
|
204
|
+
export function targets() {
|
|
205
|
+
const by = new Map();
|
|
206
|
+
for (const r of all())
|
|
207
|
+
by.set(r.target, [...(by.get(r.target) ?? []), r.state]);
|
|
208
|
+
return [...by.entries()].map(([target, runs]) => {
|
|
209
|
+
const r = recallFrom(runs);
|
|
210
|
+
return { target, runs: r.runs, findings: r.findings.length, paths: r.paths.length, lastRun: r.lastRun };
|
|
211
|
+
}).sort((a, b) => b.lastRun - a.lastRun);
|
|
212
|
+
}
|
|
213
|
+
/** Forget every run on one target. Returns how many were deleted. Throws 503 while the vault is locked. */
|
|
214
|
+
export function forget(scope) {
|
|
215
|
+
const target = targetKey(scope);
|
|
216
|
+
if (!target)
|
|
217
|
+
return 0;
|
|
218
|
+
const mine = all().filter((r) => r.target === target);
|
|
219
|
+
for (const r of mine)
|
|
220
|
+
fs.rmSync(file(r.id), { force: true });
|
|
221
|
+
for (let i = pending.length - 1; i >= 0; i--)
|
|
222
|
+
if (targetKey(pending[i].scope) === target)
|
|
223
|
+
pending.splice(i, 1);
|
|
224
|
+
audit("recon.forgotten", { runs: mine.length });
|
|
225
|
+
return mine.length;
|
|
226
|
+
}
|
|
227
|
+
//# sourceMappingURL=recon-memory.js.map
|
package/server/dist/recon-run.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { driveRecon, extractReconCommand, parseTurnStatus, parseVerifierFindings, resolveHarness, } from "./recon-driver.js";
|
|
2
2
|
import { activeProfileName, originOf } from "./recon.js";
|
|
3
3
|
import { httpError } from "./errors.js";
|
|
4
|
+
import { EvidenceLog } from "./recon-evidence.js";
|
|
4
5
|
/** The agent the driver prompts, and the subagent whose replies are verdicts. */
|
|
5
6
|
export const EXECUTOR_AGENT = "recon";
|
|
6
7
|
export const VERIFY_AGENT = "recon-verify";
|
|
@@ -39,6 +40,9 @@ export class OpencodeReconRunner {
|
|
|
39
40
|
toolInputs = new Map();
|
|
40
41
|
handledPermissions = new Set();
|
|
41
42
|
verified = new Set();
|
|
43
|
+
/** What the run's shell commands really returned, from the event stream: what quotes are held to. */
|
|
44
|
+
evidence = new EvidenceLog();
|
|
45
|
+
recorded = new Set();
|
|
42
46
|
capped = new Map();
|
|
43
47
|
constructor(backend, sessionID, env, onGate = () => { }) {
|
|
44
48
|
this.backend = backend;
|
|
@@ -91,6 +95,8 @@ export class OpencodeReconRunner {
|
|
|
91
95
|
this.sub = null;
|
|
92
96
|
}
|
|
93
97
|
get wasAborted() { return this.aborted; }
|
|
98
|
+
/** Hold quotes to what this run's commands really returned. */
|
|
99
|
+
proof(quotes) { return this.evidence.check(quotes); }
|
|
94
100
|
/** Does this run own `sessionID` (the root or one of its subagent sessions)? */
|
|
95
101
|
owns(sessionID) { return this.family.has(sessionID); }
|
|
96
102
|
async runTurn(args) {
|
|
@@ -213,6 +219,11 @@ export class OpencodeReconRunner {
|
|
|
213
219
|
this.toolInputs.set(part.callID, st.input);
|
|
214
220
|
if (st.status !== "completed" && st.status !== "error")
|
|
215
221
|
return;
|
|
222
|
+
// Every shell command of the run, the subagents' included: its output is the record quotes are checked against.
|
|
223
|
+
if (part.tool === "bash" && part.callID && typeof st.output === "string" && !this.recorded.has(part.callID)) {
|
|
224
|
+
this.recorded.add(part.callID);
|
|
225
|
+
this.evidence.add(st.output);
|
|
226
|
+
}
|
|
216
227
|
if (part.sessionID !== this.sessionID || !this.turn)
|
|
217
228
|
return;
|
|
218
229
|
this.turn.toolsCompleted.add(part.callID);
|
|
@@ -223,7 +234,7 @@ export class OpencodeReconRunner {
|
|
|
223
234
|
if ((input.subagent_type ?? input.agent) !== VERIFY_AGENT || typeof st.output !== "string")
|
|
224
235
|
return;
|
|
225
236
|
this.verified.add(part.callID);
|
|
226
|
-
this.turn.findings.push(...parseVerifierFindings(st.output, this.env));
|
|
237
|
+
this.turn.findings.push(...parseVerifierFindings(st.output, this.env).map((f) => ({ ...f, proof: this.evidence.check(f.quotes) })));
|
|
227
238
|
this.turn.verifierOutputs.push(st.output);
|
|
228
239
|
}
|
|
229
240
|
onPermission(perm) {
|
|
@@ -313,6 +324,9 @@ export async function startRecon(o) {
|
|
|
313
324
|
sessionID: o.sessionID, scope, objective, env: o.env, profile: activeProfileName(),
|
|
314
325
|
status: "running", rounds: 0, maxRounds: harness.maxRounds, tokens: 0, budgetTokens: harness.budgetTokens,
|
|
315
326
|
gate: { allowed: 0, asked: 0, denied: 0 }, findings: [], startedAt: Date.now(),
|
|
327
|
+
...(o.retest?.length ? { mode: "retest", retests: [] } : {}),
|
|
328
|
+
...(o.session ? { session: { capturedAt: o.session.capturedAt, cookies: o.session.cookies, authorization: o.session.authorization } } : {}),
|
|
329
|
+
...(o.prior ? { memory: { runs: o.prior.runs, findings: o.prior.findings.length, paths: o.prior.paths.length, lastRun: o.prior.lastRun } } : {}),
|
|
316
330
|
};
|
|
317
331
|
const run = { state, runner };
|
|
318
332
|
await runner.start(); // subscribed before the first prompt, so no event is missed
|
|
@@ -320,6 +334,7 @@ export async function startRecon(o) {
|
|
|
320
334
|
o.log?.("recon.started", { session: o.sessionID, scope, objective, env: o.env, profile: state.profile, maxRounds: state.maxRounds, budgetTokens: state.budgetTokens });
|
|
321
335
|
let lastError;
|
|
322
336
|
const seam = {
|
|
337
|
+
proof: (quotes) => runner.proof(quotes),
|
|
323
338
|
async runTurn(args) {
|
|
324
339
|
try {
|
|
325
340
|
const res = await runner.runTurn(args);
|
|
@@ -339,20 +354,45 @@ export async function startRecon(o) {
|
|
|
339
354
|
}
|
|
340
355
|
state.chains = [...chains];
|
|
341
356
|
};
|
|
342
|
-
|
|
357
|
+
const onRetest = (retests) => { state.retests = [...retests]; };
|
|
358
|
+
const onLeads = (leads) => { state.leads = leads.map((l) => ({ ...l })); };
|
|
359
|
+
// A path recorded during the main loop: shown at once, and the run stays in its main phase.
|
|
360
|
+
const onChains = (chains) => { state.chains = [...chains]; };
|
|
361
|
+
void driveRecon({ objective, scope, env: o.env, runner: seam, harness, rateLimited: () => runner.rateLimited(), onChainPass, onChains, prior: o.prior, session: o.session, retest: o.retest, onRetest, onLeads })
|
|
343
362
|
.then((result) => {
|
|
344
363
|
snapshot(run); // last live numbers before the status flips
|
|
345
364
|
state.status = "finished";
|
|
346
365
|
state.stopped = runner.wasAborted ? "aborted" : result.stopped;
|
|
347
366
|
state.findings = result.findings;
|
|
348
367
|
state.chains = result.chains;
|
|
349
|
-
|
|
368
|
+
if (result.leads.length)
|
|
369
|
+
state.leads = result.leads;
|
|
370
|
+
if (result.retests)
|
|
371
|
+
state.retests = result.retests;
|
|
372
|
+
else
|
|
373
|
+
state.chainPass = result.chainPass; // a retest run has no chain pass to report on
|
|
350
374
|
state.rounds = result.rounds;
|
|
351
375
|
state.chainRounds = result.chainRounds;
|
|
352
376
|
if (state.stopped === "error")
|
|
353
377
|
state.error = lastError;
|
|
354
378
|
state.finishedAt = Date.now();
|
|
355
379
|
runner.close();
|
|
380
|
+
try {
|
|
381
|
+
o.session?.cleanup();
|
|
382
|
+
}
|
|
383
|
+
catch { /* the folder is gone or not ours to remove */ }
|
|
384
|
+
if (o.remember) {
|
|
385
|
+
try {
|
|
386
|
+
state.kept = o.remember(state);
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
state.kept = "off";
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
try {
|
|
393
|
+
o.onFinished?.(state);
|
|
394
|
+
}
|
|
395
|
+
catch { /* the listener's failure is not the run's */ }
|
|
356
396
|
o.log?.("recon.finished", {
|
|
357
397
|
session: o.sessionID, stopped: state.stopped, rounds: state.rounds, tokens: state.tokens,
|
|
358
398
|
gate: state.gate, findings: state.findings, chainPass: state.chainPass, chains: state.chains, error: state.error,
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A logged-in session for a recon target: the cookies (and, if the app uses one, the
|
|
3
|
+
* Authorization header) of a browser the person logged in with themselves, so the test can
|
|
4
|
+
* go past the login screen, 2FA included.
|
|
5
|
+
*
|
|
6
|
+
* How it gets here: the person asks the runner for a pairing code for one target, pastes it
|
|
7
|
+
* into the BugXHunter browser extension, logs in to the target and presses send. The
|
|
8
|
+
* extension posts the session with the code; the code is single-use, expires in ten
|
|
9
|
+
* minutes, and only accepts a session for the target it was issued for.
|
|
10
|
+
*
|
|
11
|
+
* Where it lives: sealed with the vault key next to the vault (sessions/, on the runner-only
|
|
12
|
+
* volume in Docker), one file per target, nothing about the target in the clear. For a run
|
|
13
|
+
* it is written into the project folder as two files curl can read (a cookie jar and a
|
|
14
|
+
* header file) and removed when the run ends. The values are never put in a prompt; the
|
|
15
|
+
* agent is given the file names. It can still read the files: use a test account.
|
|
16
|
+
*/
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import crypto from "node:crypto";
|
|
20
|
+
import { VAULT_FILE, isInitialised, isUnsealed, openData, sealData } from "./vault.js";
|
|
21
|
+
import { httpError } from "./errors.js";
|
|
22
|
+
import { audit } from "./audit.js";
|
|
23
|
+
import { originOf } from "./recon.js";
|
|
24
|
+
import { isInside, projectPath } from "./opencode.js";
|
|
25
|
+
const dir = () => process.env.OPEN_RUNNER_SESSION_DIR ?? path.join(path.dirname(VAULT_FILE), "sessions");
|
|
26
|
+
export const PAIRING_TTL_MS = 10 * 60_000;
|
|
27
|
+
const MAX_PAIRINGS = 5;
|
|
28
|
+
const MAX_COOKIES = 150;
|
|
29
|
+
const MAX_VALUE = 8192;
|
|
30
|
+
const MAX_TARGETS = 100;
|
|
31
|
+
/** The folder, inside the project, that holds session files: one subfolder per run. */
|
|
32
|
+
export const SESSION_FOLDER = ".bugxhunter";
|
|
33
|
+
const ID = /^[a-f0-9]{24}$/;
|
|
34
|
+
const key = (scope) => {
|
|
35
|
+
const { host, port } = originOf(scope.trim());
|
|
36
|
+
return host ? `${host}:${port}` : undefined;
|
|
37
|
+
};
|
|
38
|
+
/* ─────────────── reading what the extension sent ─────────────── */
|
|
39
|
+
/** A cookie name, per RFC 6265: a token. */
|
|
40
|
+
const NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]{1,256}$/;
|
|
41
|
+
/** No control characters, so a value can never start a new line in the jar or the header file. */
|
|
42
|
+
const CLEAN = /^[^\x00-\x1f\x7f]*$/;
|
|
43
|
+
const HOST = /^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/;
|
|
44
|
+
/** Would a cookie with this domain be sent to `host`? */
|
|
45
|
+
function sentTo(host, domain, subdomains) {
|
|
46
|
+
return host === domain || (subdomains && host.endsWith(`.${domain}`));
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Validate a capture and keep only what belongs to the target: cookies the browser would
|
|
50
|
+
* send to its host, with clean names and values. Anything malformed is dropped, and a
|
|
51
|
+
* capture with nothing usable left is refused.
|
|
52
|
+
*/
|
|
53
|
+
export function parseCapture(raw, scope, now = Date.now()) {
|
|
54
|
+
const target = key(scope);
|
|
55
|
+
const host = originOf(scope).host;
|
|
56
|
+
if (!target || !host)
|
|
57
|
+
throw httpError(400, "The pairing code is not for a valid target.");
|
|
58
|
+
const r = (raw && typeof raw === "object" ? raw : {});
|
|
59
|
+
const from = typeof r.origin === "string" ? key(r.origin) : undefined;
|
|
60
|
+
if (from !== target)
|
|
61
|
+
throw httpError(400, `This pairing code is for ${target}. Open that site's tab and send again.`);
|
|
62
|
+
const cookies = [];
|
|
63
|
+
for (const c of Array.isArray(r.cookies) ? r.cookies.slice(0, 1000) : []) {
|
|
64
|
+
const o = (c && typeof c === "object" ? c : {});
|
|
65
|
+
const name = typeof o.name === "string" ? o.name : "";
|
|
66
|
+
const value = typeof o.value === "string" ? o.value : "";
|
|
67
|
+
const rawDomain = typeof o.domain === "string" ? o.domain.trim().toLowerCase() : "";
|
|
68
|
+
const domain = rawDomain.replace(/^\./, "");
|
|
69
|
+
const subdomains = o.hostOnly === false || (o.hostOnly === undefined && rawDomain.startsWith("."));
|
|
70
|
+
const p = typeof o.path === "string" && o.path.startsWith("/") ? o.path : "/";
|
|
71
|
+
if (!NAME.test(name) || value.length > MAX_VALUE || !CLEAN.test(value) || /\s/.test(value))
|
|
72
|
+
continue;
|
|
73
|
+
if (!HOST.test(domain) || !sentTo(host, domain, subdomains))
|
|
74
|
+
continue;
|
|
75
|
+
if (p.length > 1024 || !CLEAN.test(p) || /\s/.test(p))
|
|
76
|
+
continue;
|
|
77
|
+
const expires = typeof o.expirationDate === "number" && Number.isFinite(o.expirationDate) ? Math.floor(o.expirationDate) : undefined;
|
|
78
|
+
if (expires !== undefined && expires * 1000 <= now)
|
|
79
|
+
continue; // already expired
|
|
80
|
+
cookies.push({ name, value, domain, subdomains, path: p, secure: o.secure === true, httpOnly: o.httpOnly === true, ...(expires !== undefined ? { expires } : {}) });
|
|
81
|
+
if (cookies.length >= MAX_COOKIES)
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
const auth = typeof r.authorization === "string" ? r.authorization.trim() : "";
|
|
85
|
+
const authorization = auth && auth.length <= MAX_VALUE && CLEAN.test(auth) ? auth : undefined;
|
|
86
|
+
if (!cookies.length && !authorization)
|
|
87
|
+
throw httpError(400, "Nothing to capture: no cookies for this site and no Authorization header seen. Log in first, then send.");
|
|
88
|
+
return { target, capturedAt: now, cookies, ...(authorization ? { authorization } : {}) };
|
|
89
|
+
}
|
|
90
|
+
const pairings = new Map();
|
|
91
|
+
const digest = (token) => crypto.createHash("sha256").update(token).digest("hex");
|
|
92
|
+
/** A single-use code the extension sends a session with. Good for one target, for ten minutes. */
|
|
93
|
+
export function issuePairing(scope, now = Date.now()) {
|
|
94
|
+
const target = key(scope);
|
|
95
|
+
if (!target)
|
|
96
|
+
throw httpError(400, "scope must be one host or URL");
|
|
97
|
+
if (!isInitialised())
|
|
98
|
+
throw httpError(409, "Set up the vault (sidebar → keys) first: a captured session is encrypted with it.");
|
|
99
|
+
if (!isUnsealed())
|
|
100
|
+
throw httpError(503, "The vault is sealed (locked). Unlock it to capture a session.");
|
|
101
|
+
for (const [k, p] of pairings)
|
|
102
|
+
if (p.expiresAt <= now)
|
|
103
|
+
pairings.delete(k);
|
|
104
|
+
while (pairings.size >= MAX_PAIRINGS)
|
|
105
|
+
pairings.delete(pairings.keys().next().value);
|
|
106
|
+
const token = crypto.randomBytes(24).toString("base64url");
|
|
107
|
+
const expiresAt = now + PAIRING_TTL_MS;
|
|
108
|
+
pairings.set(digest(token), { scope: scope.trim(), target, expiresAt });
|
|
109
|
+
audit("recon.session.pairing", {});
|
|
110
|
+
return { token, target, expiresAt };
|
|
111
|
+
}
|
|
112
|
+
/** The extension's post: check the code, keep the session, and spend the code. */
|
|
113
|
+
export function redeem(token, raw, now = Date.now()) {
|
|
114
|
+
const id = typeof token === "string" && token ? digest(token) : "";
|
|
115
|
+
const p = pairings.get(id);
|
|
116
|
+
if (!p || p.expiresAt <= now) {
|
|
117
|
+
if (p)
|
|
118
|
+
pairings.delete(id);
|
|
119
|
+
audit("recon.session.refused", { reason: "code" });
|
|
120
|
+
throw httpError(401, "That pairing code is not valid or has expired. Get a new one in BugXHunter's recon dialog.");
|
|
121
|
+
}
|
|
122
|
+
const session = parseCapture(raw, p.scope, now); // a bad capture leaves the code usable: fix and resend
|
|
123
|
+
save(session);
|
|
124
|
+
pairings.delete(id);
|
|
125
|
+
audit("recon.session.captured", { cookies: session.cookies.length, authorization: Boolean(session.authorization) });
|
|
126
|
+
return info(session);
|
|
127
|
+
}
|
|
128
|
+
const aad = (id) => `recon-session:${id}:body`;
|
|
129
|
+
const file = (id) => path.join(dir(), `${id}.json`);
|
|
130
|
+
function stored() {
|
|
131
|
+
if (isInitialised() && !isUnsealed())
|
|
132
|
+
throw httpError(503, "The vault is sealed (locked). Unlock it to use a captured session.");
|
|
133
|
+
let names;
|
|
134
|
+
try {
|
|
135
|
+
names = fs.readdirSync(dir());
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return [];
|
|
139
|
+
}
|
|
140
|
+
const out = [];
|
|
141
|
+
for (const name of names) {
|
|
142
|
+
const id = name.endsWith(".json") ? name.slice(0, -5) : "";
|
|
143
|
+
if (!ID.test(id))
|
|
144
|
+
continue;
|
|
145
|
+
try {
|
|
146
|
+
const r = JSON.parse(fs.readFileSync(file(id), "utf8"));
|
|
147
|
+
if (r?.v !== 1 || r.id !== id)
|
|
148
|
+
continue;
|
|
149
|
+
const session = JSON.parse(openData(r.body, aad(id)));
|
|
150
|
+
if (typeof session?.target === "string" && Array.isArray(session.cookies))
|
|
151
|
+
out.push({ id, session });
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
if (e.status === 503)
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
function save(session) {
|
|
161
|
+
const all = stored();
|
|
162
|
+
const prev = all.find((s) => s.session.target === session.target);
|
|
163
|
+
if (!prev && all.length >= MAX_TARGETS)
|
|
164
|
+
throw httpError(409, `Sessions for up to ${MAX_TARGETS} targets are kept; forget some first.`);
|
|
165
|
+
const id = prev?.id ?? crypto.randomBytes(12).toString("hex");
|
|
166
|
+
const record = { v: 1, id, body: sealData(JSON.stringify(session), aad(id)) };
|
|
167
|
+
fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
|
|
168
|
+
const tmp = `${file(id)}.${process.pid}.tmp`;
|
|
169
|
+
fs.writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 });
|
|
170
|
+
fs.renameSync(tmp, file(id));
|
|
171
|
+
}
|
|
172
|
+
function info(s) {
|
|
173
|
+
const expiries = s.cookies.map((c) => c.expires).filter((e) => e !== undefined);
|
|
174
|
+
return {
|
|
175
|
+
target: s.target, capturedAt: s.capturedAt, cookies: s.cookies.length, authorization: Boolean(s.authorization),
|
|
176
|
+
...(expiries.length ? { firstExpiry: Math.min(...expiries) * 1000 } : {}),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
function find(scope) {
|
|
180
|
+
const target = key(scope);
|
|
181
|
+
return target ? stored().find((s) => s.session.target === target)?.session : undefined;
|
|
182
|
+
}
|
|
183
|
+
/** What is held for a target, without any value. Throws 503 while the vault is locked. */
|
|
184
|
+
export function sessionInfo(scope) {
|
|
185
|
+
const s = find(scope);
|
|
186
|
+
return s ? info(s) : null;
|
|
187
|
+
}
|
|
188
|
+
/** Forget the session held for a target. */
|
|
189
|
+
export function forgetSession(scope) {
|
|
190
|
+
const target = key(scope);
|
|
191
|
+
const hit = target ? stored().find((s) => s.session.target === target) : undefined;
|
|
192
|
+
if (!hit)
|
|
193
|
+
return false;
|
|
194
|
+
fs.rmSync(file(hit.id), { force: true });
|
|
195
|
+
audit("recon.session.forgotten", {});
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
/* ─────────────── handing it to a run ─────────────── */
|
|
199
|
+
/**
|
|
200
|
+
* The cookies as a Netscape cookie jar, the format `curl -b <file>` reads: curl then sends
|
|
201
|
+
* each cookie only where its domain, path and secure flag allow, as the browser would.
|
|
202
|
+
* Expired cookies are left out. A session cookie has expiry 0.
|
|
203
|
+
*/
|
|
204
|
+
export function cookieJar(cookies, now = Date.now()) {
|
|
205
|
+
const lines = ["# Netscape HTTP Cookie File", "# Written by BugXHunter for one recon run. Removed when the run ends."];
|
|
206
|
+
for (const c of cookies) {
|
|
207
|
+
if (c.expires !== undefined && c.expires * 1000 <= now)
|
|
208
|
+
continue;
|
|
209
|
+
const domain = `${c.httpOnly ? "#HttpOnly_" : ""}${c.subdomains ? "." : ""}${c.domain}`;
|
|
210
|
+
lines.push([domain, c.subdomains ? "TRUE" : "FALSE", c.path, c.secure ? "TRUE" : "FALSE", String(c.expires ?? 0), c.name, c.value].join("\t"));
|
|
211
|
+
}
|
|
212
|
+
return lines.join("\n") + "\n";
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Write a target's session into the project folder for one run, and say where. Returns
|
|
216
|
+
* undefined when nothing is held for the target (or the vault is locked: a run never
|
|
217
|
+
* fails for want of a session it was only offered). `cleanup` removes the files.
|
|
218
|
+
*/
|
|
219
|
+
export function materialise(scope, directory, now = Date.now()) {
|
|
220
|
+
let s;
|
|
221
|
+
try {
|
|
222
|
+
s = find(scope);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
if (!s)
|
|
228
|
+
return undefined;
|
|
229
|
+
const live = s.cookies.filter((c) => c.expires === undefined || c.expires * 1000 > now);
|
|
230
|
+
if (!live.length && !s.authorization)
|
|
231
|
+
return undefined;
|
|
232
|
+
// One folder per run, so two runs in the same project never share or remove each other's files.
|
|
233
|
+
const rel = `${SESSION_FOLDER}/session-${crypto.randomBytes(4).toString("hex")}`;
|
|
234
|
+
const root = projectPath(directory, "", "dir"); // the project folder itself, symlinks resolved
|
|
235
|
+
const folder = path.join(root, ...rel.split("/"));
|
|
236
|
+
fs.mkdirSync(folder, { recursive: true });
|
|
237
|
+
// The project's contents are the agent's to change: if .bugxhunter was made a link to somewhere
|
|
238
|
+
// else, the session must not follow it out of the project.
|
|
239
|
+
if (!isInside(fs.realpathSync(folder), root)) {
|
|
240
|
+
audit("recon.session.refused", { reason: "folder" });
|
|
241
|
+
throw httpError(400, "The project's .bugxhunter folder points outside the project. Remove it and start again.");
|
|
242
|
+
}
|
|
243
|
+
// Keeps the folder out of the project's changes and commits. Never replaces one that is there.
|
|
244
|
+
try {
|
|
245
|
+
fs.writeFileSync(path.join(path.dirname(folder), ".gitignore"), "*\n", { flag: "wx" });
|
|
246
|
+
}
|
|
247
|
+
catch { /* already there */ }
|
|
248
|
+
const use = { capturedAt: s.capturedAt, cookies: live.length, authorization: Boolean(s.authorization), cleanup: () => fs.rmSync(folder, { recursive: true, force: true }) };
|
|
249
|
+
if (live.length) {
|
|
250
|
+
fs.writeFileSync(path.join(folder, "cookies.txt"), cookieJar(live, now), { mode: 0o600 });
|
|
251
|
+
use.cookieFile = `${rel}/cookies.txt`;
|
|
252
|
+
}
|
|
253
|
+
if (s.authorization) {
|
|
254
|
+
fs.writeFileSync(path.join(folder, "headers.txt"), `Authorization: ${s.authorization}\n`, { mode: 0o600 });
|
|
255
|
+
use.headerFile = `${rel}/headers.txt`;
|
|
256
|
+
}
|
|
257
|
+
audit("recon.session.used", { cookies: live.length, authorization: Boolean(s.authorization) });
|
|
258
|
+
return use;
|
|
259
|
+
}
|
|
260
|
+
//# sourceMappingURL=recon-session.js.map
|