@enclave-vm/browser implements defense-in-depth through a double iframe architecture. Each execution creates two nested iframes — an outer security barrier and an inner sandbox — with 8 distinct security layers that work together to prevent sandbox escapes.
The layers do not all stand on their own. Some are enforced by the browser, some by the host page, and some hold only for a script the validator has accepted: What Each Guarantee Rests On says which is which, and Timeouts and the Browser’s Process Model says when a script that never yields can be stopped.
Double Iframe Architecture
- Host Page: Your application. Creates the outer iframe and handles tool calls.
- Outer Iframe: Security barrier with rate limiting, pattern detection, and name filtering. Relays validated messages between host and inner iframe.
- Inner Iframe: The actual sandbox. Contains prototype hardening, secure proxies, safe runtime wrappers, and the user code.
The 8 Security Layers
Layer 1: Content Security Policy
Both iframe documents carry a strict CSP in a<meta> tag:
The outer document’s policy names two scripts: its own and the inner document’s. A document that a frame creates inherits the policy of its creator, so the inner document is bound by both policies, and every document the inner frame could create is bound to the inner document’s one script. Nothing but the two scripts the package wrote runs in any document of the sandbox, and no worker starts.
The policy has no say over a peer connection (WebRTC). The names that create one are removed from the inner frame instead: see Layer 4.
Layer 2: Iframe Sandbox Attribute
Both iframes use a restrictive sandbox attribute:allow-scripts is enabled. Crucially, allow-same-origin is not set, which means:
- The iframe cannot access the host page’s DOM, cookies, or storage
- The iframe cannot read
parent.documentortop.document - The iframe has a unique
nullorigin
Layer 3: Outer Frame Validation
The outer iframe acts as a security barrier between the host and the inner sandbox. All tool calls from the inner iframe pass through validation:Layer 4: Dangerous Global Removal
Dangerous globals are deleted from the inner iframe’swindow object based on the security level:
Always removed (all security levels):
fetch, XMLHttpRequest, WebSocket, EventSource, Worker, SharedWorker, ServiceWorker, importScripts, localStorage, sessionStorage, indexedDB, caches, navigator (also under its other name, clientInformation), open, close, alert, confirm, prompt, and the peer-connection constructors (RTCPeerConnection and its prefixed aliases).
The peer-connection constructors open a connection that the document policy does not govern. They are removed at every security level and for every preset, the object behind the name is made unusable as well (its members throw TypeError: Network connections are not available in this sandbox, and it is frozen), and a run whose frame still has one of the names is not started (SANDBOX_SETUP_FAILED).
The frame’s document is closed. A node that is part of a document can make the browser load something, and not every such load is a request the document policy governs. A script has no use for the document of the frame it runs in (the frame is never shown), so before a script starts the inner frame’s document is emptied, and every member of the prototypes a document gets its behaviour from, and of Range, throws TypeError: The document of this sandbox frame is not available. With no node in the document and no way to add one, nothing a script builds is ever part of a document: no element loads anything, and no frame is created. This holds at every security level and for every preset.
What cannot be removed: a page’s window, document, location and top are properties the browser does not let a script delete or replace. The name document is shadowed in the scope a script runs in, and the validator refuses all four names and every other name it does not know, so a validated script cannot reach them. This layer removes names and closes the document; it is the validator that keeps a script from naming the window the names were removed from.
Layer 5: Prototype Freezing
All built-in prototypes are frozen after security patches are applied:Object.prototype,Array.prototype,Function.prototypeString.prototype,Number.prototype,Boolean.prototypeDate.prototype,Error.prototype,Promise.prototypeTypeError.prototype,RangeError.prototype,SyntaxError.prototypeReferenceError.prototype,URIError.prototype,EvalError.prototype
__lookupGetter__, __lookupSetter__, __defineGetter__, __defineSetter__) are replaced with no-ops on Object.prototype. Error prototypes have __proto__ shadowed to return null.
Regular expressions
AgentScript has no regular expressions: the validator refuses a literal, theRegExp name and the methods that run a pattern. When a script is validated with the agentscript preset (the default), its realm cannot run one either:
exec,test,compileand theSymbol.match/matchAll/replace/search/splitmethods ofRegExp.prototypethrowTypeError: Regular expressions are not available in this sandbox, and the prototype is frozen. Every regular expression of the realm reaches its matcher through these, including the one the engine builds from a string formatch,matchAllandsearch.- The names
RegExpandURLPatternare removed from the realm.
split(','), replace('a', 'b'), includes, indexOf) are not affected. With another preset, or with validate: false, regular expressions work as in any page. @enclave-vm/core applies the same rule with its realm allowlist.
Layer 6: Secure Proxy
Every global object exposed to user code is wrapped in aProxy that blocks access to dangerous properties:
The proxy behavior is configurable per security level. At
STRICT and SECURE levels, accessing blocked properties throws an error. At PERMISSIVE, it returns undefined.
Custom globals are serialized into the inner frame’s bootstrap, so sandboxed code only ever sees plain data for them — no live outer-page object crosses the frame boundary.
Additionally, dangerous static methods on Object are neutralized: defineProperty, defineProperties, setPrototypeOf, getOwnPropertyDescriptor, and getOwnPropertyDescriptors.
Layer 7: Safe Runtime Wrappers
User code runs through transformed wrappers that enforce resource limits:
The iteration limit is per loop: each loop may run
maxIterations passes every time it is entered, so nested loops multiply, and the callbacks a built-in drives (map, forEach, sort) are not counted. It stops a loop that does not end; it is not a bound on the work a script does. That bound is the timeout: see Timeouts and the Browser’s Process Model.
This is the AgentScript transform alone. @enclave-vm/core applies three more steps after validation that the browser does not: the guard on property keys known only at run time, the deadline checks inside functions and loops, and the tracking of string concatenation. The frame also defines __safe_concat and __safe_template for code transformed elsewhere; the browser’s own transform does not emit them.
Layer 8: Memory Tracking
Memory-intensive operations are patched to track estimated usage:
When the cumulative tracked memory exceeds
memoryLimit (default: 1MB), a RangeError is thrown. An estimate that is not a positive number counts as nothing, so a call with a missing, non-numeric or negative size neither switches the accounting off nor gives back what was charged before; and when a call builds more than was estimated, the difference is charged afterwards.
Message Protocol
All communication between layers usespostMessage with validated messages. Every message includes a __enclave_msg__: true discriminator and a requestId for correlation.
Message Types
What the Host Checks
The host page does not take the iframes’ word for anything. It listens only to the outer iframe of the execution it started, and every message from it is validated against a Zod schema before it is acted on. A message that does not match (an unknown type, a missing or extra field, a tool name that is not a string of 1–256 characters, arguments that are not an object, the id of another execution) ends the execution withPROTOCOL_VIOLATION and removes the iframes.
The limits that protect the host are enforced by the host as well as inside the sandbox:
- Tool calls: no more than
maxToolCallsreach your tool handler, and a tool name thatallowedOperationPatternorblockedOperationPatternsrefuse does not reach it. The function-basedsuspiciousPatternsof your configuration are asked here as well, for every call that got this far. - Tool arguments: the handler receives a copy made by the host, of JSON data only (strings, finite numbers, booleans,
null, arrays without holes and plain objects), without__proto__,constructororprototypekeys at any depth. Arguments that hold anything else end the execution. A call whose arguments hold more than 1,000,000 array items and object keys is refused (the script’scallToolrejects) and the handler is not called. - Results: a returned value is copied into plain host data (primitives, arrays, dates and plain objects, within
maxSanitizeDepthandmaxSanitizeProperties); anything else ends the execution. Error texts are cut to a bounded length. - Console: no more than
maxConsoleCallslines andmaxConsoleOutputBytesreach the host console. The host copies each line, counts it by the JSON text of that copy, and prints the copy. A line that holds anything but plain data (strings, numbers, booleans,null,undefined, arrays and plain objects, at most 100 levels deep) is dropped and still counts as a call. The sandbox sends objects as their JSON copy and a BigInt, symbol or function as its text.
PROTOCOL_VIOLATION by itself. What the host would refuse as a broken protocol (a tool name that is too long, arguments that are too deep or are not an object, a result beyond its limits) the inner iframe refuses first, as an ordinary error the script can catch.
What Each Guarantee Rests On
The inner iframe is a document, and a script is part of the same piece of code as the logic that sets the sandbox up. Four different things keep a script in place (the browser, what the inner frame does before a script starts, the host page, and the validator), and it matters which one a property depends on:
With
validate: false (or a preset other than agentscript together with transform: false) a script has the inner frame’s window to itself: it can read and change the variables of the sandbox’s own code, including the limits and counters kept there, it can post messages as the frame, and it can learn the origin of the page that embeds the sandbox. What still holds is what the browser, the closed frame and the host page enforce, the first six rows. Run code you do not trust with validation on.
The network rows were measured in Chromium 145, in the headless shell and in the full build, with a listener on the local machine for each kind of request. Firefox and Safari have not been measured.
Custom globals and tool namespaces reach a script as parameters of the function it runs in, so a configured name means the host’s value even when the frame’s window or the sandbox’s own code has something of the same name.
Timeouts and the Browser’s Process Model
The timeout is kept by timers: one in the outer iframe for the script’s own running time, and two in the host page (the hard stop attimeout plus parentTimeoutBuffer, and the bound on a tool call that is in progress then). A timer fires between tasks, and the two frames share one thread. A script that computes without yielding (a long loop, a chain of callbacks) holds that thread, and the outer iframe’s timer cannot fire until it yields.
What ends such a script is the host page’s hard stop, which removes the frames. That works where the browser runs the sandboxed frames in a different process from the page:
Firefox and Safari have not been measured. There is nothing a page can do to interrupt a script that shares its thread, so where that is the case the timeout bounds a script that waits (for a tool, for a promise) and not one that computes. The per-loop iteration limit narrows what a script can do in one loop; it does not bound nested loops or callbacks.
@enclave-vm/core, on a server, checks the deadline inside the script’s own loops and functions and does not depend on a timer for this.
With the default toolCallGraceMs, run() returns within about three times timeout plus parentTimeoutBuffer where the timers can fire: tool calls may be in progress for timeout, the buffer and the grace, and the script’s own running time is bounded by timeout on top of that.
What’s Blocked
What’s Available
Sandboxed code has access to a safe subset of JavaScript:Related
- Overview - Getting started with browser enclave
- Configuration - All configuration options
- Double VM Layer - Node.js equivalent architecture
- Security Levels - Security preset details