bkit-marketplace
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.
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
Markdown
[](/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)
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "bkit-marketplace",
- "version": "2.1.41",
- "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).",
- "owner": {
- "name": "DubDubDub Corp.",
- "email": "biz@ww-w.ai",
- "url": "https://ww-w.ai"
- },
- "plugins": [
- {
- "name": "bkit-starter",
- "description": "Korean learning guide for Claude Code beginners. No programming experience required. Includes 4 learning commands.",
- "version": "1.0.0",
- "author": {
- "name": "DubDubDub Corp.",
- "email": "biz@ww-w.ai"
- },
- "repository": "https://github.com/ww-w-ai/bkit-starter",
- "source": {
- "source": "url",
- "url": "https://github.com/ww-w-ai/bkit-starter.git"
- },
- "category": "learning",
- "keywords": [
- "beginner",
- "korean",
- "tutorial",
- "starter",
- "learning"
- ]
- },
- {
- "name": "bkit",
- "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
- "author": {
- "name": "DubDubDub Corp.",
- "email": "biz@ww-w.ai"
- },
- "version": "2.1.41",
- "repository": "https://github.com/ww-w-ai/bkit-claude-code",
- "source": {
- "source": "url",
- "url": "https://github.com/ww-w-ai/bkit-claude-code.git"
- },
- "category": "development",
- "keywords": [
- "vibecoding",
- "pdca",
- "development-pipeline",
- "ai-native",
- "agentic",
- "agent",
- "automation",
- "workflow",
- "fullstack",
- "multilingual",
- "baas",
- "enterprise"
- ]
- }
- ]
- }
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)
- # bkit — AI Native Development OS
- > A Claude Code plugin that verifies AI-generated code against its own design specs.
- **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.
- [](https://opensource.org/licenses/Apache-2.0)
- [](https://code.claude.com)
- [](CHANGELOG.md)
- [](https://ww-w.ai)
- > **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).
- ---
- ## Who bkit is for
- | You are… | bkit gives you |
- |---|---|
- | 🌱 **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. |
- | 👤 **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. |
- | 👥 **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. |
- | 🌐 **Non-English speaker** | 8-language auto-detection. Type *"로그인 기능 만들어줘"* or *"作成新功能"* and bkit picks the right command for you. |
- ## What you'll achieve with bkit
- > **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.
- | Without bkit | With bkit |
- |---|---|
- | 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). |
- | 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, …) |
- | 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 |
- | 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. |
- | 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. |
- ## The 4-step experience
- This is the canonical workflow when you use bkit. You describe a release; bkit handles the rest.
- ```mermaid
- flowchart TB
- You(["You: describe the release"])
- You --> S1["Step 1<br/>/sprint master-plan my-release<br/>--features auth, billing, reports"]
- S1 --> Auto1["bkit auto-action<br/>• sprint-master-planner agent investigates code + web in depth<br/>• Splits features into context-budgeted Sprints (≤ 75K tokens each)<br/>• Writes the master plan with Context Anchor"]
- Auto1 --> S2["Step 2<br/>You approve the plan"]
- S2 --> Auto2["bkit auto-action<br/>• Every sprint registered in Task Management<br/>• Memory saved — survives session clear"]
- Auto2 --> S3["Step 3<br/>/sprint start sprint-1"]
- 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."]
- Auto3 --> Gate{"All quality<br/>gates pass?"}
- Gate -- "no, auto-fix" --> Repair["pdca-iterator self-repair<br/>(max 5 cycles)"]
- Repair --> Gate
- Gate -- "yes" --> Done(["Release-ready code + docs"])
- Ctrl["Step 4<br/>/control level 0..4"] -.->|"set how much<br/>runs unattended"| Auto1
- Ctrl -.->|"applies"| Auto3
- style You fill:#e3f2fd
- style S1 fill:#fff3e0
- style S2 fill:#fff8e1
- style S3 fill:#fff3e0
- style Auto3 fill:#fce4ec
- style Repair fill:#ffe0b2
- style Done fill:#c8e6c9
- style Ctrl fill:#f3e5f5
- ```
- ### Step 1 — Plan the release in depth
- You type: `/sprint master-plan my-release --features auth, billing, reports`.
- 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).
- 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.
- ### Step 2 — Approve, register, remember
- 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.
- 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.
- ### Step 3 — Auto-run each sprint through PDCA
- You type: `/sprint start sprint-1`.
- 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**:
- | Phase | What runs | Output |
- |---|---|---|
- | **PRD / Plan** | `pm-lead` orchestrates 4 PM agents (discovery, strategy, research, prd) with 43 frameworks | Comprehensive PRD + plan with Context Anchor |
- | **Design** | `cto-lead` proposes 3 architecture options; you pick one (the only required user input) | Detailed design doc |
- | **Do** | `/pdca team` spawns 4–6 specialist agents in parallel (developer, qa, frontend, backend, security, architect) | Working code |
- | **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 |
- | **QA** | `qa-lead` runs 4 QA agents through L1–L5 tests + dataFlow integrity (S1 gate, 7-layer hop check) | QA report |
- | **Report** | `report-generator` writes the completion report | Final report with KPI + lessons learned |
- **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.
- ### Step 4 — Govern with one dial
- `/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.
- | Level | What it means |
- |---|---|
- | **L0 Manual** | Ask me at every phase. Best for your first sprint — inspect each output. |
- | **L2 Semi-Auto** (default) | Plan/Design/Do auto; ask me on QA and Report. |
- | **L4 Full-Auto** | Wake me when the sprint is done. Pauses only on a quality gate failure or one of 4 auto-pause triggers. |
- 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.
- ## How the bkit author actually uses bkit
- 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.
- ### Step A — Use Claude Code as a thinking amplifier *before* the master plan
- 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.**
- 1. Open a fresh Claude Code session.
- 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.
- 3. Have it investigate — read your repo, search the web, surface edge cases you hadn't considered.
- 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.
- 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.
- ### Step B — Hand the rest to Trust Level 4
- 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:
- | Release size | What you type | What happens |
- |---|---|---|
- | **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. |
- | **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. |
- **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.
- **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.
- ## The three commands
- | Command | When to use | What it spawns | Output |
- |---|---|---|---|
- | **`/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 |
- | **`/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 |
- | **`/control`** | Anytime — set autonomy | — | Updates Trust Level scope; affects both `/sprint` and `/pdca` |
- ## How bkit closes the AI-coding gap — Context Engineering
- 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.
- | The AI coding problem | bkit's Context Engineering answer |
- |---|---|
- | AI hallucinates because it doesn't know your conventions | 44 skills (PDCA, Sprint, PM frameworks, …) auto-injected based on intent |
- | AI loses focus as the session grows | Memory + Task Management resumes across sessions; Sprints are context-budgeted |
- | AI ships code that drifts from the spec | 11 Quality Gates + `gap-detector` measurement + `pdca-iterator` auto-repair |
- | You only catch bugs at PR review | Phase-by-phase gating: drift is caught at every transition, not at the end |
- | You need to remember the right command | 8-language auto-trigger + intent-router; type *"login 만들어줘"* or *"build login"* and bkit picks the path |
- | AI sessions are ephemeral; no audit trail | Audit log + Token Ledger + `Docs = Code` philosophy: every decision is on disk |
- ## bkit's three philosophies (from [`bkit-system/philosophy/core-mission.md`](bkit-system/philosophy/core-mission.md))
- | Principle | What it means for you |
- |---|---|
- | **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. |
- | **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. |
- | **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. |
- ## Quick start
- ```bash
- # 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).
- ## Quality gates — the safety net explained
- 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:
- | Gate | What it measures | If it fails |
- |---|---|---|
- | **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) |
- | **M3 critical issues** | Security or correctness bugs flagged by `code-analyzer` | Any critical → workflow pauses, you decide |
- | **S1 dataFlow integrity** | 7-layer check: UI → Client → API → Validation → DB → Response → Client → UI | Below 85 % → 7 hops re-verified one by one |
- | **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) |
- Full M1–M10 + S1 catalog in [README-FULL.md §5](README-FULL.md#5-quality-gates--self-repair).
- ## Architecture at a glance
- 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`.
- 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.
- Full architecture deep-dive: [README-FULL.md §9](README-FULL.md#9-architecture).
- ## Documentation
- | Path | What's there |
- |---|---|
- | [README-FULL.md](README-FULL.md) | Full command reference, deep workflow internals, agent teams, architecture, Skill Evals |
- | [CHANGELOG.md](CHANGELOG.md) | Release history (single source of truth — latest release: v2.1.41) |
- | [CUSTOMIZATION-GUIDE.md](CUSTOMIZATION-GUIDE.md) | Override any bkit component in your `.claude/` directory |
- | [AI-NATIVE-DEVELOPMENT.md](AI-NATIVE-DEVELOPMENT.md) | The 6 AI-Native principles and how bkit implements them |
- | [`bkit-system/philosophy/`](bkit-system/philosophy/) | Core mission, Context Engineering, PDCA methodology, AI-Native principles |
- | [`docs/06-guide/sprint-management.guide.md`](docs/06-guide/sprint-management.guide.md) | Sprint Management deep-dive (English) |
- | [`docs/06-guide/sprint-migration.guide.md`](docs/06-guide/sprint-migration.guide.md) | PDCA ↔ Sprint migration mapping (English) |
- ## 🌟 Real User Hall of Fame
- bkit's quality is measured by how well it responds to real users running
- bkit in production on their own projects. This section recognizes
- **external dogfooders** whose precise bug reports + reproduction scripts
- have been absorbed directly into bkit's regression test suite
- (`test/e2e/external-dogfood/`).
- ### v2.1.19 (2026-05-30 — first entry)
- - **[@pruge (James Kim)](https://github.com/pruge)** — `dandi-village-ledger`
- project. 10 GitHub issues over 1.5 days (#92–#107) driving bkit v2.1.17,
- v2.1.18 closes + the entire v2.1.19 Quality Maturation Sprint. 5 reproduction
- scenarios absorbed as E2E tests at `test/e2e/external-dogfood/dandi-*.test.js`.
- See [`docs/external-dogfooders/pruge.md`](docs/external-dogfooders/pruge.md)
- for the full contribution archive. **Thank you for trusting bkit with
- your production sprint.** 🙏
- ### v2.1.20 (2026-05-26 — second entry, first-follower effect validated)
- - **[@bj (정병진)](https://github.com/ww-w-ai/bkit-claude-code/issues)** —
- bkit v2.1.14 install incident (2026-05-26, `Validation errors: : Unrecognized
- key: "displayName"`). Precise error message + cache path + Cursor IDE
- environment metadata sharing drove the entire **v2.1.20 Marketplace
- Recovery Sprint** (14 features / 3 sub-sprints / 3 new ENH 321/322/323 /
- 1 new ADR 0011 Plugin Manifest Schema Compliance Policy). Reproduction
- absorbed at `test/e2e/external-dogfood/cc-min-version.test.js` (5 TC,
- Lifecycle Stage 4 Regression Lock achieved). Triggered ADR 0006 §
- Empirical Validation Gate recovery (~30-day wire delay closed). See
- [`docs/external-dogfooders/bj.md`](docs/external-dogfooders/bj.md) for the
- full contribution archive. **Thank you for sharing the precise error
- message that scoped the entire sprint correctly.** 🙏
- ### v2.1.36 (2026-08-12 — third entry)
- - **[@Sinclair-Seo](https://github.com/ww-w-ai/bkit-claude-code/issues/148)**
- — issue #148. Three Destructive Detector rules were refusing commands that are
- read-only or narrowly scoped. The report came with a 12-case reproduction
- harness that included **negative controls**, and the note that makes them
- matter: a "0 false positives" reading proves nothing unless genuinely
- destructive commands are still caught in the same run — a point they made after
- first measuring a bogus green from a one-argument `detect()` call.
- It also named the real cost. A PreToolUse block asks a question, and an
- unattended run has nobody to answer it, so the agent **stalls silently instead
- of failing** — ~15 minutes of dead time, twice in one sprint, caught only
- because an idle-stall monitor was attached.
- Auditing all 16 rules on the strength of that report measured the defect class
- at roughly 3× what was filed, and found the same root cause producing **false
- 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
- absorbed at
- `test/e2e/external-dogfood/sinclair-seo-148-guardrail-precision.test.js`
- (Lifecycle Stage 4 Regression Lock). **Thank you for the negative controls —
- they caught a regression we introduced while fixing this.** 🙏
- ## 🚀 bkit Early Adopter Program
- > Running bkit on a non-trivial production project and willing to file
- > detailed bug reports with reproductions makes you part of bkit's
- > quality system, not just a bug reporter.
- Established **v2.1.19** (master plan §15.4 DA-1~DA-4, ENH-318 차별화 7/7).
- **Benefits**:
- - 🏆 Public recognition in this README + dedicated archive
- - 🔒 Your reproduction scripts become permanent E2E regression tests
- - 📊 Your activity directly powers bkit's Trust Score
- (`externalDogfoodFeedbackResponseRate` component, weight 0.05)
- - 📝 CHANGELOG attribution on every release where your scenarios
- were absorbed
- - 🤝 Direct line to bkit maintainers — priority issue triage,
- reproduction-script-first response
- **How to join**: file your first detailed issue at
- [bkit-claude-code/issues](https://github.com/ww-w-ai/bkit-claude-code/issues)
- with bkit version, reproduction steps, expected vs actual behavior,
- and file:line references. See
- [`docs/external-dogfooders/_README.md`](docs/external-dogfooders/_README.md)
- for the full 5-stage User-Feedback Lifecycle and program structure.
- > **DA-4 acquisition goal**: by v2.1.20 (30 days post-v2.1.19 GA),
- > measure dogfooder population. **DA-4 status (v2.1.20)**: **N=2 confirmed**
- > (@pruge + @bj) — first-follower effect validated. v2.1.21+ continues
- > active outreach (CC marketplace narrative, community engagement) to
- > grow N≥3.
- ## License
- 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
- #!/usr/bin/env node
- /**
- * Destructive Operation Detector (FR-10)
- * Detects destructive operations before execution using 8 guardrail rules.
- *
- * Rules G-001 to G-008 cover recursive delete, force push, hard reset,
- * protected branch modification, env file modification, secret key access,
- * mass file deletion, and root directory operations.
- *
- * @version 2.1.10
- * @module lib/control/destructive-detector
- */
- /**
- * @typedef {Object} GuardrailRule
- * @property {string} id - Rule identifier (G-001 to G-008)
- * @property {string} name - Human-readable rule name
- * @property {RegExp} pattern - Detection pattern
- * @property {'critical'|'high'|'medium'} severity - Rule severity
- * @property {'deny'|'ask'|'allow'} defaultAction - Default action when triggered
- */
- /**
- * @typedef {Object} DetectionResult
- * @property {boolean} detected - Whether a destructive operation was detected
- * @property {Array<{id: string, name: string, severity: string, pattern: string}>} rules - Matched rules
- * @property {number} confidence - Detection confidence 0-1
- */
- /**
- * Guardrail rules for destructive operation detection
- * @type {GuardrailRule[]}
- */
- const GUARDRAIL_RULES = [
- {
- id: 'G-001',
- name: 'Recursive delete',
- pattern: /\b(rm\s+-(r|rf|fr)\b|rm\s+--recursive|rimraf|shutil\.rmtree|Remove-Item\s+-Recurse)/i,
- severity: 'critical',
- defaultAction: 'deny',
- /*
- * v2.1.34 (D9) — severity depends on WHAT is being deleted.
- *
- * This rule matched `rm -r` regardless of target, so deleting a scoped
- * temporary directory was refused exactly as hard as deleting `/`. The
- * refusal then advised "Scope the command to a specific path instead of a
- * broad or root target" — advice the rule made impossible to act on, since
- * scoping changed nothing. Guidance a user cannot follow is how a guard
- * teaches people to switch it off, and both cases below were hit doing
- * ordinary work on this release.
- *
- * A dangerous target still denies. A specific one asks.
- */
- severityFor: (text) => (deleteTargetIsBroad(text) ? 'critical' : 'high'),
- },
- {
- id: 'G-002',
- name: 'Force push',
- pattern: /\bgit\s+push\s+.*(-f|--force|--force-with-lease)\b/i,
- severity: 'critical',
- defaultAction: 'deny',
- // ENH-462 (v2.1.36): grade by target. A protected branch denies; a topic
- // branch asks. See pushTargetIsProtected().
- severityFor: (text) => (pushTargetIsProtected(text) ? 'critical' : 'high'),
- },
- {
- id: 'G-003',
- name: 'Hard reset',
- pattern: /\bgit\s+reset\s+--hard\b/i,
- severity: 'high',
- defaultAction: 'ask'
- },
- {
- id: 'G-004',
- name: 'Protected branch modification',
- /*
- * ENH-442 (v2.1.36) — `(?!-)` excludes hyphenated sub-commands.
- *
- * `\b` is satisfied by a hyphen, so `merge` matched `merge-base` and the
- * read-only `git merge-base origin/master HEAD` was graded as a protected
- * branch modification. Reported in issue #148; `merge-tree` and `merge-file`
- * were measured to have the same defect and are covered by the same guard.
- *
- * The hyphenated spellings are git's plumbing (`merge-base`, `merge-tree`,
- * `merge-file`, `commit-tree`) — they compute and report, they do not move a
- * branch. The porcelain commands that DO move a branch are exactly the
- * un-hyphenated four, so excluding the hyphen form is the whole fix.
- */
- pattern: /\bgit\s+(commit|merge|rebase|push)(?!-)\b.*\b(main|master|release|production)\b/i,
- severity: 'high',
- defaultAction: 'ask'
- },
- {
- id: 'G-005',
- name: 'Environment file modification',
- /*
- * ENH-477 (v2.1.37) — this rule had never fired for the filename it names.
- *
- * The old pattern was /\b(\.env|\.env\.\w+)\b/i. `\b` is a transition
- * between a word and a non-word character, and the character before a
- * leading `.` is a space, a `/`, or the start of the string — all non-word.
- * So `\b\.env` could not match `.env` as it is actually written. Measured
- * against the shipped rule:
- *
- * cat .env -> no match git add -f .env.production -> no match
- * ./.env, foo/.env -> no match myapp.env -> MATCH
- *
- * It matched only when a word character preceded the dot, which is close to
- * never for a real environment file. Same class as ENH-263 and ENH-469:
- * shipped, asserted by tests that checked the rule existed, and never once
- * triggered by the thing it was written for.
- *
- * It was wrong in BOTH directions at once, which is why neither showed up as
- * a complaint. Measured against the shipped rule:
- *
- * .env, cat .env, ./.env -> no match (blind to the secret store)
- * process.env.NODE_ENV -> MATCH (ordinary JavaScript)
- * import.meta.env.VITE_KEY -> MATCH (ordinary JavaScript)
- * config.env.production -> MATCH (correct)
- *
- * v2.1.36's false-positive audit did not catch the second half because its
- * corpus was Bash commands, and `process.env.X` arrives through `content` on
- * an Edit. Editing any file that reads an environment variable prompted.
- *
- * The blast radius of the false NEGATIVE was one surface: `Write`/`Edit` to
- * `.env` is guarded by the `.env*` deny glob in scope-limiter.js:34 and that
- * one works. What went unguarded was the Bash surface this detector owns.
- *
- * The replacement drops `\b` — which cannot express "start of a filename"
- * when the filename starts with a dot — and matches the whole dotted chain,
- * so both spellings are covered: the leading-dot file (`.env.production`)
- * and the prefixed one (`config.env.production`, which DT-005 asserts).
- * `(?![\w-])` keeps `.envrc` out; the two suppressors below keep templates
- * and runtime env access out.
- */
- pattern: /\.env(?:\.[\w-]+)*(?![\w-])/i,
- severity: 'high',
- defaultAction: 'ask',
- suppressIf: isBenignEnvMention,
- },
- {
- id: 'G-006',
- name: 'Secret key access',
- pattern: /\b[\w/.-]+(\.key|\.pem|\.p12|\.pfx|\.jks|\.keystore)\b/i,
- severity: 'high',
- defaultAction: 'ask',
- // ENH-445 (v2.1.36): listing a key file is not accessing it. See
- // isMetadataOnlyAccess(). Readers and copiers are unaffected.
- suppressIf: isMetadataOnlyAccess,
- },
- {
- id: 'G-007',
- name: 'Mass file deletion',
- pattern: /\b(rm|del|delete|remove)\b.*(\s+\S+){5,}/i,
- severity: 'medium',
- defaultAction: 'ask',
- // ENH-447 (v2.1.36): SQL's `DELETE FROM` is not a filesystem deletion. The
- // SQL rules own that language; G-010b still catches an unscoped DELETE.
- // ENH-470 (v2.1.37): and the verb has to be the command, not just a word that
- // appears in it. See isNotACommandLevelDelete().
- suppressIf: (text) => looksLikeSqlStatement(text) || isNotACommandLevelDelete(text),
- },
- {
- id: 'G-008',
- name: 'Root directory operations',
- pattern: /\b(rm|mv|cp|chmod|chown)\s+.*\s+\/\s*$/,
- severity: 'critical',
- defaultAction: 'deny'
- },
- // v2.1.12 Sprint E-1 (defect #19 fix): DB destruction patterns previously
- // were not matched (e.g. `DROP TABLE users` returned isDestructive=false).
- // Added SQL DDL/DML destruction + NoSQL drop patterns.
- {
- id: 'G-009',
- name: 'SQL table/database drop',
- // matches DROP TABLE / DROP DATABASE / DROP SCHEMA / DROP INDEX / DROP VIEW
- pattern: /\bDROP\s+(TABLE|DATABASE|SCHEMA|INDEX|VIEW|TRIGGER|PROCEDURE|FUNCTION)\b/i,
- severity: 'critical',
- defaultAction: 'deny',
- // ENH-440: SQL statements end at `;`, not at a newline. See splitCommandSegments().
- segmentOn: 'sql'
- },
- {
- id: 'G-010',
- name: 'SQL TRUNCATE / ALTER DROP COLUMN',
- pattern: /\b(TRUNCATE\s+TABLE\b|ALTER\s+TABLE\s+\S+\s+DROP\s+COLUMN)\b/i,
- severity: 'critical',
- defaultAction: 'deny',
- segmentOn: 'sql'
- },
- {
- id: 'G-010b',
- name: 'DELETE without WHERE clause',
- /*
- * Matches `DELETE FROM <ident>` only when no WHERE clause follows it.
- *
- * ENH-446 (v2.1.36) — the lookahead is unchanged, but it is now evaluated
- * against ONE statement instead of the whole input. Previously a WHERE
- * belonging to an unrelated later statement suppressed the match, so an
- * unscoped DELETE went undetected. Measured on v2.1.35:
- *
- * DELETE FROM audit_log; SELECT 1 FROM t WHERE x=1 -> not detected
- * DELETE FROM audit_log -- WHERE -> not detected
- *
- * Both now segment at `;` (and the comment case matches within its own
- * statement), so the lookahead only sees the DELETE's own clause.
- */
- pattern: /\bDELETE\s+FROM\s+[\w.]+(?![\s\S]*\bWHERE\b)/i,
- severity: 'critical',
- defaultAction: 'deny',
- segmentOn: 'sql'
- },
- {
- id: 'G-011',
- name: 'NoSQL collection drop',
- // MongoDB `db.collection.drop()` / `dropDatabase()` / Redis FLUSHALL/FLUSHDB
- pattern: /\b(db\.\w+\.drop\s*\(\s*\)|dropDatabase\s*\(\s*\)|FLUSHALL\b|FLUSHDB\b)/i,
- severity: 'critical',
- defaultAction: 'deny',
- segmentOn: 'sql'
- },
- /*
- * G-012 ~ G-015 (v2.1.34) — bypasses proven against the shipped v2.1.33 rules.
- *
- * The rules above are a denylist of literal shapes, so they hold only for the
- * spellings someone thought to write down. Probing the live PreToolUse handler
- * showed which spellings were missing: the recursive-delete rules caught the
- * plain form, a variable-indirected form, an xargs form and `shutil.rmtree`,
- * but these four went straight through with `decision: allow`.
- *
- * A denylist is never complete, and these additions do not make it so. They
- * close the specific holes that were demonstrated rather than imagined, and
- * each ships with a regression test in
- * test/regression/destructive-bypass.test.js. The honest framing of this
- * subsystem is a known-pattern guard, not a complete defense — the docs now
- * say that.
- */
- {
- id: 'G-012',
- name: 'Obfuscated command execution',
- // `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
- // the `bash <(...)` process-substitution form. The payload is unknowable at
- // match time, which is exactly why executing it cannot be waved through.
- pattern: /\b(base64\s+(-d|-D|--decode)\b[\s\S]*\|\s*(ba)?sh\b|eval\s+"?\$\(|(ba)?sh\s+<\(|\|\s*eval\b)/i,
- severity: 'critical',
- defaultAction: 'deny'
- },
- {
- id: 'G-013',
- name: 'Find-based mass deletion',
- // `find / -delete` and `find . -exec rm {} \;` delete recursively without
- // ever containing the token `rm -rf`, so G-001 and G-007 both miss them.
- 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,
- severity: 'critical',
- defaultAction: 'deny',
- // ENH-443 (v2.1.36): grade by target, matching G-001. A broad target still
- // denies; a scoped one asks. See findTargetIsBroad() for the measured
- // asymmetry this removes.
- severityFor: (text) => (findTargetIsBroad(text) ? 'critical' : 'high'),
- },
- {
- id: 'G-014',
- name: 'Raw device or disk write',
- // `dd of=/dev/disk0`, `mkfs`, `> /dev/sda`. Destroys a volume outright and
- // shares no token with any delete rule.
- pattern: /\b(dd\s+[\s\S]*\bof=\s*\/dev\/|mkfs(\.\w+)?\s|>\s*\/dev\/(disk|sd|nvme|hd)\w*|\bwipefs\b|\bblkdiscard\b)/i,
- severity: 'critical',
- defaultAction: 'deny'
- },
- {
- id: 'G-015',
- name: 'Remote script piped to a shell',
- // `curl … | sh`, `wget -O- … | bash`. Executes code nobody in this session
- // has read, from a host nobody has vetted.
- pattern: /\b(curl|wget|fetch)\b[\s\S]*\|\s*(sudo\s+)?(ba|z|k|da)?sh\b/i,
- severity: 'critical',
- defaultAction: 'deny'
- },
- /*
- * G-016 ~ G-018 (v2.1.37, ENH-477) — git commands that destroy work, measured
- * against the shipped v2.1.36 rules and found to pass unguarded.
- *
- * The trigger was Claude Code v2.1.229 removing auto-approval from 56 git/gh
- * spellings in `/commit-push-pr`. That list is NOT the model for these rules,
- * and copying it would have been a mistake: it carves dangerous commands out
- * of one skill's auto-approval, whereas this detector asks a human about
- * destruction anywhere. The two answer different questions.
- *
- * So each candidate was graded by one test — does it destroy work that cannot
- * be recovered? Of the four the analysis named, two failed that test and are
- * deliberately NOT here:
- *
- * --amend rewrites the last commit, and the original stays in the
- * reflog. The dangerous half is publishing it, which needs a
- * force push, which is G-002. On its own it is routine.
- * --no-verify skips git's own hooks. It bypasses a check; it destroys
- * nothing.
- *
- * Adding those would have regressed the work v2.1.36 did — twelve measured
- * false positives down to one — by prompting on ordinary commits. A guard that
- * fires on routine work is how people learn to switch guards off.
- *
- * `git add -f` is likewise absent: it stages an ignored file, which is a leak
- * rather than a destruction, and the leak that matters (`git add -f .env`) is
- * now caught by G-005, whose word-boundary defect this release fixes.
- */
- {
- id: 'G-016',
- name: 'Untracked file deletion',
- /*
- * `git clean` with `-f` plus `-d` or `-x` deletes untracked files outright.
- * It is the most irreversible command in ordinary git use: unlike `reset
- * --hard` (G-003) there is no reflog entry, because the files were never in
- * the object store. Nothing in G-001 or G-013 sees it — the token `rm` never
- * appears.
- *
- * `-f` alone (no `-d`/`-x`) still deletes untracked files in the current
- * directory, so the force flag is matched anywhere in a short cluster, in
- * any order: `-fd`, `-df`, `-xdf`, `--force -d`. The first attempt anchored
- * `f` immediately after the dashes and missed `-xdf`, which is the spelling
- * most people actually type.
- */
- pattern: /\bgit\s+clean\b(?=[\s\S]*(?:--force\b|-[a-zA-Z]*f))/i,
- severity: 'critical',
- defaultAction: 'deny',
- // `-n` / `--dry-run` prints what WOULD be removed and removes nothing.
- // Prompting for a preview is the unfollowable friction ENH-445 removed
- // elsewhere; git itself treats the combination as a preview.
- suppressIf: isGitCleanDryRun,
- // Graded like G-001 and G-013: a broad target denies, a scoped one asks.
- // `git clean -fdx` at the repo root is not the same act as `git clean -fd ./build`.
- severityFor: (text) => (gitCleanTargetIsBroad(text) ? 'critical' : 'high'),
- },
- {
- id: 'G-017',
- name: 'Uncommitted change discard',
- /*
- * The three spellings that throw away the working tree without touching
- * history: `git checkout -f`, `git restore` against the worktree, and
- * `git switch --discard-changes`. Same consequence as `git reset --hard`,
- * which has been an `ask` since G-003 — so these are an `ask` too, rather
- * than three rules that grade one act differently depending on which verb
- * the user reached for.
- *
- * `git restore --staged` alone only unstages and is excluded: the file
- * content survives in the working tree. That exclusion lives in
- * isStagedOnlyRestore() rather than in a negative lookahead — the first
- * attempt used `(?![\s\S]*--staged\s*$)`, which only held when the flag was
- * the last token, so `git restore --staged .` still matched.
- */
- pattern: /\bgit\s+(?:checkout\s+(?:-f\b|--force\b)|switch\b[\s\S]*--discard-changes\b|restore\b)/i,
- severity: 'high',
- defaultAction: 'ask',
- suppressIf: isStagedOnlyRestore,
- },
- {
- id: 'G-018',
- name: 'Recovery history destruction',
- /*
- * The reflog is what makes `git reset --hard`, `git branch -D` and an
- * amended commit recoverable — it is the reason those are graded `ask` or
- * left alone. Expiring it and pruning immediately removes that safety net,
- * which is why this is here and plain `git gc` is not: the danger is the
- * combination of expiring NOW and pruning NOW.
- *
- * Deleting the backups is a bigger act than any single deletion they cover.
- */
- pattern: /\bgit\s+(?:reflog\s+expire\b[\s\S]*--expire(?:-unreachable)?=(?:now|all)\b|gc\b[\s\S]*--prune=now\b)/i,
- severity: 'critical',
- defaultAction: 'deny',
- }
- ];
- /**
- * Fields of a parsed hook input that can carry a destructive operation.
- * Anything not listed here (ids, booleans, metadata) is not worth matching and
- * only adds noise.
- */
- const MATCHABLE_FIELDS = ['command', 'file_path', 'filePath', 'content', 'old_string', 'oldString', 'new_string', 'newString'];
- /**
- * Normalize an input into the list of strings the rules should run against.
- *
- * ENH-389 (v2.1.33): this used to be `JSON.stringify(toolInput)` for anything
- * that was not already a string, which quietly broke every anchored pattern.
- * `{"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
- * matched and commands aimed at the filesystem root were invisible. Measured
- * before the fix:
- * 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
- * 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
- *
- * Fixing only the call site would have left the trap armed for the next caller
- * (`scripts/pre-write.js:217` passes a parsed object today). Each field is
- * matched separately so per-field anchors behave exactly as they do for a bare
- * string, rather than being concatenated into one blob.
- *
- * @param {string|object|null|undefined} toolInput
- * @returns {string[]}
- */
- function toMatchableStrings(toolInput) {
- if (typeof toolInput === 'string') return [toolInput];
- if (!toolInput || typeof toolInput !== 'object') return [''];
- const parts = [];
- for (const key of MATCHABLE_FIELDS) {
- const v = toolInput[key];
- if (typeof v === 'string' && v.length > 0) parts.push(v);
- }
- // Nothing recognizable — fall back to the raw values so a novel shape is not
- // silently exempt from every rule.
- if (parts.length === 0) {
- for (const v of Object.values(toolInput)) {
- if (typeof v === 'string' && v.length > 0) parts.push(v);
- }
- }
- return parts.length > 0 ? parts : [''];
- }
- /**
- * Targets that make a recursive delete catastrophic rather than routine.
- *
- * Deliberately conservative: anything not recognised as specific is treated as
- * broad. Being wrong in this direction costs a confirmation prompt; being wrong
- * in the other direction costs the user their data.
- */
- const BROAD_DELETE_TARGETS = [
- /(^|\s)\/(\s|$)/, // the filesystem root
- /(^|\s)~(\/?\s|\/?$)/, // home
- /\$(HOME|PWD|CWD|ROOT|PROJECT_ROOT)\b/, // an env var standing in for a root
- /(^|\s)\.\.?(\s|$)/, // bare . or ..
- /(^|\s)\/(etc|usr|var|bin|sbin|lib|opt|boot|dev|sys|proc|System|Library|Applications|Users|home)(\/|\s|$)/i,
- /(^|\s)[A-Za-z]:\\(\s|$)/, // a Windows drive root
- /(^|\s)\/\*/, // a glob directly under root
- /(^|\s)\*(\s|$)/, // a bare glob
- /(^|\s)["']?\$\{?\w+\}?["']?(\s|$)/, // an unresolved variable as the whole target
- ];
- /**
- * Does this recursive-delete command aim at something broad?
- *
- * An unparseable command counts as broad — the point is to be sure the target
- * is specific before relaxing, never to guess that it is.
- *
- * @param {string} text - the command that matched the recursive-delete pattern
- * @returns {boolean}
- */
- function deleteTargetIsBroad(text) {
- if (typeof text !== 'string') return true;
- /*
- * The target list runs from the delete verb to the next command separator —
- * NOT to the end of the input.
- *
- * The first version used `(.*)$` with the `s` flag, which swallowed every
- * subsequent line of a multi-command block, so anything appearing later in
- * the script was read as an operand of the delete. Reproduced while working
- * on v2.1.34, on a block of the shape:
- *
- * cd "$JOB/tmp" && rm -rf degtest && mkdir degtest
- * ...
- * printf ... | CLAUDE_PROJECT_DIR="$PWD" node r.js
- *
- * `$PWD` on the last line matched the "env var standing in for a root" rule,
- * so a delete of one scoped directory was graded `critical` and refused —
- * while advising the user to "scope the command to a specific path", which
- * they had already done. A guard that refuses correct commands and gives
- * unfollowable advice is one people switch off, and then it protects nothing.
- */
- const m = text.match(/\b(?:rm|rimraf|Remove-Item)\b([^\n;|&]*)/i);
- if (!m) return true; // shutil.rmtree(...) and friends: not parsed, stay strict
- const operands = m[1]
- .split(/\s+/)
- .filter((tok) => tok && !tok.startsWith('-'));
- if (operands.length === 0) return true; // no target found — do not relax
- return operands.some((operand) => {
- // `$(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
- const target = ' ' + operand.replace(/[)`]+$/, '').replace(/^["']|["']$/g, '') + ' ';
- return BROAD_DELETE_TARGETS.some((re) => re.test(target));
- });
- }
- /**
- * Commands that report a file's METADATA without reading its contents.
- *
- * ENH-445 (v2.1.36) — G-006 fires on any mention of a key-file extension, so
- * `ls -la ./certs/server.pem` was graded "Secret key access" and prompted. The
- * rule exists to notice a secret being READ or moved; a directory listing does
- * neither, and prompting for it is the kind of unfollowable friction that
- * teaches people to switch the guard off.
- *
- * Deliberately a short allowlist of commands whose entire job is metadata. Any
- * verb not on it — including every reader (`cat`, `head`, `openssl`, `base64`)
- * and every copier (`cp`, `scp`, `rsync`) — still fires.
- */
- const METADATA_ONLY_COMMANDS = [
- 'ls', 'll', 'stat', 'file', 'find', 'basename', 'dirname', 'realpath',
- 'readlink', 'test', 'wc', 'du',
- ];
- /**
- * Conventional `.env` template suffixes — files whose entire purpose is to be
- * committed. Kept identical to the closed list ENH-464 (v2.1.36) settled on for
- * the write path in lib/control/scope-limiter.js, so the two surfaces cannot
- * disagree about one file.
- */
- const ENV_TEMPLATE_SUFFIXES = ['example', 'sample', 'template', 'dist'];
- /**
- * Runtime objects whose `.env` is a variable map, not a file.
- *
- * `process.env.NODE_ENV` is how every Node program reads configuration, and the
- * shipped G-005 pattern matched it — so editing any file that reads an
- * environment variable prompted. A closed list, in the style of
- * METADATA_ONLY_COMMANDS: anything not named here still fires.
- */
- const RUNTIME_ENV_ACCESSORS = ['process', 'meta', 'deno', 'bun', 'globalthis'];
- /**
- * Every `.env` in this segment is harmless.
- *
- * ENH-477 (v2.1.37). Two harmless shapes, and the suppression holds only when
- * EVERY occurrence is one of them — `cp .env.example .env` mentions a template
- * and a real secret store, and the second is the reason to ask.
- *
- * template `.env.example`, `.env.local.example` — exists to be
- * committed. Judged on the LAST segment of the dotted chain, so
- * a nested template is still a template; the first attempt read
- * only the first segment and prompted on `.env.local.example`,
- * which an existing regression control caught.
- * runtime access `process.env.PORT` — a variable read, not a file.
- *
- * @param {string} text - the segment that matched
- * @returns {boolean}
- */
- function isBenignEnvMention(text) {
- if (typeof text !== 'string') return false;
- // Greedy on the prefix, deliberately: a lazy `*?` matches empty every time and
- // the accessor is never captured, so `process.env.PORT` reads as a bare file.
- const re = /([\w.]*)\.env((?:\.[\w-]+)*)(?![\w-])/gi;
- let m;
- let seen = 0;
- while ((m = re.exec(text)) !== null) {
- seen++;
- const prefix = (m[1] || '').split('.').filter(Boolean).pop() || '';
- if (RUNTIME_ENV_ACCESSORS.includes(prefix.toLowerCase())) continue;
- const chain = (m[2] || '').split('.').filter(Boolean);
- const last = (chain[chain.length - 1] || '').toLowerCase();
- if (ENV_TEMPLATE_SUFFIXES.includes(last)) continue;
- return false; // this one is a real environment file
- }
- return seen > 0;
- }
- /**
- * Is this segment nothing but a metadata query over its operands?
- *
- * @param {string} text - the segment that matched
- * @returns {boolean} true when the leading command only reports metadata
- */
- function isMetadataOnlyAccess(text) {
- if (typeof text !== 'string') return false;
- const m = text.trim().match(/^([\w./-]+)/);
- if (!m) return false;
- const verb = m[1].split('/').pop(); // /bin/ls -> ls
- return METADATA_ONLY_COMMANDS.includes(verb.toLowerCase());
- }
- /**
- * Wrappers that stand in front of the real command without changing what it is.
- * `sudo rm …` is still an `rm`; the guard has to see through them.
- */
- const COMMAND_WRAPPERS = ['sudo', 'command', 'env', 'nice', 'nohup', 'time', 'exec', 'doas'];
- /**
- * Commands that can only read and report. Deliberately short.
- *
- * `echo` and `printf` are NOT here, and that is the whole design of this list:
- * they are how a payload gets built (`echo "…" | sh`), so treating them as inert
- * would open the hole this guard exists to close. Only search tools qualify —
- * they have no write mode at all.
- */
- const SEARCH_ONLY_COMMANDS = ['grep', 'egrep', 'fgrep', 'rg', 'ripgrep', 'ag', 'ack'];
- /**
- * Does this segment contain a shell metacharacter OUTSIDE quotes?
- *
- * The quote-awareness is not a nicety. A search pattern routinely contains the
- * very characters that would otherwise disqualify it — `grep -rlE "DROP|rm" lib`
- * has a `|` inside a quoted regex, and reading that as a pipe would leave the
- * commonest form of this false positive unfixed while claiming to have fixed it.
- *
- * Scanning follows splitCommandSegments(): a backslash escapes the next
- * character, single and double quotes toggle, and only unquoted text counts. An
- * unbalanced quote means the segment cannot be parsed with confidence, so it is
- * reported as escaping — the conservative answer.
- *
- * @param {string} text
- * @returns {boolean}
- */
- function hasUnquotedShellEscape(text) {
- let inSingle = false;
- let inDouble = false;
- for (let i = 0; i < text.length; i++) {
- const c = text[i];
- if (c === '\\') { i++; continue; }
- if (c === "'" && !inDouble) { inSingle = !inSingle; continue; }
- if (c === '"' && !inSingle) { inDouble = !inDouble; continue; }
- if (inSingle || inDouble) continue;
- if (c === '|' || c === '>' || c === '<' || c === '`' || c === ';' || c === '&') return true;
- if (c === '$' && text[i + 1] === '(') return true;
- }
- // Unbalanced quoting — do not claim to understand this segment.
- return inSingle || inDouble;
- }
- /**
- * Is this segment a search that provably cannot execute or delete anything?
- *
- * ENH-473 (v2.1.37). Every rule in this table matches text, so a command that
- * merely *contains* a dangerous string is graded as if it performed one. Searching
- * for the string is the clearest case: this was hit twice while writing v2.1.37,
- * once when a `grep` for two rule patterns was refused as "Recursive delete; SQL
- * table drop". Nothing was deleted and nothing could have been — grep has no
- * write mode.
- *
- * Same defect class as ENH-470 one level up: ENH-470 stopped G-007 reading a WORD
- * as a delete command, and this stops any rule reading a search ARGUMENT as an
- * operation.
- *
- * The bound is deliberately severe, because the failure direction here is a false
- * negative — a real destructive command passing unseen — and that is much worse
- * than the false positive it fixes. Both conditions must hold:
- *
- * 1. the command head is a search tool with no write mode (not `echo`, which is
- * how `echo "…" | sh` starts), and
- * 2. the segment contains no character through which a shell could be reached.
- *
- * With both, the segment cannot do anything but print. `grep -rn "…" . | sh`
- * fails (2), `echo "…" | sh` fails (1), and a redirection to a file that is later
- * executed fails (2). Negative controls for all three ship with this change.
- *
- * @param {string} text - one command segment
- * @returns {boolean} true when no rule should be matched against this segment
- */
- function isInertSearchInvocation(text) {
- if (typeof text !== 'string') return false;
- const trimmed = text.trim();
- if (!trimmed) return false;
- if (hasUnquotedShellEscape(trimmed)) return false;
- let rest = trimmed;
- // eslint-disable-next-line no-constant-condition
- while (true) {
- const m = rest.match(/^(\S+)\s+([\s\S]*)$/);
- if (!m) break;
- const head = m[1];
- const isAssignment = /^[A-Za-z_][A-Za-z0-9_]*=/.test(head);
- const isWrapper = COMMAND_WRAPPERS.includes(head.split('/').pop().toLowerCase());
- if (!isAssignment && !isWrapper) break;
- rest = m[2].trim();
- }
- const command = (rest.split(/\s+/)[0] || '').split('/').pop().toLowerCase();
- return SEARCH_ONLY_COMMANDS.includes(command);
- }
- /** The verbs G-007 is written about. */
- const DELETE_VERBS = ['rm', 'del', 'delete', 'remove'];
- /**
- * Is the delete verb something OTHER than this segment's command?
- *
- * ENH-470 (v2.1.37). G-007 is named "Mass file deletion" and counts operands
- * after the token `rm`/`del`/`delete`/`remove`. Its pattern lets that token sit
- * anywhere in the segment, so anything that merely *mentions* deletion and takes
- * five or more arguments matched. Measured on v2.1.36, after issue #148's
- * segment-scoping fix had already landed:
- *
- * grep -rn delete src a b c d e -> G-007, ask (read-only)
- * npm remove lodash react vue axios dayjs -> G-007, ask (package manager)
- *
- * Neither deletes a file. The first cannot delete anything at all. This is the
- * same defect class issue #148 reported — an operand list read past its own
- * boundaries — surviving one level down: #148 fixed reading across command
- * separators, and this fixes reading across the command name itself.
- *
- * The rule stands down unless the segment's command head is a delete verb, after
- * looking through `VAR=value` prefixes, the wrappers above, and a path
- * (`/bin/rm` reads as `rm`). `npm remove …` therefore stops matching, because the
- * command is `npm`.
- *
- * This narrows G-007 only, and G-007 is the weakest rule in the table
- * (`medium`/`ask`). A genuine `rm a b c d e f` still matches here; a recursive
- * delete is G-001's; a find-driven delete is G-013's; an unscoped SQL DELETE is
- * G-010b's. Regression controls for all four ship alongside this change, because
- * a narrowing without them is indistinguishable from a hole.
- *
- * @param {string} text - one command segment
- * @returns {boolean} true when G-007 should stand down
- */
- function isNotACommandLevelDelete(text) {
- if (typeof text !== 'string') return false;
- let rest = text.trim();
- if (!rest) return false;
- // Strip leading `VAR=value` assignments and transparent wrappers, repeatedly:
- // `sudo NODE_ENV=x /bin/rm …` has both.
- // eslint-disable-next-line no-constant-condition
- while (true) {
- const m = rest.match(/^(\S+)\s+([\s\S]*)$/);
- if (!m) break;
- const head = m[1];
- const isAssignment = /^[A-Za-z_][A-Za-z0-9_]*=/.test(head);
- const isWrapper = COMMAND_WRAPPERS.includes(head.split('/').pop().toLowerCase());
- if (!isAssignment && !isWrapper) break;
- rest = m[2].trim();
- }
- const command = (rest.split(/\s+/)[0] || '').split('/').pop().toLowerCase();
- return !DELETE_VERBS.includes(command);
- }
- /**
- * Does this segment read as a SQL statement rather than a shell command?
- *
- * ENH-447 (v2.1.36) — G-007 ("Mass file deletion") counts operands after the
- * token `delete`, and SQL's `DELETE FROM` supplies it. Measured on v2.1.35, the
- * safe, scoped statement
- *
- * DELETE FROM audit_log WHERE id = 1
- *
- * was reported as a filesystem mass-deletion. The SQL rules (G-009, G-010,
- * G-010b, G-011) are the ones that own this language; G-007 has nothing useful
- * to say about it and should stand down rather than double-report.
- *
- * This suppresses G-007 only. It does not weaken the SQL rules — a genuinely
- * unscoped `DELETE FROM audit_log` is still caught by G-010b, which is the rule
- * written for it.
- *
- * @param {string} text
- * @returns {boolean}
- */
- function looksLikeSqlStatement(text) {
- if (typeof text !== 'string') return false;
- 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);
- }
- /**
- * Branch names a force push must never quietly overwrite.
- *
- * Mirrors G-004's protected set, so "which branches matter" is stated once in
- * spirit even though the two rules match different shapes.
- */
- const PROTECTED_BRANCHES = /\b(main|master|release|production)\b/i;
- /**
- * Is this force push aimed at a protected branch?
- *
- * ENH-462 (v2.1.36) — G-002 had no `severityFor`, so every force push denied,
- * including the routine one:
- *
- * git push --force-with-lease origin my-topic-branch -> critical / deny
- *
- * Rewriting your own topic branch after a rebase is ordinary work, and
- * `--force-with-lease` is the careful spelling of it — it refuses if upstream
- * moved. Denying that outright is the "refuses correct commands" failure this
- * release is about, and it is why bkit's own push-event-guard already
- * distinguishes upstream from fork while this rule did not.
- *
- * A protected target still denies. Anything else asks, so the push is confirmed
- * rather than refused. An unparseable target counts as protected: when the
- * branch cannot be read, `git push --force` with no refspec pushes the current
- * branch, which may well be main.
- *
- * @param {string} text - the segment that matched the force-push pattern
- * @returns {boolean}
- */
- function pushTargetIsProtected(text) {
- if (typeof text !== 'string') return true;
- const m = text.match(/\bgit\s+push\b([^\n;|&]*)/i);
- if (!m) return true;
- const operands = m[1]
- .split(/\s+/)
- .filter((tok) => tok && !tok.startsWith('-'));
- // No remote/refspec given: git pushes the current branch, which is unknown here.
- if (operands.length === 0) return true;
- return operands.some((tok) => PROTECTED_BRANCHES.test(tok));
- }
- /**
- * Does this find-based deletion aim at something broad?
- *
- * ENH-443 (v2.1.36) — G-013 had no `severityFor`, so it graded every match
- * `critical` and denied outright. That produced the asymmetry issue #148 called
- * out, measured on v2.1.35:
- *
- * rm -rf /tmp/scratch/build -> G-001 / high / ask
- * find /tmp/scratch -type f -name '*.tmp' -delete -> G-013 / critical / deny
- *
- * The strictly narrower operation was refused harder, and the refusal advised
- * "scope the command to a specific path" — which the user had already done.
- *
- * find's paths are the operands before the first expression token, so the search
- * stops at the first `-flag`. A find with no path defaults to the working
- * directory, which `BROAD_DELETE_TARGETS` already treats as broad; an
- * unparseable command stays broad for the same reason `deleteTargetIsBroad()`
- * does — be sure the target is specific before relaxing, never guess that it is.
- *
- * @param {string} text - the segment that matched the find-based deletion pattern
- * @returns {boolean}
- */
- /**
- * Is this `git clean` a preview rather than a deletion?
- *
- * ENH-477 (v2.1.37). `-n` / `--dry-run` prints what would be removed and removes
- * nothing, and git accepts it alongside `-f`. Prompting for a preview is the
- * unfollowable friction ENH-445 removed from G-006.
- *
- * @param {string} text - the segment that matched
- * @returns {boolean}
- */
- function isGitCleanDryRun(text) {
- if (typeof text !== 'string') return false;
- return /(^|\s)(--dry-run\b|-[a-zA-Z]*n(?![a-zA-Z]))/.test(text);
- }
- /**
- * Is this `git restore` only unstaging?
- *
- * ENH-477 (v2.1.37). `--staged` on its own moves content out of the index and
- * leaves the working tree untouched, so nothing is lost. Paired with
- * `--worktree` it DOES overwrite the working tree, which is the act G-017
- * exists for.
- *
- * Only `restore` is inspected: the other two spellings the rule matches
- * (`checkout -f`, `switch --discard-changes`) have no such harmless form.
- *
- * @param {string} text - the segment that matched
- * @returns {boolean}
- */
- function isStagedOnlyRestore(text) {
- if (typeof text !== 'string') return false;
- if (!/\bgit\s+restore\b/i.test(text)) return false;
- const staged = /(^|\s)(--staged|-S)(\s|$)/.test(text);
- const worktree = /(^|\s)(--worktree|-W)(\s|$)/.test(text);
- return staged && !worktree;
- }
- /**
- * Does this `git clean` invocation target the whole repository?
- *
- * ENH-477 (v2.1.37). Graded the same way as G-001 and G-013: a broad target
- * denies, a scoped one asks. `git clean -fd ./build` is a build-directory reset;
- * `git clean -fdx` at the root deletes every untracked file in the repository,
- * including local config the user never intended to lose.
- *
- * With no path operand git cleans from the current directory down, so the
- * absence of a path is the broad case, not the narrow one — the same default
- * findTargetIsBroad() takes for `find`.
- *
- * @param {string} text - the segment that matched
- * @returns {boolean}
- */
- function gitCleanTargetIsBroad(text) {
- if (typeof text !== 'string') return true;
- const m = text.match(/\bgit\s+clean\b([^\n;]*)/i);
- if (!m) return true;
- const paths = [];
- for (const tok of m[1].split(/\s+/)) {
- if (!tok) continue;
- if (tok === '--') continue;
- if (tok.startsWith('-')) continue; // flags may precede or follow the path
- paths.push(tok);
- }
- if (paths.length === 0) return true; // implicit cwd — cleans everything below it
- return paths.some((operand) => {
- const target = ' ' + operand.replace(/^["']|["']$/g, '') + ' ';
- return BROAD_DELETE_TARGETS.some((re) => re.test(target));
- });
- }
- function findTargetIsBroad(text) {
- if (typeof text !== 'string') return true;
- const m = text.match(/\bfind\b([^\n;]*)/i);
- if (!m) return true;
- const paths = [];
- for (const tok of m[1].split(/\s+/)) {
- if (!tok) continue;
- if (tok.startsWith('-')) break; // expressions start here; paths are done
- paths.push(tok);
- }
- if (paths.length === 0) return true; // implicit cwd, or nothing parseable
- return paths.some((operand) => {
- const target = ' ' + operand.replace(/^["']|["']$/g, '') + ' ';
- return BROAD_DELETE_TARGETS.some((re) => re.test(target));
- });
- }
- /**
- * Remove heredoc BODIES before rule matching.
- *
- * A heredoc body is data on a program's stdin, not a command line. Matching
- * rules against it produces false positives that are indistinguishable from
- * real findings — writing a commit message that merely *mentions* `find -delete`
- * or `curl | sh`, or piping documentation text through `python3 - <<'PY'`, was
- * enough to be refused as critical. Both happened during work on v2.1.34, and a
- * guard that blocks ordinary work is a guard people switch off.
- *
- * This does not create a bypass. The heredoc-as-bypass vector — a heredoc piped
- * into an interpreter, or a command substitution alongside one — is the whole
- * subject of `lib/defense/heredoc-detector.js`, which inspects the command
- * STRUCTURE and still sees everything here. What this strips is only the inert
- * payload, and the delimiter line itself is kept so structural rules can still
- * see that a heredoc was present.
- *
- * Handles the `<<EOF`, `<<-EOF`, `<<'EOF'` and `<<"EOF"` spellings.
- *
- * @param {string} command
- * @returns {string} the command with heredoc bodies elided
- */
- /**
- * Find a heredoc opener on a line, ignoring any `<<` that sits inside quotes.
- *
- * v2.1.34: an earlier version matched `<<` anywhere on the line, which is a
- * bypass rather than a nicety. `echo "example: cmd << EOF"` starts a bogus
- * elision, and every line up to the next `EOF` is discarded — including a real
- * destructive command. Measured against that earlier version:
- *
- * echo "example: cmd << EOF" → stripped to the echo alone
- * rm -rf ~/ (elided)
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 939 on GitHub
- * EOF detect: []
- *
- * Quote tracking is deliberately simple — single and double quotes, with
- * backslash escapes — because the only decision it feeds is "may this line be
- * treated as an opener". Anything it cannot parse confidently is left alone,
- * which keeps evidence rather than removing it.
- *
- * @param {string} line
- * @returns {{delimiter: string, quoted: boolean}|null} the delimiter and whether its
- * tag was quoted (a quoted body is literal text), or null when no heredoc opens
- */
- function findHeredocDelimiter(line) {
- let inSingle = false;
- let inDouble = false;
- for (let i = 0; i < line.length; i++) {
- const c = line[i];
- if (c === '\\') { i++; continue; }
- if (c === "'" && !inDouble) { inSingle = !inSingle; continue; }
- if (c === '"' && !inSingle) { inDouble = !inDouble; continue; }
- if (inSingle || inDouble) continue;
- if (c !== '<' || line[i + 1] !== '<') continue;
- // `<<<` is a here-STRING, not a heredoc — it has no body and no terminator.
- if (line[i + 2] === '<') continue;
- const m = line.slice(i).match(/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))/);
- if (m) return { delimiter: m[1] || m[2] || m[3], quoted: !m[3] };
- return null;
- }
- return null;
- }
- /**
- * Join backslash-newline continuations the way bash does: a newline is removed
- * only when an odd run of backslashes precedes it (`\\` is a literal backslash).
- * A scanner rather than a regex, so consecutive continuations all join.
- */
- function joinLineContinuations(text) {
- let out = '';
- let run = 0;
- for (const c of text) {
- if (c === '\n' && run % 2 === 1) { out = out.slice(0, -1); run = 0; continue; }
- out += c;
- run = c === '\\' ? run + 1 : 0;
- }
- return out;
- }
- /** True when the line has a `$(` or backtick that no backslash escapes. */
- function hasUnescapedSubstitution(line) {
- for (let i = 0; i < line.length; i++) {
- const c = line[i];
- if (c === '\\') { i++; continue; }
- if (c === '`' || (c === '$' && line[i + 1] === '(')) return true;
- }
- return false;
- }
- function stripHeredocBodies(command) {
- if (typeof command !== 'string' || !command.includes('<<')) return command;
- const lines = command.split('\n');
- const out = [];
- let delimiter = null;
- let terminated = true;
- let quoted = false;
- let body = [];
- for (const line of lines) {
- if (delimiter === null) {
- out.push(line);
- const found = findHeredocDelimiter(line);
- if (found) { ({ delimiter, quoted } = found); terminated = false; body = []; }
- continue;
- }
- /*
- * Inside a body: drop the content, but keep the terminator line WHOLE. A
- * known bypass writes the exec vector on that line (`EOF-1 | bash`), so
- * truncating at the delimiter would remove the very thing worth matching.
- * Prefix match, not equality, for the same reason.
- */
- if (line.trim() === delimiter || line.trimStart().startsWith(delimiter)) {
- // A bare-tag body is expanded by bash, so an unescaped `$(` or backtick
- // 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
- // backslash-newline continuations, so keep the whole body, joined the way
- // bash reads it. Either view finding a substitution keeps the body.
- const expanded = joinLineContinuations(body.join('\n'));
- const substitutes = body.some(hasUnescapedSubstitution) || hasUnescapedSubstitution(expanded);
- if (!quoted && substitutes) out.push(...expanded.split('\n'));
- out.push(line);
- delimiter = null;
- terminated = true;
- continue;
- }
- body.push(line);
- }
- // No terminator found — there is no trustworthy body boundary, so match
- // against everything. This helper may remove noise, never evidence.
- if (!terminated) return command;
- return out.join('\n');
- }
- /**
- * Strip SQL comments so a commented-out keyword cannot stand in for a real clause.
- *
- * ENH-446 (v2.1.36) — G-010b fires only when no WHERE follows the DELETE, so any
- * occurrence of the WORD `WHERE` suppresses it. A comment is not a clause.
- * Measured on v2.1.35:
- *
- * DELETE FROM audit_log -- WHERE -> not detected
- *
- * A comment introducer must be `--` followed by WHITESPACE or end-of-input.
- * Without that condition this helper destroys evidence: the first version
- * treated the shell flag `--command` as a comment, so
- *
- * wrangler d1 execute db --command "DROP TABLE audit_log"
- *
- * was truncated to `wrangler d1 execute db` and G-009 stopped firing — a real
- * DROP went undetected. That regression was caught by the negative controls
- * before it left the working tree, which is precisely why they are run on every
- * change. `--WHERE` (no space) is therefore left intact; keeping a token we are
- * unsure about costs a prompt, discarding one costs a table.
- *
- * Quote-aware for the same reason as everywhere else in this file — a literal
- * `'--'` inside a string is data, not a comment introducer.
- *
- * @param {string} text
- * @returns {string} the statement with `--` line comments and block comments removed
- */
- function stripSqlComments(text) {
- if (typeof text !== 'string' || (!text.includes('--') && !text.includes('/*'))) return text;
- let out = '';
- let inSingle = false;
- let inDouble = false;
- for (let i = 0; i < text.length; i++) {
- const c = text[i];
- if (c === '\\') { out += c + (text[i + 1] || ''); i++; continue; }
- if (c === "'" && !inDouble) { inSingle = !inSingle; out += c; continue; }
- if (c === '"' && !inSingle) { inDouble = !inDouble; out += c; continue; }
- if (!inSingle && !inDouble) {
- if (c === '-' && text[i + 1] === '-' && /^(\s|$)/.test(text[i + 2] || '')) {
- const nl = text.indexOf('\n', i);
- if (nl === -1) break;
- i = nl;
- out += '\n';
- continue;
- }
- if (c === '/' && text[i + 1] === '*') {
- const end = text.indexOf('*/', i + 2);
- if (end === -1) break;
- i = end + 1;
- out += ' ';
- continue;
- }
- }
- out += c;
- }
- return out;
- }
- /**
- * Split a command into the segments a rule may legitimately span.
- *
- * ENH-440 (v2.1.36) — every rule below is written as a single command's shape,
- * but they were matched against the WHOLE input. `.*` and `[\s\S]*` therefore ran
- * past `&&`, `;` and newlines, so tokens belonging to *other* commands in a chain
- * were read as operands of the dangerous one. G-001 already solved this for
- * itself at `deleteTargetIsBroad()` by cutting at `[^\n;|&]`; this generalizes
- * that cut so every rule gets it, instead of nine near-copies of the same regex.
- *
- * Measured on v2.1.35, this defect ran in BOTH directions:
- *
- * false positives — a safe command refused because a later command supplied
- * the incriminating token:
- * git push origin feature-x && rm -f /tmp/scratch/note.txt -> G-002 deny
- * cp a.txt b.txt && ls / -> G-008 deny
- * dd if=/dev/zero of=./scratch.img && echo "of=/dev/null" -> G-014 deny
- *
- * false negatives — a real threat hidden because a later command pushed an
- * end-anchor out of reach or satisfied a negative lookahead:
- * 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
- * DELETE FROM audit_log; SELECT 1 WHERE x=1 -> G-010b defeated
- *
- * The false negatives are why this is a correctness fix and not a comfort fix.
- *
- * `|` is deliberately NOT a split point. A pipe is how several rules' threat is
- * expressed — `curl … | sh` (G-015), `base64 -d … | sh` (G-012),
- Note: Quoted as data in code: Decodes base64 and runs the result in a shell
- Line 1,124 on GitHub
- * `find … | xargs rm` (G-013) are each ONE dangerous construct, not two safe
- * ones. Splitting there would blind exactly the rules that exist to catch it.
- * `||` is a sequencer, not a pipe, and does split.
- *
- * Quote tracking mirrors `findHeredocDelimiter()`: single and double quotes with
- * backslash escapes, so `echo "a && b"` stays one segment. Anything the tracker
- * cannot parse confidently is left joined — this helper may narrow a window,
- * never hide evidence.
- *
- * A newline separates SHELL commands but NOT SQL statements, which end at `;`.
- * Splitting SQL on newlines would refuse the ordinary
- *
- * DELETE FROM audit_log
- * WHERE id = 1
- *
- * because segment 1 has no WHERE — turning a fix for one false positive into a
- * new one. Hence `mode`: rules written in SQL declare `segmentOn: 'sql'` and are
- * cut at `;` only. Measured on v2.1.35, that statement is correctly clean today,
- * and it must stay clean.
- *
- * @param {string} text
- * @param {'shell'|'sql'} [mode='shell'] which separators terminate a statement
- * @returns {string[]} one entry per segment; the original text when it contains
- * no top-level separator
- */
- function splitCommandSegments(text, mode) {
- if (typeof text !== 'string' || text.length === 0) return [''];
- const sqlMode = mode === 'sql';
- const segments = [];
- let start = 0;
- let inSingle = false;
- let inDouble = false;
- for (let i = 0; i < text.length; i++) {
- const c = text[i];
- if (c === '\\') { i++; continue; }
- if (c === "'" && !inDouble) { inSingle = !inSingle; continue; }
- if (c === '"' && !inSingle) { inDouble = !inDouble; continue; }
- if (inSingle || inDouble) continue;
- let sepLen = 0;
- if (c === ';') sepLen = 1;
- else if (!sqlMode && c === '\n') sepLen = 1;
- else if (!sqlMode && ((c === '&' && text[i + 1] === '&') || (c === '|' && text[i + 1] === '|'))) sepLen = 2;
- if (sepLen > 0) {
- segments.push(text.slice(start, i));
- i += sepLen - 1;
- start = i + 1;
- }
- }
- segments.push(text.slice(start));
- const trimmed = segments.map((s) => s.trim()).filter((s) => s.length > 0);
- return trimmed.length > 0 ? trimmed : [text];
- }
- /**
- * Detect destructive operations in a tool invocation
- * @param {string} toolName - Name of the tool being invoked
- * @param {string|object} toolInput - Command string, or a parsed tool input whose
- * command/path/content fields are matched individually (see toMatchableStrings)
- * @returns {DetectionResult}
- */
- /**
- * Resolve the action a matched rule calls for, from its declaration and its
- * graded severity.
- *
- * `critical` always denies. Otherwise the rule's own `defaultAction` stands —
- * except when the rule graded ITSELF down from `critical` (G-001 on a scoped
- * target). There the declaration describes the worst case, not this match, so
- * `deny` relaxes exactly one tier, to `ask`. It never relaxes to silence.
- *
- * @param {object} rule - the rule as declared in GUARDRAIL_RULES
- * @param {string} severity - the severity this particular match graded to
- * @returns {'deny'|'ask'|'allow'}
- */
- function resolveAction(rule, severity) {
- if (severity === 'critical') return 'deny';
- const declared = rule.defaultAction || 'ask';
- const gradedDown = typeof rule.severityFor === 'function' && rule.severity === 'critical';
- if (declared === 'deny') return gradedDown ? 'ask' : 'deny';
- return declared;
- }
- function detect(toolName, toolInput) {
- const inputs = toMatchableStrings(toolInput).map(stripHeredocBodies);
- // Kept for the tool-specific checks below, which only need substring semantics.
- const input = inputs.join('\n');
- /*
- * ENH-440 (v2.1.36) — match each rule against single command/statement
- * segments rather than the whole input. See splitCommandSegments() for why
- * this fixes false positives and false negatives at the same time, and why
- * `|` is not a split point.
- *
- * Both segmentations are computed once and reused across the 19 rules; a rule
- * picks the one matching the language it is written in.
- */
- /*
- * ENH-473 (v2.1.37): a segment that provably cannot execute or delete anything
- * is dropped before any rule sees it. Applied to both segmentations, because a
- * shell `grep` invocation is still present in the SQL-mode split and would
- * otherwise be matched by the SQL rules against its own search pattern.
- */
- const inert = isInertSearchInvocation;
- const segmentsByMode = {
- shell: inputs.flatMap((s) => splitCommandSegments(s, 'shell')).filter((s) => !inert(s)),
- // Comments are stripped BEFORE splitting so a `--` comment cannot hide a
- // statement separator, and a commented-out keyword cannot satisfy a
- // negative lookahead (ENH-446).
- sql: inputs.flatMap((s) => splitCommandSegments(stripSqlComments(s), 'sql')).filter((s) => !inert(s)),
- };
- const matchedRules = [];
- for (const rule of GUARDRAIL_RULES) {
- const segments = segmentsByMode[rule.segmentOn === 'sql' ? 'sql' : 'shell'];
- /*
- * A rule may declare `suppressIf` for contexts where its pattern provably
- * says nothing useful — a metadata-only listing for G-006, a SQL statement
- * for G-007. Suppression is evaluated per segment, so a chain that also
- * contains a genuine match still reports it.
- *
- * This is deliberately narrower than grading: `severityFor` cannot help a
- * rule whose declared action is already `ask`, because resolveAction()
- * returns a non-critical rule's declared action unchanged and there is no
- * tier below `ask` short of silence.
- */
- const hit = segments.find(
- (s) => rule.pattern.test(s)
- && !(typeof rule.suppressIf === 'function' && rule.suppressIf(s))
- );
- if (hit !== undefined) {
- // A rule may grade itself from the matched text — see G-001, where the
- // target decides whether a recursive delete is catastrophic or routine.
- const severity = typeof rule.severityFor === 'function'
- ? rule.severityFor(hit)
- : rule.severity;
- matchedRules.push({
- id: rule.id,
- name: rule.name,
- severity,
- /*
- * v2.1.34 — the action the rule table declares for this match.
- *
- * `defaultAction` has been on every rule since the table was written,
- * but nothing read it: the hook branched on `severity === 'critical'`
- * and did nothing at all otherwise. Ten rules declared `ask` and none
- * of them ever asked. Surfacing it here makes the table the single
- * place that decides deny-vs-ask.
- *
- * A graded rule outranks its own declaration in the dangerous
- * direction only: G-001 declares `deny`, and a scoped delete grades to
- * `high`, so it asks — but a broad delete grades back to `critical`
- * and denies. Grading never turns a `deny` into silence.
- */
- action: resolveAction(rule, severity),
- pattern: rule.pattern.source
- });
- }
- }
- /*
- * A second look at the two file rules against the UN-segmented input, for a
- * Write or an Edit whose payload a segment boundary could have split.
- *
- * ENH-481 (v2.1.37) — this used to test `rule.pattern` and nothing else. It
- * skipped `suppressIf`, so both suppressors that guard these two rules were
- * dead on this path while working on the Bash path:
- *
- * G-006 ENH-445's isMetadataOnlyAccess — `ls -la ./certs/server.pem` is
- * suppressed for a Bash command and was NOT suppressed here.
- * G-005 every exemption below, including `.env.example`.
- *
- * The same class as ENH-441, which v2.1.36 fixed for `isDestructive()`: two
- * entry points answering differently about one input, with the difference
- * invisible until someone routed a payload through the other one. It was found
- * while fixing G-005, when a suppressor that returned `true` for its segment
- * did not suppress the rule.
- *
- * The purpose of the second look is kept — segmentation can split a payload —
- * but it now applies the same predicate the main loop does.
- */
- if (toolName === 'Write' || toolName === 'Edit') {
- for (const id of ['G-005', 'G-006']) {
- const rule = GUARDRAIL_RULES.find((r) => r.id === id);
- if (!rule || matchedRules.some((r) => r.id === id)) continue;
- if (!rule.pattern.test(input)) continue;
- if (typeof rule.suppressIf === 'function' && rule.suppressIf(input)) continue;
- const severity = typeof rule.severityFor === 'function'
- ? rule.severityFor(input)
- : rule.severity;
- matchedRules.push({
- id: rule.id,
- name: rule.name,
- severity,
- action: resolveAction(rule, severity),
- pattern: rule.pattern.source,
- });
- }
- }
- const confidence = matchedRules.length > 0
- ? Math.min(1, 0.5 + matchedRules.length * 0.2)
- : 0;
- return {
- detected: matchedRules.length > 0,
- rules: matchedRules,
- confidence
- };
- }
- /**
- * Quick check whether a Bash command is destructive
- * @param {string} command - Bash command string
- * @returns {boolean}
- */
- function isDestructive(command) {
- if (!command || typeof command !== 'string') return false;
- /*
- * ENH-441 (v2.1.36): segment and suppress exactly as detect() does.
- *
- * This used to test each pattern against the whole command, so the two
- * exported entry points answered differently for the same input — `git push
- * origin feature-x && rm -f note.txt` was clean under detect() and destructive
- * here. It has no production callers today, which is precisely why the
- * divergence could sit unnoticed until someone wired it up and inherited the
- * false positives this release removes.
- */
- const shell = splitCommandSegments(stripHeredocBodies(command), 'shell');
- const sql = splitCommandSegments(stripSqlComments(stripHeredocBodies(command)), 'sql');
- return GUARDRAIL_RULES.some((rule) => {
- const segments = rule.segmentOn === 'sql' ? sql : shell;
- return segments.some(
- (s) => rule.pattern.test(s)
- && !(typeof rule.suppressIf === 'function' && rule.suppressIf(s))
- );
- });
- }
- /**
- * Recovery advice that fits the rule that actually fired.
- *
- * ENH-459 (v2.1.36) — the refusal offered the same three lines for every rule,
- * led by "Scope the command to a specific path instead of a broad or root
- * target". That is followable for a recursive delete. It is meaningless for
- * `curl … | sh` (G-015), for `DROP TABLE users` (G-009), for `dd of=/dev/disk0`
- * (G-014) — there is no path to scope. So most refusals ended with advice the
- * user could not act on, which is the exact failure the v2.1.34 comment on
- * G-001 warned about and issue #148 quoted back:
- *
- * "A guard that refuses correct commands and gives unfollowable advice is one
- * people switch off, and then it protects nothing."
- *
- * Scoping advice is now offered only by the two rules where scoping changes the
- * outcome — G-001 and G-013 both grade by target, so narrowing genuinely turns a
- * denial into a confirmation. Everything else gets advice that matches what it
- * refused, and G-014 gets none, because a raw-device write has no safer form
- * worth suggesting.
- *
- * @param {Array<{id: string}>} rules - the matched rules
- * @returns {string[]} advice, most specific first, always non-empty
- */
- function alternativesFor(rules) {
- const ids = new Set((rules || []).map((r) => r && r.id).filter(Boolean));
- const out = [];
- const add = (line) => { if (!out.includes(line)) out.push(line); };
- // Rules that grade by target: narrowing the target is a real remedy.
- if (ids.has('G-001') || ids.has('G-013')) {
- add('Narrow the target to a specific path — a scoped target is confirmed rather than refused');
- }
- if (ids.has('G-008')) {
- add('Name the directory you mean instead of operating on the filesystem root');
- }
- if (ids.has('G-002') || ids.has('G-003') || ids.has('G-004')) {
- add('Target a topic branch, or drop the force flag and reconcile the histories instead');
- }
- if (ids.has('G-005') || ids.has('G-006')) {
- add('Read the value from the environment or a secret store rather than the file itself');
- }
- if (ids.has('G-009') || ids.has('G-010')) {
- add('Run this against a disposable copy of the schema, and keep a dump you can restore from');
- }
- if (ids.has('G-010b')) {
- add('Add a WHERE clause naming the rows you mean to remove');
- }
- if (ids.has('G-011')) {
- add('Drop a single collection or key by name instead of the whole store');
- }
- if (ids.has('G-012') || ids.has('G-015')) {
- add('Download the script to a file, read it, then run the local copy — do not pipe it straight into a shell');
- }
- if (ids.has('G-007')) {
- add('Delete the files you mean by name, or list them first and confirm the set');
- }
- // G-014 (raw device / mkfs) is deliberately absent: there is no scoped form of
- // overwriting a volume, and inventing one would be the unfollowable advice
- // this function exists to remove.
- add('Ask the user for explicit confirmation if this is intended');
- return out;
- }
- /**
- * Generate a human-readable block message for matched rules
- * @param {Array<{id: string, name: string, severity: string, pattern: string}>} rules - Matched rules
- * @returns {string}
- */
- function getBlockMessage(rules) {
- if (!rules || rules.length === 0) {
- return 'No destructive operations detected.';
- }
- const lines = [
- '⛔ Destructive operation blocked by bkit guardrails:',
- ''
- ];
- for (const rule of rules) {
- const severityTag = rule.severity === 'critical' ? '[CRITICAL]'
- : rule.severity === 'high' ? '[HIGH]'
- : '[MEDIUM]';
- lines.push(` ${severityTag} ${rule.id}: ${rule.name}`);
- }
- lines.push('');
- /*
- * ENH-448 (v2.1.36) — this used to read "To proceed, adjust guardrail settings
- * in bkit.config.json or use manual override."
- *
- * Neither route existed. This module never reads bkit.config.json (that string
- * appeared exactly once in the file — inside the message), and `disableRule()`
- * sets a flag `detect()` does not consult, by design (see its own docs). So the
- * message named two recoveries, both imaginary, to a user who had just been
- * refused. Issue #148 called this out, and it is the same class of defect as
- * the rules themselves: a guard giving advice nobody can act on.
- *
- * It shares alternativesFor() with the hook rather than keeping its own copy.
- * The first attempt at this fix rewrote the wording HERE alone and reported the
- * user-facing message as corrected — but this function has no production
- * callers, so nothing changed for anyone. The text users actually see is built
- * in scripts/unified-bash-pre.js. One helper, both call sites, no way for the
- * two to disagree again.
- */
- lines.push('Ways forward:');
- for (const alt of alternativesFor(rules)) lines.push(` - ${alt}`);
- lines.push(' - Split a chained command: each segment is judged on its own.');
- lines.push('');
- lines.push('These rules cannot be switched off at runtime — that is deliberate, not an oversight.');
- return lines.join('\n');
- }
- /**
- * Get the default action for a specific rule
- * @param {string} ruleId - Rule ID (e.g., 'G-001')
- * @returns {'deny'|'ask'|'allow'|null}
- */
- function getRuleAction(ruleId) {
- const rule = GUARDRAIL_RULES.find(r => r.id === ruleId);
- return rule ? rule.defaultAction : null;
- }
- /**
- * Get all guardrail rules
- * @returns {GuardrailRule[]}
- */
- function getRules() {
- return GUARDRAIL_RULES.map(r => ({
- id: r.id,
- name: r.name,
- severity: r.severity,
- defaultAction: r.defaultAction,
- pattern: r.pattern.source
- }));
- }
- /**
- * Add a custom guardrail rule at runtime
- * @param {{ id: string, name: string, severity: string, pattern: RegExp, defaultAction: string }} rule
- */
- function addCustomRule(rule) {
- if (!rule || !rule.id || !rule.pattern) return;
- const existing = GUARDRAIL_RULES.find(r => r.id === rule.id);
- if (!existing) {
- GUARDRAIL_RULES.push(rule);
- }
- }
- /**
- * Mark a guardrail rule disabled — WITHOUT removing it from detection.
- *
- * ENH-449 (v2.1.36) — read the name and you expect the rule to stop firing. It
- * does not, and that is intentional: `detect()` never consults `_disabled`, so a
- * rule cannot be switched off from inside a running session. The property is
- * locked by test/security/integrity-verification.test.js IV-09, whose assertion
- * says so explicitly.
- *
- * The flag is therefore an annotation — it records that someone asked — and this
- * function is retained for that and for API compatibility. It has no production
- * callers. Do not "fix" the flag to be honoured without deliberately overturning
- * IV-09; the immutability is the security property, and the false-positive
- * pressure that motivates an off-switch is answered by rule precision instead
- * (see splitCommandSegments and the grading helpers above).
- *
- * @param {string} ruleId - Rule ID to annotate
- * @param {string} [reason] - Reason recorded alongside the annotation
- * @returns {boolean} True if the rule exists (NOT that detection changed)
- */
- function disableRule(ruleId, reason) {
- const rule = GUARDRAIL_RULES.find(r => r.id === ruleId);
- if (rule) {
- rule._disabled = true;
- rule._disableReason = reason || 'unknown';
- return true;
- }
- return false;
- }
- module.exports = {
- detect,
- isDestructive,
- getBlockMessage,
- // ENH-459 (v2.1.36): shared with scripts/unified-bash-pre.js so the advice a
- // user is given matches the rule that refused them, and so the hook and this
- // module cannot drift into offering different remedies for the same block.
- alternativesFor,
- getRuleAction,
- getRules,
- addCustomRule,
- disableRule,
- stripHeredocBodies,
- // ENH-440/446 (v2.1.36): exported so their behaviour can be asserted directly
- // rather than only inferred from detect() outcomes. The `--command` regression
- // below was a helper-level defect that a detect()-only test would have found
- // only by luck.
- splitCommandSegments,
- stripSqlComments,
- // ENH-470 (v2.1.37): same reason as the two above — a predicate that decides
- // whether a rule stands down is worth asserting directly, not only through the
- // outcome of detect().
- isNotACommandLevelDelete,
- isInertSearchInvocation,
- GUARDRAIL_RULES
- };
lib/defense/heredoc-detector.js · Bundled script · 536 lines · 2 findings marked
- /**
- * HeredocDetector — Defense Layer pure-fn detector for heredoc-pipe permission bypass.
- *
- * Design Ref: docs/sprint/v2114/design.md §3.3
- * Plan SC: ENH-310 Heredoc Pipe Bypass Defense.
- * Differentiation: bkit moat #6 — CC permission system regression self-defense.
- *
- * Background:
- * CC #58904 (regression of #48518, present v2.1.73 through v2.1.141, ~68
- * unfixed versions) lets a Bash command of the form
- *
- * cat <<'EOF' | bash
- * rm -rf /
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 13 on GitHub
- * EOF
- *
- * bypass CC's permission system: CC inspects only the outer `cat` token,
- * never the heredoc body or its pipe-target. bkit's PreToolUse defense
- * stack inherited the same blind spot — `scripts/unified-bash-pre.js`
- * substring patterns and `lib/control/destructive-detector.js` G-001~G-011
- * evaluate only top-level argv. This module closes that gap.
- *
- * Responsibility:
- * detect(command) inspects an entire Bash command string for the
- * `heredoc + (command-substitution | pipe-to-shell | eval/source)`
- * combination that defines the bypass. It returns a structured verdict
- * so the calling hook can emit a deterministic deny with safe-alternative
- * suggestions via `outputBlockWithContext`.
- *
- * Design invariants:
- * 1) Pure function — no fs, child_process, http, network, env reads.
- * Domain-grade purity even though this lives in Defense Layer.
- * 2) Conservative false-positive policy: lone `<<` heredoc returns
- * severity='warning' (audit-only, allow), never 'critical'. Only the
- * combination with `$(`, backtick, or pipe-to-shell promotes to
- * severity='critical' (deny).
- * 3) 30+ patterns categorized by attack vector (sub / pipe-shell /
- * eval-source / sudo). PATTERNS array is Object.freeze'd so callers
- * cannot mutate the policy at runtime.
- * 4) Deterministic ordering: critical patterns are evaluated before
- * warning patterns, then short-circuit on first critical match.
- *
- * Calling site (Step 6, scripts/unified-bash-pre.js):
- * const { detect } = require('../lib/defense/heredoc-detector');
- * const verdict = detect(command);
- * if (verdict.matched && verdict.severity === 'critical') {
- * outputBlockWithContext(verdict.reason, {
- * additionalContext: verdict.alternatives.join('\n'),
- * }, 'PreToolUse');
- * }
- *
- * @module lib/defense/heredoc-detector
- * @version 2.1.14
- * @since 2.1.14
- * @layer Defense
- * @enh ENH-310
- * @differentiation #6
- */
- 'use strict';
- /**
- * @typedef {'critical'|'warning'|null} Severity
- * critical — heredoc COMBINED with a payload-execution vector. Hook MUST deny.
- * warning — heredoc present but no execution vector detected. Hook MAY allow + audit.
- * null — no heredoc detected; out of scope for this detector.
- */
- /**
- * @typedef {Object} HeredocVerdict
- * @property {boolean} matched — true when at least one pattern matched
- * @property {Severity} severity — see Severity typedef
- * @property {string|null} pattern — regex source string of the matched pattern (debugging)
- * @property {string|null} vector — semantic vector: 'sub'|'pipe-shell'|'eval-source'|'sudo'|'lone-heredoc'|null
- * @property {string} reason — human-readable explanation (for hook deny message)
- * @property {string[]} alternatives — safe alternative suggestions for the user/model
- */
- /**
- * Critical patterns: heredoc combined with payload-execution vector.
- *
- * Conservative regex design: each pattern requires the explicit
- * `<<` (heredoc start) AND an unambiguous execution token. Single
- * tokens (e.g. lone `$(`) never produce critical here — that is
- * destructive-detector territory.
- *
- * Pattern source strings are kept on each entry so the verdict can
- * report which pattern matched (debug + audit-log richness).
- */
- const CRITICAL_PATTERNS = Object.freeze([
- // -------- vector: 'sub' (heredoc inside $() command substitution) --------
- {
- vector: 'sub',
- re: /\$\(\s*[\w./-]*\s*<<-?\s*['"]?\w+['"]?[\s\S]*?\)/,
- description: '$(cmd <<TAG ... TAG) — heredoc inside $() substitution',
- },
- {
- vector: 'sub',
- re: /`\s*[\w./-]*\s*<<-?\s*['"]?\w+['"]?[\s\S]*?`/,
- description: '`cmd <<TAG ... TAG` — heredoc inside backtick substitution',
- },
- {
- vector: 'sub',
- re: /\$\(\s*cat\s+<<-?\s*['"]?\w+['"]?/,
- description: '$(cat <<TAG …) — bypass via cat heredoc + substitution',
- },
- {
- vector: 'sub',
- re: /`\s*cat\s+<<-?\s*['"]?\w+['"]?/,
- description: '`cat <<TAG …` — bypass via cat heredoc + backtick',
- },
- /*
- * -------- vector: 'pipe-shell' (heredoc piped to interpreter) -----------
- *
- * ENH-390 (v2.1.33): one tolerant pattern replaces eight literal ones.
- *
- * Each rule used to be `\|\s*\bbash\b` — the interpreter name had to follow
- * the pipe immediately. Every ordinary way of writing the same command
- * therefore fell through to the WARNING tier, and `scripts/unified-bash-pre.js:325`
- * lets warnings through with an audit entry only. Measured before the fix,
- * all of these executed:
- *
- * cat <<EOF … EOF | /bin/bash -> warning (allowed)
- * cat <<EOF … EOF | /usr/bin/sh -> warning (allowed)
- * cat <<EOF … EOF | nice bash -> warning (allowed)
- * cat <<EOF … EOF | command bash -> warning (allowed)
- * cat <<EOF … EOF | "bash" -> warning (allowed)
- * cat <<EOF … EOF | \bash -> warning (allowed)
- *
- * against `… | bash` -> critical (blocked). So bkit differentiation #6, the
- * heredoc bypass defense, was defeated by an absolute path.
- *
- * The delimiter also widened from `\w+` to `[^\s|;&<>'"]+`, so `<<'EOF-1'`
- * and `<<EOF.1` are recognised as delimiters rather than parsed as `EOF`
- * plus body text.
- */
- {
- vector: 'pipe-shell',
- re: new RegExp(
- '<<-?\\s*[\'"]?[^\\s|;&<>\'"]+[\'"]?[\\s\\S]*?'
- // the pipe, then any stack of harmless wrappers…
- + '\\|\\s*(?:(?:command|exec|env|nice|nohup|time|xargs)\\s+(?:-\\S+\\s+)*)*'
- // …optional quote/backslash obfuscation, optional absolute or relative path…
- + '[\'"\\\\]*(?:[\\w./-]*/)?'
- // …and the interpreter itself.
- + '(?:bash|sh|zsh|ksh|dash|ash|fish|csh|tcsh|python[\\d.]*|perl|ruby|node|deno|bun)\\b',
- ),
- description: 'heredoc | interpreter — pipe to a shell/interpreter (path, quote, backslash and wrapper forms included)',
- },
- {
- // An interpreter chosen at runtime cannot be inspected, so it is treated as
- // the most dangerous case rather than the least. Previously `| $SHELL`
- // matched no interpreter rule at all and landed in the warning tier.
- vector: 'pipe-shell',
- re: /<<-?\s*['"]?[^\s|;&<>'"]+['"]?[\s\S]*?\|\s*(?:\$\{?\w+\}?|`[^`]*`|\$\([^)]*\))/,
- description: 'heredoc | $VAR — pipe to an interpreter resolved at runtime (unknown target)',
- },
- {
- // A wrapper on its own is still an execution vector: `… | exec` and
- // `… | env` both run the piped content. The consolidated interpreter rule
- // above requires an interpreter AFTER the wrapper, so these standalone
- // forms need their own rule — dropping them was a coverage regression the
- // v2.1.14 suite (CR-07/CR-08) caught immediately.
- vector: 'pipe-shell',
- re: /<<-?\s*['"]?[^\s|;&<>'"]+['"]?[\s\S]*?\|\s*(?:command|exec|env|nice|nohup|time|xargs)\b/,
- description: 'heredoc | exec/env/... — pipe to an execution wrapper',
- },
- // -------- vector: 'eval-source' (heredoc piped to eval/source/.) --------
- {
- vector: 'eval-source',
- re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\beval\b/,
- description: 'heredoc | eval — pipe to eval',
- },
- {
- vector: 'eval-source',
- re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\bsource\b/,
- description: 'heredoc | source — pipe to source',
- },
- {
- vector: 'eval-source',
- re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\.\s/,
- description: 'heredoc | . path — pipe to POSIX `.` (source)',
- },
- // -------- vector: 'sudo' (heredoc piped to sudo) ------------------------
- {
- vector: 'sudo',
- re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\bsudo\b/,
- description: 'heredoc | sudo — escalated pipe',
- },
- {
- vector: 'sudo',
- re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\bdoas\b/,
- description: 'heredoc | doas — OpenBSD escalated pipe',
- },
- // -------- vector: 'sub' with shell-as-arg ($(bash <<EOF …)) -------------
- {
- vector: 'sub',
- re: /\$\(\s*(?:bash|sh|zsh|ksh|dash|fish)\s+-c\s*['"]?<<-?\s*['"]?\w+['"]?/,
- description: '$(bash -c "<<TAG …") — substitution wrapping shell -c heredoc',
- },
- {
- vector: 'sub',
- re: /\$\(\s*(?:bash|sh|zsh|ksh|dash|fish)\s+<<-?\s*['"]?\w+['"]?/,
- description: '$(bash <<TAG …) — substitution wrapping shell heredoc',
- },
- // -------- vector: 'direct-shell' (interpreter consumes the heredoc as code) --
- /*
- * ENH-461 (v2.1.36) — the most direct execution vector was missing.
- *
- * The list above covers the heredoc reaching a shell through a substitution
- * (`$(bash <<TAG)`), a pipe (`<<TAG | sh`), or xargs. It did not cover the
- * plainest spelling of all:
- *
- * bash <<'EOF'
- * rm -rf /
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 219 on GitHub
- * EOF
- *
- * Measured on v2.1.35 and still on this branch before this rule: the hook
- * ALLOWED it. destructive-detector elides heredoc bodies before matching, by
- * design, so G-001 never sees the delete; and this file graded the form
- * `warning`, which the hook audits and permits. Between the two, the payload
- * executed and nothing objected. Found by running ordinary commands through
- * the real hook rather than through detect() — a module-level test could not
- * have seen it, because neither module is wrong on its own.
- *
- * A script argument means the heredoc is stdin DATA, not code
- * (`bash deploy.sh <<EOF`), so the pattern allows only flags between the
- * interpreter and `<<`. The command must also start a command — after a
- * separator or at the beginning — so `echo bash <<EOF` stays a warning.
- *
- * Scope is shells, matching the rest of this table. `python3 - <<'PY'` is a
- * routine, legitimate way to run a script and is deliberately not included;
- * widening to every interpreter would refuse work people do every day, which
- * is the failure this release exists to remove.
- */
- {
- vector: 'direct-shell',
- re: /(?:^|[\n;|&(])\s*(?:bash|sh|zsh|ksh|dash|fish)\s+(?:-[a-zA-Z]+\s+)*<<-?\s*['"]?\w+/,
- description: 'bash <<TAG … — interpreter executes the heredoc body directly',
- },
- // -------- vector: 'pipe-shell' (here-string + shell, less common variant)
- {
- vector: 'pipe-shell',
- re: /<<<\s*[\s\S]*?\|\s*\b(?:bash|sh|zsh|ksh|dash|fish|exec)\b/,
- description: 'here-string (<<<) | shell — variant of heredoc-pipe',
- },
- // -------- vector: 'pipe-shell' (heredoc → curl|bash anti-pattern) --------
- {
- vector: 'pipe-shell',
- re: /<<-?\s*['"]?\w+['"]?[\s\S]*?\|\s*\bxargs\b\s+(?:bash|sh|zsh|ksh|dash|fish|exec)\b/,
- description: 'heredoc | xargs (bash|sh|…) — xargs-shell escalation',
- },
- ]);
- /**
- * Warning patterns: heredoc present but no execution vector detected.
- * Returns severity='warning' (allow + audit). This list intentionally
- * captures only the heredoc-start surface so audit logs can attribute
- * the pattern without triggering false-positive denies.
- */
- const WARNING_PATTERNS = Object.freeze([
- {
- vector: 'lone-heredoc',
- re: /<<-?\s*['"]?\w+['"]?/,
- description: '<<TAG — lone heredoc start (no exec vector detected)',
- },
- {
- vector: 'lone-heredoc',
- re: /<<<\s*\S/,
- description: '<<< — here-string (no exec vector detected)',
- },
- ]);
- /** Safe alternatives to suggest when severity='critical'. */
- const CRITICAL_ALTERNATIVES = Object.freeze([
- '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)',
- 'Inline a single safe command without heredoc: e.g. `echo "..." | grep foo` instead of `<<EOF … EOF | bash`',
- 'Use bkit checkpoint + manual review: /pdca checkpoint create → review the planned changes → confirm before executing',
- ]);
- /** Safe alternatives to suggest when severity='warning'. */
- const WARNING_ALTERNATIVES = Object.freeze([
- 'Heredoc usage is acceptable for static input (e.g. SQL, JSON, plain text). Verify no `$(`/backtick/pipe-to-shell follows the heredoc.',
- ]);
- /**
- * Detect heredoc-pipe bypass attempt in a Bash command string.
- *
- * Pure function — same input always returns the same verdict. No IO.
- * Returns a structured verdict; callers (hooks) own the decision to
- * deny / allow / audit.
- *
- * @param {string|unknown} command
- * @returns {HeredocVerdict}
- */
- /**
- * Replace the body of every QUOTED heredoc with a placeholder line, keeping the
- * opener and terminator.
- *
- * Quoted delimiter => the shell expands nothing inside the body, so the body is
- * inert data on a program's stdin. Unquoted delimiter => `$(...)` and backticks
- * inside the body DO execute, so those bodies are deliberately left untouched.
- *
- * @param {string} command
- * @returns {string}
- */
- function elideQuotedHeredocBodies(command) {
- if (!command.includes('<<')) return command;
- const lines = command.split('\n');
- const out = [];
- let delimiter = null;
- let terminated = true;
- for (const line of lines) {
- if (delimiter === null) {
- out.push(line);
- // Quoted forms only: <<'EOF' / <<-'EOF' / <<"EOF" / <<-"EOF"
- const m = line.match(/<<-?\s*(?:'([^']+)'|"([^"]+)")/);
- if (m) { delimiter = m[1] || m[2]; terminated = false; }
- continue;
- }
- /*
- * The terminator line is kept WHOLE, not just recognised. A known bypass
- * writes the pipe on that line — `EOF-1 | bash` — so discarding anything
- * after the delimiter would delete the exec vector along with the body.
- * The line is matched by prefix rather than equality for the same reason.
- */
- if (line.trim() === delimiter || line.trimStart().startsWith(delimiter)) {
- out.push('__BKIT_HEREDOC_BODY__');
- out.push(line);
- delimiter = null;
- terminated = true;
- }
- }
- /*
- * An unterminated heredoc means the delimiter was never found, so there is no
- * body boundary to trust. Returning the original text keeps every pattern
- * looking at everything — this helper may only ever remove noise, never
- * remove evidence.
- */
- if (!terminated) return command;
- return out.join('\n');
- }
- /**
- * Split a command into the regions a heredoc pattern may legitimately span.
- *
- * v2.1.34. The `pipe-shell` pattern is
- * `<<-?\s*['"]?TAG['"]?[\s\S]*?\|\s*<interpreter>` — and `[\s\S]*?` crosses
- * newlines, terminator lines, and any number of subsequent commands. So a
- * heredoc that opened and closed cleanly, followed later by a completely
- * unrelated pipe, was graded CRITICAL.
- *
- * Reproduced against this very session: the block
- *
- * python3 - <<'PY'
- * ...
- * PY
- * echo done | python3 -c "..."
- *
- * was refused as "pipe to a shell/interpreter", though the heredoc closed two
- * lines before the pipe and the two share nothing but a process. Exactly the
- * defect class this release fixes elsewhere — a pattern reading past the
- * construct it is analysing — sitting in a guard that refuses commands.
- *
- * A terminated heredoc becomes one region, opener line through terminator line
- * INCLUSIVE, because both known exec vectors live on those lines: `<<EOF | bash`
- * on the opener and `EOF-1 | bash` on the terminator. Everything outside is a
- * separate region. An UNTERMINATED heredoc yields the whole text as one region:
- * with no trustworthy boundary the guard must keep seeing everything.
- *
- * @param {string} text
- * @returns {string[]} regions to match independently
- */
- function heredocRegions(text) {
- const lines = text.split('\n');
- const regions = [];
- let outside = [];
- let current = null;
- let delimiter = null;
- /*
- * A line that BEGINS with a shell continuation token belongs to the command
- * that just ended, not to a new one.
- *
- * Without this the region closes at the terminator and the form
- *
- * cat <<'EOF'
- * …
- * EOF
- * | bash
- *
- * splits the pipe away from its heredoc — twenty-three assertions in
- * tests/qa/v2114-defense-heredoc.test.js exist for exactly that shape, and the
- * first cut of this split turned all of them from critical to warning. A
- * region that ends one token early is a hole, and closing a false positive by
- * opening a hole is not a fix.
- *
- * The distinguishing test is whether the next line CONTINUES the pipeline or
- * STARTS something: `| bash` continues, `echo done | python3 -c …` starts.
- */
- const CONTINUATION = /^\s*(?:[|)&;]|\|\||&&|>>?|<)/;
- let closing = false;
- for (const line of lines) {
- if (closing) {
- if (CONTINUATION.test(line)) { current.push(line); continue; }
- regions.push(current.join('\n'));
- current = null;
- closing = false;
- // fall through: this line starts a new region
- }
- if (delimiter === null) {
- const m = line.match(/<<-?\s*['"]?([^\s|;&<>'"]+)['"]?/);
- if (m) {
- if (outside.length) { regions.push(outside.join('\n')); outside = []; }
- delimiter = m[1];
- current = [line];
- } else {
- outside.push(line);
- }
- continue;
- }
- current.push(line);
- if (line.trim() === delimiter || line.trimStart().startsWith(delimiter)) {
- delimiter = null;
- closing = true; // keep absorbing continuation lines — see below
- }
- }
- // Unterminated: no boundary to trust, so nothing may be split apart.
- if (delimiter !== null) return [text];
- if (closing && current) regions.push(current.join('\n'));
- if (outside.length) regions.push(outside.join('\n'));
- return regions.length ? regions : [text];
- }
- function detect(command) {
- if (typeof command !== 'string' || command.length === 0) {
- return emptyVerdict();
- }
- /*
- * v2.1.34: elide the bodies of QUOTED heredocs before matching.
- *
- * This module's subject is the command STRUCTURE — a heredoc combined with a
- * pipe to an interpreter, a command substitution, or eval. Body text is not
- * structure. Matching against it produced refusals that were indistinguishable
- * from real findings: during work on this release, `python3 - <<'PY' … PY` was
- * blocked as "pipe to an interpreter resolved at runtime (unknown target)"
- * when the interpreter was the literal `python3` and the trigger was the
- * string `Write|Edit` sitting in the body.
- *
- * Only QUOTED delimiters (`<<'EOF'`, `<<"EOF"`) are elided. With a quoted
- * delimiter the shell performs no expansion, so the body genuinely is inert
- * data. An UNQUOTED heredoc still expands `$(...)` and backticks inside the
- * body at runtime — that is a real execution vector and its body is left fully
- * visible to every pattern below. The opener and terminator lines survive in
- * both cases, so a heredoc piped into a shell is still matched exactly as
- * before.
- */
- const bodyElided = elideQuotedHeredocBodies(command);
- // Strip escaped sequences that should not count toward matching:
- // \$\( and \` are escaped substitutions — treat as inert.
- // \\<< is an escaped heredoc start — treat as inert.
- const stripped = bodyElided
- .replace(/\\\$\(/g, '__BKIT_ESCAPED_DOLLAR_PAREN__')
- .replace(/\\`/g, '__BKIT_ESCAPED_BACKTICK__')
- .replace(/\\<</g, '__BKIT_ESCAPED_HEREDOC__');
- /*
- * Critical patterns are evaluated per REGION, not across the whole command —
- * see `heredocRegions`. A pattern that may span `[\s\S]*?` must not span
- * from one command into an unrelated one.
- */
- const regions = heredocRegions(stripped);
- // Evaluate critical patterns first; short-circuit on first hit.
- for (const p of CRITICAL_PATTERNS) {
- if (regions.some((r) => { p.re.lastIndex = 0; return p.re.test(r); })) {
- return {
- matched: true,
- severity: 'critical',
- pattern: p.re.source,
- vector: p.vector,
- reason: `bkit ENH-310 heredoc-bypass guard: ${p.description}`,
- alternatives: CRITICAL_ALTERNATIVES.slice(),
- };
- }
- }
- // Then warning patterns (heredoc present but no exec vector).
- for (const p of WARNING_PATTERNS) {
- if (p.re.test(stripped)) {
- return {
- matched: true,
- severity: 'warning',
- pattern: p.re.source,
- vector: p.vector,
- reason: `bkit ENH-310 heredoc audit: ${p.description}`,
- alternatives: WARNING_ALTERNATIVES.slice(),
- };
- }
- }
- return emptyVerdict();
- }
- function emptyVerdict() {
- return {
- matched: false,
- severity: null,
- pattern: null,
- vector: null,
- reason: '',
- alternatives: [],
- };
- }
- module.exports = {
- detect,
- // Exposed for contract tests + observability — DO NOT mutate at runtime
- // (Object.freeze enforces immutability; mutation in non-strict mode is silent,
- // in strict mode throws).
- CRITICAL_PATTERNS,
- WARNING_PATTERNS,
- CRITICAL_ALTERNATIVES,
- WARNING_ALTERNATIVES,
- };
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.