Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/sandbox-disable-storage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- Let TSX sandbox hosts deny access to NSGo storage (#2299 by @J4ck1e2000).
4 changes: 2 additions & 2 deletions docs/architecture/tsx.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Each `js.Runtime` on the web is a realm of its own, a hidden iframe of the page'
- Promise reactions and the browser's own callbacks run once Go gives the page its turn, after the engine's commit, not as the outermost call returns. What they call of Go runs under the app's root, untracked, and a commit follows (`engine_browser.go`). Goja's continuation tracker carries a plugin call's deadline across `await`. The page engine runs the continuation in a separate turn under the app root. `nsgotest`'s headless runs give the page its turn as they settle on the web.
- The page's `Intl` is the browser's; `intl.go` is goja's alone.
- The page's engine cannot be interrupted while JavaScript runs. `CallTotal` can drop NSGo's waiting work after control returns to Go. The browser supplies the stack depth, and sandbox hardening applies.
- A sandbox's realm is of the page's origin too, so its code reaches the page's own APIs past Go: `XMLHttpRequest`, `WebSocket`, `navigator` with the clipboard, `localStorage` and the page's window. Capabilities would hold only the requests the runtime and core make, and a package's storage partition and a `Trust` kept in the page's storage would be open to it, so a sandbox with `Capabilities` or a `Grant`, which `View` and `Load` always have, refuses to start with `ErrUnisolated` unless `Sandbox.WebUnisolated` gives it the page's authority. A sandbox with neither runs: it reaches what the app's code does on every target, and on the web its `Storage` partition and `Host` do not confine it either, since its code reaches the page's `localStorage` and the other realms through the page's window. Running packages isolated, in an opaque-origin frame or worker over an asynchronous bridge, is on the [roadmap](../roadmap.md#tsx-and-dynamic-delivery).
- A sandbox's realm shares the page's origin, so its code reaches the page's own APIs and trust store outside Go. A sandbox with `Capabilities`, `Grant` or `DisableStorage` refuses to start with `ErrUnisolated` unless `Sandbox.WebUnisolated` is set. That opt-in gives the bundle the page's authority even if its NSGo `Storage` is disabled. Running packages in an isolated frame or worker over an asynchronous bridge is on the [roadmap](../roadmap.md#tsx-and-dynamic-delivery).

## Compiling

Expand Down Expand Up @@ -187,7 +187,7 @@ Limits and checks are Go's, never JS's, since a bundle holds only the app's code
- **Imports.** A sandboxed bundle imports `SandboxModules`, NSGo's own, with what is registered into them `SandboxSafe()`: a component, part, class or static is hidden from sandboxes until its registration says so, so a new one reaches plugins only by a decision. Not so marked are `Terminal`, which starts programs, `Scrollbar.setTheme`, which restyles every scroll bar in the window, and the Go functions `RegisterFunctions` registers; the runtime's own `setColorScheme`, which forces every window's appearance, and `BackHandler.exitApp`, which leaves the app, are withheld too (`appWide`). Those, other modules and the embedding app's native components a bundle imports only as `Sandbox.Modules` names them (`myapp`, `nsgo/base.Terminal`, `nsgo/base.Scrollbar.setTheme`, `nsgo.setColorScheme`, `native:MapView`, `*`). `tsx/testdata/sandbox-surface.txt` lists what a default sandbox imports, its exports' members included, and a test fails when it changes. As a sandbox reads the registry when it first imports a module, `Register` and its kin panic once an app has started, and into the `nsgo` modules from a package outside NSGo's module, told by the caller's function name.
- **Host controls.** `Plugin.CallWithBudget` extends one waiting call's wall deadline on the engine goroutine, between VM entries. An expiration posted before the extension checks the current deadline. A sandboxed view applies `CallTotal` to events and the work they start. `Sandbox.OnViewRuntime` publishes an interruptible view handle before the entry script, leaving the view mounted on host interruption and reporting `ErrViewClosed` when normally disposed. The host reads native `JSTime` across completed and active Goja entries. Synchronous registered Go functions pause the measurement, and a nested JavaScript entry resumes it for as long as it runs. `ViewRuntime.EngineTime` additionally measures synchronous Go calls and the view's owned reactive, mounting, commit and layout work, including an active span. Core scopes switch attribution at ownership boundaries (`ObserveWork`, `BeginWork`); layout nodes carry the same optional hook, so nested work counts once and host or sibling work pauses the counter. Ordinary graphs install no observers. Waiting, shared commit bookkeeping and native drawing are excluded. The browser cooperatively drops future NSGo callbacks and provides neither counter.
- **The window around it.** Its key bindings and back handlers, `keymap`'s, `BackHandler`'s and its Go components' alike, fire only while the keyboard focus is on a view it shows (`Scope.Confine`), so `when: "always"` reaches only its own fields; a press they leave goes on to the host's. Nor does it take the focus on its own: a ref's `focus()`, `autoFocus`, `Keyboard.dismiss` and `setAccessibilityFocus`, its Go components' too, move the focus only while it is already in its view or as the user's input on its view is handled, until the commit after it ([keyboard focus](interaction.md#keyboard-focus)), so a timer cannot pull the host's keys and typing into it. It shows in a view of its own that the host's scope owns (`Sandboxed`), which grows into the room its parent gives it and shrinks to it, so it cannot grow over the host's views (in a scroll view it takes the scroll view's height unless the host puts it in a view of its own), and clips it: its views take no touch outside it, and its overlays, popovers, menus and toasts are hosted, sized and placed in it, so a host that gives it a small view gets small popups. What that view cannot clip, a dialog the platform presents, an alert or a context menu, and `announce`, wait for the same window as the focus; its overlays and navigation stacks hear back only while the focus is in it, and back closes a dialog it showed whether or not it removes the dialog.
- **Host and storage.** `Sandbox.Host` is the only host its `host` module reaches (`Scope.ProvideHost`), so the Go app answers a plugin's calls through a `core.Host` of the plugin's own and none of the app's handlers, which run outside the plugin's owner, held to the scope they call services on ([access](core.md#access)); a package's storage is a partition of the app's under its app ID (`Scope.ProvideStorage`), which the app's own `Storage` neither lists nor clears.
- **Host and storage.** `Sandbox.Host` is the only host its `host` module reaches (`Scope.ProvideHost`); the app's handlers run outside the plugin's owner and are held to the [scope they call services on](core.md#access). A package stores data in its own partition under its app ID (`Scope.ProvideStorage`), which the app's own `Storage` neither lists nor clears. `Sandbox.DisableStorage` makes the NSGo `Storage` methods throw `tsx: Storage is disabled for this sandbox` without accessing the partition. A zero `Limits.Storage` still means no byte quota.
- **Plugins of functions.** `tsx.Load` runs a package as `View` does, synchronously on the caller's goroutine in a scope attached to a view tree, without showing it, recovering what its entry module throws inside the scope's run so that it returns it rather than core sending it to a `Catch` or the app's report, and `Plugin.Call` calls what its entry module exports, the bundle's `__nsgo_exports` (`bundler.Compile`'s global name), resolving promises; arguments and results cross as JSON values, and what an export throws, at once or as a rejection, comes back as the same error: its message, as a `*core.Error` when it carries a `code`. A scope without a tree returns `tsx.ErrNoTree`.
`Plugin.Stopped()` and `Err()` read the first terminal reason under `stopMu`. Close and owner disposal record `ErrPluginClosed` after the plugin's cleanups if no earlier stop won. The engine fails waiting calls and invokes `Sandbox.OnStop` once. `Sandbox.OnError`, when supplied to `Load`, receives uncaught callbacks outside waiting calls on the engine goroutine. `callbackError` keeps nested JS throws on their JS catch path; `queueMicrotask` forwards its implementation promise’s rejected callback, and `reportError` uses the same plugin handler. A retained promise job’s native slice cut reports `ErrBudget` once after its owner’s call settled, without replacing the result of another call that drained it. Ordinary callback failures leave the plugin running for the host’s breaker to decide; entry, returned-call and view-boundary failures retain their existing routing.

Expand Down
4 changes: 3 additions & 1 deletion docs/public/en/tsx.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ trust.Accept(p) // once it ran, older builds are refused

`Sandbox.Grant` gives it less than it declares, `Sandbox.Limits` other time budgets and quotas, and `Sandbox.Modules` Go functions and components beyond NSGo's own. Its keyboard shortcuts, back handlers and navigation stacks take effect only while the keyboard focus is in its view, and it moves the focus itself (`focus()`, `autoFocus`, `Keyboard.dismiss`, `setAccessibilityFocus`) only while the focus is already there or in answer to the user's press in it. It shows in a view of its own that fills the room its parent gives it, no more, and clips it, menus, popovers and toasts included; in a scroll view, put it in a view to let it take its content's height. A dialog, an alert, a context menu or an announcement of its shows only in the same way, and back closes a dialog of its even if it does not remove it. `View.Export` names a component the package's entry module exports, shown in place of the root the entry mounts, whose `mount` then neither renders nor runs its component, and given `View.Props`, a JSON-encodable map copied for each view, so one package provides several views, each with state of its own, under the same capabilities and limits; a missing export panics with `tsx.ErrNoViewExport` and one that is not a function with `tsx.ErrViewExportNotComponent`. A package whose entry exports functions is a plugin of functions: `tsx.Load(cx, p, tsx.Sandbox{})` runs it unseen and synchronously on the caller's goroutine, under a `cx` that belongs to a view tree (without one it returns `tsx.ErrNoTree`), or returns what its entry module threw as it loaded, and `Plugin.Call` calls them. `go tool nsgo dev -limits` runs an app as such a view would, and `go tool nsgo revoke` signs a list of revoked release keys and packages for `Trust.UpdateRevocations`. `examples/plugins` asks the user to grant a package's capabilities, installs it and runs it. `Limits.Memory`, 64 MiB by default, budgets metered native storage for arrays, strings, buffers, and typed arrays. This includes `concat`, `flat`, `slice`, array spread, string concatenation, templates, `replace`, `replaceAll`, `TextEncoder`, and `Blob` copies. `memory=<bytes>` in `-limits` changes the budget, and `memory=0` turns it off. Checks run before allocation. A package exceeding the budget stops with `ERR_NSH_QUOTA_EXCEEDED` and resource `memory` after Go has checked for collectible storage. Ordinary objects, closures, stacks, small allocations, and unmetered built-ins and host APIs can also allocate. The browser keeps its own heap. An app that signs packages itself with `pkg.Build`, or `go tool nsgo publish -extra <file>` with that file's bytes, can put metadata of its own in `pkg.Contents.Extra`, such as what a plugin adds to its menus: it is signed with the package, and `Verify` returns it unchanged as `p.Extra` for the app to parse, so the app reads it without running the package's code.

Set `Sandbox.DisableStorage` to `true` to deny all reads and writes through `Storage` from `nsgo`. Each method throws an `Error` with the message `tsx: Storage is disabled for this sandbox`; existing data is left alone. A zero `Limits.Storage` still means no byte quota.

An app can sign its own JSON documents, such as a catalog of its plugins, with `pkg.SignDocument` and verify them with `Signed.Open`, with the keys `nsgo keygen` prints. Give each kind of document an `app:` context of its own with a version, as `app:catalog-v1`: a document never passes for another kind, nor for a package, certificate or revocation list. `Open` trusts exactly the public keys it is given, with no certificate or revocation list, and refuses body fields the type it decodes into lacks. The envelope holds no time or sequence, so an older document verifies as well as a newer one: put a version or expiry in the body and check it.
In a native sandbox, `JSON.stringify`, `JSON.parse` with a reviver, `Array.prototype.join`, `toString`, `toLocaleString` and `flat`, and so `String()` of an array, throw a catchable `RangeError` once they go more than 1,000 levels deep, counting one inside another, as an array's `toString` and the `join` it calls each count; deeper data would hang the call or end the app. The web uses the browser's built-ins.

Expand All @@ -138,7 +140,7 @@ Set `Sandbox.OnViewRuntime` to receive each view's `*tsx.ViewRuntime` on the eng

`Plugin.JSTime` and `ViewRuntime.JSTime` report the elapsed time spent in the native runtime's JavaScript entries, including the current entry. Waiting between entries and time inside registered synchronous Go functions are excluded. `ViewRuntime.EngineTime` also includes synchronous Go calls and owned reactive, mounting, commit and layout work, including work still running. It excludes waiting between engine entries, work belonging to the host or another view, shared commit bookkeeping and native drawing. Both counters are safe to read from any goroutine. The browser's JavaScript turns outside NSGo cannot be measured or preempted. There both counters report unavailable and `Interrupt` stops future NSGo callbacks when the host regains control.

The web cannot isolate a package from the page yet: its code would reach the page's own network, clipboard and storage, the trust store's included, past its capabilities. There `tsx.View` and `tsx.Load` refuse a package with `tsx.ErrUnisolated`, unless you set `Sandbox.WebUnisolated` to run it with the page's authority, which suits only packages you would trust with the app's own.
The web cannot isolate a package from the page yet: its code has the page's network, clipboard and storage authority, including the trust store. `tsx.View` and `tsx.Load` refuse packages there with `tsx.ErrUnisolated` unless you set `Sandbox.WebUnisolated`; a custom `tsx.Sandboxed` with capabilities or `DisableStorage` also requires that opt-in. It does not restore disabled NSGo `Storage` or protect the page's own storage. Use it only for code you trust with the app's own authority.

## Editors and tests

Expand Down
Loading
Loading