Safe by Default
ClawMagic is designed to be safe for beginners out of the box. It runs exclusively on localhost by default and ships with the most locked-down security profile active. Advanced features require explicit opt-in.
- Default binding:
127.0.0.1only. Not exposed to the network. Remote access requiresallow_remote=true+ API token. - Safe defaults:
safe_mode=true,command_sandbox=restricted,approvals_enabled=true,security_profile=beginner. - Beginner profile: Most restrictive. 27 dangerous commands blocked, 7 arg patterns blocked, exec approval required for all tool calls.
- Critical field protection: API cannot modify
gateway.allow_remote,api_token,cors_allowlist,approvals_enabled, orsetup.*. Returns 403. - Developer override: Advanced/developer profiles require token + confirmation + time-limited session.
All 50 Controls at a Glance
Every control has been audited and rated Strong. The table below shows each area and its category.
| # | Security Area | Category | Rating |
|---|---|---|---|
| 1 | CORS / DNS Rebinding | Auth | Strong |
| 2 | Auth Token (Timing-Safe) | Auth | Strong |
| 3 | Password Hashing & Complexity | Auth | Strong |
| 4 | MFA / TOTP + WebAuthn | Auth | Strong |
| 5 | Session Management | Auth | Strong |
| 6 | Auth Failure Lockout | Auth | Strong |
| 7 | Execution Approval System | Auth | Strong |
| 8 | Env Var Sanitization | Exec | Strong |
| 9 | SSRF Prevention | Network | Strong |
| 10 | Prompt Injection Defense | Input | Strong |
| 11 | Indirect Prompt Injection | Input | Strong |
| 12 | Boundary Markers & Homoglyphs | Input | Strong |
| 13 | Rate Limiting (Global + Scoped) | HTTP | Strong |
| 14 | HTTP Security Headers | HTTP | Strong |
| 15 | CSRF Protection | HTTP | Strong |
| 16 | ReDoS Protection | Input | Strong |
| 17 | Container Network Isolation | Container | Strong |
| 18 | Docker / Container Hardening | Container | Strong |
| 19 | Agent Self-Modification Prevention | Exec | Strong |
| 20 | Command Sandbox (4-Tier) | Exec | Strong |
| 21 | Under Attack / DDoS Defense | HTTP | Strong |
| 22 | Obfuscation Detection | Input | Strong |
| 23 | File System Confinement | FS | Strong |
| 24 | OS-Level Auth Gate | Auth | Strong |
| 25 | Credential Redaction | FS | Strong |
| 26 | Plugin Revocation System | Plugin | Strong |
| 27 | Malware Scan & Checksum | Plugin | Strong |
| 28 | Behavioral Sandbox Test | Plugin | Strong |
| 29 | Health / Status Hardening | Ops | Strong |
| 30 | Network Monitoring & Auto-Ban | Network | Strong |
| 31 | Supply Chain Security | Plugin | Strong |
| 32 | Config Integrity & Immutability | Ops | Strong |
| 33 | Deployment Guidance | Ops | Strong |
| 34 | Plugin Reputation & Signing | Plugin | Strong |
| 35 | CSP (Content Security Policy) | HTTP | Strong |
| 36 | Input Validation | Input | Strong |
| 37 | Backup & Recovery | Ops | Strong |
| 38 | Security Audit Dashboard | Ops | Strong |
| 39 | Portal Security Panel | UX | Strong |
| 40 | Sandbox Toggle UX | UX | Strong |
| 41 | Beginner Onboarding | UX | Strong |
| 42 | Plugin Capabilities | Plugin | Strong |
| 43 | Secret Change Audit Trail | Ops | Strong |
| 44 | HKDF Key Derivation | Crypto | Strong |
| 45 | Zero-Exposure Credential Proxy | Crypto | Strong |
| 46 | Aho-Corasick Pattern Matching | Input | Strong |
| 47 | External Content Wrapping | Input | Strong |
| 48 | Cost Guard / Spending Control | Ops | Strong |
| 49 | Leak Detection Events | FS | Strong |
| 50 | OAuth 2.1 + PKCE | Auth | Strong |
Authentication & Access Control
Eight controls protect identity, sessions, and authorization at every layer.
- CORS / DNS rebinding: Allowlist-based CORS. Localhost-only in local mode, explicit origins in remote mode. DNS rebinding protection via Host header validation.
- Timing-safe token comparison: All token comparisons use constant-time algorithms to prevent timing attacks.
- Password hashing: bcrypt/argon2 with tuned cost factors and complexity requirements.
- MFA: TOTP and WebAuthn support. Admin sessions require multi-factor authentication.
- Session management: Server-side session store with revocation, persistence, expiry, and secure cookie attributes.
- Auth failure lockout: Progressive lockout on failed attempts. Rate-limited per IP with auto-ban after threshold.
- Execution approval: ExecApprovalManager with per-agent approval, persistence, stats, history, glob matching, and 4-tier security profiles.
- OS-level auth gate: Operating system authentication gate for local access beyond API token.
Execution Safety
Three controls prevent dangerous code execution and agent self-modification.
- Env var sanitization: Dual-layer filtering with allowlist + 23 blocked variables + 3 blocked prefixes. Prevents secrets from leaking into subprocess environments.
- Agent self-modification prevention: Agents cannot modify their own configuration, security settings, or approval rules.
- Command sandbox (4-tier): Beginner, standard, advanced, and developer profiles. Beginner blocks 27 dangerous commands and 7 argument patterns. Each tier progressively unlocks capabilities with explicit opt-in.
Network & HTTP
Seven controls cover network isolation, transport security, and HTTP hardening.
- SSRF prevention: DNS pinning, private IP blocking, redirect validation, IDN normalization, IP bypass prevention, and 10 cloud metadata provider blocks.
- Network monitoring & auto-ban: Real-time traffic monitoring with automatic IP banning on suspicious patterns.
- Rate limiting: Global + scoped sliding window at 60 req/min per endpoint class. Sensitive endpoint, auth, and chat-specific limits. Policy-based overrides.
- Security headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy enforced on all responses.
- CSRF protection: X-Requested-With header validation on all state-changing endpoints (POST/PUT/PATCH/DELETE). Cannot be sent by form submissions.
- Under attack / DDoS defense: Activatable under-attack mode with aggressive rate limiting, challenge pages, and IP blocking.
- Content Security Policy: Strict CSP headers preventing inline script injection and unauthorized resource loading.
Input Validation & Prompt Defense
Six controls protect against injection, manipulation, and malformed input.
- Prompt injection defense: 28+ detection patterns with IP blocklist. Structured boundary markers separate system prompts, user input, and tool results.
- Indirect prompt injection: Tool outputs treated as untrusted data. Never injected directly into system prompts. Structured logging of detected attempts.
- Boundary markers & homoglyphs: Unicode normalization prevents homograph and zero-width character attacks. Input normalized before processing.
- ReDoS protection:
compileSafeRegex()(386 lines) validates patterns against catastrophic backtracking before execution. - Obfuscation detection: Detects and flags obfuscated code patterns in plugin submissions and user inputs.
- Body size limits: Per-route enforcement via
ROUTE_BODY_LIMITS: plugins 50MB, secrets 10KB, settings 100KB, chat 1MB, default 1MB.
Plugin Security
Six controls protect the plugin lifecycle from submission through execution.
- Plugin revocation: Marketplace can revoke plugins post-publish. Revocation propagates to all installed instances.
- Malware scan & checksum: SHA-256 checksums on download and install. Zip MIME verification, manifest parsing, entry file checks, optional malware scanning hook.
- Behavioral sandbox test: Plugins run in a sandboxed environment during review. Network, filesystem, and process access monitored.
- Supply chain security: Ed25519 maintainer signatures + ECDSA post-approval signatures + marketplace counter-signature (ECDSA P-256). Full chain validation from maintainer to marketplace. SBOM and reproducible build verification.
- Plugin reputation & signing: Signed packages with public key verification. Reputation scoring based on install count, review history, and security posture.
- Plugin capabilities: PluginTrustLevel (system/trusted/untrusted/quarantined) with PluginCapabilityDeclaration. Runtime enforcement with wildcard pattern matching. Undeclared capability access is blocked.
Container Hardening
- Container network isolation: Per-container network policies. No inter-container communication unless explicitly allowed.
- Docker hardening:
cap-drop ALL, seccomp/AppArmor profiles, read-only root filesystem, non-root execution. Runtime validation of container security posture.
File System & Secrets
- File system confinement:
isWithinBoundary()+ factory pattern + audit logging. Prevents directory traversal and path escape. - Credential redaction: 23+ regex patterns and 19 keyword matches. Prefix masking with SHA-256 before logging or display. Covers API keys, tokens, passwords, connection strings, and cloud credentials.
- Secrets at rest: AES-256-GCM encryption with hybrid keychain. Key rotation with versioning, expiry, and backup. Never plaintext on disk.
- Secret change audit trail: SecretAuditEntry types with key versioning (createdAt, keyVersion, expiresAt). Every create/rotate/delete logged with actor + timestamp to
secrets_audit.jsonl.
Operations & Monitoring
- Health / status hardening: Health endpoints expose minimal information. Version, uptime, and component status without internals.
- Config integrity: SHA-256 hash stored in
.config_hash(mode 0o600). Verified on everyloadConfig()call. Field-level change audit logging viaemitConfigAuditLog(). - Deployment guidance: Heroku runbooks, CI/CD security steps, and production hardening checklists.
- Backup & recovery: SHA-256 checksums on local backups with
.sha256sidecar files.verifyBackupIntegrity()for on-demand verification. Backup age alerting for stale warnings. - Security audit dashboard: Real-time security event dashboard with filterable audit log and trend analysis.
- Rate limit dashboard: Auto-refreshing (30s) portal page with per-IP breakdown, usage bars, active bans panel, and auth lockout tracking.
- Incident response: 6 structured runbooks served via API: compromised API token, malicious plugin, brute force/DDoS, config tampering, data exposure, prompt injection. Each with indicators, step-by-step procedures, and CLI commands.
Portal Security UX
- Security settings panel: Dedicated page with posture grade display, PolicyToggle controls for safeMode/approvals/gitPush/coreWrites, and developer override panel.
- Sandbox toggle: Explicit on/off toggle with confirmation modal when disabling. Shows active restrictions and profile description (beginner/standard/advanced).
- Beginner onboarding: New users start in the most restrictive profile. Guided upgrade path with clear explanations of what each level unlocks.
Advanced Cryptography & Cost Controls
Additional security patterns adopted from cross-project audit, all implemented with flat-file JSON/JSONL storage (no database required).
- HKDF key derivation: Per-secret encryption keys derived using HKDF-SHA256 with unique 16-byte salt. Compromising one ciphertext reveals nothing about others. Backward compatible with legacy format (auto re-encrypts on next save).
- Zero-exposure credential proxy: Credentials never touch plugin execution contexts. Opaque handles with
proxiedFetch()inject secrets at the network boundary. Plugins declare required capabilities. - Aho-Corasick pattern matching: Compiled trie-based automaton replaces sequential regex for injection detection. Single-pass matching across 28+ patterns. BFS failure links. Regex fallback for complex patterns (lookahead, captures).
- External content wrapping:
wrapExternalContent(source, content)applies boundary markers and source attribution to all untrusted data. Random markers prevent marker spoofing. Tool outputs, fetched URLs, and plugin responses are wrapped automatically. - Cost guard: CostGuard class with task and chain-run scopes. Configurable per-session, per-day, and per-month budgets with soft (warn) and hard (stop) thresholds. PerUserCostManager for multi-user daily/monthly quotas. State persisted to flat-file JSON.
- Leak detection events:
scanForCredentialLeaks()monitors for credential exposure with 7 pattern categories. Events logged toleak_events.jsonlwith timestamp, source, and matched pattern. - OAuth 2.1 + PKCE: Full PKCE S256 implementation for MCP/tool authentication. 32-byte random verifier, SHA-256 challenge. Multi-provider support. Tokens stored in AES-256-GCM encrypted auth profiles.
Security Regression Tests
16 automated invariants run on every deployment, covering:
Verification Commands
Run these locally to verify the security posture of your ClawMagic instance.
pnpm security:audit # dependency vulnerability scan pnpm security:sast # static analysis security testing pnpm security:policy-check # verify security policies pnpm test:security # run security test suite pnpm test:integration # end-to-end security validation
Production Checklist
- Set strong secrets and rotate all payment/webhook credentials.
- Enable HTTPS-only origins and correct base URLs.
- Verify
security_profile=beginneris active (default). - Confirm
allow_remote=falseunless remote access is needed. - Enable alerting and malware scanning integrations where available.
- Run security commands in CI before every release.
- Review audit events after launches and payment/webhook incidents.
- Verify backup integrity checksums are being generated.
- Test incident response runbooks with your team.