Place a YAML rule gate before DSH tool calls, generating allow/deny/ask decisions based on tool name/parameters/path/agent/network target; control local agent outbound traffic with full read-only audit.
- Language
- TypeScript
- License
- Apache-2.0
- Branch
- main
Install
$ dsh plugin --profile web add dsh-permission-rulesRun the command above in your terminal to install this plugin via the dsh CLI. You can switch Profile in the top-right corner. New to dsh? Read the beginner tutorial
Install via your agent
Install the DeepSeek Harness plugin PerryLink/dsh-permission-rules for me: review the repository at https://github.com/PerryLink/dsh-permission-rules first, then run the install command and verify the plugin loads successfully.
Paste this instruction to the DSH Web GUI assistant — it will install and verify for you.
One-Line Description
Place a YAML-written allow/deny/ask gate before each tool call in DeepSeek Harness, matching by tool name, parameters, paths, Agent identity, and network targets; overlay a local HTTP/CONNECT proxy to uniformly control subprocess outbound network, all hits write read-only audit logs, but the model cannot see them and is not disturbed by side effects other than blocking.
Core Capabilities
- Ordered Rule Chain: Each tool call is evaluated using a "first match wins" approach in file order, with matched rules producing one of three actions:
allow/deny/ask;deny/asktruncate subsequent rules, whileallowand no-match strictlynext()pass through without ever blocking downstream. - Rich Matching Dimensions: Tool name glob (supports
mcp__*), Agent identity selectors (main/subagent/preset:<name>, unknown identity never matches—fail-safe fallback), parameter key-value glob or regex (including!patternnegation andabsentmissing dimension), workspace-relative paths with arbitrary nesting,whenhost conditions (environment variables + platform allowlist). - Process-Level Network Policy: Built-in local HTTP/CONNECT proxy uniformly controls shell subprocess outbound network; rules can use
match.networkwithdomains/ips/ports/schemes(glob, wildcard, CIDR, port range) for target matching; three network modes automatically follow official sandbox presets (readonly→deny-all, workspace-write→whitelist, danger-full-access→allow-all). - Hot Reload with Hierarchical Files: Chokidar watches rule file changes with debounce; broken edits preserve old rules without crashing; optional
searchUpmerges parent directory.dsh/rules.yamltogether (closer takes precedence). - Complete Read-Only Audit: Every hit and every pass writes
permissionRules/decisionsession event (withignorableflag), proxy intercepts also writepermissionRules/network; logs don't enter model context, only for post-hoc traceback. - Visual Settings Panel: Web profile adds a "Permission Rules" settings page showing network mode summary, intercept count, recent intercept list and rule editor, all data fetched via Typert remote API.
Technical Implementation
- Language: TypeScript (ESM, strict mode; client React 18)
- Key Dependencies:
@deepseek-ai/cordis+@deepseek-ai/schemastery(plugin loading & Config validation),chokidar(rule file watching),yaml(rule file parsing),react(Web settings panel) - Architecture Pattern: Functional cordis plugin (
name/inject/Config/apply, no default export);applyregisterstools/pre-executelistener,/rulescommand, settings section, local proxy; Web half-package communicates with host via Typert remote API. Rule matching is pure function (no I/O, replayable, unit-testable). - Entry Files:
src/index.ts(host entry),src/client/index.ts(Web settings panel entry),src/runtime.ts(core assembly &apply),cordis.patch.yml(profile bundle patch)
Use Cases
Suitable for projects that need to add "allowlist/blocklist/graylist" to AI Agent tool calls: for example, protecting secrets/ and .env from arbitrary editing, restricting network outbound to only hit trusted APIs, requiring sensitive operations to go through secondary approval. Typical users are individuals or teams who want to add an auditable, hot-reloadable, traceable rule source security fence to a session or entire organization using pure YAML config files without writing code.
Prerequisites & Compatibility
| Dependency | Minimum Version | Description |
|---|---|---|
| DeepSeek Harness | >=0.1.0-rc.8 <0.2.0 | All dsh-* peerDependencies and devDependencies locked to rc.8; workshop manifest declares compatibility with rc.5/rc.7/rc.8; starting from rc.8 Session.append will cover ignorable flag |
| Node.js | ^22.19.0 || >=24.0.0 | Enforced by package.json#engines.node |
| Platform | Cross-platform | Host side pure JS (no native modules); Web settings panel runs in browser (web profile); caseInsensitivePaths defaults to on on Windows |
| Native Modules | None | No dependency on node-pty/node:sqlite etc. |
Installation
dsh plugin --profile web add github:PerryLink/dsh-permission-rules
Configuration Options
| Config | Type | Description | Default |
|---|---|---|---|
rulesFile | string | Rule file location, relative paths resolved against session cwd, absolute paths globally effective | .dsh/rules.yaml |
fallbackPath | string | Fallback file when rules not found in workspace, absolute or relative to process.cwd() | Not set |
badFilePolicy | enum | Action when rule file parsing/compilation fails: fail makes current call error directly; ignore-with-warning warns and continues with empty rules | fail |
maxRules | integer | Maximum number of rules in entire effective chain, load fails if exceeded | 256 |
maxCachedWorkspaces | integer | Number of cached workspace rule loads (LRU eviction) | 512 |
patternMode | enum | Matching syntax for params/paths/when.env: glob or regex | glob |
watch | boolean | Whether to watch rule file changes and auto-reload | true |
watchStabilityThresholdMs | integer | Watch reload debounce window (milliseconds) | 200 |
language | enum | /rules command output language: en/zh/es/pt/hi | en |
caseInsensitivePaths | boolean | Whether paths vs workspace root comparison ignores ASCII case | Automatically true on Windows |
audit | enum | Audit granularity: all records hits and passes; hits only records hits | all |
searchUp | boolean | Whether to traverse parent directories merging all .dsh/rules.yaml (closer takes precedence) | false |
maxGlobStars | integer | Upper limit on unbounded */** quantity in single glob (backtracking degree protection) | 2 |
enforce | boolean | Whether to actually block: false enters dry-run, all hits only write audit without blocking | true |
allowUnmarkedAudit | boolean | Still write audit on old hosts that don't recognize ignorable flag (defaults to not writing to keep session recoverable) | false |
network.enabled | boolean | Network policy master switch, controls proxy, subprocess env var injection, and Web tool mode default | true |
network.mode | enum | Network policy mode: auto follows sandbox preset, or fixed deny-all/whitelist/allow-all | auto |
network.autoFallback | enum | Fallback mode used by auto when sandbox service not found | allow-all |
network.unlisted | enum | Handling of unmatched targets in whitelist mode: ask (default) or deny | ask |
network.proxyBind | string | Local proxy bind address (loopback only, not publicly listening) | 127.0.0.1 |
network.proxyPort | integer | Local proxy port; 0 means auto-allocate free ephemeral port | 0 |
network.proxyMaxRecent | integer | Number of entries retained in settings page "Recent Intercepts" list | 100 |
network.loopback | enum | Loopback target handling: allow (consistent with Codex, defaults to allowing local dev services) or policy (evaluated by rules) | allow |
network.injectEnv | boolean | Whether to inject HTTP_PROXY etc. proxy environment variables for subprocesses | true |
network.noProxy | enum | Subprocess NO_PROXY handling: clear forces policy, preserve keeps original | clear |
FAQ
Q: Rules not effective after installation?
A: Installing only mounts the plugin to the profile; you must restart the profile for id: permission-rules line to appear; then you also need a .dsh/rules.yaml in your working directory (or configure a fallback file via fallbackPath), having no rules equals "allow all".
Q: Is it a replacement or complement to dsh-auto-review?
A: Complementary. This plugin produces ask going through approval channel, dsh-auto-review attaches a second AI model for judgment on the approval channel; when only this plugin is installed, ask goes through human or host default behavior, only when both are installed does it form a closed loop of "rule filtering + model review".
Q: How to observe if new policy will accidentally block legitimate calls?
A: In cordis.yml temporarily set enforce to false to enter dry-run: all deny/ask hits only write audit logs with dryRun flag, don't block calls, events flow normally to downstream; after observation switch back to true.
Q: What happens with malformed YAML?
A: With default badFilePolicy: 'fail', the tool call waiting to execute errors directly; in HMR reload scenarios, the last successfully loaded rules are preserved, never crash; to be more forgiving, change to ignore-with-warning to warn and continue with empty rules.
Q: How does network policy work by default? How to change?
A: Default is network.enabled: true and network.mode: 'auto', following official sandbox presets (readonly→deny-all, workspace-write→whitelist, danger-full-access→allow-all), falls back to autoFallback when host has no sandbox service (default allow-all). To fix it, explicitly set mode to one of deny-all/whitelist/allow-all.
Q: Why can't I see audit events on old hosts?
A: Host 0.1.0-rc.6 and earlier discard the ignorable flag, causing audit events without the flag and breaking session recovery on new hosts. The plugin actively downgrades to not write session log audit and prints a one-time warning; to keep audit, set allowUnmarkedAudit: true, but old logs may need running scripts/repair-session-logs.mjs repair.
Q: How to view currently effective rules and recent decisions?
A: Run /rules in session to list all rules and source files, /rules reload to force-reload current workspace rule chain, /rules decisions [n] to see last n decisions in this session (default 10), /rules test <tool> <json> can dry-run rule matching without actually triggering tool call.
Q: How to uninstall?
A: One line dsh plugin --profile web remove dsh-permission-rules does it, transactional uninstall, doesn't affect other plugins or session state outside the profile.
Learning Curve
Beginner — configuration is primarily pure YAML, placing config file in workspace root takes effect immediately; refer back to docs when encountering complex matching dimensions (agent selector, CIDR, backtracking protection).
Known Issues & Limitations
- Audit downgrade on old hosts:
Session.appendin0.1.0-rc.1–0.1.0-rc.7series doesn't recognizeignorableflag, plugin actively downgrades to not write session log audit and prints one-time warning; to keep audit setallowUnmarkedAudit: true, and accept that old sessions may needscripts/repair-session-logs.mjsrepair on new host. - Path candidates are heuristic: Only document-listed parameter keys (
url/path/file_pathetc.) participate in path matching, and only match workspace-relative paths; non-convention keys and references outside absolute paths won't be covered by rules. - Glob is a conservative subset: No brace expansion support, need to write two rules or switch to
regexmode;maxGlobStars(default 2) rejects globs with too many unbounded stars to prevent backtracking. - Regex backtracking protection is structural not exhaustive: Can block common disaster patterns (nested unbounded quantifiers, overlapping quantified literals), but not complete ReDoS detection, untrusted files should stay in glob mode.
- Proxy layer
askcannot enter interactive approval channel: Local proxy has no session context, when encountering targets requiring approval can only intercept with structured message and writepermissionRules/networkaudit, model sees reason via shell tool error output; only Web toolaskgoes through real interactive approval.
🛡️ dsh-permission-rules
Claude Code-style declarative permission rules for DeepSeek Harness.
Rules decide what is known. A reviewer model decides what is not.
Compatibility
| Surface | Status |
|---|---|
| Harness | DeepSeek Harness 0.1.0-rc.8 |
| Node | `^22.19.0 |
| Platforms | All (host + web settings client) |
| Model | Any (deny/ask reasons surface through tool results) |
What you get
dsh-permission-rules puts an ordered allow / deny / ask rule list in front of every tool call on the tools/pre-execute waterfall — deterministic, instant, auditable, and written by you in plain YAML:
denyblocks the call; the rule'sreasonbecomes the model-visible error.askrides the official approval seam (mountdsh-auto-reviewfor a second-model answerer, or a human answers; with neither, the harness fails closed).allow(and no-match) strictly delegates vianext()— downstream listeners are never short-circuited.
Every hit and every passthrough is audit-logged as a permissionRules/decision session event (log-only — nothing extra is injected into the model context).
- Rich matching — tool-name globs (including
mcp__*), agent-identity selectors (main/subagent/preset:*), argument key/value globs or regexes (with!patternnegation and anabsentkey dimension), workspace-relative path globs at any nesting depth, andwhenhost conditions (env vars, platform). - Hierarchical rule files — optional
searchUpmerges every.dsh/rules.yamlfrom the session cwd to the filesystem root, nearest first. - Dry-run rollout —
enforce: falseaudits what the policy would do while passing every call through. - Hot reload — Chokidar watch with debounce; a broken edit keeps the previous rules, never crashes.
- Fail loud — invalid YAML, unknown actions/fields, bad globs/regexes, backtracking-prone patterns, or more than
maxRulesrules fail the load.
Rule syntax
# <project>/.dsh/rules.yaml
rules:
- match: { tools: [bash, pwsh], params: { command: "git push*" }, paths: ["**/secrets/**"] }
action: deny
reason: "No pushes from protected paths"
- match: { tools: [edit, write] }
action: ask
reason: "File writes need confirmation"
- Match dimensions —
tools(globs, incl.mcp__*),agents(main/subagent/preset:<name>; unknown identity never matches — fail closed),params(key/value globs or regexes,!patternnegation,absentkey dimension),paths(workspace-relative globs extracted at any nesting depth),when(envvar globs/regexes + a closedplatformlist), andnetwork(domains/ips/ports/schemes— globs, wildcards, CIDRs, port ranges). - Actions —
allow/deny/ask, evaluated in file order, first match wins. - Rule metadata —
enabled: false(visible but inert),description,tags; unknown fields fail the load. - Schema — a JSON Schema ships at docs/rules-format.schema.json (editor completion via
# yaml-language-server: $schema=...); the full vocabulary and a 5-rule security baseline live in docs/rules-format.en.md.
Network policy
A Codex-style process-level network policy: shell subprocess traffic flows through a built-in local HTTP/CONNECT proxy, and every connection is decided by ordered network rules or by three modes mapped onto the official sandbox presets:
-
deny-all— the read-only sandbox preset: block all outbound. -
whitelist— the workspace-write preset: allow listed targets,unlisted: ask(ordeny) for the rest. -
allow-all— the danger-full-access preset: allow everything. -
auto(default) — follows the sandbox preset; on hosts without the sandbox-policy service it resolves toautoFallback(allow-all). -
Matching —
match.networkwithdomains/ips/ports/schemes(globs, wildcards, CIDRs, port ranges; numeric YAML ports are accepted). URL-candidate extraction on thetools/pre-executehot path fires on web-tool arguments and URLs embedded in bash/pwsh command text; loopback targets can short-circuit rules perloopbackpolicy. -
Audit — denied connections append
permissionRules/networkto the owning session (same adaptiveignorablegate), with block counters and recent interceptions in/rules networkand the settings page.
Quick start
# 1. install the bundle into your profile
dsh plugin --profile web add "github:PerryLink/dsh-permission-rules#main"
# or from npm (published releases)
dsh plugin --profile web add dsh-permission-rules
# 2. restart and verify the row
dsh --profile web --dump-config | grep -A4 'id: permission-rules'
Install & uninstall
- git channel (latest
main):dsh plugin --profile web add "github:PerryLink/dsh-permission-rules#main"— thepreparescript builds with production dependencies only. - npm channel (published releases):
dsh plugin --profile web add dsh-permission-rules. - tarball channel:
pnpm packin this repo, thendsh plugin --profile web add ./dsh-permission-rules-<version>.tgz. - uninstall:
dsh plugin --profile web remove dsh-permission-rules.
Configuration
All tunables are Schemastery Config fields (changeable from cordis.yml). An id-targeted override replaces the whole row — restate every key you need.
| Key | Default | Meaning |
|---|---|---|
rulesFile | .dsh/rules.yaml | Rule file location; relative = resolved against the calling session's cwd, absolute = global and validated at mount |
fallbackPath | (none) | Rule file used when per-cwd discovery finds nothing; validated at mount |
badFilePolicy | fail | Bad rule file: fail errors the pending tool call loudly; ignore-with-warning warns and continues empty |
maxRules | 256 | Hard cap on rule count across the effective source chain |
maxCachedWorkspaces | 512 | Hard cap on cached per-workspace rule loads (LRU eviction) |
patternMode | glob | params/paths/when.env pattern flavor: glob or regex (tool names are always globs) |
watch | true | Chokidar watch + reload on change |
watchStabilityThresholdMs | 200 | Reload debounce window (ms) |
language | en | /rules output language: en, zh, es, pt, hi |
caseInsensitivePaths | (win32) | paths patterns and workspace-root comparison ignore ASCII case; true on Windows |
audit | all | Audit granularity: all logs every hit AND passthrough; hits skips passthrough events |
searchUp | false | Walk parent directories from the session cwd and merge every found rule file, nearest first |
maxGlobStars | 2 | Hard cap on unbounded */** quantifiers per glob pattern |
enforce | true | false = dry-run mode: deny/ask hits are audit-logged with a dryRun marker and every call passes through |
allowUnmarkedAudit | false | Pre-marker hosts drop the ignorable marker; the plugin disables session-log audit with a warning. Set true to opt back in |
network.enabled | true | Master switch for the proxy, env injection, and web-tool mode defaults |
network.mode | auto | Policy mode: auto follows the sandbox preset, or deny-all / whitelist / allow-all |
network.autoFallback | allow-all | Mode used when auto has no sandbox-policy service |
network.unlisted | ask | Whitelist-mode handling of targets no rule matched: ask or deny |
network.proxyBind | 127.0.0.1 | Local proxy bind address (loopback only) |
network.proxyPort | 0 | Local proxy port; 0 picks a free ephemeral port |
network.proxyMaxRecent | 100 | Cap on recent-block records kept for the settings page |
network.loopback | allow | Loopback targets: allow (Codex parity) or policy |
network.injectEnv | true | Whether proxy environment variables are injected for subprocesses |
network.noProxy | clear | Subprocess NO_PROXY handling: clear enforces the policy or preserve |
Tools & surfaces
| Surface | Kind | Notes |
|---|---|---|
tools/pre-execute | listener | First-match allow/deny/ask rules + network URL-candidate extraction |
/rules | command | list · reload · decisions [n] · test <tool> <json> |
permissionRules/decision | event | Log-only audit for every hit and passthrough |
permissionRules/network | event | Proxy-layer audit for blocked connections |
| HTTP/CONNECT proxy | service | Built-in local proxy governing shell subprocess traffic |
| settings page | client | Network-mode editor, rule editor, block counters, recent interceptions |
/rules list the active rules, their source files, and any last-reload error
/rules list explicit alias for the bare listing
/rules reload re-read the rule-file chain for this workspace
/rules decisions [n] show the last n permission decisions of this session (default 10)
/rules test <tool> <json> dry-evaluate the rules against a hypothetical call
/rules test also accepts leading flags: --cwd <dir>, --env KEY=VALUE (repeatable), --agent <selector> (repeatable), and --platform <name>. In multi-file chains (e.g. searchUp), every listed rule line is attributed to its own source file.
Permissions & data
- Permissions: declares
files:read,files:watch,files:write,session:append, andnetwork:outboundin its workshop manifest.askdecisions ride the official approval seam — nothing is re-implemented or bypassed. - Data: rule files are read from disk; no rule data is written. No model calls, no reviewer subagents.
- Session log:
permissionRules/decisionis never injected into the model context and is appended with the envelope'signorable: truemarker so any harness build loads the log.
Security boundaries
- Policy, not a kernel.
pathscandidates come only from a documented set of argument keys (at any nesting depth, depth-capped), and only workspace-relative paths match. - No reviewer here. The plugin never spawns subagents or calls models — producing an
askdecision is the end of its work. - No sandbox changes. OS-level sandbox policy belongs to the sandbox seam, not this plugin.
- Loud misconfiguration. Unknown YAML fields, unknown actions, and bad patterns are rejected at load.
- Backtracking bounds. Glob patterns are capped at
maxGlobStarsunbounded star expansions; regex-mode patterns reject nested unbounded quantifiers and quantified overlapping literal alternations.
Known limitations
- Audit marker on pre-marker hosts.
permissionRules/decisionis appended withignorable: true; hosts whoseSession.appendpredates the marker (the0.1.0-rc.6line) silently drop it, so the runtime disables session-log audit with a one-time warning. SetallowUnmarkedAudit: trueto opt back in; repair already-written logs withscripts/repair-session-logs.mjs. - Path candidates are heuristic. Only the documented argument keys feed path matching, and workspace-relative matching is ASCII-case-insensitive only when
caseInsensitivePathsis on. - Globs are a conservative subset. No brace expansion — write two patterns, or use regex mode.
- The regex backtracking guard is structural, not exhaustive. Prefer glob mode for untrusted files.
Collaborating with dsh-auto-review
dsh-permission-rulesproducesask;dsh-auto-reviewanswers on theapproval/requestwaterfall with a read-only second-model verdict (or delegates to humans). Mount both for the full closed loop.- Integration-tested:
permissionRules/decision→approval/asked→autoReview/verdict→approval/decided, with the reviewer replaced by a scripted mock. - The
neverapproval policy and every fail-closed guarantee of the official harness stay untouched.
Session log repair
Session logs written before the ignorable marker existed can be refused by newer harness builds (SessionFormatUnsupportedError). The shipped scripts/repair-session-logs.mjs rewrites only the targeted audit rows to carry ignorable: true, frame-preserving, with backups:
node scripts/repair-session-logs.mjs scan [--home DIR] # report foreign rows, change nothing
node scripts/repair-session-logs.mjs repair [--home DIR] [--dry-run]
--home defaults to $DSH_HOME/sessions (or ~/.dsh/sessions).
Development
pnpm install # node ^22.19 || >=24
pnpm run typecheck # tsc, src + tests
pnpm run lint # eslint, src + tests + scripts
pnpm test # vitest: 139 tests, 9 suites
pnpm run test:coverage # coverage gate (90/80/90/90)
pnpm run build # tsc declarations + tsdown bundles (lib/)
pnpm run pack:check # build + pack (the published artifact)
node scripts/check-readme-sync.mjs # five-language README sync gate (also in CI)
See VERIFICATION.md for the headless end-to-end verification record.
Topics
dsh, dsh-plugin, deepseek-harness, permission, policy, allow-deny-ask, approval, safety, network, network-policy, proxy
Contributors
- @PerryLink — creator and maintainer: rule vocabulary and evaluation, runtime, HMR watch, session-log audit, network policy + proxy, and the five-language docs.
- @22xuan — the detailed report on rc.6 hosts silently dropping the audit event's
ignorablemarker (#2) and the upstream harness discussion; the v0.4.1 runtime host-capability detection and the documentation correction drew directly from that analysis.
PerryLink DSH Plugin Family
This project is one of the 15 DeepSeek Harness plugins maintained by PerryLink. If this one helps you, the others likely will too:
| Plugin | One-liner |
|---|---|
| dsh-mcp-panel | Read-only MCP runtime panel: /mcp command + Settings tab with status, tools and errors |
| dsh-doublecheck | Engineering-discipline guard: requirements grill, test gates, adversary review |
| dsh-background-agents | Durable background child agents with a Web UI sidebar, messaging and interrupt |
| dsh-lsp-actions | LSP diagnostics, formatting, completion, code actions and rename over language servers |
| dsh-output-styles | Claude Code outputStyles-equivalent runtime style switching |
| dsh-checkpoint-rewind | Claude Code /rewind-equivalent: snapshots, session forks, one-shot restore |
| dsh-permission-rules | Claude Code-style declarative allow/deny/ask permission rules with audit |
| dsh-auto-review | Second-model auto-review on the approval chain, fail-closed by default |
| dsh-memento | Approval-gated cross-session memory: ctx.memory seam + SQLite + memory tool |
| dsh-skill-pack-security | Security-audit skill pack: secret scan, dependency and supply-chain review |
| dsh-session-pin | Pin sessions in the Web sidebar with durable ordering |
| dsh-composer-history | Terminal-style input history for the web composer: arrows, Ctrl+R search |
| dsh-github | GitHub PR/issues integration for DSH, every write gated by approval |
| dsh-plugin-guide | Plugin-development knowledge base as an on-demand agent skill |
| dsh-claude-move | Migrate Claude Code sessions, memory, skills and CLAUDE.md into DSH |
License
Apache License 2.0 © 2026 dsh-permission-rules contributors
Read the usage guide →
Install steps, key points, FAQ and compatibility for this plugin — auto-derived from indexed fields.
Listing badge
[](https://deepseek-plugin.org/plugins/PerryLink/dsh-permission-rules)Paste this markdown into your GitHub README to link back to this listing. The badge only states the listing — not a security endorsement.