API reference

Complete reference for all SDK methods and types.


createSecurityLayer()

Creates and returns a SecurityLayer instance. This is the main entry point for the SDK.

import { createSecurityLayer } from "@securitylayerai/sdk";

const sl = await createSecurityLayer(options?: SecurityLayerOptions);

Options

OptionTypeDefaultDescription
configDirstring~/.securitylayerPath to Security Layer configuration directory
sessionIdstringAuto-generated UUIDDefault session ID for checks
configLoadedConfigPre-loaded config object (skips file loading, useful for testing)
eventBusEventBusAuto-createdInjected event bus (useful for testing or sharing events)

Throws: ConfigError if config files can't be loaded, InitializationError if the security pipeline fails to initialize.


SecurityLayer

The object returned by createSecurityLayer(). Provides all security checking, taint tracking, and event handling methods.

check()

Evaluate an action through the security pipeline before execution.

const result = await sl.check(
  tool: string,
  params: Record<string, unknown>,
  context?: ExecutionContext,
): Promise<CheckResult>;

Parameters:

ParameterTypeDescription
toolstringThe capability being used: "exec", "file.read", "file.write", "web_fetch", etc.
paramsobjectTool-specific parameters. For exec, the command is extracted from command, cmd, or input properties.
contextExecutionContextOptional context overrides for this check

Returns: Promise<CheckResult>

waitForApproval()

Block until a human approves or denies a REQUIRE_APPROVAL decision.

const approved = await sl.waitForApproval(
  approvalId: string,
  options?: ApprovalOptions,
): Promise<boolean>;

Parameters:

ParameterTypeDescription
approvalIdstringThe approval ID from a REQUIRE_APPROVAL check result
options.timeoutnumberTimeout in milliseconds (default: 300000 / 5 minutes)

Returns: true if approved, false if denied, timed out, or approvalId is unknown.

ingestContent()

Update the taint tracker when external content enters the session.

sl.ingestContent(
  content: string,
  metadata: ContentMetadata,
): void;

Parameters:

ParameterTypeDescription
contentstringThe content that was read or fetched
metadata.source"web" | "file" | "channel" | "skill" | "memory"Where the content came from
metadata.pathstring?File path, skill name, or channel identifier
metadata.urlstring?URL (for web sources)

Source-to-taint mapping:

SourceTaint Level
webWEB
fileUNTRUSTED
channelUNTRUSTED
skillSKILL
memoryMEMORY

scanEgress()

Scan outbound content for leaked secrets, PII, and sensitive data before sending.

const result = sl.scanEgress(content: string): EgressScanResult;

Returns: EgressScanResult with clean: boolean and findings: EgressFinding[].

getSessionTaint()

Get the current session's effective taint level.

const taint = sl.getSessionTaint(): string;

Returns: One of "owner", "trusted", "untrusted", "web", "skill", "memory".

on()

Subscribe to security events from the internal event bus.

const unsubscribe = sl.on(type: string, handler: (event) => void): () => void;

Parameters:

ParameterTypeDescription
typestringEvent type to listen for (e.g., "action.evaluated", "taint.elevated", "approval.requested")
handlerfunctionCallback invoked when the event fires

Returns: An unsubscribe function. Call it to stop receiving events.

destroy()

Clean up resources. Resolves all pending approval requests as timed-out and clears all event handlers.

sl.destroy(): void;

Always call destroy() when you're done with the SecurityLayer instance.


withSecurityLayer()

Middleware wrapper that adds security checks to any function. Intercepts calls transparently — the wrapped function has the same signature as the original.

import { createSecurityLayer, withSecurityLayer } from "@securitylayerai/sdk";

const sl = await createSecurityLayer();

const protectedExec = withSecurityLayer(sl, originalExecFn, "exec");
const protectedRead = withSecurityLayer(sl, originalReadFn, "file.read");

Signature:

function withSecurityLayer<TArgs extends unknown[], TReturn>(
  sl: SecurityLayer,
  fn: (...args: TArgs) => TReturn | Promise<TReturn>,
  tool: string,
  options?: {
    extractParams?: (...args: unknown[]) => Record<string, unknown>;
  },
): (...args: TArgs) => Promise<TReturn>;

Behavior:

  • ALLOW → calls the original function and returns its result
  • DENY → throws SecurityLayerError without calling the function
  • REQUIRE_APPROVAL → waits for approval, throws if denied

Default parameter extraction: If the first argument is a string, it's mapped to { command: arg }. If it's an object, it's used directly as params.


Error classes

All SDK errors extend SecurityLayerError, which extends Error.

import {
  SecurityLayerError,
  ConfigError,
  InitializationError,
  CheckError,
  ApprovalTimeoutError,
} from "@securitylayerai/sdk";
ErrorPropertiesThrown when
SecurityLayerErrormessageBase class; also thrown by withSecurityLayer() on DENY
ConfigErrorconfigPath?: stringConfig files can't be loaded or parsed
InitializationErrorcause?: unknownSecurity pipeline fails to initialize
CheckErrortool?: stringAction evaluation fails unexpectedly
ApprovalTimeoutErrorapprovalId: stringApproval request times out

Types

CheckResult

interface CheckResult {
  decision: "ALLOW" | "DENY" | "REQUIRE_APPROVAL";
  reason: string;
  approvalId?: string;
  layers: LayerResults;
  degraded: boolean;
  timing: {
    total: number;
    capability?: number;
    rules?: number;
    llm?: number;
  };
}

LayerResults

interface LayerResults {
  capability: {
    allowed: boolean;
    reason?: string;
  };
  rules?: {
    decision: string;
    reason?: string;
  };
  llm?: {
    decision: string;
    confidence: number;
    reasoning?: string;
  };
}

EgressScanResult

interface EgressScanResult {
  clean: boolean;
  findings: EgressFinding[];
}

interface EgressFinding {
  type:
    | "api_key"
    | "pem_block"
    | "private_key"
    | "password"
    | "high_entropy"
    | "pii"
    | "credential_pattern";
  confidence: number;
  location: { start: number; end: number };
  redacted: string;
}

ExecutionContext

interface ExecutionContext {
  sessionId?: string;
  skillId?: string;
  channelId?: string;
}

ContentMetadata

interface ContentMetadata {
  source: "web" | "file" | "channel" | "skill" | "memory";
  path?: string;
  url?: string;
}

SecurityLayerOptions

interface SecurityLayerOptions {
  configDir?: string;
  sessionId?: string;
  config?: LoadedConfig;
  eventBus?: EventBus;
}

ApprovalOptions

interface ApprovalOptions {
  timeout?: number; // milliseconds, default 300000 (5 min)
}

See also

On this page