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

> Built-in security rules for AST validation

ast-guard ships with 21 built-in rules; 19 of them are exported as classes (`InfiniteLoopRule` and `ResourceExhaustionRule` are part of the AgentScript preset only). Each rule can be configured and combined to match your security requirements. This page covers the ones a host is most likely to configure itself; the [AgentScript preset](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/agentscript-preset.md) combines them for LLM-generated code.

## NoGlobalAccessRule

Blocks access to the global objects, to `constructor`, to the `Reflect` API and to the reflection statics of `Object`.

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

const rule = new NoGlobalAccessRule({
  blockedGlobals: ['window', 'globalThis', 'self', 'global', 'this'], // the default
  blockMemberAccess: true,       // window.x (default: true)
  blockComputedAccess: true,     // window['x'], window[name] (default: true)
  requireDirectObjectUse: false, // see below (default: false)
});
```

**Blocks:**

* `window.location`
* `globalThis['Function']`
* `this` as a value in any position, when `'this'` is in `blockedGlobals`: `const g = this`, `f(this)`, `const { x } = this`. The STRICT and SECURE presets refuse it this way
* `Object.create`, `Object.defineProperty`, `Object.getPrototypeOf` and the other prototype and descriptor statics, wherever the member is read

With `requireDirectObjectUse: true` the global `Object` may only be used directly: as `Object.name` with a name written in the source, called, constructed, or as the operand of `typeof` / `instanceof`. An alias (`const O = Object`), passing or storing it, destructuring from it, a member name computed at run time and `Object.valueOf()` are refused with `OBJECT_INDIRECT_USE`. The AgentScript preset switches this on.

## ReservedPrefixRule

Prevents user code from declaring identifiers with reserved prefixes.

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

const rule = new ReservedPrefixRule({
  reservedPrefixes: ['__ag_', '__safe_'], // the default
  allowedIdentifiers: ['__ag_main'],
});
```

**Blocks:**

* `const __ag_hack = 1;`
* `let __safe_bypass = true;`
* `__maxIterations`, the runtime's name for the iteration limit, whatever prefixes are configured

On the rule, `reservedPrefixes` is the complete list. The `reservedPrefixes` option of the AgentScript preset adds to `__ag_` and `__safe_` instead.

## NoCallTargetAssignmentRule

Protects critical call targets from being reassigned or shadowed.

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

const rule = new NoCallTargetAssignmentRule({
  protectedTargets: ['callTool', '__safe_callTool'],
});
```

**Blocks:**

* `callTool = malicious;` - Direct assignment
* `const callTool = () => {};` - Variable shadowing
* `const { callTool } = obj;` - Destructuring shadowing
* `function callTool() {}` - Function declaration shadowing

The rule sees every write and every declaration of a protected name: destructuring patterns, loop heads, `++` / `--`, catch-clause patterns, parameters and their default values, and class names.

## UnicodeSecurityRule

Reports bidirectional control characters, look-alike characters, zero-width characters and invisible characters in a script. The tag characters (U+E0000 to U+E007F) count as invisible characters. No preset includes this rule; add it to a validator yourself.

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

const rule = new UnicodeSecurityRule({
  blockBidi: true,          // Block bidirectional text attacks
  blockHomoglyphs: true,    // Block lookalike characters
  blockZeroWidth: true,     // Block zero-width characters
  blockInvisible: true,     // Block invisible formatting
  checkComments: true,      // Also check inside comments
});
```

> [!WARNING]
>
> 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.

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

const rule = new StaticCallTargetRule({
  targetFunctions: ['callTool', '__safe_callTool'],
  argumentPosition: 0,
  allowedToolNames: ['users:list', /^billing:/], // Optional whitelist: exact names or RegExp
  requireDirectCall: false, // true: the target may only appear as a direct call
});
```

**Blocks:**

* `callTool(dynamicName, {})` - Variable as tool name
* `callTool(getToolName(), {})` - Function call as tool name

**Allows:**

* `callTool('users:list', {})` - Static string literal

With `requireDirectCall: true` (as in the AgentScript preset) nothing else may be done with the target function: no alias, no `.call` / `.apply` / `.bind`, no tagged template, no passing it as a value.

## NoRegexLiteralRule

Blocks or analyzes regex literals for ReDoS vulnerabilities.

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

// Block all regex (AgentScript preset)
new NoRegexLiteralRule({ blockAll: true });

// Analyze patterns for ReDoS
new NoRegexLiteralRule({
  analyzePatterns: true,
  analysisLevel: 'catastrophic',
  blockThreshold: 80,
  warnThreshold: 50,
});
```

## DisallowedIdentifierRule

Blocks specific identifier names.

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

const rule = new DisallowedIdentifierRule({
  disallowed: ['eval', 'Function', 'process', 'require'],
});
```

## ForbiddenLoopRule

Restricts which loop constructs are allowed.

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

const rule = new ForbiddenLoopRule({
  allowFor: true,
  allowForOf: true,
  allowWhile: false,
  allowDoWhile: false,
  allowForIn: false,
});
```

## RequiredFunctionCallRule

Ensures code contains required function calls.

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

const rule = new RequiredFunctionCallRule({
  required: ['callTool'],
  minCalls: 1,
});
```

## UnknownGlobalRule

Rejects references to undeclared identifiers (whitelist mode).

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

const rule = new UnknownGlobalRule({
  allowedGlobals: ['callTool', 'Math', 'JSON', 'Array', 'Object'],
  allowStandardGlobals: true, // Allow undefined, null, NaN, etc.
  allowGlobalAssignment: false, // Assigning to an allowed global is refused (default)
});
```

Names are resolved by lexical scope: a declaration in a block, an arrow function or a catch clause makes a name local only there. The first `UNKNOWN_GLOBAL` issue of a validation states the list of allowed globals (in its message and in `data.allowedGlobals`); the following ones name the identifier only.

## NoEvalRule

Blocks eval and dynamic code execution.

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

const rule = new NoEvalRule();
```

**Blocks:**

* `eval('code')`
* `new Function('return 1')`
* `setTimeout('code', 100)` - String form

## NoAsyncRule

Restricts async/await usage.

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

const rule = new NoAsyncRule({
  allowAwait: true,
  allowAsyncFunctions: false,
});
```

## NoUserDefinedFunctionsRule

Blocks user-defined functions (prevents recursion).

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

const rule = new NoUserDefinedFunctionsRule({
  allowArrowFunctions: true, // For array methods
  allowedFunctionNames: ['__ag_main'], // The wrapper a compiler puts around the script (default)
});
```

A name in `allowedFunctionNames` allows one declaration: the first one at the top level that has the shape of the wrapper (`async function name() { ... }`: async, not a generator, no parameters). Every other function declaration is refused whatever its name.

**Blocks:**

* `function foo() {}`
* `const fn = function() {}`

**Allows:**

* `array.map(x => x * 2)` - Arrow functions (if enabled)

## UnreachableCodeRule

Detects code after return/throw statements.

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

const rule = new UnreachableCodeRule();
```

## CallArgumentValidationRule

Validates function call arguments.

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

const rule = new CallArgumentValidationRule({
  functions: {
    callTool: {
      minArgs: 1,
      maxArgs: 2,
      expectedTypes: ['string', 'object'],
    },
  },
});
```

## AllowedSyntaxRule

An allowlist of syntax: a script may only contain the listed ESTree node types.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { AllowedSyntaxRule, AGENTSCRIPT_ALLOWED_NODE_TYPES } from '@enclave-vm/ast';

const rule = new AllowedSyntaxRule({
  allowedNodeTypes: [...AGENTSCRIPT_ALLOWED_NODE_TYPES],
});
```

Four constructs share their node type with an ordinary one and are constructs of their own. They are refused (`DISALLOWED_SYNTAX`) unless listed under their own name: `UsingDeclaration`, `AwaitUsingDeclaration`, `ForAwaitStatement` and `GeneratorFunction`. Listing `ForOfStatement` allows `for…of`, not `for await…of`.

## NoRegexMethodsRule

Blocks the string and regex methods that run a regular expression.

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

const rule = new NoRegexMethodsRule({
  allowStringArguments: false, // Also refuse a string argument (default: true)
  hostObjectNames: ['docs'],   // Globals that are host objects, not strings
  requireDirectCall: false,    // true: the methods cannot be read as values (default: false)
});
```

`match`, `matchAll` and `search` compile a string argument into a regular expression, so with `allowStringArguments: false` they are refused with any argument. The method name is resolved in every static spelling (`x.match`, `x['match']`, a template literal without substitutions), and the call is seen through `call` / `apply` / `bind`, as a template tag and without an argument.

With `requireDirectCall: true`, a property named `match`, `matchAll` or `search` can only be called where it stands: reading it, passing or storing it and taking it by destructuring are refused. That also refuses reading a field of ordinary data with such a name (`params.search`), which is why it is off by default.

## NoJsonCallbacksRule

Blocks `JSON.stringify` with a replacer function and `JSON.parse` with a reviver function.

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

const rule = new NoJsonCallbacksRule({
  requireDirectUse: true, // JSON may only appear as JSON.parse(...) / JSON.stringify(...)
});
```

With `requireDirectUse: true` an alias of `JSON`, `.call` / `.apply` / `.bind`, a computed method name and every method other than `parse` and `stringify` are refused (`JSON_INDIRECT_USE`). Only the global `undefined` counts as "no replacer or reviver", not a variable of the script with that name.

## Rule Severity

A rule has a default severity. Override it per validation, by rule name:

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

const result = await validator.validate(code, {
  rules: {
    'disallowed-identifier': { enabled: true, severity: ValidationSeverity.WARNING },
  },
});
```

## Related

* [Custom Rules](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/custom-rules.md) - Writing your own rules
* [AgentScript Preset](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/agentscript-preset.md) - Pre-configured ruleset
* [Pre-Scanner](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/pre-scanner.md) - Layer 0 defense


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.