> ## 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 names, as a variable and as a property.

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

const rule = new DisallowedIdentifierRule({
  disallowed: ['eval', 'Function', 'process', 'require'],
  disallowedProperties: ['__lookupGetter__'],  // refused as a property only
  blockProtoInObjectLiterals: true,            // { __proto__: x }, { ['__proto__']: x }
  disallowedObjectKeys: ['hook'],              // refused as a key of an object literal too
  resolveVariableKeys: true,                   // const k = 'eval'; obj[k]   (default: true)
  checkDestructuringKeys: true,                // const { eval: e } = obj    (default: true)
});
```

A listed name is refused wherever a property is read or written: `obj.name`, `obj?.name`, `obj['name']`, an assignment target, and the key of a destructuring pattern (`const { name: x } = obj`, `({ name }) => ...`).

A computed key is evaluated, not matched against a list of spellings. A key that is made of constants (literals, operators, the built-in functions of the language applied to constants, a function written in place and called there) has one fixed value, which is compared with the refused names: `obj['na' + 'me']`, `obj[['na', 'me'].join('')]` and `obj['NAME'.toLowerCase()]` are all `obj.name`.

| Key | Answer |
| - | - |
| Made of constants, and a refused name | `DISALLOWED_IDENTIFIER` |
| Made of constants, and not computed by the validator | `STATIC_KEY_UNRESOLVED`: a name the validator cannot read is not accepted unread |
| Made of constants, and built to more than 4096 characters (`'ab'.repeat(5000)`) | `STATIC_KEY_TOO_LONG`, without building it. A literal that long (a string, or a template without a substitution) is not built: it is read as it is written |
| Held in a variable (`resolveVariableKeys`) | A `const` that holds a constant is that constant. For any other variable, and for a parameter, the constants the script can be seen giving it are compared with the refused names: an assignment, a pattern, a loop, a call that can be seen, a value stored into the list or the object it holds. A `var` named like a parameter is that parameter (where the parameter list has an expression in it, a variable of its own that starts with the parameter's value), and a rest parameter is the list of the arguments from where it stands. This is a search, not a proof: a name a script assembles at run time over several statements is a run-time value. A search that reaches its limit does not make the key a run-time value: the key is refused |
| Depends on a run-time value (a parameter, the result of a call into the host) | Not decided by the validator. `guardComputedMemberKeys` checks it where the script runs |

`resolveVariableKeys: false` and `checkDestructuringKeys: false` are for a validator that is followed by such a check: the AgentScript preset sets both, because `@enclave-vm/core` applies the key guard after it (which answers for a variable the way the security level says) and because `NoComputedDestructuringRule` decides the keys a pattern may read. The STRICT and SECURE presets, which nothing follows, leave both on.

A value the validator computes is the value the engine computes. Where the two could differ, the key is not computed, and so is refused: where something inside the key assigns and what follows may read it, or is not evaluated (`((k) => (k = 'b', k))('a')`; an assignment that nothing is evaluated after is the value it assigns, so `o[(name = 'alpha')]` is `o.alpha`), where the answer depends on the engine or the realm (`typeof Math`, whether a newer method exists), and, in a script that can change a built-in, for everything that goes through a built-in. A script can change a built-in when it assigns to one (`Math.max = f`), or when it hands one on (`const M = Math`) and also writes to an object that may be it (`M.max = f`); a script that only passes `Number` to `map`, or keeps `Object.keys` under another name, cannot. A limit that is reached (steps, depth, alternatives, size) is a key that is not computed, never a shorter list of names and never a key left to run time. Inside a `with` statement a name may be a property of its object, so a key that names a variable there is not computed (and `NoEvalRule` refuses `with` in every preset).

`NoGlobalAccessRule` (the `constructor` property), `NoRegexMethodsRule` and `ReservedPrefixRule` read a computed key the same way.

A rule that reads a key reports one it cannot read with the severity of the rule. Where several rules read the same key, it is reported once, at the highest of their severities: turning one rule down to a warning does not turn the refusal of another into a warning.

## 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,
  directCallsOnly: true,
});
```

`directCallsOnly: true` counts `callTool(...)` and ignores a method with the same name, such as `local.callTool(...)`. The default is `false`. With several names and `mode: 'any'`, `minCalls` and `maxCalls` apply to the combined count across those names; with the default `mode: 'all'`, they apply to each name.

## 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)` and `setInterval('code', 100)`: a string as the first argument, in every spelling that is made of constants (a literal, a template literal, pieces that are joined, a `const`, a list that is spread) or that can never be a function whatever it holds (a template, a list, an object, `String(value)`, `value.toString()`), with the timer called by name, as a member (`window.setTimeout(...)`), with `new` or as a template tag. A first argument that is a function, or that may be one, is not refused.
* `setTimeout` / `setInterval` used as a value: stored under another name, passed to a function, called through `.call`, `.apply` or `.bind`. What such a timer is then called with is out of the rule's sight. `typeof setTimeout` is allowed.
* `eval` and `Function` used as a value (`const F = Function`, `(0, eval)(code)`), and `Function(code)` called without `new`. `x instanceof Function` is allowed.

## 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: true,
  analyzeStringPatterns: { analysisLevel: 'catastrophic' },
  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 `allowStringArguments: true`, `analyzeStringPatterns` checks quoted string arguments and template literals without expressions for ReDoS. It accepts `analysisLevel: 'catastrophic' | 'polynomial'` and an optional `blockThreshold` (default: 80). Patterns over 500 characters are refused because the analysis is bounded to that length. Calls on a free global listed in `hostObjectNames` are treated as host object methods; a local variable with the same name is still analyzed. STRICT and SECURE enable catastrophic analysis.

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.