@vite-hub/sandbox 0.0.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +395 -37
- package/dist/abortable-CR01hzfi.js +57 -0
- package/dist/cloudflare-Cog_r2Me.js +910 -0
- package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
- package/dist/cloudflare-failure-CFQhalfh.js +50 -0
- package/dist/container-CqfD8yuE.js +868 -0
- package/dist/crabbox-sbV3Zjuo.js +1110 -0
- package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
- package/dist/error-diagnostics-BJtLRL9w.js +536 -0
- package/dist/file-listing-CHtRrfo1.js +26 -0
- package/dist/file-lock-D0-XPogS.js +74 -0
- package/dist/index-DsoQAUb7.d.ts +594 -0
- package/dist/index.d.ts +2 -69
- package/dist/index.js +281 -1182
- package/dist/internal/cloudflare.d.ts +176 -0
- package/dist/internal/cloudflare.js +8 -0
- package/dist/internal/host-toolchain.d.ts +22 -0
- package/dist/internal/host-toolchain.js +96 -0
- package/dist/internal/vercel.d.ts +4 -0
- package/dist/internal/vercel.js +8 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/module-types-B0LQ5H2S.js +7 -0
- package/dist/module-types-DCeJbS9Z.d.ts +110 -0
- package/dist/process-sweep-CMaujWE5.js +33 -0
- package/dist/provider-resolution-C6AQzuFG.js +133 -0
- package/dist/remote-70ZVZZlq.js +265 -0
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime-DHp6ImeP.js +32 -0
- package/dist/runtime-type-Deo4qzxN.js +9 -0
- package/dist/session-e0lyzjJ3.js +338 -0
- package/dist/shell-quote-Q3u3plif.js +6 -0
- package/dist/size-7AkVwGZb.js +118 -0
- package/dist/ssh.d.ts +63 -0
- package/dist/ssh.js +286 -0
- package/dist/task/index.d.ts +69 -0
- package/dist/task/index.js +1414 -0
- package/dist/task/runtime/empty-registry.d.ts +6 -0
- package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
- package/dist/task/runtime/provider-loader.d.ts +18 -0
- package/dist/task/runtime/provider-loader.js +16 -0
- package/dist/task/runtime/providers/cloudflare.d.ts +14 -0
- package/dist/task/runtime/providers/cloudflare.js +27 -0
- package/dist/task/runtime/providers/vercel.d.ts +12 -0
- package/dist/task/runtime/providers/vercel.js +85 -0
- package/dist/task/runtime/state.d.ts +27 -0
- package/dist/task/runtime/state.js +82 -0
- package/dist/task/vite.d.ts +486 -0
- package/dist/task/vite.js +3966 -0
- package/dist/toolchain-BIVGMRty.js +528 -0
- package/dist/trusted-host-kxkpaQcs.js +714 -0
- package/dist/vercel-BGGrNpza.js +352 -0
- package/package.json +105 -51
- package/dist/cloudflare-env-QQV4uzCT.js +0 -14
- package/dist/module-types-DKYItiOu.d.ts +0 -93
- package/dist/module-types-Dj1MFmHT.js +0 -7
- package/dist/provider-loader-D0UihePq.d.ts +0 -21
- package/dist/runtime/empty-registry.d.ts +0 -6
- package/dist/runtime/provider-loader.d.ts +0 -2
- package/dist/runtime/provider-loader.js +0 -15
- package/dist/runtime/providers/cloudflare.d.ts +0 -29
- package/dist/runtime/providers/cloudflare.js +0 -25
- package/dist/runtime/providers/vercel.d.ts +0 -121
- package/dist/runtime/providers/vercel.js +0 -51
- package/dist/runtime/state.d.ts +0 -26
- package/dist/runtime/state.js +0 -72
- package/dist/vite.d.ts +0 -48
- package/dist/vite.js +0 -3324
package/README.md
CHANGED
|
@@ -1,46 +1,399 @@
|
|
|
1
1
|
# @vite-hub/sandbox
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://npmx.dev/package/@vite-hub/sandbox)
|
|
4
|
+
[](https://npmx.dev/package/@vite-hub/sandbox)
|
|
5
|
+
[](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
|
|
6
|
+
[](https://vitehub.dev/docs)
|
|
4
7
|
|
|
5
|
-
|
|
8
|
+
`@vite-hub/sandbox` owns portable execution for ViteHub. A project declares environment inputs, immutable Home files, writable Home state, and boot checks; a runtime Adapter turns that declaration into an inspectable preparation plan and opens active Sandbox sessions without exposing a provider SDK.
|
|
6
9
|
|
|
7
10
|
## Install
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
```sh
|
|
13
|
+
pnpm add @vite-hub/sandbox
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Prepare a trusted-host Sandbox
|
|
17
|
+
|
|
18
|
+
The Sandbox below reads two secrets of the app's Server Env:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// vite.config.ts
|
|
22
|
+
import { env, hubEnv } from "@vite-hub/env/vite";
|
|
23
|
+
import { defineConfig } from "vite";
|
|
24
|
+
|
|
25
|
+
export default defineConfig({
|
|
26
|
+
plugins: [hubEnv({
|
|
27
|
+
server: {
|
|
28
|
+
githubToken: env({ secret: true, source: env.source("GITHUB_TOKEN") }),
|
|
29
|
+
codexAuthJson: env({ secret: true, source: env.source("CODEX_AUTH_JSON") }),
|
|
30
|
+
},
|
|
31
|
+
})],
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { resolveSandbox } from "@vite-hub/sandbox";
|
|
37
|
+
import { useServerEnv } from "@vite-hub/env";
|
|
38
|
+
|
|
39
|
+
const sandbox = await resolveSandbox({
|
|
40
|
+
runtime: { kind: "trusted-host", stateRoot: "/var/lib/vitehub/sandboxes" },
|
|
41
|
+
checkout: {
|
|
42
|
+
ref: "refs/pull/985/head",
|
|
43
|
+
remote: "https://github.com/vite-hub/vitehub.git",
|
|
44
|
+
sha: "0123456789abcdef0123456789abcdef01234567",
|
|
45
|
+
},
|
|
46
|
+
env: {
|
|
47
|
+
GH_TOKEN: () => useServerEnv().githubToken.unseal(),
|
|
48
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
49
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
50
|
+
},
|
|
51
|
+
home: {
|
|
52
|
+
files: {
|
|
53
|
+
".gitconfig": { from: ".vitehub/sandbox/gitconfig" },
|
|
54
|
+
".codex/config.toml": { from: ".vitehub/sandbox/codex.toml" },
|
|
55
|
+
},
|
|
56
|
+
state: {
|
|
57
|
+
".codex": {
|
|
58
|
+
key: "babysitter/codex",
|
|
59
|
+
seed: {
|
|
60
|
+
"auth.json": {
|
|
61
|
+
contents: () => useServerEnv().codexAuthJson.unseal(),
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
requires: [{ name: "GitHub CLI", command: "gh", args: ["auth", "status"] }, "pnpm"],
|
|
68
|
+
}, {});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Direct callers can inspect preparation without resolving secrets, then open a session:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { resolveSandbox } from "@vite-hub/sandbox";
|
|
75
|
+
|
|
76
|
+
const sandbox = await resolveSandbox(
|
|
77
|
+
{
|
|
78
|
+
env: { PROJECT_ENV: "test" },
|
|
79
|
+
requires: ["node", "pnpm"],
|
|
80
|
+
runtime: "trusted-host",
|
|
81
|
+
},
|
|
82
|
+
{},
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
console.log(sandbox.plan.runtime, sandbox.plan.requirements, sandbox.plan.executionAuthority);
|
|
86
|
+
|
|
87
|
+
const session = await sandbox.open();
|
|
88
|
+
try {
|
|
89
|
+
await session.files.write("workspace/input.bin", new Uint8Array([0, 1, 255]));
|
|
90
|
+
const result = await session.exec("node", ["workspace/run.mjs"], {
|
|
91
|
+
cwd: session.cwd,
|
|
92
|
+
timeout: 30_000,
|
|
93
|
+
});
|
|
94
|
+
if (!result.ok) throw new Error(result.stderr);
|
|
95
|
+
} finally {
|
|
96
|
+
await session.close();
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Binary file reads and writes, directory operations, recursive listing, removal, and command execution are required across runtimes. Long-running processes and exposed ports are explicit optional capabilities through `session.spawn` and `session.ports`. `close()` is idempotent, and every operation rejects after closure.
|
|
101
|
+
|
|
102
|
+
Spawned `vercel` processes stream `stdout` and `stderr` while they run. Consume both streams concurrently, or cancel unused output. Each channel buffers up to 1 MiB; if a log entry would exceed that limit, that stream errors with `SANDBOX_R0159` and discards its queued and subsequent output. The other channel continues streaming. Cancelling both channels stops log streaming without killing the process.
|
|
103
|
+
|
|
104
|
+
Spawned `cloudflare` processes stream `stdout` and `stderr` through `streamProcessLogs()` with the same 1 MiB per-channel limit and `SANDBOX_R0159` error. A custom `getSandbox` stub without `streamProcessLogs()` returns each channel's full output after the process exits. The built-in Durable Object starts each spawned command in its own process group with bash job control, and `child.kill()`, a `timeout`, or an aborted `signal` signals that whole group, so child processes stop too.
|
|
105
|
+
|
|
106
|
+
For trusted-host processes, `child.kill()` sends `SIGTERM`, then sends `SIGKILL` after a 250 ms grace period if needed. On POSIX hosts it terminates the process group, including descendants. `child.kill(signal)` forwards the explicit signal and waits for the process to finish without automatic escalation. Every trusted-host command starts with the `VITEHUB_SANDBOX_SESSION` environment variable. On Linux, closing the session also stops the processes that have it and left their process group, for example with `setsid`.
|
|
107
|
+
|
|
108
|
+
A `timeout` or an aborted `signal` stops only that command, on every runtime. The Sandbox and its other processes keep running. `exec()` rejects with the abort reason. For `spawn()`, the runtime kills the process and `wait()` rejects with the abort reason.
|
|
109
|
+
|
|
110
|
+
`child.kill(signal)` sends the signal that you name, or rejects. The `vercel` runtime sends `SIGHUP`, `SIGINT`, `SIGQUIT`, `SIGKILL`, `SIGTERM`, `SIGCONT`, `SIGSTOP`, or a signal number. The `cloudflare` runtime sends `SIGALRM`, `SIGHUP`, `SIGINT`, `SIGKILL`, `SIGQUIT`, `SIGTERM`, `SIGUSR1`, `SIGUSR2`, or a signal number. The `crabbox` runtime sends only `SIGTERM`. Other signals reject with `SANDBOX_R0165`.
|
|
111
|
+
|
|
112
|
+
A spawned `SandboxProcess` can also expose `stdin` as a `WritableStream<Uint8Array>`. The `trusted-host` and `crabbox` runtimes always forward it to the process. The `vercel` runtime forwards it only when you pass `stdin: true`, because a command that reads its input then waits until you close the writer. Close the writer to end the process input. Runtimes that cannot forward input leave `stdin` undefined:
|
|
113
|
+
|
|
114
|
+
```ts fragment
|
|
115
|
+
const child = await session.spawn!("node", ["workspace/filter.mjs"], { stdin: true });
|
|
116
|
+
const writer = child.stdin?.getWriter();
|
|
117
|
+
if (!writer) throw new Error("This Sandbox runtime does not forward process input.");
|
|
118
|
+
await writer.write(new TextEncoder().encode("input\n"));
|
|
119
|
+
await writer.close();
|
|
120
|
+
console.log(await new Response(child.stdout).text(), await child.wait());
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Hosted runtimes use tagged values from the same root API:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { resolveSandbox } from "@vite-hub/sandbox";
|
|
127
|
+
import type { CloudflareDurableObjectNamespace } from "@vite-hub/sandbox";
|
|
128
|
+
|
|
129
|
+
// `namespace` is the Durable Object binding of the Worker, such as `env.SANDBOX`.
|
|
130
|
+
export async function openHostedSandboxes(namespace: CloudflareDurableObjectNamespace) {
|
|
131
|
+
const cloudflare = await resolveSandbox({
|
|
132
|
+
runtime: { kind: "cloudflare", namespace },
|
|
133
|
+
}, {});
|
|
134
|
+
|
|
135
|
+
const vercel = await resolveSandbox({
|
|
136
|
+
runtime: { kind: "vercel", ports: [3000] },
|
|
137
|
+
}, {});
|
|
138
|
+
return { cloudflare, vercel };
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Use `runtime: "vercel"` for the default Vercel Sandbox configuration. Cloudflare remains tag-only because its Durable Objects namespace is required. The Vercel runtime imports `@vercel/sandbox`. Install it in the app, and the server build includes it.
|
|
143
|
+
|
|
144
|
+
The Cloudflare runtime talks to the Sandbox Durable Object that the ViteHub Cloudflare host integration generates. That class starts the Container with the Workers Container API, uses `Files` from `@cloudflare/sandbox` 1.x, preserves Durable Object idle reuse, and the runtime bounds each transport operation with a deadline. It retries only operations that are safe to repeat, such as file reads and full file writes, when Cloudflare marks the error `retryable`. It retries a command or a new process only when the Container was not ready to receive it; other errors keep the Cloudflare flag in `error.data.retryable`. Sessions with the same Sandbox ID share one Container and its files. `open()` does not delete the Home or workspace files of an earlier or concurrent session; only a `checkout` empties the workspace first. A new Container starts with no files. Pass `getSandbox` to use another Durable Object that implements `CloudflareSandboxStub`. Its `cancelExec(id)` must stop the `exec` command that was started with that `id`, and nothing else. The Vercel runtime exposes only the ports declared when the microVM is created. Both reject host `cwd`; materialize a Workspace into their working tree instead.
|
|
145
|
+
|
|
146
|
+
Both hosted runtimes take the same `networkPolicy` option for outbound traffic:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
import { resolveSandbox } from "@vite-hub/sandbox";
|
|
150
|
+
import type { CloudflareDurableObjectNamespace } from "@vite-hub/sandbox";
|
|
151
|
+
|
|
152
|
+
export async function openRestrictedSandbox(namespace: CloudflareDurableObjectNamespace) {
|
|
153
|
+
const sandbox = await resolveSandbox({
|
|
154
|
+
runtime: { kind: "cloudflare", namespace, networkPolicy: { allow: ["registry.npmjs.org", "*.github.com"] } },
|
|
155
|
+
}, {});
|
|
156
|
+
console.log(sandbox.plan.executionAuthority.network); // "restricted"
|
|
157
|
+
return sandbox;
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
| Value | Outbound traffic | `executionAuthority.network` |
|
|
162
|
+
| --- | --- | --- |
|
|
163
|
+
| `"allow-all"` (default) | All traffic. | `"unrestricted"` |
|
|
164
|
+
| `"deny-all"` | No traffic. | `"none"` |
|
|
165
|
+
| `{ allow: [...] }` | HTTP and HTTPS to the listed hostnames only. Other hosts and protocols fail. | `"restricted"` |
|
|
166
|
+
|
|
167
|
+
`"*.example.com"` matches subdomains of `example.com`, not `example.com` itself. Vercel matches HTTPS hosts by TLS SNI and does not decrypt the traffic. Vercel also takes `subnets` and its other policy forms. On Cloudflare, the generated Worker exports a `SandboxOutbound` entrypoint, and Cloudflare sends HTTP on port 80 and HTTPS on port 443 to an allowed host through it. The entrypoint checks the request host against the list again, because a command can send a `Host` header that differs from the TLS server name. It answers 403 for other hosts. Cloudflare decrypts that HTTPS traffic and signs it again with its own CA. ViteHub sets `NODE_EXTRA_CA_CERTS`, `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE`, and `GIT_SSL_CAINFO` on every command, so Node.js, curl, Python requests, and Git trust that CA. Names of other hosts do not resolve. The Cloudflare list takes at most 64 hostnames and no IP addresses. The Worker needs a `compatibility_date` of `2025-11-17` or later.
|
|
168
|
+
|
|
169
|
+
Cloudflare applies the policy when the Container starts, so each Sandbox ID has one policy at a time, not each container class. When a Sandbox ID that runs opens with another policy, ViteHub stops its Container and the next command starts a new one with the new policy. Files and processes in the old Container are lost. A custom `getSandbox` starts its own Container, so it cannot take `networkPolicy`. An invalid policy throws `SANDBOX_NETWORK_POLICY_INVALID`.
|
|
170
|
+
|
|
171
|
+
If Cloudflare Sandbox or Vercel cleanup fails, retry `session.close()`. The session rejects new operations after the first close attempt. Concurrent close calls wait for the same cleanup.
|
|
172
|
+
|
|
173
|
+
`sandbox.open({ initialize })` runs initialization inside runtime preparation. If initialization fails, a runtime must tear down the session and roll back state created for that failed boot.
|
|
174
|
+
|
|
175
|
+
`checkout` gives each invocation a disposable real Git repository at the exact requested commit. The runtime fetches `ref` from `remote`, verifies the resulting commit against the full `sha`, and starts the process in a detached checkout. Normal Git commits work, and callers can push explicitly with `git push origin HEAD:<branch>`. Use the source repository as `remote` for fork pull requests, and keep credentials in Sandbox `env` or Home rather than embedding them in the remote URL.
|
|
176
|
+
|
|
177
|
+
`checkout` and `cwd` are mutually exclusive. Use `cwd` for a caller-owned authoritative directory; use `checkout` when the Sandbox should create, isolate, and delete the working tree. Git is an implicit checkout requirement and is included in resolved Sandbox metadata.
|
|
178
|
+
|
|
179
|
+
Every Sandbox session receives a new private `HOME` plus `XDG_CONFIG_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME`. The runtime starts from a small operational environment allowlist, applies the declared `env`, attaches writable state, materializes files, and runs requirements before the process starts. Missing declarations fail boot; the host Home and undeclared credential variables cannot satisfy them.
|
|
180
|
+
|
|
181
|
+
`home.files` targets and state paths are relative POSIX paths below the materialized Home. A `from` source is relative to `cwd`, or the ViteHub process directory when `cwd` is omitted. Files with `contents` accept text, bytes, or a `SandboxValue` callback. Every declared value is required.
|
|
182
|
+
|
|
183
|
+
The project may commit declarations, non-secret files, and ciphertext. Resolve plaintext through Server Env or another runtime capability. Do not commit plaintext credentials or the capability that decrypts committed ciphertext.
|
|
184
|
+
|
|
185
|
+
## Separate files from state
|
|
186
|
+
|
|
187
|
+
`home.files` is rebuilt at every boot and never becomes authoritative runtime state. Use it for `.gitconfig`, Codex configuration, arbitrary CLI settings, and immutable credential files.
|
|
188
|
+
|
|
189
|
+
`home.state` attaches an opaque writable directory from the runtime's protected `stateRoot`. Its `key` is a stable project-owned identity. The runtime resolves `seed` only when that state directory does not exist, so a refreshed OAuth file is never replaced by stale bootstrap data. Sessions sharing a state key are serialized until the owning session stops its processes and releases the lease.
|
|
190
|
+
|
|
191
|
+
A file may live beneath a state target. The runtime attaches state first and projects the file afterward, so committed configuration wins on every boot while adjacent CLI-owned files remain writable.
|
|
192
|
+
|
|
193
|
+
`{ kind: "trusted-host", stateRoot }` requires a durable local path whenever state is declared. Keep it outside the checkout, workspace, build context, cache, and artifact directories. The runtime creates private children but does not change permissions on an existing caller-owned root.
|
|
194
|
+
|
|
195
|
+
## Use generic requirement checks
|
|
196
|
+
|
|
197
|
+
A string requirement checks that an executable exists on `PATH`. An object supplies a fixed command and argv after the Sandbox is prepared, without parsing a project-supplied shell command:
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
requires: [
|
|
201
|
+
"git",
|
|
202
|
+
{ name: "GitHub CLI", command: "gh", args: ["auth", "status"] },
|
|
203
|
+
{ name: "Acme CLI", command: "acme", args: ["auth", "status"] },
|
|
204
|
+
];
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Core does not contain provider names or auth-file formats. Declare every executable and authentication check required by the process that will run in the Sandbox.
|
|
208
|
+
|
|
209
|
+
Requirement names, commands, and argv are inspectable declaration metadata. They verify or select executables, but they do not restrict filesystem access, network egress, inherited credentials, or child processes. Inspect `sandbox.plan.executionAuthority` for those boundaries, and keep credentials in `env` or Home files rather than arguments.
|
|
210
|
+
|
|
211
|
+
## Provision the project toolchain
|
|
212
|
+
|
|
213
|
+
A Sandbox does not assume that Node.js, npm, pnpm, Yarn, or Corepack exist on the host or image. Declare `toolchain` and the Sandbox installs the versions that the project pins:
|
|
214
|
+
|
|
215
|
+
```ts fragment
|
|
216
|
+
const sandbox = await resolveSandbox({
|
|
217
|
+
runtime: { kind: "trusted-host", stateRoot: "/var/lib/vitehub/sandboxes" },
|
|
218
|
+
checkout: { ref, remote, sha },
|
|
219
|
+
toolchain: "project",
|
|
220
|
+
}, {});
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
`"project"` is short for `{ node: "project", packageManager: "project" }`. The object form accepts:
|
|
224
|
+
|
|
225
|
+
| Option | Values |
|
|
226
|
+
| --- | --- |
|
|
227
|
+
| `node` | `"project"` (default), or a version, range, or alias such as `"22.11.0"`, `"22"`, `"^22.11.0"`, or `"lts/*"` |
|
|
228
|
+
| `packageManager` | `"project"` (default), `false` for the npm bundled with Node.js, or `name@version` such as `"pnpm@10.2.0"` |
|
|
229
|
+
| `fallbackNode` | A Node.js version, range, or alias used when the project pins none |
|
|
230
|
+
|
|
231
|
+
The first match selects Node.js:
|
|
232
|
+
|
|
233
|
+
1. `package.json` `devEngines.runtime`, the entry named `node` (object or array)
|
|
234
|
+
2. `.node-version`
|
|
235
|
+
3. `.nvmrc`
|
|
236
|
+
4. `package.json` `volta.node`
|
|
237
|
+
5. `package.json` `engines.node`
|
|
238
|
+
6. `toolchain.fallbackNode`
|
|
239
|
+
|
|
240
|
+
If none matches, boot fails with `SANDBOX_R0147`. The Sandbox never falls back to a Node.js that happens to be on `PATH`. A range or alias such as `lts/*`, `lts/iron`, or `node` resolves to the highest matching release in the distribution `index.json`. The package manager comes from `package.json` `packageManager` (`pnpm@x.y.z`, `yarn@x.y.z`, or `npm@x.y.z`, with an optional `+sha512.<hex>` hash) or `devEngines.packageManager`. Without either, the project uses the npm bundled with Node.js. Bun fails with `SANDBOX_R0149`.
|
|
241
|
+
|
|
242
|
+
The ViteHub process downloads official archives with `fetch`. Node.js archives must match `SHASUMS256.txt` from the same distribution. Package managers come from the npm registry and must match its `dist.integrity` (sha512) and, when present, the `packageManager` hash. Yarn 2 and later use `@yarnpkg/cli-dist`; their `packageManager` hash is checked against its `bin/yarn.js`, as Corepack does. A project `yarnPath` still takes effect. ViteHub does not use Corepack, nvm, or mise. On musl Linux, Node.js comes from `https://unofficial-builds.nodejs.org/download/release`. Set `VITEHUB_NODE_DIST_URL`, `VITEHUB_NODE_MUSL_DIST_URL`, or `VITEHUB_NPM_REGISTRY_URL` in the ViteHub process to use a mirror.
|
|
243
|
+
|
|
244
|
+
The runtime provisions after it materializes the checkout and before requirement checks. It puts the package manager and Node.js `bin` directories first on the Sandbox `PATH`, adds `node` and the package manager to the requirements, and then checks `node -v` and `<package manager> --version` with the Sandbox environment. Without `checkout`, pins come from `cwd`, or the ViteHub process directory when `cwd` is omitted, and `sandbox.plan.toolchain` lists them. A `checkout` Sandbox reads them from the checkout at each boot, so its plan reports `source: "checkout"`. An open session reports the exact versions in `session.toolchain`.
|
|
245
|
+
|
|
246
|
+
| Runtime | Toolchain location |
|
|
247
|
+
| --- | --- |
|
|
248
|
+
| `trusted-host` | `<stateRoot>/toolchains`, or `$XDG_CACHE_HOME/vitehub/toolchains` without `stateRoot`. Shared by sessions and processes; a lock makes concurrent sessions download each version once. |
|
|
249
|
+
| `crabbox` | The same layout on the target, under the target user's cache when `stateRoot` is not set. Archives travel through the Crabbox copy transport. |
|
|
250
|
+
| `cloudflare`, `vercel` | `$HOME/.cache/vitehub/toolchains` in the Sandbox, for one session. An image `node` with the exact resolved version is used as is. |
|
|
251
|
+
|
|
252
|
+
Cache entries are content-addressed and read-only once published. Global installs such as `npm install -g` cannot write into them. To clear a cache, run `chmod -R u+w <cache> && rm -rf <cache>`. Installation uses `sh`, `tar` with gzip, `mktemp`, and `base64` on the target. The first boot of a version needs network access from the ViteHub process; an exact pin that is already cached boots without it. Custom runtimes do not provision toolchains, and boot fails with `SANDBOX_R0156` when one declares `toolchain`. Windows hosts are not supported.
|
|
253
|
+
|
|
254
|
+
## Run through Crabbox
|
|
255
|
+
|
|
256
|
+
```ts fragment
|
|
257
|
+
sandbox: {
|
|
258
|
+
runtime: {
|
|
259
|
+
kind: "crabbox",
|
|
260
|
+
profile: "babysitter",
|
|
261
|
+
stateRoot: "/var/lib/vitehub/sandboxes",
|
|
262
|
+
},
|
|
263
|
+
checkout: {
|
|
264
|
+
ref: ({ input }) => input.options?.ref,
|
|
265
|
+
remote: ({ input }) => input.options?.remote,
|
|
266
|
+
sha: ({ input }) => input.options?.sha,
|
|
267
|
+
},
|
|
268
|
+
env: {
|
|
269
|
+
GH_TOKEN: () => useServerEnv().githubToken.unseal(),
|
|
270
|
+
},
|
|
271
|
+
home: {
|
|
272
|
+
files: {
|
|
273
|
+
".gitconfig": { from: ".vitehub/sandbox/gitconfig" },
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
}
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
Crabbox materializes the same declaration on the target before requirement checks. Resolved material travels through Crabbox's protected stdin channel rather than command arguments. The private Home and writable state stay outside Workspace synchronization. An authoritative `cwd` is synchronized back; a disposable `checkout` remains target-local and is deleted with the Sandbox session.
|
|
280
|
+
|
|
281
|
+
Crabbox requires either `cwd` or `checkout` and targets Linux/POSIX Static SSH hosts. `stateRoot` is an absolute path on the target. File reads and writes use Crabbox's resolved SSH copy transport. Port URLs wait for and reuse one loopback-only Crabbox tunnel per port by default, and session teardown stops those tunnels. Use `network: "direct"` only when the target shares the ViteHub process loopback namespace.
|
|
282
|
+
|
|
283
|
+
Commands must remain owned by their Sandbox session. ViteHub adds the reserved `VITEHUB_SANDBOX_SESSION` environment marker to commands and reclaims marked processes on the SSH target when the session closes, including children adopted by supervisors. Commands cannot override this marker through the `env` option. Supervisors that launch replacement processes must preserve it.
|
|
284
|
+
|
|
285
|
+
The marker is read from each process's environment at launch. A process that starts with the marker remains owned by that Sandbox, even if it later changes its environment. A process started without the marker is not owned by that Sandbox, even if it references the Sandbox directory. This cleanup does not add process isolation.
|
|
286
|
+
|
|
287
|
+
## Run in a caged container
|
|
288
|
+
|
|
289
|
+
```ts fragment
|
|
290
|
+
sandbox: {
|
|
291
|
+
runtime: {
|
|
292
|
+
kind: "container",
|
|
293
|
+
image: "node:24-bookworm",
|
|
294
|
+
egress: { allow: ["registry.npmjs.org"] },
|
|
295
|
+
credentials: {
|
|
296
|
+
GH_TOKEN: { hosts: ["api.github.com", "github.com"], value: () => useServerEnv().githubToken.unseal() },
|
|
297
|
+
},
|
|
298
|
+
memoryBytes: 4 * 1024 ** 3,
|
|
299
|
+
},
|
|
300
|
+
checkout: { ref, remote, sha },
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Each session starts a new container on an internal Docker network, through the Docker CLI of the ViteHub process. Without `egress`, the container has no network exit. With `egress: { allow }` or `egress: "open"`, a broker container (`mitmproxy/mitmproxy`, pinned) is the only exit. It refuses hosts outside the allowlist at `CONNECT` time and for each request. Credential hosts are always allowed.
|
|
305
|
+
|
|
306
|
+
The Docker daemon must be rootful Docker Engine 28 or newer on native Linux. The isolated bridge has no host address, and the Sandbox has no `NET_RAW` capability. This blocks direct access to host services with or without egress. Docker Desktop, OrbStack, WSL, and rootless Docker have additional host routes outside this boundary and are rejected before resources are created, as are older daemons. The CLI may use a remote native Linux daemon. Host patterns without a port allow only port 443; use `host:port` for another HTTP or HTTPS port. The broker rejects raw TCP tunnels.
|
|
307
|
+
|
|
308
|
+
Credential values resolve on the ViteHub host for each session and reach only the broker, through the Docker CLI environment. They are never on a command line. The Sandbox gets `vitehub-<NAME>-<random>` in each credential variable. The broker replaces it only in HTTPS request headers, including Basic authentication, to a host that the credential lists. A placeholder in a URL, over HTTP, to another host, or from an earlier session gets a `403` with a `SANDBOX_BROKER_B00x` code. The broker logs each request as a JSON line, without query strings. Read them with `docker logs`.
|
|
309
|
+
|
|
310
|
+
The Sandbox trusts the broker certificate through `SSL_CERT_FILE`, `NODE_EXTRA_CA_CERTS`, `GIT_SSL_CAINFO`, `CURL_CA_BUNDLE`, and `REQUESTS_CA_BUNDLE`, and uses `HTTPS_PROXY`, `HTTP_PROXY`, and `NODE_USE_ENV_PROXY=1`. The CA private key stays in the broker. Home is `/vitehub/home` and the workspace is `/vitehub/workspace`. Relative file paths are relative to the workspace. `spawn` forwards input only with `stdin: true`. `kill()` signals the process group in the container. Closing the session removes both containers and the network. Each Docker object has the `dev.vitehub.sandbox` label, so `docker ps -a --filter label=dev.vitehub.sandbox` finds anything that a crashed process left.
|
|
311
|
+
|
|
312
|
+
The image needs `sh`, coreutils, GNU `find`, and `git` for a checkout. The runtime has no ports, no `cwd` mount, and no durable Home state. `cpus`, `memoryBytes`, and `pidsLimit` (default 4096) map to the `docker run` limits, and `user` runs commands as another image user. `docker` selects another Docker CLI.
|
|
313
|
+
|
|
314
|
+
## Bring a custom runtime
|
|
315
|
+
|
|
316
|
+
A `runtime` can also be an object with `name`, `prepare(input)` and `open(input, options)`. Set `network: "direct"` only when its sessions reach the ViteHub process loopback services, for example through SSH reverse tunnels. Agents then pass host Capability tools into the Sandbox. A session may implement `importWorkspace(checkout, signal)` and `refreshDependencies(checkout, signal)` to replace the generic working-tree copy and the publishing of host-installed dependencies. Use them when the runtime can transfer or install faster on its own host.
|
|
317
|
+
|
|
318
|
+
## Security boundary
|
|
319
|
+
|
|
320
|
+
A Sandbox isolates Home, configuration, and declared process environment from ambient machine state. It does not necessarily isolate the filesystem, network, installed executables, or trusted project code; the complete normalized provider declaration is `sandbox.plan.executionAuthority` and is copied unchanged onto every opened session. Dimensions the provider cannot establish remain `unknown`. The built-in `cloudflare` and `vercel` runtimes report `network` from `networkPolicy`: `"unrestricted"` by default, `"none"` for `"deny-all"`, and `"restricted"` for an allowlist. With a custom Cloudflare `getSandbox`, `network` stays `unknown`. Use `"trusted-host"` only when the Agent may act with the host user's authority, and use an isolated Sandbox runtime such as `vercel`, `cloudflare`, or `container` for untrusted code.
|
|
321
|
+
|
|
322
|
+
Resolved environment values, file contents, state keys, and physical Home paths are excluded from `sandbox.plan`; `sandbox.plan.home.state` lists declared target paths with opaque stable identities. Requirement failures discard command output, while every process inside the Sandbox remains trusted and can still read or log its credentials. Stable preparation identity uses declaration targets and state keys, never secret values or temporary paths.
|
|
323
|
+
|
|
324
|
+
Sandbox does not own Workspace snapshots, diffs, or commits. Workspace materializes those files through `SandboxSession.files`, while Sandbox remains responsible for execution and lifecycle.
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
## Trusted SSH command transport
|
|
328
|
+
|
|
329
|
+
`@vite-hub/sandbox/ssh` exports `sshLaunch` for Agent provider launch callbacks and `serveSsh` for a trusted sidecar. The client requires Node and OpenSSH. The server requires the optional `ssh2` peer.
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
import { sshLaunch } from "@vite-hub/sandbox/ssh"
|
|
333
|
+
|
|
334
|
+
const launch = sshLaunch({
|
|
335
|
+
host: "127.0.0.1",
|
|
336
|
+
port: 2222,
|
|
337
|
+
user: "agent",
|
|
338
|
+
identityFile: "/ssh/id_ed25519",
|
|
339
|
+
hostKeyFile: "/ssh/ssh_host_ed25519_key.pub",
|
|
340
|
+
})
|
|
341
|
+
// Pass launch to driver.launch in an Agent Definition.
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
The target must expose the same working-directory and credential paths, for example through a shared sidecar volume. Host keys are verified. Environment names come from the resolved provider launch context; values travel through SSH environment requests. An explicit `forwardEnvironment` narrows the list while retaining framework-required names. `serveSsh` accepts valid environment names from authenticated clients unless `acceptEnvironment` restricts them. It runs each command with `/bin/sh -c`, not a login shell, so a profile cannot replace the forwarded `PATH`.
|
|
345
|
+
|
|
346
|
+
A sidecar that is still starting refuses connections. `sshLaunch` connects again for up to `connectRetryMs` (30 seconds by default) while the SSH port refuses connections, so a provider probe or launch right after a pod restart waits for the sidecar. Authentication, host key, and command failures are not retried. Set `connectRetryMs: 0` to fail on the first refused connection.
|
|
347
|
+
|
|
348
|
+
The launch command includes a cancellable `prepare` callback. Agent Drivers await it before starting provider probe deadlines, for both Codex and Claude. It runs a separate `/bin/true` connection check; direct process consumers can await it before starting their own deadline. OpenSSH local diagnostics are kept separate from remote stderr so a command that starts another failing SSH client is never repeated.
|
|
349
|
+
|
|
350
|
+
The `vite-hub` distribution also exposes this module as `vite-hub/sandbox/ssh`, and `vitehub sandbox serve` and `vitehub sandbox check` run the server and a Driver readiness check without a project config. See the [CLI reference](https://vitehub.dev/docs/development/cli#commands).
|
|
351
|
+
|
|
352
|
+
This transport grants arbitrary command execution as the configured user. It is not a sandbox and does not synchronize Workspace files. Server shutdown closes connections and stops supervised process groups. When a command ends, the server stops its process group. On Linux it also stops the processes that the command started outside that group, for example with `setsid`. It finds them by the `VITEHUB_SSH_COMMAND` environment variable. `close({ drainTimeoutMs })` stops new connections at once and waits up to `drainTimeoutMs` for open connections to close before it ends them, so a stopping container can let running commands finish. `connections` counts the open connections. `vitehub sandbox serve --drain-timeout <ms>` uses this on SIGTERM and SIGINT.
|
|
353
|
+
|
|
354
|
+
## Sandbox Tasks
|
|
355
|
+
|
|
356
|
+
A Sandbox Task is one job that runs inside one Sandbox. `@vite-hub/sandbox/task` runs a discovered Sandbox Task Definition inside a provider-backed Sandbox. It owns discovery, package staging, typed invocation, timeouts, and result transport. The rest of this package owns the Sandbox: the execution environment and its isolation.
|
|
357
|
+
|
|
358
|
+
Most applications should install [`vite-hub`](https://vitehub.dev/docs/getting-started/installation) and import APIs such as `runSandboxTask` from `vite-hub/sandbox/task`. Import `@vite-hub/sandbox/task` directly when you are building a library, a custom Vite composition, or package-level tooling.
|
|
359
|
+
|
|
360
|
+
### Install
|
|
361
|
+
|
|
362
|
+
Install Sandbox, TypeScript, Vite, and the Sandbox provider used by your deployment. Sandbox Tasks read their Definitions with TypeScript at build time. This first run uses Vercel Sandbox:
|
|
10
363
|
|
|
11
364
|
```sh
|
|
12
|
-
pnpm add @vite-hub/sandbox @vercel/sandbox vite
|
|
365
|
+
pnpm add @vite-hub/sandbox typescript @vercel/sandbox vite
|
|
13
366
|
```
|
|
14
367
|
|
|
15
|
-
Sandbox requires Node.js
|
|
368
|
+
Sandbox Task requires Node.js 22.18 or newer. The Vercel provider accepts `@vercel/sandbox` 3.9 and 4. Version 4 requires Node.js 22.19 or newer. Vercel execution also requires a Vercel project with Sandbox access. At runtime, use the project's environment or set `VERCEL_TOKEN`, `VERCEL_TEAM_ID`, and `VERCEL_PROJECT_ID`.
|
|
16
369
|
|
|
17
|
-
For Cloudflare, install `@cloudflare/sandbox` instead and use the ViteHub Cloudflare host integration so it can emit the required Container, Durable Object binding, migration, and Worker exports. Both providers run remote, potentially billed infrastructure; Sandbox does not include a local in-process provider.
|
|
370
|
+
For Cloudflare, install `@cloudflare/sandbox` 1.x instead and use the ViteHub Cloudflare host integration so it can emit the required Container, Durable Object binding, migration, and Worker exports. Both providers run remote, potentially billed infrastructure; Sandbox does not include a local in-process provider.
|
|
18
371
|
|
|
19
|
-
|
|
372
|
+
### Run one Sandbox Task
|
|
20
373
|
|
|
21
|
-
Register discovery and select the
|
|
374
|
+
Register discovery and select the driver in Vite:
|
|
22
375
|
|
|
23
376
|
```ts
|
|
24
377
|
// vite.config.ts
|
|
25
|
-
import {
|
|
378
|
+
import { hubSandboxTask } from "@vite-hub/sandbox/task/vite";
|
|
26
379
|
import { defineConfig } from "vite";
|
|
27
380
|
|
|
28
381
|
export default defineConfig({
|
|
29
|
-
plugins: [
|
|
382
|
+
plugins: [hubSandboxTask({ driver: "vercel" })],
|
|
30
383
|
build: {
|
|
31
384
|
ssr: "src/server.ts",
|
|
32
385
|
},
|
|
33
386
|
});
|
|
34
387
|
```
|
|
35
388
|
|
|
36
|
-
Create a package-backed Definition at `server/
|
|
389
|
+
Create a package-backed Definition at `server/sandbox-tasks/release-notes/package.json`. The folder path supplies the name `release-notes`, and its manifest owns the timeout for each execution attempt:
|
|
37
390
|
|
|
38
391
|
```json
|
|
39
392
|
{
|
|
40
393
|
"private": true,
|
|
41
394
|
"type": "module",
|
|
42
395
|
"vitehub": {
|
|
43
|
-
"
|
|
396
|
+
"sandboxTask": {
|
|
44
397
|
"timeout": 30000
|
|
45
398
|
}
|
|
46
399
|
}
|
|
@@ -48,7 +401,7 @@ Create a package-backed Definition at `server/sandboxes/release-notes/package.js
|
|
|
48
401
|
```
|
|
49
402
|
|
|
50
403
|
```ts
|
|
51
|
-
// server/
|
|
404
|
+
// server/sandbox-tasks/release-notes/index.ts
|
|
52
405
|
interface ReleaseNotesPayload {
|
|
53
406
|
notes?: string;
|
|
54
407
|
}
|
|
@@ -58,19 +411,19 @@ export default async function releaseNotes(payload: ReleaseNotesPayload = {}) {
|
|
|
58
411
|
}
|
|
59
412
|
```
|
|
60
413
|
|
|
61
|
-
Invoke the discovered name from server code. `
|
|
414
|
+
Invoke the discovered name from server code. `runSandboxTask()` returns a native Web `Response` and infers its payload from the Definition. A registered handler with a required payload requires that argument at invocation; optional and zero-argument handlers can be invoked without it. The handler's context defaults to `{}` when omitted:
|
|
62
415
|
|
|
63
416
|
```ts
|
|
64
417
|
// src/server.ts
|
|
65
|
-
import {
|
|
418
|
+
import { runSandboxTask } from "@vite-hub/sandbox/task";
|
|
66
419
|
|
|
67
|
-
const
|
|
420
|
+
const response = await runSandboxTask("release-notes", {
|
|
68
421
|
notes: "ship it\nadd tests",
|
|
69
422
|
});
|
|
70
423
|
|
|
71
|
-
if (
|
|
424
|
+
if (!response.ok) throw new Error(await response.text());
|
|
72
425
|
|
|
73
|
-
console.log(JSON.stringify(
|
|
426
|
+
console.log(JSON.stringify(await response.json()));
|
|
74
427
|
```
|
|
75
428
|
|
|
76
429
|
Build through Vite so discovery and the runtime registry are generated, then run the server entry:
|
|
@@ -86,44 +439,49 @@ The process prints:
|
|
|
86
439
|
{ "summary": "ship it" }
|
|
87
440
|
```
|
|
88
441
|
|
|
89
|
-
The Definition entrypoint does not import `@vite-hub/sandbox`. ViteHub calls its default function with `(payload, context)` and returns its awaited result.
|
|
442
|
+
The Definition entrypoint does not import `@vite-hub/sandbox/task`. ViteHub calls its default function with `(payload, context)` and returns its awaited result.
|
|
443
|
+
|
|
444
|
+
### Provider and lifecycle limits
|
|
90
445
|
|
|
91
|
-
|
|
446
|
+
- Set `cpu` (vCPUs) and `memory` (MiB) next to `driver`, such as `hubSandboxTask({ driver: "cloudflare", cpu: 1, memory: 4096 })`. They are minimums, and ViteHub picks the smallest driver size that fits both. Vercel gets `resources.vcpus`: 1 or an even number up to 32, with 2048 MiB for each vCPU. Cloudflare gets the smallest instance type from `lite` to `standard-4`, and the default is `standard-1` (1/2 vCPU, 4096 MiB). On Cloudflare the size belongs to the Container class, so it applies to every task of the app. ViteHub keeps the `instance_type` of your own `containers` entry and fails the build when it is smaller than `cpu` or `memory`. `maxInstances` sets the Cloudflare Container limit (default 12).
|
|
447
|
+
- Driver selection belongs to application or host configuration, not to a Definition. `hubSandboxTask({ driver: "vercel" })` and `hubSandboxTask({ driver: "cloudflare" })` are the direct-package forms. The `vite-hub` distribution infers the driver from its Vercel and Cloudflare hosts, and takes the same options in `vitehub({ sandboxTask: { ... } })`.
|
|
448
|
+
- `vitehub.sandboxTask.timeout` must be a positive integer no greater than `2_147_483_647`. Without it, a run stops after 5 minutes on every driver. It bounds one execution attempt after driver startup, including package preparation, staging, and execution. Queueing, Sandbox startup, and retry delays can make the complete `runSandboxTask()` call take longer. An elapsed attempt timeout sends an internal abort signal to cancellable driver operations and returns a `SANDBOX_TASK_TIMEOUT` error in a non-2xx JSON response. On Vercel, the Sandbox session gets the task timeout plus 30 seconds, because its clock starts before Sandbox setup. ViteHub then ends the run at the task timeout, not the VM.
|
|
449
|
+
- Pass `signal` to `runSandboxTask()` when it belongs to a request or Agent Invocation. ViteHub forwards it to Sandbox startup and execution, cancels queued Cloudflare runs and retry backoff, and preserves the caller's abort reason. A Definition timeout remains the independent bound for each execution attempt.
|
|
450
|
+
- A failed run's JSON response keeps `error.code`, `error.message`, and `error.details`. Outside `vite dev`, the details do not include `stack`, `stdout`, `stderr`, their previews, `output`, `cause`, `cwd`, or `args`. `resolveSandboxTaskRunner(name).run()` throws the error with all details for server logs.
|
|
451
|
+
- Vercel Sandbox sessions are closed in a `finally` block after success or failure. Cloudflare also creates and closes a unique Sandbox for each run unless you configure `sandboxId` or pass one to `runSandboxTask()`. Session cleanup failures return a non-2xx JSON response, even after a successful handler. So do Cloudflare invocation-file cleanup failures in a Sandbox that stays open after the run. A Sandbox that ViteHub closes after the run loses its files when it closes, so ViteHub does not delete them separately.
|
|
452
|
+
- Cloudflare can retry the whole Task before its first command starts. After that, only the transport retries an individual command when a cold start proves it did not run. Handler errors do not replay the Task.
|
|
453
|
+
- An explicit Cloudflare `sandboxId` opts into a shared Sandbox identity. ViteHub deletes invocation-local files after each attempt, caches prepared projects by digest inside that Sandbox, and serializes runs with the same ID within one runtime isolate. Separate Worker isolates can still enter the Sandbox concurrently, so use external coordination when deployment-wide serialization is required. ViteHub leaves an explicitly named Sandbox for idle shutdown after every run, also after a timeout or an abort. A timeout or an abort stops only that run's command, so runs from other isolates keep their Container. `sleepAfter` sets the idle time (default `"5m"`), and `keepAlive: true` raises it to the 6 hour Cloudflare maximum. A Sandbox without an ID still closes after each run, also with `keepAlive: true`.
|
|
92
454
|
|
|
93
|
-
|
|
94
|
-
- `vitehub.sandbox.timeout` must be a positive integer no greater than `2_147_483_647`. It bounds one execution attempt after provider startup, including package preparation, staging, and execution. Queueing, Box startup, and retry delays can make the complete `runSandbox()` call take longer. An elapsed attempt timeout sends an internal abort signal to cancellable provider operations and returns a `SANDBOX_TIMEOUT` error in the tuple.
|
|
95
|
-
- Callers cannot currently pass an `AbortSignal` to `runSandbox()`. A disconnected request does not by itself cancel the run; configure a Definition timeout to bound each execution attempt.
|
|
96
|
-
- Vercel Box sessions are closed in a `finally` block after success or failure. Cloudflare also creates and closes a unique Box for each run unless you configure `sandboxId` or pass one to `runSandbox()`. Cleanup failures are surfaced through the `runSandbox()` error tuple; they are not suppressed after a successful handler.
|
|
97
|
-
- An explicit Cloudflare `sandboxId` opts into a shared Box identity. ViteHub deletes invocation-local files after each attempt, caches prepared projects by digest inside that Box, and serializes runs with the same ID within one runtime isolate. Separate Worker isolates can still enter the Box concurrently, so use external coordination when deployment-wide serialization is required. The provider normally leaves an explicitly named Box for idle shutdown; setting `keepAlive: true` makes ViteHub close its session after the run.
|
|
455
|
+
When `resolveSandboxTaskRunner().run()` throws, its error cause retains the original provider diagnostic. If execution and cleanup both fail, the cause chain contains an `AggregateError` with both failures. The primary error code and message stay unchanged. JSON error responses omit causes.
|
|
98
456
|
|
|
99
|
-
|
|
457
|
+
### Security and isolation
|
|
100
458
|
|
|
101
|
-
A Sandbox Definition name and its typed arguments select work; they are not a permission boundary. Code inside the
|
|
459
|
+
A Sandbox Task Definition name and its typed arguments select work; they are not a permission boundary. Code inside the Sandbox can use whatever filesystem, environment, network, credentials, executables, and child-process authority the selected provider exposes.
|
|
102
460
|
|
|
103
461
|
Inspect that authority before execution when application policy depends on it:
|
|
104
462
|
|
|
105
463
|
```ts
|
|
106
|
-
import {
|
|
464
|
+
import { resolveSandboxTaskRunner } from "@vite-hub/sandbox/task";
|
|
107
465
|
|
|
108
|
-
const runner = await
|
|
466
|
+
const runner = await resolveSandboxTaskRunner("release-notes");
|
|
109
467
|
console.log(runner.executionAuthority);
|
|
110
468
|
```
|
|
111
469
|
|
|
112
|
-
The descriptor reports the provider's complete `ExecutionAuthority`, including dimensions it cannot establish as `unknown`.
|
|
470
|
+
The descriptor reports the provider's complete `ExecutionAuthority`, including dimensions it cannot establish as `unknown`. Set `networkPolicy` in the `vercel` or `cloudflare` provider options to limit outbound traffic, keep secrets in server environment or provider configuration, and do not treat container execution alone as authorization for untrusted code.
|
|
113
471
|
|
|
114
|
-
Payloads, context, and results must be JSON-serializable. Nested `Blob` and `Uint8Array` values cross the
|
|
472
|
+
Payloads, context, and results must be JSON-serializable. Nested `Blob` and `Uint8Array` values cross the Sandbox boundary through invocation-local binary files, and Node.js `Buffer` values retain their type.
|
|
115
473
|
|
|
116
|
-
|
|
474
|
+
### Package projects
|
|
117
475
|
|
|
118
|
-
ViteHub uses the package manifest's `packageManager`, then a lockfile at that package root, then npm. A matching `pnpm-workspace.yaml` moves preparation to the pnpm Workspace root and carries the transitive `workspace:*` dependency closure into the
|
|
476
|
+
ViteHub uses the package manifest's `packageManager`, then a lockfile at that package root, then npm. A matching `pnpm-workspace.yaml` moves preparation to the pnpm Workspace root and carries the transitive `workspace:*` dependency closure into the Sandbox while the entrypoint still runs from its package directory.
|
|
119
477
|
|
|
120
478
|
Package entrypoints are ESM projects. Keep `"type": "module"`, use explicit relative ESM imports for local `.ts` and `.mts` source, and depend on packages that expose runtime-ready JavaScript. ViteHub compiles reachable local TypeScript without bundling package dependencies or moving relative assets. It rejects CommonJS/CTS, local package aliases and self-references, imports that escape the selected package, and Workspace dependencies that expose TypeScript runtime entries.
|
|
121
479
|
|
|
122
|
-
Use `<path>.sandbox.ts` with `
|
|
480
|
+
Use `<path>.sandbox-task.ts` with `defineSandboxTask()` for a free-form Definition outside `server/sandbox-tasks`. Free-form Definitions use their nearest package project.
|
|
123
481
|
|
|
124
|
-
|
|
482
|
+
### Read more about Sandbox Tasks
|
|
125
483
|
|
|
126
|
-
- [Sandbox guide](https://vitehub.dev/docs/
|
|
127
|
-
- [
|
|
484
|
+
- [Sandbox Task guide](https://vitehub.dev/docs/sandbox)
|
|
485
|
+
- [Sandbox execution and security model](https://vitehub.dev/docs/agents/sandboxes)
|
|
128
486
|
- [Runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix)
|
|
129
487
|
- [ViteHub security policy](https://github.com/vite-hub/vitehub/blob/main/SECURITY.md)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
//#region src/internal/abortable.ts
|
|
2
|
+
/**
|
|
3
|
+
* Wait for a promise until the caller's signal aborts.
|
|
4
|
+
*
|
|
5
|
+
* The underlying operation is intentionally not cancelled. This helper only
|
|
6
|
+
* stops waiting for it and rejects with the signal reason.
|
|
7
|
+
*/
|
|
8
|
+
function abortable(promise, signal) {
|
|
9
|
+
if (!signal) return promise;
|
|
10
|
+
signal.throwIfAborted();
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const onAbort = () => {
|
|
13
|
+
signal.removeEventListener("abort", onAbort);
|
|
14
|
+
reject(signal.reason);
|
|
15
|
+
};
|
|
16
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
17
|
+
promise.then((value) => {
|
|
18
|
+
signal.removeEventListener("abort", onAbort);
|
|
19
|
+
resolve(value);
|
|
20
|
+
}, (error) => {
|
|
21
|
+
signal.removeEventListener("abort", onAbort);
|
|
22
|
+
reject(error);
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Kills a started process when the signal aborts, so a timeout or cancellation stops only that command.
|
|
28
|
+
* After an abort, `wait()` rejects with the signal reason.
|
|
29
|
+
*/
|
|
30
|
+
function killOnAbort(process, signal) {
|
|
31
|
+
if (!signal) return process;
|
|
32
|
+
let killed;
|
|
33
|
+
const abort = () => {
|
|
34
|
+
killed = process.kill("KILL").catch(() => void 0);
|
|
35
|
+
};
|
|
36
|
+
if (signal.aborted) abort();
|
|
37
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
38
|
+
const exit = process.wait().finally(() => signal.removeEventListener("abort", abort));
|
|
39
|
+
exit.catch(() => void 0);
|
|
40
|
+
return {
|
|
41
|
+
pid: process.pid,
|
|
42
|
+
stderr: process.stderr,
|
|
43
|
+
get stdin() {
|
|
44
|
+
return process.stdin;
|
|
45
|
+
},
|
|
46
|
+
stdout: process.stdout,
|
|
47
|
+
kill: async (signal) => await process.kill(signal),
|
|
48
|
+
async wait() {
|
|
49
|
+
const result = await exit;
|
|
50
|
+
if (!killed) return result;
|
|
51
|
+
await killed;
|
|
52
|
+
throw signal.reason;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { killOnAbort as n, abortable as t };
|