bugxhunter 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -103,7 +103,15 @@ Two containers:
103
103
  key and only allows `/chat/completions` and `/models`. **The SCX key never enters the agent
104
104
  container** — this holds even though the agent has direct internet.
105
105
  - Projects live in the `workspace` Docker volume (`/workspace`, a git repo so Changes work). No
106
- host folders are mounted. Copy a repo in as a snapshot, and results back out:
106
+ host folders are mounted.
107
+ - **Workspaces and files in the UI**: the sidebar's **workspaces** button lists the folders under
108
+ `/workspace` (locally `~/bugxhunter/repos`, or `OPEN_RUNNER_WORKSPACE`), including GitHub
109
+ clones, and creates a new one (an empty git repository) or deletes one. A delete asks for the
110
+ name typed back, the open project can't be deleted, and only a listed workspace can be. The
111
+ **files** button browses the open project: click a file to download it, and upload with the
112
+ button or by dropping files on the list (up to 200 MB each). An upload never replaces a file;
113
+ a clash is saved as `name-1.ext`.
114
+ - From the command line, copy a repo in as a snapshot, and results back out:
107
115
 
108
116
  ```powershell
109
117
  powershell -File docker/copy-in.ps1 C:\code\my-repo # -> /workspace/my-repo (skips node_modules, .env, …)
@@ -151,7 +159,10 @@ agent can call a model. **Ctrl+Shift+L** locks it at once. The crypto is symmetr
151
159
  see [SECURITY.md](SECURITY.md#the-key-vault).
152
160
 
153
161
  While the vault is locked, model calls fail with a clear "vault is sealed" message. Without a vault
154
- the app falls back to `SCX_API` in `.env` or OpenCode's `auth.json`, in the clear.
162
+ the app takes the key from a key file (`SCX_API_FILE`), else falls back to `SCX_API` in `.env` or
163
+ OpenCode's `auth.json`, in the clear. A key file is for a runner nobody unlocks, such as one behind
164
+ Sigilant: mount it as a secret; it is re-read on every call, so replacing it rotates the key, and if
165
+ it cannot be read the call fails rather than falling back to a key in the clear.
155
166
 
156
167
  **Sign-in is the same passkey.** Once a vault exists the API needs a session, and the ways in are
157
168
  a WebAuthn assertion with one of the vault's passkeys (verified server-side), the backup
@@ -236,6 +247,28 @@ before scanning and to scan only hosts you name.
236
247
  To fence the agent to a specific lab/target range, add firewall rules on the Docker host or the VM
237
248
  you run this in — Docker's bridge NAT doesn't restrict outbound on its own.
238
249
 
250
+ ## Through Sigilant (governed runs)
251
+
252
+ `sigilant/` is the runner's side of running under [Sigilant](https://github.com/cintelis/sigilant): the runner is a
253
+ registered agent there, every call it makes is decided by a gateway against the scope the customer signed, risky ones
254
+ wait for a person, and each is written to a signed audit chain. Two processes, one image (`sigilant/Dockerfile`):
255
+
256
+ | | |
257
+ |---|---|
258
+ | `serve-tools.ts` | the tools a gateway forwards to: `repo.read`, `repo.comment`, `repo.block`, `repo.alerts` (GitHub's own Dependabot, code scanning and secret scanning alerts, read through the app), `target.request`, `finding.record`, `retest.summary` (what a retest came to, once, at its end), and for discovery `repo.scan`, `net.discover`, `discovery.report`; `run.usage`, which the runner's own process reports each step's usage with; GitHub with the engagement's token (`GITHUB_TOKEN_FILE`) |
259
+ | `github-app.ts` | the runner on GitHub as a GitHub App: a JWT signed with the app's key, exchanged for an installation token and renewed before it runs out, so that comments and reviews carry the app's name and logo (GitHub requires RS256 for the JWT; that RSA is GitHub's, confined to this file) |
260
+ | `usage.ts` | follows a run on the runner and reports each step — tokens, cost, time, tool calls — through the gateway as it completes; `run.ts` and the webhook do this for every run they start |
261
+ | `serve-bridge.ts` | an MCP server the agent is pointed at (`mcp.sigilant` in OpenCode's config), which holds the runner's identity and puts every call through the gateway |
262
+ | `opencode.json`, `AGENTS.md` | the agent's configuration for a governed run, merged over the image's (`OPENCODE_CONFIG`): the bridge as its one MCP server, the sandbox's own tools off, and what a denial or a held call means |
263
+ | `run.ts` | starts a run on the runner's API with nobody at the keyboard: `--pr owner/name#N` reviews a pull request |
264
+ | `serve-webhook.ts` | the webhooks: GitHub's (`/hooks/github`), where a pull request opened or updated on a repository it serves starts that review, and a deploy's (`/hooks/deploy`), where a deploy of a target it serves starts a retest of what changed; signatures checked, deliveries seen before ignored |
265
+ | `serve-scheduler.ts` | the timetable: a retest of each target every so often (`SCHEDULE_RETEST_EVERY`, 24h) and a discovery of the scope less often (`SCHEDULE_DISCOVER_EVERY`, 7d), each run followed and its usage reported; remembers when each last ran in the workspace, so a restart neither forgets nor starts everything again; `--now retest` or `--now discover` for one by hand |
266
+ | `deploy.ts` | tells the webhook a deploy has happened — the target, its version, the paths it changed — signed and named, so that CI or the host starts the retest with one command |
267
+
268
+ The package stands on its own (`cd sigilant && npm install && npm run typecheck && npm test`), with `@sigilant/sdk`
269
+ from a Sigilant checkout beside this one; the image takes the SDK built from an image of Sigilant's
270
+ (`SIGILANT_SDK_IMAGE`). Sigilant's `deploy/compose/bugxhunter.yaml` runs both beside its stack.
271
+
239
272
  ## Configuration (environment variables)
240
273
 
241
274
  | Variable | Default | Purpose |
@@ -244,7 +277,9 @@ you run this in — Docker's bridge NAT doesn't restrict outbound on its own.
244
277
  | `OPEN_RUNNER_DIR` | this folder | Default project folder |
245
278
  | `OPEN_RUNNER_AGENT_PORT` | `8791` | Port for the OpenCode server |
246
279
  | `PORT` | `8790` | Backend port |
247
- | `SCX_API` | the vault, else `opencode auth login` | SCX key in the clear; ignored once a vault exists (preferred) |
280
+ | `SCX_API_FILE` | unset | A file holding the SCX key, re-read on every call; for a runner with no one to unlock the vault. Ignored once a vault exists |
281
+ | `SCX_API` | the vault, else `opencode auth login` | SCX key in the clear; ignored once a vault or key file exists (prefer either) |
282
+ | `OPENROUTER_API_KEY_FILE` | unset | A file holding the OpenRouter key, as `SCX_API_FILE` |
248
283
  | `OPENROUTER_API_KEY` | the vault, else unset | OpenRouter key in the clear; prefer the vault item of the same name |
249
284
  | `OPENROUTER_MODELS` | unset | Comma list of OpenRouter model ids the agent may use; becomes an OpenCode provider through the proxy |
250
285
  | `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | OpenRouter endpoint |
@@ -275,6 +310,9 @@ GHCR images by digest) and the signed `checksums.txt` that covers them all.
275
310
  <!-- releases:start -->
276
311
  | Release | Published | Checksums | Signature | Signature check | Build |
277
312
  | --- | --- | --- | --- | --- | --- |
313
+ | [v0.8.2](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.8.2) | 2026-10-21 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.8.2/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.8.2/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/39570620468) |
314
+ | [v0.8.1](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.8.1) | 2026-10-09 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.8.1/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.8.1/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/37888271992) |
315
+ | [v0.8.0](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.8.0) | 2026-10-09 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.8.0/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.8.0/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/37885369502) |
278
316
  | [v0.7.0](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.7.0) | 2026-10-08 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.7.0/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.7.0/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/37718565914) |
279
317
  | [v0.6.0](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.6.0) | 2026-10-08 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.6.0/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.6.0/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/37705423314) |
280
318
  | [v0.5.0](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.5.0) | 2026-10-07 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.5.0/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.5.0/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/37702342512) |
@@ -130,11 +130,11 @@ async function dockerMode(rest) {
130
130
  fs.copyFileSync(path.join(ROOT, "docker-compose.yml"), path.join(dir, "docker-compose.yml"));
131
131
  const envFile = path.join(dir, ".env");
132
132
  const vals = new Map();
133
- if (fs.existsSync(envFile)) {
134
- for (const line of fs.readFileSync(envFile, "utf8").split(/\r?\n/)) {
135
- const m = /^\s*([A-Z0-9_]+)=(.*)$/.exec(line);
136
- if (m) vals.set(m[1], m[2]);
137
- }
133
+ let envText = "";
134
+ try { envText = fs.readFileSync(envFile, "utf8"); } catch (e) { if (e.code !== "ENOENT") throw e; }
135
+ for (const line of envText.split(/\r?\n/)) {
136
+ const m = /^\s*([A-Z0-9_]+)=(.*)$/.exec(line);
137
+ if (m) vals.set(m[1], m[2]);
138
138
  }
139
139
  const fresh = !vals.size;
140
140
  if (!vals.get("OPEN_RUNNER_SECRET")) vals.set("OPEN_RUNNER_SECRET", crypto.randomBytes(32).toString("base64url"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugxhunter",
3
- "version": "0.8.1",
3
+ "version": "0.8.3",
4
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
5
  "license": "MIT",
6
6
  "homepage": "https://bugxhunter.com",
@@ -31,6 +31,7 @@
31
31
  "@opencode-ai/sdk": "^1.17.11",
32
32
  "dotenv": "^18.0.6",
33
33
  "express": "^5.2.1",
34
+ "express-rate-limit": "^8.7.1",
34
35
  "opencode-ai": "^1.18.35"
35
36
  },
36
37
  "publishConfig": {
@@ -35,7 +35,7 @@ function uniquePath(dir, name) {
35
35
  return candidate;
36
36
  }
37
37
  export function saveAttachments(directory, files, inlineImages = true) {
38
- const dir = path.join(directory, "attachments");
38
+ const dir = path.resolve(directory, "attachments");
39
39
  fs.mkdirSync(dir, { recursive: true });
40
40
  const parts = [];
41
41
  const saved = [];
@@ -46,8 +46,11 @@ export function saveAttachments(directory, files, inlineImages = true) {
46
46
  }
47
47
  const name = safeName(f.name);
48
48
  const mime = f.mime || "application/octet-stream";
49
- const abs = uniquePath(dir, name);
50
- fs.writeFileSync(abs, bytes);
49
+ const abs = path.resolve(uniquePath(dir, name));
50
+ // safeName already keeps it to a bare file name; this makes the rule explicit.
51
+ if (!abs.startsWith(dir + path.sep))
52
+ throw Object.assign(new Error(`Refusing to save ${f.name} outside attachments/`), { status: 400 });
53
+ fs.writeFileSync(abs, bytes, { flag: "wx" });
51
54
  const rel = path.relative(directory, abs).split(path.sep).join("/");
52
55
  saved.push({ name: path.basename(abs), path: rel, bytes: bytes.length, mime });
53
56
  if (mime.startsWith("image/")) {
@@ -22,8 +22,13 @@ function ensureDir() {
22
22
  fs.mkdirSync(LOG_DIR, { recursive: true });
23
23
  // Keep logs out of git status / the Changes view.
24
24
  const ignore = path.join(LOG_DIR, ".gitignore");
25
- if (!fs.existsSync(ignore))
26
- fs.writeFileSync(ignore, "*\n");
25
+ try {
26
+ fs.writeFileSync(ignore, "*\n", { flag: "wx" });
27
+ }
28
+ catch (e) {
29
+ if (e.code !== "EEXIST")
30
+ throw e;
31
+ }
27
32
  ready = true;
28
33
  }
29
34
  catch (e) {
@@ -20,6 +20,7 @@
20
20
  import crypto from "node:crypto";
21
21
  import * as vault from "./vault.js";
22
22
  import { audit } from "./audit.js";
23
+ import { authLimiter } from "./ratelimit.js";
23
24
  const SECRET = process.env.OPEN_RUNNER_SECRET || crypto.randomBytes(32).toString("hex");
24
25
  const COOKIE = "or_session";
25
26
  const MAX_AGE_S = 7 * 24 * 3600;
@@ -172,6 +173,8 @@ export function verifyAssertion(a, allowedHosts) {
172
173
  }
173
174
  // --- routes ------------------------------------------------------------------------
174
175
  export function mountAuth(app, allowedHosts) {
176
+ // Sign-in is the one place worth guessing at; the recovery code is 128 bits, but no reason to allow a stream.
177
+ app.use("/api/auth", authLimiter);
175
178
  app.get("/api/auth/me", (req, res) => {
176
179
  const me = { required: authRequired(), authenticated: isAuthenticated(req) };
177
180
  res.json(me);
@@ -347,15 +347,17 @@ async function api(tok, route) {
347
347
  }
348
348
  throw httpError(r.status === 404 || r.status === 403 ? r.status : 502, `GitHub: ${message}`);
349
349
  }
350
- /** The token's account, remembered per token so the status call stays cheap. */
351
- const logins = new Map();
350
+ /**
351
+ * The token's account, remembered so the status call stays cheap. One entry:
352
+ * there is one connection at a time, and a new token (refresh, reconnect)
353
+ * simply replaces it.
354
+ */
355
+ let lastLogin = null;
352
356
  async function whoami(tok) {
353
- const key = crypto.createHash("sha256").update(tok).digest("hex");
354
- const hit = logins.get(key);
355
- if (hit && Date.now() - hit.at < 10 * 60_000)
356
- return hit.login;
357
+ if (lastLogin && lastLogin.tok === tok && Date.now() - lastLogin.at < 10 * 60_000)
358
+ return lastLogin.login;
357
359
  const me = await api(tok, "/user");
358
- logins.set(key, { login: me.login, at: Date.now() });
360
+ lastLogin = { tok, login: me.login, at: Date.now() };
359
361
  return me.login;
360
362
  }
361
363
  export async function status() {
@@ -18,6 +18,8 @@ import { mountAuth, authRequired, issueSession } from "./auth.js";
18
18
  import { audit, followOpencode, LOG_DIR } from "./audit.js";
19
19
  import { saveAttachments } from "./attachments.js";
20
20
  import * as vault from "./vault.js";
21
+ import { apiLimiter, fileLimiter, staticLimiter } from "./ratelimit.js";
22
+ import { createWorkspace, deleteWorkspace, listFiles, listWorkspaces, saveUpload, WORKSPACES_ROOT } from "./workspaces.js";
21
23
  import * as github from "./github.js";
22
24
  // Keys, the proxy token and the provider clients live in providers.ts, which
23
25
  // also scrubs every secret from the environment before OpenCode is spawned.
@@ -104,6 +106,8 @@ app.use("/api", (req, res, next) => {
104
106
  // Prompts can carry attachments (base64), so allow larger bodies there.
105
107
  app.use("/api/agent/prompt", express.json({ limit: "40mb" }));
106
108
  app.use(express.json({ limit: "4mb" }));
109
+ // Rate limits before anything else under /api, sign-in included (see ratelimit.ts).
110
+ app.use("/api", apiLimiter);
107
111
  mountAuth(app, ALLOWED_HOSTS);
108
112
  // Any authenticated write counts as activity for the vault's auto-lock (reads
109
113
  // don't, so the sidebar's status polling can't keep it open).
@@ -112,6 +116,8 @@ app.use("/api", (req, _res, next) => {
112
116
  vault.touch();
113
117
  next();
114
118
  });
119
+ /** An error (or anything) as a single log line, newlines escaped. */
120
+ const oneLine = (e) => String(e instanceof Error ? e.stack ?? e.message : e).replace(/\r/g, "").replace(/\n/g, " | ");
115
121
  const sendError = (res, e) => {
116
122
  if (e instanceof SCXError) {
117
123
  // The provider rejecting our key is a configuration problem here, not the
@@ -124,7 +130,8 @@ const sendError = (res, e) => {
124
130
  const status = e?.status;
125
131
  if (status)
126
132
  return res.status(status).json({ error: { message: e.message } });
127
- console.error("[server error]", e);
133
+ // One line: an error message can carry request input, and a newline in it would forge log lines.
134
+ console.error("[server error]", oneLine(e));
128
135
  return res.status(500).json({ error: { message: String(e?.message ?? e) } });
129
136
  };
130
137
  app.get("/api/health", (_req, res) => res.json({ ok: true, baseUrl: PROVIDERS.scx.baseUrl }));
@@ -431,7 +438,62 @@ app.get("/api/agent/directory", async (req, res) => {
431
438
  * Download a file the agent wrote (the UI links paths it prints). The file
432
439
  * must be inside the project folder; see projectFile.
433
440
  */
434
- app.get("/api/agent/file", async (req, res) => {
441
+ // --- workspaces (server/src/workspaces.ts) ------------------------------------
442
+ app.get("/api/workspaces", (_req, res) => {
443
+ try {
444
+ res.json({ root: WORKSPACES_ROOT, workspaces: listWorkspaces() });
445
+ }
446
+ catch (e) {
447
+ sendError(res, e);
448
+ }
449
+ });
450
+ app.post("/api/workspaces", async (req, res) => {
451
+ try {
452
+ const ws = await createWorkspace(req.body?.name);
453
+ audit("workspace.created", { directory: ws.directory });
454
+ res.json(ws);
455
+ }
456
+ catch (e) {
457
+ sendError(res, e);
458
+ }
459
+ });
460
+ app.delete("/api/workspaces", (req, res) => {
461
+ try {
462
+ const ws = deleteWorkspace(req.query.directory);
463
+ audit("workspace.deleted", { directory: ws.directory });
464
+ res.json({ ok: true, deleted: ws });
465
+ }
466
+ catch (e) {
467
+ sendError(res, e);
468
+ }
469
+ });
470
+ /** One folder of the project, for the files dialog. */
471
+ app.get("/api/agent/files", async (req, res) => {
472
+ try {
473
+ const directory = await resolveDirectory(req.query.directory);
474
+ res.json(listFiles(directory, req.query.path));
475
+ }
476
+ catch (e) {
477
+ sendError(res, e);
478
+ }
479
+ });
480
+ /**
481
+ * Upload one file into a folder of the project: the raw bytes as the body,
482
+ * name and folder in the query. Never replaces an existing file.
483
+ */
484
+ app.post("/api/agent/upload", fileLimiter, express.raw({ type: () => true, limit: "200mb" }), async (req, res) => {
485
+ try {
486
+ const directory = await resolveDirectory(req.query.directory);
487
+ const bytes = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
488
+ const saved = saveUpload(directory, req.query.path, req.query.name, bytes);
489
+ audit("file.uploaded", { directory, file: saved.path, bytes: saved.bytes });
490
+ res.json(saved);
491
+ }
492
+ catch (e) {
493
+ sendError(res, e);
494
+ }
495
+ });
496
+ app.get("/api/agent/file", fileLimiter, async (req, res) => {
435
497
  try {
436
498
  const directory = await resolveDirectory(req.query.directory);
437
499
  const file = projectFile(directory, req.query.path);
@@ -777,8 +839,9 @@ app.get("/api/agent/events", async (req, res) => {
777
839
  // Production (Docker): serve the built web app from the same origin.
778
840
  const WEB_DIST = path.join(REPO_ROOT, "web", "dist");
779
841
  if (process.env.NODE_ENV === "production" && fs.existsSync(WEB_DIST)) {
842
+ app.use(staticLimiter);
780
843
  app.use(express.static(WEB_DIST, { index: false }));
781
- app.get(/^(?!\/api\/|\/scx\/).*/, (_req, res) => res.sendFile(path.join(WEB_DIST, "index.html")));
844
+ app.get(/^(?!\/api\/|\/scx\/).*/, staticLimiter, (_req, res) => res.sendFile(path.join(WEB_DIST, "index.html")));
782
845
  }
783
846
  // Body-parser failures (oversized attachment payloads, malformed JSON) and
784
847
  // anything a route threw synchronously: answer in JSON like every other error.
@@ -798,6 +861,7 @@ const server = app.listen(PORT, process.env.HOST ?? "127.0.0.1", () => {
798
861
  const src = keySource(p.id);
799
862
  const where = {
800
863
  vault: "vault",
864
+ file: "a key file (not in the clear in the environment)",
801
865
  env: ".env — consider moving it into the vault",
802
866
  "opencode-auth": "OpenCode's auth.json — consider moving it into the vault",
803
867
  none: p.id === "scx" ? "none yet — set up the vault in the sidebar" : "not configured (optional)",
@@ -173,7 +173,7 @@ const notFound = (dir) => httpError(400, `Folder not found: ${dir}`);
173
173
  */
174
174
  export const ALLOWED_ROOTS = (process.env.OPEN_RUNNER_ALLOWED_ROOTS ?? "")
175
175
  .split(path.delimiter).map((s) => s.trim()).filter(Boolean).map((r) => path.resolve(r));
176
- const isInside = (abs, root) => {
176
+ export const isInside = (abs, root) => {
177
177
  const [a, r] = process.platform === "win32" ? [abs.toLowerCase(), root.toLowerCase()] : [abs, root];
178
178
  return a === r || a.startsWith(r.endsWith(path.sep) ? r : r + path.sep);
179
179
  };
@@ -222,21 +222,32 @@ export function projectFile(directory, file) {
222
222
  const raw = typeof file === "string" ? file.trim() : "";
223
223
  if (!raw)
224
224
  throw httpError(400, "path required");
225
+ return projectPath(directory, raw, "file");
226
+ }
227
+ /**
228
+ * A file or folder inside a (validated) project folder: absolute or relative
229
+ * to the project ("" is the project itself), symlinks resolved, still inside,
230
+ * and of the expected kind.
231
+ */
232
+ export function projectPath(directory, rel, kind) {
225
233
  const P = REMOTE_URL ? path.posix : path;
226
- const abs = P.isAbsolute(raw) ? P.normalize(raw) : P.resolve(directory, raw);
234
+ const abs = P.isAbsolute(rel) ? P.normalize(rel) : P.resolve(directory, rel || ".");
227
235
  if (!isInside(abs, directory))
228
- throw httpError(400, `Not inside the project: ${raw}`);
236
+ throw httpError(400, `Not inside the project: ${rel}`);
229
237
  let real;
230
238
  try {
231
239
  real = fs.realpathSync(abs);
232
240
  }
233
241
  catch {
234
- throw httpError(404, `No such file: ${raw}`);
242
+ throw httpError(404, `No such ${kind === "file" ? "file" : "folder"}: ${rel}`);
235
243
  }
236
244
  if (!isInside(real, fs.realpathSync(directory)))
237
- throw httpError(400, `Not inside the project: ${raw}`);
238
- if (!fs.statSync(real).isFile())
239
- throw httpError(400, `Not a file: ${raw}`);
245
+ throw httpError(400, `Not inside the project: ${rel}`);
246
+ const st = fs.statSync(real);
247
+ if (kind === "file" && !st.isFile())
248
+ throw httpError(400, `Not a file: ${rel}`);
249
+ if (kind === "dir" && !st.isDirectory())
250
+ throw httpError(400, `Not a folder: ${rel}`);
240
251
  return real;
241
252
  }
242
253
  /** SDK client scoped to one project folder. */
@@ -525,6 +536,7 @@ export function toUiMessages(raw) {
525
536
  tokens: info.tokens,
526
537
  cost: info.cost,
527
538
  model: info.modelID ? `${info.providerID}/${info.modelID}` : undefined,
539
+ time: info.time ? { created: info.time.created, completed: info.time.completed } : undefined,
528
540
  error: info.error ? errorText(info.error) : undefined,
529
541
  };
530
542
  });
@@ -3,9 +3,13 @@
3
3
  * its catalogue (https://openrouter.ai/models). Both speak the OpenAI API, so
4
4
  * one client class and one key-injecting proxy serve both.
5
5
  *
6
- * Keys: the vault item (SCX_API, OPENROUTER_API_KEY) first, then .env, then
7
- * OpenCode's own auth store. They are read once here and scrubbed from the
8
- * environment: the OpenCode server is spawned with a copy of our environment,
6
+ * Keys: the vault item (SCX_API, OPENROUTER_API_KEY) first, then a key file
7
+ * (SCX_API_FILE, OPENROUTER_API_KEY_FILE), then .env, then OpenCode's own auth
8
+ * store. A key file is for a runner nobody is at the keyboard of, where the
9
+ * vault cannot be unlocked: a mounted secret, re-read on every call so that
10
+ * replacing the file rotates the key without a restart. Keys in the
11
+ * environment are read once here and scrubbed from it, and so are the key
12
+ * files' paths: the OpenCode server is spawned with a copy of our environment,
9
13
  * and the agent's shell inherits that.
10
14
  *
11
15
  * In the Playground, OpenRouter models are addressed as `openrouter/<id>`.
@@ -23,11 +27,11 @@ import * as vault from "./vault.js";
23
27
  export const PROVIDERS = {
24
28
  scx: {
25
29
  id: "scx", name: "SCX.ai", baseUrl: process.env.SCX_BASE_URL ?? "https://api.scx.ai/v1",
26
- vaultItem: "SCX_API", envVars: ["SCX_API", "SCX_API_KEY"], authId: "scx",
30
+ vaultItem: "SCX_API", envVars: ["SCX_API", "SCX_API_KEY"], fileVar: "SCX_API_FILE", authId: "scx",
27
31
  },
28
32
  openrouter: {
29
33
  id: "openrouter", name: "OpenRouter", baseUrl: process.env.OPENROUTER_BASE_URL ?? "https://openrouter.ai/api/v1",
30
- vaultItem: "OPENROUTER_API_KEY", envVars: ["OPENROUTER_API_KEY"], authId: "openrouter",
34
+ vaultItem: "OPENROUTER_API_KEY", envVars: ["OPENROUTER_API_KEY"], fileVar: "OPENROUTER_API_KEY_FILE", authId: "openrouter",
31
35
  // Attribution headers OpenRouter asks apps to send.
32
36
  headers: { "HTTP-Referer": "https://bugxhunter.com", "X-Title": "BugXHunter" },
33
37
  },
@@ -52,6 +56,7 @@ function readAuthStore() {
52
56
  }
53
57
  }
54
58
  const envKeys = {};
59
+ const keyFiles = {};
55
60
  const authKeys = readAuthStore();
56
61
  for (const p of Object.values(PROVIDERS)) {
57
62
  for (const v of p.envVars)
@@ -61,6 +66,21 @@ for (const p of Object.values(PROVIDERS)) {
61
66
  }
62
67
  for (const v of p.envVars)
63
68
  delete process.env[v];
69
+ if (process.env[p.fileVar]?.trim())
70
+ keyFiles[p.id] = process.env[p.fileVar].trim();
71
+ delete process.env[p.fileVar];
72
+ }
73
+ /** The key in a provider's key file, read now; undefined if it has none, or it is empty. */
74
+ function fileKey(id) {
75
+ const file = keyFiles[id];
76
+ if (!file)
77
+ return undefined;
78
+ try {
79
+ return fs.readFileSync(file, "utf8").trim() || undefined;
80
+ }
81
+ catch {
82
+ return undefined;
83
+ }
64
84
  }
65
85
  for (const k of ["SCX_PROXY_TOKEN", "OPEN_RUNNER_SECRET"])
66
86
  delete process.env[k];
@@ -69,6 +89,8 @@ export function keySource(id) {
69
89
  const p = PROVIDERS[id];
70
90
  if (vault.isInitialised() && vault.status("none").items.includes(p.vaultItem))
71
91
  return "vault";
92
+ if (keyFiles[id])
93
+ return "file";
72
94
  if (envKeys[id])
73
95
  return "env";
74
96
  if (authKeys[p.authId])
@@ -81,6 +103,13 @@ export function apiKey(id) {
81
103
  const p = PROVIDERS[id];
82
104
  switch (keySource(id)) {
83
105
  case "vault": return vault.getItem(p.vaultItem); // throws 503 while sealed
106
+ case "file": {
107
+ const key = fileKey(id);
108
+ // A key file named and then not readable is a fault, never a reason to fall back to a key in the clear.
109
+ if (!key)
110
+ throw httpError(503, `The ${p.name} key file ${p.fileVar} names cannot be read, or is empty.`);
111
+ return key;
112
+ }
84
113
  case "env": return envKeys[id];
85
114
  case "opencode-auth": return authKeys[p.authId];
86
115
  default:
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Request rate limits, per client IP, per minute.
3
+ *
4
+ * The runner is single-user and localhost-only by default, so these are not
5
+ * about load: they cap what a script on the same machine (or a page that got
6
+ * past the Host check) can do in a burst, and they make the sign-in routes
7
+ * useless for guessing. The general limit sits well above what the UI itself
8
+ * sends (status polls, session lists, one SSE stream).
9
+ */
10
+ import { rateLimit } from "express-rate-limit";
11
+ const limiter = (limit, what) => rateLimit({
12
+ windowMs: 60_000,
13
+ limit,
14
+ standardHeaders: "draft-7",
15
+ legacyHeaders: false,
16
+ message: { error: { message: `Too many ${what} requests; try again in a minute.`, code: "rate_limited" } },
17
+ });
18
+ /** Everything under /api. */
19
+ export const apiLimiter = limiter(1200, "API");
20
+ /** Sign-in: challenge, passkey assertion, recovery. */
21
+ export const authLimiter = limiter(30, "sign-in");
22
+ /** File downloads from the project folder. */
23
+ export const fileLimiter = limiter(120, "download");
24
+ /** The built web app (production). */
25
+ export const staticLimiter = limiter(1200, "page");
26
+ //# sourceMappingURL=ratelimit.js.map
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Workspaces and the files in them.
3
+ *
4
+ * A workspace is a folder under the workspace root: /workspace in Docker
5
+ * (the volume both containers mount at the same path), or
6
+ * OPEN_RUNNER_WORKSPACE / ~/bugxhunter/repos locally — the same place GitHub
7
+ * clones land. A clone sits one level deeper (<owner>/<repo>), so a folder
8
+ * holding only other git repositories is listed as those repositories.
9
+ *
10
+ * Deleting only ever removes something listWorkspaces() would show: never the
11
+ * root, never an owner folder of clones, never a path the browser made up.
12
+ *
13
+ * Files: list a folder of the current project, and save uploads into one.
14
+ * Downloads use projectFile (index.ts). Everything is confined to the project
15
+ * folder with symlinks resolved (projectPath).
16
+ */
17
+ import { execFile } from "node:child_process";
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import { promisify } from "node:util";
21
+ import { safeName } from "./attachments.js";
22
+ import { httpError } from "./errors.js";
23
+ import { CLONE_ROOT, isInside, projectPath, REMOTE_URL } from "./opencode.js";
24
+ const execFileP = promisify(execFile);
25
+ /** Where workspaces live. */
26
+ export const WORKSPACES_ROOT = CLONE_ROOT;
27
+ const P = REMOTE_URL ? path.posix : path;
28
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
29
+ const MAX_ENTRIES = 2000;
30
+ const isGit = (p) => fs.existsSync(P.join(p, ".git"));
31
+ const modified = (p) => { try {
32
+ return fs.statSync(p).mtime.toISOString();
33
+ }
34
+ catch {
35
+ return null;
36
+ } };
37
+ const children = (p) => {
38
+ try {
39
+ return fs.readdirSync(p, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name);
40
+ }
41
+ catch {
42
+ return [];
43
+ }
44
+ };
45
+ export function listWorkspaces() {
46
+ const out = [];
47
+ for (const name of children(WORKSPACES_ROOT)) {
48
+ const dir = P.join(WORKSPACES_ROOT, name);
49
+ const inner = isGit(dir) ? [] : children(dir).filter((c) => isGit(P.join(dir, c)));
50
+ if (inner.length) {
51
+ // An owner folder of GitHub clones: list the repositories in it.
52
+ for (const c of inner)
53
+ out.push({ name: `${name}/${c}`, directory: P.join(dir, c), git: true, modified: modified(P.join(dir, c)) });
54
+ }
55
+ else {
56
+ out.push({ name, directory: dir, git: isGit(dir), modified: modified(dir) });
57
+ }
58
+ }
59
+ return out.sort((a, b) => (b.modified ?? "").localeCompare(a.modified ?? ""));
60
+ }
61
+ /** A new, empty workspace, initialised as a git repository (the Changes view diffs against it). */
62
+ export async function createWorkspace(name) {
63
+ const n = typeof name === "string" ? name.trim() : "";
64
+ if (!NAME.test(n))
65
+ throw httpError(400, "A workspace name is letters, digits, dot, dash or underscore (up to 64), starting with a letter or digit.");
66
+ fs.mkdirSync(WORKSPACES_ROOT, { recursive: true });
67
+ const dir = P.join(WORKSPACES_ROOT, n);
68
+ try {
69
+ fs.mkdirSync(dir);
70
+ }
71
+ catch (e) {
72
+ if (e.code === "EEXIST")
73
+ throw httpError(409, `A workspace called ${n} already exists.`);
74
+ throw e;
75
+ }
76
+ try {
77
+ await execFileP("git", ["init", "-q", "-b", "main", dir], { windowsHide: true, timeout: 15_000 });
78
+ }
79
+ catch { /* no git: still a usable folder */ }
80
+ return { name: n, directory: dir, git: isGit(dir), modified: modified(dir) };
81
+ }
82
+ /** Delete a workspace and everything in it. Only a listed workspace qualifies. */
83
+ export function deleteWorkspace(directory) {
84
+ const want = typeof directory === "string" ? P.resolve(directory.trim()) : "";
85
+ const ws = listWorkspaces().find((w) => w.directory === want);
86
+ if (!ws)
87
+ throw httpError(404, "Not a workspace.");
88
+ if (ws.directory === WORKSPACES_ROOT || !isInside(ws.directory, WORKSPACES_ROOT))
89
+ throw httpError(400, "Not a workspace.");
90
+ const real = fs.realpathSync(ws.directory);
91
+ if (!isInside(real, fs.realpathSync(WORKSPACES_ROOT)) || real === fs.realpathSync(WORKSPACES_ROOT))
92
+ throw httpError(400, "Not a workspace.");
93
+ fs.rmSync(real, { recursive: true, force: true, maxRetries: 3 });
94
+ return ws;
95
+ }
96
+ /** One folder of the project: sub-folders first, then files, by name. */
97
+ export function listFiles(directory, sub) {
98
+ const rel = typeof sub === "string" ? sub.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "") : "";
99
+ const dir = projectPath(directory, rel, "dir");
100
+ const all = fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.name !== ".git");
101
+ const entries = [];
102
+ for (const d of all.slice(0, MAX_ENTRIES)) {
103
+ const full = P.join(dir, d.name);
104
+ let st = null;
105
+ try {
106
+ st = fs.statSync(full);
107
+ }
108
+ catch { /* broken link */ }
109
+ const type = st?.isDirectory() ? "dir" : "file";
110
+ entries.push({ name: d.name, type, size: type === "file" ? st?.size ?? 0 : 0, modified: st?.mtime.toISOString() ?? null });
111
+ }
112
+ entries.sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === "dir" ? -1 : 1));
113
+ return { path: rel, entries, truncated: all.length > MAX_ENTRIES };
114
+ }
115
+ /**
116
+ * Save an uploaded file into a folder of the project. The name is reduced to
117
+ * a bare file name; an existing file is never replaced (name-1.ext, …).
118
+ */
119
+ export function saveUpload(directory, sub, name, bytes) {
120
+ const rel = typeof sub === "string" ? sub.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "") : "";
121
+ const dir = projectPath(directory, rel, "dir");
122
+ const base = safeName(typeof name === "string" ? name : "");
123
+ const ext = P.extname(base);
124
+ const stem = base.slice(0, base.length - ext.length);
125
+ for (let i = 0; i < 1000; i++) {
126
+ const candidate = P.resolve(dir, i ? `${stem}-${i}${ext}` : base);
127
+ if (!isInside(candidate, dir))
128
+ throw httpError(400, "Refusing to write outside the folder.");
129
+ try {
130
+ fs.writeFileSync(candidate, bytes, { flag: "wx" });
131
+ const saved = P.basename(candidate);
132
+ return { path: rel ? `${rel}/${saved}` : saved, name: saved, bytes: bytes.length };
133
+ }
134
+ catch (e) {
135
+ if (e.code !== "EEXIST")
136
+ throw e;
137
+ }
138
+ }
139
+ throw httpError(409, `Too many files called ${base}.`);
140
+ }
141
+ //# sourceMappingURL=workspaces.js.map