# π¦ @goodandready/dsh-shadow-auditor
---
## β‘ Overview
**`dsh-shadow-auditor`** provides real-time, non-intrusive background security auditing and command safety protection for **DeepSeek Harness** agents.
When autonomous agents write code, stage files, or run shell scripts, there is a constant risk of accidental API key/secret leakage into git diffs or unintentional execution of destructive terminal commands (`rm -rf /`, dangerous database wipes, credential exports).
`dsh-shadow-auditor` operates as an in-process security firewall, scanning code diffs for private tokens and verifying terminal commands before execution.
```mermaid
graph LR
subgraph AgentExecution [DSH Agent Runtime Actions]
Agent[π€ Agent: Writes Code / Prepares Command] --> Intercept{Security Interceptor Hook}
end
subgraph SecurityEngines [dsh-shadow-auditor Engine]
Intercept --> SecretScan[π Secret & Token Scanner: High-Entropy & Key Patterns]
Intercept --> CmdGuard[π‘οΈ Command Safety Firewall: Destructive Shell Blocker]
end
subgraph Enforcement [Action & Telemetry Pipeline]
SecretScan -->|Clean| Pass[β
Proceed Execution]
SecretScan -->|Secret Detected| Block1[β Block & Redact Token Payload]
CmdGuard -->|Safe| Pass
CmdGuard -->|Destructive Hazard| Block2[β Block & Raise User Confirmation]
Block1 --> AuditLog[π Security Audit Telemetry & Dashboard]
Block2 --> AuditLog
end
style AgentExecution fill:#1e1e2e,stroke:#89b4fa,stroke-width:2px,color:#cdd6f4
style SecurityEngines fill:#181825,stroke:#cba6f7,stroke-width:2px,color:#cdd6f4
style Enforcement fill:#11111b,stroke:#a6e3a1,stroke-width:2px,color:#cdd6f4
```
---
## β¨ Key Capabilities & Modules
### 1. π Pre-Flight Secret & Credential Scanning (`lib/guards/secrets.js`)
* Real-time regex and entropy scanning for API keys, private tokens, RSA/SSH keys, OAuth bearer secrets, and database credentials;
* Intercepts code before transmission to LLMs or storage in version control;
* Automatic token redaction and masking in logs.
### 2. π‘οΈ Destructive Command Firewall (`lib/guards/command.js`)
* Analyzes shell command AST and argument tokens before terminal execution;
* Flags and blocks dangerous operations (unbounded `rm -rf`, disk wipes, fork bombs, destructive `dd`, accidental recursive permission overwrites);
* Workspace boundary protection (#103): blocks recursive deletions targeting filesystem root or paths resolving outside session workspace;
* Critical system prefix protection (#105): unconditionally safeguards sensitive directories (`~/.dsh`, `~/.claude`, `~/.ssh`, `/etc`, `/usr`, Windows system folders);
* Dry-run verification pass-through (#104): recognizes preview flags (`-WhatIf`, `-Confirm`, `--dry-run`, `git clean -n`), permitting safe inspection without false-positive blocks;
* Requires explicit user override for hazardous scripts.
### 3. π Security Rules Engine & Live Dashboard (`lib/client.js`)
* In-memory configurable rule matrix with toggleable strictness;
* Security audit badge and incident log viewer in the DSH Web UI.
### 4. πͺ Multi-Surface Lifecycle Interception Engine (`lib/guards/lifecycle-hooks.js`)
* **Priority Hook Registration (`prepend: true`)** (#125): Guarantees execution at the head of the Cordis handler pipeline before third-party extension handlers execute;
* **Unconditional Critical Threat Blocking (`secretBlockCritical`)** (#124): High-severity destructive commands (root wipe, disk formatting, AWS/private key exfiltration) are strictly blocked even in `audit_only` or `warning` mode;
* **Interactive User Approval Mode (`ask`)** (#108): Seamlessly integrates with DSH approval mechanism in `tools/pre-execute` returning `{ kind: 'ask', reason, displayReason }` on suspicious operations;
* **Prompt Injection Pre-Filtering (`agent/pre-step`)** (#110): Scans incoming user messages before model ingestion, rejecting jailbreak and prompt-injection payloads early (`{ kind: 'reject' }`);
* **Tool Result Sanitization & Output Redaction (`tools/post-execute`)** (#111): Intercepts tool outputs and masks exposed credentials and high-entropy secrets before model context ingestion.
---
## π οΈ Agent Tools Reference (3 Tools)
| Tool Name | Parameters | Description |
|---|---|---|
| `shadow_auditor_scan_diff` | `diff: string` | Scans a unified diff or code chunk for exposed API keys, credentials, and private tokens |
| `shadow_auditor_check_command` | `command: string` | Evaluates shell commands against destructive execution patterns and safety policies |
| `shadow_auditor_rules_list` | *(none)* | Returns currently active security rules, patterns, and enforcement modes |
---
## π¦ Quick Installation
```bash
dsh plugin --profile web add @goodandready/dsh-shadow-auditor
```
---
## βοΈ Configuration Reference (`settings.yaml`)
```yaml
dsh-shadow-auditor:
strictSecretScanning: true # Block execution if API keys or tokens are detected in diffs
blockDangerousCommands: true # Block destructive shell commands automatically
secretBlockCritical: true # Unconditionally block critical threats bypassing soft audit modes
enableReversibleMasking: true # Reversibly replace detected PII and secrets with placeholders
shellGuardMode: 'enforce' # Policy for command guard: enforce (block), audit_only (log), ask (interactive user prompt)
diffGateMode: 'warning' # Diff gate mode: disabled, warning, or block
enableAuditBadge: true # Display security shield badge in UI and approval dialogs
enableAuditLog: true # Record persistent JSONL audit logs with rotation under DSH_HOME
```
---
### π Reversible Masking & Placeholder Engine
When `enableReversibleMasking` is active (default: `true`), incoming prompts at `agent/pre-step` are inspected. Detected secrets, API keys, private keys, emails, IPv4 addresses, and phone numbers are replaced with monotonic placeholders (``, ``, ``).
* **Value Reuse**: Identical sensitive values across steps and turns in the same session automatically reuse their existing placeholder.
* **Prefix Collision Safety**: Demasking processes placeholders strictly in descending length order (`` before ``), preventing substring corruption.
* **Session Demasking Command**: Authorized users can demask text locally using the slash command:
```text
/shadow-auditor restore
```
* **Session Log Cleanliness Invariant**: LLM prompts and recorded audit JSONL logs contain zero raw secrets.
---
---
## π Version History
### v0.2.9 (Security Evolution & Canonical Localization)
- **Canonical Language Standard**: Complete runtime and client localization in English (`en`) and Chinese (`zh`); Russian localization managed via `goodandready/dsh-russian-lang`.
- **Packaging Hygiene**: Clean distribution package with non-product files (`AGENTS.md`, `index.md`) purged; strict $\le 256$ KiB file limit.
- **Real-Time Interception Feed**: Live telemetry event viewer with filtering by All, Shell Guard, Diff Gate, and High Risk.
- **Configurable Security Policies**: Custom regex blocklists for shell commands and sensitive paths, with Enforce vs Audit-only modes.
- **Diff Gate Visual Inspector & Remediation**: Inline inspector showing offending code snippets and actionable safe remediation hints.
- **File Integrity & Secret Anchor Monitor**: Proactive interception of file tools touching `.env`, `settings.yaml`, and credential anchors.
- **Compliance Export**: One-click export of audit logs to JSON or Markdown Operation Bills from UI or HTTP endpoints.
### v0.2.8 (UI Unification & Settings Sync)
* **Unified UI Style (Aligned with `dsh-clinebot`)**: Redesigned client settings card into four structured section cards using native DSH design tokens (`--dsw-alias-*`), clean responsive grids, status badges, and styled form controls.
* **Complete Settings Synchronization**: Added full reactive tracking and draft persistence for `diffGateMode`, `enableSastScan`, and `enablePromptInjectionScan`.
* **Hardened Error Handling**: Replaced silent catch blocks with logger diagnostics.
* **Expanded Test Coverage**: Added dedicated unit test suite `test/ui-and-stability-028.test.mjs` (26 test suites passing).
### v0.2.7 (Stability Refinements & False-Positive Elimination)
* **Secret-Write False-Positive Fix**: `secret-write` guard strictly targets actual secret and credential stores (`.env`, `.credentials`, SSH keys) without falsely matching developer scripts such as `check_token.js` or test suites `test_secret.py`.
* **Smart SAST Comment Filtering**: Comments containing SQL keywords or `eval` examples no longer trigger code security alerts. Safe relative path traversal via `import.meta.url` and `__dirname` is permitted.
* **Diff Gate Resource Limits**: Line scanning truncates beyond 2048 characters to protect against minified bundle stalls, and test files bypass prompt injection heuristics.
* **Bounded Chat /audit**: Chat slash command reads recent 50 entries by default to prevent OOM on large logs (override with `--all`).
* **Tab Visibility Polling**: Background tab polling in `AuditShieldChip` is paused when document is hidden.
### v0.2.4 (DSH Authoring Standards & Settings UI Card Enhancements)
* **Comprehensive Settings Card Controls**: exposed audit log controls in the Web UI card (`enableAuditLog`, `maxFileSizeMb`, `retentionDays`) with English and Russian localization (#34).
* **Elimination of Dual Registration**: removed `setTimeout` delayed fallback to `settings.section`; settings card registers cleanly and atomically into `settings.plugin.item` (#35).
* **Disabled Form on Unavailable Snapshot**: when settings snapshot is `unavailable`, form inputs and the save button are disabled (`disabled: true`) and a warning notice is displayed (#32).
* **Peer Dependencies Cleanup**: removed unused `@deepseek-ai/dsh-credentials` from `peerDependencies` in `package.json` (#33).
* **Style Isolation**: added `data-dsh-plugin="dsh-shadow-auditor"` to `