sandbox-runtime README

README проекта с github.com/anthropics/sandbox-runtime. Одним файлом markdown: README.md.

Anthropic Sandbox Runtime (srt)

A lightweight sandboxing tool for enforcing filesystem and network restrictions on arbitrary processes at the OS level, without requiring a container.

srt uses native OS sandboxing primitives (sandbox-exec on macOS, bubblewrap on Linux) and proxy-based network filtering. It can be used to sandbox the behaviour of agents, local MCP servers, bash commands and arbitrary processes.

Beta Research Preview

The Sandbox Runtime is a research preview developed for Claude Code to enable safer AI agents. It's being made available as an early open source preview to help the broader ecosystem build more secure agentic systems. As this is an early research preview, APIs and configuration formats may evolve. We welcome feedback and contributions to make AI agents safer by default!

Installation

npm install -g @anthropic-ai/sandbox-runtime

Basic Usage

# Network restrictions
$ srt "curl anthropic.com"
Running: curl anthropic.com
<html>...</html>  # Request succeeds

$ srt "curl example.com"
Running: curl example.com
Connection blocked by network allowlist  # Request blocked

# Filesystem restrictions
$ srt "cat README.md"
Running: cat README.md
# Anthropic Sandb...  # Current directory access allowed

$ srt "cat ~/.ssh/id_rsa"
Running: cat ~/.ssh/id_rsa
cat: /Users/ollie/.ssh/id_rsa: Operation not permitted  # Specific file blocked

Overview

This package provides a standalone sandbox implementation that can be used as both a CLI tool and a library. It's designed with a secure-by-default philosophy tailored for common developer use cases: processes start with minimal access, and you explicitly poke only the holes you need.

Key capabilities:

Example Use Case: Sandboxing MCP Servers

A key use case is sandboxing Model Context Protocol (MCP) servers to restrict their capabilities. For example, to sandbox the filesystem MCP server:

Without sandboxing (.mcp.json):

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem"]
    }
  }
}

With sandboxing (.mcp.json):

{
  "mcpServers": {
    "filesystem": {
      "command": "srt",
      "args": ["npx", "-y", "@modelcontextprotocol/server-filesystem"]
    }
  }
}

Then configure restrictions in ~/.srt-settings.json:

{
  "filesystem": {
    "denyRead": [],
    "allowWrite": ["."],
    "denyWrite": ["~/sensitive-folder"]
  },
  "network": {
    "allowedDomains": [],
    "deniedDomains": []
  }
}

Now the MCP server will be blocked from writing to the denied path:

> Write a file to ~/sensitive-folder
✗ Error: EPERM: operation not permitted, open '/Users/ollie/sensitive-folder/test.txt'

How It Works

The sandbox uses OS-level primitives to enforce restrictions that apply to the entire process tree:

0d1c612947c798aef48e6ab4beb7e8544da9d41a-4096x2305

Dual Isolation Model

Both filesystem and network isolation are required for effective sandboxing. Without file isolation, a compromised process could exfiltrate SSH keys or other sensitive files. Without network isolation, a process could escape the sandbox and gain unrestricted network access.

Filesystem Isolation enforces read and write restrictions:

Network Isolation (allow-only pattern): By default, all network access is denied. You must explicitly allow domains. An empty allowedDomains list means no network access. Network traffic is routed through proxy servers running on the host:

Both HTTP/HTTPS (via HTTP proxy) and other TCP traffic (via SOCKS5 proxy) are mediated by these proxies, which enforce your domain allowlists and denylists.

For more details on sandboxing in Claude Code, see:

Architecture

src/
├── index.ts                  # Library exports
├── cli.ts                    # CLI entrypoint (srt command)
├── utils/                    # Shared utilities
│   ├── debug.ts             # Debug logging
│   ├── settings.ts          # Settings reader (permissions + sandbox config)
│   ├── platform.ts          # Platform detection
│   └── exec.ts              # Command execution utilities
└── sandbox/                  # Sandbox implementation
    ├── sandbox-manager.ts    # Main sandbox manager
    ├── sandbox-schemas.ts    # Zod schemas for validation
    ├── sandbox-violation-store.ts # Violation tracking
    ├── sandbox-utils.ts      # Shared sandbox utilities
    ├── http-proxy.ts         # HTTP/HTTPS proxy for network filtering
    ├── socks-proxy.ts        # SOCKS5 proxy for network filtering
    ├── linux-sandbox-utils.ts # Linux bubblewrap sandboxing
    ├── macos-sandbox-utils.ts # macOS sandbox-exec sandboxing
    └── windows-sandbox-utils.ts # Windows srt-win sandboxing

Usage

As a CLI tool

The srt command (Anthropic Sandbox Runtime) wraps any command with security boundaries:

# Run a command in the sandbox
srt echo "hello world"

# With debug logging
srt --debug curl https://example.com

# Specify custom settings file
srt --settings /path/to/srt-settings.json npm install

The settings file is optional — with no file at ~/.srt-settings.json, srt runs with built-in defaults: no network access, no writes outside the default write paths, and unrestricted reads. A settings file that is there but is empty, cannot be read, or does not validate is an error: srt says so and exits rather than falling back to those defaults, which are a different config rather than a weaker one — falling back would drop the file's denyRead, allowRead and credential rules along with everything else it said. The same goes for a file named with --settings, which must also exist.

Updating the config while the command runs: --control-fd

--control-fd <fd> reads config updates from a descriptor the caller has already opened, one JSON object per line in the same shape as the settings file. Each line replaces the whole config and is validated against the same schema, so a line is a complete config rather than a patch: network and filesystem are required, and a key the line leaves out goes back to its default.

# fd 3 is the read end of a pipe the caller writes lines to
srt --control-fd 3 -- npm test

What an accepted line changes once the command is running:

How srt reads the channel, and what it refuses:

As a standalone proxy with an external decider: srt proxy

srt proxy (or the single-file srt-proxy executable built by bun run build:srt-proxy) runs only SRT's HTTP proxy, with no sandboxed child, for a host that runs the workload elsewhere. It accepts on a listening socket the host hands in, terminates every CONNECT in-process, and forwards a request only when a separate decider process, reached over another inherited descriptor, allows it. See docs/srt-proxy.md for the command line, the decider protocol and the security model.

As a library

import {
  SandboxManager,
  type SandboxRuntimeConfig,
} from '@anthropic-ai/sandbox-runtime'
import { spawn } from 'child_process'

// Define your sandbox configuration
const config: SandboxRuntimeConfig = {
  network: {
    allowedDomains: ['example.com', 'api.github.com'],
    deniedDomains: [],
  },
  filesystem: {
    denyRead: ['~/.ssh'],
    allowWrite: ['.', '/tmp'],
    denyWrite: ['.env'],
  },
}

// Initialize the sandbox (starts proxy servers, etc.)
await SandboxManager.initialize(config)

// Wrap a command with sandbox restrictions
const sandboxedCommand = await SandboxManager.wrapWithSandbox(
  'curl https://example.com',
)

// Execute the sandboxed command
const child = spawn(sandboxedCommand, { shell: true, stdio: 'inherit' })

// Handle exit and cleanup after child process completes
child.on('exit', async code => {
  console.log(`Command exited with code ${code}`)
  // Cleanup when done (optional, happens automatically on process exit)
  await SandboxManager.reset()
})

Violation attribution (commandId / commandText). Violations observed while a wrapped command runs (seatbelt log lines, seccomp events, proxy denies) are stored under an attribution key, and annotateStderrWithSandboxFailures(key, stderr) / getViolationsForCommand(key) look them up by that same key. By default the key is the wrapped string itself. Pass an opaque per-invocation commandId (e.g. a tool-use id) to key by that instead — recommended: keys compare on their first 100 characters, so long commands sharing a prefix would otherwise cross-attribute, and a rerun of the same text would inherit the earlier run's events. If the string you execute is not the command the invocation represents (e.g. you wrap an assembled source <snapshot> && eval '<cmd>'), also pass commandText: '<cmd>': it is what ignoreViolations command patterns match against and what each violation reports as its command. A commandId you pass to wrapWithSandbox must be the same non-empty string you then pass to annotateStderrWithSandboxFailures / getViolationsForCommand; an empty one is treated as no commandId at all, so the key is the command.

Only the key is cut to 100 characters. As of v0.0.76 the reported command — and the text ignoreViolations command patterns are matched against — is the whole command for an invocation wrapped without a commandId, not its first 100 characters; a pattern can therefore only suppress more than it did before, never less. An attribution key no invocation of this process registered (the carriers are writable from inside the sandbox) is reported sanitized and cut to that same key length.

const wrapped = await SandboxManager.wrapWithSandbox(
  assembledCommand, // what actually runs
  undefined,
  undefined,
  undefined,
  { commandId: invocationId, commandText: rawCommand },
)
// ... run it ...
const annotated = SandboxManager.annotateStderrWithSandboxFailures(
  invocationId,
  stderr,
)

Asking about a host no rule decides (the ask callback). The second argument to SandboxManager.initialize is an optional SandboxAskCallback. It is asked about a destination that neither network.deniedDomains, nor network.allowedDomains, nor a per-command allow list (next section) decided, and it is never asked under network.strictAllowlist. Without a callback such a destination is denied. The callback resolves to one of:

Any other answer denies, whether it is truthy or not, and reports the generic reason. That includes an object that carries a reason without saying allow: false, such as { allow: true, reason: '...' }: its reason is not reported.

The reason is sanitized before it is stored, the way the rest of a violation line is. Each run of control characters (line breaks and tabs included) or of invisible ones (zero-width characters, the joiner among them, and bidi controls) becomes one space; < and > are removed, so re-run with <host> listed is stored as re-run with host listed; the ends are trimmed. The result is cut to 500 characters, counted as UTF-16 code units the way String.prototype.length counts them. A reason with nothing left after that falls back to user denied. Write it as one line of plain text.

Behaviour change in the first release after 0.0.79: the filter used to allow on any truthy answer, so a callback that resolved to a truthy value other than true (1, a string, any object) allowed the connection. It now denies. For the same reason, { allow: false, reason } returned to an older release would be read there as an allow, because an object is truthy. SandboxManager.askCallbackDenyReason is true on a release that understands the object: check it before returning one, and deny with a plain false where it is absent.

const deny = (reason: string) =>
  SandboxManager.askCallbackDenyReason
    ? { allow: false as const, reason }
    : false

await SandboxManager.initialize(config, async ({ host, port }) => {
  if (await userApproves(host, port)) return true
  return deny(`${host} was not approved for this session`)
})

Per-command network allow lists (registerCommandNetworkLists). One invocation can carry an allow list of its own, in addition to the configured one, for as long as it runs:

import { randomBytes } from 'node:crypto'

// 128 bits of randomness, 22 characters. See below for why nothing less will do.
const commandId = randomBytes(16).toString('base64url')
const wrapped = await SandboxManager.wrapWithSandbox(
  command,
  undefined,
  undefined,
  undefined,
  { commandId },
)

SandboxManager.registerCommandNetworkLists(commandId, {
  allowedDomains: ['registry.example.org', '*.cdn.example.org:443'],
})
const child = spawn(wrapped, { shell: true })
const unregister = () => SandboxManager.unregisterCommandNetworkLists(commandId)
child.once('exit', unregister)
child.once('error', unregister) // the child never started

Entries use the grammar and the matcher of network.allowedDomains and get the same validation. registerCommandNetworkLists throws on an invalid entry, and on a commandId shorter than 22 characters (an unpaired surrogate does not count). Registering an id again replaces its list; unregisterCommandNetworkLists is a no-op for an id that has none; reset() removes every registration.

The order of evaluation for a connection is:

  1. a network.deniedDomains match denies;
  2. a network.allowedDomains match allows;
  3. network.strictAllowlist denies;
  4. a match in the list registered for the id the connection presents allows;
  5. the ask callback decides if there is one, and otherwise the connection is denied.

So a per-command entry never overrides a configured deniedDomains entry, and is ignored entirely under strictAllowlist. It never enters network.* either: getConfig() and getNetworkRestrictionConfig() do not show it, and the default injectHosts scope of a masked credential, which is network.allowedDomains, does not grow. A host allowed this way still goes through the resolved-address check when it is dialed, and an IP literal in a per-command list adds no exemption there.

What the id has to be, and what this feature is not: the proxy learns which invocation a connection belongs to from the proxy username, and the username is presented by the client inside the sandbox. The id is therefore the only thing binding a connection to an allow list. It must be unguessable: at least 128 bits of randomness, never a counter, a timestamp or anything derived from the command. A sandboxed process that presents another live invocation's id gets that invocation's allows, so this is attribution, not a boundary between concurrent commands of one session. Register just before spawning the wrapped command, and unregister when the child exits or never started: a registration that outlives its command widens the window in which its id is worth presenting. As with every attribution key, only the first 100 characters of an id take part. Keep ids ASCII: a list under a non-ASCII id whose encoded form does not fit in the proxy username (255 bytes) registers and never applies.

No list applies while network.httpProxyPort names an external proxy: the wrap gives that proxy no username, so no connection carries an id. registerCommandNetworkLists still succeeds (and says so in one line under SRT_DEBUG), and every connection is decided as if no list existed.

Available exports

// Main sandbox manager
export { SandboxManager } from '@anthropic-ai/sandbox-runtime'

// Violation tracking
export { SandboxViolationStore } from '@anthropic-ai/sandbox-runtime'

// TypeScript types
export type {
  SandboxRuntimeConfig,
  NetworkConfig,
  FilesystemConfig,
  IgnoreViolationsConfig,
  SandboxAskCallback,
  FsReadRestrictionConfig,
  FsWriteRestrictionConfig,
  NetworkRestrictionConfig,
} from '@anthropic-ai/sandbox-runtime'

Configuration

Settings File Location

By default, the sandbox runtime looks for configuration at ~/.srt-settings.json. You can specify a custom path using the --settings flag:

srt --settings /path/to/srt-settings.json <command>

Complete Configuration Example

{
  "network": {
    "allowedDomains": [
      "github.com",
      "*.github.com",
      "lfs.github.com",
      "api.github.com",
      "npmjs.org",
      "*.npmjs.org"
    ],
    "deniedDomains": ["malicious.com"],
    "allowUnixSockets": ["/var/run/docker.sock"],
    "allowLocalBinding": false
  },
  "filesystem": {
    "denyRead": ["~/.ssh"],
    "allowRead": [],
    "allowWrite": [".", "src/", "test/", "/tmp"],
    "denyWrite": [".env", "config/production.json"]
  },
  "ignoreViolations": {
    "*": ["/usr/bin", "/System"],
    "git push": ["/usr/bin/nc"],
    "npm": ["/private/tmp"]
  },
  "enableWeakerNestedSandbox": false,
  "allowNestedUserNamespaces": false,
  "enableWeakerNetworkIsolation": false,
  "allowAppleEvents": false
}

Configuration Options

Network Configuration

Uses an allow-only pattern - all network access is denied by default.

Resolved-address check. The allow/deny lists match by name, but whoever controls a permitted name's DNS (or any label under a permitted wildcard) controls what it resolves to. So before dialing an allowed hostname directly, the proxy resolves it once, drops any address in a denied set, and connects to a surviving address (the address that passed the check is the one dialed — there is no second lookup). If nothing survives, the connection is refused like any other policy denial: HTTP/CONNECT get 403 (X-Proxy-Error: blocked-by-sandbox-runtime, the reason in the body and, for a CONNECT, as the status phrase), SOCKS gets "connection not allowed by ruleset", and a deny network-outbound host:port (resolved to a loopback address) line — naming the class of address (loopback, link-local, this host's, cloud metadata, deny-listed, listed, …), not the address itself, which only the debug log carries — is recorded in the violation store.

The denied set is: loopback (127.0.0.0/8, ::1), unspecified (0.0.0.0/8, ::), link-local (169.254.0.0/16, fe80::/10), multicast (224.0.0.0/4, ff00::/8), broadcast, the cloud instance-metadata / platform endpoints that live outside link-local (100.100.100.200, 168.63.129.16, 192.0.0.192, fd00:ec2::/32, fd20:ce::254, fd00:c1::a9fe:a9fe, fd00:42::42), every address currently assigned to one of this host's own network interfaces (a service bound to 0.0.0.0 answers on the LAN or global address exactly as it does on loopback), every IP literal listed in deniedDomains (honouring its :port if it has one), and anything in deniedResolvedAddresses. IPv4 entries also match the IPv6 forms that carry an IPv4 address — IPv4-mapped, IPv4-compatible and IPv4-translated addresses, the NAT64 well-known prefix (64:ff9b::/96) and 6to4 (2002::/16) are judged by the IPv4 address they embed. The local-use NAT64 prefix 64:ff9b:1::/48 and network-specific prefixes are not decoded — their layout (RFC 6052 allows the IPv4 in several positions) can't be recognised from the address alone; on such a network, list the prefix's translations of the ranges you deny (e.g. <prefix>::a00:0/104 for 10.0.0.0/8). Addresses that reach this host without being assigned to it — a cloud instance's 1:1-NAT public address, a router port-forward, a container or VM host-gateway alias — are not covered automatically; list them in deniedResolvedAddresses.

What the check leaves alone: allowlist entries that are IP literals (allow-listing 127.0.0.1:3000 is an explicit choice) — and, by the same token, a hostname may resolve to an otherwise-denied address when that IP literal (on that port) is itself in allowedDomains, since reaching it by name grants nothing the literal entry does not (an IP literal in deniedDomains still wins, exactly as it does for a literal request). So a dev setup where myapp.test maps to a local server via /etc/hosts allow-lists ["myapp.test", "127.0.0.1:3000"]; there is no separate carve-out list. localhost and names under .localhost resolve to loopback (or an allow-listed literal) and nothing else. The check is not evaluated for connections routed through parentProxy (including one picked up from HTTP_PROXY / HTTPS_PROXY in srt's own environment) or mitmProxy — that hop resolves the name and owns its own address policy — and it only governs what the proxy dials: on macOS, allowLocalBinding separately lets the sandboxed process connect to loopback ports without going through the proxy at all.

TLS termination (network.tlsTerminate, experimental): when set, HTTPS CONNECTs are terminated in-process so SRT can see (and filter, via network.filterRequest) the decrypted requests. The sandboxed process is pointed at a trust bundle containing the MITM CA (caCertPath/caKeyPath, or an ephemeral CA if omitted) plus the host's regular roots, so proxy-minted certificates and real upstream certificates both verify. It needs Node, or Bun 1.4 or later; on an older Bun, SandboxManager.initialize throws. See TLS Termination for how it works, its limits, and what changed from the per-tunnel listener it replaced.

These two are read at each CONNECT, so updateConfig changes them for the tunnels that follow.

{
  "network": {
    "allowedDomains": ["*.example.com", "internal-mtls.example.net"],
    "deniedDomains": [],
    "tlsTerminate": {
      "excludeDomains": ["internal-mtls.example.net"],
      "extraCaCertPaths": ["/etc/internal-mtls-roots.pem"]
    }
  }
}

Request rewriting (with network.filterRequest, set by library consumers): an allow decision may also carry header edits (removeHeaders, setHeaders) and an onResponse observer, and a deny decision may choose its status (403 by default). These options are read when the proxy starts; updateConfig does not change them.

While filterRequest is set, on plain HTTP and inside a terminated tunnel, the target goes upstream byte for byte as the client spelled it, without a fragment (except under "normalize"), and the callback's second argument carries both forms, requestTarget as spelled and normalizedRequestTarget, and requestTargetIsAmbiguous: under "asSpelled" a callback can refuse an ambiguous target itself, for the hosts and with the status it chooses. request.url is a parsed URL, so, as in earlier releases, its path has dot segments already resolved and is not the spelling. Not ambiguous, and forwarded as spelled: // after the first segment, %2F, ; parameters, dots in the query, a character the URL parser would only escape ({, ", '), and an empty query. A byte outside ASCII, which only Bun's listener for plain HTTP lets through, is percent-encoded in requestTarget and on the wire, as in earlier releases. A # and what follows it are cut off first, in every mode: a fragment is no part of a request target, but some clients leave it in the absolute form they send a proxy, and upstreams differ in what they make of one. So the callback, a signature, the upstream and a violation line all get the target without it; %23 is data and stays.

Answered 400 in every mode, and recorded as a violation: a target that is not origin form, an absolute http(s) URI, or * for OPTIONS; and one with bytes that are not UTF-8, which the runtime has replaced by the time the proxy reads them. So is, inside a terminated tunnel and with or without filterRequest, a request the runtime's own HTTP parser refuses, which ends the tunnel: a raw byte outside ASCII in the target (/café has to be sent as /caf%C3%A9), a space, a malformed header.

While filterRequest is set, TRACE and TRACK requests are answered 405 before it is asked, on plain HTTP and inside a terminated tunnel, because their response would echo a header the decision set back to the client. Node's and Bun 1.4's HTTP parsers already answer TRACK 400 before the proxy sees it; under Bun 1.3 the connection is closed without an answer. Refusals are recorded as violations.

Unix Socket Settings (platform-specific behavior):

Setting macOS Linux
allowUnixSockets: string[] Allowlist of socket paths Ignored (seccomp can't filter by path)
allowAllUnixSockets: boolean Allow all sockets Disable seccomp blocking

Unix sockets are blocked by default on both platforms.

Filesystem Configuration

Uses two different patterns:

Read restrictions (deny-then-allow pattern) - all reads allowed by default:

Write restrictions (allow-only pattern) - all writes denied by default:

A few paths are writable without being listed: the child's stdio and /tmp/claude, and as a convenience ~/.npm/_logs and ~/.claude/debug. Those two home directories are dropped when a denyRead entry covers them (and kept when an allowRead entry beneath that deny re-opens them), so list them in allowWrite if you want them writable under a home read-deny.

Path Syntax (macOS):

Paths support git-style glob patterns on macOS, similar to .gitignore syntax:

Examples:

Path Syntax (Linux):

bubblewrap binds concrete paths, so glob support is narrower than on macOS:

Examples:

All platforms:

Other Configuration

Common Configuration Recipes

Allow GitHub access (all necessary endpoints):

{
  "network": {
    "allowedDomains": [
      "github.com",
      "*.github.com",
      "lfs.github.com",
      "api.github.com"
    ],
    "deniedDomains": []
  },
  "filesystem": {
    "denyRead": [],
    "allowWrite": ["."],
    "denyWrite": []
  }
}

Restrict to specific directories:

{
  "network": {
    "allowedDomains": [],
    "deniedDomains": []
  },
  "filesystem": {
    "denyRead": ["~/.ssh"],
    "allowWrite": [".", "src/", "test/"],
    "denyWrite": [".env", "secrets/"]
  }
}

Workspace-only filesystem access (deny reads outside the workspace):

{
  "network": {
    "allowedDomains": [],
    "deniedDomains": []
  },
  "filesystem": {
    "denyRead": ["/Users"],
    "allowRead": ["."],
    "allowWrite": ["."],
    "denyWrite": []
  }
}

This denies reading anything under /Users (or /home on Linux), then re-allows the current working directory. System paths (/usr, /lib, etc.) remain readable.

Common Issues and Tips

Running Jest: Use --no-watchman flag to avoid sandbox violations:

srt "jest --no-watchman"

Watchman accesses files outside the sandbox boundaries, which will trigger permission errors. Disabling it allows Jest to run with the built-in file watcher instead.

Exit status under zsh (Linux): From the first release after v0.0.77, a wrap that restricts the network reports the wrapped command's own exit status when binShell is zsh. Up to v0.0.77 a failing command could report 0 there: the wrapper's cleanup trap ended with a bare exit, which zsh resolves to the status of the trap's last command. bash (the default) and dash were not affected.

zod 4 in the same dependency tree: The zod dependency range is ^3.25.0. The library imports zod/v3, which exists from zod 3.25 on, so that it keeps the v3 API where a dependency tree resolves zod to version 4.

Platform Support

Platform-Specific Dependencies

Linux requires:

Supported bubblewrap versions: 0.4.0 and later, except that one thing needs 0.5.0 or newer, a change to how bubblewrap prepares the mount point for a file bind: a denyRead entry or credential mask naming a path that is not a regular file — a fifo, a socket, a device node — cannot be applied on an older bubblewrap, which creates a file at the destination instead of binding over what is there (that fails on a read-only mount and blocks on a fifo). checkDependencies() runs bwrap --version (once for each path of bwrap: the answer, or that there was none, is kept for the life of the process) and returns a warning naming the version it found when bubblewrap is older than 0.5.0; it is a warning, not a refusal. CI runs the whole suite against the bubblewrap Ubuntu ships and against 0.12.0, and the Linux mount-plan suites against 0.4.1 as well.

Ubuntu 24.04+ note: These releases enable kernel.apparmor_restrict_unprivileged_userns by default, which allows unshare(CLONE_NEWUSER) but strips capabilities from the resulting namespace. Both bubblewrap and the seccomp isolation layer need capability-bearing user namespaces. Disable the restriction with:

sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0

or add an AppArmor profile that grants userns to the relevant binaries.

Running as root: a caller with euid 0 needs CAP_SETFCAP in its capability bounding set. Bubblewrap's user namespace maps the caller's uid, and Linux 5.12 — and the older distribution kernels that backported the change — lets a namespace map uid 0 only when its creator held that capability; the seccomp isolation layer's nested namespace has the same requirement. Without it every sandboxed command fails with Operation not permitted while writing a uid map, and initialize() refuses to start once bubblewrap has confirmed it. Grant the capability to the calling process — it is in Docker's default set, but capsh --drop=cap_setfcap and a tightened CapabilityBoundingSet= remove it — or run as a non-root user, for which none of this applies. The bounding set is what counts, because bubblewrap is reached by execve and the kernel recomputes a root caller's permitted set from it.

Prefer a non-root caller where there is the choice. Under the seccomp isolation layer a root caller's command still holds a full capability set inside the helper's nested user namespace, which is identity-mapped to the caller's uid 0; what holds the filesystem policy there is the helper's namespaces filter (next paragraph), not the command's capabilities: the nested namespace's copies of the mounts are locked, which refuses the unmount of any one deny but not the whole tree being moved aside with pivot_root. A non-root caller's command holds no capabilities at all.

The command stays in the namespaces made for it. Every write deny on Linux is a read-only bind mount, and a bind protects a path only in the mount namespace it was made in. Creating a user namespace takes no capability and gives its creator a full capability set over a private copy of the mount tree, from which the binds can be removed; so a sandboxed command may not create one. The seccomp isolation layer enforces that with a second filter beside the Unix-socket one, which refuses unshare and clone with the user-namespace or the mount-namespace flag, setns, mount, umount2, pivot_root and the newer mount calls (EPERM), and clone3 (ENOSYS, which sends libc and the language runtimes to clone), and with user.max_user_namespaces set to zero in the helper's own user namespace.

What stops working as a result is whatever sandboxes itself with user namespaces: Chromium's and Electron's namespace sandbox, rootless podman and buildah, a nested bubblewrap or srt, unshare -r in a build script. They fail with EPERM (unshare: unshare failed: Operation not permitted); a nested bubblewrap blames a kernel setting and suggests a sysctl, which does not apply here. A root caller's command also loses mount, umount and setns for purposes of its own (unshare -m, nsenter, ip netns exec), and a direct clone3 call has no fallback. The cure is allowNestedUserNamespaces: true, at the price stated under that option. Known limits:

Optional Linux dependencies (for seccomp fallback):

The package includes pre-generated seccomp BPF filters for x86-64 and arm architectures. These dependencies are only needed if you are on a different architecture where pre-generated filters are not available:

macOS requires:

Windows requires:

Windows (alpha)

Windows support is alpha. The sandboxed process runs under a dedicated srt-sandbox local user account, isolated from the calling user by native Windows security primitives — a Windows Filtering Platform (WFP) egress fence keyed on the sandbox account's SID, a write-restricted token, and explicit ACEs that grant or deny the sandbox access to configured filesystem paths.

Setup

Run once per machine (self-elevates; one UAC prompt):

npx @anthropic-ai/sandbox-runtime windows-install

This provisions the srt-sandbox local user account (with a random password stored DPAPI-encrypted in HKLM\SOFTWARE\sandbox-runtime — machine-wide, so fleet installs running as SYSTEM work and one user's rotation updates the copy the others read), the sandbox-runtime-users local group, and installs a machine-wide WFP filter set keyed on the srt-sandbox SID. It is idempotent — re-running it rotates the sandbox account's password and reconciles the filter set.

After the elevated step, the install makes your user profile readable to sandboxed commands, except for credential stores, as the user who ran it and without elevation; on a large profile this takes minutes the first time. It first prints one line saying so, naming the configuration files that can hold feed tokens and how to skip (--skip-profile-grant) or undo it (srt-win profile forget). See Reading your user profile for what is readable, what is excluded, and how to restrict or remove it — and read Shared machines before installing on a computer that more than one person uses. The sandbox works without the grant; its commands then read nothing in your profile.

No logout is required. The WFP filters key on the dedicated sandbox account's SID, so your own network, services, and every other principal on the machine are unaffected.

After install, SandboxManager.initialize() and the srt CLI work as on other platforms. initialize() verifies the sandbox account and WFP fence are live, and fails with an actionable error if not.

Programmatic install/uninstall are exported as installWindowsSandbox() / uninstallWindowsSandbox().

Upgrading from an earlier release: run windows-install once more (one UAC prompt). It upgrades the existing install in place; nothing has to be uninstalled first, and this is the only reinstall this release asks for. The install records a setup version, and this release raises it (2 → 3) because it keeps write grants on project directories between sessions (see the child token and kept grants). Until the install is re-run, initialize() and checkDependencies() report that the sandbox was set up by a different release and say to re-run the install, and nothing is granted or run. Once it has been re-run, an older release on the same machine refuses to start its sandbox, instead of running commands under a token that the kept grants were not made for. Its message also says to re-run the install; with the older release that is a downgrade, so read the next paragraph first.

Going back to an earlier release: run windows-uninstall with this release first (or srt-win acl forget --all as each user who ran sandboxed sessions), then install the older one. An older release's install does not know about the kept grants and does not remove them, and under its token they would let any sandboxed command write those directories. srt-win user status lists the directories that still carry one (persistent_grants.roots).

Security model

The sandboxed command runs as the srt-sandbox account, not as the calling user. The bundled srt-win.exe helper does a two-hop launch: the broker calls CreateProcessWithLogonW to start a runner as srt-sandbox, and the runner spawns the target under a restricted token inside a job object. The child inherits the sandbox account's isolated profile (%USERPROFILE%, %TEMP%, HKCU) and a fresh environment overlaid with only the broker's PATH and the generated proxy variables.

Running under a distinct user SID structurally closes the surrogate-spawn class of escape (Task Scheduler, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS onto a broker-owned process, BITS, out-of-process COM with RunAs="Interactive User"): any process the child manages to spawn out-of-band still carries the srt-sandbox SID, so the connections it makes itself remain subject to the WFP egress fence and it has no rights on the calling user's files. Traffic a system service carries for such a process is a separate matter (see Known limitations).

Network isolation is a set of two WFP filters, optionally three, at each of FWPM_LAYER_ALE_AUTH_CONNECT_V4/V6, installed machine-wide:

The BLOCK is keyed on the sandbox account alone, so no other process on the machine is restricted. The filtering engine attributes a connect to the token that was in effect when its socket was created; a sandboxed thread that puts another token on itself before creating a socket is therefore not recognised as srt-sandbox. Traffic that a system service carries on the process's behalf is not matched by these filters either (see Known limitations).

A connection the sandboxed process makes itself reaches the internet only via the JS HTTP/SOCKS5 proxies listening in that range; a process that strips its proxy environment and connects directly is blocked at the kernel. initialize() proves this each session by running connects as the sandbox account — with its own token and under copies of its token with the integrity level lowered, each of the latter on a socket created before the token is assumed and on one created after — and refuses to start if any of them gets out. The connects are made under the token a sandboxed command gets; where that token does not let a lowered copy be assumed, the attempt is reported as not made (the lowered-integrity-unprobed residual), not as a failure. The same probe connects while impersonating the anonymous token and under a deny-only copy of its token; those are not fenced, and are reported, not refused (see Known limitations). With loopback open, the connects that must be blocked go to the one loopback port that stays blocked (see Local servers on Windows), and one more connect, to a loopback listener the library binds for the probe, must succeed.

The fence blocks the identities it can name and lets everything else through, which leaves two gaps for tokens a sandboxed process can put on a thread, beside the traffic that system services carry (see Known limitations).

Filesystem isolation is enforced by NTFS discretionary ACLs. The srt-sandbox account has no inherent rights on the calling user's files, so at initialize() the sandbox writes additive, inheriting explicit ACEs — for the sandbox account, and for allowWrite roots for the sandbox group and an identifier of the root's own (below) — and never rewrites or replaces a path's existing security descriptor:

The lists rank as on the other platforms. The ACEs set on an object come before the ones it inherits, so an allowRead beneath a denyRead directory is readable. An allowWrite at or beneath a denyWrite path grants READ|EXECUTE only, and an allowRead or allowWrite at or beneath a credentials.files entry grants nothing. "Beneath" is decided on the paths as they resolve on disk: links, junctions, 8.3 names and letter case make no difference (a UNC path is compared as spelled, whatever its case). A deny that one command brings in its customConfig ranks the same way against the session's grants.

reset() removes the ACEs this session added, except the write grants on allowWrite roots and the denies beneath them, which are kept for the next session (below). What is removed is refcounted across this user's concurrent hosts via the per-user session DB; a crash-recovery pass on the next initialize() cleans up after an unclean exit. Directory targets are supported (the ACEs inherit to the whole subtree). Glob patterns are expanded to concrete paths at initialize() time — a matching path that appears later is not covered. A pattern is walked from the literal directory it starts with, a drive root or the root of a share included (C:\Users*\.ssh\*, \\server\share\*.pem); a ** right below such a root lists the whole volume. In an entry without * or ?, [ and ] are characters of the name. In a pattern they are read as a character class, as on the other platforms, and the pattern is also expanded beneath a folder that has them in its name.

The child token and kept write grants

The sandbox account is a member of BUILTIN\Users, so an ordinary token for it can write wherever Users / Authenticated Users hold write access, whatever filesystem.allowWrite says: directories created under C:\, trees on data drives, PATH directories outside Program Files. The sandboxed process therefore runs under a **write-restricted token**. Its restricting SIDs are the sandbox account, Everyone, RESTRICTED, and one identifier per allowWrite root of the session, so those group-held write rights do not apply: only the session's allowWrite roots, the sandbox account's own profile, and locations writable by Everyone are writable. Reads are unaffected by the token.

What does not work inside the sandbox: Schannel. Windows does not hand TLS credentials to a restricted token, so a client that uses the operating system's TLS stack cannot complete an HTTPS handshake:

There is no workaround for these inside the sandbox: run such a tool outside it.

What keeps working: clients that bring their own TLS stack — Node, Python, Java, Go programs, msys2 / Git for Windows curl built with OpenSSL, and Git for Windows itself, which the sandbox steers to its OpenSSL backend (http.sslBackend=openssl in the injected git config). They take their trust roots from the environment variables described under TLS termination. git on its OpenSSL backend reads a PEM bundle, not the Windows certificate store: a host that does not terminate TLS itself and whose network path needs a root that exists only in the store (a TLS-inspecting corporate proxy, say) must supply it by setting GIT_SSL_CAINFO to a PEM bundle that contains it.

Write grants on allowWrite roots are kept between sessions. Granting a directory means writing an access entry that Windows copies to every file below it, which takes time proportional to the tree — and as long again to take back. So a root is granted the first time it is used; afterwards initialize() reads one access list per root, and reset() leaves the grant in place.

The library always passes --write-restricted-token to srt-win exec: there is no setting that runs a sandboxed command under the sandbox account's ordinary token. srt-win itself still accepts a call without the flag, and refuses it while a kept grant exists or its absence cannot be established.

initialize() verifies the egress fence under the write-restricted token and fails if the probe is not blocked; a passed check is remembered for the rest of the process, until the sandbox account changes (a re-install) or a session asks for the other loopback mode (network.allowLocalBinding). If the token cannot be created, or a command fails under it, the failure is reported: nothing retries under another token.

Reading your user profile

Installing the sandbox makes the tool directories of your user profile readable to sandboxed commands: the places where per-user tools install themselves — AppData\Local\Programs, AppData\Roaming\npm, go, .nuget and the rest of the list below — and the configuration files the package managers read. Tools installed under the profile run, and npm, pip, NuGet, Maven, Gradle and git find your configuration, including the sign-in for a private package feed. Everything else in the profile — your documents, desktop and downloads, your projects, the data of other applications under AppData — stays unreadable, and the credential stores listed below are denied outright.

The read access is a grant kept on disk. windows-install (installWindowsSandbox() / installWindowsSandboxAsync()) applies it right after the elevated step, without elevation, as the user who ran the install and for that user's profile:

const r = await installWindowsSandboxAsync({
  srtWin,
  profileExclude: ['.myapp'], // extra paths to keep unreadable
  onProfileGrantProgress: line => console.error(line), // "12/57 top-level item(s) done"
  profileGrantTimeoutMs: 30 * 60_000, // the default
})
// r.profileGrant: { applied: true, userSid, result } | { applied: false, reason }

The grant being there is the switch. initialize() does not create it. With no grant recorded — skipped at install, or removed with profile forget — a session runs exactly as it would without this feature, and SandboxManager.getWindowsProfileRead() returns 'absent'. With a current grant it returns 'granted'. initialize() rejects, with profile_grant_outdated, only when a grant is recorded that cannot be relied on: its run did not finish, it was made by a release with another list of what is readable and what is excluded (a path excluded since would otherwise stay readable, and a directory dropped from the list would too) or for another profile directory, or its record is unreadable or lacks its list of exclusions. Then run grantWindowsProfileRead() (or windows-install) again, or forgetWindowsProfileRead() to go without.

A release that narrows the list narrows your grant by itself. When a grant was made with an older list, on this same profile, or a grant's own run was cut short, initialize() runs the grant again before the session starts, as you and without a prompt: entries that have left the list are removed, with what they handed down to everything beneath them, and any empty directories the grant created for them. This can take minutes on a large profile, once; initialize() gives it the same 30 minutes as the install (a run that takes longer rejects with srt_win_timeout and no session starts; the next start skips the trees it finished, but a single tree is walked again from its top), and onWindowsProfileGrantProgress in its options reports progress so you can tell the user why the session has not started. It needs no other sandbox session or command running, and rejects with profile_grant_blocked_by_session if one is. A recorded object that no longer exists is simply dropped, and one that has moved has its entry taken off where it now is. A run that does not finish (it fails, times out, or another session is running) makes initialize() reject with a typed error. A run that finishes but could not remove some entries (access denied, an unreachable volume) does not stop the session: getWindowsProfileReadWarnings() lists each path as profile_stale_allow, and getWindowsProfileReadRefresh() returns the run's result. A path listed in that warning may stay readable to sandboxed commands until the entry is removed. Those entries stay recorded, and initialize() tries them again, on those paths alone: at most every six hours, on local volumes only, and never keeping another starting session out. That attempt is stopped after about ten seconds, so an entry on a tree too large to walk in that time is not cleared at a session start and keeps its warning; srt-win profile retry-stale tries them all at any time. The warning is shown at every start until the entry is gone. A list that widens what is readable is never applied this way, nor is a grant made for another profile, a removal that was cut short, or a record newer than this release: those reject with profile_grant_outdated.

What is readable

The grant is read + execute for the sandbox group, never write, on these directories of your profile (%USERPROFILE% unless marked; %APPDATA% is AppData\Roaming and %LOCALAPPDATA% is AppData\Local, or wherever the known folders really are):

Directory For
%LOCALAPPDATA%\Programs python.org's Python, Git for Windows, VS Code, Node and other per-user installs
%LOCALAPPDATA%\Microsoft\WinGet winget packages and the links to their executables
%APPDATA%\npm npm global installs and their shims
%APPDATA%\nvm, %APPDATA%\fnm, %LOCALAPPDATA%\fnm_multishells, %LOCALAPPDATA%\Volta, %LOCALAPPDATA%\pnpm the Node version managers, and pnpm
go, .dotnet, %LOCALAPPDATA%\Microsoft\dotnet, .bun, .deno, .jdks, pipx, miniconda3, anaconda3 those tools' binaries and what they need
.nuget the packages a NuGet restore fetched
.rustup, .cargo the Rust toolchains; cargo's shims, registry and config (credentials and credentials.toml stay denied)
.m2, %APPDATA%\pip, pip, %APPDATA%\NuGet, .gradle, .config\git, .config\pip, %APPDATA%\Python, .pyenv the configuration of Maven, pip, NuGet, Gradle and git (the rest of .config is not readable, and the credential stores under .config and .gradle stay denied); the Python user site-packages; pyenv-win's Pythons
.npmrc, .gitconfig the two files of the profile directory itself that are readable

A listed directory is granted whole, with one inheriting entry, so what a tool installs into it later is readable at once — unless an excluded path could lie beneath it (.cargo, .config\git, .gradle; every child of %LOCALAPPDATA% and of %LOCALAPPDATA%\Microsoft, and every application directory directly under %LOCALAPPDATA%\Programs and %LOCALAPPDATA%\Microsoft\WinGet\Packages, where an application may keep an embedded browser profile; so Programs\nodejs, VS Code, pnpm and Volta are among these): then the directory can be listed and passed through, and its children are granted one by one, each file through an entry of its own. The profile directory itself and every directory on the way to a listed or an excluded path (AppData, AppData\Roaming, AppData\Local, AppData\Local\Microsoft, …) can be listed and passed through as well; their other files are not readable.

An unlisted directory is not readable through the grant. Most get no entry at all. Your documents, your projects, %APPDATA%\Code, %APPDATA%\Anthropic are not readable through the grant, and they are not denied either: a session that needs one names it in filesystem.allowRead, or works in it as its working directory, as it would a directory outside the profile. A directory a tool keeps somewhere the list does not name can be added to the grant instead, for every session: profileInclude: ['tools\\cargo'] to the install, include: [...] to grantWindowsProfileRead(), or srt-win profile grant --include <path> (repeatable; absolute, or relative to the profile). Added inclusions are recorded with the grant (extraInclusions in its status) and stay on later runs that do not name them; replaceInclusions: true (--replace-includes) makes the given list the whole added list. An inclusion that is an excluded path or lies inside one is refused, and so is the temporary directory or anything in it; one that lies above an excluded path is admitted and granted child by child. Nothing removes a built-in entry.

No path the exclusion list matches ever sits beneath a directory that is granted whole, so an excluded directory or file that is deleted and created again, or replaced by a rename, does not become readable. The list matches what it names and no deeper: its embedded browser rules cover EBWebView and <exe>.WebView2\EBWebView directly in an application's directory under %LOCALAPPDATA%\Programs and WinGet\Packages, not nested further (Programs\Vendor\App\EBWebView is not matched, and is readable if Programs\Vendor\App is granted whole).

What it does not do.

Cost. The first run sets an entry on every file under the granted directories and on the excluded ones: expect minutes on a large profile, and no other session of yours can start while it runs. A refresh reads one access list per recorded path and writes only what changed.

Readable files that can contain package-feed tokens

These configuration files are readable by sandboxed commands. That is deliberate — a private feed's sign-in works inside the sandbox — and it means a sandboxed command can read any token stored in them:

File Read by
%USERPROFILE%\.npmrc npm
%APPDATA%\pip\pip.ini, %USERPROFILE%\pip\pip.ini, %USERPROFILE%\.config\pip\pip.conf pip
%APPDATA%\NuGet\NuGet.Config NuGet
%USERPROFILE%\.m2\settings.xml, settings-security.xml, settings-security4.xml Maven. The last two are the master password files: readable by design, so a sandboxed command can decrypt the passwords stored in settings.xml
%USERPROFILE%\.gradle\gradle.properties Gradle
%USERPROFILE%\.gitconfig, %USERPROFILE%\.config\git\config git

To keep one of them unreadable, list it in credentials.files or filesystem.denyRead (for your sessions), or exclude it from the grant (for every session — see Restricting it).

The sandboxed process has its own profile, so a tool does not look in yours by itself. windowsProfileReadEnv(getWindowsProfileReadStatus({ srtWin }), yourEnv) returns the variables that point each tool at its file, for the files that exist; the library sets none of them — pass the ones you want with the command's environment:

Variable Tool Notes
NPM_CONFIG_USERCONFIG npm
GIT_CONFIG_GLOBAL git 2.32+ replaces both global files; left out when you set it yourself
PIP_CONFIG_FILE pip read in addition to pip's other files
MAVEN_ARGS (-s <settings.xml> -Dsettings.security=<settings-security.xml>) Maven 3.9+ no quotes, since mvn expands the variable unquoted; a path holding whitespace or a character the launchers treat specially is given by its 8.3 names, or, where no such name is free of them, the variable is withheld and srt-win profile status says why under env_withheld; older Maven needs -s on the command line
RUSTUP_HOME rustup (cargo, rustc) a directory: your RUSTUP_HOME if you set one, else %USERPROFILE%\.rustup; without it rustup's shims find no toolchain
CARGO_HOME cargo a directory: your CARGO_HOME if you set one, else %USERPROFILE%\.cargo; read-only — see below
— NuGet no variable names the user file: pass --configfile, or keep a NuGet.Config in or above the project
— Gradle no variable names gradle.properties (GRADLE_USER_HOME would move the caches too): pass properties as ORG_GRADLE_PROJECT_<name> or -P

RUSTUP_HOME and CARGO_HOME are the two that name a directory rather than a file, and are returned only when the directory exists and the grant reaches it (a location outside your profile is not offered, and neither is the default in its place). With CARGO_HOME pointing at your real, read-only directory, cargo builds from what is already cached there (--offline) but cannot add to the registry cache or install binaries from inside the sandbox. That is the intended trade: an empty writable cache in the sandbox account's own profile would be no better, since cargo's downloads use the Windows TLS stack, which does not work under the sandbox token. credentials and credentials.toml in that directory stay unreadable — they are denied on the files themselves, whatever names the directory — so an operation that needs a registry token fails there. config.toml in it stays readable, like .npmrc: a registry token written there rather than in credentials.toml is readable to sandboxed commands.

Stores you have moved. The exclusion list protects each tool's store where the tool keeps it by default. If your own environment moves one to another place inside your profile, the grant protects what the variable names as well: CARGO_HOME (its credentials and credentials.toml), GRADLE_USER_HOME (its enterprise\keys.properties and develocity\keys.properties), GNUPGHOME, DOCKER_CONFIG, AZURE_CONFIG_DIR, GH_CONFIG_DIR, AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE, NETRC, and each file in KUBECONFIG. They are read from the environment srt-win profile grant runs in, recorded with the grant (env_exclusions in srt-win profile status), and never dropped by a later run — not when the variable changes or goes away, not with --replace-excludes: what was protected once stays protected until the grant is forgotten. A variable set after the grant was made takes effect at the next srt-win profile grant; until then a moved cargo home is not offered as CARGO_HOME, and srt-win profile status says so under env_withheld. Other variables that move a credential store are not followed; add such a place with --exclude.

Exclusions

There are two kinds.

Protected paths hold credentials, keys or tokens. They are never granted, and they are denied explicitly to the sandbox group (the deny is written before anything is granted; the commonest of these directories are created empty, to carry it, where they do not exist yet). A session cannot grant read access to one, to anything inside one, or to a directory above one — see Restricting it. They are:

Left ungranted, but not closed: %LOCALAPPDATA%\Temp. Every program you run drops files in the temporary directory, so nothing in it is readable through the grant — a file directly in it is as unreadable as before. But it is not a secret as a whole, and it is where sessions (and this library, for its trust bundle) stage directories of their own: it is not denied, and a session may grant a directory inside it with filesystem.allowRead or allowWrite as usual. Only a grant of the temporary directory itself, or of a directory above it, is refused, because that would cover everything in it. (The browser caches under Microsoft\Windows are protected, not merely ungranted: they hold cookie and history databases and pages fetched with your sign-ins, and nothing stages a session directory in them.)

Links. A junction or symbolic link is never granted through or written on. Where an excluded name is itself a link — .ssh or .config pointing into a dotfiles directory, say — the exclusion follows it: the link's target, if it is inside the profile, is excluded in its place (or becomes a directory of which only the right children are excluded), and is recorded with the grant at its real location. Links are resolved from the links themselves, one at a time, and only while they stay on this machine's drives; a link that leads to a network share is reported and not followed.

Objects you may not change. A real profile holds directories its user does not own (the Windows Installer cache, for one) and directories locked down so far that their own owner is denied reading. The grant works around them and says what it did — in its result, on the command line, and in srt-win profile status / getWindowsProfileReadStatus() — and none of them makes it fail or leaves it incomplete:

A protected path that is readable through an entry this product wrote is the one case here that calls for action. It arises when a path carries an allow from an earlier run, is on the exclusion list now — the built-in list grew, or you added an exclusion — and its access list can no longer be written; or when a directory was granted whole, something beneath it became an exclusion, and the directory cannot be rewritten. It is reported among unprotected (the profile_exclusion_unprotected warning names these first), with protectedExclusion: true and entry on the item: explicit when the entry is on the object itself, inherited when it is a copy handed down from a directory above that could not be taken off the object. The session still starts — refusing every session over an object you cannot change would cost the sandbox and close nothing — and no per-command deny can help, since that would have to be written to the same access list. Where the entry is inherited the grant has already rewritten the directory it came from; what is left is the copy on the object. The item's reason gives the command that removes it, to be run as the object's owner or from an elevated prompt — icacls "<path>" /remove:g "*<sandbox group SID>" for an explicit entry, icacls "<path>" /inheritance:e for an inherited copy — followed by srt-win profile grant again. A staleAllow item carries the same two fields, with protectedExclusion: false.

The last three are what the access lists say when they are read, not what they said when the grant ran: srt-win profile status looks at each such exclusion again, so one that has been opened up since is reported as unprotected at the next session start, and one that can be denied by now is denied by the next run of the grant.

A grant reads as incomplete only when a run was cut short.

The list covers known stores. AppData holds the data of every application you run; an application's directory there is not readable unless the list of readable directories names it, or you add it — so an exclusion is needed only for a store that lies inside a readable directory.

When the grant changes

The grant is written, refreshed and removed only while no sandbox session or command of yours is running, so that a session's view of your profile is fixed from its start to its end. grantWindowsProfileRead() (srt-win profile grant), srt-win profile forget and uninstall write nothing and fail — profile_grant_blocked_by_session, kept_grants_in_use — while one is; close the running sessions and run it again. A write root kept from an earlier session that is, lies inside, or lies above an exclusion is forgotten by the grant, and named in its output and result (forgottenRoots): its inheriting allow would otherwise reach the excluded store, and a session that asks for such a root is refused anyway. That is the price of a refresh: a new item in a directory granted child by child becomes readable at the next refresh, and a refresh needs the sessions closed. While a grant or a forget runs (half a minute to many minutes on a large profile), a session or command that tries to start fails with profile_operation_in_progress — at once where it asks for the grant's status, after about three seconds where it waits for the lock — rather than waiting it out. Every session counts, whatever it was given: initialize() registers it with srt-win, and a command wrapped with no session behind it registers itself for as long as it runs (one more acquisition of srt-win's lock per such command). A sandboxed command does not outlive its session: srt-win exec watches the process that started it, and if that process ends while the command runs — it is killed, or crashes — the command and everything it started are terminated at once and srt-win exec exits 26 (session_ended from parseWindowsSandboxError). So "no session is running" means no sandboxed process is. The refusals name the processes: kept_grants_in_use and profile_grant_blocked_by_session say for each whether it is a session or command, holds a session grant or deny, or runs on a kept write root.

Shared machines

The sandbox account and the sandbox group exist once per machine, not once per user. The read grant on your profile is a grant to that group. So once ANY user's profile is granted, sandboxed commands started by ANY local user who can use the sandbox can read the listed directories of that profile — not only commands you start. A person at another account on the same computer can read your per-user tools, the configuration files listed above and any directory you added with --include by running a sandboxed command.

On a computer that more than one person has an account on, do not apply the grant: install with --skip-profile-grant (skipProfileGrant: true), or run srt-win profile forget if it is already there. The sandbox works without it.

The same holds for the write grants kept on project roots (see The child token and kept write grants): another user's sandboxed session can read a kept root, though not write it.

Restricting it

Removing it

forgetWindowsProfileRead({ srtWin }) or srt-win profile forget takes the sandbox group's entry off every recorded path, leaving each access list as it was, and removes the empty directories the grant created. windows-uninstall does the same. While a sandbox session or command is running nothing is removed and the call fails with kept_grants_in_use, naming the process. forgetWindowsProfileReadAsync() is the same removal without blocking the event loop. srt-win profile status shows what is recorded. After a removal sessions keep running; they no longer read the profile. A recorded path on a volume that cannot be reached, with nothing recorded that could find it when the volume returns, does not hold the removal open: it comes back in deferred (srt-win profile forget --json), is no longer recorded, and may still carry the entry if the volume returns.

A kept write grant on a volume that cannot be reached — a disk that is not attached, a drive with no media, a locked BitLocker volume, a share that does not answer — cannot be taken off, and does not have to be for srt-win acl forget to succeed: it is listed as pending and is removed — by the next session start, forget or uninstall — once the volume is back, wherever the directory has been moved to on it. For a volume that will not come back, srt-win acl forget --drop-pending <path> gives the record up and says what it leaves behind; nothing else drops one.

TLS termination on Windows

network.tlsTerminate does not need the MITM CA in the sandbox user's certificate store. Only Schannel clients read that store, and they do not run inside the sandbox (above); windowsTrustCa() / srt-win user trust-ca remain available but initialize() no longer checks for them.

Clients with their own TLS stack (msys2 curl, git on its OpenSSL backend, Node, Python) are covered by the env-var trust layer: the same trust bundle used on macOS/Linux is passed into the sandbox via NODE_EXTRA_CA_CERTS, SSL_CERT_FILE, CURL_CA_BUNDLE, GIT_SSL_CAINFO, CARGO_HTTP_CAINFO, etc., and the bundle path is added to the session's allowRead grant so the sandbox account can open it.

The MXC backend does not support network.tlsTerminate: initialize() refuses that combination.

Windows-specific configuration

The cross-platform filesystem and network blocks apply as described above. Windows-only settings live under windows:

MXC backend (experimental)

windows.backend: 'mxc' runs commands in an MXC BaseContainer through the @microsoft/mxc-sdk package (an optional peer dependency that needs Node 24 or later, so install it yourself, or pass your own SDK as windowsMxcSdk to initialize()). The OS applies the filesystem and network policy for each command, so there is no install step, no sandbox user and no ACL changes. It needs a Windows build with the BaseContainer tier; MXC's AppContainer tiers are never used. An embedder that bundles the SDK passes it to initialize() as the windowsMxcSdk option, an object with its probe() and spawn(); the package is then not resolved.

The SDK starts the process itself, so commands start with spawnSandboxed() rather than wrapWithSandboxArgv(), which throws under this backend:

const proc = await SandboxManager.spawnSandboxed('npm test', { cwd })
proc.stdout?.pipe(process.stdout)
proc.stderr?.pipe(process.stderr)
const { exitCode, timedOut } = await proc.wait()
proc.dispose()

spawnSandboxed() takes the same commandId and commandText as wrapWithSandboxArgv()'s options, so per-command network lists and violation attribution work as on the other backends. kill() ends the command and everything it started. Each call checks its own policy with MXC's probe first and throws backend_unsupported if the host cannot enforce all of it; nothing falls back to a weaker policy or to srt-win.

What works: the network fence (only the proxy is reachable), reads everywhere on the system drive except the deny-list, writes only inside allowWrite and the host's temp folder (by its full path), per-command allowRead/allowWrite, credential masking of environment variables, and everyday tools such as cmd, PowerShell, git, node and whoami.

Known limitations:

Local servers on Windows

By default a sandboxed command cannot connect to anything on localhost except the sandbox's own proxies: not a development server, not a database, not a server another sandboxed command started. network.allowLocalBinding — the same setting that opens local ports on macOS — opens loopback on Windows. It is off by default, and it is a property of the install:

npx @anthropic-ai/sandbox-runtime windows-install --allow-loopback
{ "network": { "allowLocalBinding": true } }

What it opens. Any service listening on the machine's loopback (127.0.0.0/8 and ::1, every TCP and UDP port) becomes reachable by sandboxed commands, whoever started it and whenever — including a local proxy or forwarder that carries traffic off the machine, which the domain allowlist does not cover. This is the same as on macOS with the setting on; Linux gives the sandbox its own loopback instead. Connections to any non-loopback address, the machine's own LAN address included, stay blocked. One loopback port, 1, stays blocked as well, so that the sandbox can check its own fence.

Set at install time, machine-wide. The filters need an administrator, so the mode changes only by running windows-install again, elevated — with --force, as for any other change to an existing install (omit --allow-loopback to close loopback again). srt-win status reports it as wfp.allow_loopback, with a loopback_notice when it is open, and the fence probe and the dependency check say so in their warnings (WINDOWS_ALLOW_LOOPBACK_EFFECT).

One mode per machine, not per session. The key is written per session, but the mode it names belongs to the machine: every session on the machine, of every application that uses this install, must ask for the installed mode. A session that asks for the other one — in either direction — does not start: initialize() rejects with a WindowsSandboxError whose code is wfp_loopback_mismatch, srt-win exec exits 19 with the same code on its error line and launches nothing, and the dependency check reports it as an error when it is given the configuration, each naming the one install command to run. The mode cannot change for one command or through updateConfig(): those are refused the same way, and reset() then initialize() re-checks. Two applications that need different values therefore cannot share a machine; an embedder that offers the setting should say so where it offers it, and treat this error as "the machine is installed the other way", not as a broken install.

Where the setting may come from. Because it decides what sandboxed code can reach, an application embedding this library should take network.allowLocalBinding — and decide whether to install with --allow-loopback — only from a source the machine's user or administrator controls, never from a project's own files. The library cannot tell where its configuration came from; that is the embedder's duty.

no_proxy. With loopback closed the sandbox sets no no_proxy, so HTTP clients send localhost requests to the proxy like any other, where the domain allowlist decides them. With loopback open, the sandbox sets no_proxy=localhost,127.0.0.1,::1 (in lower case only, like the other proxy variables) so that proxy-aware clients connect to local servers directly: those requests bypass the filtering proxy.

Known limitations

Uninstall

npx @anthropic-ai/sandbox-runtime windows-uninstall

Removes the WFP filter set, the srt-sandbox account and its profile, the sandbox-runtime-users group, the write grants kept on allowWrite roots by sessions of the user running it, that user's profile read grant, and removes the HKLM\SOFTWARE\sandbox-runtime key (credential, marker, CA record) — one UAC prompt. It refuses up front, with kept_grants_in_use, while a sandbox session or command of yours is running. That is checked once, before the prompt: a session started between the check and the elevated step is not kept out, loses its account under it, and is named when the uninstall finishes. Nothing is removed before the prompt is accepted: declining it leaves the sandbox and every grant as they were. The elevated step removes the install; the grants are then taken off by the process that asked, as the user who asked, whenever the account is gone. If one cannot be, the uninstall says which, exits non-zero, and srt-win acl forget --all / srt-win profile forget finish it later — also after a reinstall, which gives the group a new identifier: the old one is remembered with the grants. A grant on a disk that is not attached is listed rather than reported as removed. %ProgramData%\sandbox-runtime (the CA key material) is left in place; delete it (and %LOCALAPPDATA%\sandbox-runtime per user) manually for a full sweep.

Development

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Type checking
npm run typecheck

# Lint code
npm run lint

# Format code
npm run format

Building Seccomp Binaries

The BPF filter and apply-seccomp loader are compiled from C source in vendor/seccomp-src/ via npm run build:seccomp (Linux only; needs gcc and libseccomp-dev). CI runs it before tests on each Linux arch, and the release workflow builds both arches and bundles them into the published package.

Implementation Details

Network Isolation Architecture

The sandbox runs HTTP and SOCKS5 proxy servers on the host machine that filter all network requests based on permission rules:

  1. HTTP/HTTPS Traffic: An HTTP proxy server intercepts requests and validates them against allowed/denied domains
  2. Other Network Traffic: A SOCKS5 proxy handles all other TCP connections (SSH, database connections, etc.)
  3. Permission Enforcement: The proxies enforce the permissions rules from your configuration

Platform-specific proxy communication:

git over SSH (macOS/Linux): ssh reads no proxy variable, so srt sets GIT_SSH_COMMAND to an ssh whose ProxyCommand opens an HTTP CONNECT through the proxy and presents its token: socat on Linux, and on macOS a /bin/sh script around /usr/bin/nc, carried in SRT_SSH_PROXY_COMMAND, which keeps the token out of the arguments of ssh and of what it starts. (On macOS, a socksProxyPort or httpProxyPort of your own keeps nc -X 5 to the SOCKS port.) The destination is held to allowedDomains / deniedDomains like any other: github.com admits port 22, github.com:443 does not. On macOS a refusal is one line on stderr before ssh's own, with the proxy's reason: sandbox proxy: github.com:22: 403 host is not on the allow list. On Linux it is up to socat: 1.8.1 prints the reason, 1.8.0 nothing. What ssh needs to authenticate is a separate matter: its agent's socket has to be in allowUnixSockets, and its keys readable. An ssh that git does not start is not covered.

Node.js (Windows): Node's built-in fetch, http and https clients read HTTP_PROXY/HTTPS_PROXY only when asked to, so on Windows srt sets NODE_USE_ENV_PROXY=1 alongside them (read by Node 22.21+ and 24.5+; on older releases those clients still connect directly and are refused). The two do not use the proxy the same way: http.get to an http:// URL sends the request to the proxy, while fetch opens a CONNECT tunnel even for an http:// URL, so for fetch the proxy sees and filters the host and port and nothing of the request inside the tunnel. With the variable set, Node's default agent proxies every request, so a library that already does its own proxying through that agent (it is handed the proxy's address and sends its requests there) has those requests proxied a second time and fails. To opt out, clear the variable in the command (in cmd, set "NODE_USE_ENV_PROXY=" & set "node_use_env_proxy=" & node app.js: a *_PROXY name is in the environment in both cases, and set removes one entry at a time), or give it a value of your own in the environment variables you pass for the sandboxed command: a caller's value replaces the generated one. On macOS and Linux srt does not set it.

JVM tools (macOS/Linux): the JVM ignores HTTPS_PROXY/NO_PROXY and has no environment variable for proxy credentials — proxy selection comes from the https.proxyHost system properties and the credential can only be supplied through java.net.Authenticator. So JVM-based tools (Bazel's gRPC remote cache, Gradle, Maven, …) would otherwise dial the target directly and fail, or reach the proxy without its token and get a 407. To close that gap srt injects a small -javaagent via JAVA_TOOL_OPTIONS (the env var carries only the jar path, the credential stays in HTTPS_PROXY). At JVM start the agent sets http[s].proxyHost/Port and http.nonProxyHosts from the proxy env vars, re-enables Basic auth for CONNECT tunnels, and installs an Authenticator for the proxy endpoint. Explicit -D proxy properties on the JVM command line still win, and any inherited JAVA_TOOL_OPTIONS is preserved (unless it is a denied credential env var). Every JVM prints a Picked up JAVA_TOOL_OPTIONS: … line to stderr as a result; a jlink'd runtime built without the java.instrument module cannot load agents and will refuse to start under the sandbox — unset JAVA_TOOL_OPTIONS in the command for such a tool. The jar ships in the npm package as vendor/java-proxy-agent/srt-proxy-agent.jar (source: vendor/java-proxy-agent-src/; built by the release workflow, or locally with npm run build:java-agent — needs a JDK ≥ 17). If it is not found, JAVA_TOOL_OPTIONS is left alone and JVMs behave as before; bundlers can point at their own copy with javaAgentJarPath.

TLS Termination

With network.tlsTerminate, a CONNECT to an allowed host that is not in excludeDomains is answered 200, and the client's first bytes are read. If they are a TLS ClientHello, the TLS is terminated in the SRT process, on the tunnel's own socket: the leaf certificate is minted for the server name read from the ClientHello (for the CONNECT target when there is none, and always with requireHostMatch), and the decrypted connection is handed to an HTTP server that never listens. Each request on it goes through filterRequest and the credential hooks and is forwarded upstream over a separate, certificate-verified TLS connection. The decrypted traffic, and the credentials injected into it, stay inside the SRT process and leave it only re-encrypted, to that verified upstream. Nothing is opened that another process could connect to: there is no per-tunnel listener and no per-tunnel socket file. A CONNECT whose first bytes are not TLS is tunnelled opaquely, as before (or refused, with refuseOpaqueTunnels).

Runtime requirement. Handing a decrypted connection to an HTTP server needs an http.Server that serves a connection passed to it with emit('connection'). Node's does, and Bun's does from 1.4. On an older Bun, SandboxManager.initialize with network.tlsTerminate set throws before it starts anything, with an error that names the runtime found:

tlsTerminate needs Node, or Bun 1.4 or later (this is Bun 1.3.13)

A program built with bun build --compile runs on the Bun that built it, so build it with Bun 1.4 or later. Without tlsTerminate, nothing changes on any runtime. Should a tunnel still reach the proxy on such a runtime, it is closed rather than left hanging.

Limits. At most maxTunnels tunnels (default 256) are terminated at once, and each must finish its handshake within handshakeTimeoutMs (default 10 s) of its CONNECT; see Network Configuration. Past its handshake, an idle tunnel (no request on it, nothing queued for its client) is closed and its slot freed: 10 s after its ClientHello if no whole request head has come, and 6 s after a response if none has followed, which is 1 s later than the Keep-Alive: timeout=5 that responses carry; a client that does not answer the close is cut off as long again later. A tunnel whose request is not all in or is held back for an upstream that takes no more of it, or whose client does not take what is queued for it, is closed 300 to 360 s after anything last moved. A client that goes on reading, slowly or in bursts, loses nothing; that it reads shows as the kernel's send buffer frees up, up to a megabyte or two at a time, so one that takes less than about 5 KB/s of a response larger than the kernel's buffers hold counts as one that has stopped. A whole request may wait for its response without limit. Leaf certificates share one key per CA, and the proxy keeps those of the 256 most recently used host names.

Memory held for slow peers. A response to a client that is not reading waits once about 1 MiB is queued for that client, or once all tunnels together have 256 MiB queued, on Node and Bun alike. A request body to an upstream that is not reading is held back by the runtime under Node. Under Bun, the proxy does it itself (it pauses a tunnel once 4 MiB of its request body is buffered, or once the shared 256 MiB is used), but that only works on a connection the proxy is handed by its host. The proxy SandboxManager runs accepts its own connections, and Bun keeps reading such a tunnel while it is paused. So under Bun an upload to an upstream that has stopped reading is buffered in the SRT process without bound. This is a limitation of the runtime. Use Node where a sandboxed process may upload more than the host can hold.

Changes a tlsTerminate user can observe. On a supported runtime, compared with the per-tunnel listener:

Filesystem Isolation

Filesystem restrictions are enforced at the OS level:

Default filesystem permissions:

Precedence is intentionally opposite for reads vs writes: allowRead overrides denyRead, while denyWrite overrides allowWrite. This lets you carve out readable regions within denied areas, and carve out protected regions within writable areas. On Linux and Windows that also holds when the denyWrite entry is at or above the allowWrite one — allowWrite: ["/", "/work"] with denyWrite: ["/"] leaves /work read-only rather than writable — and with debug logging on (SRT_DEBUG) a warning names both paths.

Writes through links (Linux and macOS): a write is judged by where it lands, after symbolic links are followed. A link inside an allowed write path that leads out of it gives a command nothing: the write is refused. A link that leads into an allowed write path works like any other name for that place. A hard link is a second name for the file itself: on Linux a file outside the allowed write paths that already has a hard link inside one can be written through it, and a sandboxed command cannot create such a link. On macOS nothing is promised for such a file.

Read-side rules (Linux): an entry is matched by the name it is, not by what it points at.

Write denies on paths that do not exist yet (Linux): bubblewrap can only deny a path by mounting over it, so for a denyWrite path that is absent under a writable directory it first creates a mount point there: an empty, read-only file (or an empty directory for a missing intermediate component) that is visible on the host for as long as a sandbox is alive and is removed afterwards. Host tools therefore see such a path as existing while a sandboxed command runs, which matters for paths whose existence is their meaning (a lockfile such as `.git/con

sandbox-runtime (anthropics/sandbox-runtime)

Ищем в базе…

Что это такое?srt (Anthropic Sandbox Runtime) — это легковесный инструмент изоляции, который накладывает ограничения на доступ к файловой системе и сети для любых процессов на уровне операционной системы, без необходимости в контейнере. Он создан для безопасного запуска ИИ-агентов, локальных MCP-серверов и bash-команд.
Это CLI-инструмент или библиотека, которую я импортирую в код?И то, и другое: srt поставляется как отдельный CLI, который оборачивает любую команду, а также как пакет, который можно импортировать, чтобы встроить изоляцию в свой код на TypeScript/Node.
Как запустить команду внутри песочницы?Оберните любую команду в CLI srt (например, `srt -- your-command`). По умолчанию ограничения читаются из ~/.srt-settings.json, но можно указать другой файл с помощью флага --settings.
Нужны ли Docker или виртуальная машина для использования?Нет, среда контейнеров вообще не требуется: srt использует встроенные механизмы ОС — sandbox-exec на macOS, bubblewrap на Linux, а на Windows отдельную локальную учетную запись и фильтр исходящего трафика на базе Windows Filtering Platform. Это пакет Node.js, написанный на TypeScript (для работы нужен Node 20.11+).
Насколько это стабильно и готово ли к продакшену?Проект официально помечен как Beta Research Preview и создан для Claude Code. Авторы говорят, что API и форматы конфигурации могут еще меняться, и просят обратную связь, поэтому относитесь к этому как к ранней стадии.
Получает ли Windows такие же гарантии изоляции, как macOS и Linux?Не совсем тот же механизм: macOS и Linux используют настоящие песочницы уровня ядра (Seatbelt и bubblewrap), а Windows запускает процесс под отдельной локальной учетной записью srt-sandbox, с сетевым фильтром на уровне всей машины и файловыми ACL, действующими на время сеанса.
Зачем изолировать MCP-сервер?MCP-серверам по умолчанию часто выдается широкий доступ к файловой системе и сети. Если обернуть такой сервер в srt, можно ограничить его только теми путями и доменами, которые ему действительно нужны, например запретить запись за пределами разрешенной папки.
Как работают правила разрешения и запрета для сети?Доступ к сети работает по принципу «только разрешенное»: всё запрещено, пока вы не добавите домен в allowedDomains (поддерживаются подстановочные символы и необязательные суффиксы :port). При этом deniedDomains всегда имеют приоритет и могут содержать собственную причину блокировки, которая показывается заблокированному процессу.
Почему правила чтения и записи файлов устроены по-разному?Чтение работает по схеме «сначала запрет, потом выборочное разрешение»: всё доступно для чтения, пока вы не запретите, а затем выборочно разрешаете нужное. Запись устроена строже, по схеме «только разрешенное»: всё запрещено, пока явно не разрешено. Доступ на запись — это то, что нужно включать вручную для каждого пути.
Может ли он перехватывать HTTPS-трафик для фильтрации?Да, через экспериментальный режим терминации TLS: он выполняет MITM-перехват HTTPS CONNECT-запросов внутри самого процесса, чтобы SRT мог проверять и фильтровать расшифрованные запросы. Можно исключить домены, которые используют mTLS или закрепление сертификатов (certificate pinning).
Какие есть похожие проекты?agentbox, quicksand, deltabox-lite, qwen-code, NemoClaw, nono, box, SPACE
Автор
anthropics
Размер
11.1 MB
Звёзды
7.2K
Возраст
1 г
Коммиты · 90 дней