@vite-hub/sandbox 0.1.0 → 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 +118 -53
- 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-BFCdf41h.js → crabbox-sbV3Zjuo.js} +10 -6
- package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
- package/dist/error-diagnostics-BJtLRL9w.js +536 -0
- package/dist/{file-listing-DECFTdSl.js → file-listing-CHtRrfo1.js} +1 -1
- package/dist/{file-lock-CxyVl4Cv.js → file-lock-D0-XPogS.js} +3 -2
- package/dist/{index-CXej1Bt0.d.ts → index-DsoQAUb7.d.ts} +94 -19
- package/dist/index.d.ts +2 -2
- package/dist/index.js +15 -10
- package/dist/internal/cloudflare.d.ts +173 -1
- package/dist/internal/cloudflare.js +4 -12
- package/dist/internal/host-toolchain.d.ts +1 -1
- package/dist/internal/host-toolchain.js +6 -7
- package/dist/internal/vercel.d.ts +1 -1
- package/dist/internal/vercel.js +3 -11
- 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-1Jz2oUMK.js → remote-70ZVZZlq.js} +32 -14
- package/dist/runtime-type-Deo4qzxN.js +9 -0
- package/dist/{session-DD0S1PDC.js → session-e0lyzjJ3.js} +2 -1
- package/dist/size-7AkVwGZb.js +118 -0
- package/dist/ssh.d.ts +8 -0
- package/dist/ssh.js +107 -40
- package/dist/task/index.d.ts +19 -17
- package/dist/task/index.js +92 -201
- package/dist/task/runtime/provider-loader.d.ts +7 -9
- package/dist/task/runtime/provider-loader.js +2 -5
- package/dist/task/runtime/providers/cloudflare.d.ts +5 -19
- package/dist/task/runtime/providers/cloudflare.js +7 -6
- package/dist/task/runtime/providers/vercel.d.ts +3 -3
- package/dist/task/runtime/providers/vercel.js +35 -4
- package/dist/task/runtime/state.d.ts +4 -1
- package/dist/task/runtime/state.js +11 -2
- package/dist/task/vite.d.ts +143 -17
- package/dist/task/vite.js +723 -400
- package/dist/{toolchain-BUVXtQ2m.js → toolchain-BIVGMRty.js} +12 -11
- package/dist/{trusted-host-DNMJ-Oig.js → trusted-host-kxkpaQcs.js} +21 -179
- package/dist/{vercel-Jtxa9TJx.js → vercel-BGGrNpza.js} +107 -34
- package/package.json +15 -12
- package/dist/cloudflare-DO0h3Ncf.js +0 -281
- package/dist/cloudflare-env-BBJaBbuQ.js +0 -39
- package/dist/error-diagnostics-BSysPv-D.js +0 -166
- package/dist/error-diagnostics-dGQqfgLt.js +0 -99
- package/dist/module-types-BfyRBaiP.js +0 -7
- package/dist/module-types-Cis4hrF1.d.ts +0 -95
- package/dist/runtime-type-DrmrW5m5.js +0 -42
|
@@ -0,0 +1,868 @@
|
|
|
1
|
+
import { r as markBuiltInSandboxRuntime } from "./runtime-DHp6ImeP.js";
|
|
2
|
+
import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
|
|
3
|
+
import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
|
|
4
|
+
import { t as listCommandFiles } from "./file-listing-CHtRrfo1.js";
|
|
5
|
+
import { i as resolveRemoteEnvironment, n as openRemoteSandbox, r as remoteSandboxPlan } from "./remote-70ZVZZlq.js";
|
|
6
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
7
|
+
import { posix } from "node:path";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
10
|
+
import { Readable, Writable } from "node:stream";
|
|
11
|
+
//#region src/internal/container-broker.ts
|
|
12
|
+
/**
|
|
13
|
+
* mitmproxy addon for the container runtime broker. It is the only network exit of a
|
|
14
|
+
* caged Sandbox. It enforces the egress allowlist and swaps credential placeholders for
|
|
15
|
+
* real values, only in HTTPS request headers sent to the hosts that a credential names.
|
|
16
|
+
*
|
|
17
|
+
* The design follows the broker of antfu/dev-container (MIT).
|
|
18
|
+
*/
|
|
19
|
+
const containerBrokerAddon = String.raw`
|
|
20
|
+
import base64
|
|
21
|
+
import binascii
|
|
22
|
+
import ipaddress
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import re
|
|
26
|
+
|
|
27
|
+
from mitmproxy import http
|
|
28
|
+
|
|
29
|
+
PLACEHOLDER = re.compile(r"vitehub-[A-Za-z_][A-Za-z0-9_]*-[0-9a-f]{32}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def log(event, **fields):
|
|
33
|
+
print(json.dumps({"event": event, **fields}), flush=True)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def normalize(host):
|
|
37
|
+
return (host or "").lower().rstrip(".")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def authority_host(value):
|
|
41
|
+
value = (value or "").strip()
|
|
42
|
+
if value.startswith("["):
|
|
43
|
+
return normalize(value[1:value.find("]")])
|
|
44
|
+
return normalize(value.rpartition(":")[0] if value.count(":") == 1 else value)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def is_ip(host):
|
|
48
|
+
try:
|
|
49
|
+
ipaddress.ip_address(host)
|
|
50
|
+
return True
|
|
51
|
+
except ValueError:
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def host_matches(pattern, host, port):
|
|
56
|
+
name, _, want_port = pattern.lower().partition(":")
|
|
57
|
+
if int(want_port or "443") != port:
|
|
58
|
+
return False
|
|
59
|
+
if name.startswith("*."):
|
|
60
|
+
return host.endswith(name[1:])
|
|
61
|
+
return host == name
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Blocked(Exception):
|
|
65
|
+
def __init__(self, code, why):
|
|
66
|
+
super().__init__(why)
|
|
67
|
+
self.code = code
|
|
68
|
+
self.why = why
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Broker:
|
|
72
|
+
def __init__(self):
|
|
73
|
+
config = json.loads(os.environ["VITEHUB_BROKER_RULES"])
|
|
74
|
+
self.policy = config["policy"]
|
|
75
|
+
self.allow = tuple(config["allow"])
|
|
76
|
+
self.secrets = {}
|
|
77
|
+
for index, secret in enumerate(config["secrets"]):
|
|
78
|
+
self.secrets[secret["placeholder"]] = {
|
|
79
|
+
"hosts": tuple(secret["hosts"]),
|
|
80
|
+
"name": secret["name"],
|
|
81
|
+
"value": os.environ.get("VITEHUB_BROKER_SECRET_%d" % index, ""),
|
|
82
|
+
}
|
|
83
|
+
log("ready", policy=self.policy, secrets=[s["name"] for s in self.secrets.values()])
|
|
84
|
+
|
|
85
|
+
def allowed(self, host, port):
|
|
86
|
+
if self.policy == "open":
|
|
87
|
+
return True
|
|
88
|
+
patterns = self.allow + tuple(h for s in self.secrets.values() for h in s["hosts"])
|
|
89
|
+
return any(host_matches(p, host, port) for p in patterns)
|
|
90
|
+
|
|
91
|
+
def block(self, flow, blocked):
|
|
92
|
+
request = flow.request
|
|
93
|
+
log("block", host=request.host, port=request.port, method=request.method,
|
|
94
|
+
path=request.path.partition("?")[0], code=blocked.code, why=blocked.why)
|
|
95
|
+
flow.metadata["vitehub_logged"] = True
|
|
96
|
+
flow.response = http.Response.make(
|
|
97
|
+
403,
|
|
98
|
+
"[%s] %s\n" % (blocked.code, blocked.why),
|
|
99
|
+
{"content-type": "text/plain; charset=utf-8", "x-vitehub-sandbox-diagnostic": blocked.code},
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
def http_connect(self, flow):
|
|
103
|
+
# A tunnel that does not carry HTTP never reaches request(), so check egress here too.
|
|
104
|
+
host = normalize(flow.request.host)
|
|
105
|
+
if not self.allowed(host, flow.request.port):
|
|
106
|
+
self.block(flow, Blocked("SANDBOX_BROKER_B001", "Host %s is not on the Sandbox egress allowlist." % host))
|
|
107
|
+
|
|
108
|
+
def request(self, flow):
|
|
109
|
+
request = flow.request
|
|
110
|
+
# Inside a CONNECT tunnel, mitmproxy takes host and port from the tunnel target,
|
|
111
|
+
# not from the Host header that the Sandbox controls.
|
|
112
|
+
host = normalize(request.host)
|
|
113
|
+
port = request.port
|
|
114
|
+
try:
|
|
115
|
+
# The TLS server name and the Host header pick the upstream site on shared hosting.
|
|
116
|
+
# Both must name the CONNECT target, or a request could reach another site there.
|
|
117
|
+
# Clients send no server name for an IP address.
|
|
118
|
+
sni = flow.client_conn.sni
|
|
119
|
+
if request.scheme == "https" and normalize(sni) != host and not (sni is None and is_ip(host)):
|
|
120
|
+
raise Blocked("SANDBOX_BROKER_B007", "The TLS server name does not match the host %s." % host)
|
|
121
|
+
if request.host_header is not None and authority_host(request.host_header) != host:
|
|
122
|
+
raise Blocked("SANDBOX_BROKER_B007", "The Host header does not match the host %s." % host)
|
|
123
|
+
if not self.allowed(host, port):
|
|
124
|
+
raise Blocked("SANDBOX_BROKER_B001", "Host %s is not on the Sandbox egress allowlist." % host)
|
|
125
|
+
if PLACEHOLDER.search(request.url):
|
|
126
|
+
raise Blocked("SANDBOX_BROKER_B002", "A credential placeholder is in the URL. Send credentials only in request headers.")
|
|
127
|
+
injected = []
|
|
128
|
+
|
|
129
|
+
def swap(match):
|
|
130
|
+
secret = self.secrets.get(match.group(0))
|
|
131
|
+
if secret is None:
|
|
132
|
+
raise Blocked("SANDBOX_BROKER_B003", "The request has an unknown credential placeholder. Read the credential from its environment variable again.")
|
|
133
|
+
if not any(host_matches(p, host, port) for p in secret["hosts"]):
|
|
134
|
+
raise Blocked("SANDBOX_BROKER_B004", "%s is not bound to %s." % (secret["name"], host))
|
|
135
|
+
if request.scheme != "https":
|
|
136
|
+
raise Blocked("SANDBOX_BROKER_B005", "The broker sends %s only over HTTPS." % secret["name"])
|
|
137
|
+
if not secret["value"]:
|
|
138
|
+
raise Blocked("SANDBOX_BROKER_B006", "%s has no value." % secret["name"])
|
|
139
|
+
if secret["name"] not in injected:
|
|
140
|
+
injected.append(secret["name"])
|
|
141
|
+
return secret["value"]
|
|
142
|
+
|
|
143
|
+
headers = []
|
|
144
|
+
for name, value in request.headers.items(multi=True):
|
|
145
|
+
headers.append((name, substitute_header(value, lambda text: PLACEHOLDER.sub(swap, text))))
|
|
146
|
+
except Blocked as blocked:
|
|
147
|
+
self.block(flow, blocked)
|
|
148
|
+
return
|
|
149
|
+
if injected:
|
|
150
|
+
request.headers = http.Headers(
|
|
151
|
+
[(k.encode("utf-8", "surrogateescape"), v.encode("utf-8", "surrogateescape")) for k, v in headers]
|
|
152
|
+
)
|
|
153
|
+
flow.metadata["vitehub_injected"] = injected
|
|
154
|
+
|
|
155
|
+
def response(self, flow):
|
|
156
|
+
if flow.metadata.get("vitehub_logged"):
|
|
157
|
+
return
|
|
158
|
+
request = flow.request
|
|
159
|
+
log("request", host=request.host, port=request.port, method=request.method,
|
|
160
|
+
path=request.path.partition("?")[0], status=flow.response.status_code if flow.response else 0,
|
|
161
|
+
injected=flow.metadata.get("vitehub_injected", []))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def substitute_header(value, substitute):
|
|
165
|
+
scheme, _, credentials = value.partition(" ")
|
|
166
|
+
if scheme.lower() == "basic" and credentials:
|
|
167
|
+
try:
|
|
168
|
+
decoded = base64.b64decode(credentials.strip(), validate=True).decode("utf-8")
|
|
169
|
+
except (binascii.Error, UnicodeDecodeError):
|
|
170
|
+
return substitute(value)
|
|
171
|
+
replaced = substitute(decoded)
|
|
172
|
+
if replaced != decoded:
|
|
173
|
+
return scheme + " " + base64.b64encode(replaced.encode("utf-8")).decode("ascii")
|
|
174
|
+
return value
|
|
175
|
+
return substitute(value)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
addons = [Broker()]
|
|
179
|
+
`;
|
|
180
|
+
/** Starts mitmdump with the addon. The CA private key stays in the broker container. */
|
|
181
|
+
const containerBrokerEntrypoint = [
|
|
182
|
+
"set -eu",
|
|
183
|
+
"mkdir -p /tmp/vitehub-broker",
|
|
184
|
+
"printf '%s' \"$VITEHUB_BROKER_ADDON\" > /tmp/vitehub-broker/addon.py",
|
|
185
|
+
"exec mitmdump --listen-host 0.0.0.0 --listen-port 8080 --quiet --set connection_strategy=lazy --set rawtcp=false --set confdir=/tmp/vitehub-broker -s /tmp/vitehub-broker/addon.py"
|
|
186
|
+
].join("\n");
|
|
187
|
+
const containerBrokerCaPath = "/tmp/vitehub-broker/mitmproxy-ca-cert.pem";
|
|
188
|
+
//#endregion
|
|
189
|
+
//#region src/internal/container.ts
|
|
190
|
+
const defaultContainerBrokerImage = "mitmproxy/mitmproxy:12.2.3";
|
|
191
|
+
const brokerAlias = "vitehub-broker";
|
|
192
|
+
const brokerPort = 8080;
|
|
193
|
+
const sandboxRoot = "/vitehub";
|
|
194
|
+
const sandboxHome = `${sandboxRoot}/home`;
|
|
195
|
+
const sandboxWorkspace = `${sandboxRoot}/workspace`;
|
|
196
|
+
const brokerCaTarget = `${sandboxRoot}/broker-ca.pem`;
|
|
197
|
+
const pidDirectory = `${sandboxRoot}/.pids`;
|
|
198
|
+
const hostPattern = /^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?::\d{1,5})?$/;
|
|
199
|
+
const environmentName = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
200
|
+
const reservedCredentialNames = /* @__PURE__ */ new Set([
|
|
201
|
+
"ALL_PROXY",
|
|
202
|
+
"CODEX_HOME",
|
|
203
|
+
"CURL_CA_BUNDLE",
|
|
204
|
+
"GIT_SSL_CAINFO",
|
|
205
|
+
"HOME",
|
|
206
|
+
"HTTPS_PROXY",
|
|
207
|
+
"HTTP_PROXY",
|
|
208
|
+
"INIT_CWD",
|
|
209
|
+
"NODE_EXTRA_CA_CERTS",
|
|
210
|
+
"NODE_USE_ENV_PROXY",
|
|
211
|
+
"NO_PROXY",
|
|
212
|
+
"OLDPWD",
|
|
213
|
+
"PATH",
|
|
214
|
+
"PWD",
|
|
215
|
+
"REQUESTS_CA_BUNDLE",
|
|
216
|
+
"SSL_CERT_FILE",
|
|
217
|
+
"XDG_CACHE_HOME",
|
|
218
|
+
"XDG_CONFIG_HOME",
|
|
219
|
+
"XDG_STATE_HOME"
|
|
220
|
+
]);
|
|
221
|
+
/** Names that the Docker CLI reads itself. Their Sandbox values travel on the command line instead of the CLI environment. */
|
|
222
|
+
const cliEnvironment = (name) => name === "PATH" || name === "HOME" || name.startsWith("DOCKER_") || name.startsWith("XDG_");
|
|
223
|
+
function createContainerRuntime(options) {
|
|
224
|
+
const normalized = normalizeContainerOptions(options);
|
|
225
|
+
const executionAuthority = containerExecutionAuthority(normalized);
|
|
226
|
+
return markBuiltInSandboxRuntime({
|
|
227
|
+
name: "container",
|
|
228
|
+
async prepare(input) {
|
|
229
|
+
assertCredentialNames(input, normalized);
|
|
230
|
+
return remoteSandboxPlan(input, {
|
|
231
|
+
executionAuthority,
|
|
232
|
+
runtime: "container"
|
|
233
|
+
});
|
|
234
|
+
},
|
|
235
|
+
async open(input, openOptions) {
|
|
236
|
+
assertCredentialNames(input, normalized);
|
|
237
|
+
openOptions.signal?.throwIfAborted();
|
|
238
|
+
const env = await resolveRemoteEnvironment(input, {
|
|
239
|
+
home: sandboxHome,
|
|
240
|
+
workspace: sandboxWorkspace
|
|
241
|
+
});
|
|
242
|
+
const runtimeSession = await startContainer(normalized, env, openOptions.id ?? `vitehub-${randomUUID()}`, openOptions.signal);
|
|
243
|
+
return await openRemoteSandbox(input, runtimeSession, {
|
|
244
|
+
executionAuthority: openOptions.executionAuthority,
|
|
245
|
+
home: sandboxHome,
|
|
246
|
+
initialize: openOptions.initialize,
|
|
247
|
+
runtime: "container",
|
|
248
|
+
signal: openOptions.signal,
|
|
249
|
+
workspace: sandboxWorkspace
|
|
250
|
+
}, env);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
function containerExecutionAuthority(options) {
|
|
255
|
+
return {
|
|
256
|
+
credentials: options.credentials.length ? "provisioned" : "unknown",
|
|
257
|
+
environment: "selected",
|
|
258
|
+
filesystem: {
|
|
259
|
+
access: "read-write",
|
|
260
|
+
scope: "sandbox"
|
|
261
|
+
},
|
|
262
|
+
isolation: "container",
|
|
263
|
+
network: options.egress.policy === "none" ? "none" : options.egress.policy === "open" ? "unrestricted" : "restricted",
|
|
264
|
+
processes: "arbitrary"
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
function normalizeContainerOptions(options) {
|
|
268
|
+
if (!options || typeof options !== "object") throw invalid("The container Sandbox runtime requires options with an image.");
|
|
269
|
+
const image = requireText(options.image, "image");
|
|
270
|
+
const brokerImage = options.brokerImage === void 0 ? defaultContainerBrokerImage : requireText(options.brokerImage, "brokerImage");
|
|
271
|
+
const docker = options.docker === void 0 ? "docker" : requireText(options.docker, "docker");
|
|
272
|
+
const user = options.user === void 0 ? void 0 : requireText(options.user, "user");
|
|
273
|
+
const cpus = options.cpus;
|
|
274
|
+
if (cpus !== void 0 && (typeof cpus !== "number" || !Number.isFinite(cpus) || cpus <= 0)) throw invalid("Container Sandbox cpus must be a positive number.");
|
|
275
|
+
const memoryBytes = options.memoryBytes;
|
|
276
|
+
if (memoryBytes !== void 0 && (!Number.isSafeInteger(memoryBytes) || memoryBytes < 6291456)) throw invalid("Container Sandbox memoryBytes must be a safe integer of at least 6 MiB.");
|
|
277
|
+
const pidsLimit = options.pidsLimit ?? 4096;
|
|
278
|
+
if (!Number.isSafeInteger(pidsLimit) || pidsLimit <= 0) throw invalid("Container Sandbox pidsLimit must be a positive integer.");
|
|
279
|
+
const egress = normalizeEgress(options.egress);
|
|
280
|
+
const credentialEntries = Object.entries(options.credentials ?? {});
|
|
281
|
+
if (options.credentials !== void 0 && (typeof options.credentials !== "object" || options.credentials === null || Array.isArray(options.credentials))) throw invalid("Container Sandbox credentials must be an object keyed by environment variable name.");
|
|
282
|
+
if (credentialEntries.length && egress.policy === "none") throw invalid("Container Sandbox credentials need egress. Set egress to { allow: [...] } or \"open\".");
|
|
283
|
+
const credentials = credentialEntries.map(([name, credential]) => {
|
|
284
|
+
if (!environmentName.test(name)) throw invalid(`Invalid container Sandbox credential name: ${name}`);
|
|
285
|
+
if (reservedCredentialNames.has(name)) throw invalid(`${name} is managed by the container Sandbox runtime.`);
|
|
286
|
+
if (!credential || typeof credential !== "object" || !Array.isArray(credential.hosts) || credential.hosts.length === 0) throw invalid(`Container Sandbox credential ${name} requires at least one host.`);
|
|
287
|
+
if (typeof credential.value !== "string" && typeof credential.value !== "function") throw invalid(`Container Sandbox credential ${name} requires a value or a value function.`);
|
|
288
|
+
return Object.freeze({
|
|
289
|
+
hosts: Object.freeze(credential.hosts.map((host) => normalizeHost(host, `credential ${name} host`))),
|
|
290
|
+
name,
|
|
291
|
+
value: credential.value
|
|
292
|
+
});
|
|
293
|
+
});
|
|
294
|
+
return Object.freeze({
|
|
295
|
+
brokerImage,
|
|
296
|
+
...cpus === void 0 ? {} : { cpus },
|
|
297
|
+
credentials: Object.freeze(credentials),
|
|
298
|
+
docker,
|
|
299
|
+
egress,
|
|
300
|
+
image,
|
|
301
|
+
...memoryBytes === void 0 ? {} : { memoryBytes },
|
|
302
|
+
pidsLimit,
|
|
303
|
+
...user === void 0 ? {} : { user }
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
function normalizeEgress(egress) {
|
|
307
|
+
if (egress === void 0 || egress === "none") return Object.freeze({
|
|
308
|
+
allow: Object.freeze([]),
|
|
309
|
+
policy: "none"
|
|
310
|
+
});
|
|
311
|
+
if (egress === "open") return Object.freeze({
|
|
312
|
+
allow: Object.freeze([]),
|
|
313
|
+
policy: "open"
|
|
314
|
+
});
|
|
315
|
+
if (!egress || typeof egress !== "object" || !Array.isArray(egress.allow)) throw invalid("Container Sandbox egress must be \"none\", \"open\", or { allow: [...] }.");
|
|
316
|
+
return Object.freeze({
|
|
317
|
+
allow: Object.freeze(egress.allow.map((host) => normalizeHost(host, "egress host"))),
|
|
318
|
+
policy: "allowlist"
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
function normalizeHost(value, label) {
|
|
322
|
+
if (typeof value !== "string") throw invalid(`Container Sandbox ${label} must be a string.`);
|
|
323
|
+
const host = value.trim().toLowerCase();
|
|
324
|
+
const port = host.includes(":") ? Number(host.slice(host.lastIndexOf(":") + 1)) : 443;
|
|
325
|
+
if (!hostPattern.test(host) || port < 1 || port > 65535) throw invalid(`Container Sandbox ${label} must be a host name, *.host name, or either with :port: ${value}`);
|
|
326
|
+
return host;
|
|
327
|
+
}
|
|
328
|
+
function requireText(value, label) {
|
|
329
|
+
if (typeof value !== "string" || !value.trim() || value.includes("\0")) throw invalid(`Container Sandbox ${label} must be a non-empty string.`);
|
|
330
|
+
return value.trim();
|
|
331
|
+
}
|
|
332
|
+
function assertCredentialNames(input, options) {
|
|
333
|
+
for (const credential of options.credentials) if (Object.hasOwn(input.plan.env, credential.name)) throw invalid(`Container Sandbox credential ${credential.name} is also declared in sandbox.env. Declare it in one place.`);
|
|
334
|
+
}
|
|
335
|
+
function invalid(message) {
|
|
336
|
+
return sandboxErrorDiagnostics.SANDBOX_R0160({ message: `[vitehub] ${message}` });
|
|
337
|
+
}
|
|
338
|
+
/** Docker object names allow [a-zA-Z0-9][a-zA-Z0-9_.-]. */
|
|
339
|
+
function dockerName(id) {
|
|
340
|
+
return `vitehub-sandbox-${id.replace(/[^a-zA-Z0-9_.-]/g, "-").replace(/^[^a-zA-Z0-9]+/, "").slice(0, 40) || "session"}-${randomBytes(4).toString("hex")}`;
|
|
341
|
+
}
|
|
342
|
+
async function startContainer(options, env, id, signal) {
|
|
343
|
+
const name = dockerName(id);
|
|
344
|
+
const network = `${name}-net`;
|
|
345
|
+
const broker = `${name}-broker`;
|
|
346
|
+
const label = `dev.vitehub.sandbox=${name}`;
|
|
347
|
+
const docker = (args, run = {}) => dockerCommand({
|
|
348
|
+
docker: options.docker,
|
|
349
|
+
...run
|
|
350
|
+
}, args);
|
|
351
|
+
const created = { containers: [] };
|
|
352
|
+
const cleanup = async () => {
|
|
353
|
+
const failures = [];
|
|
354
|
+
if (created.containers.length) {
|
|
355
|
+
const result = await docker([
|
|
356
|
+
"rm",
|
|
357
|
+
"-f",
|
|
358
|
+
...created.containers
|
|
359
|
+
]);
|
|
360
|
+
if (result.exitCode !== 0 && !/No such container/i.test(result.stderr)) failures.push(result.stderr.trim());
|
|
361
|
+
}
|
|
362
|
+
if (created.network) {
|
|
363
|
+
const result = await docker([
|
|
364
|
+
"network",
|
|
365
|
+
"rm",
|
|
366
|
+
created.network
|
|
367
|
+
]);
|
|
368
|
+
if (result.exitCode !== 0 && !/not found|No such network/i.test(result.stderr)) failures.push(result.stderr.trim());
|
|
369
|
+
}
|
|
370
|
+
if (failures.length) throw sandboxErrorDiagnostics.SANDBOX_R0162({ message: `[vitehub] Container Sandbox cleanup failed: ${failures.join("; ")}` });
|
|
371
|
+
};
|
|
372
|
+
try {
|
|
373
|
+
const version = await required(docker([
|
|
374
|
+
"version",
|
|
375
|
+
"--format",
|
|
376
|
+
"{{.Server.Version}}"
|
|
377
|
+
], { signal }), "check the Docker daemon version");
|
|
378
|
+
const major = /^v?(\d+)\./.exec(version.stdout.trim());
|
|
379
|
+
if (!major || Number(major[1]) < 28) throw invalid("Container Sandbox requires Docker Engine 28 or newer for isolated bridge gateway mode.");
|
|
380
|
+
const details = await required(docker([
|
|
381
|
+
"info",
|
|
382
|
+
"--format",
|
|
383
|
+
"{{json .}}"
|
|
384
|
+
], { signal }), "check the Docker daemon platform");
|
|
385
|
+
const unsupportedPlatform = () => invalid("Container Sandbox requires rootful Docker Engine on native Linux. Docker Desktop, OrbStack, WSL, and rootless Docker are not supported because their host routes bypass isolated bridge gateway mode.");
|
|
386
|
+
let platform;
|
|
387
|
+
try {
|
|
388
|
+
platform = JSON.parse(details.stdout);
|
|
389
|
+
} catch {
|
|
390
|
+
throw unsupportedPlatform();
|
|
391
|
+
}
|
|
392
|
+
if (!platform || platform.OSType !== "linux" || typeof platform.OperatingSystem !== "string" || !platform.OperatingSystem.trim() || typeof platform.KernelVersion !== "string" || !platform.KernelVersion.trim() || /docker desktop|orbstack|rancher desktop|colima|linuxkit/i.test(`${platform.OperatingSystem} ${platform.KernelVersion}`) || /microsoft|wsl/i.test(platform.KernelVersion) || !Array.isArray(platform.SecurityOptions) || platform.SecurityOptions.some((option) => typeof option !== "string" || /rootless/i.test(option))) throw unsupportedPlatform();
|
|
393
|
+
await required(docker([
|
|
394
|
+
"network",
|
|
395
|
+
"create",
|
|
396
|
+
"--internal",
|
|
397
|
+
"--opt",
|
|
398
|
+
"com.docker.network.bridge.gateway_mode_ipv4=isolated",
|
|
399
|
+
"--opt",
|
|
400
|
+
"com.docker.network.bridge.gateway_mode_ipv6=isolated",
|
|
401
|
+
"--label",
|
|
402
|
+
label,
|
|
403
|
+
network
|
|
404
|
+
], { signal }), "create the Sandbox network");
|
|
405
|
+
created.network = network;
|
|
406
|
+
if (options.egress.policy !== "none") {
|
|
407
|
+
const secretEnvironment = {};
|
|
408
|
+
const secrets = [];
|
|
409
|
+
for (const [index, credential] of options.credentials.entries()) {
|
|
410
|
+
const value = typeof credential.value === "function" ? await credential.value() : credential.value;
|
|
411
|
+
if (typeof value !== "string" || !value || value.includes("\0")) throw sandboxErrorDiagnostics.SANDBOX_R0160({ message: `[vitehub] Container Sandbox credential ${credential.name} must resolve to a non-empty string.` });
|
|
412
|
+
const placeholder = `vitehub-${credential.name}-${randomBytes(16).toString("hex")}`;
|
|
413
|
+
secretEnvironment[`VITEHUB_BROKER_SECRET_${index}`] = value;
|
|
414
|
+
secrets.push({
|
|
415
|
+
hosts: credential.hosts,
|
|
416
|
+
name: credential.name,
|
|
417
|
+
placeholder
|
|
418
|
+
});
|
|
419
|
+
env[credential.name] = placeholder;
|
|
420
|
+
}
|
|
421
|
+
const brokerEnvironment = {
|
|
422
|
+
VITEHUB_BROKER_ADDON: containerBrokerAddon,
|
|
423
|
+
VITEHUB_BROKER_RULES: JSON.stringify({
|
|
424
|
+
allow: options.egress.allow,
|
|
425
|
+
policy: options.egress.policy,
|
|
426
|
+
secrets
|
|
427
|
+
}),
|
|
428
|
+
...secretEnvironment
|
|
429
|
+
};
|
|
430
|
+
await required(docker([
|
|
431
|
+
"run",
|
|
432
|
+
"-d",
|
|
433
|
+
"--name",
|
|
434
|
+
broker,
|
|
435
|
+
"--label",
|
|
436
|
+
label,
|
|
437
|
+
"--network",
|
|
438
|
+
"bridge",
|
|
439
|
+
"--user",
|
|
440
|
+
"mitmproxy",
|
|
441
|
+
"--security-opt",
|
|
442
|
+
"no-new-privileges:true",
|
|
443
|
+
...Object.keys(brokerEnvironment).flatMap((key) => ["-e", key]),
|
|
444
|
+
"--entrypoint",
|
|
445
|
+
"sh",
|
|
446
|
+
options.brokerImage,
|
|
447
|
+
"-c",
|
|
448
|
+
containerBrokerEntrypoint
|
|
449
|
+
], {
|
|
450
|
+
env: brokerEnvironment,
|
|
451
|
+
signal
|
|
452
|
+
}), "start the Sandbox broker");
|
|
453
|
+
created.containers.push(broker);
|
|
454
|
+
await required(docker([
|
|
455
|
+
"network",
|
|
456
|
+
"connect",
|
|
457
|
+
"--alias",
|
|
458
|
+
brokerAlias,
|
|
459
|
+
network,
|
|
460
|
+
broker
|
|
461
|
+
], { signal }), "connect the Sandbox broker");
|
|
462
|
+
const ca = await waitForBroker(docker, broker, signal);
|
|
463
|
+
const proxy = `http://${brokerAlias}:${brokerPort}`;
|
|
464
|
+
Object.assign(env, {
|
|
465
|
+
ALL_PROXY: proxy,
|
|
466
|
+
CURL_CA_BUNDLE: brokerCaTarget,
|
|
467
|
+
GIT_SSL_CAINFO: brokerCaTarget,
|
|
468
|
+
HTTPS_PROXY: proxy,
|
|
469
|
+
HTTP_PROXY: proxy,
|
|
470
|
+
NODE_EXTRA_CA_CERTS: brokerCaTarget,
|
|
471
|
+
NODE_USE_ENV_PROXY: "1",
|
|
472
|
+
NO_PROXY: "localhost,127.0.0.1,::1",
|
|
473
|
+
REQUESTS_CA_BUNDLE: brokerCaTarget,
|
|
474
|
+
SSL_CERT_FILE: brokerCaTarget,
|
|
475
|
+
all_proxy: proxy,
|
|
476
|
+
http_proxy: proxy,
|
|
477
|
+
https_proxy: proxy,
|
|
478
|
+
no_proxy: "localhost,127.0.0.1,::1"
|
|
479
|
+
});
|
|
480
|
+
created.containers.unshift(name);
|
|
481
|
+
await startSandboxContainer(options, docker, name, network, label, signal);
|
|
482
|
+
await writeContainerFile(options.docker, name, brokerCaTarget, ca, signal, "0");
|
|
483
|
+
} else {
|
|
484
|
+
created.containers.unshift(name);
|
|
485
|
+
await startSandboxContainer(options, docker, name, network, label, signal);
|
|
486
|
+
}
|
|
487
|
+
} catch (error) {
|
|
488
|
+
try {
|
|
489
|
+
await cleanup();
|
|
490
|
+
} catch (cleanupError) {
|
|
491
|
+
throw new AggregateError([error, cleanupError], `[vitehub] Container Sandbox start failed: ${messageOf(error)} Cleanup failed: ${messageOf(cleanupError)}`);
|
|
492
|
+
}
|
|
493
|
+
throw error;
|
|
494
|
+
}
|
|
495
|
+
return createContainerSession({
|
|
496
|
+
cleanup,
|
|
497
|
+
container: name,
|
|
498
|
+
docker: options.docker,
|
|
499
|
+
env,
|
|
500
|
+
id
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
async function startSandboxContainer(options, docker, name, network, label, signal) {
|
|
504
|
+
await required(docker([
|
|
505
|
+
"run",
|
|
506
|
+
"-d",
|
|
507
|
+
"--name",
|
|
508
|
+
name,
|
|
509
|
+
"--label",
|
|
510
|
+
label,
|
|
511
|
+
"--network",
|
|
512
|
+
network,
|
|
513
|
+
"--init",
|
|
514
|
+
"--security-opt",
|
|
515
|
+
"no-new-privileges:true",
|
|
516
|
+
"--cap-drop",
|
|
517
|
+
"NET_RAW",
|
|
518
|
+
"--pids-limit",
|
|
519
|
+
String(options.pidsLimit),
|
|
520
|
+
...options.cpus === void 0 ? [] : ["--cpus", String(options.cpus)],
|
|
521
|
+
...options.memoryBytes === void 0 ? [] : ["--memory", String(options.memoryBytes)],
|
|
522
|
+
...options.user === void 0 ? [] : ["--user", options.user],
|
|
523
|
+
"--entrypoint",
|
|
524
|
+
"sh",
|
|
525
|
+
options.image,
|
|
526
|
+
"-c",
|
|
527
|
+
"trap 'exit 0' TERM INT; while :; do sleep 3600 & wait $!; done"
|
|
528
|
+
], { signal }), "start the Sandbox container");
|
|
529
|
+
const owner = options.user === void 0 ? "\"$(id -u):$(id -g)\"" : shellQuote(options.user);
|
|
530
|
+
const setup = await docker([
|
|
531
|
+
"exec",
|
|
532
|
+
...options.user === void 0 ? [] : ["-u", "0"],
|
|
533
|
+
name,
|
|
534
|
+
"sh",
|
|
535
|
+
"-c",
|
|
536
|
+
`mkdir -p ${sandboxRoot} ${pidDirectory} && chown ${owner} ${sandboxRoot} ${pidDirectory}`
|
|
537
|
+
], { signal });
|
|
538
|
+
if (setup.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0161({ message: `[vitehub] Container Sandbox could not prepare ${sandboxRoot}. Run the image as root, or set user to a user that root can chown to: ${setup.stderr.trim()}` });
|
|
539
|
+
}
|
|
540
|
+
async function waitForBroker(docker, broker, signal) {
|
|
541
|
+
const deadline = Date.now() + 3e4;
|
|
542
|
+
const probe = `test -s ${containerBrokerCaPath} && python3 -c 'import socket; socket.create_connection(("127.0.0.1", ${brokerPort}), 1)' && cat ${containerBrokerCaPath}`;
|
|
543
|
+
let last;
|
|
544
|
+
while (Date.now() < deadline) {
|
|
545
|
+
signal?.throwIfAborted();
|
|
546
|
+
last = await docker([
|
|
547
|
+
"exec",
|
|
548
|
+
broker,
|
|
549
|
+
"sh",
|
|
550
|
+
"-c",
|
|
551
|
+
probe
|
|
552
|
+
], { signal });
|
|
553
|
+
if (last.exitCode === 0 && last.stdout.includes("BEGIN CERTIFICATE")) return last.stdout;
|
|
554
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
555
|
+
}
|
|
556
|
+
const logs = await docker([
|
|
557
|
+
"logs",
|
|
558
|
+
"--tail",
|
|
559
|
+
"20",
|
|
560
|
+
broker
|
|
561
|
+
]);
|
|
562
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0161({ message: `[vitehub] Container Sandbox broker did not start within 30 seconds: ${(last?.stderr || "").trim()} ${logs.stdout.trim()} ${logs.stderr.trim()}`.trim() });
|
|
563
|
+
}
|
|
564
|
+
async function required(result, action) {
|
|
565
|
+
const value = await result;
|
|
566
|
+
if (value.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0161({ message: `[vitehub] Container Sandbox could not ${action}: ${value.stderr.trim() || value.stdout.trim()}` });
|
|
567
|
+
return value;
|
|
568
|
+
}
|
|
569
|
+
function spawnDocker(options, args, stdin) {
|
|
570
|
+
return spawn(options.docker, args, {
|
|
571
|
+
env: {
|
|
572
|
+
...process.env,
|
|
573
|
+
...options.env
|
|
574
|
+
},
|
|
575
|
+
stdio: [
|
|
576
|
+
stdin ? "pipe" : "ignore",
|
|
577
|
+
"pipe",
|
|
578
|
+
"pipe"
|
|
579
|
+
]
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
async function dockerCommand(options, args) {
|
|
583
|
+
options.signal?.throwIfAborted();
|
|
584
|
+
const child = spawnDocker(options, args, options.input !== void 0);
|
|
585
|
+
const stdout = [];
|
|
586
|
+
const stderr = [];
|
|
587
|
+
child.stdout.on("data", (chunk) => stdout.push(chunk));
|
|
588
|
+
child.stderr.on("data", (chunk) => stderr.push(chunk));
|
|
589
|
+
if (options.input !== void 0) {
|
|
590
|
+
child.stdin.on("error", () => void 0);
|
|
591
|
+
child.stdin.end(options.input);
|
|
592
|
+
}
|
|
593
|
+
const abort = () => child.kill("SIGKILL");
|
|
594
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
595
|
+
try {
|
|
596
|
+
const exitCode = await waitForExit(child);
|
|
597
|
+
options.signal?.throwIfAborted();
|
|
598
|
+
return {
|
|
599
|
+
exitCode,
|
|
600
|
+
stderr: Buffer.concat(stderr).toString("utf8"),
|
|
601
|
+
stdout: Buffer.concat(stdout).toString("utf8")
|
|
602
|
+
};
|
|
603
|
+
} finally {
|
|
604
|
+
options.signal?.removeEventListener("abort", abort);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
function waitForExit(child) {
|
|
608
|
+
return new Promise((resolve, reject) => {
|
|
609
|
+
child.once("error", reject);
|
|
610
|
+
child.once("close", (code, signal) => resolve(code ?? (signal ? 128 + signalNumber(signal) : 1)));
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
function signalNumber(signal) {
|
|
614
|
+
return {
|
|
615
|
+
SIGHUP: 1,
|
|
616
|
+
SIGINT: 2,
|
|
617
|
+
SIGKILL: 9,
|
|
618
|
+
SIGTERM: 15
|
|
619
|
+
}[signal] ?? 0;
|
|
620
|
+
}
|
|
621
|
+
async function writeContainerFile(docker, container, path, content, signal, user) {
|
|
622
|
+
const result = await dockerCommand({
|
|
623
|
+
docker,
|
|
624
|
+
input: typeof content === "string" ? new TextEncoder().encode(content) : content,
|
|
625
|
+
signal
|
|
626
|
+
}, [
|
|
627
|
+
"exec",
|
|
628
|
+
"-i",
|
|
629
|
+
...user === void 0 ? [] : ["-u", user],
|
|
630
|
+
container,
|
|
631
|
+
"sh",
|
|
632
|
+
"-c",
|
|
633
|
+
`cat > ${shellQuote(path)} && chmod 0644 ${shellQuote(path)}`
|
|
634
|
+
]);
|
|
635
|
+
if (result.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0163({ message: `[vitehub] Container Sandbox could not write ${path}: ${result.stderr.trim()}` });
|
|
636
|
+
}
|
|
637
|
+
function createContainerSession(state) {
|
|
638
|
+
const children = /* @__PURE__ */ new Set();
|
|
639
|
+
let destroyPromise;
|
|
640
|
+
/** Starts `command` in the Sandbox. The wrapper records the process id so kill() reaches the Sandbox process, not only the Docker CLI. */
|
|
641
|
+
const start = (options, stdin) => {
|
|
642
|
+
const pidFile = `${pidDirectory}/${randomUUID()}`;
|
|
643
|
+
const environment = {
|
|
644
|
+
...state.env,
|
|
645
|
+
...options.env
|
|
646
|
+
};
|
|
647
|
+
const inline = [];
|
|
648
|
+
const inherited = {};
|
|
649
|
+
for (const [key, value] of Object.entries(environment)) if (cliEnvironment(key)) inline.push("-e", `${key}=${value}`);
|
|
650
|
+
else {
|
|
651
|
+
inherited[key] = value;
|
|
652
|
+
inline.push("-e", key);
|
|
653
|
+
}
|
|
654
|
+
const enter = options.workingDirectory === void 0 ? `cd ${sandboxWorkspace} 2>/dev/null || cd /` : "cd -- \"$2\" || exit 127";
|
|
655
|
+
const child = spawnDocker({
|
|
656
|
+
docker: state.docker,
|
|
657
|
+
env: inherited
|
|
658
|
+
}, [
|
|
659
|
+
"exec",
|
|
660
|
+
...stdin ? ["-i"] : [],
|
|
661
|
+
"-w",
|
|
662
|
+
"/",
|
|
663
|
+
...inline,
|
|
664
|
+
state.container,
|
|
665
|
+
"sh",
|
|
666
|
+
"-c",
|
|
667
|
+
`echo $$ > "$0"; ${enter}; exec sh -c "$1"`,
|
|
668
|
+
pidFile,
|
|
669
|
+
options.command,
|
|
670
|
+
...options.workingDirectory === void 0 ? [] : [options.workingDirectory]
|
|
671
|
+
], stdin);
|
|
672
|
+
children.add(child);
|
|
673
|
+
let exited = false;
|
|
674
|
+
const exit = waitForExit(child).finally(() => {
|
|
675
|
+
exited = true;
|
|
676
|
+
children.delete(child);
|
|
677
|
+
dockerCommand({ docker: state.docker }, [
|
|
678
|
+
"exec",
|
|
679
|
+
state.container,
|
|
680
|
+
"rm",
|
|
681
|
+
"-f",
|
|
682
|
+
pidFile
|
|
683
|
+
]).catch(() => void 0);
|
|
684
|
+
});
|
|
685
|
+
const kill = async (signal = "TERM") => {
|
|
686
|
+
const name = signal.replace(/^SIG/, "").toUpperCase();
|
|
687
|
+
if (!/^[A-Z0-9]+$/.test(name)) throw sandboxErrorDiagnostics.SANDBOX_R0164({ message: `[vitehub] Invalid signal: ${signal}` });
|
|
688
|
+
const deadline = Date.now() + 1e4;
|
|
689
|
+
while (!exited) {
|
|
690
|
+
const result = await dockerCommand({ docker: state.docker }, [
|
|
691
|
+
"exec",
|
|
692
|
+
state.container,
|
|
693
|
+
"sh",
|
|
694
|
+
"-c",
|
|
695
|
+
`pid=$(cat ${shellQuote(pidFile)} 2>/dev/null) && [ -n "$pid" ] || exit 3; kill -s ${name} -- "-$pid" 2>/dev/null || kill -s ${name} "$pid"`
|
|
696
|
+
]);
|
|
697
|
+
if (exited) return;
|
|
698
|
+
if (result.exitCode === 0) {
|
|
699
|
+
if (name === "KILL") child.kill("SIGKILL");
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
if (result.exitCode !== 3 || Date.now() >= deadline) throw sandboxErrorDiagnostics.SANDBOX_R0164({ message: `[vitehub] Container Sandbox could not signal the process: ${result.stderr.trim() || "PID registration timed out."}` });
|
|
703
|
+
await setTimeout$1(50);
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
return {
|
|
707
|
+
child,
|
|
708
|
+
exit,
|
|
709
|
+
kill
|
|
710
|
+
};
|
|
711
|
+
};
|
|
712
|
+
const run = async (options) => {
|
|
713
|
+
options.abortSignal?.throwIfAborted();
|
|
714
|
+
const { child, exit, kill } = start(options, false);
|
|
715
|
+
const stdout = [];
|
|
716
|
+
const stderr = [];
|
|
717
|
+
child.stdout.on("data", (chunk) => stdout.push(chunk));
|
|
718
|
+
child.stderr.on("data", (chunk) => stderr.push(chunk));
|
|
719
|
+
let termination;
|
|
720
|
+
const abort = () => {
|
|
721
|
+
termination = kill("KILL").catch((error) => {
|
|
722
|
+
child.kill("SIGKILL");
|
|
723
|
+
throw error;
|
|
724
|
+
});
|
|
725
|
+
termination.catch(() => void 0);
|
|
726
|
+
};
|
|
727
|
+
options.abortSignal?.addEventListener("abort", abort, { once: true });
|
|
728
|
+
try {
|
|
729
|
+
const exitCode = await exit;
|
|
730
|
+
await termination;
|
|
731
|
+
options.abortSignal?.throwIfAborted();
|
|
732
|
+
return {
|
|
733
|
+
exitCode,
|
|
734
|
+
stderr: Buffer.concat(stderr).toString("utf8"),
|
|
735
|
+
stdout: Buffer.concat(stdout).toString("utf8")
|
|
736
|
+
};
|
|
737
|
+
} finally {
|
|
738
|
+
options.abortSignal?.removeEventListener("abort", abort);
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
const readFile = async (path, abortSignal) => {
|
|
742
|
+
abortSignal?.throwIfAborted();
|
|
743
|
+
const child = spawnDocker({ docker: state.docker }, [
|
|
744
|
+
"exec",
|
|
745
|
+
state.container,
|
|
746
|
+
"sh",
|
|
747
|
+
"-c",
|
|
748
|
+
`if [ -f ${shellQuote(path)} ]; then exec cat -- ${shellQuote(path)}; elif [ -e ${shellQuote(path)} ]; then echo "not a file" >&2; exit 2; else exit 3; fi`
|
|
749
|
+
], false);
|
|
750
|
+
const stdout = [];
|
|
751
|
+
const stderr = [];
|
|
752
|
+
child.stdout.on("data", (chunk) => stdout.push(chunk));
|
|
753
|
+
child.stderr.on("data", (chunk) => stderr.push(chunk));
|
|
754
|
+
const abort = () => child.kill("SIGKILL");
|
|
755
|
+
abortSignal?.addEventListener("abort", abort, { once: true });
|
|
756
|
+
try {
|
|
757
|
+
const exitCode = await waitForExit(child);
|
|
758
|
+
abortSignal?.throwIfAborted();
|
|
759
|
+
if (exitCode === 3) return null;
|
|
760
|
+
if (exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0163({ message: `[vitehub] Container Sandbox could not read ${path}: ${Buffer.concat(stderr).toString("utf8").trim()}` });
|
|
761
|
+
return new Uint8Array(Buffer.concat(stdout));
|
|
762
|
+
} finally {
|
|
763
|
+
abortSignal?.removeEventListener("abort", abort);
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
const checked = async (options, action) => {
|
|
767
|
+
const result = await run(options);
|
|
768
|
+
if (result.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0163({ message: `[vitehub] Container Sandbox could not ${action}: ${(result.stderr || result.stdout).trim()}` });
|
|
769
|
+
};
|
|
770
|
+
const destroy = async () => {
|
|
771
|
+
destroyPromise ??= (async () => {
|
|
772
|
+
for (const child of children) child.kill("SIGKILL");
|
|
773
|
+
await state.cleanup();
|
|
774
|
+
})();
|
|
775
|
+
try {
|
|
776
|
+
await destroyPromise;
|
|
777
|
+
} catch (error) {
|
|
778
|
+
destroyPromise = void 0;
|
|
779
|
+
throw error;
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
return {
|
|
783
|
+
defaultWorkingDirectory: sandboxWorkspace,
|
|
784
|
+
id: state.id,
|
|
785
|
+
destroy,
|
|
786
|
+
async existsFile({ abortSignal, path: input }) {
|
|
787
|
+
const path = sandboxPath(input);
|
|
788
|
+
return (await run({
|
|
789
|
+
abortSignal,
|
|
790
|
+
command: `test -e ${shellQuote(path)} || test -L ${shellQuote(path)}`
|
|
791
|
+
})).exitCode === 0;
|
|
792
|
+
},
|
|
793
|
+
async listFiles({ abortSignal, path: input, recursive }) {
|
|
794
|
+
const path = sandboxPath(input);
|
|
795
|
+
return await listCommandFiles(run, {
|
|
796
|
+
abortSignal,
|
|
797
|
+
path,
|
|
798
|
+
recursive
|
|
799
|
+
}, (result) => sandboxErrorDiagnostics.SANDBOX_R0163({ message: `[vitehub] Container Sandbox could not list ${path}: ${result.stderr.trim()}` }));
|
|
800
|
+
},
|
|
801
|
+
async makeDirectory({ abortSignal, path: input, recursive }) {
|
|
802
|
+
const path = sandboxPath(input);
|
|
803
|
+
await checked({
|
|
804
|
+
abortSignal,
|
|
805
|
+
command: `mkdir ${recursive ? "-p " : ""}-- ${shellQuote(path)}`
|
|
806
|
+
}, `create ${path}`);
|
|
807
|
+
},
|
|
808
|
+
async moveFile({ abortSignal, destination, source }) {
|
|
809
|
+
await checked({
|
|
810
|
+
abortSignal,
|
|
811
|
+
command: `mv -- ${shellQuote(sandboxPath(source))} ${shellQuote(sandboxPath(destination))}`
|
|
812
|
+
}, `move ${source}`);
|
|
813
|
+
},
|
|
814
|
+
async readBinaryFile({ abortSignal, path }) {
|
|
815
|
+
return await readFile(sandboxPath(path), abortSignal);
|
|
816
|
+
},
|
|
817
|
+
async removeFile({ abortSignal, path: input, recursive }) {
|
|
818
|
+
const path = sandboxPath(input);
|
|
819
|
+
await checked({
|
|
820
|
+
abortSignal,
|
|
821
|
+
command: recursive ? `rm -rf -- ${shellQuote(path)}` : `if test -d ${shellQuote(path)} && ! test -L ${shellQuote(path)}; then rmdir -- ${shellQuote(path)}; else rm -f -- ${shellQuote(path)}; fi`
|
|
822
|
+
}, `remove ${path}`);
|
|
823
|
+
},
|
|
824
|
+
run,
|
|
825
|
+
async spawn(options) {
|
|
826
|
+
options.abortSignal?.throwIfAborted();
|
|
827
|
+
const stdin = options.stdin === true;
|
|
828
|
+
const { child, exit, kill } = start(options, stdin);
|
|
829
|
+
let termination;
|
|
830
|
+
const abort = () => {
|
|
831
|
+
termination = kill("KILL").catch((error) => {
|
|
832
|
+
child.kill("SIGKILL");
|
|
833
|
+
throw error;
|
|
834
|
+
});
|
|
835
|
+
termination.catch(() => void 0);
|
|
836
|
+
};
|
|
837
|
+
options.abortSignal?.addEventListener("abort", abort, { once: true });
|
|
838
|
+
exit.finally(() => options.abortSignal?.removeEventListener("abort", abort)).catch(() => void 0);
|
|
839
|
+
return {
|
|
840
|
+
stderr: Readable.toWeb(child.stderr),
|
|
841
|
+
...stdin ? { stdin: Writable.toWeb(child.stdin) } : {},
|
|
842
|
+
stdout: Readable.toWeb(child.stdout),
|
|
843
|
+
async kill(signal) {
|
|
844
|
+
await kill(signal);
|
|
845
|
+
},
|
|
846
|
+
async wait() {
|
|
847
|
+
const exitCode = await exit;
|
|
848
|
+
await termination;
|
|
849
|
+
if (termination) throw options.abortSignal.reason;
|
|
850
|
+
return { exitCode };
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
},
|
|
854
|
+
stop: destroy,
|
|
855
|
+
async writeBinaryFile({ abortSignal, content, path }) {
|
|
856
|
+
await writeContainerFile(state.docker, state.container, sandboxPath(path), content, abortSignal);
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
/** Relative file paths are relative to the Sandbox workspace, like command working directories. */
|
|
861
|
+
function sandboxPath(path) {
|
|
862
|
+
return posix.isAbsolute(path) ? path : posix.join(sandboxWorkspace, path);
|
|
863
|
+
}
|
|
864
|
+
function messageOf(error) {
|
|
865
|
+
return error instanceof Error ? error.message || error.name : String(error);
|
|
866
|
+
}
|
|
867
|
+
//#endregion
|
|
868
|
+
export { createContainerRuntime };
|