Skip to main content
ast-guard is FrontMCP’s AST validation library for JavaScript. It inspects user-provided or LLM-generated code before execution, blocking dangerous constructs and enforcing API usage policies. ast-guard powers Enclave’s first security layer and can be used standalone for any JavaScript validation needs.

16 Built-in Rules

Block eval, dangerous globals, prototype manipulation, unbounded loops, ReDoS, and more with battle-tested validation rules.

Pre-Scanner Defense

Layer 0 security that runs BEFORE parsing - catches DoS attacks that could crash the parser itself.

AgentScript Preset

Purpose-built preset for LLM-generated orchestration code with whitelist-only globals and strict control flow.

When to Use ast-guard

  • LLM-generated code - Validate AI-written JavaScript before execution
  • User scripts - Accept arbitrary JavaScript with deterministic guardrails
  • Workflow builders - Enforce API usage and block dangerous constructs
  • Compliance requirements - Audit trails showing exactly which rule blocked a script
ast-guard is a pure TypeScript package with zero native dependencies. It works in Node.js 22+ and can be used standalone or as part of the Enclave execution environment.

Installation

Quick Start

Instantiate JSAstValidator once and reuse it. This keeps presets, custom rules, and caches consistent across requests.

Pre-Scanner (Layer 0 Defense)

The pre-scanner runs BEFORE the JavaScript parser (acorn) to catch DoS attacks that could crash or hang the parser itself. It enforces mandatory security limits that cannot be disabled.

Mandatory Limits (Cannot Be Exceeded)

These limits protect against parser crashes and cannot be overridden:

Pre-Scanner Preset Comparison

Regex Handling Modes

The pre-scanner supports three regex handling modes:
  • block - Block ALL regex literals (AgentScript default, maximum security)
  • analyze - Allow but analyze for ReDoS patterns (Strict/Secure/Standard)
  • allow - Allow all regex without analysis (Permissive only)

ReDoS Detection Patterns

The pre-scanner detects these dangerous regex patterns: | Pattern | Score | Example | Risk | | ----------------------- | ----- | ------------ | ------------------------ | ------------------------ | | Nested quantifier | 90 | (a+)+ | Exponential backtracking | | Star in repetition | 85 | (a+){2,} | Exponential backtracking | | Repetition in star | 85 | (a{2,})+ | Exponential backtracking | | Overlapping alternation | 80 | (a | ab)+ | Exponential backtracking | | Greedy backtracking | 75 | (.*a)+ | Polynomial backtracking | | Multiple greedy | 70 | .*foo.*bar | Polynomial backtracking |

AgentScript Preset

The AgentScript preset is purpose-built for validating LLM-generated orchestration code. It’s the default preset used by Enclave and the CodeCall Plugin.

AgentScript Preset Options

Use requireCallTool: true to ensure AgentScript code actually interacts with tools rather than just performing local computations. This is useful for preventing scripts that do nothing useful.

What AgentScript Blocks

What AgentScript Allows


Code Transformation

ast-guard can transform validated code for safe execution:
Transformations provide:
  • Main wrapper: async function __ag_main() enables top-level await
  • Safe callTool: Proxied through runtime with call counting
  • Safe loops: Iteration limits enforced at runtime
  • Reserved prefixes: __ag_ and __safe_ cannot be used by user code

Security Presets

ast-guard includes four security presets for different use cases:

Validation in Tools

Use ast-guard to validate scripts inside FrontMCP tools:

Enforce policy at the platform level

Use hooks to reject bad scripts before the tool executes, even if multiple tools submit code.
src/plugins/script-guard.plugin.ts

Built-in Security Rules

ast-guard ships with a comprehensive set of security rules:

NoGlobalAccessRule

Blocks access to dangerous global objects via member expressions (e.g., window.location, process.env).

ReservedPrefixRule

Prevents user code from declaring or assigning identifiers with reserved prefixes (e.g., __ag_, __safe_).

NoCallTargetAssignmentRule

Protects critical call targets from being reassigned or shadowed.
This blocks:
  • callTool = malicious; - Direct assignment
  • const callTool = () => {}; - Variable shadowing
  • const { callTool } = obj; - Destructuring shadowing
  • function callTool() {} - Function declaration shadowing

UnicodeSecurityRule

Detects and blocks Unicode-based attacks including Trojan Source, homoglyphs, and invisible characters.
Trojan Source attacks (CVE-2021-42574) use Unicode bidirectional control characters to make code appear different than it actually executes. Always enable blockBidi: true for untrusted code.

StaticCallTargetRule

Enforces static string literals for call targets, preventing dynamic tool name injection.
This blocks:
  • callTool(toolName, args); - Variable reference
  • callTool("tool" + suffix, args); - Concatenation
  • callTool(\tool_$`, args);` - Template with expressions
  • callTool(cond ? "a" : "b", args); - Ternary expression

NoRegexLiteralRule

Blocks or analyzes regex literals for ReDoS vulnerabilities.

NoRegexMethodsRule

Blocks regex method calls to provide defense-in-depth against ReDoS.
Even if regex literals are blocked, attackers could construct regex through other means. This rule blocks the execution paths.

Mix in fine-grained rules

Combine built-in rules to match your own threat model.
src/security/custom-rules.ts

Whitelist-based identifier control with UnknownGlobalRule

UnknownGlobalRule implements a whitelist-based approach where all identifier references must be either declared locally or explicitly allowed. This is the most secure option for sandboxed environments.
UnknownGlobalRule uses a flat symbol table for performance. It collects all declarations across the AST without tracking lexical scope. This is an intentional simplification for AgentScript v1 where user-defined functions are blocked by default (NoUserDefinedFunctionsRule). If you enable user functions, be aware that inner-scope declarations will “whitelist” that identifier name globally.

Return actionable errors to requesters

Surface structured issues so users (or copilots) know how to fix their scripts.

Monitor and tune validation

  • stopOnFirstError halts validation as soon as a rule reports an error—great for latency-sensitive flows.
  • maxIssues caps the number of findings returned for a single run to avoid overwhelming users.
  • parseOptions lets you enforce sourceType, strict mode, or JSX support per tool.
  • validator.getStats(result, durationMs) produces telemetry-friendly counters.
AST Guard prevents unsafe syntax from entering your sandbox, but it does not execute or sandbox code itself. Pair it with your existing isolation layer (isolated-vm, workers, remote runners, etc.) for complete defense-in-depth.