Skip to content
Back to search

bkit-marketplace

MarketplaceWorks with Claude CodeGitHub

DubDubDub Corp.'s Vibecoding Kit marketplace - PDCA methodology and AI-native development tools. Requires Claude Code v2.1.143+ for the bkit plugin (older versions reject the displayName field).

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/ww-w-ai/bkit-claude-code with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/ww-w-ai/bkit-claude-code'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/popup-studio-ai--bkit-claude-code/badge.svg)](/listings/popup-studio-ai--bkit-claude-code)

HTML

<a href="/listings/popup-studio-ai--bkit-claude-code"><img src="/api/listings/popup-studio-ai--bkit-claude-code/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# 1. Install (one time)
claude plugin install bkit

# 2. Enable parallel team execution (optional, recommended)
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1

# 3. Your very first run — single feature
/pdca pm my-feature        # Describes what you want; bkit handles the rest

# 4. When you're ready for a multi-feature release
/sprint master-plan my-release --name "Q2 Launch" --features auth, billing, reports
# (You approve the plan)
/sprint start my-release-s1

Recommended Claude Code runtime: **v2.1.220** (bkit explicitly handles v2.1.218's `context: fork` background-by-default change and v2.1.219's nested-subagent depth-3 default; Claude 5 alias resolution — `sonnet` → Sonnet 5 needs ≥ v2.1.197). Model floor: **v2.1.170+** required by the 6 Fable-pinned agents (below it they fail to spawn; bkit shows a SessionStart advisory with a workaround). Install minimum **v2.1.143**; runtime minimum **v2.1.78**.

**On Claude Code v2.1.232 and later**, fork mode is on by default in interactive sessions: a subagent's result arrives as a notification on a *later* turn, and the Agent tool no longer accepts `run_in_background`. bkit's skills are unaffected. Sprint gates that measure through a subagent will report **"not measured"** rather than a score, and name the cause — a missing number, never a wrong one. Set `CLAUDE_CODE_FORK_SUBAGENT=0` to get in-turn results back. bkit shows this once at SessionStart and does not block. Verified against v2.1.232; Breaking changes 0 across v2.1.228–v2.1.232 (171 consecutive compatible releases).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 64 lines · 2 findings marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "bkit-marketplace",
  4. "version": "2.1.41",
  5. "description": "DubDubDub Corp.'s Vibecoding Kit marketplace - PDCA methodology and AI-native development tools. Requires Claude Code v2.1.143+ for the bkit plugin (older versions reject the displayName field).",
  6. "owner": {
  7. "name": "DubDubDub Corp.",
  8. "email": "biz@ww-w.ai",
  9. "url": "https://ww-w.ai"
  10. },
  11. "plugins": [
  12. {
  13. "name": "bkit-starter",
  14. "description": "Korean learning guide for Claude Code beginners. No programming experience required. Includes 4 learning commands.",
  15. "version": "1.0.0",
  16. "author": {
  17. "name": "DubDubDub Corp.",
  18. "email": "biz@ww-w.ai"
  19. },
  20. "repository": "https://github.com/ww-w-ai/bkit-starter",
  21. "source": {
  22. "source": "url",
  23. "url": "https://github.com/ww-w-ai/bkit-starter.git"
  24. },
  25. "category": "learning",
  26. "keywords": [
  27. "beginner",
  28. "korean",
  29. "tutorial",
  30. "starter",
  31. "learning"
  32. ]
  33. },
  34. {
  35. "name": "bkit",
  36. "description": "Requires Claude Code v2.1.143+ (older versions reject the strict plugin-manifest displayName field — run `npm install -g @anthropic-ai/claude-code@latest` to upgrade; see docs/06-guide/cc-compatibility.guide.md). Vibecoding Kit - PDCA + Sprint Management + CTO-Led Agent Teams + Living Context System + 43 PM frameworks. v2.1.14 5 differentiations (Memory Enforcer, Layer 6 Defense, Sequential Dispatch, Effort-aware, Heredoc-bypass) — a sixth, PostToolUse continueOnBlock, was withdrawn in v2.1.37 (ENH-432) after the field was measured to belong to prompt-type hook definitions, which bkit has none of. v2.1.15 pdca-status.json fix. v2.1.16 4 GitHub issues (Quality Gates UX). v2.1.17 5/12~5/20 contract red 8-day class close. v2.1.18 Issues #100/#101/#102 — Sprint Trust UX Fix. v2.1.19 Quality Maturation Sprint — 5 sub-sprint master plan (S1 Self-Dogfooding Enablement / S2 Convention Restoration / S3 Sprint Report Maturity / S4 External Dogfooder Lifecycle / S5 Sprint Maturity Index) + ENH-318 차별화 7/7 정식 편입 + Real User Hall of Fame 도입 + 첫 외부 dogfooder entry @pruge. v2.1.20 Marketplace Recovery — minimum CC v2.1.143 advisory (F1+F4) + plugin manifest 21-key whitelist CI gate (F5+F6, ENH-322) + claude plugin validate wire (F7, ADR 0006 § Empirical Validation Gate) + cc-regression R3-321 (F8, ENH-321) + SessionStart CC version detection (F10, ENH-323) + ADR 0011 Plugin Manifest Schema Compliance Policy + Hall of Fame @bj (#2 external dogfooder, Lifecycle 5-stage). v2.1.21 Issue Response — Session Title Isolation (#111: per-session sessions[sessionId] cache map + GC + legacy migration + stable session tag for parallel-window disambiguation) + Sprint Output Enforcement (#113: lib/sprint/executive-summary.js sprint-shape + scripts/sprint-skill-stop.js run-export Stop hook + SKILL_HANDLERS sprint registration + advancePhase phaseTransitionSummary + /sprint status·watch human-readable display) + ADR 0012 Sprint Stop Hook Output Enforcement. v2.1.24 Skill Namespace Hardening — Issues #125/#126 (@hslee-cmyk): normalizeSkillName() canonicalizes CC `plugin:skill` form (bkit:pdca → pdca) so getSkillConfig + skill-post + implicit-trigger injection + Stop-handler dispatch resolve the bare folder; hook-reachability check no longer false-positives skill_post (event-driven vs canary correlation). v2.1.25 Claude 5 Model Alignment + Issue Response — 4-tier role-based model matrix (9 fable verification/orchestration core + 7 opus deep-reasoning/security + 16 sonnet implementers + 2 haiku monitors), dual floor (install v2.1.143 / model v2.1.170 advisory ENH-368), Claude 5 pricing sync; Issues #128 (@NEXCODE-MK: 6 deprecated pdca-eval-* stubs removed from the prompt surface → deprecation registry, ADR 0014) + #129 (@NEXCODE-MK: agent description token diet −44%, compact 8-language triggers) + #130 (@s99606931: learning-stop.js piped-stdin isTTY gate fix). v2.1.26 MCP Manifest Relocation + Fable Cost Retune — fixes the /plugin 'Needs attention: bkit MCP failed' defect (repo-root .mcp.json dual-loaded as plugin manifest + project config where CLAUDE_PLUGIN_ROOT is undefined; now declared inline in plugin.json, root file deleted, regression-locked MS-016) + release-plugin-tag.sh drift fix + full test-state isolation refactor (projectRoot injectable through batch-orchestrator/sprint-registry/audit-logger; tests no longer leak fixtures into the real .bkit) + ADR 0011 amendment/ADR 0015 (locale-scoped deferral)/eval re-baseline SOP + Fable cost retune (ENH-370: high-frequency PDCA verifiers gap-detector/design-validator/pdca-iterator fable→opus for cost → 6 fable / 10 opus / 16 sonnet / 2 haiku). v2.1.27 Slash-Path Orchestration Restored — Issue #132 (@hslee-cmyk): bkit's four orchestrator side-effects (next-skill/agent guidance, PDCA phase auto-advance, decision-trace phase_transition, audit skill_executed) were wired only to PostToolUse:Skill, which never fires on native slash commands (/bkit:pdca ...) — the only invocation form bkit's docs teach — so the advertised audit trail was empty for real usage; ENH-371 dual-wires the effects into a source-agnostic module fired from BOTH PostToolUse:Skill AND a new fail-open UserPromptExpansion hook (slash path records a new skill_invoked action), plus repays two latent defects (dead IntentRouter onboardingContext ReferenceError + slash-path Stop-handler marker) — graceful degradation on CC without UserPromptExpansion, no version floor bump. v2.1.28 Runtime-Phase-Aware Skill Guidance — Issue #135 (@hslee-cmyk), the narrower follow-up to #132: the next-step GUIDANCE-TEXT half of the same UserPromptExpansion mechanism never fired for multi-action routers (pdca/sprint/+9) because orchestrateSkillPost derived suggestions only from STATIC frontmatter (next-skill/pdca-phase), which those routers declare null by design. Root fix: new lib/orchestrator/runtime-guidance.js resolves the phase at call time from args.action + live PDCA/Sprint state and REUSES the manual-path SSoT (getNextPdcaActionAfterCompletion / buildNextActions) — no duplicated phase table; wired at the shared runSkillInvocationEffects chokepoint so BOTH slash and Skill-tool paths surface guidance; fail-open; only pdca/sprint eligible (9 utility routers stay intentionally silent); suggestedAgent extended (design→design-validator, qa→qa-lead); hardcoded Korean guidance strings migrated to EN-default + KO via i18n detector. 23-TC regression test, 0 main-baseline regressions. v2.1.29 PDCA Predecessor-Task Completion — Issue #137 (@hslee-cmyk): the `pdca` skill chains phase Tasks via `blockedBy` ([Plan]→[Design]→[Do]→…) but SKILL.md documented Task creation only, never predecessor completion, so a prior-phase Task left `in_progress` leaked a stale phase (e.g. \"design\" during \"do\") into Claude Code's ambient prompt context — disagreeing with `.bkit/state/pdca-status.json`'s phase (the phase source of truth). The issue's Option-2 (a hook auto-completing the predecessor) is technically infeasible — CC hooks communicate via stdout/exit-code/additionalContext only and cannot call TaskUpdate; only the model can — so v2.1.29 applies Option-1: every phase action now instructs the model to mark predecessor Task(s) `completed` before creating the next phase Task, and a new `## Task Integration` Phase Transition Rule codifies the completion semantics + rationale; a regression test guards each transition. Cosmetic/informational fix, zero runtime/architecture-count change. v2.1.30 Stop-Hook stdin-Block Hardening — Issue #139 (@thenopen, found via Claude Code /doctor): every bkit hook reads its payload through lib/core/io.js readStdinSync(), which used fs.readFileSync(0) — a blocking stdin read with NO timeout that returns only at EOF, so a hook stalls for as long as Claude Code keeps the stdin write-end open (the turn-gating Stop hook unified-stop.js was observed stalling up to ~15.5 min, far past its own 10s timeout). Reproduced: payload sent + pipe held open 4s → 4.07s block with flat CPU (I/O-blocked, matching the reporter's low-CPU tail). Central fix (all 36 hook scripts): readStdinSync now reads incrementally with parse-early and returns the instant the buffer holds a complete JSON value, never waiting for EOF; the turn-gating unified-stop.js additionally uses a new async readStdinBounded (parse-early + hard timeout that destroys stdin on resolve) so it is fully bounded even for no-data/truncated held-open pipes; state-store lock() CPU-burning busy-wait spin replaced with a no-CPU Atomics.wait sleep. 16-TC regression test, 0 main-baseline regressions, architecture counts invariant. v2.1.31 CC v2.1.218 Fork Background-Default Compat — the 8 `context: fork` producer skills add `background: false` to opt out of CC v2.1.218 background-by-default; qa-phase leaves the fork set to run in the main context (AskUserQuestion is stripped at the fork sub-agent boundary, CC #34592/#54892); the Invocation Contract runner gains a `contextChanges` allowance (deprecation-registry.json, ADR 0014 pattern — baseline JSON immutable); CC recommended v2.1.220. Skill-frontmatter-only, architecture counts invariant. 🚀 bkit Early Adopter Program — running bkit on a non-trivial production project + filing detailed bug reports makes you part of bkit's quality system: public Hall of Fame recognition, E2E regression test absorption, Trust Score externalDogfoodFeedbackResponseRate component (weight 0.05). 44 Skills, 34 Agents (6 pdca-eval-* registry-tombstoned per ADR 0014), 63 Scripts, 200 Lib Modules, 21 Hook Events (24 blocks), 40 Templates, 4 Output Styles, 2 MCP Servers (19 tools, declared inline in plugin.json), 14 ADR invariants. v2.1.36 Guardrail Precision — external dogfooder @Sinclair-Seo (issue #148) reported three Destructive Detector rules refusing safe commands; auditing all 16 measured the defect at ~3x the report and found the same root cause producing FALSE NEGATIVES (`chmod 777 / ; ls` was detected by nothing at all). Rules are now matched per command segment instead of against the whole input, so a chained command cannot lend its tokens to a neighbour — 12 measured false positives to 1 (an intended grading change: a scoped find-delete now asks instead of denying, matching G-001), 3 false negatives to 0, every negative control intact. G-004 stops matching git plumbing (merge-base/merge-tree/merge-file), G-013 grades by target like G-001, G-006 ignores metadata-only listing, G-007 stands down on SQL statements. the refusal message names only recourse that exists AND fits the rule that fired (the first attempt rewrote a function with no production callers, so nothing changed for anyone; the text users see is built in the hook). Auditing the whole hook path rather than one module also found `bash <<EOF … rm -rf / … EOF` being ALLOWED, a push guard refusing `git push origin feature-x && rm -f note.txt` as a force push, and every `ask` the push guard computed being emitted as a refusal. ADR 0016 records that guardrail rules are immutable at runtime — deliberately, not by omission. Config drift closed in both directions: 5 getConfig() paths that never resolved to 1 (verified benign), 27 keys read by nobody to 13, each now documented in the file with its reason. Suite 3835/3839 PASS 0 FAIL (+41 TC, verified failing against the pre-fix tree). v2.1.37 Permission-Mode Awareness — Claude Code sends `permission_mode` on every hook event and bkit read it in ZERO places (`grep -rn permission_mode scripts lib hooks` returned nothing), so all ten decision surfaces behaved identically whether the session had asked for maximum oversight or had run `--dangerously-skip-permissions`. Not a CC defect: PreToolUse hooks run BEFORE the permission prompt, proven with a bkit-free project whose single ask-hook stopped a bare `echo` in bypass mode on CC v2.1.231. The cost is that a PreToolUse question needs a human answer and an unattended run has none, so the agent stalls instead of failing. New pure domain module lib/domain/policy/permission-mode-policy.js holds the whole decision table; the ask tier stands down in bypassPermissions/dontAsk/acceptEdits while `critical` refusals and the user's own CLAUDE.md directives hold in every mode — the line is the decision's GRADE, the same line CC draws by keeping a circuit breaker on `rm -rf /` in bypass. Measured 7 modes x 21 commands: benign commands stopped 14 to 0, negative controls 49/49 intact. Five coupled defects shipped with it: the phase-9 guard refusing on the bare substrings `--force`/`production`, the QA guard's private 9-entry rule table (which refused `rm -r ./tmp` and missed `chmod 777 /`) deleted in favour of the shared detector, ENH-263 fed from a payload field CC has never sent so it had not fired once since v2.1.10, `removeWhen(ccVersion)` declared by two guards and called by nothing, G-007 matching the WORD `delete` so `grep -rn delete a b c d e` asked for confirmation, and a `grep` for a dangerous string graded as performing one. 148 test files that ran in neither the local runner nor CI were adopted — 147 passed, and the one that failed was catching this release's own doc drift. v2.1.38 QA Measurement — the QA phase reported success while producing nothing the quality gate could read, and none of it could surface as a failing run. No Stop handler had ever seen its hook payload: unified-stop reads stdin with a reader that destroys it on resolve (deliberate, issue #139) and then dispatches handlers with require() in the same process, so the parent saw the payload and every child saw {} — measured with a two-file harness reproducing the dispatch. qa-phase-stop then called .match() on that parsed object, throwing on its first pattern into its own catch, so M11-M15 were never written on any run since v2.1.1; analysis-stop and qa-stop regexed their own hardcoded guidance string, so M2 was always the 75 baseline and M5 always 0; gap-detector-stop, iterator-stop and pdca-skill-stop regexed the hook ENVELOPE (hook_event_name, session_id, transcript_path, cwd), which contains none of the signals they look for. io.js now hands the payload it already read to the later reader and readHookText() resolves it to the assistant's reported text via transcript_path. The qa gate had required qaCriticalCount === 0 since v2.1.1 with no metric ID producing that name, and an absent metric is unsatisfied, so the gate could never return pass and QA could not advance to Report regardless of test results — M16 supplies the metric, the gate is unchanged. Chrome MCP detection read MCP_SERVERS, which Claude Code does not set, so L3-L5 were skipped on 100% of runs while qa-lead's docs called that skip normal fallback; detection is now layered behind a runtime probe qa-lead records. act -> qa (QA_RETRY) was defined and emitted by nothing and its counter never advanced, so the escape hatch from the qa <-> act loop could not fire. An unmeasured match rate defaulted to 0, which isMeasured() accepts as real, turning a parse failure into a recorded regression. qa-test-planner had Write on its disallowed list while its role is producing test plan documents; the pre-release scanner scanned bkit instead of the caller's project. 78 new TC across three regression suites, suite 5355 TC 0 FAIL, live hooks 23/23.",
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Dismissed after review: Sets world-writable permissions on a root path (chmod 777 /)
    • Line 36 on GitHub
  37. "author": {
  38. "name": "DubDubDub Corp.",
  39. "email": "biz@ww-w.ai"
  40. },
  41. "version": "2.1.41",
  42. "repository": "https://github.com/ww-w-ai/bkit-claude-code",
  43. "source": {
  44. "source": "url",
  45. "url": "https://github.com/ww-w-ai/bkit-claude-code.git"
  46. },
  47. "category": "development",
  48. "keywords": [
  49. "vibecoding",
  50. "pdca",
  51. "development-pipeline",
  52. "ai-native",
  53. "agentic",
  54. "agent",
  55. "automation",
  56. "workflow",
  57. "fullstack",
  58. "multilingual",
  59. "baas",
  60. "enterprise"
  61. ]
  62. }
  63. ]
  64. }
README.md · README · 319 lines · 1 finding marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # bkit — AI Native Development OS
  2. > A Claude Code plugin that verifies AI-generated code against its own design specs.
  3. **Three commands. Anyone — even someone vibe-coding for the first time — can ship robust, production-quality software.** bkit turns Claude Code into a *Context Engineering system*: 44 skills, 34 specialist agents, 11 quality gates, and a memory that survives across sessions deliver the right context to the AI at the right moment, so you don't have to know prompts, commands, or PDCA to get high-quality results.
  4. [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
  5. [![Claude Code](https://img.shields.io/badge/Claude%20Code-v2.1.143+-purple.svg)](https://code.claude.com)
  6. [![Version](https://img.shields.io/badge/Version-2.1.41-green.svg)](CHANGELOG.md)
  7. [![Author](https://img.shields.io/badge/Author-DubDubDub%20Corp.-orange.svg)](https://ww-w.ai)
  8. > **Requirement**: bkit requires Claude Code **v2.1.143 or later** (the strict plugin-manifest path recognizes the official `displayName` field only from v2.1.143). On older Claude Code you will see `Validation errors: Unrecognized key: "displayName"` during `claude plugin install`. Run `npm install -g @anthropic-ai/claude-code@latest` to upgrade, or see [`docs/06-guide/cc-compatibility.guide.md`](docs/06-guide/cc-compatibility.guide.md).
  9. ---
  10. ## Who bkit is for
  11. | You are… | bkit gives you |
  12. |---|---|
  13. | 🌱 **First-time vibe coder** — you describe what you want and AI codes for you, but you don't yet know how to tell if the result is correct | A safety net. AI proposes, bkit measures the result against its own design spec, and **auto-repairs** the gap when it drifts. You can ship without becoming a senior engineer first. |
  14. | 👤 **Solo developer / indie builder** | A team-in-a-box. `/pdca team` spawns 4–6 specialist agents in parallel — frontend, backend, QA, security — orchestrated by an AI tech lead. |
  15. | 👥 **Team lead planning a release** | Sprint Management. `/sprint master-plan` splits your release into **context-budgeted sprints** so a single Claude Code session can finish each one without running out of memory, and resumes after any session interruption. |
  16. | 🌐 **Non-English speaker** | 8-language auto-detection. Type *"로그인 기능 만들어줘"* or *"作成新功能"* and bkit picks the right command for you. |
  17. ## What you'll achieve with bkit
  18. > **The promise**: anyone — including non-developers — can build **robust, production-quality software** by using bkit. bkit replaces the senior engineer's intuition with a workflow.
  19. | Without bkit | With bkit |
  20. |---|---|
  21. | AI gives you plausible code; you have no way to know if it really matches what you asked for | `gap-detector` measures **match rate** between your design spec and the generated code. Below 90 % → bkit auto-repairs (up to 5 cycles). |
  22. | You only spot drift at PR review — by then the cleanup is expensive | 11 **Quality Gates** halt the workflow before drift compounds (match rate, critical issues, convention, test coverage, security, dataFlow integrity, …) |
  23. | Long projects exceed Claude Code's session window and you lose context | bkit splits the project into **context-budgeted Sprints** (≤ 75 K tokens each); memory + Task Management lets any session resume where the last one stopped |
  24. | You don't know which command, agent, or skill to use | **8-language auto-trigger** + intent-router pick the right skill / agent automatically. You just describe what you want. |
  25. | AI ships code, you ship hope; nobody documents what changed | **Docs = Code** philosophy: every feature produces a PRD + plan + design + analysis + completion report. The history is the audit trail. |
  26. ## The 4-step experience
  27. This is the canonical workflow when you use bkit. You describe a release; bkit handles the rest.
  28. ```mermaid
  29. flowchart TB
  30. You(["You: describe the release"])
  31. You --> S1["Step 1<br/>/sprint master-plan my-release<br/>--features auth, billing, reports"]
  32. S1 --> Auto1["bkit auto-action<br/>• sprint-master-planner agent investigates code + web in depth<br/>• Splits features into context-budgeted Sprints (&le; 75K tokens each)<br/>• Writes the master plan with Context Anchor"]
  33. Auto1 --> S2["Step 2<br/>You approve the plan"]
  34. S2 --> Auto2["bkit auto-action<br/>• Every sprint registered in Task Management<br/>• Memory saved — survives session clear"]
  35. Auto2 --> S3["Step 3<br/>/sprint start sprint-1"]
  36. S3 --> Auto3["bkit auto-action — full PDCA per feature:<br/>PRD/Plan → Design → Do → Iterate (target 100%, gated) →<br/>QA (gated) → Report. /pdca pm, /pdca team, /pdca qa as needed."]
  37. Auto3 --> Gate{"All quality<br/>gates pass?"}
  38. Gate -- "no, auto-fix" --> Repair["pdca-iterator self-repair<br/>(max 5 cycles)"]
  39. Repair --> Gate
  40. Gate -- "yes" --> Done(["Release-ready code + docs"])
  41. Ctrl["Step 4<br/>/control level 0..4"] -.->|"set how much<br/>runs unattended"| Auto1
  42. Ctrl -.->|"applies"| Auto3
  43. style You fill:#e3f2fd
  44. style S1 fill:#fff3e0
  45. style S2 fill:#fff8e1
  46. style S3 fill:#fff3e0
  47. style Auto3 fill:#fce4ec
  48. style Repair fill:#ffe0b2
  49. style Done fill:#c8e6c9
  50. style Ctrl fill:#f3e5f5
  51. ```
  52. ### Step 1 — Plan the release in depth
  53. You type: `/sprint master-plan my-release --features auth, billing, reports`.
  54. bkit's `sprint-master-planner` agent **investigates carefully — not quickly**. Depending on what you're building, it reads your existing code base in depth or researches the web, then writes a master plan. Critically, it splits your features into **context-budgeted Sprints**: each sprint is sized so a single Claude Code session can finish it without overflowing the context window (the default is ≤ 75 K tokens per sprint, dependency-aware via Kahn topological sort + greedy bin-packing).
  55. You can also call specialist agents directly when you want more depth: `/pdca pm` runs 4 product-management agents in parallel with 43 frameworks; `/pdca team` spawns a multi-specialist implementation team; `/pdca qa` runs a 5-agent QA team.
  56. ### Step 2 — Approve, register, remember
  57. You read the master plan. When you approve, bkit registers **every sprint** in its Task Management System with the right dependency order (Kahn-topologically sorted). It also writes to memory.
  58. This means: if your laptop crashes, your session clears, or you start a new Claude Code session next week — **bkit picks up exactly where you stopped**. The plan and progress are durable.
  59. ### Step 3 — Auto-run each sprint through PDCA
  60. You type: `/sprint start sprint-1`.
  61. bkit runs the 8-phase Sprint lifecycle (prd → plan → design → do → iterate → qa → report → archived). Inside the **do** phase, bkit runs the full **PDCA loop once per feature**:
  62. | Phase | What runs | Output |
  63. |---|---|---|
  64. | **PRD / Plan** | `pm-lead` orchestrates 4 PM agents (discovery, strategy, research, prd) with 43 frameworks | Comprehensive PRD + plan with Context Anchor |
  65. | **Design** | `cto-lead` proposes 3 architecture options; you pick one (the only required user input) | Detailed design doc |
  66. | **Do** | `/pdca team` spawns 4–6 specialist agents in parallel (developer, qa, frontend, backend, security, architect) | Working code |
  67. | **Iterate** | Target **100 % match** between design and code. `gap-detector` measures; `pdca-iterator` self-repairs until quality gate M1 (matchRate ≥ 90 %) passes. Max 5 cycles. | Repaired code + iteration report |
  68. | **QA** | `qa-lead` runs 4 QA agents through L1–L5 tests + dataFlow integrity (S1 gate, 7-layer hop check) | QA report |
  69. | **Report** | `report-generator` writes the completion report | Final report with KPI + lessons learned |
  70. **Every phase is gated by quality thresholds**. If anything fails — match rate too low, critical issue found, dataFlow broken — bkit pauses and tells you why. You don't have to remember to verify; verification is automatic.
  71. ### Step 4 — Govern with one dial
  72. `/control level N` is the single autonomy knob. It decides how far the orchestrator runs before stopping. **The same dial controls both Sprint and PDCA** — no second knob to manage.
  73. | Level | What it means |
  74. |---|---|
  75. | **L0 Manual** | Ask me at every phase. Best for your first sprint — inspect each output. |
  76. | **L2 Semi-Auto** (default) | Plan/Design/Do auto; ask me on QA and Report. |
  77. | **L4 Full-Auto** | Wake me when the sprint is done. Pauses only on a quality gate failure or one of 4 auto-pause triggers. |
  78. L1 (Guided) and L3 (Auto) sit between. bkit also computes a **Trust Score (0–100)** from your track record and can recommend a level — but you stay in charge.
  79. ## How the bkit author actually uses bkit
  80. The 4-step experience above is the canonical flow. Here's the concrete recipe the person who built bkit uses every day — **two steps** — so you can copy it without needing to understand the full machinery underneath.
  81. ### Step A — Use Claude Code as a thinking amplifier *before* the master plan
  82. The master plan is the single most important artifact in a sprint. Garbage in, garbage out. So **don't write it alone, and don't let bkit write it cold either.**
  83. 1. Open a fresh Claude Code session.
  84. 2. Talk through the release in plain language — what's the goal, who is it for, what could go wrong, what depends on what, what's still unknown? Let Claude Code push back.
  85. 3. Have it investigate — read your repo, search the web, surface edge cases you hadn't considered.
  86. 4. *Then* run `/sprint master-plan my-release --features ...`. By the time you do, your context is already saturated; the master plan reflects what you really meant, not a generic template.
  87. This is what **Context Engineering** looks like in practice: you don't tune the perfect prompt — you saturate the context first, then let bkit synthesise.
  88. ### Step B — Hand the rest to Trust Level 4
  89. Once you approve the master plan, the keyboard goes quiet until the final report lands. The bkit author picks one of two patterns based on release size:
  90. | Release size | What you type | What happens |
  91. |---|---|---|
  92. | **Small–medium** — a few related features, single context budget | `/control level 4`, then `/sprint start <project>` once | bkit runs every sprint and every PDCA phase straight through to `archived`. You read the final report. |
  93. | **Large** — many sprints, large total token budget, or cross-sprint dependencies | `/control level 4`, then `/sprint start <sprint-id>` per sprint in dependency order | Each sprint runs full-auto. You skim the sprint report before launching the next sprint — a natural checkpoint between context windows. |
  94. **Trust Level 4 is not "no safety"**. The 11 quality gates and 4 auto-pause triggers still fire. bkit halts and asks for you only when a measurable rule fails. The dial removes the *unnecessary* pauses, not the necessary ones.
  95. **The outcome, repeatable**: AI plans, designs, codes, self-verifies, self-repairs, tests, and writes the completion report. You provide intent — and the final ship/no-ship decision. Nothing else.
  96. ## The three commands
  97. | Command | When to use | What it spawns | Output |
  98. |---|---|---|---|
  99. | **`/sprint`** | Multi-feature release (quarter, milestone, multiple linked features) | `sprint-master-planner`, `sprint-orchestrator`, `sprint-qa-flow`, `sprint-report-writer` | Master plan + 8-phase per sprint + cumulative report |
  100. | **`/pdca`** | A single feature (or runs inside a sprint per feature) | `pm-lead`, `cto-lead`, `gap-detector`, `pdca-iterator`, `qa-lead`, `report-generator` (any of 34 agents) | PRD + plan + design + code + analysis + report |
  101. | **`/control`** | Anytime — set autonomy | — | Updates Trust Level scope; affects both `/sprint` and `/pdca` |
  102. ## How bkit closes the AI-coding gap — Context Engineering
  103. bkit is more than commands. It is a **Context Engineering system** that solves the root cause of AI-coding failures: the AI doesn't have the right context.
  104. | The AI coding problem | bkit's Context Engineering answer |
  105. |---|---|
  106. | AI hallucinates because it doesn't know your conventions | 44 skills (PDCA, Sprint, PM frameworks, …) auto-injected based on intent |
  107. | AI loses focus as the session grows | Memory + Task Management resumes across sessions; Sprints are context-budgeted |
  108. | AI ships code that drifts from the spec | 11 Quality Gates + `gap-detector` measurement + `pdca-iterator` auto-repair |
  109. | You only catch bugs at PR review | Phase-by-phase gating: drift is caught at every transition, not at the end |
  110. | You need to remember the right command | 8-language auto-trigger + intent-router; type *"login 만들어줘"* or *"build login"* and bkit picks the path |
  111. | AI sessions are ephemeral; no audit trail | Audit log + Token Ledger + `Docs = Code` philosophy: every decision is on disk |
  112. ## bkit's three philosophies (from [`bkit-system/philosophy/core-mission.md`](bkit-system/philosophy/core-mission.md))
  113. | Principle | What it means for you |
  114. |---|---|
  115. | **Automation First** | You don't need to know PDCA, Sprint, or any command. Type what you want; bkit picks the right workflow. The state machine + workflow engine drive the rest. |
  116. | **No Guessing** | If bkit isn't sure, it checks the docs. If still unsure, it asks you. It never makes up an answer. `gap-detector`, `design-validator`, and 11 quality gates enforce this. |
  117. | **Docs = Code** | Every feature produces docs (PRD + plan + design + analysis + report). The docs are the contract; bkit verifies that the code matches. `scripts/docs-code-sync.js` enforces 0 drift in CI. |
  118. ## Quick start
  119. ```bash
  120. # 1. Install (one time)
  121. claude plugin install bkit
  122. # 2. Enable parallel team execution (optional, recommended)
  123. export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
  124. # 3. Your very first run — single feature
  125. /pdca pm my-feature # Describes what you want; bkit handles the rest
  126. # 4. When you're ready for a multi-feature release
  127. /sprint master-plan my-release --name "Q2 Launch" --features auth, billing, reports
  128. # (You approve the plan)
  129. /sprint start my-release-s1
  130. ```
  131. Recommended Claude Code runtime: **v2.1.220** (bkit explicitly handles v2.1.218's `context: fork` background-by-default change and v2.1.219's nested-subagent depth-3 default; Claude 5 alias resolution — `sonnet` → Sonnet 5 needs ≥ v2.1.197). Model floor: **v2.1.170+** required by the 6 Fable-pinned agents (below it they fail to spawn; bkit shows a SessionStart advisory with a workaround). Install minimum **v2.1.143**; runtime minimum **v2.1.78**.
  132. **On Claude Code v2.1.232 and later**, fork mode is on by default in interactive
  133. sessions: a subagent's result arrives as a notification on a *later* turn, and the
  134. Agent tool no longer accepts `run_in_background`. bkit's skills are unaffected.
  135. Sprint gates that measure through a subagent will report **"not measured"** rather
  136. than a score, and name the cause — a missing number, never a wrong one. Set
  137. `CLAUDE_CODE_FORK_SUBAGENT=0` to get in-turn results back. bkit shows this once at
  138. SessionStart and does not block. Verified against v2.1.232; Breaking changes 0
  139. across v2.1.228–v2.1.232 (171 consecutive compatible releases).
  140. ## Quality gates — the safety net explained
  141. A "quality gate" is a hard stop that won't let the workflow advance until a measurable condition is true. bkit ships 11 of them. The ones that matter most for new users:
  142. | Gate | What it measures | If it fails |
  143. |---|---|---|
  144. | **M1 matchRate** | How much of your design actually appears in the code, 0–100 % | Below 90 % → `pdca-iterator` automatically rewrites the code (up to 5 cycles) |
  145. | **M3 critical issues** | Security or correctness bugs flagged by `code-analyzer` | Any critical → workflow pauses, you decide |
  146. | **S1 dataFlow integrity** | 7-layer check: UI → Client → API → Validation → DB → Response → Client → UI | Below 85 % → 7 hops re-verified one by one |
  147. | **qa gate** | QA pass rate ≥ 95 %, zero critical findings, zero runtime errors — from what `qa-lead` actually measured | Below 95 % → back to `act` for fixes, then QA re-runs (v2.1.38: the return path and its retry ceiling both work) |
  148. Full M1–M10 + S1 catalog in [README-FULL.md §5](README-FULL.md#5-quality-gates--self-repair).
  149. ## Architecture at a glance
  150. 44 skills · 34 agents · 21 hook events / 24 blocks across 28 handlers · 2 MCP servers (19 tools) · 200 lib modules across 22 subdirs · 59 scripts · 40 templates · 385 test files (5,355 test cases). Clean Architecture 4-Layer · Defense-in-Depth 4-Layer · Invocation Contract L1–L6, where L6 is host integration: a real `claude -p --plugin-dir` run whose recorded evidence CI checks against the shipped `hooks.json`.
  151. Agents run on a 4-tier role-based model matrix: **fable** (long-horizon orchestration — leads), **opus** (deep reasoning, security & high-frequency PDCA verifiers), **sonnet** (implementers), **haiku** (monitors). The repeated Check/iterate verifiers (gap-detector, design-validator, pdca-iterator) run on Opus 4.8 — strong verification at half Fable's cost.
  152. Full architecture deep-dive: [README-FULL.md §9](README-FULL.md#9-architecture).
  153. ## Documentation
  154. | Path | What's there |
  155. |---|---|
  156. | [README-FULL.md](README-FULL.md) | Full command reference, deep workflow internals, agent teams, architecture, Skill Evals |
  157. | [CHANGELOG.md](CHANGELOG.md) | Release history (single source of truth — latest release: v2.1.41) |
  158. | [CUSTOMIZATION-GUIDE.md](CUSTOMIZATION-GUIDE.md) | Override any bkit component in your `.claude/` directory |
  159. | [AI-NATIVE-DEVELOPMENT.md](AI-NATIVE-DEVELOPMENT.md) | The 6 AI-Native principles and how bkit implements them |
  160. | [`bkit-system/philosophy/`](bkit-system/philosophy/) | Core mission, Context Engineering, PDCA methodology, AI-Native principles |
  161. | [`docs/06-guide/sprint-management.guide.md`](docs/06-guide/sprint-management.guide.md) | Sprint Management deep-dive (English) |
  162. | [`docs/06-guide/sprint-migration.guide.md`](docs/06-guide/sprint-migration.guide.md) | PDCA ↔ Sprint migration mapping (English) |
  163. ## 🌟 Real User Hall of Fame
  164. bkit's quality is measured by how well it responds to real users running
  165. bkit in production on their own projects. This section recognizes
  166. **external dogfooders** whose precise bug reports + reproduction scripts
  167. have been absorbed directly into bkit's regression test suite
  168. (`test/e2e/external-dogfood/`).
  169. ### v2.1.19 (2026-05-30 — first entry)
  170. - **[@pruge (James Kim)](https://github.com/pruge)** — `dandi-village-ledger`
  171. project. 10 GitHub issues over 1.5 days (#92–#107) driving bkit v2.1.17,
  172. v2.1.18 closes + the entire v2.1.19 Quality Maturation Sprint. 5 reproduction
  173. scenarios absorbed as E2E tests at `test/e2e/external-dogfood/dandi-*.test.js`.
  174. See [`docs/external-dogfooders/pruge.md`](docs/external-dogfooders/pruge.md)
  175. for the full contribution archive. **Thank you for trusting bkit with
  176. your production sprint.** 🙏
  177. ### v2.1.20 (2026-05-26 — second entry, first-follower effect validated)
  178. - **[@bj (정병진)](https://github.com/ww-w-ai/bkit-claude-code/issues)** —
  179. bkit v2.1.14 install incident (2026-05-26, `Validation errors: : Unrecognized
  180. key: "displayName"`). Precise error message + cache path + Cursor IDE
  181. environment metadata sharing drove the entire **v2.1.20 Marketplace
  182. Recovery Sprint** (14 features / 3 sub-sprints / 3 new ENH 321/322/323 /
  183. 1 new ADR 0011 Plugin Manifest Schema Compliance Policy). Reproduction
  184. absorbed at `test/e2e/external-dogfood/cc-min-version.test.js` (5 TC,
  185. Lifecycle Stage 4 Regression Lock achieved). Triggered ADR 0006 §
  186. Empirical Validation Gate recovery (~30-day wire delay closed). See
  187. [`docs/external-dogfooders/bj.md`](docs/external-dogfooders/bj.md) for the
  188. full contribution archive. **Thank you for sharing the precise error
  189. message that scoped the entire sprint correctly.** 🙏
  190. ### v2.1.36 (2026-08-12 — third entry)
  191. - **[@Sinclair-Seo](https://github.com/ww-w-ai/bkit-claude-code/issues/148)**
  192. — issue #148. Three Destructive Detector rules were refusing commands that are
  193. read-only or narrowly scoped. The report came with a 12-case reproduction
  194. harness that included **negative controls**, and the note that makes them
  195. matter: a "0 false positives" reading proves nothing unless genuinely
  196. destructive commands are still caught in the same run — a point they made after
  197. first measuring a bogus green from a one-argument `detect()` call.
  198. It also named the real cost. A PreToolUse block asks a question, and an
  199. unattended run has nobody to answer it, so the agent **stalls silently instead
  200. of failing** — ~15 minutes of dead time, twice in one sprint, caught only
  201. because an idle-stall monitor was attached.
  202. Auditing all 16 rules on the strength of that report measured the defect class
  203. at roughly 3× what was filed, and found the same root cause producing **false
  204. negatives**: `chmod 777 / ; ls` was detected by nothing at all. The harness is
    • Dismissed after review: Sets world-writable permissions on a root path (chmod 777 /)
    • Line 279 on GitHub
  205. absorbed at
  206. `test/e2e/external-dogfood/sinclair-seo-148-guardrail-precision.test.js`
  207. (Lifecycle Stage 4 Regression Lock). **Thank you for the negative controls —
  208. they caught a regression we introduced while fixing this.** 🙏
  209. ## 🚀 bkit Early Adopter Program
  210. > Running bkit on a non-trivial production project and willing to file
  211. > detailed bug reports with reproductions makes you part of bkit's
  212. > quality system, not just a bug reporter.
  213. Established **v2.1.19** (master plan §15.4 DA-1~DA-4, ENH-318 차별화 7/7).
  214. **Benefits**:
  215. - 🏆 Public recognition in this README + dedicated archive
  216. - 🔒 Your reproduction scripts become permanent E2E regression tests
  217. - 📊 Your activity directly powers bkit's Trust Score
  218. (`externalDogfoodFeedbackResponseRate` component, weight 0.05)
  219. - 📝 CHANGELOG attribution on every release where your scenarios
  220. were absorbed
  221. - 🤝 Direct line to bkit maintainers — priority issue triage,
  222. reproduction-script-first response
  223. **How to join**: file your first detailed issue at
  224. [bkit-claude-code/issues](https://github.com/ww-w-ai/bkit-claude-code/issues)
  225. with bkit version, reproduction steps, expected vs actual behavior,
  226. and file:line references. See
  227. [`docs/external-dogfooders/_README.md`](docs/external-dogfooders/_README.md)
  228. for the full 5-stage User-Feedback Lifecycle and program structure.
  229. > **DA-4 acquisition goal**: by v2.1.20 (30 days post-v2.1.19 GA),
  230. > measure dogfooder population. **DA-4 status (v2.1.20)**: **N=2 confirmed**
  231. > (@pruge + @bj) — first-follower effect validated. v2.1.21+ continues
  232. > active outreach (CC marketplace narrative, community engagement) to
  233. > grow N≥3.
  234. ## License
  235. Apache 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE). DubDubDub Corp. · `kay@popupstudio.ai`
lib/control/destructive-detector.js · Bundled script · 1,572 lines · 9 findings marked
  1. #!/usr/bin/env node
  2. /**
  3. * Destructive Operation Detector (FR-10)
  4. * Detects destructive operations before execution using 8 guardrail rules.
  5. *
  6. * Rules G-001 to G-008 cover recursive delete, force push, hard reset,
  7. * protected branch modification, env file modification, secret key access,
  8. * mass file deletion, and root directory operations.
  9. *
  10. * @version 2.1.10
  11. * @module lib/control/destructive-detector
  12. */
  13. /**
  14. * @typedef {Object} GuardrailRule
  15. * @property {string} id - Rule identifier (G-001 to G-008)
  16. * @property {string} name - Human-readable rule name
  17. * @property {RegExp} pattern - Detection pattern
  18. * @property {'critical'|'high'|'medium'} severity - Rule severity
  19. * @property {'deny'|'ask'|'allow'} defaultAction - Default action when triggered
  20. */
  21. /**
  22. * @typedef {Object} DetectionResult
  23. * @property {boolean} detected - Whether a destructive operation was detected
  24. * @property {Array<{id: string, name: string, severity: string, pattern: string}>} rules - Matched rules
  25. * @property {number} confidence - Detection confidence 0-1
  26. */
  27. /**
  28. * Guardrail rules for destructive operation detection
  29. * @type {GuardrailRule[]}
  30. */
  31. const GUARDRAIL_RULES = [
  32. {
  33. id: 'G-001',
  34. name: 'Recursive delete',
  35. pattern: /\b(rm\s+-(r|rf|fr)\b|rm\s+--recursive|rimraf|shutil\.rmtree|Remove-Item\s+-Recurse)/i,
  36. severity: 'critical',
  37. defaultAction: 'deny',
  38. /*
  39. * v2.1.34 (D9) — severity depends on WHAT is being deleted.
  40. *
  41. * This rule matched `rm -r` regardless of target, so deleting a scoped
  42. * temporary directory was refused exactly as hard as deleting `/`. The
  43. * refusal then advised "Scope the command to a specific path instead of a
  44. * broad or root target" — advice the rule made impossible to act on, since
  45. * scoping changed nothing. Guidance a user cannot follow is how a guard
  46. * teaches people to switch it off, and both cases below were hit doing
  47. * ordinary work on this release.
  48. *
  49. * A dangerous target still denies. A specific one asks.
  50. */
  51. severityFor: (text) => (deleteTargetIsBroad(text) ? 'critical' : 'high'),
  52. },
  53. {
  54. id: 'G-002',
  55. name: 'Force push',
  56. pattern: /\bgit\s+push\s+.*(-f|--force|--force-with-lease)\b/i,
  57. severity: 'critical',
  58. defaultAction: 'deny',
  59. // ENH-462 (v2.1.36): grade by target. A protected branch denies; a topic
  60. // branch asks. See pushTargetIsProtected().
  61. severityFor: (text) => (pushTargetIsProtected(text) ? 'critical' : 'high'),
  62. },
  63. {
  64. id: 'G-003',
  65. name: 'Hard reset',
  66. pattern: /\bgit\s+reset\s+--hard\b/i,
  67. severity: 'high',
  68. defaultAction: 'ask'
  69. },
  70. {
  71. id: 'G-004',
  72. name: 'Protected branch modification',
  73. /*
  74. * ENH-442 (v2.1.36) — `(?!-)` excludes hyphenated sub-commands.
  75. *
  76. * `\b` is satisfied by a hyphen, so `merge` matched `merge-base` and the
  77. * read-only `git merge-base origin/master HEAD` was graded as a protected
  78. * branch modification. Reported in issue #148; `merge-tree` and `merge-file`
  79. * were measured to have the same defect and are covered by the same guard.
  80. *
  81. * The hyphenated spellings are git's plumbing (`merge-base`, `merge-tree`,
  82. * `merge-file`, `commit-tree`) — they compute and report, they do not move a
  83. * branch. The porcelain commands that DO move a branch are exactly the
  84. * un-hyphenated four, so excluding the hyphen form is the whole fix.
  85. */
  86. pattern: /\bgit\s+(commit|merge|rebase|push)(?!-)\b.*\b(main|master|release|production)\b/i,
  87. severity: 'high',
  88. defaultAction: 'ask'
  89. },
  90. {
  91. id: 'G-005',
  92. name: 'Environment file modification',
  93. /*
  94. * ENH-477 (v2.1.37) — this rule had never fired for the filename it names.
  95. *
  96. * The old pattern was /\b(\.env|\.env\.\w+)\b/i. `\b` is a transition
  97. * between a word and a non-word character, and the character before a
  98. * leading `.` is a space, a `/`, or the start of the string — all non-word.
  99. * So `\b\.env` could not match `.env` as it is actually written. Measured
  100. * against the shipped rule:
  101. *
  102. * cat .env -> no match git add -f .env.production -> no match
  103. * ./.env, foo/.env -> no match myapp.env -> MATCH
  104. *
  105. * It matched only when a word character preceded the dot, which is close to
  106. * never for a real environment file. Same class as ENH-263 and ENH-469:
  107. * shipped, asserted by tests that checked the rule existed, and never once
  108. * triggered by the thing it was written for.
  109. *
  110. * It was wrong in BOTH directions at once, which is why neither showed up as
  111. * a complaint. Measured against the shipped rule:
  112. *
  113. * .env, cat .env, ./.env -> no match (blind to the secret store)
  114. * process.env.NODE_ENV -> MATCH (ordinary JavaScript)
  115. * import.meta.env.VITE_KEY -> MATCH (ordinary JavaScript)
  116. * config.env.production -> MATCH (correct)
  117. *
  118. * v2.1.36's false-positive audit did not catch the second half because its
  119. * corpus was Bash commands, and `process.env.X` arrives through `content` on
  120. * an Edit. Editing any file that reads an environment variable prompted.
  121. *
  122. * The blast radius of the false NEGATIVE was one surface: `Write`/`Edit` to
  123. * `.env` is guarded by the `.env*` deny glob in scope-limiter.js:34 and that
  124. * one works. What went unguarded was the Bash surface this detector owns.
  125. *
  126. * The replacement drops `\b` — which cannot express "start of a filename"
  127. * when the filename starts with a dot — and matches the whole dotted chain,
  128. * so both spellings are covered: the leading-dot file (`.env.production`)
  129. * and the prefixed one (`config.env.production`, which DT-005 asserts).
  130. * `(?![\w-])` keeps `.envrc` out; the two suppressors below keep templates
  131. * and runtime env access out.
  132. */
  133. pattern: /\.env(?:\.[\w-]+)*(?![\w-])/i,
  134. severity: 'high',
  135. defaultAction: 'ask',
  136. suppressIf: isBenignEnvMention,
  137. },
  138. {
  139. id: 'G-006',
  140. name: 'Secret key access',
  141. pattern: /\b[\w/.-]+(\.key|\.pem|\.p12|\.pfx|\.jks|\.keystore)\b/i,
  142. severity: 'high',
  143. defaultAction: 'ask',
  144. // ENH-445 (v2.1.36): listing a key file is not accessing it. See
  145. // isMetadataOnlyAccess(). Readers and copiers are unaffected.
  146. suppressIf: isMetadataOnlyAccess,
  147. },
  148. {
  149. id: 'G-007',
  150. name: 'Mass file deletion',
  151. pattern: /\b(rm|del|delete|remove)\b.*(\s+\S+){5,}/i,
  152. severity: 'medium',
  153. defaultAction: 'ask',
  154. // ENH-447 (v2.1.36): SQL's `DELETE FROM` is not a filesystem deletion. The
  155. // SQL rules own that language; G-010b still catches an unscoped DELETE.
  156. // ENH-470 (v2.1.37): and the verb has to be the command, not just a word that
  157. // appears in it. See isNotACommandLevelDelete().
  158. suppressIf: (text) => looksLikeSqlStatement(text) || isNotACommandLevelDelete(text),
  159. },
  160. {
  161. id: 'G-008',
  162. name: 'Root directory operations',
  163. pattern: /\b(rm|mv|cp|chmod|chown)\s+.*\s+\/\s*$/,
  164. severity: 'critical',
  165. defaultAction: 'deny'
  166. },
  167. // v2.1.12 Sprint E-1 (defect #19 fix): DB destruction patterns previously
  168. // were not matched (e.g. `DROP TABLE users` returned isDestructive=false).
  169. // Added SQL DDL/DML destruction + NoSQL drop patterns.
  170. {
  171. id: 'G-009',
  172. name: 'SQL table/database drop',
  173. // matches DROP TABLE / DROP DATABASE / DROP SCHEMA / DROP INDEX / DROP VIEW
  174. pattern: /\bDROP\s+(TABLE|DATABASE|SCHEMA|INDEX|VIEW|TRIGGER|PROCEDURE|FUNCTION)\b/i,
  175. severity: 'critical',
  176. defaultAction: 'deny',
  177. // ENH-440: SQL statements end at `;`, not at a newline. See splitCommandSegments().
  178. segmentOn: 'sql'
  179. },
  180. {
  181. id: 'G-010',
  182. name: 'SQL TRUNCATE / ALTER DROP COLUMN',
  183. pattern: /\b(TRUNCATE\s+TABLE\b|ALTER\s+TABLE\s+\S+\s+DROP\s+COLUMN)\b/i,
  184. severity: 'critical',
  185. defaultAction: 'deny',
  186. segmentOn: 'sql'
  187. },
  188. {
  189. id: 'G-010b',
  190. name: 'DELETE without WHERE clause',
  191. /*
  192. * Matches `DELETE FROM <ident>` only when no WHERE clause follows it.
  193. *
  194. * ENH-446 (v2.1.36) — the lookahead is unchanged, but it is now evaluated
  195. * against ONE statement instead of the whole input. Previously a WHERE
  196. * belonging to an unrelated later statement suppressed the match, so an
  197. * unscoped DELETE went undetected. Measured on v2.1.35:
  198. *
  199. * DELETE FROM audit_log; SELECT 1 FROM t WHERE x=1 -> not detected
  200. * DELETE FROM audit_log -- WHERE -> not detected
  201. *
  202. * Both now segment at `;` (and the comment case matches within its own
  203. * statement), so the lookahead only sees the DELETE's own clause.
  204. */
  205. pattern: /\bDELETE\s+FROM\s+[\w.]+(?![\s\S]*\bWHERE\b)/i,
  206. severity: 'critical',
  207. defaultAction: 'deny',
  208. segmentOn: 'sql'
  209. },
  210. {
  211. id: 'G-011',
  212. name: 'NoSQL collection drop',
  213. // MongoDB `db.collection.drop()` / `dropDatabase()` / Redis FLUSHALL/FLUSHDB
  214. pattern: /\b(db\.\w+\.drop\s*\(\s*\)|dropDatabase\s*\(\s*\)|FLUSHALL\b|FLUSHDB\b)/i,
  215. severity: 'critical',
  216. defaultAction: 'deny',
  217. segmentOn: 'sql'
  218. },
  219. /*
  220. * G-012 ~ G-015 (v2.1.34) — bypasses proven against the shipped v2.1.33 rules.
  221. *
  222. * The rules above are a denylist of literal shapes, so they hold only for the
  223. * spellings someone thought to write down. Probing the live PreToolUse handler
  224. * showed which spellings were missing: the recursive-delete rules caught the
  225. * plain form, a variable-indirected form, an xargs form and `shutil.rmtree`,
  226. * but these four went straight through with `decision: allow`.
  227. *
  228. * A denylist is never complete, and these additions do not make it so. They
  229. * close the specific holes that were demonstrated rather than imagined, and
  230. * each ships with a regression test in
  231. * test/regression/destructive-bypass.test.js. The honest framing of this
  232. * subsystem is a known-pattern guard, not a complete defense — the docs now
  233. * say that.
  234. */
  235. {
  236. id: 'G-012',
  237. name: 'Obfuscated command execution',
  238. // `eval "$(echo <base64> | base64 -d)"`, `... | base64 --decode | sh`, and
    • Note: Quoted as data in code: Mentions decoding base64 into a shell (no payload shown)
    • Line 241 on GitHub
  239. // the `bash <(...)` process-substitution form. The payload is unknowable at
  240. // match time, which is exactly why executing it cannot be waved through.
  241. pattern: /\b(base64\s+(-d|-D|--decode)\b[\s\S]*\|\s*(ba)?sh\b|eval\s+"?\$\(|(ba)?sh\s+<\(|\|\s*eval\b)/i,
  242. severity: 'critical',
  243. defaultAction: 'deny'
  244. },
  245. {
  246. id: 'G-013',
  247. name: 'Find-based mass deletion',
  248. // `find / -delete` and `find . -exec rm {} \;` delete recursively without
  249. // ever containing the token `rm -rf`, so G-001 and G-007 both miss them.
  250. pattern: /\bfind\s+[\s\S]*?(-delete\b|-exec\s+(rm|unlink|shred)\b|-execdir\s+(rm|unlink|shred)\b|\|\s*xargs\s+(-\S+\s+)*(rm|unlink|shred)\b)/i,
  251. severity: 'critical',
  252. defaultAction: 'deny',
  253. // ENH-443 (v2.1.36): grade by target, matching G-001. A broad target still
  254. // denies; a scoped one asks. See findTargetIsBroad() for the measured
  255. // asymmetry this removes.
  256. severityFor: (text) => (findTargetIsBroad(text) ? 'critical' : 'high'),
  257. },
  258. {
  259. id: 'G-014',
  260. name: 'Raw device or disk write',
  261. // `dd of=/dev/disk0`, `mkfs`, `> /dev/sda`. Destroys a volume outright and
  262. // shares no token with any delete rule.
  263. pattern: /\b(dd\s+[\s\S]*\bof=\s*\/dev\/|mkfs(\.\w+)?\s|>\s*\/dev\/(disk|sd|nvme|hd)\w*|\bwipefs\b|\bblkdiscard\b)/i,
  264. severity: 'critical',
  265. defaultAction: 'deny'
  266. },
  267. {
  268. id: 'G-015',
  269. name: 'Remote script piped to a shell',
  270. // `curl … | sh`, `wget -O- … | bash`. Executes code nobody in this session
  271. // has read, from a host nobody has vetted.
  272. pattern: /\b(curl|wget|fetch)\b[\s\S]*\|\s*(sudo\s+)?(ba|z|k|da)?sh\b/i,
  273. severity: 'critical',
  274. defaultAction: 'deny'
  275. },
  276. /*
  277. * G-016 ~ G-018 (v2.1.37, ENH-477) — git commands that destroy work, measured
  278. * against the shipped v2.1.36 rules and found to pass unguarded.
  279. *
  280. * The trigger was Claude Code v2.1.229 removing auto-approval from 56 git/gh
  281. * spellings in `/commit-push-pr`. That list is NOT the model for these rules,
  282. * and copying it would have been a mistake: it carves dangerous commands out
  283. * of one skill's auto-approval, whereas this detector asks a human about
  284. * destruction anywhere. The two answer different questions.
  285. *
  286. * So each candidate was graded by one test — does it destroy work that cannot
  287. * be recovered? Of the four the analysis named, two failed that test and are
  288. * deliberately NOT here:
  289. *
  290. * --amend rewrites the last commit, and the original stays in the
  291. * reflog. The dangerous half is publishing it, which needs a
  292. * force push, which is G-002. On its own it is routine.
  293. * --no-verify skips git's own hooks. It bypasses a check; it destroys
  294. * nothing.
  295. *
  296. * Adding those would have regressed the work v2.1.36 did — twelve measured
  297. * false positives down to one — by prompting on ordinary commits. A guard that
  298. * fires on routine work is how people learn to switch guards off.
  299. *
  300. * `git add -f` is likewise absent: it stages an ignored file, which is a leak
  301. * rather than a destruction, and the leak that matters (`git add -f .env`) is
  302. * now caught by G-005, whose word-boundary defect this release fixes.
  303. */
  304. {
  305. id: 'G-016',
  306. name: 'Untracked file deletion',
  307. /*
  308. * `git clean` with `-f` plus `-d` or `-x` deletes untracked files outright.
  309. * It is the most irreversible command in ordinary git use: unlike `reset
  310. * --hard` (G-003) there is no reflog entry, because the files were never in
  311. * the object store. Nothing in G-001 or G-013 sees it — the token `rm` never
  312. * appears.
  313. *
  314. * `-f` alone (no `-d`/`-x`) still deletes untracked files in the current
  315. * directory, so the force flag is matched anywhere in a short cluster, in
  316. * any order: `-fd`, `-df`, `-xdf`, `--force -d`. The first attempt anchored
  317. * `f` immediately after the dashes and missed `-xdf`, which is the spelling
  318. * most people actually type.
  319. */
  320. pattern: /\bgit\s+clean\b(?=[\s\S]*(?:--force\b|-[a-zA-Z]*f))/i,
  321. severity: 'critical',
  322. defaultAction: 'deny',
  323. // `-n` / `--dry-run` prints what WOULD be removed and removes nothing.
  324. // Prompting for a preview is the unfollowable friction ENH-445 removed
  325. // elsewhere; git itself treats the combination as a preview.
  326. suppressIf: isGitCleanDryRun,
  327. // Graded like G-001 and G-013: a broad target denies, a scoped one asks.
  328. // `git clean -fdx` at the repo root is not the same act as `git clean -fd ./build`.
  329. severityFor: (text) => (gitCleanTargetIsBroad(text) ? 'critical' : 'high'),
  330. },
  331. {
  332. id: 'G-017',
  333. name: 'Uncommitted change discard',
  334. /*
  335. * The three spellings that throw away the working tree without touching
  336. * history: `git checkout -f`, `git restore` against the worktree, and
  337. * `git switch --discard-changes`. Same consequence as `git reset --hard`,
  338. * which has been an `ask` since G-003 — so these are an `ask` too, rather
  339. * than three rules that grade one act differently depending on which verb
  340. * the user reached for.
  341. *
  342. * `git restore --staged` alone only unstages and is excluded: the file
  343. * content survives in the working tree. That exclusion lives in
  344. * isStagedOnlyRestore() rather than in a negative lookahead — the first
  345. * attempt used `(?![\s\S]*--staged\s*$)`, which only held when the flag was
  346. * the last token, so `git restore --staged .` still matched.
  347. */
  348. pattern: /\bgit\s+(?:checkout\s+(?:-f\b|--force\b)|switch\b[\s\S]*--discard-changes\b|restore\b)/i,
  349. severity: 'high',
  350. defaultAction: 'ask',
  351. suppressIf: isStagedOnlyRestore,
  352. },
  353. {
  354. id: 'G-018',
  355. name: 'Recovery history destruction',
  356. /*
  357. * The reflog is what makes `git reset --hard`, `git branch -D` and an
  358. * amended commit recoverable — it is the reason those are graded `ask` or
  359. * left alone. Expiring it and pruning immediately removes that safety net,
  360. * which is why this is here and plain `git gc` is not: the danger is the
  361. * combination of expiring NOW and pruning NOW.
  362. *
  363. * Deleting the backups is a bigger act than any single deletion they cover.
  364. */
  365. pattern: /\bgit\s+(?:reflog\s+expire\b[\s\S]*--expire(?:-unreachable)?=(?:now|all)\b|gc\b[\s\S]*--prune=now\b)/i,
  366. severity: 'critical',
  367. defaultAction: 'deny',
  368. }
  369. ];
  370. /**
  371. * Fields of a parsed hook input that can carry a destructive operation.
  372. * Anything not listed here (ids, booleans, metadata) is not worth matching and
  373. * only adds noise.
  374. */
  375. const MATCHABLE_FIELDS = ['command', 'file_path', 'filePath', 'content', 'old_string', 'oldString', 'new_string', 'newString'];
  376. /**
  377. * Normalize an input into the list of strings the rules should run against.
  378. *
  379. * ENH-389 (v2.1.33): this used to be `JSON.stringify(toolInput)` for anything
  380. * that was not already a string, which quietly broke every anchored pattern.
  381. * `{"command":"chmod 777 /"}` ends with `"}`, so G-008's `\/\s*$` never
    • Note: Quoted as data in code: Sets world-writable permissions on a root path (chmod 777 /)
    • Line 386 on GitHub
  382. * matched and commands aimed at the filesystem root were invisible. Measured
  383. * before the fix:
  384. * detect('Bash', 'chmod 777 /') -> G-008 critical
    • Note: Quoted as data in code: Sets world-writable permissions on a root path (chmod 777 /)
    • Line 389 on GitHub
  385. * detect('Bash', { command: 'chmod 777 /' }) -> not detected
    • Note: Quoted as data in code: Sets world-writable permissions on a root path (chmod 777 /)
    • Line 390 on GitHub
  386. *
  387. * Fixing only the call site would have left the trap armed for the next caller
  388. * (`scripts/pre-write.js:217` passes a parsed object today). Each field is
  389. * matched separately so per-field anchors behave exactly as they do for a bare
  390. * string, rather than being concatenated into one blob.
  391. *
  392. * @param {string|object|null|undefined} toolInput
  393. * @returns {string[]}
  394. */
  395. function toMatchableStrings(toolInput) {
  396. if (typeof toolInput === 'string') return [toolInput];
  397. if (!toolInput || typeof toolInput !== 'object') return [''];
  398. const parts = [];
  399. for (const key of MATCHABLE_FIELDS) {
  400. const v = toolInput[key];
  401. if (typeof v === 'string' && v.length > 0) parts.push(v);
  402. }
  403. // Nothing recognizable — fall back to the raw values so a novel shape is not
  404. // silently exempt from every rule.
  405. if (parts.length === 0) {
  406. for (const v of Object.values(toolInput)) {
  407. if (typeof v === 'string' && v.length > 0) parts.push(v);
  408. }
  409. }
  410. return parts.length > 0 ? parts : [''];
  411. }
  412. /**
  413. * Targets that make a recursive delete catastrophic rather than routine.
  414. *
  415. * Deliberately conservative: anything not recognised as specific is treated as
  416. * broad. Being wrong in this direction costs a confirmation prompt; being wrong
  417. * in the other direction costs the user their data.
  418. */
  419. const BROAD_DELETE_TARGETS = [
  420. /(^|\s)\/(\s|$)/, // the filesystem root
  421. /(^|\s)~(\/?\s|\/?$)/, // home
  422. /\$(HOME|PWD|CWD|ROOT|PROJECT_ROOT)\b/, // an env var standing in for a root
  423. /(^|\s)\.\.?(\s|$)/, // bare . or ..
  424. /(^|\s)\/(etc|usr|var|bin|sbin|lib|opt|boot|dev|sys|proc|System|Library|Applications|Users|home)(\/|\s|$)/i,
  425. /(^|\s)[A-Za-z]:\\(\s|$)/, // a Windows drive root
  426. /(^|\s)\/\*/, // a glob directly under root
  427. /(^|\s)\*(\s|$)/, // a bare glob
  428. /(^|\s)["']?\$\{?\w+\}?["']?(\s|$)/, // an unresolved variable as the whole target
  429. ];
  430. /**
  431. * Does this recursive-delete command aim at something broad?
  432. *
  433. * An unparseable command counts as broad — the point is to be sure the target
  434. * is specific before relaxing, never to guess that it is.
  435. *
  436. * @param {string} text - the command that matched the recursive-delete pattern
  437. * @returns {boolean}
  438. */
  439. function deleteTargetIsBroad(text) {
  440. if (typeof text !== 'string') return true;
  441. /*
  442. * The target list runs from the delete verb to the next command separator —
  443. * NOT to the end of the input.
  444. *
  445. * The first version used `(.*)$` with the `s` flag, which swallowed every
  446. * subsequent line of a multi-command block, so anything appearing later in
  447. * the script was read as an operand of the delete. Reproduced while working
  448. * on v2.1.34, on a block of the shape:
  449. *
  450. * cd "$JOB/tmp" && rm -rf degtest && mkdir degtest
  451. * ...
  452. * printf ... | CLAUDE_PROJECT_DIR="$PWD" node r.js
  453. *
  454. * `$PWD` on the last line matched the "env var standing in for a root" rule,
  455. * so a delete of one scoped directory was graded `critical` and refused —
  456. * while advising the user to "scope the command to a specific path", which
  457. * they had already done. A guard that refuses correct commands and gives
  458. * unfollowable advice is one people switch off, and then it protects nothing.
  459. */
  460. const m = text.match(/\b(?:rm|rimraf|Remove-Item)\b([^\n;|&]*)/i);
  461. if (!m) return true; // shutil.rmtree(...) and friends: not parsed, stay strict
  462. const operands = m[1]
  463. .split(/\s+/)
  464. .filter((tok) => tok && !tok.startsWith('-'));
  465. if (operands.length === 0) return true; // no target found — do not relax
  466. return operands.some((operand) => {
  467. // `$(rm -rf ~)` and backticks: the closer is not part of the operand.
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 477 on GitHub
  468. const target = ' ' + operand.replace(/[)`]+$/, '').replace(/^["']|["']$/g, '') + ' ';
  469. return BROAD_DELETE_TARGETS.some((re) => re.test(target));
  470. });
  471. }
  472. /**
  473. * Commands that report a file's METADATA without reading its contents.
  474. *
  475. * ENH-445 (v2.1.36) — G-006 fires on any mention of a key-file extension, so
  476. * `ls -la ./certs/server.pem` was graded "Secret key access" and prompted. The
  477. * rule exists to notice a secret being READ or moved; a directory listing does
  478. * neither, and prompting for it is the kind of unfollowable friction that
  479. * teaches people to switch the guard off.
  480. *
  481. * Deliberately a short allowlist of commands whose entire job is metadata. Any
  482. * verb not on it — including every reader (`cat`, `head`, `openssl`, `base64`)
  483. * and every copier (`cp`, `scp`, `rsync`) — still fires.
  484. */
  485. const METADATA_ONLY_COMMANDS = [
  486. 'ls', 'll', 'stat', 'file', 'find', 'basename', 'dirname', 'realpath',
  487. 'readlink', 'test', 'wc', 'du',
  488. ];
  489. /**
  490. * Conventional `.env` template suffixes — files whose entire purpose is to be
  491. * committed. Kept identical to the closed list ENH-464 (v2.1.36) settled on for
  492. * the write path in lib/control/scope-limiter.js, so the two surfaces cannot
  493. * disagree about one file.
  494. */
  495. const ENV_TEMPLATE_SUFFIXES = ['example', 'sample', 'template', 'dist'];
  496. /**
  497. * Runtime objects whose `.env` is a variable map, not a file.
  498. *
  499. * `process.env.NODE_ENV` is how every Node program reads configuration, and the
  500. * shipped G-005 pattern matched it — so editing any file that reads an
  501. * environment variable prompted. A closed list, in the style of
  502. * METADATA_ONLY_COMMANDS: anything not named here still fires.
  503. */
  504. const RUNTIME_ENV_ACCESSORS = ['process', 'meta', 'deno', 'bun', 'globalthis'];
  505. /**
  506. * Every `.env` in this segment is harmless.
  507. *
  508. * ENH-477 (v2.1.37). Two harmless shapes, and the suppression holds only when
  509. * EVERY occurrence is one of them — `cp .env.example .env` mentions a template
  510. * and a real secret store, and the second is the reason to ask.
  511. *
  512. * template `.env.example`, `.env.local.example` — exists to be
  513. * committed. Judged on the LAST segment of the dotted chain, so
  514. * a nested template is still a template; the first attempt read
  515. * only the first segment and prompted on `.env.local.example`,
  516. * which an existing regression control caught.
  517. * runtime access `process.env.PORT` — a variable read, not a file.
  518. *
  519. * @param {string} text - the segment that matched
  520. * @returns {boolean}
  521. */
  522. function isBenignEnvMention(text) {
  523. if (typeof text !== 'string') return false;
  524. // Greedy on the prefix, deliberately: a lazy `*?` matches empty every time and
  525. // the accessor is never captured, so `process.env.PORT` reads as a bare file.
  526. const re = /([\w.]*)\.env((?:\.[\w-]+)*)(?![\w-])/gi;
  527. let m;
  528. let seen = 0;
  529. while ((m = re.exec(text)) !== null) {
  530. seen++;
  531. const prefix = (m[1] || '').split('.').filter(Boolean).pop() || '';
  532. if (RUNTIME_ENV_ACCESSORS.includes(prefix.toLowerCase())) continue;
  533. const chain = (m[2] || '').split('.').filter(Boolean);
  534. const last = (chain[chain.length - 1] || '').toLowerCase();
  535. if (ENV_TEMPLATE_SUFFIXES.includes(last)) continue;
  536. return false; // this one is a real environment file
  537. }
  538. return seen > 0;
  539. }
  540. /**
  541. * Is this segment nothing but a metadata query over its operands?
  542. *
  543. * @param {string} text - the segment that matched
  544. * @returns {boolean} true when the leading command only reports metadata
  545. */
  546. function isMetadataOnlyAccess(text) {
  547. if (typeof text !== 'string') return false;
  548. const m = text.trim().match(/^([\w./-]+)/);
  549. if (!m) return false;
  550. const verb = m[1].split('/').pop(); // /bin/ls -> ls
  551. return METADATA_ONLY_COMMANDS.includes(verb.toLowerCase());
  552. }
  553. /**
  554. * Wrappers that stand in front of the real command without changing what it is.
  555. * `sudo rm …` is still an `rm`; the guard has to see through them.
  556. */
  557. const COMMAND_WRAPPERS = ['sudo', 'command', 'env', 'nice', 'nohup', 'time', 'exec', 'doas'];
  558. /**
  559. * Commands that can only read and report. Deliberately short.
  560. *
  561. * `echo` and `printf` are NOT here, and that is the whole design of this list:
  562. * they are how a payload gets built (`echo "…" | sh`), so treating them as inert
  563. * would open the hole this guard exists to close. Only search tools qualify —
  564. * they have no write mode at all.
  565. */
  566. const SEARCH_ONLY_COMMANDS = ['grep', 'egrep', 'fgrep', 'rg', 'ripgrep', 'ag', 'ack'];
  567. /**
  568. * Does this segment contain a shell metacharacter OUTSIDE quotes?
  569. *
  570. * The quote-awareness is not a nicety. A search pattern routinely contains the
  571. * very characters that would otherwise disqualify it — `grep -rlE "DROP|rm" lib`
  572. * has a `|` inside a quoted regex, and reading that as a pipe would leave the
  573. * commonest form of this false positive unfixed while claiming to have fixed it.
  574. *
  575. * Scanning follows splitCommandSegments(): a backslash escapes the next
  576. * character, single and double quotes toggle, and only unquoted text counts. An
  577. * unbalanced quote means the segment cannot be parsed with confidence, so it is
  578. * reported as escaping — the conservative answer.
  579. *
  580. * @param {string} text
  581. * @returns {boolean}
  582. */
  583. function hasUnquotedShellEscape(text) {
  584. let inSingle = false;
  585. let inDouble = false;
  586. for (let i = 0; i < text.length; i++) {
  587. const c = text[i];
  588. if (c === '\\') { i++; continue; }
  589. if (c === "'" && !inDouble) { inSingle = !inSingle; continue; }
  590. if (c === '"' && !inSingle) { inDouble = !inDouble; continue; }
  591. if (inSingle || inDouble) continue;
  592. if (c === '|' || c === '>' || c === '<' || c === '`' || c === ';' || c === '&') return true;
  593. if (c === '$' && text[i + 1] === '(') return true;
  594. }
  595. // Unbalanced quoting — do not claim to understand this segment.
  596. return inSingle || inDouble;
  597. }
  598. /**
  599. * Is this segment a search that provably cannot execute or delete anything?
  600. *
  601. * ENH-473 (v2.1.37). Every rule in this table matches text, so a command that
  602. * merely *contains* a dangerous string is graded as if it performed one. Searching
  603. * for the string is the clearest case: this was hit twice while writing v2.1.37,
  604. * once when a `grep` for two rule patterns was refused as "Recursive delete; SQL
  605. * table drop". Nothing was deleted and nothing could have been — grep has no
  606. * write mode.
  607. *
  608. * Same defect class as ENH-470 one level up: ENH-470 stopped G-007 reading a WORD
  609. * as a delete command, and this stops any rule reading a search ARGUMENT as an
  610. * operation.
  611. *
  612. * The bound is deliberately severe, because the failure direction here is a false
  613. * negative — a real destructive command passing unseen — and that is much worse
  614. * than the false positive it fixes. Both conditions must hold:
  615. *
  616. * 1. the command head is a search tool with no write mode (not `echo`, which is
  617. * how `echo "…" | sh` starts), and
  618. * 2. the segment contains no character through which a shell could be reached.
  619. *
  620. * With both, the segment cannot do anything but print. `grep -rn "…" . | sh`
  621. * fails (2), `echo "…" | sh` fails (1), and a redirection to a file that is later
  622. * executed fails (2). Negative controls for all three ship with this change.
  623. *
  624. * @param {string} text - one command segment
  625. * @returns {boolean} true when no rule should be matched against this segment
  626. */
  627. function isInertSearchInvocation(text) {
  628. if (typeof text !== 'string') return false;
  629. const trimmed = text.trim();
  630. if (!trimmed) return false;
  631. if (hasUnquotedShellEscape(trimmed)) return false;
  632. let rest = trimmed;
  633. // eslint-disable-next-line no-constant-condition
  634. while (true) {
  635. const m = rest.match(/^(\S+)\s+([\s\S]*)$/);
  636. if (!m) break;
  637. const head = m[1];
  638. const isAssignment = /^[A-Za-z_][A-Za-z0-9_]*=/.test(head);
  639. const isWrapper = COMMAND_WRAPPERS.includes(head.split('/').pop().toLowerCase());
  640. if (!isAssignment && !isWrapper) break;
  641. rest = m[2].trim();
  642. }
  643. const command = (rest.split(/\s+/)[0] || '').split('/').pop().toLowerCase();
  644. return SEARCH_ONLY_COMMANDS.includes(command);
  645. }
  646. /** The verbs G-007 is written about. */
  647. const DELETE_VERBS = ['rm', 'del', 'delete', 'remove'];
  648. /**
  649. * Is the delete verb something OTHER than this segment's command?
  650. *
  651. * ENH-470 (v2.1.37). G-007 is named "Mass file deletion" and counts operands
  652. * after the token `rm`/`del`/`delete`/`remove`. Its pattern lets that token sit
  653. * anywhere in the segment, so anything that merely *mentions* deletion and takes
  654. * five or more arguments matched. Measured on v2.1.36, after issue #148's
  655. * segment-scoping fix had already landed:
  656. *
  657. * grep -rn delete src a b c d e -> G-007, ask (read-only)
  658. * npm remove lodash react vue axios dayjs -> G-007, ask (package manager)
  659. *
  660. * Neither deletes a file. The first cannot delete anything at all. This is the
  661. * same defect class issue #148 reported — an operand list read past its own
  662. * boundaries — surviving one level down: #148 fixed reading across command
  663. * separators, and this fixes reading across the command name itself.
  664. *
  665. * The rule stands down unless the segment's command head is a delete verb, after
  666. * looking through `VAR=value` prefixes, the wrappers above, and a path
  667. * (`/bin/rm` reads as `rm`). `npm remove …` therefore stops matching, because the
  668. * command is `npm`.
  669. *
  670. * This narrows G-007 only, and G-007 is the weakest rule in the table
  671. * (`medium`/`ask`). A genuine `rm a b c d e f` still matches here; a recursive
  672. * delete is G-001's; a find-driven delete is G-013's; an unscoped SQL DELETE is
  673. * G-010b's. Regression controls for all four ship alongside this change, because
  674. * a narrowing without them is indistinguishable from a hole.
  675. *
  676. * @param {string} text - one command segment
  677. * @returns {boolean} true when G-007 should stand down
  678. */
  679. function isNotACommandLevelDelete(text) {
  680. if (typeof text !== 'string') return false;
  681. let rest = text.trim();
  682. if (!rest) return false;
  683. // Strip leading `VAR=value` assignments and transparent wrappers, repeatedly:
  684. // `sudo NODE_ENV=x /bin/rm …` has both.
  685. // eslint-disable-next-line no-constant-condition
  686. while (true) {
  687. const m = rest.match(/^(\S+)\s+([\s\S]*)$/);
  688. if (!m) break;
  689. const head = m[1];
  690. const isAssignment = /^[A-Za-z_][A-Za-z0-9_]*=/.test(head);
  691. const isWrapper = COMMAND_WRAPPERS.includes(head.split('/').pop().toLowerCase());
  692. if (!isAssignment && !isWrapper) break;
  693. rest = m[2].trim();
  694. }
  695. const command = (rest.split(/\s+/)[0] || '').split('/').pop().toLowerCase();
  696. return !DELETE_VERBS.includes(command);
  697. }
  698. /**
  699. * Does this segment read as a SQL statement rather than a shell command?
  700. *
  701. * ENH-447 (v2.1.36) — G-007 ("Mass file deletion") counts operands after the
  702. * token `delete`, and SQL's `DELETE FROM` supplies it. Measured on v2.1.35, the
  703. * safe, scoped statement
  704. *
  705. * DELETE FROM audit_log WHERE id = 1
  706. *
  707. * was reported as a filesystem mass-deletion. The SQL rules (G-009, G-010,
  708. * G-010b, G-011) are the ones that own this language; G-007 has nothing useful
  709. * to say about it and should stand down rather than double-report.
  710. *
  711. * This suppresses G-007 only. It does not weaken the SQL rules — a genuinely
  712. * unscoped `DELETE FROM audit_log` is still caught by G-010b, which is the rule
  713. * written for it.
  714. *
  715. * @param {string} text
  716. * @returns {boolean}
  717. */
  718. function looksLikeSqlStatement(text) {
  719. if (typeof text !== 'string') return false;
  720. return /\b(DELETE\s+FROM|INSERT\s+INTO|UPDATE\s+[\w.]+\s+SET|TRUNCATE\s+TABLE|DROP\s+(TABLE|DATABASE|SCHEMA|INDEX|VIEW)|SELECT\s+[\s\S]*\bFROM\b)\b/i.test(text);
  721. }
  722. /**
  723. * Branch names a force push must never quietly overwrite.
  724. *
  725. * Mirrors G-004's protected set, so "which branches matter" is stated once in
  726. * spirit even though the two rules match different shapes.
  727. */
  728. const PROTECTED_BRANCHES = /\b(main|master|release|production)\b/i;
  729. /**
  730. * Is this force push aimed at a protected branch?
  731. *
  732. * ENH-462 (v2.1.36) — G-002 had no `severityFor`, so every force push denied,
  733. * including the routine one:
  734. *
  735. * git push --force-with-lease origin my-topic-branch -> critical / deny
  736. *
  737. * Rewriting your own topic branch after a rebase is ordinary work, and
  738. * `--force-with-lease` is the careful spelling of it — it refuses if upstream
  739. * moved. Denying that outright is the "refuses correct commands" failure this
  740. * release is about, and it is why bkit's own push-event-guard already
  741. * distinguishes upstream from fork while this rule did not.
  742. *
  743. * A protected target still denies. Anything else asks, so the push is confirmed
  744. * rather than refused. An unparseable target counts as protected: when the
  745. * branch cannot be read, `git push --force` with no refspec pushes the current
  746. * branch, which may well be main.
  747. *
  748. * @param {string} text - the segment that matched the force-push pattern
  749. * @returns {boolean}
  750. */
  751. function pushTargetIsProtected(text) {
  752. if (typeof text !== 'string') return true;
  753. const m = text.match(/\bgit\s+push\b([^\n;|&]*)/i);
  754. if (!m) return true;
  755. const operands = m[1]
  756. .split(/\s+/)
  757. .filter((tok) => tok && !tok.startsWith('-'));
  758. // No remote/refspec given: git pushes the current branch, which is unknown here.
  759. if (operands.length === 0) return true;
  760. return operands.some((tok) => PROTECTED_BRANCHES.test(tok));
  761. }
  762. /**
  763. * Does this find-based deletion aim at something broad?
  764. *
  765. * ENH-443 (v2.1.36) — G-013 had no `severityFor`, so it graded every match
  766. * `critical` and denied outright. That produced the asymmetry issue #148 called
  767. * out, measured on v2.1.35:
  768. *
  769. * rm -rf /tmp/scratch/build -> G-001 / high / ask
  770. * find /tmp/scratch -type f -name '*.tmp' -delete -> G-013 / critical / deny
  771. *
  772. * The strictly narrower operation was refused harder, and the refusal advised
  773. * "scope the command to a specific path" — which the user had already done.
  774. *
  775. * find's paths are the operands before the first expression token, so the search
  776. * stops at the first `-flag`. A find with no path defaults to the working
  777. * directory, which `BROAD_DELETE_TARGETS` already treats as broad; an
  778. * unparseable command stays broad for the same reason `deleteTargetIsBroad()`
  779. * does — be sure the target is specific before relaxing, never guess that it is.
  780. *
  781. * @param {string} text - the segment that matched the find-based deletion pattern
  782. * @returns {boolean}
  783. */
  784. /**
  785. * Is this `git clean` a preview rather than a deletion?
  786. *
  787. * ENH-477 (v2.1.37). `-n` / `--dry-run` prints what would be removed and removes
  788. * nothing, and git accepts it alongside `-f`. Prompting for a preview is the
  789. * unfollowable friction ENH-445 removed from G-006.
  790. *
  791. * @param {string} text - the segment that matched
  792. * @returns {boolean}
  793. */
  794. function isGitCleanDryRun(text) {
  795. if (typeof text !== 'string') return false;
  796. return /(^|\s)(--dry-run\b|-[a-zA-Z]*n(?![a-zA-Z]))/.test(text);
  797. }
  798. /**
  799. * Is this `git restore` only unstaging?
  800. *
  801. * ENH-477 (v2.1.37). `--staged` on its own moves content out of the index and
  802. * leaves the working tree untouched, so nothing is lost. Paired with
  803. * `--worktree` it DOES overwrite the working tree, which is the act G-017
  804. * exists for.
  805. *
  806. * Only `restore` is inspected: the other two spellings the rule matches
  807. * (`checkout -f`, `switch --discard-changes`) have no such harmless form.
  808. *
  809. * @param {string} text - the segment that matched
  810. * @returns {boolean}
  811. */
  812. function isStagedOnlyRestore(text) {
  813. if (typeof text !== 'string') return false;
  814. if (!/\bgit\s+restore\b/i.test(text)) return false;
  815. const staged = /(^|\s)(--staged|-S)(\s|$)/.test(text);
  816. const worktree = /(^|\s)(--worktree|-W)(\s|$)/.test(text);
  817. return staged && !worktree;
  818. }
  819. /**
  820. * Does this `git clean` invocation target the whole repository?
  821. *
  822. * ENH-477 (v2.1.37). Graded the same way as G-001 and G-013: a broad target
  823. * denies, a scoped one asks. `git clean -fd ./build` is a build-directory reset;
  824. * `git clean -fdx` at the root deletes every untracked file in the repository,
  825. * including local config the user never intended to lose.
  826. *
  827. * With no path operand git cleans from the current directory down, so the
  828. * absence of a path is the broad case, not the narrow one — the same default
  829. * findTargetIsBroad() takes for `find`.
  830. *
  831. * @param {string} text - the segment that matched
  832. * @returns {boolean}
  833. */
  834. function gitCleanTargetIsBroad(text) {
  835. if (typeof text !== 'string') return true;
  836. const m = text.match(/\bgit\s+clean\b([^\n;]*)/i);
  837. if (!m) return true;
  838. const paths = [];
  839. for (const tok of m[1].split(/\s+/)) {
  840. if (!tok) continue;
  841. if (tok === '--') continue;
  842. if (tok.startsWith('-')) continue; // flags may precede or follow the path
  843. paths.push(tok);
  844. }
  845. if (paths.length === 0) return true; // implicit cwd — cleans everything below it
  846. return paths.some((operand) => {
  847. const target = ' ' + operand.replace(/^["']|["']$/g, '') + ' ';
  848. return BROAD_DELETE_TARGETS.some((re) => re.test(target));
  849. });
  850. }
  851. function findTargetIsBroad(text) {
  852. if (typeof text !== 'string') return true;
  853. const m = text.match(/\bfind\b([^\n;]*)/i);
  854. if (!m) return true;
  855. const paths = [];
  856. for (const tok of m[1].split(/\s+/)) {
  857. if (!tok) continue;
  858. if (tok.startsWith('-')) break; // expressions start here; paths are done
  859. paths.push(tok);
  860. }
  861. if (paths.length === 0) return true; // implicit cwd, or nothing parseable
  862. return paths.some((operand) => {
  863. const target = ' ' + operand.replace(/^["']|["']$/g, '') + ' ';
  864. return BROAD_DELETE_TARGETS.some((re) => re.test(target));
  865. });
  866. }
  867. /**
  868. * Remove heredoc BODIES before rule matching.
  869. *
  870. * A heredoc body is data on a program's stdin, not a command line. Matching
  871. * rules against it produces false positives that are indistinguishable from
  872. * real findings — writing a commit message that merely *mentions* `find -delete`
  873. * or `curl | sh`, or piping documentation text through `python3 - <<'PY'`, was
  874. * enough to be refused as critical. Both happened during work on v2.1.34, and a
  875. * guard that blocks ordinary work is a guard people switch off.
  876. *
  877. * This does not create a bypass. The heredoc-as-bypass vector — a heredoc piped
  878. * into an interpreter, or a command substitution alongside one — is the whole
  879. * subject of `lib/defense/heredoc-detector.js`, which inspects the command
  880. * STRUCTURE and still sees everything here. What this strips is only the inert
  881. * payload, and the delimiter line itself is kept so structural rules can still
  882. * see that a heredoc was present.
  883. *
  884. * Handles the `<<EOF`, `<<-EOF`, `<<'EOF'` and `<<"EOF"` spellings.
  885. *
  886. * @param {string} command
  887. * @returns {string} the command with heredoc bodies elided
  888. */
  889. /**
  890. * Find a heredoc opener on a line, ignoring any `<<` that sits inside quotes.
  891. *
  892. * v2.1.34: an earlier version matched `<<` anywhere on the line, which is a
  893. * bypass rather than a nicety. `echo "example: cmd << EOF"` starts a bogus
  894. * elision, and every line up to the next `EOF` is discarded — including a real
  895. * destructive command. Measured against that earlier version:
  896. *
  897. * echo "example: cmd << EOF" → stripped to the echo alone
  898. * rm -rf ~/ (elided)
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 939 on GitHub
  899. * EOF detect: []
  900. *
  901. * Quote tracking is deliberately simple — single and double quotes, with
  902. * backslash escapes — because the only decision it feeds is "may this line be
  903. * treated as an opener". Anything it cannot parse confidently is left alone,
  904. * which keeps evidence rather than removing it.
  905. *
  906. * @param {string} line
  907. * @returns {{delimiter: string, quoted: boolean}|null} the delimiter and whether its
  908. * tag was quoted (a quoted body is literal text), or null when no heredoc opens
  909. */
  910. function findHeredocDelimiter(line) {
  911. let inSingle = false;
  912. let inDouble = false;
  913. for (let i = 0; i < line.length; i++) {
  914. const c = line[i];
  915. if (c === '\\') { i++; continue; }
  916. if (c === "'" && !inDouble) { inSingle = !inSingle; continue; }
  917. if (c === '"' && !inSingle) { inDouble = !inDouble; continue; }
  918. if (inSingle || inDouble) continue;
  919. if (c !== '<' || line[i + 1] !== '<') continue;
  920. // `<<<` is a here-STRING, not a heredoc — it has no body and no terminator.
  921. if (line[i + 2] === '<') continue;
  922. const m = line.slice(i).match(/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))/);
  923. if (m) return { delimiter: m[1] || m[2] || m[3], quoted: !m[3] };
  924. return null;
  925. }
  926. return null;
  927. }
  928. /**
  929. * Join backslash-newline continuations the way bash does: a newline is removed
  930. * only when an odd run of backslashes precedes it (`\\` is a literal backslash).
  931. * A scanner rather than a regex, so consecutive continuations all join.
  932. */
  933. function joinLineContinuations(text) {
  934. let out = '';
  935. let run = 0;
  936. for (const c of text) {
  937. if (c === '\n' && run % 2 === 1) { out = out.slice(0, -1); run = 0; continue; }
  938. out += c;
  939. run = c === '\\' ? run + 1 : 0;
  940. }
  941. return out;
  942. }
  943. /** True when the line has a `$(` or backtick that no backslash escapes. */
  944. function hasUnescapedSubstitution(line) {
  945. for (let i = 0; i < line.length; i++) {
  946. const c = line[i];
  947. if (c === '\\') { i++; continue; }
  948. if (c === '`' || (c === '$' && line[i + 1] === '(')) return true;
  949. }
  950. return false;
  951. }
  952. function stripHeredocBodies(command) {
  953. if (typeof command !== 'string' || !command.includes('<<')) return command;
  954. const lines = command.split('\n');
  955. const out = [];
  956. let delimiter = null;
  957. let terminated = true;
  958. let quoted = false;
  959. let body = [];
  960. for (const line of lines) {
  961. if (delimiter === null) {
  962. out.push(line);
  963. const found = findHeredocDelimiter(line);
  964. if (found) { ({ delimiter, quoted } = found); terminated = false; body = []; }
  965. continue;
  966. }
  967. /*
  968. * Inside a body: drop the content, but keep the terminator line WHOLE. A
  969. * known bypass writes the exec vector on that line (`EOF-1 | bash`), so
  970. * truncating at the delimiter would remove the very thing worth matching.
  971. * Prefix match, not equality, for the same reason.
  972. */
  973. if (line.trim() === delimiter || line.trimStart().startsWith(delimiter)) {
  974. // A bare-tag body is expanded by bash, so an unescaped `$(` or backtick
  975. // runs. A substitution can span lines (`$(` / `rm -rf ~` / `)`) or use
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 1,019 on GitHub
  976. // backslash-newline continuations, so keep the whole body, joined the way
  977. // bash reads it. Either view finding a substitution keeps the body.
  978. const expanded = joinLineContinuations(body.join('\n'));
  979. const substitutes = body.some(hasUnescapedSubstitution) || hasUnescapedSubstitution(expanded);
  980. if (!quoted && substitutes) out.push(...expanded.split('\n'));
  981. out.push(line);
  982. delimiter = null;
  983. terminated = true;
  984. continue;
  985. }
  986. body.push(line);
  987. }
  988. // No terminator found — there is no trustworthy body boundary, so match
  989. // against everything. This helper may remove noise, never evidence.
  990. if (!terminated) return command;
  991. return out.join('\n');
  992. }
  993. /**
  994. * Strip SQL comments so a commented-out keyword cannot stand in for a real clause.
  995. *
  996. * ENH-446 (v2.1.36) — G-010b fires only when no WHERE follows the DELETE, so any
  997. * occurrence of the WORD `WHERE` suppresses it. A comment is not a clause.
  998. * Measured on v2.1.35:
  999. *
  1000. * DELETE FROM audit_log -- WHERE -> not detected
  1001. *
  1002. * A comment introducer must be `--` followed by WHITESPACE or end-of-input.
  1003. * Without that condition this helper destroys evidence: the first version
  1004. * treated the shell flag `--command` as a comment, so
  1005. *
  1006. * wrangler d1 execute db --command "DROP TABLE audit_log"
  1007. *
  1008. * was truncated to `wrangler d1 execute db` and G-009 stopped firing — a real
  1009. * DROP went undetected. That regression was caught by the negative controls
  1010. * before it left the working tree, which is precisely why they are run on every
  1011. * change. `--WHERE` (no space) is therefore left intact; keeping a token we are
  1012. * unsure about costs a prompt, discarding one costs a table.
  1013. *
  1014. * Quote-aware for the same reason as everywhere else in this file — a literal
  1015. * `'--'` inside a string is data, not a comment introducer.
  1016. *
  1017. * @param {string} text
  1018. * @returns {string} the statement with `--` line comments and block comments removed
  1019. */
  1020. function stripSqlComments(text) {
  1021. if (typeof text !== 'string' || (!text.includes('--') && !text.includes('/*'))) return text;
  1022. let out = '';
  1023. let inSingle = false;
  1024. let inDouble = false;
  1025. for (let i = 0; i < text.length; i++) {
  1026. const c = text[i];
  1027. if (c === '\\') { out += c + (text[i + 1] || ''); i++; continue; }
  1028. if (c === "'" && !inDouble) { inSingle = !inSingle; out += c; continue; }
  1029. if (c === '"' && !inSingle) { inDouble = !inDouble; out += c; continue; }
  1030. if (!inSingle && !inDouble) {
  1031. if (c === '-' && text[i + 1] === '-' && /^(\s|$)/.test(text[i + 2] || '')) {
  1032. const nl = text.indexOf('\n', i);
  1033. if (nl === -1) break;
  1034. i = nl;
  1035. out += '\n';
  1036. continue;
  1037. }
  1038. if (c === '/' && text[i + 1] === '*') {
  1039. const end = text.indexOf('*/', i + 2);
  1040. if (end === -1) break;
  1041. i = end + 1;
  1042. out += ' ';
  1043. continue;
  1044. }
  1045. }
  1046. out += c;
  1047. }
  1048. return out;
  1049. }
  1050. /**
  1051. * Split a command into the segments a rule may legitimately span.
  1052. *
  1053. * ENH-440 (v2.1.36) — every rule below is written as a single command's shape,
  1054. * but they were matched against the WHOLE input. `.*` and `[\s\S]*` therefore ran
  1055. * past `&&`, `;` and newlines, so tokens belonging to *other* commands in a chain
  1056. * were read as operands of the dangerous one. G-001 already solved this for
  1057. * itself at `deleteTargetIsBroad()` by cutting at `[^\n;|&]`; this generalizes
  1058. * that cut so every rule gets it, instead of nine near-copies of the same regex.
  1059. *
  1060. * Measured on v2.1.35, this defect ran in BOTH directions:
  1061. *
  1062. * false positives — a safe command refused because a later command supplied
  1063. * the incriminating token:
  1064. * git push origin feature-x && rm -f /tmp/scratch/note.txt -> G-002 deny
  1065. * cp a.txt b.txt && ls / -> G-008 deny
  1066. * dd if=/dev/zero of=./scratch.img && echo "of=/dev/null" -> G-014 deny
  1067. *
  1068. * false negatives — a real threat hidden because a later command pushed an
  1069. * end-anchor out of reach or satisfied a negative lookahead:
  1070. * chmod 777 / ; ls -> NOTHING detected (G-008 defeated)
    • Note: Quoted as data in code: Sets world-writable permissions on a root path (chmod 777 /)
    • Line 1,118 on GitHub
  1071. * DELETE FROM audit_log; SELECT 1 WHERE x=1 -> G-010b defeated
  1072. *
  1073. * The false negatives are why this is a correctness fix and not a comfort fix.
  1074. *
  1075. * `|` is deliberately NOT a split point. A pipe is how several rules' threat is
  1076. * expressed — `curl … | sh` (G-015), `base64 -d … | sh` (G-012),
  1077. * `find … | xargs rm` (G-013) are each ONE dangerous construct, not two safe
  1078. * ones. Splitting there would blind exactly the rules that exist to catch it.
  1079. * `||` is a sequencer, not a pipe, and does split.
  1080. *
  1081. * Quote tracking mirrors `findHeredocDelimiter()`: single and double quotes with
  1082. * backslash escapes, so `echo "a && b"` stays one segment. Anything the tracker
  1083. * cannot parse confidently is left joined — this helper may narrow a window,
  1084. * never hide evidence.
  1085. *
  1086. * A newline separates SHELL commands but NOT SQL statements, which end at `;`.
  1087. * Splitting SQL on newlines would refuse the ordinary
  1088. *
  1089. * DELETE FROM audit_log
  1090. * WHERE id = 1
  1091. *
  1092. * because segment 1 has no WHERE — turning a fix for one false positive into a
  1093. * new one. Hence `mode`: rules written in SQL declare `segmentOn: 'sql'` and are
  1094. * cut at `;` only. Measured on v2.1.35, that statement is correctly clean today,
  1095. * and it must stay clean.
  1096. *
  1097. * @param {string} text
  1098. * @param {'shell'|'sql'} [mode='shell'] which separators terminate a statement
  1099. * @returns {string[]} one entry per segment; the original text when it contains
  1100. * no top-level separator
  1101. */
  1102. function splitCommandSegments(text, mode) {
  1103. if (typeof text !== 'string' || text.length === 0) return [''];
  1104. const sqlMode = mode === 'sql';
  1105. const segments = [];
  1106. let start = 0;
  1107. let inSingle = false;
  1108. let inDouble = false;
  1109. for (let i = 0; i < text.length; i++) {
  1110. const c = text[i];
  1111. if (c === '\\') { i++; continue; }
  1112. if (c === "'" && !inDouble) { inSingle = !inSingle; continue; }
  1113. if (c === '"' && !inSingle) { inDouble = !inDouble; continue; }
  1114. if (inSingle || inDouble) continue;
  1115. let sepLen = 0;
  1116. if (c === ';') sepLen = 1;
  1117. else if (!sqlMode && c === '\n') sepLen = 1;
  1118. else if (!sqlMode && ((c === '&' && text[i + 1] === '&') || (c === '|' && text[i + 1] === '|'))) sepLen = 2;
  1119. if (sepLen > 0) {
  1120. segments.push(text.slice(start, i));
  1121. i += sepLen - 1;
  1122. start = i + 1;
  1123. }
  1124. }
  1125. segments.push(text.slice(start));
  1126. const trimmed = segments.map((s) => s.trim()).filter((s) => s.length > 0);
  1127. return trimmed.length > 0 ? trimmed : [text];
  1128. }
  1129. /**
  1130. * Detect destructive operations in a tool invocation
  1131. * @param {string} toolName - Name of the tool being invoked
  1132. * @param {string|object} toolInput - Command string, or a parsed tool input whose
  1133. * command/path/content fields are matched individually (see toMatchableStrings)
  1134. * @returns {DetectionResult}
  1135. */
  1136. /**
  1137. * Resolve the action a matched rule calls for, from its declaration and its
  1138. * graded severity.
  1139. *
  1140. * `critical` always denies. Otherwise the rule's own `defaultAction` stands —
  1141. * except when the rule graded ITSELF down from `critical` (G-001 on a scoped
  1142. * target). There the declaration describes the worst case, not this match, so
  1143. * `deny` relaxes exactly one tier, to `ask`. It never relaxes to silence.
  1144. *
  1145. * @param {object} rule - the rule as declared in GUARDRAIL_RULES
  1146. * @param {string} severity - the severity this particular match graded to
  1147. * @returns {'deny'|'ask'|'allow'}
  1148. */
  1149. function resolveAction(rule, severity) {
  1150. if (severity === 'critical') return 'deny';
  1151. const declared = rule.defaultAction || 'ask';
  1152. const gradedDown = typeof rule.severityFor === 'function' && rule.severity === 'critical';
  1153. if (declared === 'deny') return gradedDown ? 'ask' : 'deny';
  1154. return declared;
  1155. }
  1156. function detect(toolName, toolInput) {
  1157. const inputs = toMatchableStrings(toolInput).map(stripHeredocBodies);
  1158. // Kept for the tool-specific checks below, which only need substring semantics.
  1159. const input = inputs.join('\n');
  1160. /*
  1161. * ENH-440 (v2.1.36) — match each rule against single command/statement
  1162. * segments rather than the whole input. See splitCommandSegments() for why
  1163. * this fixes false positives and false negatives at the same time, and why
  1164. * `|` is not a split point.
  1165. *
  1166. * Both segmentations are computed once and reused across the 19 rules; a rule
  1167. * picks the one matching the language it is written in.
  1168. */
  1169. /*
  1170. * ENH-473 (v2.1.37): a segment that provably cannot execute or delete anything
  1171. * is dropped before any rule sees it. Applied to both segmentations, because a
  1172. * shell `grep` invocation is still present in the SQL-mode split and would
  1173. * otherwise be matched by the SQL rules against its own search pattern.
  1174. */
  1175. const inert = isInertSearchInvocation;
  1176. const segmentsByMode = {
  1177. shell: inputs.flatMap((s) => splitCommandSegments(s, 'shell')).filter((s) => !inert(s)),
  1178. // Comments are stripped BEFORE splitting so a `--` comment cannot hide a
  1179. // statement separator, and a commented-out keyword cannot satisfy a
  1180. // negative lookahead (ENH-446).
  1181. sql: inputs.flatMap((s) => splitCommandSegments(stripSqlComments(s), 'sql')).filter((s) => !inert(s)),
  1182. };
  1183. const matchedRules = [];
  1184. for (const rule of GUARDRAIL_RULES) {
  1185. const segments = segmentsByMode[rule.segmentOn === 'sql' ? 'sql' : 'shell'];
  1186. /*
  1187. * A rule may declare `suppressIf` for contexts where its pattern provably
  1188. * says nothing useful — a metadata-only listing for G-006, a SQL statement
  1189. * for G-007. Suppression is evaluated per segment, so a chain that also
  1190. * contains a genuine match still reports it.
  1191. *
  1192. * This is deliberately narrower than grading: `severityFor` cannot help a
  1193. * rule whose declared action is already `ask`, because resolveAction()
  1194. * returns a non-critical rule's declared action unchanged and there is no
  1195. * tier below `ask` short of silence.
  1196. */
  1197. const hit = segments.find(
  1198. (s) => rule.pattern.test(s)
  1199. && !(typeof rule.suppressIf === 'function' && rule.suppressIf(s))
  1200. );
  1201. if (hit !== undefined) {
  1202. // A rule may grade itself from the matched text — see G-001, where the
  1203. // target decides whether a recursive delete is catastrophic or routine.
  1204. const severity = typeof rule.severityFor === 'function'
  1205. ? rule.severityFor(hit)
  1206. : rule.severity;
  1207. matchedRules.push({
  1208. id: rule.id,
  1209. name: rule.name,
  1210. severity,
  1211. /*
  1212. * v2.1.34 — the action the rule table declares for this match.
  1213. *
  1214. * `defaultAction` has been on every rule since the table was written,
  1215. * but nothing read it: the hook branched on `severity === 'critical'`
  1216. * and did nothing at all otherwise. Ten rules declared `ask` and none
  1217. * of them ever asked. Surfacing it here makes the table the single
  1218. * place that decides deny-vs-ask.
  1219. *
  1220. * A graded rule outranks its own declaration in the dangerous
  1221. * direction only: G-001 declares `deny`, and a scoped delete grades to
  1222. * `high`, so it asks — but a broad delete grades back to `critical`
  1223. * and denies. Grading never turns a `deny` into silence.
  1224. */
  1225. action: resolveAction(rule, severity),
  1226. pattern: rule.pattern.source
  1227. });
  1228. }
  1229. }
  1230. /*
  1231. * A second look at the two file rules against the UN-segmented input, for a
  1232. * Write or an Edit whose payload a segment boundary could have split.
  1233. *
  1234. * ENH-481 (v2.1.37) — this used to test `rule.pattern` and nothing else. It
  1235. * skipped `suppressIf`, so both suppressors that guard these two rules were
  1236. * dead on this path while working on the Bash path:
  1237. *
  1238. * G-006 ENH-445's isMetadataOnlyAccess — `ls -la ./certs/server.pem` is
  1239. * suppressed for a Bash command and was NOT suppressed here.
  1240. * G-005 every exemption below, including `.env.example`.
  1241. *
  1242. * The same class as ENH-441, which v2.1.36 fixed for `isDestructive()`: two
  1243. * entry points answering differently about one input, with the difference
  1244. * invisible until someone routed a payload through the other one. It was found
  1245. * while fixing G-005, when a suppressor that returned `true` for its segment
  1246. * did not suppress the rule.
  1247. *
  1248. * The purpose of the second look is kept — segmentation can split a payload —
  1249. * but it now applies the same predicate the main loop does.
  1250. */
  1251. if (toolName === 'Write' || toolName === 'Edit') {
  1252. for (const id of ['G-005', 'G-006']) {
  1253. const rule = GUARDRAIL_RULES.find((r) => r.id === id);
  1254. if (!rule || matchedRules.some((r) => r.id === id)) continue;
  1255. if (!rule.pattern.test(input)) continue;
  1256. if (typeof rule.suppressIf === 'function' && rule.suppressIf(input)) continue;
  1257. const severity = typeof rule.severityFor === 'function'
  1258. ? rule.severityFor(input)
  1259. : rule.severity;
  1260. matchedRules.push({
  1261. id: rule.id,
  1262. name: rule.name,
  1263. severity,
  1264. action: resolveAction(rule, severity),
  1265. pattern: rule.pattern.source,
  1266. });
  1267. }
  1268. }
  1269. const confidence = matchedRules.length > 0
  1270. ? Math.min(1, 0.5 + matchedRules.length * 0.2)
  1271. : 0;
  1272. return {
  1273. detected: matchedRules.length > 0,
  1274. rules: matchedRules,
  1275. confidence
  1276. };
  1277. }
  1278. /**
  1279. * Quick check whether a Bash command is destructive
  1280. * @param {string} command - Bash command string
  1281. * @returns {boolean}
  1282. */
  1283. function isDestructive(command) {
  1284. if (!command || typeof command !== 'string') return false;
  1285. /*
  1286. * ENH-441 (v2.1.36): segment and suppress exactly as detect() does.
  1287. *
  1288. * This used to test each pattern against the whole command, so the two
  1289. * exported entry points answered differently for the same input — `git push
  1290. * origin feature-x && rm -f note.txt` was clean under detect() and destructive
  1291. * here. It has no production callers today, which is precisely why the
  1292. * divergence could sit unnoticed until someone wired it up and inherited the
  1293. * false positives this release removes.
  1294. */
  1295. const shell = splitCommandSegments(stripHeredocBodies(command), 'shell');
  1296. const sql = splitCommandSegments(stripSqlComments(stripHeredocBodies(command)), 'sql');
  1297. return GUARDRAIL_RULES.some((rule) => {
  1298. const segments = rule.segmentOn === 'sql' ? sql : shell;
  1299. return segments.some(
  1300. (s) => rule.pattern.test(s)
  1301. && !(typeof rule.suppressIf === 'function' && rule.suppressIf(s))
  1302. );
  1303. });
  1304. }
  1305. /**
  1306. * Recovery advice that fits the rule that actually fired.
  1307. *
  1308. * ENH-459 (v2.1.36) — the refusal offered the same three lines for every rule,
  1309. * led by "Scope the command to a specific path instead of a broad or root
  1310. * target". That is followable for a recursive delete. It is meaningless for
  1311. * `curl … | sh` (G-015), for `DROP TABLE users` (G-009), for `dd of=/dev/disk0`
  1312. * (G-014) — there is no path to scope. So most refusals ended with advice the
  1313. * user could not act on, which is the exact failure the v2.1.34 comment on
  1314. * G-001 warned about and issue #148 quoted back:
  1315. *
  1316. * "A guard that refuses correct commands and gives unfollowable advice is one
  1317. * people switch off, and then it protects nothing."
  1318. *
  1319. * Scoping advice is now offered only by the two rules where scoping changes the
  1320. * outcome — G-001 and G-013 both grade by target, so narrowing genuinely turns a
  1321. * denial into a confirmation. Everything else gets advice that matches what it
  1322. * refused, and G-014 gets none, because a raw-device write has no safer form
  1323. * worth suggesting.
  1324. *
  1325. * @param {Array<{id: string}>} rules - the matched rules
  1326. * @returns {string[]} advice, most specific first, always non-empty
  1327. */
  1328. function alternativesFor(rules) {
  1329. const ids = new Set((rules || []).map((r) => r && r.id).filter(Boolean));
  1330. const out = [];
  1331. const add = (line) => { if (!out.includes(line)) out.push(line); };
  1332. // Rules that grade by target: narrowing the target is a real remedy.
  1333. if (ids.has('G-001') || ids.has('G-013')) {
  1334. add('Narrow the target to a specific path — a scoped target is confirmed rather than refused');
  1335. }
  1336. if (ids.has('G-008')) {
  1337. add('Name the directory you mean instead of operating on the filesystem root');
  1338. }
  1339. if (ids.has('G-002') || ids.has('G-003') || ids.has('G-004')) {
  1340. add('Target a topic branch, or drop the force flag and reconcile the histories instead');
  1341. }
  1342. if (ids.has('G-005') || ids.has('G-006')) {
  1343. add('Read the value from the environment or a secret store rather than the file itself');
  1344. }
  1345. if (ids.has('G-009') || ids.has('G-010')) {
  1346. add('Run this against a disposable copy of the schema, and keep a dump you can restore from');
  1347. }
  1348. if (ids.has('G-010b')) {
  1349. add('Add a WHERE clause naming the rows you mean to remove');
  1350. }
  1351. if (ids.has('G-011')) {
  1352. add('Drop a single collection or key by name instead of the whole store');
  1353. }
  1354. if (ids.has('G-012') || ids.has('G-015')) {
  1355. add('Download the script to a file, read it, then run the local copy — do not pipe it straight into a shell');
  1356. }
  1357. if (ids.has('G-007')) {
  1358. add('Delete the files you mean by name, or list them first and confirm the set');
  1359. }
  1360. // G-014 (raw device / mkfs) is deliberately absent: there is no scoped form of
  1361. // overwriting a volume, and inventing one would be the unfollowable advice
  1362. // this function exists to remove.
  1363. add('Ask the user for explicit confirmation if this is intended');
  1364. return out;
  1365. }
  1366. /**
  1367. * Generate a human-readable block message for matched rules
  1368. * @param {Array<{id: string, name: string, severity: string, pattern: string}>} rules - Matched rules
  1369. * @returns {string}
  1370. */
  1371. function getBlockMessage(rules) {
  1372. if (!rules || rules.length === 0) {
  1373. return 'No destructive operations detected.';
  1374. }
  1375. const lines = [
  1376. '⛔ Destructive operation blocked by bkit guardrails:',
  1377. ''
  1378. ];
  1379. for (const rule of rules) {
  1380. const severityTag = rule.severity === 'critical' ? '[CRITICAL]'
  1381. : rule.severity === 'high' ? '[HIGH]'
  1382. : '[MEDIUM]';
  1383. lines.push(` ${severityTag} ${rule.id}: ${rule.name}`);
  1384. }
  1385. lines.push('');
  1386. /*
  1387. * ENH-448 (v2.1.36) — this used to read "To proceed, adjust guardrail settings
  1388. * in bkit.config.json or use manual override."
  1389. *
  1390. * Neither route existed. This module never reads bkit.config.json (that string
  1391. * appeared exactly once in the file — inside the message), and `disableRule()`
  1392. * sets a flag `detect()` does not consult, by design (see its own docs). So the
  1393. * message named two recoveries, both imaginary, to a user who had just been
  1394. * refused. Issue #148 called this out, and it is the same class of defect as
  1395. * the rules themselves: a guard giving advice nobody can act on.
  1396. *
  1397. * It shares alternativesFor() with the hook rather than keeping its own copy.
  1398. * The first attempt at this fix rewrote the wording HERE alone and reported the
  1399. * user-facing message as corrected — but this function has no production
  1400. * callers, so nothing changed for anyone. The text users actually see is built
  1401. * in scripts/unified-bash-pre.js. One helper, both call sites, no way for the
  1402. * two to disagree again.
  1403. */
  1404. lines.push('Ways forward:');
  1405. for (const alt of alternativesFor(rules)) lines.push(` - ${alt}`);
  1406. lines.push(' - Split a chained command: each segment is judged on its own.');
  1407. lines.push('');
  1408. lines.push('These rules cannot be switched off at runtime — that is deliberate, not an oversight.');
  1409. return lines.join('\n');
  1410. }
  1411. /**
  1412. * Get the default action for a specific rule
  1413. * @param {string} ruleId - Rule ID (e.g., 'G-001')
  1414. * @returns {'deny'|'ask'|'allow'|null}
  1415. */
  1416. function getRuleAction(ruleId) {
  1417. const rule = GUARDRAIL_RULES.find(r => r.id === ruleId);
  1418. return rule ? rule.defaultAction : null;
  1419. }
  1420. /**
  1421. * Get all guardrail rules
  1422. * @returns {GuardrailRule[]}
  1423. */
  1424. function getRules() {
  1425. return GUARDRAIL_RULES.map(r => ({
  1426. id: r.id,
  1427. name: r.name,
  1428. severity: r.severity,
  1429. defaultAction: r.defaultAction,
  1430. pattern: r.pattern.source
  1431. }));
  1432. }
  1433. /**
  1434. * Add a custom guardrail rule at runtime
  1435. * @param {{ id: string, name: string, severity: string, pattern: RegExp, defaultAction: string }} rule
  1436. */
  1437. function addCustomRule(rule) {
  1438. if (!rule || !rule.id || !rule.pattern) return;
  1439. const existing = GUARDRAIL_RULES.find(r => r.id === rule.id);
  1440. if (!existing) {
  1441. GUARDRAIL_RULES.push(rule);
  1442. }
  1443. }
  1444. /**
  1445. * Mark a guardrail rule disabled — WITHOUT removing it from detection.
  1446. *
  1447. * ENH-449 (v2.1.36) — read the name and you expect the rule to stop firing. It
  1448. * does not, and that is intentional: `detect()` never consults `_disabled`, so a
  1449. * rule cannot be switched off from inside a running session. The property is
  1450. * locked by test/security/integrity-verification.test.js IV-09, whose assertion
  1451. * says so explicitly.
  1452. *
  1453. * The flag is therefore an annotation — it records that someone asked — and this
  1454. * function is retained for that and for API compatibility. It has no production
  1455. * callers. Do not "fix" the flag to be honoured without deliberately overturning
  1456. * IV-09; the immutability is the security property, and the false-positive
  1457. * pressure that motivates an off-switch is answered by rule precision instead
  1458. * (see splitCommandSegments and the grading helpers above).
  1459. *
  1460. * @param {string} ruleId - Rule ID to annotate
  1461. * @param {string} [reason] - Reason recorded alongside the annotation
  1462. * @returns {boolean} True if the rule exists (NOT that detection changed)
  1463. */
  1464. function disableRule(ruleId, reason) {
  1465. const rule = GUARDRAIL_RULES.find(r => r.id === ruleId);
  1466. if (rule) {
  1467. rule._disabled = true;
  1468. rule._disableReason = reason || 'unknown';
  1469. return true;
  1470. }
  1471. return false;
  1472. }
  1473. module.exports = {
  1474. detect,
  1475. isDestructive,
  1476. getBlockMessage,
  1477. // ENH-459 (v2.1.36): shared with scripts/unified-bash-pre.js so the advice a
  1478. // user is given matches the rule that refused them, and so the hook and this
  1479. // module cannot drift into offering different remedies for the same block.
  1480. alternativesFor,
  1481. getRuleAction,
  1482. getRules,
  1483. addCustomRule,
  1484. disableRule,
  1485. stripHeredocBodies,
  1486. // ENH-440/446 (v2.1.36): exported so their behaviour can be asserted directly
  1487. // rather than only inferred from detect() outcomes. The `--command` regression
  1488. // below was a helper-level defect that a detect()-only test would have found
  1489. // only by luck.
  1490. splitCommandSegments,
  1491. stripSqlComments,
  1492. // ENH-470 (v2.1.37): same reason as the two above — a predicate that decides
  1493. // whether a rule stands down is worth asserting directly, not only through the
  1494. // outcome of detect().
  1495. isNotACommandLevelDelete,
  1496. isInertSearchInvocation,
  1497. GUARDRAIL_RULES
  1498. };
lib/defense/heredoc-detector.js · Bundled script · 536 lines · 2 findings marked
  1. /**
  2. * HeredocDetector — Defense Layer pure-fn detector for heredoc-pipe permission bypass.
  3. *
  4. * Design Ref: docs/sprint/v2114/design.md §3.3
  5. * Plan SC: ENH-310 Heredoc Pipe Bypass Defense.
  6. * Differentiation: bkit moat #6 — CC permission system regression self-defense.
  7. *
  8. * Background:
  9. * CC #58904 (regression of #48518, present v2.1.73 through v2.1.141, ~68
  10. * unfixed versions) lets a Bash command of the form
  11. *
  12. * cat <<'EOF' | bash
  13. * rm -rf /
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 13 on GitHub
  14. * EOF
  15. *
  16. * bypass CC's permission system: CC inspects only the outer `cat` token,
  17. * never the heredoc body or its pipe-target. bkit's PreToolUse defense
  18. * stack inherited the same blind spot — `scripts/unified-bash-pre.js`
  19. * substring patterns and `lib/control/destructive-detector.js` G-001~G-011
  20. * evaluate only top-level argv. This module closes that gap.
  21. *
  22. * Responsibility:
  23. * detect(command) inspects an entire Bash command string for the
  24. * `heredoc + (command-substitution | pipe-to-shell | eval/source)`
  25. * combination that defines the bypass. It returns a structured verdict
  26. * so the calling hook can emit a deterministic deny with safe-alternative
  27. * suggestions via `outputBlockWithContext`.
  28. *
  29. * Design invariants:
  30. * 1) Pure function — no fs, child_process, http, network, env reads.
  31. * Domain-grade purity even though this lives in Defense Layer.
  32. * 2) Conservative false-positive policy: lone `<<` heredoc returns
  33. * severity='warning' (audit-only, allow), never 'critical'. Only the
  34. * combination with `$(`, backtick, or pipe-to-shell promotes to
  35. * severity='critical' (deny).
  36. * 3) 30+ patterns categorized by attack vector (sub / pipe-shell /
  37. * eval-source / sudo). PATTERNS array is Object.freeze'd so callers
  38. * cannot mutate the policy at runtime.
  39. * 4) Deterministic ordering: critical patterns are evaluated before
  40. * warning patterns, then short-circuit on first critical match.
  41. *
  42. * Calling site (Step 6, scripts/unified-bash-pre.js):
  43. * const { detect } = require('../lib/defense/heredoc-detector');
  44. * const verdict = detect(command);
  45. * if (verdict.matched && verdict.severity === 'critical') {
  46. * outputBlockWithContext(verdict.reason, {
  47. * additionalContext: verdict.alternatives.join('\n'),
  48. * }, 'PreToolUse');
  49. * }
  50. *
  51. * @module lib/defense/heredoc-detector
  52. * @version 2.1.14
  53. * @since 2.1.14
  54. * @layer Defense
  55. * @enh ENH-310
  56. * @differentiation #6
  57. */
  58. 'use strict';
  59. /**
  60. * @typedef {'critical'|'warning'|null} Severity
  61. * critical — heredoc COMBINED with a payload-execution vector. Hook MUST deny.
  62. * warning — heredoc present but no execution vector detected. Hook MAY allow + audit.
  63. * null — no heredoc detected; out of scope for this detector.
  64. */
  65. /**
  66. * @typedef {Object} HeredocVerdict
  67. * @property {boolean} matched — true when at least one pattern matched
  68. * @property {Severity} severity — see Severity typedef
  69. * @property {string|null} pattern — regex source string of the matched pattern (debugging)
  70. * @property {string|null} vector — semantic vector: 'sub'|'pipe-shell'|'eval-source'|'sudo'|'lone-heredoc'|null
  71. * @property {string} reason — human-readable explanation (for hook deny message)
  72. * @property {string[]} alternatives — safe alternative suggestions for the user/model
  73. */
  74. /**
  75. * Critical patterns: heredoc combined with payload-execution vector.
  76. *
  77. * Conservative regex design: each pattern requires the explicit
  78. * `<<` (heredoc start) AND an unambiguous execution token. Single
  79. * tokens (e.g. lone `$(`) never produce critical here — that is
  80. * destructive-detector territory.
  81. *
  82. * Pattern source strings are kept on each entry so the verdict can
  83. * report which pattern matched (debug + audit-log richness).
  84. */
  85. const CRITICAL_PATTERNS = Object.freeze([
  86. // -------- vector: 'sub' (heredoc inside $() command substitution) --------
  87. {
  88. vector: 'sub',
  89. re: /\$\(\s*[\w./-]*\s*<<-?\s*['"]?\w+['"]?[\s\S]*?\)/,
  90. description: '$(cmd <<TAG ... TAG) — heredoc inside $() substitution',
  91. },
  92. {
  93. vector: 'sub',
  94. re: /`\s*[\w./-]*\s*<<-?\s*['"]?\w+['"]?[\s\S]*?`/,
  95. description: '`cmd <<TAG ... TAG` — heredoc inside backtick substitution',
  96. },
  97. {
  98. vector: 'sub',
  99. re: /\$\(\s*cat\s+<<-?\s*['"]?\w+['"]?/,
  100. description: '$(cat <<TAG …) — bypass via cat heredoc + substitution',
  101. },
  102. {
  103. vector: 'sub',
  104. re: /`\s*cat\s+<<-?\s*['"]?\w+['"]?/,
  105. description: '`cat <<TAG …` — bypass via cat heredoc + backtick',
  106. },
  107. /*
  108. * -------- vector: 'pipe-shell' (heredoc piped to interpreter) -----------
  109. *
  110. * ENH-390 (v2.1.33): one tolerant pattern replaces eight literal ones.
  111. *
  112. * Each rule used to be `\|\s*\bbash\b` — the interpreter name had to follow
  113. * the pipe immediately. Every ordinary way of writing the same command
  114. * therefore fell through to the WARNING tier, and `scripts/unified-bash-pre.js:325`
  115. * lets warnings through with an audit entry only. Measured before the fix,
  116. * all of these executed:
  117. *
  118. * cat <<EOF … EOF | /bin/bash -> warning (allowed)
  119. * cat <<EOF … EOF | /usr/bin/sh -> warning (allowed)
  120. * cat <<EOF … EOF | nice bash -> warning (allowed)
  121. * cat <<EOF … EOF | command bash -> warning (allowed)
  122. * cat <<EOF … EOF | "bash" -> warning (allowed)
  123. * cat <<EOF … EOF | \bash -> warning (allowed)
  124. *
  125. * against `… | bash` -> critical (blocked). So bkit differentiation #6, the
  126. * heredoc bypass defense, was defeated by an absolute path.
  127. *
  128. * The delimiter also widened from `\w+` to `[^\s|;&<>'"]+`, so `<<'EOF-1'`
  129. * and `<<EOF.1` are recognised as delimiters rather than parsed as `EOF`
  130. * plus body text.
  131. */
  132. {
  133. vector: 'pipe-shell',
  134. re: new RegExp(
  135. '<<-?\\s*[\'"]?[^\\s|;&<>\'"]+[\'"]?[\\s\\S]*?'
  136. // the pipe, then any stack of harmless wrappers…
  137. + '\\|\\s*(?:(?:command|exec|env|nice|nohup|time|xargs)\\s+(?:-\\S+\\s+)*)*'
  138. // …optional quote/backslash obfuscation, optional absolute or relative path…
  139. + '[\'"\\\\]*(?:[\\w./-]*/)?'
  140. // …and the interpreter itself.
  141. + '(?:bash|sh|zsh|ksh|dash|ash|fish|csh|tcsh|python[\\d.]*|perl|ruby|node|deno|bun)\\b',
  142. ),
  143. description: 'heredoc | interpreter — pipe to a shell/interpreter (path, quote, backslash and wrapper forms included)',
  144. },
  145. {
  146. // An interpreter chosen at runtime cannot be inspected, so it is treated as
  147. // the most dangerous case rather than the least. Previously `| $SHELL`
  148. // matched no interpreter rule at all and landed in the warning tier.
  149. vector: 'pipe-shell',
  150. re: /<<-?\s*['"]?[^\s|;&<>'"]+['"]?[\s\S]*?\|\s*(?:\$\{?\w+\}?|`[^`]*`|\$\([^)]*\))/,
  151. description: 'heredoc | $VAR — pipe to an interpreter resolved at runtime (unknown target)',
  152. },
  153. {
  154. // A wrapper on its own is still an execution vector: `… | exec` and
  155. // `… | env` both run the piped content. The consolidated interpreter rule
  156. // above requires an interpreter AFTER the wrapper, so these standalone
  157. // forms need their own rule — dropping them was a coverage regression the
  158. // v2.1.14 suite (CR-07/CR-08) caught immediately.
  159. vector: 'pipe-shell',
  160. re: /<<-?\s*['"]?[^\s|;&<>'"]+['"]?[\s\S]*?\|\s*(?:command|exec|env|nice|nohup|time|xargs)\b/,
  161. description: 'heredoc | exec/env/... — pipe to an execution wrapper',
  162. },
  163. // -------- vector: 'eval-source' (heredoc piped to eval/source/.) --------
  164. {
  165. vector: 'eval-source',
  166. re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\beval\b/,
  167. description: 'heredoc | eval — pipe to eval',
  168. },
  169. {
  170. vector: 'eval-source',
  171. re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\bsource\b/,
  172. description: 'heredoc | source — pipe to source',
  173. },
  174. {
  175. vector: 'eval-source',
  176. re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\.\s/,
  177. description: 'heredoc | . path — pipe to POSIX `.` (source)',
  178. },
  179. // -------- vector: 'sudo' (heredoc piped to sudo) ------------------------
  180. {
  181. vector: 'sudo',
  182. re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\bsudo\b/,
  183. description: 'heredoc | sudo — escalated pipe',
  184. },
  185. {
  186. vector: 'sudo',
  187. re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\bdoas\b/,
  188. description: 'heredoc | doas — OpenBSD escalated pipe',
  189. },
  190. // -------- vector: 'sub' with shell-as-arg ($(bash <<EOF …)) -------------
  191. {
  192. vector: 'sub',
  193. re: /\$\(\s*(?:bash|sh|zsh|ksh|dash|fish)\s+-c\s*['"]?<<-?\s*['"]?\w+['"]?/,
  194. description: '$(bash -c "<<TAG …") — substitution wrapping shell -c heredoc',
  195. },
  196. {
  197. vector: 'sub',
  198. re: /\$\(\s*(?:bash|sh|zsh|ksh|dash|fish)\s+<<-?\s*['"]?\w+['"]?/,
  199. description: '$(bash <<TAG …) — substitution wrapping shell heredoc',
  200. },
  201. // -------- vector: 'direct-shell' (interpreter consumes the heredoc as code) --
  202. /*
  203. * ENH-461 (v2.1.36) — the most direct execution vector was missing.
  204. *
  205. * The list above covers the heredoc reaching a shell through a substitution
  206. * (`$(bash <<TAG)`), a pipe (`<<TAG | sh`), or xargs. It did not cover the
  207. * plainest spelling of all:
  208. *
  209. * bash <<'EOF'
  210. * rm -rf /
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 219 on GitHub
  211. * EOF
  212. *
  213. * Measured on v2.1.35 and still on this branch before this rule: the hook
  214. * ALLOWED it. destructive-detector elides heredoc bodies before matching, by
  215. * design, so G-001 never sees the delete; and this file graded the form
  216. * `warning`, which the hook audits and permits. Between the two, the payload
  217. * executed and nothing objected. Found by running ordinary commands through
  218. * the real hook rather than through detect() — a module-level test could not
  219. * have seen it, because neither module is wrong on its own.
  220. *
  221. * A script argument means the heredoc is stdin DATA, not code
  222. * (`bash deploy.sh <<EOF`), so the pattern allows only flags between the
  223. * interpreter and `<<`. The command must also start a command — after a
  224. * separator or at the beginning — so `echo bash <<EOF` stays a warning.
  225. *
  226. * Scope is shells, matching the rest of this table. `python3 - <<'PY'` is a
  227. * routine, legitimate way to run a script and is deliberately not included;
  228. * widening to every interpreter would refuse work people do every day, which
  229. * is the failure this release exists to remove.
  230. */
  231. {
  232. vector: 'direct-shell',
  233. re: /(?:^|[\n;|&(])\s*(?:bash|sh|zsh|ksh|dash|fish)\s+(?:-[a-zA-Z]+\s+)*<<-?\s*['"]?\w+/,
  234. description: 'bash <<TAG … — interpreter executes the heredoc body directly',
  235. },
  236. // -------- vector: 'pipe-shell' (here-string + shell, less common variant)
  237. {
  238. vector: 'pipe-shell',
  239. re: /<<<\s*[\s\S]*?\|\s*\b(?:bash|sh|zsh|ksh|dash|fish|exec)\b/,
  240. description: 'here-string (<<<) | shell — variant of heredoc-pipe',
  241. },
  242. // -------- vector: 'pipe-shell' (heredoc → curl|bash anti-pattern) --------
  243. {
  244. vector: 'pipe-shell',
  245. re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\bxargs\b\s+(?:bash|sh|zsh|ksh|dash|fish|exec)\b/,
  246. description: 'heredoc | xargs (bash|sh|…) — xargs-shell escalation',
  247. },
  248. ]);
  249. /**
  250. * Warning patterns: heredoc present but no execution vector detected.
  251. * Returns severity='warning' (allow + audit). This list intentionally
  252. * captures only the heredoc-start surface so audit logs can attribute
  253. * the pattern without triggering false-positive denies.
  254. */
  255. const WARNING_PATTERNS = Object.freeze([
  256. {
  257. vector: 'lone-heredoc',
  258. re: /<<-?\s*['"]?\w+['"]?/,
  259. description: '<<TAG — lone heredoc start (no exec vector detected)',
  260. },
  261. {
  262. vector: 'lone-heredoc',
  263. re: /<<<\s*\S/,
  264. description: '<<< — here-string (no exec vector detected)',
  265. },
  266. ]);
  267. /** Safe alternatives to suggest when severity='critical'. */
  268. const CRITICAL_ALTERNATIVES = Object.freeze([
  269. 'Write the script to a file first, audit it, then run with explicit permission: bkit \'cat > script.sh && cat script.sh && bash script.sh\' (3 separate tool calls)',
  270. 'Inline a single safe command without heredoc: e.g. `echo "..." | grep foo` instead of `<<EOF … EOF | bash`',
  271. 'Use bkit checkpoint + manual review: /pdca checkpoint create → review the planned changes → confirm before executing',
  272. ]);
  273. /** Safe alternatives to suggest when severity='warning'. */
  274. const WARNING_ALTERNATIVES = Object.freeze([
  275. 'Heredoc usage is acceptable for static input (e.g. SQL, JSON, plain text). Verify no `$(`/backtick/pipe-to-shell follows the heredoc.',
  276. ]);
  277. /**
  278. * Detect heredoc-pipe bypass attempt in a Bash command string.
  279. *
  280. * Pure function — same input always returns the same verdict. No IO.
  281. * Returns a structured verdict; callers (hooks) own the decision to
  282. * deny / allow / audit.
  283. *
  284. * @param {string|unknown} command
  285. * @returns {HeredocVerdict}
  286. */
  287. /**
  288. * Replace the body of every QUOTED heredoc with a placeholder line, keeping the
  289. * opener and terminator.
  290. *
  291. * Quoted delimiter => the shell expands nothing inside the body, so the body is
  292. * inert data on a program's stdin. Unquoted delimiter => `$(...)` and backticks
  293. * inside the body DO execute, so those bodies are deliberately left untouched.
  294. *
  295. * @param {string} command
  296. * @returns {string}
  297. */
  298. function elideQuotedHeredocBodies(command) {
  299. if (!command.includes('<<')) return command;
  300. const lines = command.split('\n');
  301. const out = [];
  302. let delimiter = null;
  303. let terminated = true;
  304. for (const line of lines) {
  305. if (delimiter === null) {
  306. out.push(line);
  307. // Quoted forms only: <<'EOF' / <<-'EOF' / <<"EOF" / <<-"EOF"
  308. const m = line.match(/<<-?\s*(?:'([^']+)'|"([^"]+)")/);
  309. if (m) { delimiter = m[1] || m[2]; terminated = false; }
  310. continue;
  311. }
  312. /*
  313. * The terminator line is kept WHOLE, not just recognised. A known bypass
  314. * writes the pipe on that line — `EOF-1 | bash` — so discarding anything
  315. * after the delimiter would delete the exec vector along with the body.
  316. * The line is matched by prefix rather than equality for the same reason.
  317. */
  318. if (line.trim() === delimiter || line.trimStart().startsWith(delimiter)) {
  319. out.push('__BKIT_HEREDOC_BODY__');
  320. out.push(line);
  321. delimiter = null;
  322. terminated = true;
  323. }
  324. }
  325. /*
  326. * An unterminated heredoc means the delimiter was never found, so there is no
  327. * body boundary to trust. Returning the original text keeps every pattern
  328. * looking at everything — this helper may only ever remove noise, never
  329. * remove evidence.
  330. */
  331. if (!terminated) return command;
  332. return out.join('\n');
  333. }
  334. /**
  335. * Split a command into the regions a heredoc pattern may legitimately span.
  336. *
  337. * v2.1.34. The `pipe-shell` pattern is
  338. * `<<-?\s*['"]?TAG['"]?[\s\S]*?\|\s*<interpreter>` — and `[\s\S]*?` crosses
  339. * newlines, terminator lines, and any number of subsequent commands. So a
  340. * heredoc that opened and closed cleanly, followed later by a completely
  341. * unrelated pipe, was graded CRITICAL.
  342. *
  343. * Reproduced against this very session: the block
  344. *
  345. * python3 - <<'PY'
  346. * ...
  347. * PY
  348. * echo done | python3 -c "..."
  349. *
  350. * was refused as "pipe to a shell/interpreter", though the heredoc closed two
  351. * lines before the pipe and the two share nothing but a process. Exactly the
  352. * defect class this release fixes elsewhere — a pattern reading past the
  353. * construct it is analysing — sitting in a guard that refuses commands.
  354. *
  355. * A terminated heredoc becomes one region, opener line through terminator line
  356. * INCLUSIVE, because both known exec vectors live on those lines: `<<EOF | bash`
  357. * on the opener and `EOF-1 | bash` on the terminator. Everything outside is a
  358. * separate region. An UNTERMINATED heredoc yields the whole text as one region:
  359. * with no trustworthy boundary the guard must keep seeing everything.
  360. *
  361. * @param {string} text
  362. * @returns {string[]} regions to match independently
  363. */
  364. function heredocRegions(text) {
  365. const lines = text.split('\n');
  366. const regions = [];
  367. let outside = [];
  368. let current = null;
  369. let delimiter = null;
  370. /*
  371. * A line that BEGINS with a shell continuation token belongs to the command
  372. * that just ended, not to a new one.
  373. *
  374. * Without this the region closes at the terminator and the form
  375. *
  376. * cat <<'EOF'
  377. * …
  378. * EOF
  379. * | bash
  380. *
  381. * splits the pipe away from its heredoc — twenty-three assertions in
  382. * tests/qa/v2114-defense-heredoc.test.js exist for exactly that shape, and the
  383. * first cut of this split turned all of them from critical to warning. A
  384. * region that ends one token early is a hole, and closing a false positive by
  385. * opening a hole is not a fix.
  386. *
  387. * The distinguishing test is whether the next line CONTINUES the pipeline or
  388. * STARTS something: `| bash` continues, `echo done | python3 -c …` starts.
  389. */
  390. const CONTINUATION = /^\s*(?:[|)&;]|\|\||&&|>>?|<)/;
  391. let closing = false;
  392. for (const line of lines) {
  393. if (closing) {
  394. if (CONTINUATION.test(line)) { current.push(line); continue; }
  395. regions.push(current.join('\n'));
  396. current = null;
  397. closing = false;
  398. // fall through: this line starts a new region
  399. }
  400. if (delimiter === null) {
  401. const m = line.match(/<<-?\s*['"]?([^\s|;&<>'"]+)['"]?/);
  402. if (m) {
  403. if (outside.length) { regions.push(outside.join('\n')); outside = []; }
  404. delimiter = m[1];
  405. current = [line];
  406. } else {
  407. outside.push(line);
  408. }
  409. continue;
  410. }
  411. current.push(line);
  412. if (line.trim() === delimiter || line.trimStart().startsWith(delimiter)) {
  413. delimiter = null;
  414. closing = true; // keep absorbing continuation lines — see below
  415. }
  416. }
  417. // Unterminated: no boundary to trust, so nothing may be split apart.
  418. if (delimiter !== null) return [text];
  419. if (closing && current) regions.push(current.join('\n'));
  420. if (outside.length) regions.push(outside.join('\n'));
  421. return regions.length ? regions : [text];
  422. }
  423. function detect(command) {
  424. if (typeof command !== 'string' || command.length === 0) {
  425. return emptyVerdict();
  426. }
  427. /*
  428. * v2.1.34: elide the bodies of QUOTED heredocs before matching.
  429. *
  430. * This module's subject is the command STRUCTURE — a heredoc combined with a
  431. * pipe to an interpreter, a command substitution, or eval. Body text is not
  432. * structure. Matching against it produced refusals that were indistinguishable
  433. * from real findings: during work on this release, `python3 - <<'PY' … PY` was
  434. * blocked as "pipe to an interpreter resolved at runtime (unknown target)"
  435. * when the interpreter was the literal `python3` and the trigger was the
  436. * string `Write|Edit` sitting in the body.
  437. *
  438. * Only QUOTED delimiters (`<<'EOF'`, `<<"EOF"`) are elided. With a quoted
  439. * delimiter the shell performs no expansion, so the body genuinely is inert
  440. * data. An UNQUOTED heredoc still expands `$(...)` and backticks inside the
  441. * body at runtime — that is a real execution vector and its body is left fully
  442. * visible to every pattern below. The opener and terminator lines survive in
  443. * both cases, so a heredoc piped into a shell is still matched exactly as
  444. * before.
  445. */
  446. const bodyElided = elideQuotedHeredocBodies(command);
  447. // Strip escaped sequences that should not count toward matching:
  448. // \$\( and \` are escaped substitutions — treat as inert.
  449. // \\<< is an escaped heredoc start — treat as inert.
  450. const stripped = bodyElided
  451. .replace(/\\\$\(/g, '__BKIT_ESCAPED_DOLLAR_PAREN__')
  452. .replace(/\\`/g, '__BKIT_ESCAPED_BACKTICK__')
  453. .replace(/\\<</g, '__BKIT_ESCAPED_HEREDOC__');
  454. /*
  455. * Critical patterns are evaluated per REGION, not across the whole command —
  456. * see `heredocRegions`. A pattern that may span `[\s\S]*?` must not span
  457. * from one command into an unrelated one.
  458. */
  459. const regions = heredocRegions(stripped);
  460. // Evaluate critical patterns first; short-circuit on first hit.
  461. for (const p of CRITICAL_PATTERNS) {
  462. if (regions.some((r) => { p.re.lastIndex = 0; return p.re.test(r); })) {
  463. return {
  464. matched: true,
  465. severity: 'critical',
  466. pattern: p.re.source,
  467. vector: p.vector,
  468. reason: `bkit ENH-310 heredoc-bypass guard: ${p.description}`,
  469. alternatives: CRITICAL_ALTERNATIVES.slice(),
  470. };
  471. }
  472. }
  473. // Then warning patterns (heredoc present but no exec vector).
  474. for (const p of WARNING_PATTERNS) {
  475. if (p.re.test(stripped)) {
  476. return {
  477. matched: true,
  478. severity: 'warning',
  479. pattern: p.re.source,
  480. vector: p.vector,
  481. reason: `bkit ENH-310 heredoc audit: ${p.description}`,
  482. alternatives: WARNING_ALTERNATIVES.slice(),
  483. };
  484. }
  485. }
  486. return emptyVerdict();
  487. }
  488. function emptyVerdict() {
  489. return {
  490. matched: false,
  491. severity: null,
  492. pattern: null,
  493. vector: null,
  494. reason: '',
  495. alternatives: [],
  496. };
  497. }
  498. module.exports = {
  499. detect,
  500. // Exposed for contract tests + observability — DO NOT mutate at runtime
  501. // (Object.freeze enforces immutability; mutation in non-strict mode is silent,
  502. // in strict mode throws).
  503. CRITICAL_PATTERNS,
  504. WARNING_PATTERNS,
  505. CRITICAL_ALTERNATIVES,
  506. WARNING_ALTERNATIVES,
  507. };

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.