Skip to main content
import {
  createSecurityPolicy,
  createPIIConfig,
  PIIType,
  RedactionAction,
  createInjectionDefenseConfig,
  InjectionSensitivity,
  InjectionAction,
  createNetworkPolicy,
  createTransformationRule,
  TransformDirection,
  createAuditConfig,
  createEnvSecurityConfig,
  createToxicityConfig,
  createCodeSecurityConfig,
  createInvisibleTextConfig,
  ALL_TRAFFIC,
} from '@declaw/sdk';
import type {
  SecurityPolicy,
  PIIConfig,
  InjectionDefenseConfig,
  NetworkPolicy,
  TransformationRule,
  AuditConfig,
  AuditEntry,
  EnvSecurityConfig,
  SecureEnvVar,
  ToxicityConfig,
  CodeSecurityConfig,
  InvisibleTextConfig,
} 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.
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',
});
opts.pii
PIIConfig
default:"createPIIConfig()"
PII detection config. See PIIConfig.
opts.injectionDefense
boolean | InjectionDefenseConfig
default:"false"
Injection defense. Pass true for defaults, or an InjectionDefenseConfig for custom settings.
opts.transformations
TransformationRule[]
default:"[]"
Regex transformation rules.
opts.network
NetworkPolicy
Network allowlist/denylist. See NetworkPolicy.
opts.audit
boolean | AuditConfig
default:"false"
Audit logging. Pass true for defaults.
opts.envSecurity
EnvSecurityConfig
default:"createEnvSecurityConfig()"
Environment variable masking config.
opts.toxicity
ToxicityConfig
Toxicity detection on outbound HTTP bodies. See ToxicityConfig.
opts.codeSecurity
CodeSecurityConfig
Code security scanner on outbound HTTP bodies. See CodeSecurityConfig.
opts.invisibleText
InvisibleTextConfig
Invisible-unicode detection on outbound HTTP bodies. See InvisibleTextConfig.
Returns SecurityPolicy

SecurityPolicy interface

interface SecurityPolicy {
  pii: PIIConfig;
  injectionDefense: boolean | InjectionDefenseConfig;
  transformations: TransformationRule[];
  network?: NetworkPolicy;
  audit: boolean | AuditConfig;
  envSecurity: EnvSecurityConfig;
  toxicity?: ToxicityConfig;
  codeSecurity?: CodeSecurityConfig;
  invisibleText?: InvisibleTextConfig;
}

Helper functions

FunctionDescription
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.
import { createPIIConfig, PIIType, RedactionAction } from '@declaw/sdk';

const pii = createPIIConfig({
  enabled: true,
  types: [PIIType.Email, PIIType.CreditCard, PIIType.SSN],
  action: RedactionAction.Redact,
  rehydrateResponse: false,
});
opts.enabled
boolean
default:"false"
Whether PII scanning is active.
opts.types
string[]
default:"all PIIType values"
PII types to scan for. Accepts PIIType enum values or their string equivalents.
opts.action
string
default:"RedactionAction.Redact"
Action to take when PII is detected. One of RedactionAction.Redact, RedactionAction.Block, RedactionAction.LogOnly.
opts.rehydrateResponse
boolean
default:"true"
When true, replace redaction tokens in API responses with original values.

PIIType enum

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

RedactionAction enum

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

interface PIIConfig {
  enabled: boolean;
  types: string[];
  action: string;
  rehydrateResponse: boolean;
}

createInjectionDefenseConfig()

Configure prompt injection detection on outbound HTTP request bodies.
import { createInjectionDefenseConfig, InjectionSensitivity, InjectionAction } from '@declaw/sdk';

const injection = createInjectionDefenseConfig({
  enabled: true,
  sensitivity: InjectionSensitivity.High,
  action: InjectionAction.Block,
});
opts.enabled
boolean
default:"false"
Whether injection defense is active.
opts.sensitivity
string
default:"InjectionSensitivity.Medium"
Sensitivity level. One of InjectionSensitivity.Low, Medium, High. Higher sensitivity catches more patterns but may produce false positives.
opts.action
string
default:"InjectionAction.Sanitize"
Action when injection is detected. One of InjectionAction.Block, InjectionAction.Sanitize, InjectionAction.LogOnly.
opts.threshold
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.
opts.domains
string[]
Optional domain allowlist. When omitted, injection defense applies to all outbound destinations.

InjectionSensitivity enum

enum InjectionSensitivity {
  Low    = 'low',
  Medium = 'medium',
  High   = 'high',
}

InjectionAction enum

enum InjectionAction {
  Block    = 'block',     // Reject the request (HTTP 403)
  Sanitize = 'sanitize',  // Strip the injection attempt and forward
  LogOnly  = 'log_only',  // Log and forward unchanged
}

InjectionDefenseConfig interface

interface InjectionDefenseConfig {
  enabled: boolean;
  sensitivity: string;
  action: string;
  threshold: number;
  domains?: string[];
}
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.

createNetworkPolicy()

Define which outbound connections the sandbox is allowed to make.
import { createNetworkPolicy, ALL_TRAFFIC } from '@declaw/sdk';

const network = createNetworkPolicy({
  allowOut: ['api.openai.com', 'pypi.org', '*.github.com'],
  denyOut: [ALL_TRAFFIC],
  allowPublicTraffic: false,
});
opts.allowOut
string[]
default:"[]"
Destinations to allow. Accepts IP addresses, CIDR blocks, and domain names with optional *. wildcard prefix.
opts.denyOut
string[]
default:"[]"
Destinations to deny. Accepts IP addresses and CIDR blocks.
opts.allowPublicTraffic
boolean
default:"true"
Whether all public traffic is allowed by default. Set to false when using allowOut as an allowlist.
opts.maskRequestHost
string
Replace the Host header in all outbound requests with this value.

ALL_TRAFFIC constant

const ALL_TRAFFIC: string = '0.0.0.0/0';

NetworkPolicy interface

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.
import { createTransformationRule, TransformDirection } from '@declaw/sdk';

const rule = createTransformationRule({
  match: 'Bearer [A-Za-z0-9\\-_\\.]+',
  replace: 'Bearer [REDACTED]',
  direction: TransformDirection.Outbound,
});
opts.match
string
required
Valid JavaScript regex pattern (max 1000 characters). Must not contain nested quantifiers.
opts.replace
string
required
Replacement string. Supports regex back-references (e.g. $1).
opts.direction
string
default:"TransformDirection.Both"
Direction to apply the rule. One of 'outbound', 'inbound', 'both'.

TransformDirection enum

enum TransformDirection {
  Outbound = 'outbound',
  Inbound  = 'inbound',
  Both     = 'both',
}

TransformationRule interface

interface TransformationRule {
  match: string;
  replace: string;
  direction: string;
}

createAuditConfig()

Control what the MITM proxy logs for security events.
import { createAuditConfig } from '@declaw/sdk';

const audit = createAuditConfig({
  enabled: true,
  logRequestBody: true,
  logResponseBody: false,
  retentionHours: 168, // 1 week
});
opts.enabled
boolean
default:"false"
Whether audit logging is active.
opts.logRequestBody
boolean
default:"true"
Whether to include request bodies in audit log entries.
opts.logResponseBody
boolean
default:"false"
Whether to include response bodies in audit log entries.
opts.retentionHours
number
default:"24"
How many hours to retain log entries.

AuditConfig interface

interface AuditConfig {
  enabled: boolean;
  logRequestBody: boolean;
  logResponseBody: boolean;
  retentionHours: number;
}

AuditEntry interface

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.
import { createEnvSecurityConfig, DEFAULT_MASK_PATTERNS } from '@declaw/sdk';

const envSec = createEnvSecurityConfig({
  maskPatterns: [...DEFAULT_MASK_PATTERNS, '*_PRIVATE_*'],
  autoMaskInAudit: true,
});
opts.maskPatterns
string[]
default:"DEFAULT_MASK_PATTERNS"
Glob patterns matched against uppercase variable names. Default: ['*_KEY', '*_SECRET', '*_TOKEN', '*_PASSWORD', '*_CREDENTIALS', 'API_KEY', 'SECRET_KEY'].
opts.autoMaskInAudit
boolean
default:"true"
Automatically redact matching variable values in audit logs.

EnvSecurityConfig interface

interface EnvSecurityConfig {
  maskPatterns: string[];
  autoMaskInAudit: boolean;
}

SecureEnvVar interface

interface SecureEnvVar {
  key: string;
  value: string;
  secret: boolean;
}

createToxicityConfig()

Configure toxicity detection on outbound HTTP request bodies.
import { createToxicityConfig } from '@declaw/sdk';

const toxicity = createToxicityConfig({
  enabled: true,
  threshold: 0.9,
  action: 'block',
});
opts.enabled
boolean
default:"false"
Whether toxicity detection is active.
opts.threshold
number
default:"0.9"
Detection threshold in 0.0–1.0. Higher values fire only on more confident detections.
opts.action
'block' | 'log_only'
default:"'block'"
Action when toxicity is detected.
opts.domains
string[]
Optional domain allowlist. When omitted, applies to all outbound destinations.

ToxicityConfig interface

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

createCodeSecurityConfig()

Configure the code-security scanner for outbound HTTP request bodies.
import { createCodeSecurityConfig } from '@declaw/sdk';

const codeSec = createCodeSecurityConfig({
  enabled: true,
  threshold: 0.6,
  excludedLanguages: ['markdown'],
  action: 'log_only',
});
opts.enabled
boolean
default:"false"
Whether code-security scanning is active.
opts.threshold
number
default:"0.6"
Detection threshold in 0.0–1.0.
opts.excludedLanguages
string[]
Languages to skip. When omitted, all detected languages are scanned.
opts.action
'block' | 'log_only'
default:"'log_only'"
Action when a security issue is detected.
opts.domains
string[]
Optional domain allowlist. When omitted, applies to all outbound destinations.

CodeSecurityConfig interface

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.
import { createInvisibleTextConfig } from '@declaw/sdk';

const invisible = createInvisibleTextConfig({
  enabled: true,
  action: 'strip',
});
opts.enabled
boolean
default:"false"
Whether invisible-text detection is active.
opts.action
'block' | 'strip' | 'log_only'
default:"'strip'"
Action when invisible characters are detected.
opts.domains
string[]
Optional domain allowlist. When omitted, applies to all outbound destinations.

InvisibleTextConfig interface

interface InvisibleTextConfig {
  enabled: boolean;
  action: 'block' | 'strip' | 'log_only';
  domains?: string[];
}

Full policy example

import {
  Sandbox,
  createSecurityPolicy,
  createPIIConfig,
  PIIType,
  RedactionAction,
  createInjectionDefenseConfig,
  InjectionSensitivity,
  InjectionAction,
  createNetworkPolicy,
  createTransformationRule,
  TransformDirection,
  createAuditConfig,
  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,
    }),
  ],
  audit: createAuditConfig({ enabled: true, logRequestBody: true }),
});

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