diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index bd74d77f..8886237d 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -21,7 +21,7 @@ jobs: timeout-minutes: 30 steps: - name: Checkout tag - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false @@ -51,7 +51,7 @@ jobs: done - name: Create GitHub Release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 with: generate_release_notes: true files: ${{ env.tarball }} diff --git a/package.json b/package.json index f33cde87..190de85e 100644 --- a/package.json +++ b/package.json @@ -75,7 +75,7 @@ "check-standards": "node scripts/check-code-standards.mjs", "check-architecture": "tsx scripts/check-architecture.mjs", "check-version": "node scripts/check-version-sync.mjs", - "prepublishOnly": "npm ci && npm test" + "prepublishOnly": "npm run typecheck && npm test" }, "dependencies": { "@aws-sdk/client-s3": "^3.1142.0", diff --git a/plans/batch-tool.md b/plans/batch-tool.md deleted file mode 100644 index d8a48700..00000000 --- a/plans/batch-tool.md +++ /dev/null @@ -1,135 +0,0 @@ -# `batch` tool — spec - -## Goal - -Give models that emit one tool call per turn (mostly smaller/local ones) -the same per-turn throughput strong models get from native batching — -without changing the loop's ordering or safety contracts. - -## Shape - -One new tool, `batch`. Args: - -- `calls: [{ tool: string, args: object }]` (required, 1–10 sub-calls) -- `stop_on_error?: boolean` (default false) - -Each sub-call's `args` is validated the way the loop validates top-level -calls. An unparseable sub-call becomes a per-section error, not a -batch failure. Over-cap or empty `calls` is a batch-level error. - -## Execution semantics - -The handler mirrors the loop's S3 partition internally: sub-calls are -classified by the same read-only/edit rules; reads run concurrently and -edits run strictly in submission order. A read of a file another -sub-call in the same batch edits goes serial, in position (same rule as -`isParallelReadOnlyCall`). - -`execute_command` sub-calls are allowed: read-only-equivalent commands -(S3's existing test) join the concurrent group, all others go -serial-in-position. A sub-call that times out into the background yields -the standard "still running" message as its section. - -No nesting: a sub-call naming `batch` is refused as a per-section error. - -## Refusals (per-section errors, siblings still run) - -- `new_task`, `switch_mode`, `ask_followup_question`: the single - decision-marker protocol must stay single-writer. -- `attempt_completion`: completion must observe real results (same - rationale as the bundled-completion refusal). -- Unknown tool names. - -## Failure visibility (owner decision) - -Failures must not be hidden. Every batch result carries: - -- Per-section ok/error markers in submission order. -- A summary line with partial counts: `N sub-calls: X ok, Y errors.` -- `isError: true` when the batch is malformed OR when zero sub-calls - succeeded. Partial success returns `isError: false` — the errors are - visible in the sections and counts, but productive explore-and-retry - flows are not punished by mistake accounting. - -## Read-only executors - -`batch` is registered on the reviewer/QA executor too, with no special -variant: every sub-call is gated on `executor.has()`, so edit sub-calls -there become per-section "not available on this executor" refusals -(write tools are simply not registered on read-only executors). -Reads-only batches work identically everywhere. - -## Schema strictness - -`strict: false` (the only non-strict tool schema): sub-call `args` are -free-form per-tool objects, which strict schemas cannot express. Each -sub-call is validated at runtime instead. Tools pass straight through -to the provider (`body.tools = request.tools`), so a strict flag here -would be enforced — hence the deliberate opt-out, documented in -src/tools/batch.ts. - -## Result format - -Single `ToolResult`. Body is labeled sections in submission order: - -``` -[1/3] read_file {"path": "src/x.ts"} — ok - -[2/3] go_to_definition {...} — error -[Error] ... -3 sub-calls: 2 ok, 1 error. -``` - -Total body capped (~60k chars) with a truncation note naming which -sections were cut. `stop_on_error: true` skips remaining sub-calls -after the first error and notes it. - -## Loop interplay - -No loop changes. `batch` arrives as one call, lands in the serial group -(not in `PARALLEL_READ_ONLY_TOOL_NAMES`), counts as one call for -mistake accounting. - -## Prompt - -Add a short batching nudge to the tool-use guidelines: independent -reads go in one `batch` (or one native block for models that batch -natively); never put a read of a file being edited in the same batch -ahead of seeing the edit result. - -## Wiring - -- New files `src/tools/batch.ts` (handler + execution) + - `src/tools/batch-format.ts` (rendering) + `src/tools/batch-tool.ts` - (schema) + `src/tools/__tests__/batch.test.ts`. -- Schema advertised via `appendBatchTool` (loop ×2, QA, CLI dry-run), - gated on `executor.has("batch")` like the other non-vendored tools. -- `executor.register("batch", ...)` in both the headless and - read-command executors. The batch handler reaches the executor via - closure capture (the `run_tests` precedent) — `execute()` is - stateless per call and safe to fan out through. -- Reuses the S3 partition (`isParallelReadOnlyCall`, - `editToolTargetPath` from `src/engine/tool-classes.ts`, moved out of - loop.ts so tools/* can import it without an engine import cycle) - rather than reimplementing read/edit classification. -- The five new codeintel tools are auto-eligible as batch sub-calls - once registered — no extra work. - -## Tests (through the real executor, tmpdir fixtures) - -- All-reads batch returns all sections. -- Mixed read/edit preserves order semantics (edit-then-read sees - post-edit content). -- Refused tools (`attempt_completion`, `new_task`, nested `batch`) - become per-section errors with siblings executed. -- Read-only executor refuses an edit sub-call. -- 11 sub-calls → batch-level error; `stop_on_error` skips. -- Truncation note present on oversized output. -- Partial failure: counts line present, `isError: false`; all-fail: - `isError: true`. - -## Measure - -Compare turns-to-complete and wall time on a fixed eval set (weak model -vs strong model) before/after. Expect turns down sharply on the weak -model, roughly flat on the strong one. diff --git a/scripts/deploy-gate.sh b/scripts/deploy-gate.sh index cd4c1cd9..6328c93d 100755 --- a/scripts/deploy-gate.sh +++ b/scripts/deploy-gate.sh @@ -144,16 +144,15 @@ if [ ! -f "$SCRIPT_ABS" ]; then fi # ── 2. Deployment summary (via the TS helper) ──────────────────────────────── -NOTES_ARG="" +GATE_CMD=(node --import tsx "$HARNESS_ROOT/src/deploy/gate-cli.ts" --repo "$REPO" --batch "$BATCH") if [ -n "$NOTES" ]; then - NOTES_ARG="--notes '$NOTES'" + GATE_CMD+=(--notes "$NOTES") fi GATE_OUT="$(mktemp /tmp/headlesscode-deploy-gate-XXXXXX.out)" -GATE_CLI="node --import tsx '$HARNESS_ROOT/src/deploy/gate-cli.ts'" set +e -( eval "cd '$HARNESS_ROOT' && $GATE_CLI --repo '$REPO' --batch '$BATCH' $NOTES_ARG" ) >"$GATE_OUT" 2>&1 +( cd "$HARNESS_ROOT" && "${GATE_CMD[@]}" ) >"$GATE_OUT" 2>&1 GATE_EXIT=$? set -e if [ "$GATE_EXIT" -ne 0 ]; then diff --git a/scripts/run-worker.sh b/scripts/run-worker.sh index 9072bb53..ad12f26d 100755 --- a/scripts/run-worker.sh +++ b/scripts/run-worker.sh @@ -264,72 +264,16 @@ if [ "$TASK_FLAG" = "--task-file" ] && [ ! -s "$TASK_PATH" ]; then exit 2 fi -# ── Build the wrapper that runs the CLI and records completion ───────────── -# The wrapper runs in its own `bash -c` (deliberately WITHOUT `set -e` so the -# completion markers are always written, even when the CLI fails). It: -# - cd's into the harness root (HEADLESSCODE_CLI resolves from there), -# - runs the CLI with the resolved task flag + workspace + mode, -# - records the exit code and creates the .harness.done marker dir. -# Env is inherited, so OPENROUTER_* flows through unchanged. -MODEL_ARG="" -if [ -n "$MODEL" ]; then - MODEL_ARG="--model '$MODEL'" -fi -LOG_FILE_ARG="" -if [ -n "$LOG_FILE" ]; then - LOG_FILE_ARG="--log-file '$LOG_FILE'" -fi -MEMORY_DIR_ARG="" -if [ -n "${HEADLESSCODE_MEMORY_DIR:-}" ]; then - MEMORY_DIR_ARG="--memory-dir '$HEADLESSCODE_MEMORY_DIR'" -fi - -# Phase 6: forward the per-session budget env vars as CLI flags (the CLI also -# reads them from env, but forwarding makes the budget visible in harness.log). -BUDGET_ARG="" -if [ -n "${HEADLESSCODE_MAX_COST_USD:-}" ]; then - BUDGET_ARG="$BUDGET_ARG --max-cost-usd '$HEADLESSCODE_MAX_COST_USD'" -fi -if [ -n "${HEADLESSCODE_MAX_DURATION_MS:-}" ]; then - BUDGET_ARG="$BUDGET_ARG --max-duration-ms '$HEADLESSCODE_MAX_DURATION_MS'" -fi - -# Decision escalation: forward the env var as a CLI flag too (visible in -# harness.log), same rationale as the budget args above. -if [ -n "${HEADLESSCODE_DECISION_TIMEOUT_MS:-}" ]; then - BUDGET_ARG="$BUDGET_ARG --decision-timeout-ms '$HEADLESSCODE_DECISION_TIMEOUT_MS'" -fi - -# Iteration cap: forward as a CLI flag too, same rationale as above. An -# explicit --max-iterations flag on this script beats the env var. +# ── Build the argv + static wrapper that runs the CLI and records completion ── +# Dynamic values flow through exported env vars and positional args ("$@" / +# JSON argv), NEVER string interpolation into bash -c. Deliberately WITHOUT +# `set -e` inside the wrapper so completion markers are always written. +read -r -a CLI_PARTS <<< "$CLI" MAX_ITERATIONS_VALUE="${MAX_ITERATIONS:-${HEADLESSCODE_MAX_ITERATIONS:-}}" -if [ -n "$MAX_ITERATIONS_VALUE" ]; then - BUDGET_ARG="$BUDGET_ARG --max-iterations '$MAX_ITERATIONS_VALUE'" -fi - -# Sliding-window history cap (messages, not tokens): forward as a CLI flag too. -if [ -n "${HEADLESSCODE_WINDOW_SIZE:-}" ]; then - BUDGET_ARG="$BUDGET_ARG --window-size '$HEADLESSCODE_WINDOW_SIZE'" -fi - -# Issue #136 Part B: after the worker exits, diff the MAIN checkout against -# the pre-launch snapshot (taken below) — a worker that wrote outside its -# worktree trips the wire (marker file + loud harness.log lines). Runs -# before mkdir .done, so a present .done marker implies the check ran. -TRIPWIRE_CHECK="bash '$HARNESS_ROOT/scripts/check-main-tree-clean.sh' worker check '$WT_PATH' || echo 'TRIPWIRE-FAILED: main-tree check did not run — confinement unverified for this run'" - -WRAPPER=" -cd '$HARNESS_ROOT' -$CLI $TASK_FLAG '$TASK_PATH' --workspace '$WT_PATH' --mode '$MODE' $MODEL_ARG $LOG_FILE_ARG $MEMORY_DIR_ARG $BUDGET_ARG -CODE=\$? -printf '%s' \"\$CODE\" > '$WT_PATH/.harness.exit' -$TRIPWIRE_CHECK -mkdir '$WT_PATH/.harness.done' 2>/dev/null -exit \$CODE -" +PROMPT_CLEANUP="" +CMD_ARGS=() if [ "$EXECUTOR" = "muse" ]; then - PROMPT_CLEANUP="" mkdir -p "$WT_PATH/.headlesscode/scratch" if [ "$TASK_FLAG" = "--task-file" ]; then MUSE_PROMPT_FILE="$TASK_PATH" @@ -338,30 +282,12 @@ if [ "$EXECUTOR" = "muse" ]; then printf '%s' "$TASK_PATH" > "$MUSE_PROMPT_FILE" PROMPT_CLEANUP="$MUSE_PROMPT_FILE" fi - MAX_MODEL_STEPS_VALUE="${MAX_ITERATIONS:-${HEADLESSCODE_MAX_ITERATIONS:-}}" - TRIPWIRE_CHECK_Q="bash $(printf '%q' "$HARNESS_ROOT/scripts/check-main-tree-clean.sh") worker check $(printf '%q' "$WT_PATH") || echo $(printf '%q' "TRIPWIRE-FAILED: main-tree check did not run — confinement unverified for this run")" - WRAPPER="cd $(printf '%q' "$HARNESS_ROOT") -bash $(printf '%q' "$HARNESS_ROOT/scripts/run-muse-worker.sh") \ - $(printf '%q' "$WT_PATH") $(printf '%q' "$MUSE_PROMPT_FILE") \ - $(printf '%q' "$MUSE_MODEL") $(printf '%q' "$MAX_MODEL_STEPS_VALUE") -CODE=\$? -if [ -n $(printf '%q' "$PROMPT_CLEANUP") ]; then rm -f -- $(printf '%q' "$PROMPT_CLEANUP"); fi -printf '%s' \"\$CODE\" > $(printf '%q' "$WT_PATH/.harness.exit") -$TRIPWIRE_CHECK_Q -mkdir $(printf '%q' "$WT_PATH/.harness.done") 2>/dev/null -exit \$CODE -" -fi - -if [ "${HEADLESSCODE_EXECUTION_PROVIDER:-local}" = "openshell" ]; then + CMD_ARGS=(bash "$HARNESS_ROOT/scripts/run-muse-worker.sh" "$WT_PATH" "$MUSE_PROMPT_FILE" "$MUSE_MODEL" "$MAX_ITERATIONS_VALUE") +elif [ "${HEADLESSCODE_EXECUTION_PROVIDER:-local}" = "openshell" ]; then if [ -z "${HEADLESSCODE_OPENSHELL_POLICY:-}" ] || [ ! -f "$HEADLESSCODE_OPENSHELL_POLICY" ]; then echo "run-worker: set HEADLESSCODE_OPENSHELL_POLICY to an existing policy file when using OpenShell" >&2 exit 2 fi - if [ "$EXECUTOR" = "muse" ]; then - echo "run-worker: Muse executor requires the local execution provider; OpenShell dispatch is not supported" >&2 - exit 2 - fi REPO_ROOT="${TARGET_REPO:-$(git -C "$WT_PATH" rev-parse --show-toplevel)}" SANDBOX_ARGS=(openshell-worker --repo "$REPO_ROOT" --worktree "$WT_PATH" -- "$TASK_FLAG" "$TASK_PATH" --workspace "$WT_PATH" --mode "$MODE") [ -n "$MODEL" ] && SANDBOX_ARGS+=(--model "$MODEL") @@ -372,21 +298,50 @@ if [ "${HEADLESSCODE_EXECUTION_PROVIDER:-local}" = "openshell" ]; then [ -n "${HEADLESSCODE_MAX_DURATION_MS:-}" ] && SANDBOX_ARGS+=(--max-duration-ms "$HEADLESSCODE_MAX_DURATION_MS") [ -n "${HEADLESSCODE_DECISION_TIMEOUT_MS:-}" ] && SANDBOX_ARGS+=(--decision-timeout-ms "$HEADLESSCODE_DECISION_TIMEOUT_MS") [ -n "${HEADLESSCODE_WINDOW_SIZE:-}" ] && SANDBOX_ARGS+=(--window-size "$HEADLESSCODE_WINDOW_SIZE") - printf -v SANDBOX_ARGS_QUOTED ' %q' "${SANDBOX_ARGS[@]}" - WRAPPER=" -cd '$HARNESS_ROOT' -$CLI${SANDBOX_ARGS_QUOTED} -CODE=\$? -printf '%s' \"\$CODE\" > '$WT_PATH/.harness.exit' -$TRIPWIRE_CHECK -mkdir '$WT_PATH/.harness.done' 2>/dev/null -exit \$CODE -" -elif [ "${HEADLESSCODE_EXECUTION_PROVIDER:-local}" != "local" ]; then + CMD_ARGS=("${CLI_PARTS[@]}" "${SANDBOX_ARGS[@]}") +elif [ "${HEADLESSCODE_EXECUTION_PROVIDER:-local}" = "local" ]; then + CMD_ARGS=("${CLI_PARTS[@]}" "$TASK_FLAG" "$TASK_PATH" --workspace "$WT_PATH" --mode "$MODE") + [ -n "$MODEL" ] && CMD_ARGS+=(--model "$MODEL") + [ -n "$LOG_FILE" ] && CMD_ARGS+=(--log-file "$LOG_FILE") + [ -n "${HEADLESSCODE_MEMORY_DIR:-}" ] && CMD_ARGS+=(--memory-dir "$HEADLESSCODE_MEMORY_DIR") + [ -n "${HEADLESSCODE_MAX_COST_USD:-}" ] && CMD_ARGS+=(--max-cost-usd "$HEADLESSCODE_MAX_COST_USD") + [ -n "${HEADLESSCODE_MAX_DURATION_MS:-}" ] && CMD_ARGS+=(--max-duration-ms "$HEADLESSCODE_MAX_DURATION_MS") + [ -n "${HEADLESSCODE_DECISION_TIMEOUT_MS:-}" ] && CMD_ARGS+=(--decision-timeout-ms "$HEADLESSCODE_DECISION_TIMEOUT_MS") + [ -n "$MAX_ITERATIONS_VALUE" ] && CMD_ARGS+=(--max-iterations "$MAX_ITERATIONS_VALUE") + [ -n "${HEADLESSCODE_WINDOW_SIZE:-}" ] && CMD_ARGS+=(--window-size "$HEADLESSCODE_WINDOW_SIZE") +else echo "run-worker: unsupported HEADLESSCODE_EXECUTION_PROVIDER='$HEADLESSCODE_EXECUTION_PROVIDER' (expected local or openshell)" >&2 exit 2 fi +export _HC_HARNESS_ROOT="$HARNESS_ROOT" +export _HC_WT_PATH="$WT_PATH" +export _HC_PROMPT_CLEANUP="$PROMPT_CLEANUP" + +# Static wrapper body — zero variable interpolation. +IFS= read -r -d '' WRAPPER_BODY <<'WRAPPER_EOF' || true +if [ "${_HC_WRITE_PGID:-0}" = "1" ]; then + printf '%s' "$$" > "$_HC_WT_PATH/.harness.pgid" +fi +if [ "${_HC_WAIT_FD3:-0}" = "1" ]; then + read -r _ <&3 || exit 125 +fi +cd "$_HC_HARNESS_ROOT" || exit 1 +if [ "${_HC_RUN_JSON_CMD:-0}" = "1" ]; then + node -e 'const {spawnSync}=require("node:child_process");const a=JSON.parse(process.env._HC_CMD_JSON);const r=spawnSync(a[0],a.slice(1),{stdio:"inherit"});process.exit(r.status??1);' +else + "$@" +fi +CODE=$? +if [ -n "${_HC_PROMPT_CLEANUP:-}" ]; then + rm -f -- "$_HC_PROMPT_CLEANUP" +fi +printf '%s' "$CODE" > "$_HC_WT_PATH/.harness.exit" +bash "$_HC_HARNESS_ROOT/scripts/check-main-tree-clean.sh" worker check "$_HC_WT_PATH" || echo 'TRIPWIRE-FAILED: main-tree check did not run — confinement unverified for this run' +mkdir "$_HC_WT_PATH/.harness.done" 2>/dev/null +exit "$CODE" +WRAPPER_EOF + # ── Launch detached + record pid + pgid ───────────────────────────────────── rm -f "$WT_PATH/.harness.exit" rm -rf "$WT_PATH/.harness.done" @@ -421,10 +376,9 @@ if command -v setsid >/dev/null 2>&1; then else echo "run-worker: warning: setsid not found — worker will share the caller's process group; stopping it can only kill the wrapper PID (issue #20)" >&2 fi -if [ "$SETSID_OK" -eq 1 ] && [ -z "$JOB_ATTEMPT" ]; then - WRAPPER="printf '%s' \"\$\$\" > '$WT_PATH/.harness.pgid' -$WRAPPER" -fi +export _HC_WRITE_PGID="$SETSID_OK" +export _HC_WAIT_FD3="0" +export _HC_RUN_JSON_CMD="0" if [ -n "$JOB_ATTEMPT" ]; then if [ "$(uname -s)" != "Linux" ] || [ "$SETSID_OK" -ne 1 ] || ! command -v node >/dev/null 2>&1; then @@ -444,12 +398,13 @@ if [ -n "$JOB_ATTEMPT" ]; then echo "run-worker: supervisor receipts already exist for this attempt; refusing duplicate launch" >&2 exit 2 fi - WRAPPER="printf '%s' \"\$\$\" > '$WT_PATH/.harness.pgid' -read -r _ <&3 || exit 125 -$WRAPPER" + export _HC_WRITE_PGID="1" + export _HC_WAIT_FD3="1" + export _HC_RUN_JSON_CMD="1" + export _HC_CMD_JSON="$(node -e 'process.stdout.write(JSON.stringify(process.argv.slice(1)))' "${CMD_ARGS[@]}")" WRAPPER_PATH="$JOB_RECEIPT_DIR/$JOB_GROUP.wrapper.$$.sh" rm -f -- "$WT_PATH/.harness.pid" "$WT_PATH/.harness.supervisor.pid" - printf '%s' "$WRAPPER" > "$WRAPPER_PATH" + printf '%s' "$WRAPPER_BODY" > "$WRAPPER_PATH" chmod 600 "$WRAPPER_PATH" nohup setsid node "$HARNESS_ROOT/scripts/supervise-job-worker.mjs" \ "$WT_PATH" "$JOB_RECEIPT_DIR" "$JOB_ATTEMPT" "$JOB_GROUP" "$WRAPPER_PATH" \ @@ -486,9 +441,9 @@ $WRAPPER" fi if [ "$SETSID_OK" -eq 1 ]; then - nohup setsid bash -c "$WRAPPER" >>"$WT_PATH/harness.log" 2>&1 & + nohup setsid bash -c "$WRAPPER_BODY" _ "${CMD_ARGS[@]}" >>"$WT_PATH/harness.log" 2>&1 & else - nohup bash -c "$WRAPPER" >>"$WT_PATH/harness.log" 2>&1 & + nohup bash -c "$WRAPPER_BODY" _ "${CMD_ARGS[@]}" >>"$WT_PATH/harness.log" 2>&1 & fi PID=$! printf '%s' "$PID" > "$WT_PATH/.harness.pid" diff --git a/scripts/spawn-parallel-worktrees.sh b/scripts/spawn-parallel-worktrees.sh index 32578a44..459a1c61 100755 --- a/scripts/spawn-parallel-worktrees.sh +++ b/scripts/spawn-parallel-worktrees.sh @@ -444,6 +444,10 @@ for spec in "$@"; do echo "spawn-parallel-worktrees: malformed spec '$spec' (expected ::)" >&2 exit 1 fi + if [[ ! "$name" =~ ^[a-zA-Z0-9._-]+$ ]] || [ "$name" = "." ] || [ "$name" = ".." ]; then + echo "spawn-parallel-worktrees: invalid worktree name '$name' (expected ^[a-zA-Z0-9._-]+$, not . or ..)" >&2 + exit 1 + fi if [ -n "$task_file" ] && [ ! -f "$REPO_ROOT/$task_file" ]; then echo "ERROR: task file '$task_file' not found relative to $REPO_ROOT" >&2 @@ -549,32 +553,26 @@ for spec in "$@"; do # ── Record "spawned" in the orchestrator state before launching ───────── issues="$(issue_numbers_from_task_file "$task_file" 2>/dev/null || true)" - issues_json="[" - sep="" - for n in $issues; do - issues_json="${issues_json}${sep}${n}" - sep="," - done - issues_json="${issues_json}]" - spawned_ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)" patch_file="$(mktemp)" - cat > "$patch_file" < "$patch_file" </checkpoints`). */ +function shadowRepoDir(checkpointDir: string, taskId: string): string { + if (!isSafeSessionId(taskId)) { + throw new Error(`Invalid taskId: ${taskId}`) + } + const tasksRoot = path.join(path.resolve(checkpointDir), "tasks") + const target = path.join(tasksRoot, taskId, "checkpoints") + return assertContainedPath(tasksRoot, target, "taskId") +} + class RepoPerTaskCheckpointServiceWithLog extends ShadowCheckpointService { static create({ taskId, workspaceRoot, checkpointDir, log }: Required) { return new RepoPerTaskCheckpointServiceWithLog( taskId, - path.join(checkpointDir, "tasks", taskId, "checkpoints"), + shadowRepoDir(checkpointDir, taskId), workspaceRoot, log, ) @@ -207,7 +217,7 @@ export class CheckpointService { */ export function createCheckpointService(options: CreateCheckpointServiceOptions): CheckpointService { const checkpointDir = options.checkpointDir ?? defaultCheckpointDir() - + shadowRepoDir(checkpointDir, options.taskId) if (isSameOrInside(options.workspaceRoot, checkpointDir)) { throw new Error( `Checkpoint dir '${checkpointDir}' is inside the workspace it tracks ('${options.workspaceRoot}'). ` + @@ -217,7 +227,6 @@ export function createCheckpointService(options: CreateCheckpointServiceOptions) `(${defaultCheckpointDir()}).`, ) } - return new CheckpointService({ taskId: options.taskId, workspaceRoot: options.workspaceRoot, diff --git a/src/codemap/html.ts b/src/codemap/html.ts index b29f4072..82d409dd 100644 --- a/src/codemap/html.ts +++ b/src/codemap/html.ts @@ -357,35 +357,39 @@ function showDetail(i) { const ext = (CODEMAP.externalDeps && CODEMAP.externalDeps[m.path]) || []; let html = ""; html += '
path' + escapeHtml(m.path) + "
"; - html += '
role' + m.role + "
"; - html += '
language' + m.language + "
"; - html += '
size' + m.sizeBytes + " bytes · " + m.lineCount + " lines
"; - html += '
layer' + layer[i] + "
"; + html += '
role' + + '' + + escapeHtml(m.role) + "
"; + html += '
language' + + escapeHtml(m.language) + "
"; + html += '
size' + + m.sizeBytes + " bytes · " + m.lineCount + " lines
"; + html += '
layer' + + escapeHtml(layer[i]) + "
"; if (ext.length) { html += '

external deps (' + ext.length + ")

    "; - html += ext.slice(0, 40).map((s) => "
  • " + escapeHtml(s) + "
  • ").join(""); + html += ext.slice(0, 40) + .map((s) => "
  • " + escapeHtml(s) + "
  • ").join(""); if (ext.length > 40) html += "
  • …
  • "; html += "
"; } - html += "

imports (" + importOut[i].length + ")

    "; - html += importOut[i].length - ? importOut[i].map((p) => '
  • ' + escapeHtml(CODEMAP.modules[p].path) + "
  • ").join("") + const jumpList = (ids) => ids.length + ? ids.map((p) => { + const ep = escapeHtml(CODEMAP.modules[p].path); + return '
  • ' + ep + "
  • "; + }).join("") : '
  • none
  • '; + html += "

    imports (" + importOut[i].length + ")

      "; + html += jumpList(importOut[i]); html += "
    "; html += "

    imported by (" + importIn[i].length + ")

    "; html += "

    calls (" + callOut[i].length + ")

    "; html += "

    called by (" + callIn[i].length + ")

    "; const flows = (CODEMAP.flows && CODEMAP.flows[m.path]) || []; if (m.role === "entrypoint" && flows.length) { @@ -405,7 +409,12 @@ function showDetail(i) { }); } function escapeHtml(s) { - return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + return String(s ?? "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); } document.getElementById("detailClose").addEventListener("click", () => { detail.classList.remove("open"); diff --git a/src/dashboard/__tests__/audit-security.test.ts b/src/dashboard/__tests__/audit-security.test.ts new file mode 100644 index 00000000..df4f1708 --- /dev/null +++ b/src/dashboard/__tests__/audit-security.test.ts @@ -0,0 +1,224 @@ +/** + * Security regression tests for T6-01, T6-02, and T6-08. + */ +import assert from "node:assert/strict" +import * as fs from "node:fs/promises" +import * as http from "node:http" +import * as os from "node:os" +import * as path from "node:path" + +import { createCheckpointService } from "../../checkpoints/service.js" +import { eventsFilePath, isSafeSessionId } from "../../engine/events.js" +import { isDashboardArtifactAvailable, renderPage } from "../page.js" +import { startDashboardServer } from "../server.js" +import { executeTool } from "../tool-exec.js" +import { runMain } from "../../test-runner.js" + +const GATED_ROUTES: Array<[string, string]> = [ + ["GET", "/api/summary"], + ["GET", "/api/session/s1/events"], + ["GET", "/api/settings/mode-models"], + ["GET", "/api/modes"], + ["POST", "/api/projects/ensure-worktree"], + ["POST", "/api/settings/mode-models"], + ["POST", "/api/tool/execute"], +] + +function portOf(server: http.Server): number { + const addr = server.address() + return typeof addr === "object" && addr ? addr.port : 0 +} + +function rawStatus( + port: number, + reqPath: string, + headers: Record, +): Promise { + return new Promise((resolve, reject) => { + const opts = { + host: "127.0.0.1", port, path: reqPath, method: "GET", headers, + } + const req = http.request(opts, (res) => { + res.resume() + res.on("end", () => resolve(res.statusCode ?? 0)) + }) + req.on("error", reject) + req.end() + }) +} + +async function assertAuthRequired( + base: string, + method: string, + urlPath: string, +): Promise { + const unauth = await fetch(base + urlPath, { method }) + assert.equal(unauth.status, 401, `${method} ${urlPath} must 401`) + const bad = await fetch(base + urlPath, { + method, + headers: { authorization: "Bearer wrong" }, + }) + assert.equal(bad.status, 401, `${method} ${urlPath} bad token`) +} + +async function testDefaultDenyBearerAuth(): Promise { + const repo = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-auth-")) + const server = await startDashboardServer({ port: 0, repo, token: "tok1" }) + const base = `http://127.0.0.1:${portOf(server)}` + try { + for (const [m, p] of GATED_ROUTES) await assertAuthRequired(base, m, p) + const ok = await fetch(base + "/api/summary", { + headers: { authorization: "Bearer tok1" }, + }) + assert.equal(ok.status, 200) + } finally { + server.close() + await fs.rm(repo, { recursive: true, force: true }) + } +} + +async function testHostEnforcement(): Promise { + const repo = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-host-")) + const server = await startDashboardServer({ port: 0, repo }) + const port = portOf(server) + try { + const status = await rawStatus(port, "/api/summary", { + host: `evil.example:${port}`, + }) + assert.equal(status, 403) + } finally { + server.close() + await fs.rm(repo, { recursive: true, force: true }) + } +} + +async function testOriginEnforcement(): Promise { + const repo = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-orig-")) + const server = await startDashboardServer({ port: 0, repo }) + const base = `http://127.0.0.1:${portOf(server)}` + try { + const res = await fetch(base + "/api/session/start", { + method: "POST", + headers: { + "content-type": "application/json", + origin: "https://evil.example", + }, + body: JSON.stringify({ task: "hi" }), + }) + assert.equal(res.status, 403) + } finally { + server.close() + await fs.rm(repo, { recursive: true, force: true }) + } +} + +async function postToolExec( + base: string, + ct: string, + ws: string, +): Promise { + const res = await fetch(base + "/api/tool/execute", { + method: "POST", + headers: { "content-type": ct }, + body: JSON.stringify({ workspace: ws, name: "list_files", args: {} }), + }) + return res.status +} + +async function testContentTypeAndWorkspaceScope(): Promise { + const repo = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-ws1-")) + const out = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-ws2-")) + const server = await startDashboardServer({ port: 0, repo }) + const base = `http://127.0.0.1:${portOf(server)}` + try { + assert.equal(await postToolExec(base, "text/plain", out), 403) + assert.equal(await postToolExec(base, "application/json", out), 403) + const scoped = await executeTool( + { workspace: out, name: "list_files", args: { path: "." } }, + { allowedRoots: [repo] }, + ) + assert.equal(scoped.isError, true) + } finally { + server.close() + await fs.rm(repo, { recursive: true, force: true }) + await fs.rm(out, { recursive: true, force: true }) + } +} + +async function testSessionIdUnitGuards(): Promise { + assert.equal(isSafeSessionId("valid-1.2_3"), true) + assert.equal(isSafeSessionId("."), false) + assert.equal(isSafeSessionId(".."), false) + assert.equal(isSafeSessionId("../../etc"), false) + const repo = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-u1-")) + const ckpt = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-u2-")) + try { + assert.throws(() => eventsFilePath(repo, "../../etc")) + assert.throws(() => + createCheckpointService({ + taskId: "../../etc", workspaceRoot: repo, checkpointDir: ckpt, + }), + ) + } finally { + await fs.rm(repo, { recursive: true, force: true }) + await fs.rm(ckpt, { recursive: true, force: true }) + } +} + +async function testSessionIdHttpGuards(): Promise { + const repo = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-h1-")) + const ckpt = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-h2-")) + const srv = await startDashboardServer({ port: 0, repo, checkpointDir: ckpt }) + const base = `http://127.0.0.1:${portOf(srv)}` + const hdrs = { "content-type": "application/json" } + try { + const r1 = await fetch(base + "/api/session/..%2F..%2Ftarget/events") + const r2 = await fetch(base + "/api/checkpoints?session=../../etc") + const u3 = base + "/api/checkpoints/restore?session=.." + const r3 = await fetch(u3, { method: "POST", headers: hdrs, body: "{}" }) + assert.deepEqual([r1.status, r2.status, r3.status], [400, 400, 400]) + } finally { + srv.close() + await fs.rm(repo, { recursive: true, force: true }) + await fs.rm(ckpt, { recursive: true, force: true }) + } +} + +async function writeFakeUiArtifact(uiDir: string): Promise { + await fs.mkdir(path.join(uiDir, "assets"), { recursive: true }) + const tpl = '
    ' + + '' + + '' + await fs.writeFile(path.join(uiDir, "page-template.html"), tpl) + await fs.writeFile(path.join(uiDir, "assets", "headlesscode.css"), "body{}") + await fs.writeFile(path.join(uiDir, "assets", "headlesscode.js"), "1+1") +} + +async function testPageUiDirConfig(): Promise { + const uiDir = await fs.mkdtemp(path.join(os.tmpdir(), "hc-sec-ui-")) + const prev = process.env.HEADLESSCODE_DASHBOARD_UI_DIR + try { + await writeFakeUiArtifact(uiDir) + process.env.HEADLESSCODE_DASHBOARD_UI_DIR = uiDir + assert.equal(isDashboardArtifactAvailable(), true) + const html = renderPage('x" onclick="alert(1)') + assert.ok(html.includes(""")) + assert.ok(!html.includes("/home/joe/Projects")) + } finally { + if (prev === undefined) delete process.env.HEADLESSCODE_DASHBOARD_UI_DIR + else process.env.HEADLESSCODE_DASHBOARD_UI_DIR = prev + await fs.rm(uiDir, { recursive: true, force: true }) + } +} + +const tests: Array<[string, () => Promise]> = [ + ["T6-01: default-deny bearer auth", testDefaultDenyBearerAuth], + ["T6-01: loopback Host check", testHostEnforcement], + ["T6-01: loopback Origin check", testOriginEnforcement], + ["T6-01: Content-Type and workspace", testContentTypeAndWorkspaceScope], + ["T6-02: sessionId unit traversal guards", testSessionIdUnitGuards], + ["T6-02: sessionId HTTP traversal guards", testSessionIdHttpGuards], + ["T6-08: dashboard UI dir env fallback", testPageUiDirConfig], +] + +runMain("audit-security", tests) diff --git a/src/dashboard/__tests__/file-browser-permissions.test.ts b/src/dashboard/__tests__/file-browser-permissions.test.ts index 76f5dbff..b876d467 100644 --- a/src/dashboard/__tests__/file-browser-permissions.test.ts +++ b/src/dashboard/__tests__/file-browser-permissions.test.ts @@ -505,9 +505,13 @@ async function testPermissionsTokenGate(): Promise { ) assert.equal(goodAuth.status, 200) - // GET /api/settings/permissions stays open (read-only, and not a - // workspace-file-content route) even when a token is configured. - const get = await getJson(base, url) + // GET /api/settings/permissions is also gated when a token is + // configured (T6-01 default-deny across /api/*). + const getNoAuth = await getJson(base, url) + assert.equal(getNoAuth.status, 401) + const get = await getJson(base, url, { + authorization: "Bearer sekret", + }) assert.equal(get.status, 200) // The file-browser GET routes ARE gated by the same token (SEC-7): diff --git a/src/dashboard/__tests__/session-launch.test.ts b/src/dashboard/__tests__/session-launch.test.ts index e2d62e05..d6fe265e 100644 --- a/src/dashboard/__tests__/session-launch.test.ts +++ b/src/dashboard/__tests__/session-launch.test.ts @@ -453,9 +453,14 @@ async function testTokenGatesControlPlanePosts(): Promise { await sleep(300) await fs.access(fake.marker) - // GETs are unaffected (read-only stays open). + // All /api/* routes are gated when token is set. const getEvents = await fetch(base + "/api/session/nope/events") - assert.equal(getEvents.status, 200) + assert.equal(getEvents.status, 401) + const getEventsAuthed = await fetch( + base + "/api/session/nope/events", + { headers: { authorization: "Bearer sekret" } }, + ) + assert.equal(getEventsAuthed.status, 200) } finally { server.close() } diff --git a/src/dashboard/page.ts b/src/dashboard/page.ts index f669de90..d4fc3d34 100644 --- a/src/dashboard/page.ts +++ b/src/dashboard/page.ts @@ -1,12 +1,23 @@ /** Fixed local shim for the Capsize-built HeadlessCode dashboard artifact. */ import { readFileSync } from "node:fs" import * as path from "node:path" +import { fileURLToPath } from "node:url" -const UI_DIST = "/home/joe/Projects/capsize-web/apps/headlesscode/dist" +const PACKAGE_ROOT = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", + "..", +) +const DEFAULT_UI_DIST = path.join(PACKAGE_ROOT, "dist", "dashboard-ui") const REPO_MARKER = "__CAPSIZE_REPO_BOOTSTRAP__" const STYLE_MARKER = '' const SCRIPT_MARKER = '' +export function resolveUiDistDir(): string { + const envDir = process.env.HEADLESSCODE_DASHBOARD_UI_DIR?.trim() + return envDir ? path.resolve(envDir) : DEFAULT_UI_DIST +} + function htmlAttribute(value: string): string { return value.replaceAll("&", "&") .replaceAll("<", "<").replaceAll(">", ">") @@ -14,40 +25,50 @@ function htmlAttribute(value: string): string { } /** - * Render the centralized Capsize UI bundle for direct HeadlessCode dashboard - * requests. Reads are lazy so importing the CLI or server never requires the - * sibling web workspace; a missing build is an explicit service error. - */ -/** - * True when the external Capsize dashboard artifact is present. - * Test entries probe this and SKIP when the sibling web workspace is - * not built on this machine; serving itself still fails loudly. + * True when the dashboard UI build artifact is present. + * Test entries probe this and SKIP when no artifact is built; + * serving itself still fails loudly. */ export function isDashboardArtifactAvailable(): boolean { try { + const uiDist = resolveUiDistDir() return ( - readFileSync(path.join(UI_DIST, "page-template.html"), "utf8").length > 0 + readFileSync(path.join(uiDist, "page-template.html"), "utf8").length > 0 ) } catch { return false } } -export function renderPage(repo?: string): string { - const templatePath = path.join(UI_DIST, "page-template.html") - const template = readFileSync(templatePath, "utf8") +function readUiBundle(uiDist: string): { + template: string + css: string + js: string +} { + const template = readFileSync(path.join(uiDist, "page-template.html"), "utf8") const css = readFileSync( - path.join(UI_DIST, "assets", "headlesscode.css"), "utf8", + path.join(uiDist, "assets", "headlesscode.css"), + "utf8", ) const js = readFileSync( - path.join(UI_DIST, "assets", "headlesscode.js"), "utf8", + path.join(uiDist, "assets", "headlesscode.js"), + "utf8", ) + return { template, css, js } +} + +export function renderPage(repo?: string): string { + const { template, css, js } = readUiBundle(resolveUiDistDir()) const safeJs = js.replace(/<\/script/gi, "<\\/script") - if (template.split(REPO_MARKER).length !== 2 - || !template.includes(STYLE_MARKER) || !template.includes(SCRIPT_MARKER)) { + if ( + template.split(REPO_MARKER).length !== 2 || + !template.includes(STYLE_MARKER) || + !template.includes(SCRIPT_MARKER) + ) { throw new Error("Capsize HeadlessCode dashboard artifact is invalid") } - return template.replace(REPO_MARKER, () => htmlAttribute(repo ?? "")) + return template + .replace(REPO_MARKER, () => htmlAttribute(repo ?? "")) .replace(STYLE_MARKER, () => ``) .replace(SCRIPT_MARKER, () => ``) } diff --git a/src/dashboard/server.ts b/src/dashboard/server.ts index c56336c8..3e8f3ea5 100644 --- a/src/dashboard/server.ts +++ b/src/dashboard/server.ts @@ -91,6 +91,7 @@ * so it must never be gated *less* strictly than the session routes. */ +import * as crypto from "node:crypto" import * as fsp from "node:fs/promises" import * as http from "node:http" import * as path from "node:path" @@ -125,7 +126,12 @@ import { readCostHistory, readSessionCostHistory } from "../orchestrator/cost-hi import { listProjectEntries } from "../project-store.js" import { listWorkspaceDir, readWorkspaceFile } from "./files.js" import { parseStopGraceOverride, stopSession } from "./session-stop.js" -import { executeTool, type ToolExecuteRequest } from "./tool-exec.js" +import { isSafeSessionId } from "../engine/events.js" +import { + executeTool, + isDashboardWorkspaceAllowed, + type ToolExecuteRequest, +} from "./tool-exec.js" import { loadPermissionsFile, parsePermissionsFileBody, @@ -218,8 +224,138 @@ export function warnControlPlaneAuth(options: { token?: string }): void { ) } +const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost"]) + +interface StatusError extends Error { + statusCode?: number +} + +function httpStatusError(statusCode: number, message: string): Error { + const err = new Error(message) as StatusError + err.statusCode = statusCode + return err +} + +function errorStatusCode(error: unknown): number { + if (error instanceof Error) { + const code = (error as StatusError).statusCode + if (typeof code === "number") return code + } + return 500 +} + +function sendJsonError( + res: http.ServerResponse, + code: number, + error: string, +): void { + res + .writeHead(code, { "content-type": "application/json; charset=utf-8" }) + .end(JSON.stringify({ error })) +} + +function sendError(res: http.ServerResponse, error: unknown): void { + const msg = error instanceof Error ? error.message : String(error) + sendJsonError(res, errorStatusCode(error), msg) +} + +async function parseJsonObjectBody( + req: http.IncomingMessage, + res: http.ServerResponse, +): Promise<{ ok: true; body: unknown } | { ok: false }> { + const raw = await readJsonBody(req) + try { + return { ok: true, body: JSON.parse(raw || "{}") } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + sendJsonError(res, 400, `invalid JSON body: ${msg}`) + return { ok: false } + } +} + +async function resolveSessionTarget( + url: URL, options: DashboardServerOptions, + res: http.ServerResponse, sessionId: string, +): Promise<{ source: string; worktreeRoot: string } | null> { + if (rejectInvalidSession(res, sessionId)) return null + const repo = url.searchParams.get("repo") || options.repo + if (!repo) { + const m = "missing repo — pass ?repo= or start the dashboard" + sendJsonError(res, 400, `${m} with --repo`) + return null + } + const found = await findSessionEventsFile(repo, sessionId) + if (!found) { + sendJsonError(res, 404, `no session ${sessionId} found under ${repo}`) + return null + } + const root = found.source === "." + ? path.resolve(repo) : path.resolve(repo, found.source) + return { source: found.source, worktreeRoot: root } +} + +async function saveConfigFile( + res: http.ServerResponse, file: string, content: string, +): Promise { + await fsp.mkdir(path.dirname(file), { recursive: true }) + await fsp.writeFile(file, content, "utf-8") + res + .writeHead(200, { "content-type": "application/json; charset=utf-8" }) + .end(JSON.stringify({ ok: true, path: file })) +} + +function isAllowedHost( + hostHeader: string | undefined, + port: number, +): boolean { + if (!hostHeader) return false + try { + const parsed = new URL(`http://${hostHeader}`) + return ( + LOOPBACK_HOSTS.has(parsed.hostname) && + parsed.username === "" && + parsed.password === "" && + parsed.port === String(port) + ) + } catch { + return false + } +} + +function isAllowedOrigin(origin: string | undefined, port: number): boolean { + if (origin === undefined) return true + try { + const p = new URL(origin) + return ( + p.protocol === "http:" && LOOPBACK_HOSTS.has(p.hostname) && + p.port === String(port) && !p.username && !p.password && + p.pathname === "/" && !p.search && !p.hash + ) + } catch { + return false + } +} + +function tokensMatch(actual: string, expected: string): boolean { + const a = Buffer.from(actual, "utf8") + const b = Buffer.from(expected, "utf8") + return a.length === b.length && crypto.timingSafeEqual(a, b) +} + +function rejectInvalidSession( + res: http.ServerResponse, + id: string, +): boolean { + if (isSafeSessionId(id)) return false + res + .writeHead(400, { "content-type": "application/json; charset=utf-8" }) + .end(JSON.stringify({ error: `invalid session id: ${id}` })) + return true +} + /** Start the dashboard HTTP server. Resolves once it's listening. */ export function startDashboardServer(options: DashboardServerOptions): Promise { + let boundPort = options.port const server = http.createServer((req, res) => { // .catch (issue #82): handleRequest is fire-and-forget from this // callback's perspective (http.createServer's handler isn't awaited), @@ -227,7 +363,7 @@ export function startDashboardServer(options: DashboardServerOptions): Promise { + void handleRequest(req, res, options, boundPort).catch((error) => { if (!res.headersSent) { res.writeHead(500, { "content-type": "application/json; charset=utf-8" }).end( JSON.stringify({ error: `internal error: ${error instanceof Error ? error.message : String(error)}` }), @@ -241,6 +377,8 @@ export function startDashboardServer(options: DashboardServerOptions): Promise { server.once("error", reject) server.listen(options.port, "127.0.0.1", () => { + const addr = server.address() + if (addr && typeof addr === "object") boundPort = addr.port server.removeListener("error", reject) warnControlPlaneAuth(options) resolve(server) @@ -252,51 +390,32 @@ async function handleRequest( req: http.IncomingMessage, res: http.ServerResponse, options: DashboardServerOptions, + port = options.port, ): Promise { - const url = new URL(req.url ?? "/", "http://127.0.0.1") + if (!isAllowedHost(req.headers.host, port)) { + res + .writeHead(403, { "content-type": "application/json; charset=utf-8" }) + .end(JSON.stringify({ error: "host is not allowed" })) + return + } + if (!isAllowedOrigin(req.headers.origin, port)) { + res + .writeHead(403, { "content-type": "application/json; charset=utf-8" }) + .end(JSON.stringify({ error: "origin is not allowed" })) + return + } + const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`) - // Optional control-plane token (HEADLESSCODE_DASHBOARD_TOKEN — see - // DashboardServerOptions.token). When configured, every state-changing - // POST requires the bearer header: /api/session/* (start/pause/resume/ - // stop/answer), the destructive POST /api/checkpoints/restore (reverts real - // workspace files — never gated looser than the session routes), and - // POST /api/settings/permissions (a weakened permissions file is more - // consequential than starting a session — same gate). - // - // SEC-7: the same token ALSO gates the GET routes that read workspace - // files or project data (file browser, checkpoints, codemap, cost - // history, project listing). Without this, any page open in the - // operator's browser — including a malicious one, via DNS-rebinding or - // simple localhost-CSRF (`fetch("http://127.0.0.1:4390/api/files/content?...")` - // from an unrelated origin) — could read `.env` and other workspace - // files with zero auth, since GETs carry no CSRF protection by default - // and the dashboard binds 127.0.0.1 only (reachable by anything running - // on the same machine, including browser tabs). Unset token = no auth, - // exactly today's behavior — this is opt-in defense in depth, not a - // guarantee (see SECURITY.md's "Known limitations"). - const tokenGatedGetPrefixes = [ - "/api/files", - "/api/checkpoints", - "/api/codemap", - "/api/cost-history", - "/api/projects", - ] - const isTokenGatedGet = - req.method === "GET" && tokenGatedGetPrefixes.some((p) => url.pathname === p || url.pathname.startsWith(`${p}/`)) - if ( - options.token && - ((req.method === "POST" && - (url.pathname.startsWith("/api/session/") || - url.pathname === "/api/checkpoints/restore" || - url.pathname === "/api/settings/permissions" || - url.pathname === "/api/tool/execute")) || - isTokenGatedGet) - ) { + if (options.token && url.pathname.startsWith("/api/")) { const auth = req.headers.authorization ?? "" const expected = `Bearer ${options.token}` - if (auth !== expected) { - res.writeHead(401, { "content-type": "application/json; charset=utf-8" }).end( - JSON.stringify({ error: "unauthorized — set Authorization: Bearer " }), + if (!tokensMatch(auth, expected)) { + res.writeHead(401, { + "content-type": "application/json; charset=utf-8", + }).end( + JSON.stringify({ + error: "unauthorized — set Authorization: Bearer ", + }), ) return } @@ -306,6 +425,7 @@ async function handleRequest( const eventsMatch = /^\/api\/session\/([^/]+)\/events$/.exec(url.pathname) if (eventsMatch && req.method === "GET") { const sessionId = decodeURIComponent(eventsMatch[1]) + if (rejectInvalidSession(res, sessionId)) return const repo = url.searchParams.get("repo") || options.repo if (!repo) { res.writeHead(400, { "content-type": "application/json; charset=utf-8" }).end( @@ -345,6 +465,7 @@ async function handleRequest( } if (pauseMatch && req.method === "POST") { const sessionId = decodeURIComponent(pauseMatch[1]) + if (rejectInvalidSession(res, sessionId)) return const action = pauseMatch[2] const repo = url.searchParams.get("repo") || options.repo if (!repo) { @@ -394,6 +515,7 @@ async function handleRequest( } if (stopMatch && req.method === "POST") { const sessionId = decodeURIComponent(stopMatch[1]) + if (rejectInvalidSession(res, sessionId)) return const repo = url.searchParams.get("repo") || options.repo if (!repo) { res.writeHead(400, { "content-type": "application/json; charset=utf-8" }).end( @@ -453,10 +575,7 @@ async function handleRequest( }), ) } catch (error) { - const detail = error instanceof Error ? error.message : String(error) - res.writeHead(500, { "content-type": "application/json; charset=utf-8" }).end( - JSON.stringify({ error: detail }), - ) + sendError(res, error) } return } @@ -481,16 +600,9 @@ async function handleRequest( return } try { - const raw = await readJsonBody(req) - let body: unknown - try { - body = JSON.parse(raw || "{}") - } catch (err) { - res - .writeHead(400, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: `invalid JSON body: ${err instanceof Error ? err.message : String(err)}` })) - return - } + const parsed = await parseJsonObjectBody(req, res) + if (!parsed.ok) return + const body = parsed.body const repo = (body as { repo?: string }).repo?.trim() if (!repo) { res @@ -509,12 +621,11 @@ async function handleRequest( return } const scope = typeof sessionId === "string" ? sessionId.trim() || undefined : undefined + if (scope !== undefined && rejectInvalidSession(res, scope)) return const workspace = ensureWorktree(options.worktreeRoot, repo, scope) res.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ workspace })) } catch (error) { - res - .writeHead(500, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })) + sendError(res, error) } return } @@ -535,16 +646,9 @@ async function handleRequest( } if (url.pathname === "/api/session/start" && req.method === "POST") { try { - const raw = await readJsonBody(req) - let body: unknown - try { - body = JSON.parse(raw || "{}") - } catch (err) { - res - .writeHead(400, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: `invalid JSON body: ${err instanceof Error ? err.message : String(err)}` })) - return - } + const parsed = await parseJsonObjectBody(req, res) + if (!parsed.ok) return + const body = parsed.body const validationError = validateSessionStartBody(body) if (validationError) { res @@ -618,15 +722,16 @@ async function handleRequest( // Re-check under the lock: a concurrent request may have // recorded this key while we were acquiring. if (idempotencyKey) { - const replay = replayIdempotentStart(repo, idempotencyKey, start.task, payloadMode) + const replay = replayIdempotentStart( + repo, idempotencyKey, start.task, payloadMode, + ) if (replay.conflict) { - res - .writeHead(409, { "content-type": "application/json; charset=utf-8" }) - .end( - JSON.stringify({ - error: `idempotencyKey '${idempotencyKey}' was already used with a different task/mode/repo — use a fresh key`, - }), - ) + sendJsonError( + res, + 409, + `idempotencyKey '${idempotencyKey}' was already used with a ` + + "different task/mode/repo — use a fresh key", + ) return } if (replay.entry) { @@ -667,9 +772,7 @@ async function handleRequest( } } } catch (error) { - res - .writeHead(500, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })) + sendError(res, error) } return } @@ -700,12 +803,31 @@ async function handleRequest( return } const request = body as ToolExecuteRequest + const ws = typeof request?.workspace === "string" + ? request.workspace.trim() + : "" + if ( + ws !== "" && + !isDashboardWorkspaceAllowed(ws, options.repo, options.worktreeRoot) + ) { + res + .writeHead(403, { + "content-type": "application/json; charset=utf-8", + }) + .end( + JSON.stringify({ + ok: false, + isError: true, + error: "workspace is not registered or allowed", + content: "workspace is not registered or allowed", + }), + ) + return + } const result = await executeTool(request) res.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(result)) } catch (error) { - res - .writeHead(500, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })) + sendError(res, error) } return } @@ -722,31 +844,12 @@ async function handleRequest( } if (answerMatch && req.method === "POST") { const sessionId = decodeURIComponent(answerMatch[1]) - const repo = url.searchParams.get("repo") || options.repo - if (!repo) { - res.writeHead(400, { "content-type": "application/json; charset=utf-8" }).end( - JSON.stringify({ error: "missing repo — pass ?repo= or start the dashboard with --repo" }), - ) - return - } try { - const found = await findSessionEventsFile(repo, sessionId) - if (!found) { - res.writeHead(404, { "content-type": "application/json; charset=utf-8" }).end( - JSON.stringify({ error: `no session ${sessionId} found under ${repo}` }), - ) - return - } - const raw = await readJsonBody(req) - let body: unknown - try { - body = JSON.parse(raw || "{}") - } catch (err) { - res - .writeHead(400, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: `invalid JSON body: ${err instanceof Error ? err.message : String(err)}` })) - return - } + const target = await resolveSessionTarget(url, options, res, sessionId) + if (!target) return + const parsed = await parseJsonObjectBody(req, res) + if (!parsed.ok) return + const body = parsed.body const answer = (body as { answer?: unknown })?.answer if (typeof answer !== "string" || answer.trim() === "") { res @@ -756,15 +859,12 @@ async function handleRequest( } // The marker lives in the worktree that owns the session's events // feed (same resolution pause/resume uses above). - const worktreeRoot = found.source === "." ? path.resolve(repo) : path.resolve(repo, found.source) - await answerSessionDecision(worktreeRoot, answer.trim()) + await answerSessionDecision(target.worktreeRoot, answer.trim()) res.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end( - JSON.stringify({ sessionId, ok: true, worktree: found.source }), + JSON.stringify({ sessionId, ok: true, worktree: target.source }), ) } catch (error) { - res - .writeHead(500, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })) + sendError(res, error) } return } @@ -788,31 +888,12 @@ async function handleRequest( } if (messageMatch && req.method === "POST") { const sessionId = decodeURIComponent(messageMatch[1]) - const repo = url.searchParams.get("repo") || options.repo - if (!repo) { - res.writeHead(400, { "content-type": "application/json; charset=utf-8" }).end( - JSON.stringify({ error: "missing repo — pass ?repo= or start the dashboard with --repo" }), - ) - return - } try { - const found = await findSessionEventsFile(repo, sessionId) - if (!found) { - res.writeHead(404, { "content-type": "application/json; charset=utf-8" }).end( - JSON.stringify({ error: `no session ${sessionId} found under ${repo}` }), - ) - return - } - const raw = await readJsonBody(req) - let body: unknown - try { - body = JSON.parse(raw || "{}") - } catch (err) { - res - .writeHead(400, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: `invalid JSON body: ${err instanceof Error ? err.message : String(err)}` })) - return - } + const target = await resolveSessionTarget(url, options, res, sessionId) + if (!target) return + const parsed = await parseJsonObjectBody(req, res) + if (!parsed.ok) return + const body = parsed.body const text = (body as { text?: unknown })?.text if (typeof text !== "string" || text.trim() === "") { res @@ -822,15 +903,12 @@ async function handleRequest( } // The marker lives in the worktree that owns the session's events // feed (same resolution pause/resume/answer use above). - const worktreeRoot = found.source === "." ? path.resolve(repo) : path.resolve(repo, found.source) - await injectSessionMessage(worktreeRoot, text.trim()) + await injectSessionMessage(target.worktreeRoot, text.trim()) res.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end( - JSON.stringify({ sessionId, ok: true, worktree: found.source }), + JSON.stringify({ sessionId, ok: true, worktree: target.source }), ) } catch (error) { - res - .writeHead(500, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })) + sendError(res, error) } return } @@ -885,15 +963,10 @@ async function handleRequest( return } const file = modeModelsFilePath(repo) - await fsp.mkdir(path.dirname(file), { recursive: true }) - await fsp.writeFile(file, stringifyModeModelsFile(body as ModeModelsFile), "utf-8") - res - .writeHead(200, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ ok: true, path: file })) + const serialized = stringifyModeModelsFile(body as ModeModelsFile) + await saveConfigFile(res, file, serialized) } catch (error) { - res - .writeHead(500, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })) + sendError(res, error) } return } @@ -918,6 +991,7 @@ async function handleRequest( ) return } + if (rejectInvalidSession(res, session)) return const routeOptions = { workspaceRoot: repo, sessionId: session, checkpointDir: options.checkpointDir } try { if (url.pathname === "/api/checkpoints") { @@ -992,6 +1066,7 @@ async function handleRequest( ) return } + if (rejectInvalidSession(res, session)) return try { const raw = await readJsonBody(req) let body: unknown @@ -1018,9 +1093,7 @@ async function handleRequest( JSON.stringify({ ok: true, restored: hash.trim() }), ) } catch (error) { - res - .writeHead(500, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })) + sendError(res, error) } return } @@ -1116,15 +1189,9 @@ async function handleRequest( return } const file = permissionsFilePath(repo) - await fsp.mkdir(path.dirname(file), { recursive: true }) - await fsp.writeFile(file, stringifyPermissionsFile(parsed), "utf-8") - res - .writeHead(200, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ ok: true, path: file })) + await saveConfigFile(res, file, stringifyPermissionsFile(parsed)) } catch (error) { - res - .writeHead(500, { "content-type": "application/json; charset=utf-8" }) - .end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })) + sendError(res, error) } return } @@ -1333,12 +1400,20 @@ async function handleRequest( /** Read a request body as text (bounded — settings payloads are tiny). */ async function readJsonBody(req: http.IncomingMessage): Promise { + const rawType = req.headers["content-type"] + const ct = rawType?.split(";", 1)[0]?.trim().toLowerCase() + if (ct !== "application/json") { + throw httpStatusError(403, "Content-Type: application/json is required") + } const chunks: Buffer[] = [] + let totalBytes = 0 for await (const chunk of req) { - chunks.push(chunk as Buffer) - if (chunks.reduce((n, c) => n + c.length, 0) > 1_000_000) { - throw new Error("request body too large (limit 1MB)") + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + totalBytes += buf.length + if (totalBytes > 1_000_000) { + throw httpStatusError(413, "request body too large (limit 1MB)") } + chunks.push(buf) } return Buffer.concat(chunks).toString("utf-8") } diff --git a/src/dashboard/tool-exec.ts b/src/dashboard/tool-exec.ts index b31d329e..2e654fa9 100644 --- a/src/dashboard/tool-exec.ts +++ b/src/dashboard/tool-exec.ts @@ -28,8 +28,11 @@ * still spawning, orphaning it past the call (issue #186). */ +import { execFileSync } from "node:child_process" import * as fs from "node:fs" +import * as path from "node:path" +import { listProjectEntries } from "../project-store.js" import { createHeadlessExecutor } from "../tools/executor.js" import type { ToolResult } from "../engine/types.js" @@ -50,6 +53,12 @@ export interface ToolExecuteResult { content: string } +/** Optional workspace allowlist for `executeTool`. */ +export interface ToolExecuteOptions { + allowedRoots?: string[] + worktreeRoot?: string +} + /** * Run one tool call against `req.workspace` and return the executor result. * @@ -58,19 +67,20 @@ export interface ToolExecuteResult { * a timed-out backgrounded `execute_command` child is hard-killed rather than * orphaned. */ -export async function executeTool(req: ToolExecuteRequest): Promise { +export async function executeTool( + req: ToolExecuteRequest, + options?: ToolExecuteOptions, +): Promise { const err = validateToolExecuteRequest(req) - if (err) { - return { ok: false, isError: true, content: err } + if (err) return { ok: false, isError: true, content: err } + if (options?.allowedRoots && !isWorkspaceInRoots(req.workspace, options)) { + const msg = `workspace is not registered or allowed: ${req.workspace}` + return { ok: false, isError: true, content: msg } } const executor = createHeadlessExecutor(req.workspace) try { - const result: ToolResult = await executor.execute(req.name, req.args) - return { - ok: !result.isError, - isError: result.isError, - content: result.content, - } + const r: ToolResult = await executor.execute(req.name, req.args) + return { ok: !r.isError, isError: r.isError, content: r.content } } finally { executor.dispose() } @@ -109,3 +119,82 @@ function pathIsAbsolute(p: string): boolean { } return false } + +function canonicalDir(dirPath: string): string | null { + try { + const real = fs.realpathSync(dirPath) + return fs.statSync(real).isDirectory() ? real : null + } catch { + return null + } +} + +function gitWorktreeMainRoot(dir: string): string | null { + try { + const out = execFileSync( + "git", + ["-C", dir, "rev-parse", "--show-toplevel", "--git-common-dir"], + { encoding: "utf-8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }, + ).trim() + const lines = out.split("\n").map((l) => l.trim()).filter(Boolean) + if (lines.length < 2) return null + if (canonicalDir(lines[0]) !== dir) return null + const common = path.isAbsolute(lines[1]) + ? lines[1] + : path.resolve(dir, lines[1]) + return canonicalDir(path.dirname(common)) + } catch { + return null + } +} + +function matchesAllowedRoot( + candidate: string, + mainRoot: string | null, + rootPath: string, +): boolean { + const rootReal = canonicalDir(rootPath) + if (!rootReal) return false + if (candidate === rootReal) return true + if (path.dirname(candidate) === path.join(rootReal, ".worktrees")) { + return true + } + return mainRoot !== null && mainRoot === rootReal +} + +/** Check `workspace` against explicit `allowedRoots` / `worktreeRoot`. */ +export function isWorkspaceInRoots( + workspace: string, + options: ToolExecuteOptions, +): boolean { + const candidate = canonicalDir(workspace) + if (!candidate) return false + if (options.worktreeRoot) { + const wt = canonicalDir(options.worktreeRoot) + if (wt && path.dirname(candidate) === wt) return true + } + const roots = options.allowedRoots ?? [] + const mainRoot = gitWorktreeMainRoot(candidate) + return roots.some((r) => matchesAllowedRoot(candidate, mainRoot, r)) +} + +/** Check `workspace` against `repo`, `worktreeRoot`, or registered projects. */ +export function isDashboardWorkspaceAllowed( + workspace: string, + repo?: string, + worktreeRoot?: string, +): boolean { + if ( + repo && + isWorkspaceInRoots(workspace, { allowedRoots: [repo], worktreeRoot }) + ) { + return true + } + if (worktreeRoot && isWorkspaceInRoots(workspace, { worktreeRoot })) { + return true + } + const registered = listProjectEntries() + .filter((e) => e.registered && e.exists && e.path) + .map((e) => e.path as string) + return isWorkspaceInRoots(workspace, { allowedRoots: registered }) +} diff --git a/src/dashboard/trend.ts b/src/dashboard/trend.ts index 915c544e..d966d02b 100644 --- a/src/dashboard/trend.ts +++ b/src/dashboard/trend.ts @@ -244,6 +244,15 @@ export function startTrendServer(options: TrendServerOptions): Promise", ">") + .replaceAll('"', """) + .replaceAll("'", "'") +} + function renderTrendPage(repoPaths: string[]): string { return ` @@ -290,7 +299,12 @@ ul.insights li { margin-bottom: 10px; }

    headlesscode: cost-efficiency trend

    -

    Live from cost-history.jsonl across ${repoPaths.length} repo(s): ${repoPaths.map((p) => path.basename(p)).join(", ")}. Refreshes every 30s.

    +

    + Live from cost-history.jsonl across ${repoPaths.length} + repo(s): + ${repoPaths.map((p) => escapeTrendHtml(path.basename(p))).join(", ")}. + Refreshes every 30s. +

    loading…

    @@ -313,15 +327,45 @@ ul.insights li { margin-bottom: 10px; }