> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentfront.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Security Model

> Defense-in-depth security with AST validation, code transformation, runtime sandboxing, and output sanitization.

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.

<CardGroup cols={2}>
  <Card title="100+ Attack Vectors Blocked" icon="shield-check">
    Pre-Scanner + AST Guard blocks ReDoS, BiDi attacks, eval, prototype pollution, and more
  </Card>

  <Card title="Layer 0 Defense" icon="radar">
    Pre-Scanner catches attacks BEFORE parser execution - blocks parser-level DoS
  </Card>

  <Card title="AI Scoring Gate" icon="brain">
    Semantic analysis detects exfiltration patterns, bulk operations, and sensitive data access
  </Card>

  <Card title="Zero Trust Runtime" icon="lock">
    Enclave sandbox with whitelist-only globals and resource limits
  </Card>

  <Card title="Worker Pool (Optional)" icon="server">
    OS-level memory isolation via worker threads with hard halt capability
  </Card>
</CardGroup>

***

## Security Pipeline

Every script goes through this 6-layer pipeline:

```mermaid theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
graph TD
    %% Define simple styling for the box border and background
    classDef terminal fill:#fff,stroke:#333,stroke-width:1px,rx:0,ry:0,text-align:left;

    %% Nodes with explicit HTML width wrappers
    %% We use a div with min-width to FORCE the box to be wide

    Input["<div style='min-width:400px; text-align:center; font-weight:bold;'>SCRIPT INPUT</div>"]

    L0["<div style='min-width:400px'><b>LAYER 0: PRE-SCANNER (ast-guard)</b><br/>- Block ReDoS, BiDi attacks before parsing<br/>- Input size and nesting limits</div>"]

    L1["<div style='min-width:400px'><b>LAYER 1: AST VALIDATION (ast-guard)</b><br/>- Parse JavaScript to AST<br/>- Block eval, Function, dangerous globals<br/>- Block prototype manipulation<br/>- Enforce whitelist-only identifiers</div>"]

    L2["<div style='min-width:400px'><b>LAYER 2: CODE TRANSFORMATION</b><br/>- Wrap in async main function<br/>- Transform callTool -> proxied<br/>- Transform loops -> iteration-limited<br/>- Add resource tracking</div>"]

    L3["<div style='min-width:400px'><b>LAYER 3: AI SCORING GATE (Enclave)</b><br/>- Semantic analysis via AST features<br/>- Exfiltration pattern detection<br/>- Sensitive field access tracking<br/>- Risk scoring</div>"]

    L4["<div style='min-width:400px'><b>LAYER 4: RUNTIME SANDBOX (Enclave)</b><br/>- Standard: Node.js vm (prototype isolation)<br/>- Optional: Worker Pool (OS-level)<br/>- Controlled globals (Math, JSON, etc.)<br/>- Timeout enforcement</div>"]

    L5["<div style='min-width:400px'><b>LAYER 5: OUTPUT SANITIZATION</b><br/>- Remove stack traces<br/>- Scrub file paths<br/>- Truncate oversized outputs<br/>- Detect circular references</div>"]

    Result["<div style='min-width:400px; text-align:center; font-weight:bold;'>SAFE RESULT</div>"]

    %% Connections
    Input --> L0 --> L1 --> L2 --> L3 --> L4 --> L5 --> Result

    %% Apply Styles
    class Input,L0,L1,L2,L3,L4,L5,Result terminal;
```

***

## 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:

| 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

<AccordionGroup>
  <Accordion title="ReDoS (Regular Expression Denial of Service)" icon="clock">
    **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.
  </Accordion>

  <Accordion title="BiDi/Trojan Source Attacks" icon="eye-slash">
    **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).
  </Accordion>

  <Accordion title="Parser Stack Overflow" icon="layer-group">
    **Blocked:**

    * Deeply nested brackets: `(((((((((x)))))))))`
    * Deeply nested braces: `{{{{{{{{{}}}}}}}}}`

    **Why:** Recursive descent parsers can overflow their stack on deep nesting.
  </Accordion>

  <Accordion title="Input Size DoS" icon="file-arrow-up">
    **Blocked:**

    * Inputs > 50KB (AgentScript preset)
    * Inputs > configured maxInputSize

    **Why:** Large inputs can exhaust memory before validation completes.
  </Accordion>

  <Accordion title="Null Byte Injection" icon="ban">
    **Blocked:**

    * `\x00` characters anywhere in input

    **Why:** Often indicates binary data injection or attack payloads.
  </Accordion>
</AccordionGroup>

### Pre-Scanner Configuration

CodeCall uses the **AgentScript preset** which provides the strictest pre-scanning:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// AgentScript Pre-Scanner settings (automatic with CodeCall)
{
  regexMode: 'block',        // Block ALL regex literals
  maxInputSize: 50_000,      // 50KB limit
  maxNestingDepth: 30,       // Conservative nesting
  bidiMode: 'strict',        // Block all BiDi characters
}
```

***

## Layer 1: AST Validation

[AST Guard](/frontmcp/v/0.7/guides/ast-guard) parses JavaScript into an Abstract Syntax Tree and validates every node against security rules before any code executes.

### Blocked Constructs

<AccordionGroup>
  <Accordion title="Code Execution Attacks" icon="code">
    **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.
  </Accordion>

  <Accordion title="Global/System Access" icon="globe">
    **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.
  </Accordion>

  <Accordion title="Prototype Pollution" icon="virus">
    **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.
  </Accordion>

  <Accordion title="Unicode/Trojan Source Attacks" icon="eye-slash">
    **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.
  </Accordion>

  <Accordion title="Resource Exhaustion" icon="infinity">
    **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.
  </Accordion>
</AccordionGroup>

### AgentScript Preset

CodeCall uses the **AgentScript preset** - the most restrictive preset designed for LLM-generated code:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { createAgentScriptPreset } from 'ast-guard';

const preset = createAgentScriptPreset({
  // Whitelist-only globals
  allowedGlobals: [
    'callTool', 'getTool', 'codecallContext',
    'Math', 'JSON', 'Array', 'Object', 'String', 'Number', 'Date',
    'console', // optional, controlled by allowConsole
  ],

  // Only bounded loops allowed
  allowedLoops: {
    allowFor: true,      // for (let i = 0; i < n; i++)
    allowForOf: true,    // for (const x of array)
    allowWhile: false,   // ❌ blocked
    allowDoWhile: false, // ❌ blocked
    allowForIn: false,   // ❌ blocked (prototype walking)
  },

  // Arrow functions only (no recursion)
  allowArrowFunctions: true,
});
```

### What's Allowed

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// ✅ Tool calls
const users = await callTool('users:list', { limit: 100 });

// ✅ Variables
const filtered = users.filter(u => u.active);
let count = 0;

// ✅ Bounded loops
for (let i = 0; i < users.length; i++) { count++; }
for (const user of users) { console.log(user.name); }

// ✅ Array methods with arrow functions
const names = users.map(u => u.name);
const total = users.reduce((sum, u) => sum + u.score, 0);

// ✅ Safe built-ins
const max = Math.max(1, 2, 3);
const parsed = JSON.parse('{"a":1}');
const keys = Object.keys(obj);

// ✅ Context access (read-only)
const tenant = codecallContext.tenantId;

// ✅ Return values
return { count, names, total };
```

***

## 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

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Input
const users = await callTool('users:list', {});
for (const user of users) {
  console.log(user.name);
}
return users.length;

// Transformed
async function __ag_main() {
  const users = await __safe_callTool('users:list', {});
  __safe_forOf(users, (user) => {
    __safe_console.log(user.name);
  });
  return users.length;
}
```

### Reserved Prefixes

User code **cannot** declare identifiers with these prefixes:

* `__ag_` - AgentScript internal functions
* `__safe_` - Safe runtime proxies

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// ❌ BLOCKED by AST validation
const __ag_hack = 'foo';
let __safe_bypass = 123;
```

***

## 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)

| 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

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// This code triggers EXFIL_PATTERN + SENSITIVE_FIELD + EXCESSIVE_LIMIT
const users = await callTool('users:list', {
  limit: 100000,
  fields: ['email', 'password', 'apiKey']
});
await callTool('webhooks:send', { data: users });

// Score breakdown:
// - SENSITIVE_FIELD: +35 (password, apiKey)
// - EXCESSIVE_LIMIT: +25 (100000 > 10000)
// - EXFIL_PATTERN: +50 (list → send)
// Total: 110 → BLOCKED (critical risk)
```

### 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

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { createEnclave } from 'enclave-vm';

const enclave = createEnclave({
  scoringGate: {
    scorer: 'rule-based',    // 'disabled' | 'rule-based' | 'external-api'
    blockThreshold: 70,      // Block if score >= 70
    warnThreshold: 40,       // Warn if score >= 40
    failOpen: true,          // Allow on scorer errors (production default)
    cache: {
      enabled: true,
      ttlMs: 60000,          // Cache scores for 1 minute
      maxEntries: 1000,
    },
  },
});
```

### 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:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const result = await enclave.run(code, { tools });

console.log(result.scoringResult);
// {
//   allowed: true,
//   warned: true,
//   totalScore: 45,
//   riskLevel: 'medium',
//   signals: [
//     { id: 'EXCESSIVE_LIMIT', score: 25, message: 'Limit 15000 > 10000' },
//     { id: 'WILDCARD_QUERY', score: 20, message: 'Wildcard query "*" detected' }
//   ],
//   latencyMs: 0.8,
//   cached: false
// }
```

### 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

<Info>
  This section is for security auditors and advanced users who need to understand how the Scoring Gate works internally.
</Info>

#### Feature Extraction

The Scoring Gate extracts structured features from code for analysis:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ExtractedFeatures {
  // Tool call metadata
  toolCalls: Array<{
    name: string;           // Tool name (literal or 'DYNAMIC')
    argsPattern: string[];  // Argument keys/patterns
    inLoop: boolean;        // Called inside a loop?
    loopDepth: number;      // Nesting level
  }>;

  // Pattern signals
  patterns: {
    hasLoopedToolCalls: boolean;
    hasNestedLoops: boolean;
    maxLoopNesting: number;
    totalIterations: number; // Estimated from literals
  };

  // Numeric signals
  numerics: {
    maxLimit: number;       // Largest limit/count value
    totalStringLength: number;
    fanOutRisk: number;     // Loop count × tool calls
  };

  // Sensitive data signals
  sensitive: {
    fieldsAccessed: string[];  // password, token, etc.
    hasWildcard: boolean;
    hasBulkOperation: boolean;
  };

  // Code metrics
  metrics: {
    hash: string;           // SHA-256 for caching
    lineCount: number;
    complexity: number;     // Cyclomatic complexity
  };
}
```

#### 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

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { RuleBasedScorer, ScoringRule } from 'enclave-vm';

const customRule: ScoringRule = {
  id: 'CUSTOM_PII_ACCESS',
  evaluate: (features) => {
    const piiFields = ['ssn', 'dob', 'address', 'phone'];
    const accessed = features.sensitive.fieldsAccessed
      .filter(f => piiFields.some(pii => f.includes(pii)));

    if (accessed.length > 0) {
      return {
        score: accessed.length * 15,
        description: `PII fields accessed: ${accessed.join(', ')}`,
        level: accessed.length > 2 ? 'high' : 'medium',
      };
    }
    return null;
  },
};

const scorer = new RuleBasedScorer({
  customRules: [customRule],
});
```

#### 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](/frontmcp/v/0.7/guides/enclave) executes transformed code in an isolated Node.js `vm` context.

### Isolation Guarantees

<CardGroup cols={2}>
  <Card title="Fresh Context" icon="plus">
    Each execution gets a new, isolated context with no access to the host environment
  </Card>

  <Card title="Controlled Globals" icon="list-check">
    Only whitelisted globals available: Math, JSON, Array, Object, etc.
  </Card>

  <Card title="No Module Access" icon="ban">
    No require, import, or dynamic module loading
  </Card>

  <Card title="No Async Escape" icon="clock">
    No setTimeout, setInterval, or Promise.race tricks
  </Card>
</CardGroup>

### 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)  |

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  vm: {
    preset: 'secure',  // Uses defaults above
    timeoutMs: 5000,   // Override timeout
  },
});
```

### 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

<Warning>
  Don't confuse **Enclave Security Levels** with **CodeCall VM Presets** - they serve different purposes but work together.
</Warning>

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               |

**Enclave Security Level Defaults:**

| 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     |

**When configuring CodeCall, use VM Presets:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  vm: {
    preset: 'secure',  // Maps to SECURE level
    timeoutMs: 5000,   // Override specific values as needed
  },
});
```

### Worker Pool Adapter (Optional)

For environments requiring **OS-level memory isolation**, enable the Worker Pool Adapter:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { Enclave } from 'enclave-vm';

const enclave = new Enclave({
  adapter: 'worker_threads',  // Enable Worker Pool
  workerPoolConfig: {
    minWorkers: 2,
    maxWorkers: 8,
    memoryLimitPerWorker: 256 * 1024 * 1024,  // 256MB
  },
});
```

#### Dual-Layer Sandbox

When using Worker Pool, code runs in a **dual-layer sandbox**:

```mermaid theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
graph TD
    %% 1. Define Styles
    %% 'innerBox' is for the nested VM box (Bordered)
    classDef innerBox fill:#fff,stroke:#333,stroke-width:1px,rx:0,ry:0,text-align:left,margin:0;

    %% 'plainText' is for the list at the bottom (No Border, Transparent)
    classDef plainText fill:none,stroke:none,text-align:left,font-size:14px;

    %% 2. The Main Container (Worker Thread)
    subgraph Worker ["<div style='font-size:16px; font-weight:bold; margin-bottom:5px;'>Worker Thread (OS-level isolation)</div>"]
        direction TB

        %% The Nested Box (VM)
        VM["<div style='min-width:350px'><b>VM Context (prototype isolation)</b><br/>- Whitelist-only globals<br/>- __safe_* runtime functions</div>"]

        %% The Loose Text Below (as a borderless node)
        Details["<div style='min-width:350px; padding-left:5px'>- parentPort removed from globals<br/>- JSON-only message serialization<br/>- Hard halt via worker.terminate()</div>"]

        %% Connect them invisibly so they stack
        VM --- Details
    end

    %% 3. Apply Classes
    class VM innerBox;
    class Details plainText;

    %% 4. Style the Subgraph (The Outer Box)
    style Worker fill:#fff,stroke:#333,stroke-width:1px,rx:0,ry:0,color:#333

    %% 5. Hide the connecting line
    linkStyle 0 stroke-width:0px;
```

#### 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 the `globals` 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:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// These strings in globals trigger validation errors
const DANGEROUS_PATTERNS = [
  'eval',
  'Function',
  'require',
  'import',
  'process',
  'global',
  'globalThis',
  'setTimeout',
  'setInterval',
  'setImmediate',
];
```

#### Valid Custom Globals

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  vm: {
    globals: {
      // ✅ Valid - primitive values
      tenantId: 'tenant-123',
      maxLimit: 1000,
      isProduction: true,

      // ✅ Valid - plain objects
      config: {
        apiVersion: 'v2',
        features: ['search', 'export'],
      },

      // ✅ Valid - arrays
      allowedRegions: ['us-east', 'eu-west'],
    },
  },
});
```

#### Invalid Custom Globals

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  vm: {
    globals: {
      // ❌ Invalid - functions are stripped
      helper: (x) => x * 2,

      // ❌ Invalid - getters rejected
      computed: {
        get value() { return Date.now(); },
      },

      // ❌ Invalid - dangerous keys rejected
      __proto__: {},
      constructor: {},

      // ❌ Invalid - too deep (>10 levels)
      deeply: { nested: { objects: { will: { be: { rejected: {} } } } } },
    },
  },
});
```

***

## Self-Reference Guard

**Critical Security Feature:** Scripts cannot call CodeCall meta-tools from within scripts.

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Inside codecall:execute script
// ❌ BLOCKED - Self-reference detected
const result = await callTool('codecall:execute', {
  script: 'return "nested"'
});
// Returns: { success: false, error: { code: 'SELF_REFERENCE_BLOCKED' } }

// ❌ Also blocked
await callTool('codecall:search', { query: 'users' });
await callTool('codecall:describe', { toolNames: ['users:list'] });
await callTool('codecall:invoke', { tool: 'users:list', input: {} });
```

### 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:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// execute.tool.ts - First line of callTool handler
assertNotSelfReference(toolName);  // Throws if codecall:* tool
```

***

## 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:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const DEFAULT_BLACKLIST = [
  'system:*',    // System administration tools
  'internal:*',  // Internal/private tools
  '__*',         // Internal implementation tools
];
```

### Pattern Matching

Tool access rules support **glob patterns** for flexible matching:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  toolAccess: {
    mode: 'blacklist',
    patterns: [
      'admin:*',       // Block all admin tools
      'users:delete',  // Block specific tool
      '*:export',      // Block all export operations
    ],
  },
});
```

**Supported patterns:**

* `*` - Matches any characters within a segment
* `?` - Matches a single character
* `prefix:*` - Matches all tools in a namespace

<Warning>
  Pattern matching includes ReDoS protection - patterns are validated and normalized to prevent denial-of-service attacks.
</Warning>

### Whitelist Mode

For maximum security, use whitelist mode to explicitly allow only specific tools:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  toolAccess: {
    mode: 'whitelist',
    patterns: [
      'users:list',
      'users:get',
      'orders:list',
      // Only these 3 tools are accessible
    ],
  },
});
```

### Dynamic Access Control

For complex authorization (e.g., per-tenant, per-user, or context-based):

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  toolAccess: {
    mode: 'dynamic',
    evaluator: async (toolName, context) => {
      // Check tenant permissions
      const allowed = await checkPermission(
        context.tenantId,
        toolName
      );
      return {
        allowed,
        reason: allowed ? undefined : 'Tool not authorized for tenant',
      };
    },
  },
});
```

### Call Depth Tracking

Tool access control tracks **call depth** to prevent indirect privilege escalation:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Direct call from script
await callTool('users:list', {});  // depth: 1

// Tool calls another tool (if allowed)
// Inside users:list:
await callTool('cache:get', {});   // depth: 2
```

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

| 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:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Input types are converted to safe representations
Date        → ISO string
Error       → { name, message, code? }
RegExp      → string pattern
Map         → plain object
Set         → array
Buffer      → "[Buffer]"
ArrayBuffer → "[ArrayBuffer]"
```

### Circular Reference Detection

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Script returns circular reference
const obj = { name: 'test' };
obj.self = obj;
return obj;

// Sanitized output
{
  "name": "test",
  "self": "[Circular]"
}
```

### Information Leakage Prevention (Stack Trace Sanitization)

<Warning>
  Stack traces can reveal sensitive information about your infrastructure. CodeCall sanitizes **40+ patterns** from error messages.
</Warning>

**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 |

**Package Manager Paths Redacted:**

| Manager   | Patterns                 |
| --------- | ------------------------ |
| npm       | `node_modules/`, `.npm/` |
| yarn      | `.yarn/`, `yarn-cache/`  |
| pnpm      | `.pnpm/`, `pnpm-store/`  |
| workspace | `packages/`, `libs/`     |

**Cloud/Container Paths Redacted:**

| 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 |

**CI/CD Paths Redacted:**

* GitHub Actions: `/runner/`, `/_work/`
* GitLab CI: `/builds/`, CI variables
* Jenkins: `/var/jenkins/`, workspace paths
* CircleCI: `/circleci/`, project paths

**Credentials Redacted:**

```
Bearer [token]     → Bearer [REDACTED]
Authorization: ... → Authorization: [REDACTED]
api_key=xxx        → api_key=[REDACTED]
password=xxx       → password=[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

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Before sanitization (DANGEROUS - leaks infrastructure details)
{
  "error": {
    "message": "Cannot read property 'foo' of undefined",
    "stack": "TypeError: Cannot read property 'foo'\n    at processUser (/home/deploy/app/src/handlers/users.ts:42:15)\n    at /home/deploy/app/node_modules/@company/sdk/dist/index.js:156:23",
    "path": "/home/deploy/app/src/handlers/users.ts",
    "env": "production",
    "dbHost": "postgres.internal.company.com"
  }
}

// After sanitization (SAFE)
{
  "error": {
    "message": "Cannot read property 'foo' of undefined",
    "stack": "TypeError: Cannot read property 'foo'\n    at processUser (...)\n    at (...)",
    "code": "RUNTIME_ERROR"
  }
}
```

***

## 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     |

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Example error response
{
  "status": "illegal_access",
  "error": {
    "kind": "IllegalBuiltinAccess",
    "message": "Identifier 'eval' is not allowed in AgentScript"
  }
}
```

***

## Security Checklist

Before deploying CodeCall to production:

<Steps>
  <Step title="Choose VM Preset">
    Use `secure` for production, `locked_down` for sensitive data.

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    vm: { preset: 'secure' }
    ```
  </Step>

  <Step title="Enable Audit Logging">
    Monitor script execution, tool calls, and security events.

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    // Subscribe to CodeCall events
    scope.events.on('codecall:*', logEvent);
    ```
  </Step>

  <Step title="Configure Tool Allowlists">
    Limit which tools are accessible via CodeCall.

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    codecall: { enabledInCodeCall: true }  // per-tool
    includeTools: (tool) => !tool.name.startsWith('admin:')  // global
    ```
  </Step>

  <Step title="Remove Stack Traces">
    Ensure sanitization is enabled (default).

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    sanitization: { removeStackTraces: true, removeFilePaths: true }
    ```
  </Step>

  <Step title="Configure AI Scoring Gate">
    Enable rule-based scoring with appropriate thresholds.

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    scoringGate: {
      scorer: 'rule-based',
      blockThreshold: 70,
      warnThreshold: 40,
    }
    ```
  </Step>

  <Step title="Test Security Boundaries">
    Run the attack vector tests from ast-guard's security audit.
  </Step>
</Steps>

***

## Threat Model

### What CodeCall Protects Against

<CardGroup cols={2}>
  <Card title="Code Injection" icon="syringe">
    AST validation blocks eval, Function, and dynamic code execution
  </Card>

  <Card title="Sandbox Escape" icon="door-open">
    Isolated vm context with no access to Node.js APIs or globals
  </Card>

  <Card title="Data Exfiltration" icon="file-export">
    AI Scoring Gate detects fetch→send patterns and sensitive data access
  </Card>

  <Card title="Bulk Data Harvesting" icon="database">
    Scoring Gate flags excessive limits and bulk operations
  </Card>

  <Card title="Prototype Pollution" icon="virus">
    Blocked at AST level and isolated at runtime
  </Card>

  <Card title="Resource Exhaustion" icon="infinity">
    Timeouts, iteration limits, and tool call caps
  </Card>

  <Card title="I/O Flood Attacks" icon="wave-pulse">
    Console output size and call count limits prevent logging abuse
  </Card>

  <Card title="Information Leakage" icon="eye">
    Stack traces and file paths sanitized from outputs
  </Card>

  <Card title="Recursive Execution" icon="arrows-rotate">
    Self-reference guard blocks codecall:\* tool calls
  </Card>

  <Card title="VM Timeout Bypass" icon="clock">
    Worker Pool provides hard halt via worker.terminate() when VM timeout fails
  </Card>
</CardGroup>

### What CodeCall Does NOT Protect Against

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

| 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

<CardGroup cols={2}>
  <Card title="AST Guard" icon="shield-check" href="/frontmcp/v/0.7/guides/ast-guard">
    Deep dive into AST validation rules, presets, and custom rule creation
  </Card>

  <Card title="Enclave" icon="lock" href="/frontmcp/v/0.7/guides/enclave">
    Runtime sandbox configuration, sidecar storage, and advanced options
  </Card>

  <Card title="Security Audit" icon="file-shield" href="https://github.com/agentfront/enclave/blob/main/libs/ast-guard/docs/SECURITY-AUDIT.md">
    Full list of 100+ blocked attack vectors including Layer 0 Pre-Scanner
  </Card>

  <Card title="Configuration" icon="gear" href="/frontmcp/v/0.7/plugins/codecall/configuration">
    Complete configuration reference for security settings
  </Card>
</CardGroup>
