Skip to main content
CodeCall implements bank-grade security through a defense-in-depth architecture. Every script passes through six security layers before execution, ensuring that even if one layer is bypassed, others catch malicious behavior.

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:
  1. Parser DoS: Deeply nested brackets/braces can cause stack overflow in recursive descent parsers
  2. ReDoS at Parse Time: Complex regex literals can hang the parser
  3. Memory Exhaustion: Large inputs can exhaust memory before validation
  4. 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:

Pre-Scanner Attacks Blocked

Blocked Patterns:
  • (a+)+ - Nested quantifiers
  • (a|a)+ - Overlapping alternation
  • (.*a)+ - Greedy backtracking
  • (a+){2,} - Star in repetition
Why: These patterns cause exponential backtracking that can hang the parser or runtime for hours.
Blocked Characters:
  • U+202E (Right-to-Left Override)
  • U+2066 (Left-to-Right Isolate)
  • U+2069 (Pop Directional Isolate)
Why: Makes code appear different from how it executes (CVE-2021-42574).
Blocked:
  • Deeply nested brackets: (((((((((x)))))))))
  • Deeply nested braces: {{{{{{{{{}}}}}}}}}
Why: Recursive descent parsers can overflow their stack on deep nesting.
Blocked:
  • Inputs > 50KB (AgentScript preset)
  • Inputs > configured maxInputSize
Why: Large inputs can exhaust memory before validation completes.
Blocked:
  • \x00 characters anywhere in input
Why: Often indicates binary data injection or attack payloads.

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

Blocked:
  • eval('malicious code') - Dynamic code execution
  • new Function('return process')() - Function constructor
  • setTimeout(() => {}, 0) - Timer-based execution
  • setInterval, setImmediate - Async execution escape
Why: These allow arbitrary code injection that bypasses AST validation.
Blocked:
  • process.env.SECRET - Node.js process access
  • require('fs') - Module loading
  • window.location - Browser globals
  • global, globalThis - Global object access
  • this - Context leakage
Why: Prevents sandbox escape and system access.
Blocked:
  • obj.__proto__ = {} - Direct prototype manipulation
  • obj.constructor.prototype - Indirect prototype access
  • Object.prototype.polluted = true - Global prototype pollution
Why: Prototype pollution can corrupt the entire runtime.
Blocked:
  • Bidirectional override characters (CVE-2021-42574)
  • Homoglyph attacks (Cyrillic ‘а’ vs Latin ‘a’)
  • Zero-width characters
  • Invisible formatting characters
Why: Makes code appear different from how it executes.
Blocked:
  • while (true) {} - Unbounded while loops
  • do {} while (true) - Unbounded do-while loops
  • for (key in obj) - Prototype chain walking
  • Recursive function definitions
Why: Can freeze the server or exhaust memory.

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

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
The Scoring Gate uses feature extraction and rule-based analysis to assign risk scores to these behavioral patterns.

Detection Rules (8 Built-in)

Risk Levels

Example: Exfiltration Detection

Scorer Modes

The Scoring Gate supports pluggable scorers for different deployment scenarios:

Configuration

Fail-Open vs Fail-Closed

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:
  1. Quick reject - Check for obvious red flags (excessive limits)
  2. Pattern matching - Detect exfiltration sequences
  3. Sensitive field scan - Check for credential access
  4. Loop analysis - Detect fan-out patterns
  5. Final scoring - Aggregate scores from all rules

Extending with Custom Rules

Cache Configuration by Security Level


Layer 4: Runtime Sandbox

Enclave executes transformed code in an isolated Node.js vm 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

VM Presets

Security Levels vs VM Presets

Don’t confuse Enclave Security Levels with CodeCall VM Presets - they serve different purposes but work together.
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: Enclave Security Level Defaults: When configuring CodeCall, use VM Presets:

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

Worker Pool Security Features

Worker Pool Configuration

Worker Pool Presets

Custom Globals Validation

When providing custom globals to scripts via the globals config option, Enclave validates them to prevent security bypasses.

Validation Rules

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:
  1. Recursive execution: codecall:execute calls itself infinitely
  2. Sandbox escape: Nest executions to accumulate privileges
  3. Resource exhaustion: Each nested call multiplies resource usage
  4. 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

Default Blacklist

By default, CodeCall blocks these tool patterns:

Pattern Matching

Tool access rules support glob patterns for flexible matching:
Supported patterns:
  • * - Matches any characters within a segment
  • ? - Matches a single character
  • prefix:* - Matches all tools in a namespace
Pattern matching includes ReDoS protection - patterns are validated and normalized to prevent denial-of-service attacks.

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:
Maximum call depth is configurable (default: 10) to prevent deep call chains.

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

What Gets Stripped

Value sanitization removes potentially dangerous content:

Type Handling

The sanitizer handles special JavaScript types safely:

Circular Reference Detection

Information Leakage Prevention (Stack Trace Sanitization)

Stack traces can reveal sensitive information about your infrastructure. CodeCall sanitizes 40+ patterns from error messages.
File System Paths Redacted: Package Manager Paths Redacted: Cloud/Container Paths Redacted: CI/CD Paths Redacted:
  • GitHub Actions: /runner/, /_work/
  • GitLab CI: /builds/, CI variables
  • Jenkins: /var/jenkins/, workspace paths
  • CircleCI: /circleci/, project paths
Credentials Redacted:
Network Information Redacted:
  • 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:

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

CodeCall is not a silver bullet. Defense-in-depth means combining CodeCall with other security measures.

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