npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kb-labs/core-sandbox

v1.2.0

Published

Universal sandbox isolation for CLI and REST API

Readme

@kb-labs/sandbox

Universal sandbox isolation system for executing untrusted code in KB Labs ecosystem. Provides secure execution environment with resource limits, monitoring, and isolation for CLI and REST API handlers.

License: MIT Node.js pnpm

🎯 Vision & Purpose

@kb-labs/sandbox provides universal sandbox isolation system for executing untrusted code in KB Labs ecosystem. It supports both fork-based isolation (subprocess) and in-process execution modes, with resource limits, monitoring, and comprehensive security controls.

🏗️ Architecture

Core Components

Sandbox Runner

  • Purpose: Execute code in isolated environment
  • Responsibilities: Resource management, security enforcement, monitoring
  • Dependencies: None (pure Node.js)

Execution Modes

  • Subprocess Mode: Fork-based isolation with resource limits
  • In-Process Mode: Fast execution for development (no isolation)

Monitoring System

  • Purpose: Collect execution data
  • Responsibilities: Log collection, metrics tracking, trace collection
  • Dependencies: None

Design Patterns

  • Strategy Pattern: Different execution strategies (subprocess/in-process)
  • Factory Pattern: Sandbox runner creation
  • Observer Pattern: Lifecycle hooks

Data Flow

createSandboxRunner(config)
    │
    ├──► Create runner (subprocess or in-process)
    ├──► Configure resource limits
    ├──► Setup security controls
    ├──► Initialize monitoring
    └──► return SandboxRunner

sandbox.run(handler, input, context)
    │
    ├──► Validate preflight checks
    ├──► Setup resource limits
    ├──► Execute handler
    ├──► Collect logs/metrics/traces
    ├──► Enforce timeout
    └──► return ExecutionResult

🚀 Quick Start

Installation

pnpm add @kb-labs/sandbox

Basic Usage

import { createSandboxRunner } from '@kb-labs/sandbox';

const sandbox = createSandboxRunner({
  execution: {
    timeoutMs: 30000,
    memoryMb: 512,
  },
  mode: 'subprocess',
});

const result = await sandbox.run(
  { file: './handler.js', export: 'handle' },
  { message: 'Hello' },
  { /* context */ }
);

✨ Features

  • Fork-based isolation - Subprocess execution with resource limits
  • In-process mode - Fast execution for development (no isolation)
  • Resource limits - Memory, CPU, and timeout enforcement
  • Log collection - Ring buffer for capturing stdout/stderr
  • Metrics tracking - CPU, memory, and execution time
  • Distributed tracing - Support for trace propagation

Installation

pnpm add @kb-labs/sandbox

Usage

Basic Example

import { createSandboxRunner } from '@kb-labs/sandbox';

const sandbox = createSandboxRunner({
  execution: {
    timeoutMs: 30000,
    graceMs: 5000,
    memoryMb: 512,
  },
  permissions: {
    env: { allow: ['NODE_ENV', 'PATH'] },
    filesystem: { allow: [], deny: [], readOnly: false },
    network: { allow: [], deny: [] },
    capabilities: [],
  },
  monitoring: {
    collectLogs: true,
    collectMetrics: true,
    collectTraces: false,
    logBufferSizeMb: 1,
  },
  mode: 'subprocess',
});

const result = await sandbox.run(
  { file: './handler.js', export: 'handle' },
  { message: 'Hello' },
  {
    requestId: 'req-123',
    workdir: process.cwd(),
    debug: false,
  }
);

if (result.ok) {
  console.log('Success:', result.data);
  console.log('Metrics:', result.metrics);
} else {
  console.error('Error:', result.error);
}

Configuration

Execution Limits

execution: {
  timeoutMs: 30000,     // Max execution time
  graceMs: 5000,        // SIGTERM → SIGKILL grace period
  memoryMb: 512,        // Memory limit
}

Permissions

permissions: {
  env: {
    allow: ['NODE_ENV', 'PATH', 'HOME']  // Whitelisted env vars
  },
  filesystem: {
    allow: ['/tmp', '/app/data'],        // Allowed paths
    deny: ['/etc', '/root'],             // Denied paths
    readOnly: false                      // Read-only mode
  },
  network: {
    allow: ['example.com'],              // Allowed domains
    deny: ['internal.corp']              // Denied domains
  },
  capabilities: ['fs:read', 'net:fetch'] // Custom capabilities
}

Monitoring

monitoring: {
  collectLogs: true,         // Enable log collection
  collectMetrics: true,      // Track CPU/memory
  collectTraces: true,       // Distributed tracing
  logBufferSizeMb: 1,       // Log buffer size
}

Modes

subprocess - Fork-based isolation (production)

  • Full isolation
  • Resource limits enforced
  • Timeout protection
  • Separate process space

inprocess - Direct execution (development)

  • No isolation
  • Fast execution
  • Easy debugging
  • Use only for trusted code

Dev Mode

Set devMode: true or KB_PLUGIN_DEV_MODE=true environment variable to force in-process execution.

Integration Examples

Plugin Runtime

import { createSandboxRunner } from '@kb-labs/sandbox';

const sandbox = createSandboxRunner({
  execution: {
    timeoutMs: perms.quotas?.timeoutMs ?? 60000,
    graceMs: 5000,
    memoryMb: perms.quotas?.memoryMb ?? 512,
  },
  permissions: {
    env: { allow: perms.env?.allow || [] },
    filesystem: { allow: [], deny: [], readOnly: false },
    network: { allow: [], deny: [] },
    capabilities: perms.capabilities || [],
  },
  monitoring: {
    collectLogs: ctx.debug || false,
    collectMetrics: true,
    collectTraces: true,
    logBufferSizeMb: 1,
  },
  mode: devMode ? 'inprocess' : 'subprocess',
});

CLI Runtime

const sandbox = createSandboxRunner({
  execution: { timeoutMs: 30000, graceMs: 5000, memoryMb: 256 },
  permissions: {
    env: { allow: ['NODE_ENV', 'PATH', 'HOME'] },
    filesystem: { allow: [workdir], deny: [], readOnly: false },
    network: { allow: ['*'], deny: [] },
    capabilities: [],
  },
  monitoring: {
    collectLogs: true,
    collectMetrics: true,
    collectTraces: false,
    logBufferSizeMb: 1,
  },
  mode: 'subprocess',
});

Security Model

Isolation Levels

  1. Process Isolation - Separate process space (subprocess mode)
  2. Environment Isolation - Whitelisted environment variables only
  3. Resource Limits - Memory and CPU quotas
  4. Timeout Protection - Automatic termination (SIGTERM → SIGKILL)

Future Enhancements

  • Filesystem guards (path restrictions)
  • Network guards (domain whitelisting)
  • Syscall filtering
  • Deno runtime support

API Reference

createSandboxRunner(config: SandboxConfig): SandboxRunner

Creates a configured sandbox runner.

SandboxRunner.run<TInput, TOutput>(handler, input, ctx): Promise<ExecutionResult<TOutput>>

Executes a handler in the sandbox.

Parameters:

  • handler - Handler reference (file path + export name)
  • input - Input data
  • ctx - Execution context

Returns:

  • ExecutionResult - Result with data or error

SandboxRunner.dispose(): Promise<void>

Cleanup resources.

🔧 Configuration

Configuration Options

  • Execution Limits: timeoutMs, graceMs, memoryMb
  • Permissions: env, filesystem, network, capabilities
  • Monitoring: collectLogs, collectMetrics, collectTraces, logBufferSizeMb
  • Mode: subprocess (isolated) or inprocess (fast)

Environment Variables

  • KB_PLUGIN_DEV_MODE: Force in-process execution (development)

🤝 Contributing

See CONTRIBUTING.md for development guidelines.

📄 License

KB Public License v1.1 © KB Labs