From 5aadb13f515b27202ae077c162057a137d9d9444 Mon Sep 17 00:00:00 2001 From: "J4ck1e:)" Date: Tue, 24 Nov 2026 22:23:22 +0800 Subject: [PATCH] feat(tsx): allow sandbox hosts to disable storage Deny all NSGo Storage methods with an opt-in sandbox policy. Keep existing data and quota behavior, and enforce the shared-page isolation policy. Fixes #2299 --- changelog.d/sandbox-disable-storage.md | 3 + docs/architecture/tsx.md | 4 +- docs/public/en/tsx.md | 4 +- docs/public/zh/tsx.md | 4 +- skills/nsgo/SKILL.md | 1 + tsx/isolation_test.go | 3 + tsx/sandbox.go | 30 ++++++---- tsx/sandbox_test.go | 80 ++++++++++++++++++++++++++ tsx/services.go | 17 +++++- tsx/types/index.d.ts | 1 + 10 files changed, 131 insertions(+), 16 deletions(-) create mode 100644 changelog.d/sandbox-disable-storage.md diff --git a/changelog.d/sandbox-disable-storage.md b/changelog.d/sandbox-disable-storage.md new file mode 100644 index 000000000..764bef094 --- /dev/null +++ b/changelog.d/sandbox-disable-storage.md @@ -0,0 +1,3 @@ +### Added + +- Let TSX sandbox hosts deny access to NSGo storage (#2299 by @J4ck1e2000). diff --git a/docs/architecture/tsx.md b/docs/architecture/tsx.md index 26de85d7d..4c1b366a7 100644 --- a/docs/architecture/tsx.md +++ b/docs/architecture/tsx.md @@ -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 @@ -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. diff --git a/docs/public/en/tsx.md b/docs/public/en/tsx.md index 231d32985..ee6a10990 100644 --- a/docs/public/en/tsx.md +++ b/docs/public/en/tsx.md @@ -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=` 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 ` 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. @@ -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 diff --git a/docs/public/zh/tsx.md b/docs/public/zh/tsx.md index f6ed6e83f..de9185345 100644 --- a/docs/public/zh/tsx.md +++ b/docs/public/zh/tsx.md @@ -117,6 +117,8 @@ trust.Accept(p) // 运行之后,更旧的构建会被拒绝 `Sandbox.Grant` 让它得到比声明更少的权限,`Sandbox.Limits` 设置其他时间预算和配额,`Sandbox.Modules` 给它 NSGo 自带之外的 Go 函数和组件。它的快捷键、返回处理器和导航栈只在键盘焦点位于它的视图内时生效;它自己移动焦点(`focus()`、`autoFocus`、`Keyboard.dismiss`、`setAccessibilityFocus`)也只在焦点已在其中、或响应用户在其中的按压时才生效。它显示在自己的视图中,这个视图占满且不超出父视图给它的空间,并裁剪它的内容,菜单、弹出框和提示也在其中;放在滚动视图中时,用一个视图包住它,它才会按内容的高度显示。它的对话框、警告框、上下文菜单和读屏播报也只按同样的规则显示;即使它不移除自己的对话框,返回也会关闭它。`View.Export` 指定包的入口模块导出的一个组件,显示它而不是入口挂载的根,此时入口的 `mount` 既不渲染也不运行它的组件,并把 `View.Props` 作为它的 props;`View.Props` 是可以 JSON 编码的 map,每个视图各得一份副本。这样一个包能提供多个视图,各有自己的状态,权限和限额都相同;导出不存在时以 `tsx.ErrNoViewExport` panic,导出的不是函数时以 `tsx.ErrViewExportNotComponent` panic。入口导出函数的包是函数型插件:`tsx.Load(cx, p, tsx.Sandbox{})` 在调用方的 goroutine 上同步运行它而不显示,要求 `cx` 属于一个视图树,否则返回 `tsx.ErrNoTree`;入口模块加载时抛出错误则返回这个错误,`Plugin.Call` 调用这些函数。`go tool nsgo dev -limits` 像这样的视图一样运行应用,`go tool nsgo revoke` 签署吊销发布密钥和包的列表,供 `Trust.UpdateRevocations` 使用。`examples/plugins` 会请用户授予包声明的权限,再安装并运行它。`Limits.Memory` 默认为 64 MiB,在原生目标上对数组、字符串、缓冲区和类型化数组计量。其中包括 `concat`、`flat`、`slice`、数组展开、字符串拼接、模板字符串、`replace`、`replaceAll`、`TextEncoder` 和 `Blob` 副本。`-limits` 中的 `memory=` 可调整此限额,`memory=0` 将其关闭。分配前会检查限额。若 Go 检查可回收的存储后仍超限,包将以资源为 `memory` 的 `ERR_NSH_QUOTA_EXCEEDED` 停止。普通对象、闭包、栈、小额分配和未计量的内置函数或宿主 API 也会占用内存。浏览器使用自己的堆。自己用 `pkg.Build` 签名包的应用,或用 `go tool nsgo publish -extra <文件>` 放入该文件内容的应用,可以把自己的元数据放进 `pkg.Contents.Extra`,例如插件要加到菜单里的项:它和包一起签名,`Verify` 原样以 `p.Extra` 返回,由应用自己解析,因此应用无需运行包的代码就能读到它。 +将 `Sandbox.DisableStorage` 设为 `true` 可禁止通过 `nsgo` 的 `Storage` 读取或写入数据。每个方法都会抛出消息为 `tsx: Storage is disabled for this sandbox` 的 `Error`,已有数据保持不变。`Limits.Storage` 为零仍表示不限制存储字节数。 + 应用可以用 `pkg.SignDocument` 为自己的 JSON 文档(例如插件目录)签名,再用 `Signed.Open` 验证,密钥使用 `nsgo keygen` 生成的即可。每种文档使用一个带版本的独立 `app:` 上下文,例如 `app:catalog-v1`:一种文档不会被当作另一种文档,也不会被当作包、证书或吊销列表。`Open` 只信任传给它的公钥,不使用证书和吊销列表,并拒绝解码目标类型中没有的字段。信封中没有时间和序号,旧文档与新文档同样能通过验证:请在正文中放入版本或过期时间并加以检查。 在原生沙箱中,`JSON.stringify`、带 reviver 的 `JSON.parse`、`Array.prototype.join`、`toString`、`toLocaleString` 和 `flat`,以及数组的 `String()`,深入超过 1,000 层时会抛出可捕获的 `RangeError`;一个在另一个内部调用时层数累计,数组的 `toString` 和它调用的 `join` 各算一层。更深的数据会让调用卡住或让应用退出。Web 使用浏览器的内置函数。 @@ -136,7 +138,7 @@ trust.Accept(p) // 运行之后,更旧的构建会被拒绝 `Plugin.JSTime` 和 `ViewRuntime.JSTime` 报告原生运行时执行 JavaScript 的累计时长,包括当前正在执行的入口。两次执行之间的等待时间和注册的同步 Go 函数耗时不计入。`ViewRuntime.EngineTime` 还计入同步 Go 调用以及视图所属的响应式计算、挂载、提交和布局工作,包括当前尚未完成的工作;两次引擎执行之间的等待、宿主或其他视图的工作、共享提交管理工作和原生绘制不计入。两个计数器均可从任意 goroutine 读取。浏览器在 NSGo 之外执行的 JavaScript 无法测量或打断,因此两个计数器均返回不可用,`Interrupt` 在宿主重新取得控制后停止后续 NSGo 回调。 -Web 上暂时无法把包与页面隔离:包的代码能绕过它的权限,直接访问页面自己的网络、剪贴板和存储,信任库所在的存储也包括在内。因此在 Web 上 `tsx.View` 和 `tsx.Load` 会以 `tsx.ErrUnisolated` 拒绝运行包,除非设置 `Sandbox.WebUnisolated`,让它以页面的权限运行;这只适合你愿意像对待应用自身代码一样信任的包。 +Web 上暂时无法将包与页面隔离:包拥有页面自身的网络、剪贴板和存储权限,包括信任库。因此 `tsx.View` 和 `tsx.Load` 会以 `tsx.ErrUnisolated` 拒绝运行包,除非设置 `Sandbox.WebUnisolated`;带有权限限制或设置了 `DisableStorage` 的自定义 `tsx.Sandboxed` 也需要这一选项。它不会恢复被禁用的 NSGo `Storage`,也不会保护页面自身的存储。只对你愿意授予应用自身权限的代码启用它。 ## 编辑器与测试 diff --git a/skills/nsgo/SKILL.md b/skills/nsgo/SKILL.md index aa8a52926..59577e79c 100644 --- a/skills/nsgo/SKILL.md +++ b/skills/nsgo/SKILL.md @@ -140,6 +140,7 @@ func main() { nsgo.Run(Root) } - `core.PanEvent` supplies `Position` in the view and `PagePosition` in its page on every phase. - For function plugins, set `Sandbox.OnError` to attribute uncaught callbacks and native slice-budget cuts outside a waiting call. The handler runs on the engine goroutine and can open a breaker with `Plugin.Interrupt`; entry and call-result failures still return to their callers, and views use `core.Catch`. [TSX](https://nsgo.dev/docs/tsx/) - A native `Plugin.Call` reports `tsx.ErrBudget` when `Limits.Call` cuts its JS, even after `await`. `Limits.CallTotal` also counts time spent waiting. Hosts can stop the plugin with `Plugin.Interrupt`, read `Plugin.Stopped()` and `Plugin.Err()` from any goroutine, or set `Sandbox.OnStop` for a notification on the engine's goroutine. Sandboxed backtracking regexps use the shorter load or call budget as their match timeout. For host deadline extensions, view interruption, native `JSTime` and owned engine work through `ViewRuntime.EngineTime`, see [TSX](https://nsgo.dev/docs/tsx/). +- Set `Sandbox.DisableStorage` to deny a plugin NSGo `Storage` access without deleting its data. Do not use `WebUnisolated` to sandbox untrusted code. [Signed packages](https://nsgo.dev/docs/tsx.md#signed-packages) - In a native sandbox `JSON.stringify`, `JSON.parse` with a reviver, `Array.prototype.join`, `toString`, `toLocaleString` and `flat` throw a catchable `RangeError` past 1,000 levels, counted across nested calls, instead of hanging or overflowing the host's Go stack. - A native sandbox uses 1,000 frames with `DefaultLimits` and caps `Limits.Stack` at 10,000. Nonpositive Go values use the cap. - Native functions calling each other (built-in getters, `toString`/`valueOf`, `RegExp` `exec` dispatch, `Reflect.apply`/`construct`, bound-function and proxy chains) count against `Limits.Stack` and throw a catchable `RangeError`, and exporting a plugin value nested deeper fails with a `RangeError`, through NSGo's goja fork `github.com/nsgo-dev/goja`, which apps get with NSGo without a `replace` of their own. diff --git a/tsx/isolation_test.go b/tsx/isolation_test.go index c6d573278..2217bd2cf 100644 --- a/tsx/isolation_test.go +++ b/tsx/isolation_test.go @@ -21,6 +21,9 @@ func TestIsolation(t *testing.T) { {"a package's view on the web", Sandbox{}.of(&pkg.Package{}), true, true}, {"opted in on the web", Sandbox{Capabilities: caps, Grant: caps, WebUnisolated: true}, true, false}, {"no capabilities on the web", Sandbox{Storage: "com.example.plugin", Modules: []string{"*"}}, true, false}, + {"disabled storage on the web", Sandbox{DisableStorage: true}, true, true}, + {"disabled storage opted in on the web", Sandbox{DisableStorage: true, WebUnisolated: true}, true, false}, + {"disabled storage on goja", Sandbox{DisableStorage: true}, false, false}, {"capabilities on goja", Sandbox{Capabilities: caps, Grant: caps}, false, false}, } { err := c.s.isolation(c.browser) diff --git a/tsx/sandbox.go b/tsx/sandbox.go index 16016e473..1fd222d3a 100644 --- a/tsx/sandbox.go +++ b/tsx/sandbox.go @@ -41,7 +41,8 @@ type Limits struct { // Body is the most bytes a request's or a response's body may hold. Body int // Storage is the most bytes its partition of the app's storage may - // hold (Sandbox.Storage). + // hold (Sandbox.Storage). Zero leaves no partition quota; use + // Sandbox.DisableStorage to deny the nsgo Storage module instead. Storage int // Memory limits metered allocation on goja, including buffers, large array stores and strings built by concatenation or replacement. Checks precede allocation and collected stores release their charge. It does not cap the whole heap: ordinary objects, closures, small allocations and other unmetered storage can still grow, and it does not apply in the browser. Zero leaves it unlimited; DefaultLimits holds 64 MiB. Memory int @@ -157,16 +158,20 @@ type Sandbox struct { OnError func(error) // Storage names its partition of the app's storage and of its secrets (core.Scope.ProvideSecrets), which no one else's code sees; "" leaves it the app's. Storage string - // WebUnisolated runs it on the web with the page's authority. The page's engine runs it in a realm of the page's origin, which reaches the page's own APIs (XMLHttpRequest, WebSocket, navigator, localStorage, the page's window) past Go, so there Capabilities and Grant hold only the requests the runtime and core make, and Storage's partition and a pkg.Trust kept in the page's storage are open to its code. Without it, a sandbox with Capabilities or Grant refuses to start on the web with ErrUnisolated. Other targets isolate it and ignore this. + // DisableStorage makes every nsgo Storage method reject with an Error + // whose message is "tsx: Storage is disabled for this sandbox". It + // leaves existing data and the Secrets module alone. + DisableStorage bool + // WebUnisolated runs it on the web with the page's authority. The page's engine runs it in a realm of the page's origin, which reaches the page's own APIs (XMLHttpRequest, WebSocket, navigator, localStorage, the page's window) past Go. Capabilities and Grant hold only the requests the runtime and core make, and DisableStorage still withholds the nsgo Storage module's operations, not the page's storage APIs. Storage's partition and a pkg.Trust kept in the page's storage are open to its code. Without WebUnisolated, a sandbox with Capabilities, Grant or DisableStorage refuses to start on the web with ErrUnisolated. Other targets isolate it and ignore WebUnisolated. WebUnisolated bool } -// ErrUnisolated is what a sandbox with Capabilities or Grant fails with on the web unless Sandbox.WebUnisolated is set: the page's engine cannot isolate a package's realm from the page, so what it declares would not hold. -var ErrUnisolated = errors.New("tsx: the web cannot isolate a sandboxed package from the page, so its capabilities would not hold; set Sandbox.WebUnisolated to run it with the page's authority") +// ErrUnisolated is what a sandbox with Capabilities, Grant or DisableStorage fails with on the web unless Sandbox.WebUnisolated is set: the page's engine cannot isolate a package's realm from the page, so its restrictions would not hold. +var ErrUnisolated = errors.New("tsx: the web cannot isolate a sandboxed package from the page, so its restrictions would not hold; set Sandbox.WebUnisolated to run it with the page's authority") -// isolation checks whether the realm's access to the page would bypass the sandbox's capabilities. +// isolation checks whether the realm's access to the page would bypass the sandbox's restrictions. func (s Sandbox) isolation(sharesPageAuthority bool) error { - if sharesPageAuthority && (s.Capabilities != nil || s.Grant != nil) && !s.WebUnisolated { + if sharesPageAuthority && (s.Capabilities != nil || s.Grant != nil || s.DisableStorage) && !s.WebUnisolated { return ErrUnisolated } return nil @@ -181,7 +186,7 @@ type ViewOptions struct { Props map[string]any } -// Sandboxed returns the app of a bundle, as App does, run within s, in a view of its own: its frame, which fills the room its parent gives it, no more, so the bundle cannot grow over the host's views, and clips what the bundle shows, overlays included (core.Scope.Confine). In a scroll view that room is the scroll view's height: a host that wants the bundle as tall as its content puts it in a view of its own. On the web it panics with ErrUnisolated when s has Capabilities or Grant, unless s.WebUnisolated. When options has an Export, that named component, which runs within s as the rest of the bundle does, is rendered instead of the entry-mounted root; a missing one panics with ErrNoViewExport and one that is not a function with ErrViewExportNotComponent. +// Sandboxed returns the app of a bundle, as App does, run within s, in a view of its own: its frame, which fills the room its parent gives it, no more, so the bundle cannot grow over the host's views, and clips what the bundle shows, overlays included (core.Scope.Confine). In a scroll view that room is the scroll view's height: a host that wants the bundle as tall as its content puts it in a view of its own. On the web it panics with ErrUnisolated when s has Capabilities, Grant or DisableStorage, unless s.WebUnisolated. When options has an Export, that named component, which runs within s as the rest of the bundle is, is rendered instead of the entry-mounted root; a missing one panics with ErrNoViewExport and one that is not a function with ErrViewExportNotComponent. func Sandboxed(name, src string, s Sandbox, options ...ViewOptions) func(cx *core.Scope) core.Node { var view ViewOptions if len(options) > 0 { @@ -266,7 +271,11 @@ func (s Sandbox) start(cx *core.Scope, name, src string) *runtime { } else { r.regexTimeout = limits.Load } - r.sandbox = &sandboxed{caps: s.Capabilities != nil || s.Grant != nil, modules: s.Modules} + r.sandbox = &sandboxed{ + caps: s.Capabilities != nil || s.Grant != nil, + modules: s.Modules, + disableStorage: s.DisableStorage, + } r.exportView = s.exportView if s.plugin { r.onError = s.OnError @@ -359,8 +368,9 @@ func (a access) WebHosts() []string { return a.c.WebHosts() } type sandboxed struct { // caps says capabilities hold it, so the runtime checks its own // requests. - caps bool - modules []string + caps bool + modules []string + disableStorage bool // nodes, timers, requests and sounds are what it holds now. nodes, timers, requests, sounds int // stopped is why it stopped: no JS runs after. diff --git a/tsx/sandbox_test.go b/tsx/sandbox_test.go index 3329240db..272080462 100644 --- a/tsx/sandbox_test.go +++ b/tsx/sandbox_test.go @@ -120,6 +120,86 @@ func results(t *testing.T, attempts string, caps pkg.Capabilities, s tsx.Sandbox return out } +func TestSandboxDisableStorage(t *testing.T) { + p := verified(t, `import { mount, signal, Storage, Text } from "nsgo"; +const log = signal(""); +mount(() => {log}); +(async () => { + const results = []; + for (const [name, ...args] of [ + ["getItem", "existing"], + ["keys"], + ["setItem", "existing", "changed"], + ["getItem", "existing"], + ["removeItem", "existing"], + ["getItem", "existing"], + ["setItem", "new", "value"], + ["clear"], + ["keys"], + ]) { + results.push(await Storage[name](...args).then( + v => JSON.stringify(v) ?? "ok", + e => e.name + ": " + e.message, + )); + } + log.set(JSON.stringify(results)); +})();`, pkg.Capabilities{}) + allowed := []string{`"saved"`, `["existing"]`, "ok", `"changed"`, "ok", "null", "ok", "ok", "[]"} + for _, c := range []struct { + name string + sandbox tsx.Sandbox + want []string + entries []string + }{ + {"default", tsx.Sandbox{}, allowed, nil}, + {"no partition quota", tsx.Sandbox{Limits: &tsx.Limits{Storage: 0}}, allowed, nil}, + {"disabled", tsx.Sandbox{DisableStorage: true}, slices.Repeat([]string{"Error: tsx: Storage is disabled for this sandbox"}, len(allowed)), []string{"existing=saved"}}, + } { + t.Run(c.name, func(t *testing.T) { + var partition core.Storage + var seedErr error + sandbox := c.sandbox + // Exercise the module even on targets that share page authority. + sandbox.WebUnisolated = runtime.GOOS == "js" + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + seed := cx.Child() + seed.Run(func() { + seed.ProvideStorage(p.App.ID, 0) + partition = seed.Storage() + seedErr = partition.SetItem("existing", "saved") + }) + return tsx.View{Package: p, Sandbox: sandbox} + }, nsgotest.Storage(map[string]string{"existing": "host"})) + if seedErr != nil { + t.Fatal(seedErr) + } + app.WaitUntil(10*time.Second, func() bool { + return app.Find("id:storage-log").Text != "" + }) + var got []string + if err := json.Unmarshal([]byte(app.Find("id:storage-log").Text), &got); err != nil { + t.Fatal(err) + } + if !slices.Equal(got, c.want) { + t.Errorf("Storage results = %q, want %q", got, c.want) + } + var entries []string + var hostValue string + app.Post(func() { + for _, key := range partition.Keys() { + value, _ := partition.GetItem(key) + entries = append(entries, key+"="+value) + } + hostValue, _ = app.Storage().GetItem("existing") + }) + app.Settle() + if !slices.Equal(entries, c.entries) || hostValue != "host" { + t.Errorf("partition = %q, host entry = %q; want %q and host", entries, hostValue, c.entries) + } + }) + } +} + func TestSandboxHoldsAPackageToItsCapabilities(t *testing.T) { got := results(t, ` allowed: async () => (await fetch("https://api.example.com/a")).text(), diff --git a/tsx/services.go b/tsx/services.go index cdb7b00e1..64712b336 100644 --- a/tsx/services.go +++ b/tsx/services.go @@ -2,6 +2,7 @@ package tsx import ( "encoding/base64" + "errors" "fmt" "strings" @@ -228,13 +229,25 @@ func imageBytes(src string) ([]byte, error) { return []byte(data), nil } +var errStorageDisabled = errors.New("tsx: Storage is disabled for this sandbox") + func (r *runtime) storage() js.Value { o := r.vm.NewObject() - s := r.cx.Storage() + var s core.Storage + var storageErr error + if r.sandbox != nil && r.sandbox.disableStorage { + storageErr = errStorageDisabled + } else { + s = r.cx.Storage() + } set := func(name string, f func(call js.FunctionCall) (js.Value, error)) { _ = o.Set(name, r.function(func(call js.FunctionCall) js.Value { p, resolve, reject := r.newPromise() - v, err := f(call) + var v js.Value + err := storageErr + if err == nil { + v, err = f(call) + } if err != nil { _ = reject(r.goError(err)) } else { diff --git a/tsx/types/index.d.ts b/tsx/types/index.d.ts index 82997b59b..510bb8978 100644 --- a/tsx/types/index.d.ts +++ b/tsx/types/index.d.ts @@ -297,6 +297,7 @@ export interface StorageModule { keys(): Promise; clear(): Promise; } +/** Persistent key-value storage, partitioned for packages. With Sandbox.DisableStorage, every method rejects with an Error: "tsx: Storage is disabled for this sandbox". */ export declare const Storage: StorageModule; /** The app's secure store, by account: the keychain, Credential Manager, Secret Service or Android Keystore; a package's own part of it under the secrets capability. */ export interface SecretsModule {