100+ Attack Vectors Blocked
Pre-Scanner + AST Guard blocks ReDoS, BiDi attacks, eval, prototype pollution, and more
Layer 0 Defense
Pre-Scanner catches attacks BEFORE parser execution - blocks parser-level DoS
AI Scoring Gate
Semantic analysis detects exfiltration patterns, bulk operations, and sensitive data access
Zero Trust Runtime
Enclave sandbox with whitelist-only globals and resource limits
Worker Pool (Optional)
OS-level memory isolation via worker threads with hard halt capability
Security Pipeline
Every script goes through this 6-layer pipeline:Layer 0: Pre-Scanner (Defense-in-Depth)
The Pre-Scanner is a new security layer that runs BEFORE the JavaScript parser (acorn). It provides defense-in-depth protection against attacks that could DoS or exploit the parser itself.Why Layer 0?
Traditional security scanners operate on the AST (Abstract Syntax Tree), which means they rely on the parser completing successfully. Sophisticated attackers can exploit this by:- Parser DoS: Deeply nested brackets/braces can cause stack overflow in recursive descent parsers
- ReDoS at Parse Time: Complex regex literals can hang the parser
- Memory Exhaustion: Large inputs can exhaust memory before validation
- Trojan Source Attacks: Unicode BiDi characters can make code appear different from how it executes
Mandatory Limits (Cannot Be Disabled)
These limits are enforced regardless of configuration:| Limit | Value | Purpose |
|---|---|---|
| Max Input Size | 100 MB (absolute) / 50 KB (AgentScript preset) | Prevents memory exhaustion |
| Max Nesting Depth | 200 levels | Prevents stack overflow |
| Max Line Length | 100,000 chars | Handles minified code safely |
| Max Regex Length | 1,000 chars | Prevents ReDoS |
| Max Regex Count | 50 | Limits ReDoS attack surface |
Pre-Scanner Attacks Blocked
ReDoS (Regular Expression Denial of Service)
ReDoS (Regular Expression Denial of Service)
Blocked Patterns:
(a+)+- Nested quantifiers(a|a)+- Overlapping alternation(.*a)+- Greedy backtracking(a+){2,}- Star in repetition
BiDi/Trojan Source Attacks
BiDi/Trojan Source Attacks
Blocked Characters:
- U+202E (Right-to-Left Override)
- U+2066 (Left-to-Right Isolate)
- U+2069 (Pop Directional Isolate)
Parser Stack Overflow
Parser Stack Overflow
Blocked:
- Deeply nested brackets:
(((((((((x))))))))) - Deeply nested braces:
{{{{{{{{{}}}}}}}}}
Input Size DoS
Input Size DoS
Blocked:
- Inputs > 50KB (AgentScript preset)
- Inputs > configured maxInputSize
Null Byte Injection
Null Byte Injection
Blocked:
\x00characters anywhere in input
Pre-Scanner Configuration
CodeCall uses the AgentScript preset which provides the strictest pre-scanning:Layer 1: AST Validation
AST Guard parses JavaScript into an Abstract Syntax Tree and validates every node against security rules before any code executes.Blocked Constructs
Code Execution Attacks
Code Execution Attacks
Blocked:
eval('malicious code')- Dynamic code executionnew Function('return process')()- Function constructorsetTimeout(() => {}, 0)- Timer-based executionsetInterval,setImmediate- Async execution escape
Global/System Access
Global/System Access
Blocked:
process.env.SECRET- Node.js process accessrequire('fs')- Module loadingwindow.location- Browser globalsglobal,globalThis- Global object accessthis- Context leakage
Prototype Pollution
Prototype Pollution
Blocked:
obj.__proto__ = {}- Direct prototype manipulationobj.constructor.prototype- Indirect prototype accessObject.prototype.polluted = true- Global prototype pollution
Unicode/Trojan Source Attacks
Unicode/Trojan Source Attacks
Blocked:
- Bidirectional override characters (CVE-2021-42574)
- Homoglyph attacks (Cyrillic ‘а’ vs Latin ‘a’)
- Zero-width characters
- Invisible formatting characters
Resource Exhaustion
Resource Exhaustion
Blocked:
while (true) {}- Unbounded while loopsdo {} while (true)- Unbounded do-while loopsfor (key in obj)- Prototype chain walking- Recursive function definitions
AgentScript Preset
CodeCall uses the AgentScript preset - the most restrictive preset designed for LLM-generated code:What’s Allowed
Layer 2: Code Transformation
After AST validation passes, code is transformed for safe execution:Transformations Applied
| Original | Transformed | Purpose |
|---|---|---|
| Top-level code | async function __ag_main() { ... } | Enable top-level await |
callTool(...) | __safe_callTool(...) | Proxy through Enclave |
for (...) | Iteration-limited version | Enforce maxIterations |
console.log(...) | __safe_console.log(...) | Capture for logging |
Example
Reserved Prefixes
User code cannot declare identifiers with these prefixes:__ag_- AgentScript internal functions__safe_- Safe runtime proxies
Layer 3: AI Scoring Gate (NEW)
The AI Scoring Gate is a semantic security layer that analyzes code behavior patterns to detect sophisticated attacks that syntactic validation alone cannot catch. It runs after AST validation but before VM execution.Why Semantic Analysis?
AST validation catches structural threats (eval, prototype pollution), but some attacks are semantically valid code that behaves maliciously:- Data exfiltration: Fetch sensitive data, then send it externally
- Bulk data harvesting: Request excessive limits to scrape data
- Credential theft: Access password/token fields and export them
- Fan-out attacks: Loop over results and call tools for each item
Detection Rules (8 Built-in)
| Rule ID | Score | Trigger |
|---|---|---|
SENSITIVE_FIELD | +35 | Access to password, token, secret, apiKey, SSN, etc. |
EXCESSIVE_LIMIT | +25 | Limit values > 10,000 |
WILDCARD_QUERY | +20 | Query patterns like * or SELECT * |
LOOP_TOOL_CALL | +25 | Tool calls inside loops (potential fan-out) |
EXFIL_PATTERN | +50 | Fetch→Send sequence (list data, then webhook/email) |
EXTREME_VALUE | +30 | Numeric values > 1,000,000 |
DYNAMIC_TOOL | +20 | Tool name from variable (not string literal) |
BULK_OPERATION | +15 | Tool names with bulk/batch/mass/all keywords |
Risk Levels
| Total Score | Risk Level | Default Action |
|---|---|---|
| 0-19 | none | Allow |
| 20-39 | low | Allow |
| 40-69 | medium | Warn (configurable) |
| 70-89 | high | Block (configurable) |
| 90-100 | critical | Block |
Example: Exfiltration Detection
Scorer Modes
The Scoring Gate supports pluggable scorers for different deployment scenarios:| Mode | Latency | Description |
|---|---|---|
disabled | ~0ms | Pass-through, no scoring (for trusted environments) |
rule-based | ~1ms | Zero-dependency TypeScript rules (recommended) |
external-api | ~100ms | External scoring API for advanced ML models |
Configuration
Fail-Open vs Fail-Closed
| Mode | Behavior | Use Case |
|---|---|---|
failOpen: true | Allow execution if scorer fails | Production default - availability over security |
failOpen: false | Block execution if scorer fails | High-security environments |
Scoring Result
Every execution includes scoring metadata:Caching
The Scoring Gate uses an LRU cache with TTL to avoid re-scoring identical code:- Same code → same features → same score
- Cache hit latency: ~0.01ms
- Configurable TTL and max entries
- Automatic pruning of expired entries
AI Scoring Gate Internals
This section is for security auditors and advanced users who need to understand how the Scoring Gate works internally.
Feature Extraction
The Scoring Gate extracts structured features from code for analysis:Rule Evaluation Order
Rules are evaluated in a specific order for efficiency:- Quick reject - Check for obvious red flags (excessive limits)
- Pattern matching - Detect exfiltration sequences
- Sensitive field scan - Check for credential access
- Loop analysis - Detect fan-out patterns
- Final scoring - Aggregate scores from all rules
Extending with Custom Rules
Cache Configuration by Security Level
| Level | TTL | Max Entries | Eviction |
|---|---|---|---|
| STRICT | 30s | 100 | Aggressive |
| SECURE | 60s | 500 | Normal |
| STANDARD | 300s | 1,000 | Lazy |
| PERMISSIVE | 600s | 5,000 | Lazy |
Layer 4: Runtime Sandbox
Enclave executes transformed code in an isolated Node.jsvm context.
Isolation Guarantees
Fresh Context
Each execution gets a new, isolated context with no access to the host environment
Controlled Globals
Only whitelisted globals available: Math, JSON, Array, Object, etc.
No Module Access
No require, import, or dynamic module loading
No Async Escape
No setTimeout, setInterval, or Promise.race tricks
Resource Limits
| Limit | Default | Purpose |
|---|---|---|
timeoutMs | 3,500ms | Maximum execution time |
maxIterations | 5,000 | Maximum loop iterations |
maxToolCalls | 100 | Maximum tool invocations |
maxConsoleOutputBytes | 64KB | Maximum console output (I/O flood protection) |
maxConsoleCalls | 100 | Maximum console calls (I/O flood protection) |
VM Presets
| Preset | Timeout | Iterations | Tool Calls | Console Output | Console Calls | Use Case |
|---|---|---|---|---|---|---|
locked_down | 2s | 2,000 | 10 | 32KB | 50 | Ultra-sensitive data |
secure | 3.5s | 5,000 | 100 | 64KB | 100 | Production default |
balanced | 5s | 10,000 | 200 | 256KB | 500 | Complex workflows |
experimental | 10s | 20,000 | 500 | 1MB | 1000 | Development only |
Security Levels vs VM Presets
The Enclave library uses Security Levels (STRICT, SECURE, STANDARD, PERMISSIVE) for internal configuration, while CodeCall exposes VM Presets (locked_down, secure, balanced, experimental) as a user-friendly interface.
Mapping:
| VM Preset | Enclave Security Level | Description |
|---|---|---|
locked_down | STRICT | Maximum security, minimal capabilities |
secure | SECURE | Production-safe with reasonable limits |
balanced | STANDARD | More flexibility for complex scripts |
experimental | PERMISSIVE | Development/testing only |
| Config | STRICT | SECURE | STANDARD | PERMISSIVE |
|---|---|---|---|---|
| timeout | 2,000ms | 3,500ms | 5,000ms | 10,000ms |
| maxIterations | 2,000 | 5,000 | 10,000 | 20,000 |
| maxToolCalls | 10 | 100 | 200 | 500 |
| maxConsoleOutputBytes | 32KB | 64KB | 256KB | 1MB |
| maxConsoleCalls | 50 | 100 | 500 | 1,000 |
| maxSanitizeDepth | 5 | 10 | 15 | 20 |
| maxSanitizeProperties | 500 | 1,000 | 5,000 | 10,000 |
Worker Pool Adapter (Optional)
For environments requiring OS-level memory isolation, enable the Worker Pool Adapter:Dual-Layer Sandbox
When using Worker Pool, code runs in a dual-layer sandbox:When to Use Worker Pool
| Scenario | Recommendation |
|---|---|
| Trusted internal scripts | Standard VM (lower overhead) |
| Multi-tenant execution | Worker Pool (OS isolation) |
| Untrusted AI-generated code | Worker Pool (hard halt) |
| Memory-sensitive workloads | Worker Pool (per-worker limits) |
Worker Pool Security Features
| Feature | Protection |
|---|---|
worker.terminate() | Hard halt runaway scripts (VM timeout bypass) |
--max-old-space-size | Per-worker memory limits |
| JSON-only serialization | Prevents structured clone gadget attacks |
| Dangerous global removal | parentPort, workerData inaccessible |
| Rate limiting | Message flood protection |
| Safe deserialize | Prototype pollution prevention |
Worker Pool Configuration
| Option | Default | Description |
|---|---|---|
minWorkers | 2 | Minimum warm workers |
maxWorkers | CPU count | Maximum concurrent workers |
memoryLimitPerWorker | 128MB | Per-worker memory limit |
maxMessagesPerSecond | 1000 | Rate limit per worker |
maxExecutionsPerWorker | 1000 | Recycle after N executions |
Worker Pool Presets
| Level | minWorkers | maxWorkers | memoryLimit | messagesPerSec |
|---|---|---|---|---|
| STRICT | 2 | 4 | 64MB | 100 |
| SECURE | 2 | 8 | 128MB | 500 |
| STANDARD | 2 | 16 | 256MB | 1000 |
| PERMISSIVE | 4 | 32 | 512MB | 5000 |
Custom Globals Validation
When providing custom globals to scripts via theglobals config option, Enclave validates them to prevent security bypasses.
Validation Rules
| Rule | Limit | Blocked |
|---|---|---|
| No functions | - | Functions cannot be injected |
| No getters/setters | - | Property traps blocked |
| No symbols | - | Symbol-keyed properties stripped |
| No dangerous keys | - | __proto__, constructor, prototype |
| Max nesting | 10 levels | Deep objects rejected |
Blocked Function Patterns
Custom globals are scanned for dangerous function names in string values:Valid Custom Globals
Invalid Custom Globals
Self-Reference Guard
Critical Security Feature: Scripts cannot call CodeCall meta-tools from within scripts.Why This Matters
Without self-reference blocking, an attacker could:- Recursive execution:
codecall:executecalls itself infinitely - Sandbox escape: Nest executions to accumulate privileges
- Resource exhaustion: Each nested call multiplies resource usage
- Audit bypass: Hide malicious calls in nested scripts
Implementation
The guard runs before any other security checks:Advanced Tool Access Control
Beyond the Self-Reference Guard, CodeCall provides a comprehensive Tool Access Control system for fine-grained control over which tools scripts can invoke.Access Modes
| Mode | Behavior | Use Case |
|---|---|---|
whitelist | Only explicitly allowed tools can be called | High-security, known toolset |
blacklist | All tools allowed except explicitly blocked | Flexible with some restrictions |
dynamic | Custom evaluator function decides per-call | Complex authorization logic |
Default Blacklist
By default, CodeCall blocks these tool patterns:Pattern Matching
Tool access rules support glob patterns for flexible matching:*- Matches any characters within a segment?- Matches a single characterprefix:*- Matches all tools in a namespace
Whitelist Mode
For maximum security, use whitelist mode to explicitly allow only specific tools:Dynamic Access Control
For complex authorization (e.g., per-tenant, per-user, or context-based):Call Depth Tracking
Tool access control tracks call depth to prevent indirect privilege escalation:Layer 5: Output Sanitization
All outputs are sanitized before returning to the client through two mechanisms: Value Sanitization (structure/content) and Stack Trace Sanitization (information leakage).Value Sanitization Rules
| Rule | Default | Purpose |
|---|---|---|
maxDepth | 20 | Prevent deeply nested objects |
maxProperties | 10,000 | Limit total object keys |
maxStringLength | 10,000 | Truncate oversized strings |
maxArrayLength | 1,000 | Truncate large arrays |
What Gets Stripped
Value sanitization removes potentially dangerous content:| Stripped | Reason |
|---|---|
| Functions | Prevents code injection |
| Symbols | Prevents prototype manipulation |
__proto__ keys | Prevents prototype pollution |
constructor keys | Prevents constructor tampering |
| Getters/Setters | Prevents trap execution |
Type Handling
The sanitizer handles special JavaScript types safely:Circular Reference Detection
Information Leakage Prevention (Stack Trace Sanitization)
File System Paths Redacted:| Category | Examples |
|---|---|
| Unix home | /Users/john/, /home/deploy/ |
| System paths | /var/log/, /etc/, /tmp/ |
| App paths | /app/, /srv/, /opt/ |
| Windows | C:\Users\, D:\Projects\, UNC paths |
| Manager | Patterns |
|---|---|
| npm | node_modules/, .npm/ |
| yarn | .yarn/, yarn-cache/ |
| pnpm | .pnpm/, pnpm-store/ |
| workspace | packages/, libs/ |
| Environment | Patterns |
|---|---|
| Docker | /docker/, container IDs |
| Kubernetes | /var/run/secrets/, pod names |
| AWS | Lambda paths, ECS task IDs |
| GCP | Cloud Run paths, function IDs |
| Azure | Functions paths, container IDs |
- GitHub Actions:
/runner/,/_work/ - GitLab CI:
/builds/, CI variables - Jenkins:
/var/jenkins/, workspace paths - CircleCI:
/circleci/, project paths
- Internal hostnames:
*.internal,*.local - Private IPs:
10.x.x.x,192.168.x.x,172.16-31.x.x - Service URLs: Internal load balancers, databases
Example: Before and After
Error Categories
CodeCall categorizes all errors for safe exposure:| Category | Code | Exposed To Client | Contains |
|---|---|---|---|
| Syntax | SYNTAX_ERROR | Message + location | Line/column of error |
| Validation | VALIDATION_ERROR | Rule that failed | Blocked construct |
| Timeout | TIMEOUT | Duration | - |
| Self-Reference | SELF_REFERENCE_BLOCKED | Tool name | - |
| Tool Not Found | TOOL_NOT_FOUND | Tool name | - |
| Tool Error | TOOL_ERROR | Sanitized message | - |
| Runtime | RUNTIME_ERROR | Sanitized message | - |
| Worker Timeout | WORKER_TIMEOUT | Duration | Worker terminated |
| Worker Memory | WORKER_MEMORY_EXCEEDED | Memory usage | Worker recycled |
| Message Flood | MESSAGE_FLOOD_ERROR | Rate limit | Worker terminated |
| Queue Full | QUEUE_FULL_ERROR | Queue size | Request rejected |
Security Checklist
Before deploying CodeCall to production:1
Choose VM Preset
Use
secure for production, locked_down for sensitive data.2
Enable Audit Logging
Monitor script execution, tool calls, and security events.
3
Configure Tool Allowlists
Limit which tools are accessible via CodeCall.
4
Remove Stack Traces
Ensure sanitization is enabled (default).
5
Configure AI Scoring Gate
Enable rule-based scoring with appropriate thresholds.
6
Test Security Boundaries
Run the attack vector tests from ast-guard’s security audit.
Threat Model
What CodeCall Protects Against
Code Injection
AST validation blocks eval, Function, and dynamic code execution
Sandbox Escape
Isolated vm context with no access to Node.js APIs or globals
Data Exfiltration
AI Scoring Gate detects fetch→send patterns and sensitive data access
Bulk Data Harvesting
Scoring Gate flags excessive limits and bulk operations
Prototype Pollution
Blocked at AST level and isolated at runtime
Resource Exhaustion
Timeouts, iteration limits, and tool call caps
I/O Flood Attacks
Console output size and call count limits prevent logging abuse
Information Leakage
Stack traces and file paths sanitized from outputs
Recursive Execution
Self-reference guard blocks codecall:* tool calls
VM Timeout Bypass
Worker Pool provides hard halt via worker.terminate() when VM timeout fails
What CodeCall Does NOT Protect Against
| Threat | Mitigation |
|---|---|
| Tool abuse | Use enabledInCodeCall: false on sensitive tools |
| Algorithmic complexity | Scripts can run O(n²) within limits - monitor performance |
| Memory exhaustion | Large arrays/objects within timeout - set reasonable limits |
| Tool side effects | Tool calls have real effects - use read-only tools where possible |
| Business logic bugs | Script logic errors are not security issues |
Related Documentation
AST Guard
Deep dive into AST validation rules, presets, and custom rule creation
Enclave
Runtime sandbox configuration, sidecar storage, and advanced options
Security Audit
Full list of 100+ blocked attack vectors including Layer 0 Pre-Scanner
Configuration
Complete configuration reference for security settings

