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

> Best practices for securing Enclave deployments

This guide covers security best practices for hardening Enclave deployments in production environments.

## Security Checklist

### Critical

* [ ] Use `STRICT` security level for untrusted code
* [ ] Set memory limits, on the sandbox and on the process or container around it
* [ ] Configure timeouts
* [ ] Validate all tool inputs
* [ ] Authenticate callers in front of every endpoint that accepts code, and in front of every session route of the broker: the routes that list, read, replay and end sessions have no authentication of their own either
* [ ] Give the broker's session routes an `identify` hook, so that a session belongs to the caller that created it. Authentication alone does not do that. Only a broker whose routes a single trusted backend calls can go without the hook (see [Client Connections](#client-connections))
* [ ] Run as non-root user

### Recommended

* [ ] Use HTTPS for client connections: the client and the broker exchange plain JSON
* [ ] Run the sandbox in the worker pool for a hard stop of a script that runs past its timeout and a heap limit per worker. A worker thread shares the host's process: the pool does not guarantee that the host survives
* [ ] Run the enclave in a child process or a container with limits of the operating system when the host must survive any script
* [ ] Consider the AI Scoring Gate as an additional, heuristic signal
* [ ] Implement rate limiting
* [ ] Use network segmentation
* [ ] Enable audit logging
* [ ] Set up intrusion detection
* [ ] Regular security updates

## Security Levels

Always use the appropriate security level:

| Level | Use Case | Restrictions |
| - | - | - |
| `STRICT` | Untrusted AI/user code | Maximum restrictions |
| `SECURE` | Semi-trusted automation | High restrictions |
| `STANDARD` | Internal tools | Moderate restrictions |
| `PERMISSIVE` | Testing only | Minimal restrictions |

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

// For untrusted code - always use STRICT
const enclave = new Enclave({
  securityLevel: 'STRICT',
});
```

## Defense in Depth

### Layer 1: Input Validation

Validate code before it reaches Enclave:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { z } from 'zod';

const executeSchema = z.object({
  code: z
    .string()
    .min(1)
    .max(100000) // Limit code size
    .refine(
      (code) => !code.includes('__proto__'),
      'Suspicious code pattern detected'
    ),
  timeout: z.number().min(1000).max(300000).optional(),
});

app.post('/execute', async (req, res) => {
  const result = executeSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ error: 'Invalid request' });
  }
  // Proceed with validated input
});
```

### Layer 2: Pre-Scanner

`Enclave` runs the pre-scanner on the script as it was written, before anything parses it, with the pre-scanner preset named like the AST preset. With the default `agentscript` preset that is the strictest one: 100 KB of code in at most 1,000 lines of at most 2,000 characters, string literals of at most 10 KB, no regular-expression literal, and no bidirectional or invisible control character.

Loosen single limits only where your scripts need it, and keep the Unicode checks:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  preScan: {
    // The agentscript pre-scanner, with room for scripts of up to 500 KB
    config: { maxInputSize: 500 * 1024, maxLines: 5000 },
  },
});
```

`preScan: { preset: 'standard' }` gives the limits enclaves had before 2.19.2 (5 MB, 10,000 lines, regular-expression literals analyzed, no check for bidirectional or invisible characters).

### Layer 3: AST Validation

Strict AST validation:

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

const validator = new JSAstValidator(
  createAgentScriptPreset({
    // Only allow specific globals
    allowedGlobals: ['callTool', 'Math', 'JSON', 'console'],

    // Block additional identifiers
    additionalDisallowedIdentifiers: [
      'fetch',
      'XMLHttpRequest',
      'WebSocket',
    ],

    // Strict loop configuration
    allowedLoops: {
      allowFor: true,
      allowForOf: true,
      allowWhile: false,
      allowDoWhile: false,
      allowForIn: false,
    },
  })
);
```

### Layer 4: AI Scoring Gate

An optional heuristic: it scores a script by its tool calls and refuses it at a threshold. It flags patterns that look risky; a low score does not show that a script is safe.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  scoringGate: {
    scorer: 'rule-based',
    blockThreshold: 70,
    warnThreshold: 40,
    failOpen: false, // Refuse a script the gate cannot score
  },
});

const result = await enclave.run(code);

// The gate has no callback: read the score from the result
if (result.scoringResult?.warned) {
  logger.warn('Suspicious code pattern', {
    score: result.scoringResult.totalScore,
    signals: result.scoringResult.signals,
  });
}
```

### Layer 5: Runtime Isolation

Limits, and the worker pool around the sandbox:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  // Memory limit (the enclave's own accounting; the default is 1 MB)
  memoryLimit: 64 * 1024 * 1024, // 64MB

  // Execution timeout
  timeout: 30000, // 30 seconds

  // Tool call limit
  maxToolCalls: 50,

  // Iteration limit
  maxIterations: 10000,

  // Run scripts in worker threads: a heap limit per worker and a hard stop
  adapter: 'worker_threads',
  workerPoolConfig: {
    maxWorkers: 4,
    memoryLimitPerWorker: 128 * 1024 * 1024,
  },
});
```

What these limits are, and are not:

* In process, `timeout` and `memoryLimit` are the enclave's own accounting, not the engine's. The deadline is checked between the steps of the script's own code, so one call into a built-in is not bounded by `timeout`. `memoryLimit` counts the operations that make text and arrays grow; it does not count copies, objects, Maps or Sets.
* The worker pool adds the engine's heap limit and terminates a script that is still running five seconds after its timeout. A worker thread shares the process with the host: it is not process isolation, and the heap limit is a backstop, not a guarantee that the process survives.
* A host that must survive whatever a script does runs the enclave in a child process or a container with limits of the operating system.

### Layer 6: Output Sanitization

Sanitize all outputs:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function sanitizeOutput(output: unknown): unknown {
  // Remove circular references
  const seen = new WeakSet();

  function sanitize(value: unknown): unknown {
    if (value === null || typeof value !== 'object') {
      // Truncate long strings
      if (typeof value === 'string' && value.length > 10000) {
        return value.slice(0, 10000) + '... [truncated]';
      }
      return value;
    }

    if (seen.has(value)) {
      return '[Circular]';
    }
    seen.add(value);

    if (Array.isArray(value)) {
      // Limit array size
      const limited = value.slice(0, 1000);
      return limited.map(sanitize);
    }

    const sanitized: Record<string, unknown> = {};
    for (const [key, val] of Object.entries(value)) {
      // Skip sensitive keys
      if (key.match(/password|secret|token|key/i)) {
        sanitized[key] = '[REDACTED]';
      } else {
        sanitized[key] = sanitize(val);
      }
    }
    return sanitized;
  }

  return sanitize(output);
}
```

## Tool Security

### Input Validation

Always validate tool inputs:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { z } from 'zod';

const toolSchemas = {
  'users:get': z.object({
    id: z.string().uuid(),
  }),
  'users:list': z.object({
    limit: z.number().int().min(1).max(100).default(10),
    offset: z.number().int().min(0).default(0),
  }),
  'email:send': z.object({
    to: z.string().email(),
    subject: z.string().max(200),
    body: z.string().max(10000),
  }),
};

const enclave = new Enclave({
  toolHandler: async (name, args) => {
    const schema = toolSchemas[name];
    if (!schema) {
      throw new Error(`Unknown tool: ${name}`);
    }

    const result = schema.safeParse(args);
    if (!result.success) {
      throw new Error(`Invalid arguments: ${result.error.message}`);
    }

    return executeTool(name, result.data);
  },
});
```

### Permission Control

Implement tool permissions per user. A tool handler receives the tool name and the arguments, nothing about the caller, so create the enclave (or pass the handler to `run()`) for the user the script runs for:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface UserPermissions {
  tools: string[];
  limits: {
    maxToolCalls: number;
  };
}

async function runForUser(userId: string, code: string) {
  const permissions = await getUserPermissions(userId);

  const enclave = new Enclave({
    securityLevel: 'STRICT',
    // The enclave enforces the call limit itself
    maxToolCalls: permissions.limits.maxToolCalls,
    toolHandler: async (name, args) => {
      // Check tool access
      if (!permissions.tools.includes(name)) {
        throw new Error(`Tool ${name} not allowed for user`);
      }
      return executeTool(name, args, { userId });
    },
  });

  try {
    return await enclave.run(code);
  } finally {
    enclave.dispose();
  }
}
```

### Data Filtering

Filter sensitive data from tool responses:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function filterSensitiveData(data: unknown): unknown {
  if (data === null || typeof data !== 'object') {
    return data;
  }

  if (Array.isArray(data)) {
    return data.map(filterSensitiveData);
  }

  const filtered: Record<string, unknown> = {};
  const sensitiveKeys = ['password', 'secret', 'token', 'ssn', 'creditCard'];

  for (const [key, value] of Object.entries(data)) {
    if (sensitiveKeys.some(s => key.toLowerCase().includes(s))) {
      continue; // Omit sensitive fields
    }
    filtered[key] = filterSensitiveData(value);
  }

  return filtered;
}
```

## Network Security

### Isolation

Run the process that executes scripts (your application with `@enclave-vm/core`, or the broker) on an internal network, behind the gateway that authenticates callers. A script has no network access of its own; what reaches the network are your tool handlers, so give that process only the routes its tools need:

```yaml theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
# docker-compose.yml
services:
  gateway:
    networks:
      - enclave-internal
      - external

  enclave-broker:
    networks:
      - enclave-internal
    # Reached through the gateway only

networks:
  enclave-internal:
    internal: true
  external:
```

### TLS Configuration

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { createServer } from 'https';
import { readFileSync } from 'fs';

const server = createServer({
  key: readFileSync('/certs/server.key'),
  cert: readFileSync('/certs/server.crt'),
  ca: readFileSync('/certs/ca.crt'),

  // Modern TLS settings
  minVersion: 'TLSv1.2',
  ciphers: [
    'ECDHE-ECDSA-AES128-GCM-SHA256',
    'ECDHE-RSA-AES128-GCM-SHA256',
    'ECDHE-ECDSA-AES256-GCM-SHA384',
    'ECDHE-RSA-AES256-GCM-SHA384',
  ].join(':'),
});
```

### Client Connections

`@enclave-vm/client` sends requests and receives events as plain JSON. It does not encrypt and has no encryption option, so the transport is what protects a session: use an `https:` base URL. Credentials go in `headers`:

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

const client = new EnclaveClient({
  baseUrl: 'https://broker.example.com',
  headers: {
    Authorization: `Bearer ${token}`,
  },
});
```

The client's options are `baseUrl`, `headers`, `timeout`, `autoReconnect`, `maxReconnectAttempts`, `reconnectDelay`, `maxEventLength` and `fetch`. Any other key, such as `encryption` or `auth`, makes the constructor throw.

The broker's session routes have no authentication of their own. The application has to put authentication in front of all of them (the route that creates a session, and the routes that list, read, replay and end sessions) and check the credentials the client sends.

Authentication does not tell the routes whose session is whose: without an `identify` hook they answer every caller for every session. Give the session handler the hook, and let it return the caller your authentication found:

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

app.use(authenticate); // your middleware: checks the credential and sets req.user
registerExpressRoutes(
  app,
  createSessionHandler({
    broker,
    // request.raw is the request object of the HTTP framework
    identify: (request) => (request.raw as { user?: { id: string } }).user?.id,
  }),
);
```

With the hook a session belongs to the caller that created it: `GET /sessions` lists the caller's own sessions, a request for another caller's session is answered with `404`, and a request without an identity with `401`. The hook can be left out only where a single trusted backend is the one caller of the routes; that backend then has to keep the sessions of its own users apart. See [Who may see a session](https://docs.agentfront.dev/enclave/enclavejs/broker.md#who-may-see-a-session).

### Payload Encryption

No EnclaveJS package encrypts payloads. An application that wants payload encryption on top of TLS has to wire the primitives of `@enclave-vm/stream` (ECDH P-256, HKDF-SHA-256, AES-256-GCM) into its own endpoints, on both ends. See the [Encrypted Sessions](https://docs.agentfront.dev/enclave/examples/encrypted-sessions.md) example. What such an application has to take care of:

* The key exchange is not authenticated: it protects against a party that can only read the connection, not against one that can change messages. Authenticate the hello messages yourself (for example by signing them with a key the client pins) or rely on TLS for the identity of the server.
* There are two keys, one per direction. Use one `SessionEncryptionContext` per direction.
* Read envelopes with `openEncryptedEnvelope` or `context.openEnvelope`, which fail when the ciphertext or the envelope's header was changed. Whether a sequence number was seen before is for the receiver to check.
* The server that receives the code decrypts it to run it. Payload encryption does not hide anything from that server.

## Rate Limiting

### Per-User Limits

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { RateLimiterRedis } from 'rate-limiter-flexible';
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

const rateLimiter = new RateLimiterRedis({
  storeClient: redis,
  keyPrefix: 'enclave_rl',
  points: 100, // 100 requests
  duration: 60, // per minute
});

app.use('/execute', async (req, res, next) => {
  try {
    await rateLimiter.consume(req.user.id);
    next();
  } catch {
    res.status(429).json({ error: 'Too many requests' });
  }
});
```

### Per-Tool Limits

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const toolLimits = new Map([
  ['email:send', { points: 10, duration: 60 }], // 10 emails per minute
  ['db:query', { points: 100, duration: 60 }], // 100 queries per minute
]);

async function checkToolLimit(userId: string, tool: string) {
  const limit = toolLimits.get(tool);
  if (!limit) return true;

  const limiter = new RateLimiterRedis({
    storeClient: redis,
    keyPrefix: `tool_${tool}`,
    ...limit,
  });

  try {
    await limiter.consume(userId);
    return true;
  } catch {
    return false;
  }
}
```

## Audit Logging

### Comprehensive Logging

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface AuditLog {
  timestamp: string;
  userId: string;
  sessionId: string;
  action: string;
  details: Record<string, unknown>;
  result: 'success' | 'failure';
  errorCode?: string;
}

function logAudit(log: AuditLog) {
  // Send to secure logging system
  auditLogger.info(log);

  // Store for compliance
  auditStore.insert(log);
}

// A tool handler receives (name, args). Who the script runs for comes from your own code.
function createAuditedEnclave(userId: string, sessionId: string) {
  return new Enclave({
    toolHandler: async (name, args) => {
      const start = Date.now();
      let error: Error | undefined;

      try {
        return await executeTool(name, args);
      } catch (e) {
        error = e as Error;
        throw e;
      } finally {
        logAudit({
          timestamp: new Date().toISOString(),
          userId,
          sessionId,
          action: `tool:${name}`,
          details: {
            args: sanitizeForLog(args),
            duration: Date.now() - start,
          },
          result: error ? 'failure' : 'success',
          errorCode: error?.message,
        });
      }
    },
  });
}
```

### Log Retention

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Configure log retention
const logConfig = {
  // Keep detailed logs for 30 days
  detailedRetention: 30,

  // Keep summary logs for 1 year
  summaryRetention: 365,

  // Archive to cold storage after 90 days
  archiveAfter: 90,
};
```

## Container Security

### Dockerfile Best Practices

```dockerfile theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
# Use specific version
FROM node:22-slim

# Run as non-root
RUN useradd -m -u 1001 enclave

# Set secure permissions
WORKDIR /app
COPY --chown=enclave:enclave . .

# Remove unnecessary packages
RUN apt-get purge -y --auto-remove \
  && rm -rf /var/lib/apt/lists/*

# Drop all capabilities
USER enclave

# Read-only filesystem
VOLUME ["/tmp"]

# Health check
HEALTHCHECK --interval=30s CMD curl -f http://localhost:3000/health || exit 1

EXPOSE 3000
CMD ["node", "--no-warnings", "dist/server.js"]
```

### Security Context

```yaml theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
# k8s/deployment.yaml
spec:
  containers:
    - name: enclave
      securityContext:
        runAsNonRoot: true
        runAsUser: 1001
        readOnlyRootFilesystem: true
        allowPrivilegeEscalation: false
        capabilities:
          drop:
            - ALL
```

## Secrets Management

### Environment Variables

Never hardcode secrets:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Bad
const apiKey = 'sk-1234567890';

// Good
const apiKey = process.env.API_KEY;
if (!apiKey) {
  throw new Error('API_KEY not configured');
}
```

### Kubernetes Secrets

```yaml theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
apiVersion: v1
kind: Secret
metadata:
  name: enclave-secrets
type: Opaque
data:
  api-key: base64-encoded-value
  redis-url: base64-encoded-value
```

```yaml theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
# deployment.yaml
env:
  - name: API_KEY
    valueFrom:
      secretKeyRef:
        name: enclave-secrets
        key: api-key
```

## Incident Response

### Detection

Monitor for anomalies:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Alert on unusual patterns
const alerts = {
  highErrorRate: (rate: number) => rate > 0.1, // >10% error rate
  unusualToolUsage: (count: number) => count > 1000, // >1000 calls/min
  memorySpike: (mb: number) => mb > 500, // >500MB
  longExecution: (ms: number) => ms > 60000, // >60s
};
```

### Response Plan

1. **Detect** - Automated monitoring alerts
2. **Contain** - Isolate affected components
3. **Investigate** - Review audit logs
4. **Remediate** - Fix vulnerability
5. **Recover** - Restore normal operation
6. **Learn** - Post-incident review

## Related

* [Security Model](https://docs.agentfront.dev/enclave/concepts/security-model.md) - Architecture overview
* [AI Scoring](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/ai-scoring.md) - Semantic analysis
* [Production Deployment](https://docs.agentfront.dev/enclave/guides/production-deployment.md) - Deployment guide


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