npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jayyuen66/dsh-danger-guard

v0.1.23

Published

dsh 插件:危险命令物理拦截(git --no-verify / rm -rf / curl|sh / 密钥路径编辑)+ 首次编辑事实强制门(gateguard 移植,ECC MIT)

Readme

A pre-execution guard for dsh: dangerous shell commands and credential edits are physically refused before dispatch, and the model is handed the reason plus a working way out.

Contents

What it does

  • It blocks, it does not advise. The decision lives in the synchronous predicate on ctx.tools.guard: returning a string rejects that call. The host turns the reason into the call's error result, so the model reads "why this was refused, and what to write instead" - not a silent failure.
  • Three defences:
    • Dangerous bash / pwsh commands (bashVerdictOf in lib/danger-rules.ts): git hook bypass, catastrophic rm, download-and-run, long-running dev servers, the git destruction family, the infrastructure destruction family, secret-path deletion/read, and GitHub remote destruction. terminal_send from the persistent-terminal bundle (@deepseek-ai/dsh-tool-terminal, still under the host's experimental/ tree) is folded into the same face: its text is judged as a command, with the terminal backend's platform dialect.
    • Credential and secret paths on edit/write/apply_patch tools (secretPathDeny) - matched by argument key shape for single-target editors, and by the official patch parser for apply_patch, never by tool name, because tool names drift with the provider.
      • Native reads (read, read_image, str_replace_editor view, and MCP read tools such as read_file / read_multiple_files) are not hard-denied by that write gate. Their secret targets are judged by the same secretRead row as the shell face: ask in read-only / workspace-write / unknown, allow in full access, and deny when the mode cannot ask. A read that carries a write payload (content, new_string, a write action) stays on the write gate and is still refused.
      • The editor path face has a second refusal key, opaqueTarget: a target longer than the judgable length limit is neither confirmed nor cleared as a credential, so it is denied with a "paste the path to the user, do not retry verbatim" message. Same principle as nestedShellUnconfirmed on the bash side - cannot judge is not the same as safe. (An over-long command resolves to nestedShellUnconfirmed instead.)
    • The first-edit fact gate (lib/fact-gate.ts): an edit that has not read its target, or that touches a risky surface without layer evidence, gets refused with an action list naming the missing evidence. apply_patch is judged per operation target (a move counts both its source and its destination); an empty patch, one the official parser rejects, or one over APPLY_PATCH_TARGET_LIMIT (128) is refused outright instead of partially applied, and that refusal does not depend on factGateEnabled. From host 0.2.3-alpha.3 on, apply_patch is registered by default alongside edit (applyPatch follows the edit switch), so this per-target path is the default surface, not an opt-in.
      • "Has read" counts successful calls only: the evidence ledger joins tool/call to tool/result by callId, and a call without one has unknown status and does not count (the host appends the call before dispatching, so a call that never ran or already failed looks exactly like a successful one in the log).
      • "Which revision was read" lives in lib/read-basis.ts: the observation baseline and the staleness point are one record, and it is committed only after a successful result - a failed or blocked read cannot advance the baseline and thereby swallow an external change. Once an external change is attributed it stays in force until a successful read actually lands.
  • Preflight only hands the reference surface over early (face A, one waterfall):
    • Face A, on tools/post-execute: a read-only inspection (read / view / str_replace_editor view) returns its reference surface with that read's result (PostToolDecision.accept{additionalContexts}), so the model sees "who references this" before its next edit.
    • Writes are no longer pre-read or pre-credited by preflight: a blind edit gets the fact gate's action list, and the model must read the target itself; face A then attaches the reference surface to that read result. This removes the old "retry as-is and it will pass" shortcut that let the model skip the facts.
    • This is why not agent.inject(): that API queues context for the next pre-step, while decisions are made per step - evidence would arrive after the edit landed.
    • The scan is bounded by hard caps (files, directories, per-file bytes, findings) and merges cancellation with a wall clock; the platform never abandons a pending tool-policy promise, so unbounded work is not an option.
    • The credential rule: "the traversal was not truncated" or "references were found". A correctly scoped search by the model is itself not exhaustive, so demanding exhaustiveness here would be stricter than the gate. But "zero hits and truncated" grants nothing - every false negative lives there, and half an "I looked" is worse than none.
    • A zero-hit conclusion requires the scan to have actually read what it walked: the scan records files it walked past without reading their bodies (over the size cap, quarantined credentials, unreadable). If any of those remain - or the traversal itself was truncated - the block does not claim "nothing references the target"; it says the zero-hit is not exhaustive. A found hit is exempt: evidence of existence needs no exhaustiveness.
  • Every refusal carries its way out. BashVerdict holds a structured Fix: the git bypass names the offending flags, catastrophic rm names the offending targets (excluding the safe ones). The model gets "change these words and it passes", not a verdict.
  • On an ask hit, one read-only blast-radius rehearsal runs (fixed command table, no model input interpolated) and its output is rendered per locale into the approval request's reason and displayReason. Empty output only means the probe printed nothing; it does not prove the original action changes nothing. A command carrying -C/--git-dir/--work-tree, a failed policy resolution, an unknown session cwd, or host-truncated output falls back to a blind ask.
  • Repeats are not re-reported (AskDeduper): same session + same rule key + same command text no longer goes back to the lesson bus and its rehearsal is not recomputed - but the verdict and the prompt stay exactly as they were. What this suppresses is lesson-card fragmentation, not a user interruption; deduplication must never become a silent pass.

How a verdict is decided

  • Only bash and pwsh command strings are judged, plus terminal_send's text, plus MCP tools registered as mcp__<server>__<tool> whose arguments carry command / cmd (see Known boundaries); a non-string command / text passes (no guessing). The string is split at ;, &&, ||, |, newline, &, (, ), backtick, with no splitting inside quotes.
  • Segment splitting, word lexing, the structure view and the unclosed-quote check are four projections of one POSIX state machine (lib/command-segments.ts). Two different machines would give the same string opposite verdicts in different predicates.
  • Wrapper words (sudo, su, ssh, env, time, nice, stdbuf, timeout, taskset, watch, setsid, doas, pkexec, nohup, exec, command, xargs, parallel, and the rest of the table in lib/prefix-tables.ts; leading VAR=x counts too), binary path prefixes (matched by basename, so /usr/bin/sudo is no escape), quoting, and backslash continuations are not escape hatches. A quoted flag or quoted command word is a working spelling: git commit "--no-verify" really skips the hook, and "rm" -rf ~ judges like the unquoted form.
  • Because a per-tool option table can never be complete, a wrapper-led segment also treats every following word position as a candidate command head.
  • Principle: when unsure, let it through - with one exception, an execution face you cannot see. An unextractable nested -c / eval body, nesting past the drill-down limit, or a command past the judgable length limit become nestedShellUnconfirmed; a segment head that is a non-shell interpreter running a code string or reading code from stdin (python3.14 -c, python -, node -e, perl -e, php -r…) becomes interpreterCode. Launcher prefixes (uv run --project ., poetry run, pnpm exec, npm exec, npx, bunx) and attached flags (-cprint(1), -lc) are recognized on the same face, and value-taking launcher options such as --project are not mistaken for the command. Both need explicit user confirmation, or a rewrite as one plain, quote-balanced layer. interpreterCode is not deferred to the sandbox in workspace-write: a code string can cause network/process side effects, while the sandbox only governs writes.
  • Severity ordering: when one command holds both an ask segment and a deny segment, the whole string resolves as deny (the scan continues until it has one). Without this, the leading ask would end the scan early and the later catastrophe would never be judged.

Install

dsh plugin --profile web add @jayyuen66/dsh-danger-guard

Remove with dsh plugin --profile web remove @jayyuen66/dsh-danger-guard. The package is on the public npm registry, so installation needs no credentials and no scoped-registry line.

  • Requires Node.js ^24.22.3 || >=26.13.1. This is an ESM-only package. The range is the host's own floor, copied verbatim: every host on the 0.2.3 line from alpha.2 up declares Node ^24.22.3 || >=26.13.1 (Node 25 sits outside it), so any other claim here would promise a runtime the host never starts on.
  • Requires host dsh on the 0.2.3-alpha.3 host line or later. The highest host version this release was developed and tested against is 0.2.3-alpha.3; that number records when this release was cut, not the upper bound of the range. The requirement the host actually reads is engines.dsh (^0.2.3-alpha.3), and it decides alone: evaluatePluginCompatibility returns on the engines.dsh branch before it ever looks at peerDependencies, so the @deepseek-ai/dsh* peers are not consulted for compatibility here. Prereleases participate in the comparison: the host matches engines.dsh with semver's includePrerelease option (packages/boot/app-boot/src/plugin-compatibility.ts), so every host version at or above 0.2.3-alpha.3 and below 0.3.0 satisfies the range — prereleases of later tuples included, so 0.2.4-rc.1 does satisfy. 0.2.2 and earlier, and 0.3.0 or later (its own prereleases included), do not — a refused host needs the explicit risk grant dsh plugin --profile <p> allow-version <pkg>@<ver> --dsh-version <exact> --accept-risk. The @deepseek-ai/dsh* peers carry the same support-window range because the host supplies the actual copy at runtime, while @deepseek-ai/schemastery carries the window ^3.20.0-alpha.2, which admits the host's own copy on the 0.2.3 line (3.20.0-alpha.2); an exact value there is what stops npm's stricter peer resolution at ERESOLVE; the exact pins in devDependencies are the separate, compile-time discipline (enforced by test/publish-manifest.test.ts): this plugin's types and nominal brands are coupled to the host ABI, and silently following it upward is how a second copy of the host type surface ends up loaded. The support window rolls: at publish time this package is checked against every released host version inside the window — the judgement is the host's --dump-config layer line for this package, while the settings card and its namespace calls are verified once in full on the release's development baseline — and re-verified once the window moves, so the version number in this bullet is not a standing promise.
  • No @deepseek-ai/* under dependencies, by contract (test/publish-manifest.test.ts enforces it). Consumer profiles install with nodeLinker: hoisted and autoInstallPeers: false, so a host package under dependencies is materialized as a real directory next to the copy the running host already loaded - a second, host-independent copy of official code inside the profile. The concrete failure this contract was pinned against sat on the 0.2.2 host line: dsh-tools then keyed its tool-runtime scheduler with a plain Symbol (not Symbol.for), so the profile copy could never share the host's scheduler slot and native tool calls failed while build, typecheck and coverage gates stayed green. A later host refactor removed that key (the 0.2.3 source no longer declares it), so the contract stands as a manifest-level rule: this package consumes host code only through the host's own copies. Peers and devDependencies never enter the profile, so they cannot produce a second copy.
  • Host packages imported for value stay externalized. @deepseek-ai/dsh-brand, @deepseek-ai/dsh-llm, @deepseek-ai/dsh-typert-protocol and @deepseek-ai/schemastery are value imports (brandNumber, createUserMessage, TypertRemoteService, import Schema from …). The externalization list is derived by the shared build orchestration from dependencies ∪ peerDependencies (build-host.mjs only declares the artifact table); a devDependencies-only entry would let the bundler inline the official function body, giving this package its own copy of the official constructor. A required peer satisfies both halves: the specifier stays external, and the profile installs nothing extra. zod is a plain dependency (imported for value by lib/tool-ledger.ts and the settings card's src/stats-reader.ts).
  • The artifact is minified on purpose (minify: true in build-host.mjs). test/build-host.test.ts pins the bare specifiers in both host.js and settings.js with whitespace-tolerant regexes (minification yields from"x"), and enforces externalization structurally through the chunk's inlinedModules list - text checks on function names would be permanently green under mangling.
  • No TypeScript declarations ship. This is a terminal package: the host loads host.js, settings.js and client.js by package name, and no TypeScript program imports this package by name. exports therefore carries runtime targets only; ./client and ./cordis.patch.yml likewise have no types condition.
  • The plugin page reads this package's locale files. locale/en.json and locale/zh.json carry meta.title, meta.description and meta.detail; the detail page is docs/DETAIL.md / docs/DETAIL.zh.md. The locale/*.json subpath is exported and both locale/ and docs/ are listed in files, so an installed tarball has them.
  • Build artifacts are not committed; prepack rebuilds them, so what ships is always what the current source produces.

Shared version floor

If your profile pins @jayyuen66/dsh-plugin-shared with a pnpm overrides entry, that pin must be at least the version this package declares. A lower pin installs a copy without the names imported at runtime, and the host then reports N entries did not activate together with does not provide an export named ... at boot - the package installs fine and never loads, and no per-repository CI run can see it. From 0.2.3-alpha.3 on, the bundle's dsh-plugin-shared supply row is bound by mergeBundlePlugins to the copy resolved for this package (it declares the dependency), so the row no longer depends on which other bundle happens to supply shared - a profile overrides pin still applies on top, and the floor above is unchanged.

Verify it is live

  1. Mounted: the settings page lists a "danger-guard danger block" row, and dsh --profile web --dump-config shows this package's layer.
    • --dump-config is the only accepted "it is in the layer stack" signal, and it is not read-only - it rewrites that profile's root assembly file. Pass/fail therefore reads layer lines from stdout and checks stderr separately; an unmatched patch target appears only on stderr, so the exit code alone proves nothing.
    • A layer line may read # == <layer> or # == <layer>, patched by <path>; any check must accept the second form or it will report "not installed" about a layer that is really there.
  2. Blocking: ask the agent to run git commit --no-verify — noVerify is denied in all four presets (read-only, workspace write, full access and auto review all deny it; bypassing git hooks is not a sandbox decision the host can hand out). The call itself must fail with Error: <reason> and name a way out. A "no change in behaviour" result there means the gate is not mounted, not that the rule is lenient.
  3. Settings: open the card, toggle a value, Save becomes enabled, and the write returns 200. On a non-loopback page the controls are disabled with a read-only status.
  4. Stats readout: opening the card (plus a manual Refresh) invokes one Remote method on the dangerGuardStats namespace. It is read on demand and never subscribed - verdict stats only move while the agent works, and a value cached across a host reconnect is exactly the staleness this design avoids.

What it does not provide

Worth knowing before you look for them:

  • It registers no tools. There is no guard_status or similar model tool - the whole surface is the ctx.tools.guard predicate plus one preflight waterfall subscription (face A).
  • It exposes no HTTP endpoint of its own. The single Remote namespace it registers, dangerGuardStats, exists only to feed the settings card's readout through the host's /api gateway; its one method is stats (no arguments, JSON result). There is no other route beyond /api/dangerGuardStats/stats, and no CSRF or trust gate in this package - the host's gateway owns all of that.
  • It adds no CLI subcommand. dsh danger-guard … does not exist.
  • It keeps no file on disk and makes no network call (see Data and privacy for the single read-only subprocess).
  • What it does consume optionally: the lessonLoop bus (report/pass), sessionProjections for the tool ledger, fs for preflight evidence, and workingDirectory for the current directory base. Every one of those is an optional child injection - a profile without them keeps blocking, it just falls back.

Enabling it in dsh

  • Bundle form: dsh.bundle.patch in package.json points at cordis.patch.yml, and dsh plugin add/remove maintains the assembly layer.
  • The patch carries the bulkhead pair — - id: danger-guard (the guard half, no Config, name points at the package root) and - id: danger-guard-settings (the settings half, strict schema, name points at the ./settings subpath) — plus a - id: dsh-plugin-shared supplier row (keep it enabled; disabling it removes the cards' shared component supply). The card components come from the shared client row, externalized as @jayyuen66/dsh-plugin-shared/client; the host module table provides react, zod and that shared row.
    • Only the guard line brings up the card: the host scans dsh.client on bare package-name entries only, so the settings line's subpath name is deliberate rather than an oversight.
    • The card loads on the web platform only, as "danger-guard danger block" in the settings plugin list.
  • Scope: the guard registers in the scope that mounts it. Since 0.2.3-alpha.3, ctx.tools.guard attaches to the calling context's scope (guards.effect(this.ctx, ...)), and the host checks [global, ...chainLayers(agent)]. This bundle inserts its rows at the profile root, so the guard is global and covers every agent chain. Mounting the package inside an agent preset or another scoped group narrows it to that scope's chain - and the single-instance lock is process-wide (ctx.reflect.provide), so a second scoped mount steps aside and that scope runs unguarded. Keep one mount, at the profile root.
  • Deployment defaults sit on the settings row's config:; precedence is settings-card runtime value > row config > the built-in base (BUILTIN_BASE in lib/settings-schema.ts).
    • An explicit undefined in the row does not override the base, and illegal numbers (e.g. maxDenies: 0) fall back to the built-in default - 0 would switch the fact gate off entirely.
    • Defaults on the guard row are inert by design: that entry takes no config argument at all.
  • Failures go the conservative way. Only the settings row carries the strict schema, so one broken user-layer config line fails that entry alone; the guard entry falls back to the built-in base and warns once. apply throws only when the settings surface itself is missing. A missing tools service does not throw (the registration is optional-chained), but tools is in inject, so cordis never activates the entry and the startup diagnostic names it - "no gate mounted, and the host says so".
  • When dshmarket hot-mounts the package alongside the bundle layer, only one copy runs. dshmarket mounts the same host.js again in the same process at runtime; the second apply sees the package already registered in that scope, steps aside entirely, and leaves one console line - interception and stats stay with the registered copy, with no second guard and no duplicate listeners. The lock is released when that copy's fiber unloads, so a later mount can claim it again.

What the rules block

| Family | Blocks | Passes / way out | |---|---|---| | Git hook bypass | --no-verify and its unambiguous abbreviations on commit / push / merge / cherry-pick / rebase / am; the short -n on commit / am; git -c core.hooksPath= and git config core.hooksPath <dir> (including --global and the = form). Git arguments are walked by role: short clusters expand letter by letter, a value-taking option's argument is never read as a flag, everything after -- is a pathspec, and -c's value is what gets checked | git push -n (dry run), git cherry-pick -n (no commit), git rebase -n (no stat), git config --get / --unset / --list core.hooksPath, and that text appearing inside a commit message | | Catastrophic rm | The threshold is per command-word track. On the POSIX/cmd track, recursion and force are required, the one exception being an upper-case -R anywhere in a short cluster, which is disaster-level on its own. On the Remove-Item / ri track (and, under the Windows dialect, its rm / del / rd aliases), any Recurse form alone against a disaster target is enough - no -Force required, because that form silently deletes a whole tree. Targets that count: /, ~ and ~/…, the literal home path, $HOME and every ${HOME…} form, . / .. / ../…, whole trees under system and user directory prefixes, and absolute globs / brace expansions, with the path lexically normalized first. The command-word side also covers the pwsh Remove-Item family and the cmd del / rd builtins, matched case-insensitively; cmd.exe /c … itself stays outside this table (see Known boundaries). The find/xargs projection reuses this rule, while a predicate/scoped find deletion is judged as findDelete (ask) instead of hard-denying | Relative cleanup inside the project (rm -rf node_modules, ./dist), force-only (rm -f ~) or lower-case recursion-only (rm -r ~) on the POSIX track - this slot is keyed by spelling, and the asymmetry is deliberate; Remove-Item -Recurse ./build; /var and /tmp (deliberately excluded: a false block there costs more than a miss); a different segment such as /usrx | | Download-and-run | A shell or script interpreter after curl / wget / fetch, including through sudo, a path-prefixed interpreter, xargs, or parallel, and the reversed process substitutions (sh <(curl …), python <(curl …), source <(curl …), . <(curl …)). The executor set covers sh / bash / zsh / dash / ksh, pwsh / powershell / iex / Invoke-Expression, and Python / Node / Perl / Ruby / PHP / Lua / osascript because they all execute stdin as code. $( ) inside double quotes is an execution face too, so echo "$(curl x \| sh)" is denied. The PowerShell family counts on both ends: Invoke-WebRequest / Invoke-RestMethod / iwr / irm feeding pwsh / powershell / iex / Invoke-Expression judges like curl … \| sh | curl -O, curl … \| jq .name, cat x \| grep foo, ls \| sh with nothing downloaded, source ./setup.sh, and a literal \| inside quotes | | Long-running dev server | Bare vite / next / nuxt / watchexec, webpack serve / --watch, cargo watch, npm / pnpm / yarn / bun run dev / watch / serve / start, any script name rooted in dev, and a long-running package via npx / bunx / exec / dlx (a version selector does not create a new identity). vite build --watch is still judged long-running (detection only: every preset hands this family to the host's cooperative timeout - see the preset table below). The one-shot exemption is read only in subcommand position | npm test, npm run build, vite build, next build, webpack --config prod.js, cargo run / check / test, vitest run, and confirmed one-shot subcommands (vite optimize, next lint, nuxt prepare) | | Secret path edits | Any file inside .ssh / .gnupg / .aws / .kube / .docker, also in relative form; the id_rsa / id_ed25519 / id_ecdsa stems with their copy suffixes; names ending .pem / .key / .p12 / .pfx / .keystore / .jks; the whole .env family; .envrc / .npmrc / .pypirc / .netrc / .pgpass / .git-credentials; credentials.json, service-account*.json, token.json; secret(s).yaml / yml / json; .git/config. Targets are normalized first and resolved against the session cwd when the host supplies one; backslashed Windows paths judge the same | .env.example / .sample / .template / .defaults, api.key.ts, main.pem.tsx, .gitignore, mysecrets.yaml, secrets.yaml.bak, myid_rsa | | Secret deletion family (secretDelete) | rm-family deletions that hit the secret/credential paths above or .git metadata; glob targets that can expand onto a secret path are included, and source tokens fed to xargs rm plus the command's own targets are checked; find start paths, -name/-path values, -delete, -exec rm, and an rm wrapped in sh -c all pass the same secret face; braces (.env{,.local}, ~/.ssh/{id_rsa,config}) expand per shell semantics and are judged item by item | Asks in workspace-write/unknown, denies in read-only, allows in full access; no sandbox deferral. .env.example and non-secret relative paths pass | | Secret read family (secretRead) | cat / head / tail / less / more / bat / strings / xxd / od / base64, and pattern-first grep / rg / sed / awk reading a secret path, including attached -e / -f / --regexp= / --expression= forms and xargs sources; find start paths/-name values and -exec cat (including sh -c wrappers) are judged; brace expansion is the same as deletion | Asks wherever the mode can ask; no sandbox deferral. Non-secret files, and grep .env README.md, pass | | Native / MCP read tools (secretRead) | read, read_image, str_replace_editor view, and MCP read suffixes (read_file, read_text_file, get_file_contents, view_file, read_multiple_files) whose target (file_path / path / paths, including object items) hits the secret-path table. The same host-resolved realpath forms and extraSecretPatterns as the write gate are used | Ask in read-only / workspace-write / unknown, allow in full access, deny when the mode cannot ask. A read with a write payload or a write action is not a read for this row and stays hard-denied by the write gate. Non-secret files pass | | GitHub remote destruction family (ghDestroy) | gh repo delete / archive / rename / transfer; the delete subcommands of gh release (incl. delete-asset), gh project, gh codespace, gh run, gh cache, gh secret, gh variable, gh label, gh issue, gh gist; gh pr merge --admin; gh api -X DELETE / --method DELETE; and a visible gh api graphql mutation | Asks; read-only queries such as gh repo view / gh pr view / gh release view and GraphQL queries pass. The local sandbox does not govern the network | | Git destruction family (all ask) | reset --hard (including unambiguous abbreviations such as --har), checkout -- <path> / checkout . / checkout -f / checkout <rev> <path>, restore <path> (--staged alone is not judged - it only moves the index), clean -f* (including -xf / -x -f), stash drop / clear, branch -D / --delete --force, push -f / --force / --force-with-lease / +refspec. Short-option values are parsed per subcommand (push -u and clean -x are boolean, commit -m and clean -e take values). These share one walk with the no-verify rule | Every one of them has a legitimate use. Hard-refusing a "dangerous but sometimes correct" operation pushes the model into workarounds - after git reset --hard is refused it may just rm those files, a worse spelling that nothing blocks. So these ask instead | | Infrastructure destruction family (all ask) | terraform destroy / terraform apply -destroy, terraform apply -auto-approve, docker … prune, docker compose down -v/--volumes, kubectl delete, and the migration family (manage.py migrate, prisma migrate, rails db:migrate, alembic upgrade, flyway migrate, typeorm migration:run, knex migrate:latest…) | plan -destroy (a plan only prints), apply -destroy=false, a bare apply (terraform asks by itself), kubectl --dry-run=client / server (only those values; none executes), docker compose down without -v, read-only verbs (prisma migrate status, flyway info) and tool-specific dry-run flags (manage.py --plan / --sql, alembic --sql). The migration family additionally accepts launcher prefixes such as uv run / poetry run / pnpm exec / python -m, while still rejecting a command-shaped string in documentation |

Settings

Settings live on the danger-guard card in the plugin detail page, and the card is their documentation: every visible field is grouped by purpose and carries a one-line hint in the host's language. Defaults, ranges, and the effect of changing each value stay there, so this README does not keep a second field list that can drift.

The settings namespace is danger-guard-settings; built-in defaults live in BUILTIN_BASE. Every value written through the card is read again at the next decision, so changes take effect without restarting the host.

preflightEnabled is the only field without a card control. It is volatile, but the settings entry registers its form with auto: false; set it in the settings row's config: block instead. Turning it off only removes the reference context attached to a read result, not the fact gate's evidence requirements.

There is no allowlist for dangerous commands or disaster targets. The extra* word lists and refSearchTools widen detection/evidence sources, not permissions: adding a name to refSearchTools lets the fact gate accept evidence from that tool, so it makes the gate easier to satisfy rather than tighter. For a false positive on the command/target rules, the routes are: turn enabled (or only factGateEnabled) off temporarily, take the maxDenies quota release, or rewrite the command as the denial text suggests. For a false positive on the fact gate, adding the search tool you actually use to refSearchTools is a fourth, configuration-level route.

What each permission preset blocks

The host presets bundle a sandbox mode with an approval policy, and the official sandbox governs file effects only: network and process visibility are outside its vocabulary, and even the tightest mode merely refuses writes and allows every read. This package covers those two faces - and yields the write-side rules whenever the sandbox genuinely governs them.

| Rule family | Read-only | Workspace write | Full access | Auto review | |---|---|---|---|---| | noVerify (git hook bypass) | deny | deny | deny | deny | | rmrf (encloses a writable root / home / root) | allow¹ | deny | allow | deny | | rmrf (the sandbox fully covers this target) | allow | allow | allow | allow | | findDelete (predicate/scoped find deletion) | deny | ask | allow | allow | | Secret deletion family (secretDelete) | deny | ask | allow | allow | | Secret read family (secretRead) | ask | ask | allow | allow | | pipeShell (download-and-execute) | ask | deny | allow | deny | | devServer (long-running server) | allow² | allow² | allow² | allow² | | interpreterCode (interpreter code string/stdin) | ask | ask | allow | allow | | nestedShellUnconfirmed (cannot tell) | ask | allow | allow | allow | | GitHub remote destruction family (ghDestroy) | ask | ask | allow | allow | | Git destruction family | ask | ask | allow | allow | | Infrastructure destruction family | ask | ask | allow | allow |

¹ Read-only refuses every write, so nothing can be partially deleted - every target is fully covered and the whole family goes to the host, which returns its official denial marker plus the sandbox_permissions escalation path. ² The host's cooperative timeout and promoteOnTimeout already govern long-running commands, so this rule is no longer a safety property and goes to the host entirely.

  • Full access means zero guardrails - but only in the "cannot ask" arm, and with one exception. The shipped preset pins this mode to approval: never, so choosing it means "do not block, do not ask": hits only increment the card's stats and the model sees no change, except noVerify, which stays denied because bypassing a git hook is unrelated to the sandbox and would otherwise be the only way around the guard. danger-full-access + ask (a custom combination, or the default when the preset service is absent) can still ask, and that arm reuses the workspace-write column, with one exception: nestedShellUnconfirmed stays ask because the workspace-write allow relies on the resident sandbox still stopping writes, while this arm has no sandbox. Every other key (including findDelete and secret delete/read) takes the workspace-write value - what asks there still asks, what allows there still allows, and rmrf stays denied.
  • Auto review keeps three deterministic hard stops (rmrf, pipeShell, and noVerify). The reviewer is an LLM, its allow is not the user's approval, and this preset's sandbox restricts nothing; noVerify stays denied for the same reason every other column denies it - bypassing a git hook is unrelated to the sandbox. Everything else goes to the reviewer so the same action is never asked about twice.
  • One hard rule: whether asking is possible decides whether ask can land. never returns rejected deterministically before any answerer runs (with the host swapping in its own wording), so a rule that should ask is collapsed to deny here - carrying a dedicated paragraph on "this preset cannot ask, switch to one that can" so the model is not left with a bare "no".
  • When no sandbox mode is readable (no confining executor, or an unexpected service shape) the guard takes a conservative column of its own: write-side rules block, "cannot tell" still asks. It deliberately does not reuse the workspace-write column, which relies on the sandbox stopping part of the damage.
  • The type makes two properties structural: a missing tier is a compile error, and one key belonging to both tiers is impossible. The latter matters because tools.guard is synchronous while approval is async, and the host runs the guard again after approval passes - a key claimed by both tiers would show up as the user pressing Allow and still being refused.

The sandbox deferral, and why only rmrf gets one

  • Deferral happens only when the executor reports it confines, its own reported default mode is itself blocking, the resolved mode is not full access, and containment fails in both directions: the target must neither enclose a writable root nor lie inside one.
  • The writable-root table the containment test reads holds the workspace root, every additional writable root the executor granted (additionalWritableRoots from sandboxPolicy.resolve()), /tmp and the platform temp directory. On Windows the host grants additional directories to file tools only, not to sandboxed processes (the host's sandbox-policy states this verbatim in the policy context), so this package's terminal-coverage table excludes them there. If any entry cannot be read, the whole table is treated as untrusted and no scope is granted at all: dropping only the unreadable entry would make targets underneath it look fully covered and defer a deletion that would really run. A host that does not report the field counts as granting no extra root.
  • That last clause is deliberately strict. workspace-write means files inside the workspace are writable, so rm -rf ~ (workspace under ~) wipes the workspace first and only then hits the boundary - a sandbox is a path allow-list and offers no atomicity. So ~, /, . and .. are never deferred; only things like rm -rf /etc/foo or rm -rf ~/Downloads are.
  • secretPath gets no deferral at all: the local and sandboxed filesystem backends are mutually exclusive mounts and there is no readable face for "which one is composed", so the discipline is not to guess. The costs are asymmetric anyway - a false block sends the user to their terminal, a miss leaks credentials and is hard to notice.

Known boundaries

Registered honestly, one entry per class, each pinned by a test at its current verdict. Full case-by-case reasoning lives next to those tests rather than here.

  • cmd as a segment head is not judged. cmd.exe /c rd /s /q C:\Windows and its path-prefixed or extension-less spellings still escape: cmd is in neither the delete command-word table nor the drill-down list, and its quoting rules (%VAR%, ^ continuations, & that does not split segments) are far enough from POSIX that reading its /c body with the POSIX lexer would open a batch of false blocks. The PowerShell family is covered instead: the -c / -Command body of pwsh / powershell is extracted with join semantics, judged segment by segment, and forced onto the Windows glyph track inside that body. -File / -EncodedCommand without a code flag means the thing to run is by design not in the input, so it becomes a confirmation request.
  • Dry-run modifiers are not read (Remove-Item -WhatIf -Recurse ~ still denies). -WhatIf / -Confirm only make PowerShell print what it would do; treating dry-run as an exempt class is a policy decision nobody has made yet, so the current verdict is pinned as-is.
  • Bare ~user without a separator is not judged. Whether rm -rf ~root expands depends on the machine's account table, and this guard neither touches the filesystem nor looks up users. The delimited form ~user/… is covered.
  • A PATH-level interpreter running a code string always asks. python3 -c "print(1)", python3.14 -c "print(1)", and python - are benign but still need confirmation - that is the price of "invisible means not silently allowed", and workspace-write asks too.
  • MCP command tools are judged as shell text, but have no bash sandbox. A tool named mcp__<server>__<tool> whose arguments carry command / cmd is normalized to bash (POSIX) or pwsh (Win32) and judged by the same rules. MCP stdio servers are spawned directly, so there is no bash sandbox behind these calls: write-side rules are not deferred to the resident sandbox for them. An explicit non-empty sandbox_permissions on bash stays outside that deferral too: a strictly wider request runs at the approved mode rather than the resident preset, so rmrf stays denied. From 0.2.3-alpha.3 on, an equal or weaker request is a host no-op (no approval; the call runs at the effective mode, not the requested one): only an equal request inside read-only / workspace-write still counts as confined and gets the deferral; a weaker request, an equal danger-full-access request and an unreadable mode all stay out of it, so the cost is a possible extra refusal, never a hole. code is deliberately not recognized: CUA/PTC code runs in its own sandbox and stays outside this face.
  • MCP file tools enter the fact gate by suffix. Names ending in write_file, edit_file, create_file, replace_in_file, patch_file, apply_patch, str_replace, write_text_file, append_file, replace_text, insert_text, delete_text_range or apply_diff are treated as edit tools, and their path / file_path is the gated target; write text from content / file_text / new_text / new_string / new_str / text enters this session's own edit ledger. Names ending in read_file, read_text_file, get_file_contents, view_file or read_multiple_files count as read evidence, and read_multiple_files records and settles each target in its paths / file_paths array. move_file / rename_file / delete_file are still not guessed: they are pair-target or delete shapes, and taking them in requires parsing both source and destination first. Other unknown MCP tool names remain unguessed - an unknown tool that writes files can still bypass the evidence gate, and its file effects remain the host's sandbox responsibility.
  • bash redirection writes are outside the fact gate. The gate hangs on the edit / write / str_replace_editor / apply_patch tools and the MCP edit tools above; printf > f, tee, cat >, sed -i bypass the "gather evidence first" requirement. Covering them means parsing shell redirection and in-place editors.
  • terminal_send is judged as shell text, not as terminal state. The call carries no backend type, so a REPL session's input is scanned with the same shell rules (benign REPL input can be over-blocked), and a command split across multiple sends can evade the lexical check. submit: false is not exempted: the text may execute on a later Enter. The user's own typing into a terminal is not seen by the guard at all.
  • Some ask-tier forms are blind. A bare git checkout <path> is lexically indistinguishable from switching branches (the explicit checkout <rev> <path> form is judged), and git push --force does not resolve its target branch. Writes made through shell redirection and edits to a target that changed outside the session keep a small residual window.
  • Msys/Cygwin mount forms are not translated. On a real Windows host rm -rf /c/Windows/System32 needs a mount table, which is a new dependency plus a new design decision.
  • Content self-proof stops at 1 MiB. Attributing an mtime jump to this session's own edit reads the target back and looks for the written text. Above that size the guard returns "unknown" instead of holding the synchronous tool-call path while it reads the whole file, so the change counts as external and one successful read is required before the next edit.

Extended patterns are the configurer's responsibility

Fragments in extraSecretPatterns are validated one by one at load time with new RegExp(pattern, "u") and compiled for matching with the iu flags; the length cap only rejects obviously malformed input. It cannot rule out catastrophic backtracking, and a pathological pattern can make the synchronous guard take a long time on the tool-call path. Whether a pattern is safe is the configurer's responsibility: this plugin neither statically analyses patterns nor imposes a wall-clock budget on matching. An invalid fragment never takes effect and is named in the log at that validation; a fragment written after the entry was assembled is named on the next secret-path verdict, and the same string is named only once. Validation and compilation are accounted per distinct list, so the verdict path reuses the compiled set instead of rebuilding it on every tool call.

Data and privacy

| Aspect | Content | |---|---| | Nothing is written, nothing is fetched | The verdict chain does no filesystem writes and no network calls; the only output surfaces are console.* warnings and the text sent back to the model. The one exception is the ask-tier blast-radius rehearsal below | | The subprocess call (the only one) | On an ask hit, one fixed read-only command from BLAST_COMMANDS runs in the session cwd through the host's ctx.shell, so it shares the bash tool's sandbox and credential-scrubbed environment. git status uses --no-optional-locks to suppress optional locks and index refreshes, and still runs under the session's resolved sandboxPolicy. Output is capped and rendered per locale into the approval request's reason and displayReason. Any failure (executor absent, uncertain repository target, failed policy resolution, non-zero exit, timeout, cancel, host-truncated output, unexpected shape) falls back to a blind ask - no retry, no substitute command. The command table is fixed and interpolates no model input; the original command is used only for the target/policy skip checks | | What it reads | The tool ledger from the session event history (primary path: a projection unit read synchronously inside the guard; the fallback is a full event scan with byte-identical verdicts); statSync of the target and of layer directories; one target-version probe plus one reference scan when preflight attaches the reference surface to a read; one read-back of the last edited target for content self-proof (files above 1 MiB are not read back and count as unknown); the home directory from os.homedir() | | What it keeps | Entirely in process memory - fact-gate shards, verdict ledgers, and the counters the card reads - gone when the host exits, with no file left under the dsh data directory | | Two things leave: judge-cost is switchable, the denial report is not | With lesson-loop installed, the report payload carries cwd, session id, the matched command text or target path, and the denial text, plus judgeMs and (on a secret-path hit) the list of resolved target forms. Each verdict additionally emits one judge-cost pass whose cost fields are face, milliseconds and character count; the pass itself also carries the session id and cwd (the same context the denial report carries), and never the command text or the judged target's path. Only the judge-cost pass is what judgeStats governs - the judgeMs / judgeLength / resolvedPaths fields inside a denial report are always sent |

FAQ

| Question | Answer | |---|---| | It blocked a legitimate command. | There is no allowlist, so the routes are the three listed under Settings: disable temporarily, take the quota release, or rewrite the command as the denial text suggests. | | The fact gate keeps refusing. | It credits only actions that succeeded. Point the search origin at an ancestor such as the project root as the message says; if another search plugin is in play, add its tool name to refSearchTools; when evidence is unreachable, take the quota release or turn factGateEnabled off temporarily. | | It did nothing at all. | Check the settings row, then dsh --profile web --dump-config for this package's layer and stderr. The host must be on the supported line. A missing tools service means the entry never activated - the startup diagnostic names it. | | How do I know a refusal is from this package? | The denial text names the rule family and a way out, and appears as that tool call's error result. Rules never modify or drop the call; they either reject it or hand over an approval request. |

Development

pnpm install
pnpm run check     # typecheck → lint → client build → host build → types → tests → format
pnpm test          # vitest, with coverage
  • test/ splits into three layers, and the split is about the class of defect a stub cannot see: guessing the host's shape while the verdict stays self-consistent.
    • Unit tests drive hand-written ctx stubs: the predicates themselves - word lists, tiers, gaps, state machines, wording.
    • Integration tests drive the real ToolRuntime from the official testkit, with fixtures that really read and write, dispatched through ctx.tools.execute: waterfall order and materialization - pre-execute before guard, a deny becoming an isError result, additionalContexts coexisting with another plugin's.
    • Point-to-point tests drive the real agent loop and session store, with only the model scripted: that the reference surface attached to a read is visible in the very request where the model decides its next edit, and that a secret file's body appears in no request at all.
    • The division between the last two is a measured fact, not a preference: executing a tool directly does not append to the session log, so "the model read or searched it" can only be credited in the point-to-point layer.
  • Coverage thresholds are 100% across four metrics, so a new branch needs cases that reach it.
  • Assertions use discriminative markers that skip a shared prefix - the action-checklist and attached-evidence texts both begin with the same tag, so "take the first word as the marker" would make two mutually exclusive assertions true at once. The marker helpers live in one place.

Feedback

Issues and pull requests are welcome: https://github.com/JayYuen666/dsh-danger-guard/issues.

If a plugin fails to boot, include the dsh host version, the profile install shape, and the browser console line. The missed the module table line is especially useful: it tells us whether the shared client row was materialized.

License

MIT. Source at github.com/JayYuen666/dsh-danger-guard.

The fact gate and the command rules are ported in mechanism from ECC (MIT, © Affaan Mustafa) - THIRD_PARTY_NOTICES.md records the upstream files, what differs in this package, and the item-by-item comparison showing that no upstream code, word list or message text was copied.