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

# Security Policy

> SecurityPolicy type, createSecurityPolicy(), PIIConfig, InjectionDefenseConfig, NetworkPolicy, TransformationRule, AuditConfig, and EnvSecurityConfig for the TypeScript SDK.

```typescript theme={null}
import {
  createSecurityPolicy,
  createPIIConfig,
  PIIType,
  RedactionAction,
  createInjectionDefenseConfig,
  InjectionSensitivity,
  InjectionAction,
  createNetworkPolicy,
  createTransformationRule,
  TransformDirection,
  createAuditConfig,
  createEnvSecurityConfig,
  createToxicityConfig,
  createCodeSecurityConfig,
  createInvisibleTextConfig,
  createContentGateConfig,
  ALL_TRAFFIC,
} from '@declaw/sdk';
import type {
  SecurityPolicy,
  PIIConfig,
  InjectionDefenseConfig,
  NetworkPolicy,
  TransformationRule,
  AuditConfig,
  AuditEntry,
  EnvSecurityConfig,
  SecureEnvVar,
  ToxicityConfig,
  CodeSecurityConfig,
  InvisibleTextConfig,
  ContentGateConfig,
} from '@declaw/sdk';
```

A `SecurityPolicy` is passed to `Sandbox.create()` via the `security` option. It composes PII detection, injection defense, network policy, transformation rules, audit logging, and environment variable security.

## `createSecurityPolicy()`

Factory function for building a `SecurityPolicy` with defaults.

```typescript theme={null}
import { createSecurityPolicy, createPIIConfig, createInjectionDefenseConfig } from '@declaw/sdk';

const policy = createSecurityPolicy({
  pii: createPIIConfig({ enabled: true, action: 'redact' }),
  injectionDefense: createInjectionDefenseConfig({ enabled: true, action: 'block' }),
  audit: true,
});

const sbx = await Sandbox.create({
  security: policy,
  apiKey: 'key',
  domain: 'host:8080',
});
```

<ParamField body="opts.pii" type="PIIConfig" default="createPIIConfig()">
  PII detection config. See [PIIConfig](#piiconfig).
</ParamField>

<ParamField body="opts.injectionDefense" type="boolean | InjectionDefenseConfig" default="false">
  Injection defense. Pass `true` for defaults, or an `InjectionDefenseConfig`
  for custom settings.
</ParamField>

<ParamField body="opts.transformations" type="TransformationRule[]" default="[]">
  Regex transformation rules.
</ParamField>

<ParamField body="opts.network" type="NetworkPolicy">
  Network allowlist/denylist. See [NetworkPolicy](#networkpolicy).
</ParamField>

<ParamField body="opts.audit" type="boolean | AuditConfig" default="false">
  Audit logging. Pass `true` for defaults.
</ParamField>

<ParamField body="opts.envSecurity" type="EnvSecurityConfig" default="createEnvSecurityConfig()">
  Environment variable masking config.
</ParamField>

<ParamField body="opts.toxicity" type="ToxicityConfig">
  Toxicity detection on outbound HTTP bodies. See [ToxicityConfig](#toxicityconfig).
</ParamField>

<ParamField body="opts.codeSecurity" type="CodeSecurityConfig">
  Code security scanner on outbound HTTP bodies. See [CodeSecurityConfig](#codesecurityconfig).
</ParamField>

<ParamField body="opts.invisibleText" type="InvisibleTextConfig">
  Invisible-unicode detection on outbound HTTP bodies. See [InvisibleTextConfig](#invisibletextconfig).
</ParamField>

<ParamField body="opts.customPolicy" type="CustomPolicyConfig">
  Attach OPA/Rego policy — a built-in governance pack via `policyRef`, or your
  own rules via `inlineRego`/`inlineModules`. See [CustomPolicyConfig](#custompolicyconfig).
</ParamField>

<ParamField body="opts.contentGate" type="ContentGateConfig">
  Run the `content.scan` OPA gate (e.g. an LLM model allowlist / cross-signal
  rules) on the listed domains. See [ContentGateConfig](#contentgateconfig).
</ParamField>

**Returns** `SecurityPolicy`

### `SecurityPolicy` interface

```typescript theme={null}
interface SecurityPolicy {
  pii: PIIConfig;
  injectionDefense: boolean | InjectionDefenseConfig;
  transformations: TransformationRule[];
  network?: NetworkPolicy;
  audit: boolean | AuditConfig;
  envSecurity: EnvSecurityConfig;
  toxicity?: ToxicityConfig;
  codeSecurity?: CodeSecurityConfig;
  invisibleText?: InvisibleTextConfig;
  customPolicy?: CustomPolicyConfig;
  contentGate?: ContentGateConfig;
}
```

### Helper functions

| Function                          | Description                                                         |
| --------------------------------- | ------------------------------------------------------------------- |
| `parseSecurityPolicy(data)`       | Deserialize a policy from raw JSON.                                 |
| `securityPolicyToJSON(policy)`    | Serialize a policy to a JSON-friendly object.                       |
| `requiresTlsInterception(policy)` | Returns `true` if PII, injection defense, or transforms are active. |

***

## `createPIIConfig()`

Configure PII detection and redaction on outbound HTTP traffic.

```typescript theme={null}
import { createPIIConfig, PIIType, RedactionAction } from '@declaw/sdk';

const pii = createPIIConfig({
  enabled: true,
  types: [PIIType.Email, PIIType.CreditCard, PIIType.SSN],
  action: RedactionAction.Redact,
  rehydrateResponse: false,
});
```

<ParamField body="opts.enabled" type="boolean" default="false">
  Whether PII scanning is active.
</ParamField>

<ParamField body="opts.types" type="string[]" default="all PIIType values">
  PII types to scan for. Accepts `PIIType` enum values or their string
  equivalents.
</ParamField>

<ParamField body="opts.action" type="string" default="RedactionAction.Redact">
  Action to take when PII is detected. One of `RedactionAction.Redact`,
  `RedactionAction.Block`, `RedactionAction.LogOnly`.
</ParamField>

<ParamField body="opts.rehydrateResponse" type="boolean" default="true">
  When `true`, replace redaction tokens in API responses with original values.
</ParamField>

### `PIIType` enum

```typescript theme={null}
enum PIIType {
  SSN         = 'ssn',
  CreditCard  = 'credit_card',
  Email       = 'email',
  Phone       = 'phone',
  PersonName  = 'person_name',
  APIKey      = 'api_key',
  Address     = 'address',
  IPAddress   = 'ip_address',
}
```

### `RedactionAction` enum

```typescript theme={null}
enum RedactionAction {
  Redact  = 'redact',    // Replace with a placeholder token
  Block   = 'block',     // Reject the request (HTTP 403)
  LogOnly = 'log_only',  // Log but forward unchanged
}
```

### `PIIConfig` interface

```typescript theme={null}
interface PIIConfig {
  enabled: boolean;
  types: string[];
  action: string;
  rehydrateResponse: boolean;
}
```

***

## `createInjectionDefenseConfig()`

Configure prompt injection detection on outbound HTTP request bodies.

```typescript theme={null}
import { createInjectionDefenseConfig, InjectionSensitivity, InjectionAction } from '@declaw/sdk';

const injection = createInjectionDefenseConfig({
  enabled: true,
  sensitivity: InjectionSensitivity.High,
  action: InjectionAction.Block,
});
```

<ParamField body="opts.enabled" type="boolean" default="false">
  Whether injection defense is active.
</ParamField>

<ParamField body="opts.sensitivity" type="string" default="InjectionSensitivity.Medium">
  Sensitivity level. One of `InjectionSensitivity.Low`, `Medium`, `High`.
  Higher sensitivity catches more patterns but may produce false positives.
</ParamField>

<ParamField body="opts.action" type="string" default="InjectionAction.LogOnly">
  Action when injection is detected. One of `InjectionAction.Block` or
  `InjectionAction.LogOnly`.
</ParamField>

<ParamField body="opts.threshold" type="number" default="0.8">
  Detection threshold (0.0–1.0). Sent to the API alongside `sensitivity` so
  the SDK wire format matches the Python SDK's numeric-threshold form.
</ParamField>

<ParamField body="opts.domains" type="string[]">
  Optional domain allowlist. When omitted, injection defense applies to all
  outbound destinations.
</ParamField>

### `InjectionSensitivity` enum

```typescript theme={null}
enum InjectionSensitivity {
  Low    = 'low',
  Medium = 'medium',
  High   = 'high',
}
```

### `InjectionAction` enum

```typescript theme={null}
enum InjectionAction {
  Block    = 'block',     // Reject the request (HTTP 403)
  LogOnly  = 'log_only',  // Log and forward unchanged
}
```

### `InjectionDefenseConfig` interface

```typescript theme={null}
interface InjectionDefenseConfig {
  enabled: boolean;
  sensitivity: string;
  action: string;
  threshold: number;
  domains?: string[];
}
```

<Note>
  The TypeScript SDK uses `sensitivity` (low/medium/high) for injection
  thresholds. The Python SDK uses a numeric `threshold` (0.0–1.0). The API
  accepts both representations.
</Note>

***

## `createNetworkPolicy()`

Define which outbound connections the sandbox is allowed to make.

```typescript theme={null}
import { createNetworkPolicy, ALL_TRAFFIC } from '@declaw/sdk';

const network = createNetworkPolicy({
  allowOut: ['api.openai.com', 'pypi.org', '*.github.com'],
  denyOut: [ALL_TRAFFIC],
  allowPublicTraffic: false,
});
```

<ParamField body="opts.allowOut" type="string[]" default="[]">
  Destinations to allow. Accepts IP addresses, CIDR blocks, and domain names
  with optional `*.` wildcard prefix.
</ParamField>

<ParamField body="opts.denyOut" type="string[]" default="[]">
  Destinations to deny. Accepts IP addresses and CIDR blocks.
</ParamField>

<ParamField body="opts.allowPublicTraffic" type="boolean" default="true">
  Whether all public traffic is allowed by default. Set to `false` when
  using `allowOut` as an allowlist.
</ParamField>

<ParamField body="opts.maskRequestHost" type="string">
  Replace the `Host` header in all outbound requests with this value.
</ParamField>

### `ALL_TRAFFIC` constant

```typescript theme={null}
const ALL_TRAFFIC: string = '0.0.0.0/0';
```

### `NetworkPolicy` interface

```typescript theme={null}
interface NetworkPolicy {
  allowOut: string[];
  denyOut: string[];
  allowPublicTraffic: boolean;
  maskRequestHost?: string;
}
```

***

## `createTransformationRule()`

Create a regex-based transformation rule with validation. The factory checks for ReDoS-vulnerable patterns (nested quantifiers) and validates the regex syntax before returning the rule.

```typescript theme={null}
import { createTransformationRule, TransformDirection } from '@declaw/sdk';

const rule = createTransformationRule({
  match: 'Bearer [A-Za-z0-9\\-_\\.]+',
  replace: 'Bearer [REDACTED]',
  direction: TransformDirection.Outbound,
});
```

<ParamField body="opts.match" type="string" required>
  Valid JavaScript regex pattern (max 1000 characters). Must not contain
  nested quantifiers.
</ParamField>

<ParamField body="opts.replace" type="string" required>
  Replacement string. Supports regex back-references (e.g. `$1`).
</ParamField>

<ParamField body="opts.direction" type="string" default="TransformDirection.Both">
  Direction to apply the rule. One of `'outbound'`, `'inbound'`, `'both'`.
</ParamField>

### `TransformDirection` enum

```typescript theme={null}
enum TransformDirection {
  Outbound = 'outbound',
  Inbound  = 'inbound',
  Both     = 'both',
}
```

### `TransformationRule` interface

```typescript theme={null}
interface TransformationRule {
  match: string;
  replace: string;
  direction: string;
}
```

***

## `createAuditConfig()`

Toggle whether lifecycle and security events for the sandbox are shipped
to Declaw's audit log.

```typescript theme={null}
import { createAuditConfig } from '@declaw/sdk';

// Opt out of audit logging for this sandbox
const audit = createAuditConfig({ enabled: false });
```

<ParamField body="opts.enabled" type="boolean" default="true">
  When `true` (the default), the orchestrator records the sandbox's
  lifecycle events (create, kill, pause, resume, snapshot) and security
  decisions (egress allow/block) to the audit log. Set to `false` to
  suppress all audit events for the sandbox.
</ParamField>

Audit log retention is a platform-wide setting (currently a 7-day
rolling window) and is not configurable per sandbox. Request and
response body logging is not exposed to callers.

### `AuditConfig` interface

```typescript theme={null}
interface AuditConfig {
  enabled: boolean;
}
```

### `AuditEntry` interface

```typescript theme={null}
interface AuditEntry {
  timestamp: Date;
  method: string;
  url: string;
  statusCode: number;
  piiRedactions: number;
  injectionBlocks: number;
  transformationsApplied: number;
  direction: string;
}
```

***

## `createEnvSecurityConfig()`

Control how environment variable values are masked in audit logs.

```typescript theme={null}
import { createEnvSecurityConfig, DEFAULT_MASK_PATTERNS } from '@declaw/sdk';

const envSec = createEnvSecurityConfig({
  maskPatterns: [...DEFAULT_MASK_PATTERNS, '*_PRIVATE_*'],
  autoMaskInAudit: true,
});
```

<ParamField body="opts.maskPatterns" type="string[]" default="DEFAULT_MASK_PATTERNS">
  Glob patterns matched against uppercase variable names. Default:
  `['*_KEY', '*_SECRET', '*_TOKEN', '*_PASSWORD', '*_CREDENTIALS', 'API_KEY', 'SECRET_KEY']`.
</ParamField>

<ParamField body="opts.autoMaskInAudit" type="boolean" default="true">
  Automatically redact matching variable values in audit logs.
</ParamField>

### `EnvSecurityConfig` interface

```typescript theme={null}
interface EnvSecurityConfig {
  maskPatterns: string[];
  autoMaskInAudit: boolean;
}
```

### `SecureEnvVar` interface

```typescript theme={null}
interface SecureEnvVar {
  key: string;
  value: string;
  secret: boolean;
}
```

***

## `createToxicityConfig()`

Configure toxicity detection on outbound HTTP request bodies.

```typescript theme={null}
import { createToxicityConfig } from '@declaw/sdk';

const toxicity = createToxicityConfig({
  enabled: true,
  threshold: 0.9,
  action: 'block',
});
```

<ParamField body="opts.enabled" type="boolean" default="false">
  Whether toxicity detection is active.
</ParamField>

<ParamField body="opts.threshold" type="number" default="0.9">
  Detection threshold in 0.0–1.0. Higher values fire only on more confident
  detections.
</ParamField>

<ParamField body="opts.action" type="'block' | 'log_only'" default="'block'">
  Action when toxicity is detected.
</ParamField>

<ParamField body="opts.domains" type="string[]">
  Optional domain allowlist. When omitted, applies to all outbound destinations.
</ParamField>

### `ToxicityConfig` interface

```typescript theme={null}
interface ToxicityConfig {
  enabled: boolean;
  threshold: number;
  action: 'block' | 'log_only';
  domains?: string[];
}
```

***

## `createCodeSecurityConfig()`

Configure the code-security scanner for outbound HTTP request bodies.

```typescript theme={null}
import { createCodeSecurityConfig } from '@declaw/sdk';

const codeSec = createCodeSecurityConfig({
  enabled: true,
  threshold: 0.6,
  excludedLanguages: ['markdown'],
  action: 'log_only',
});
```

<ParamField body="opts.enabled" type="boolean" default="false">
  Whether code-security scanning is active.
</ParamField>

<ParamField body="opts.threshold" type="number" default="0.6">
  Detection threshold in 0.0–1.0.
</ParamField>

<ParamField body="opts.excludedLanguages" type="string[]">
  Languages to skip. When omitted, all detected languages are scanned.
</ParamField>

<ParamField body="opts.action" type="'block' | 'log_only'" default="'log_only'">
  Action when a security issue is detected.
</ParamField>

<ParamField body="opts.domains" type="string[]">
  Optional domain allowlist. When omitted, applies to all outbound destinations.
</ParamField>

### `CodeSecurityConfig` interface

```typescript theme={null}
interface CodeSecurityConfig {
  enabled: boolean;
  threshold: number;
  excludedLanguages?: string[];
  action: 'block' | 'log_only';
  domains?: string[];
}
```

***

## `createInvisibleTextConfig()`

Detect and handle zero-width or otherwise invisible Unicode characters in
outbound HTTP bodies.

```typescript theme={null}
import { createInvisibleTextConfig } from '@declaw/sdk';

const invisible = createInvisibleTextConfig({
  enabled: true,
  action: 'strip',
});
```

<ParamField body="opts.enabled" type="boolean" default="false">
  Whether invisible-text detection is active.
</ParamField>

<ParamField body="opts.action" type="'block' | 'strip' | 'log_only'" default="'strip'">
  Action when invisible characters are detected.
</ParamField>

<ParamField body="opts.domains" type="string[]">
  Optional domain allowlist. When omitted, applies to all outbound destinations.
</ParamField>

### `InvisibleTextConfig` interface

```typescript theme={null}
interface InvisibleTextConfig {
  enabled: boolean;
  action: 'block' | 'strip' | 'log_only';
  domains?: string[];
}
```

***

## `CustomPolicyConfig`

Attach OPA/Rego policy — a built-in governance pack via `policyRef`, or your
own rules via `inlineRego`/`inlineModules`. Custom rules are evaluated at the
enforcement layer alongside the platform defaults and can only tighten policy,
never relax it. Set it as a plain object on `customPolicy`:

```typescript theme={null}
// Reference a built-in governance pack
const policy = createSecurityPolicy({
  customPolicy: {
    enabled: true,
    policyRef: 'owasp-llm-top10@v1',
    defaultDeny: false,
  },
});

// Or supply your own Rego
const policy = createSecurityPolicy({
  customPolicy: {
    enabled: true,
    inlineRego: `
      deny_command contains msg if {
        input.action.command in {"rm", "dd"}
        msg := "dangerous command blocked"
      }
    `,
  },
});
```

<ParamField body="enabled" type="boolean" default="false">
  Whether custom policy evaluation is active for the sandbox.
</ParamField>

<ParamField body="inlineRego" type="string">
  A single Rego module string appended to the platform defaults. Use this for
  a single-package policy.
</ParamField>

<ParamField body="inlineModules" type="string[]">
  A list of independent Rego module strings, each its own `package`. Use this
  when your policy spans multiple packages; for a single package use
  `inlineRego` instead.
</ParamField>

<ParamField body="policyRef" type="string">
  Reference a published or built-in policy bundle by `name@version` (e.g.
  `owasp-llm-top10@v1`), `sha256:<hex>`, or `blob:<key>`. See
  [Governance Packs](/security/governance-packs) for the catalog.
</ParamField>

<ParamField body="defaultDeny" type="boolean" default="false">
  Fail-closed behavior: when `true`, an evaluator error or unreachable engine
  denies the action. Fail-closed is safer for hard security gates; fail-open
  (`false`) is acceptable for advisory-only scanners.
</ParamField>

### `CustomPolicyConfig` interface

```typescript theme={null}
interface CustomPolicyConfig {
  enabled: boolean;
  inlineRego?: string;
  inlineModules?: string[];
  policyRef?: string;
  defaultDeny?: boolean;
}
```

See [Custom Policy](/security/custom-policy) and
[Governance Packs](/security/governance-packs) for the full guides.

***

## `createContentGateConfig()`

Run the `content.scan` OPA gate (e.g. an LLM model allowlist / cross-signal
rules) on the listed domains. Opts a sandbox into content-gate enforcement
without requiring an ML scanner to be enabled.

```typescript theme={null}
import { createContentGateConfig } from '@declaw/sdk';

const contentGate = createContentGateConfig({
  enabled: true,
  domains: ['api.openai.com', 'api.anthropic.com'],
});
```

<ParamField body="opts.enabled" type="boolean" default="false">
  Whether the content gate is active.
</ParamField>

<ParamField body="opts.domains" type="string[]">
  Opt-in list of destination hosts to intercept. Omitted or empty means no
  hosts are intercepted.
</ParamField>

### `ContentGateConfig` interface

```typescript theme={null}
interface ContentGateConfig {
  enabled: boolean;
  domains?: string[];
}
```

See [Custom Policy](/security/custom-policy) for details.

***

## Full policy example

```typescript theme={null}
import {
  Sandbox,
  createSecurityPolicy,
  createPIIConfig,
  PIIType,
  RedactionAction,
  createInjectionDefenseConfig,
  InjectionSensitivity,
  InjectionAction,
  createNetworkPolicy,
  createTransformationRule,
  TransformDirection,
  createAuditConfig,
  createContentGateConfig,
  ALL_TRAFFIC,
} from '@declaw/sdk';

const policy = createSecurityPolicy({
  pii: createPIIConfig({
    enabled: true,
    types: [PIIType.Email, PIIType.SSN, PIIType.CreditCard],
    action: RedactionAction.Redact,
    rehydrateResponse: true,
  }),
  injectionDefense: createInjectionDefenseConfig({
    enabled: true,
    sensitivity: InjectionSensitivity.High,
    action: InjectionAction.Block,
  }),
  network: createNetworkPolicy({
    allowOut: ['api.openai.com', 'pypi.org'],
    denyOut: [ALL_TRAFFIC],
    allowPublicTraffic: false,
  }),
  transformations: [
    createTransformationRule({
      match: 'sk-[A-Za-z0-9]+',
      replace: 'sk-[REDACTED]',
      direction: TransformDirection.Outbound,
    }),
  ],
  customPolicy: {
    enabled: true,
    policyRef: 'owasp-llm-top10@v1',
  },
  contentGate: createContentGateConfig({
    enabled: true,
    domains: ['api.openai.com'],
  }),
  audit: createAuditConfig({ enabled: true }),
});

const sbx = await Sandbox.create({
  security: policy,
  apiKey: 'your-api-key',
  domain: '104.198.24.180:8080',
});
```
