Docs

Sandbox and Capabilities

An app written in Rust is native code compiled into the app that ships it, as the rest of that app is, and runs with its trust; its calls into NSH’s services (fetch, images, web views, the status bar) go through the same native checks as TSX’s, under what a host grants. The TSX and JavaScript an app runs, its own or a signed package it downloads, run in a QuickJS VM per view, and everything they can do outside that VM goes through NSH’s native runtime. That makes it possible to run code you did not write, such as third-party mini apps or downloaded updates, under rules the host app controls:

  • Limits bound the memory, time and native resources one app can use.
  • Hardening removes the ways to turn strings into code in release builds.
  • Capabilities list what an app may reach: which hosts it may fetch from, which pages a web view may show, whether it may change the status bar. The app declares them; a host app may grant less.

A bundle holds only the app’s code: the reactive graph, the renderer and every module the app imports are native. So nothing in JS is trusted, and every limit and check is enforced in Rust; there is no JS code an app could patch to get around them.

#Limits

Limits bound a VM: they apply to TSX and JavaScript. An app embedded in another app runs within limits its host app decides. An app on its own (packaged with nsh package, the web included, or run with nsh run) is your own code, as a native app is: it uses the memory and time the device gives it, and its interpreter stack of 4096 KB turns deep recursion into a RangeError the app can catch.

An embedded app has these limits:

Limit Default When it is hit
JS heap 256 MB The VM stops.
Interpreter stack 4096 KB (also the maximum) Deep recursion throws a RangeError, which the app can catch.
Time to evaluate the bundle 10 s The evaluation is cut off.
Time of any other call into JS 2 s The call is cut off; the app goes on.
Nodes kept 200 000 The VM stops.
Changes at once (queued operations) 8 000 000 values The VM stops.
Operations in one canvas drawing 1 000 000 The VM stops.

Time is budgeted per call, not per app. A “call” is one thing the runtime asks JS to do: handle one event (including the rendering it causes), bind one list row, run one timer, run one frame’s requestAnimationFrame callbacks, drain the microtask queue. A long-running app never accumulates time toward a limit; only a single call that does not return in time is interrupted. Calls nested inside another share the outer call’s budget. A call is charged the time it runs: its thread’s CPU time on Linux, Android, macOS and iOS, monotonic time on Windows and the web. Time the system keeps the app frozen or suspended in the background, or waiting for a CPU, is not the call’s.

An interrupted call ends with an exception that no catch can swallow, and the error is reported with the budget it exceeded:

the script was interrupted: a call into JS exceeded its budget of 2000 ms

The VM keeps running: the next event, timer or frame runs normally.

Running out of memory or going over a quota stops the VM. The error is reported once (to the host app’s error handler, and in development builds over the app), no JS runs after that, and the views stay as they were. The node and operation quotas exist because native views and queued changes live in native memory, which the JS heap limit does not cover: without them, an app could exhaust the device’s memory through the UI.

Arrays NSH reads natively hold up to 2^20 (1 048 576) items, in every app. Children (nested arrays counted together), <Each>’s items, menus (submenus counted together), a tray’s title, Animated.sequence / parallel / stagger, split’s keys, a navigation stack’s routes, a native component’s props and events and the values it is given, a pan’s touches, a canvas call’s arguments, a style (its nested styles, shadows and transforms), a prop’s lists, an animation’s ranges and easing and the animations a composite runs (each counted together) are read in native code, beyond the call budget’s reach, and an array is as long as it says, empty or not (new Array(2 ** 32 - 1)). A longer one throws an error the app can catch: a RangeError, a TypeError for a menu or the tray; an animation’s start rejects its promise; a canvas call ignores it with a warning. A navigation stack holds up to as many screens: push beyond that throws a RangeError. Children, submenus and styles nested more than 64 levels deep throw a TypeError. A <List>’s each takes any number of rows.

Host apps set the limits per view: NshAppView.limits on iOS, NshView.setLimits on Android, AppOptions::limits / AppView::set_limits in a GPUI app. They apply from the next load.

To see in development what a TSX app does within a host app’s limits, run it with --limits: nsh run App.tsx --limits uses the defaults above, and nsh run --limits memory=128MB,call=500ms sets those two as a host app would, the rest keeping their defaults.

#Hardening

Release builds (everything not loaded from a dev server) are hardened when they load:

  • eval is removed, and the Function, AsyncFunction, GeneratorFunction and AsyncGeneratorFunction constructors throw. NSH runs no code made from strings:

    TypeError: the Function constructor is disabled: nsh runs no code from strings (development builds allow it)
  • The prototypes all modules share (Object, Array, Function, String, Number, Promise, Map, typed arrays and the rest) are frozen, so one module (or one library) cannot change Array.prototype for everyone else. Error.prototype stays writable, so error subclasses can set this.name.

Freezing prototypes would normally break a common pattern, the “override mistake”: assigning Sub.prototype.constructor = Sub or obj.toString = … throws when the inherited property is frozen. NSH turns the commonly overridden members (constructor, toString, valueOf, toJSON, …) into accessors whose setter defines the property on the object assigned to, so such code (and libraries like axios that use it) keeps working.

Bundles served by nsh dev / nsh run (with or without --release) are not hardened, so you can debug with eval. Test the release behavior with nsh test (which hardens) or a packaged build before shipping code that relies on dynamic code.

#Capabilities

An app declares what it may reach outside its VM in nsh.json:

{
  "name": "Quotes",
  "id": "com.example.quotes",
  "version": "1.0.0",
  "build": 3,
  "capabilities": {
    "network": {
      "hosts": ["api.example.com", "*.cdn.example.com"],
      "http": [{ "host": "quotes.example.com", "methods": ["GET"], "pathPrefix": "/v1/" }],
      "sockets": ["feed.example.com:7000"]
    },
    "webview": { "hosts": ["*.example.com"], "input": true },
    "statusBar": true,
    "clipboard": true,
    "picker": true,
    "share": true,
    "speech": true,
    "notifications": true,
    "audio": true,
    "application": true,
    "homeDir": true,
    "host": ["getUserInfo", "bridge.*"],
    "openUrl": { "schemes": ["https", "mailto"] },
    "windows": { "kinds": ["normal", "dialog", "panel"], "max": 4 }
  }
}

An app without "capabilities" may do everything: a standalone app is its developer’s own, and nothing is restricted. Raw TCP sockets are granted by name in every app, through network.sockets, and the host’s functions through host. An app with "capabilities" may do only what it lists: everything else is denied. A key or value NSH cannot read grants nothing: the build warns of it, so a typo shows up when you build instead of as a missing permission at runtime. A signed package from a newer NSH may declare capabilities an older runtime does not know: they are not granted there.

#network

Covers fetch (including every redirect), WebSockets, remote images (<Image>, placeholder, canvas images, Image.getSize / Image.prefetch), video and sound sources and raw TCP sockets (net.connect).

Key Type Description
hosts string[] Hosts the app may reach with any method and scheme (http, https, ws, wss).
http object[] Finer grants: a host, narrowed by any of the keys below.
http[].host string The host or host pattern (required).
http[].methods string[] Allowed methods, such as ["GET", "HEAD"]. Missing: any.
http[].schemes string[] Allowed schemes (scheme: one, as a string). Missing: any of http, https, ws, wss.
http[].port number The port; a URL without one has its scheme’s default (443 for https). Missing: any.
http[].paths string[] Exact paths, such as ["/v1/quote"] (the query is not part of the path).
http[].pathPrefixes string[] Path prefixes covering whole segments: /v1 covers /v1 and /v1/quote, /v1/ what follows it. pathPrefix (one, as a string) and path_prefixes read the same.
sockets string[] Raw TCP destinations for net.connect, each an exact "host:port" ("[::1]:9000" for IPv6).

An http rule covers every path when it lists no paths or pathPrefixes, and with both a path matching either.

Paths are matched as the request sends them, after WHATWG’s URL parser resolves dot segments, percent-encoded ones too: /v1/../admin and /v1/%2e%2e/admin are /admin, which pathPrefix: "/v1" does not cover. The request goes out with the URL that was checked, so the server receives the path the rule matched. A rule’s own paths are read the same way: /my photos covers /my%20photos, and a path with a . or .. segment is an error. An encoded / or \ (%2F, %5C) stays as written, so /v1/x%2F..%2F..%2Fadmin is under /v1; a server that decodes them before it resolves dot segments serves another path.

Host patterns are * (any host), *.example.com (any subdomain of example.com, not example.com itself) or an exact host name. Matching ignores case and the port. The host is taken after the last @, so https://api.example.com@evil.io/ is checked as evil.io. A URL that platforms read as different hosts or paths is granted only by * in hosts (or a * rule with no port or path): one with a backslash before its query (write %5C), a control character, or a host with percent-encoding or a character hosts cannot contain (a space, <, >, ^, |, or [ / ] outside an IPv6 address).

A WebSocket handshake is an HTTP GET: ws:// is checked as http:// and wss:// as https://, so the hosts and http grants that allow a GET of the URL allow the WebSocket. A raw socket reaches past every HTTP rule, so sockets lists each host and port exactly, and only sockets grants them.

asset: URIs (the app’s own files) are always allowed while their path stays inside the app’s files, as fetch’s do: no empty, . or .. segment, encoded or not, and no backslash, colon or encoded /. Images, videos and sounds may also use data: and blob: URIs. A relative path is the page’s on the web; a native app has no page, so for an app with capabilities it loads nothing there (a sound’s relative path is a bundled file). A source that starts with // names a host: on the web it takes the page’s scheme and is checked as that URL; in a native app it has no page to take a scheme from, so it loads nothing (write https://…). Any other source with a scheme is checked as a URL, and loads what was checked. Spaces and control characters around a source are dropped, as the URL parser drops them, and the cleaned URL loads. A source that platforms read differently (a backslash, a control character, tab or newline inside it, an unusual host) is granted only by * and loads as written (in a native app, one that starts with // then loads nothing).

A local file in a media source (a file: URL, or in a native app an absolute path such as /Users/a/x.png or C:\pictures\x.png) is read under the fs capability’s read roots, as fs/promises reads files, and so only on the desktops. Its symlinks are resolved when the source is set, and the platform loads the resolved path, so a link inside a granted root then does not lead out of it; a link made there later is followed while the source stays set. On the web, /x.png is the page’s own path. An app without capabilities loads local files as before.

#webview

Key Type Description
hosts string[] Hosts a web view may show and navigate to (http and https). Without webview, the app may not show web pages at all.
input boolean A web view’s ref may give its page trusted input (sendInput). Never granted unless declared, also for an app without "capabilities".
media string[] What web pages may capture with getUserMedia: "microphone", "camera". Never granted unless declared, also for an app without "capabilities".

Top-level navigations inside the web view are checked too, by the platform’s navigation delegate, before they load. The page’s own subresources (its scripts, images, XHRs) are the web content’s business and are not checked. about:blank and inline HTML (html) need only web views to be granted at all: "webview": { "hosts": [] } allows them without allowing any remote page. A baseUrl gives inline HTML that URL’s origin in the native web views, so the base URL needs the grant a page there would: its host in hosts.

A page may show and download a blob: URL it made (URL.createObjectURL, a <a download> link): a blob URL embeds the origin of the document that made it, so it is allowed when that origin is a host in hosts, and a blob of a host the page may not show — or an opaque one (blob:null/…) — is not. Every platform checks this the same way.

input is separate from hosts because trusted input carries user activation, which injectJavaScript never gets: the page may then open windows, write the clipboard, open the system’s file panel, start WebAuthn or permission prompts and press any button that checks isTrusted. Without it the core drops sendInput and logs which key to add.

media answers the web view’s own media capture requests: those for a declared kind are allowed on macOS, iOS, Android, Windows and Linux, and the rest are denied. The system still asks the user the first time, so packages declare what it needs: nsh package writes NSMicrophoneUsageDescription / NSCameraUsageDescription (word them your own way with ios.infoPlist / macos.infoPlist), the macOS com.apple.security.device.audio-input / com.apple.security.device.camera entitlements, and Android’s RECORD_AUDIO / CAMERA permissions, which the app asks for when a page first needs them. Pages need a secure context (https: or localhost) for getUserMedia.

{ "capabilities": { "webview": { "hosts": ["phone.example.com"], "media": ["microphone"] } } }

#statusBar

"statusBar": true lets the app change the status bar (the statusBar of pages and dialogs in nsh/base, and nsh.json’s "statusBar" default).

#clipboard

"clipboard": true lets the app read and write the system clipboard (Clipboard). Copying from a selectable text’s edit menu is the user’s own act and needs no capability.

#picker

"picker": true lets the app show the system’s picker for photos (Picker): the user picks what reaches the app.

#share

"share": true lets the app show the system’s share sheet (Share): the user chooses where the content goes. A shared file must also be readable under fs.read.

#speech

"speech": true lets the app recognize what the user says (Speech): the microphone and the system’s speech recognizer, whose transcript reaches the app. The system still asks the user once.

#audio

"audio": true lets the app make sound (Sound and AudioPlayer). A remote source also needs a network grant for its host.

#notifications

"notifications": true lets the app show system notifications and set its icon’s badge (Notifications). The system still asks the user once, where it asks.

#application

"application": true lets the app act on the application as a whole on the desktop (nsh/desktop): the main window (currentWindow() outside any <Window>, Window.get("main"): its title, title bar, mode, frame and level, bringing it to the front, closing it), the application menu (Menu.setApplicationMenu), the tray, global shortcuts, Application.quit(), Application.restart() and Application.setLaunchAtLogin(). Without it they do nothing, Application.launchAtLogin() resolves false and setLaunchAtLogin rejects with ERR_ACCESS_DENIED (permission "application"). Context menus (Menu.popup) show in the app’s own view, and windows the app opens are granted by windows, so neither needs it.

#homeDir

"homeDir": true lets os.homedir() tell the user’s home directory; without it the call throws an error with code ERR_ACCESS_DENIED. The path is only a name: reading or writing there still needs fs grants.

#openUrl

Lets the app open URLs outside it (openUrl, a TextView’s links with links="open"): "openUrl": true for every scheme, "openUrl": { "schemes": ["https", "mailto"] } for the schemes listed. A URL whose scheme is not granted rejects with ERR_ACCESS_DENIED (permission "openUrl", resource the URL). URLs that would run code or reach the app’s own data (javascript:, data:, file:, …) are never opened, whatever the capability.

#windows

Lets the app open windows of its own on the desktops (Window): "windows": true for every kind but overlays, or an object that narrows it:

Key Type Description
kinds string[] The kinds it may open: "normal", "dialog", "panel", "popup", "overlay". Missing: every kind but "overlay".
levels string[] The levels its windows may float at: "normal", "floating", "aboveDock", "desktopIcon". Missing: every level.
max number How many windows of its own may be open at once. Missing: any number.
overlay boolean Overlays and click-through windows (pointerEvents: "none"). Never granted unless declared, also for an app without "capabilities".

overlay is separate because a transparent, click-through window above every other can pass for the system’s own UI. The main window needs no grant.

#Storage

Every app may keep its own data on the device with Storage, with no capability: the storage holds only that app’s data, and the embedding app decides where it is kept.

#host

host lists the functions of the app embedding NSH that nsh’s host.call(name, args) may call: exact names ("getUserInfo") or prefixes ending in * ("bridge.*" matches bridge.call and bridge.share). "host": true allows every function. A function not listed is refused, also in an app without "capabilities": the host’s functions are never granted by default, and building an app that imports host from nsh without host warns that every call will be refused. Names are 1 to 128 characters from A–Z, a–z, 0–9, _, ., : and -, without ..; the call of any other name is refused before the grants are read. End a prefix with a separator ("bridge.*"): "bridge*" matches bridgeAdmin too. The host’s events (host.on(event, listener)) reach the app’s listeners as the host sends them.

import { host } from "nsh";

if (host.available()) {
  const user = await host.call("getUserInfo");
  const stop = host.on("loginChanged", (payload) => console.log(payload));
  stop();
}

host.available() is true on platforms that embed a host; elsewhere host.call rejects with code "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM".

#What a refusal looks like

Request Result
fetch The promise rejects with a TypeError, as every failed request, whose code is ERR_ACCESS_DENIED, permission "network" and resource the URL (the request’s, or the redirect’s); the request never reaches the network.
Image.getSize, Image.prefetch The promise rejects with ERR_ACCESS_DENIED, permission "network" and resource the URL; the image is never requested.
Remote image, video source, web view source or html Nothing is shown, and the element’s onError reports it with code "ERR_ACCESS_DENIED". A web view’s navigation to a host not granted is cancelled and reported the same way.
Status bar change, canvas image Nothing changes or is drawn; the refusal is logged.
Clipboard Every function of Clipboard rejects with ERR_ACCESS_DENIED, permission "clipboard" and resource ""; the system clipboard is never touched.
Picker pickImages and pickFiles show nothing and reject with ERR_ACCESS_DENIED, permission "picker" and resource "".
Share Share.available() resolves false and Share.show shows nothing and rejects with ERR_ACCESS_DENIED, permission "share" and resource "".
Speech Speech.start throws ERR_ACCESS_DENIED, permission "speech" and resource ""; the microphone stays off.
Sound Sound.load rejects and new AudioPlayer throws ERR_ACCESS_DENIED, permission "audio" and resource the source; nothing is read or played.
Notifications Each function of Notifications rejects or throws ERR_ACCESS_DENIED, permission "notifications" and resource ""; nothing shows.
openUrl The promise rejects with ERR_ACCESS_DENIED, permission "openUrl" and resource the URL; nothing opens.
Host call host.call rejects with ERR_ACCESS_DENIED, permission "host" and resource the function’s name (host.post throws it); the call never reaches the host.
Files (fs/promises) The promise rejects with ERR_ACCESS_DENIED, permission "fs" and resource the path; the disk is never touched.
Processes (process) run rejects, and spawn and exit throw, with ERR_ACCESS_DENIED, permission "process" and resource the command ("exit" for exit); no child starts.
TCP socket (net.connect) The promise rejects with ERR_ACCESS_DENIED, permission "network" and resource the "host:port", before any DNS lookup.
Window (Window.open, <Window>) Throws ERR_ACCESS_DENIED, permission "windows" and resource the window’s id; nothing opens. An attribute of set() not granted is left as it is, with a warning.
WebSocket The websocket module’s connect rejects with ERR_ACCESS_DENIED, permission "network" and resource the URL; the global WebSocket fires error and then close (code 1006), as a connection that fails does.

The errors of the standard modules carry code "ERR_ACCESS_DENIED", so an app tells a refusal apart from a failed operation, and their permission and resource name the capability and what was asked for. The modules of nsh refuse the same way: their promises reject with ERR_ACCESS_DENIED, permission and resource (fetch with a TypeError, the class of every failed request).

import { Clipboard } from "nsh";

try {
  await Clipboard.writeText(link);
} catch (error) {
  if (error.code !== "ERR_ACCESS_DENIED") throw error;
  console.warn(`${error.permission} is not granted`); // "clipboard"
}

Rust components get the same refusals in Rust’s terms: a refused clipboard read answers what an empty clipboard does, a refused pick no files, a refused open_url false and a refused fetch an Err with the message.

Each refusal is logged once, saying which key to add:

fetch GET https://evil.example.org/x is not granted: add `evil.example.org` to capabilities.network in nsh.json

Redirects are followed by NSH, not by the platform’s HTTP stack, so every hop is checked against the capabilities. (A streamed request body is not sent twice, so a 307 / 308 redirect of a streamed upload fails.)

#Where capabilities travel

The declaration goes with the app wherever it goes:

  • nsh build and nsh package write it next to the bundle as capabilities.json;
  • nsh publish puts it in the signed package header, covered by the signature;
  • nsh dev sends it with every build, so development enforces the same rules. Changing capabilities reloads the app instead of hot-patching it;
  • an app whose root is a Rust component ("root" in nsh.json) has it compiled in with the root, so every runner, the web and nsh test included, checks the app’s calls against it, as a TSX app’s. Without "capabilities" it reaches what any app without a declaration does.

#Grants: what a host app allows

A host app that embeds NSH can grant at most some capabilities, in the same JSON form:

// iOS, in Rust (nsh_platform_ios::AppView)
let grant = nsh_engine::Capabilities::from_json(&serde_json::json!({
    "network": { "hosts": ["api.example.com"] }
}))?;
app.set_granted_capabilities(Some(grant));
// iOS
try app.grantCapabilities(#"{ "network": { "hosts": ["api.example.com"] } }"#)
// Android
nsh.setGrantedCapabilities("{ \"network\": { \"hosts\": [\"api.example.com\"] } }");

A request must be allowed by both the app’s declaration and the host’s grant. With the grant above, an app that declares "hosts": ["*"] can still only reach api.example.com, and cannot show web pages or change the status bar. Without a grant (nil / null, the default), what each app declares applies.

Grants apply from the next load. A typical setup for third-party mini apps: grant each one only its own API host, run it from a signed package whose declaration you reviewed, and keep the default limits or lower them.

#Summary

Layer Enforced by Set by
Limits (heap, stack, time, nodes) the runtime, per VM the host app per view (embedded apps)
Hardening the runtime, on load always on outside development
Capabilities the runtime (fetch, images, video, web views, status bar, windows, files, processes, sockets) the app (nsh.json) and the host app (grant)
Code integrity signature verification nsh publish; the host app’s trusted roots

#See also