@vite-hub/sandbox 0.0.3 → 0.1.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/LICENSE +201 -0
- package/README.md +388 -22
- package/dist/cloudflare-DO0h3Ncf.js +281 -0
- package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
- package/dist/crabbox-BFCdf41h.js +1106 -0
- package/dist/error-diagnostics-BSysPv-D.js +166 -0
- package/dist/error-diagnostics-dGQqfgLt.js +99 -0
- package/dist/file-listing-DECFTdSl.js +26 -0
- package/dist/file-lock-CxyVl4Cv.js +73 -0
- package/dist/index-CXej1Bt0.d.ts +519 -0
- package/dist/index.d.ts +2 -65
- package/dist/index.js +277 -1172
- package/dist/internal/cloudflare.d.ts +4 -0
- package/dist/internal/cloudflare.js +16 -0
- package/dist/internal/host-toolchain.d.ts +22 -0
- package/dist/internal/host-toolchain.js +97 -0
- package/dist/internal/vercel.d.ts +4 -0
- package/dist/internal/vercel.js +16 -0
- package/dist/module-types-BfyRBaiP.js +7 -0
- package/dist/module-types-Cis4hrF1.d.ts +95 -0
- package/dist/remote-1Jz2oUMK.js +247 -0
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime-DHp6ImeP.js +32 -0
- package/dist/runtime-type-DrmrW5m5.js +42 -0
- package/dist/session-DD0S1PDC.js +337 -0
- package/dist/shell-quote-Q3u3plif.js +6 -0
- package/dist/ssh.d.ts +55 -0
- package/dist/ssh.js +219 -0
- package/dist/task/index.d.ts +67 -0
- package/dist/task/index.js +1523 -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 +20 -0
- package/dist/task/runtime/provider-loader.js +19 -0
- package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
- package/dist/task/runtime/providers/cloudflare.js +26 -0
- package/dist/task/runtime/providers/vercel.d.ts +12 -0
- package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
- package/dist/task/runtime/state.d.ts +24 -0
- package/dist/task/runtime/state.js +73 -0
- package/dist/task/vite.d.ts +360 -0
- package/dist/task/vite.js +3643 -0
- package/dist/toolchain-BUVXtQ2m.js +527 -0
- package/dist/trusted-host-DNMJ-Oig.js +872 -0
- package/dist/vercel-Jtxa9TJx.js +279 -0
- package/package.json +103 -39
- package/dist/cloudflare-env-2NctU8i7.js +0 -12
- package/dist/module-types-DfXe133f.d.ts +0 -91
- package/dist/module-types-Dj1MFmHT.js +0 -7
- package/dist/provider-loader-hL7uHVWp.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 -112
- package/dist/runtime/state.d.ts +0 -17
- package/dist/runtime/state.js +0 -21
- package/dist/vite.d.ts +0 -24
- package/dist/vite.js +0 -2367
|
@@ -0,0 +1,1106 @@
|
|
|
1
|
+
import { r as markBuiltInSandboxRuntime } from "./runtime-DHp6ImeP.js";
|
|
2
|
+
import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
|
|
3
|
+
import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
|
|
4
|
+
import { t as listCommandFiles } from "./file-listing-DECFTdSl.js";
|
|
5
|
+
import { a as sandboxRequirementSecrets, i as sandboxRequirementPlan, o as sandboxRequirementSignal, r as sandboxRequirementError, s as materializeGitCheckout, t as createSandboxSession } from "./session-DD0S1PDC.js";
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
import { cp, lstat, mkdtemp, readFile, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname, join, posix, resolve } from "node:path";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { Readable, Writable } from "node:stream";
|
|
12
|
+
//#region src/internal/crabbox.ts
|
|
13
|
+
const workspaceSessions = /* @__PURE__ */ new Map();
|
|
14
|
+
const crabboxSessionEnvironmentKey = "VITEHUB_SANDBOX_SESSION";
|
|
15
|
+
const runtimeEnvironmentKeys = /* @__PURE__ */ new Set([
|
|
16
|
+
"CODEX_HOME",
|
|
17
|
+
"HOME",
|
|
18
|
+
"INIT_CWD",
|
|
19
|
+
"OLDPWD",
|
|
20
|
+
"PWD",
|
|
21
|
+
"XDG_CACHE_HOME",
|
|
22
|
+
"XDG_CONFIG_HOME",
|
|
23
|
+
"XDG_STATE_HOME",
|
|
24
|
+
crabboxSessionEnvironmentKey
|
|
25
|
+
]);
|
|
26
|
+
const crabboxExecutionAuthority = {
|
|
27
|
+
credentials: "unknown",
|
|
28
|
+
environment: "selected",
|
|
29
|
+
filesystem: {
|
|
30
|
+
access: "read-write",
|
|
31
|
+
scope: "host"
|
|
32
|
+
},
|
|
33
|
+
isolation: "none",
|
|
34
|
+
network: "unrestricted",
|
|
35
|
+
processes: "arbitrary"
|
|
36
|
+
};
|
|
37
|
+
function createCrabboxRuntime(options = {}) {
|
|
38
|
+
return markBuiltInSandboxRuntime({
|
|
39
|
+
name: "crabbox",
|
|
40
|
+
async prepare(input) {
|
|
41
|
+
const { workspace } = await resolveCrabboxInput(input, options);
|
|
42
|
+
return {
|
|
43
|
+
cache: { state: "disposable" },
|
|
44
|
+
environment: { env: {} },
|
|
45
|
+
executionAuthority: crabboxExecutionAuthority,
|
|
46
|
+
home: options.stateRoot ? { state: input.plan.state.map((state) => ({
|
|
47
|
+
identity: createHash("sha256").update(JSON.stringify([
|
|
48
|
+
options.profile ?? null,
|
|
49
|
+
posix.normalize(options.stateRoot),
|
|
50
|
+
state.key,
|
|
51
|
+
state.path
|
|
52
|
+
])).digest("hex"),
|
|
53
|
+
path: state.path
|
|
54
|
+
})) } : void 0,
|
|
55
|
+
identity: input.identity,
|
|
56
|
+
requirements: sandboxRequirementPlan(input.requirements),
|
|
57
|
+
runtime: "crabbox",
|
|
58
|
+
workspace: workspace ? {
|
|
59
|
+
path: workspace,
|
|
60
|
+
state: "authoritative",
|
|
61
|
+
workDir: "workspace"
|
|
62
|
+
} : {
|
|
63
|
+
state: "disposable",
|
|
64
|
+
workDir: "workspace"
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
},
|
|
68
|
+
async open(input, openOptions) {
|
|
69
|
+
const { workspace } = await resolveCrabboxInput(input, options);
|
|
70
|
+
const provider = createCrabboxProvider({
|
|
71
|
+
...options,
|
|
72
|
+
...input.checkout ? { checkout: input.checkout } : {},
|
|
73
|
+
plan: input.plan,
|
|
74
|
+
requirements: input.requirements,
|
|
75
|
+
...input.toolchain ? { toolchain: input.toolchain } : {},
|
|
76
|
+
...workspace ? { workspace } : {}
|
|
77
|
+
});
|
|
78
|
+
let initializedSession;
|
|
79
|
+
const runtimeSession = await provider.createSession({
|
|
80
|
+
abortSignal: openOptions?.signal,
|
|
81
|
+
...openOptions?.initialize ? { async initialize(session) {
|
|
82
|
+
initializedSession = createSandboxSession(session, openOptions, posix.join(session.defaultWorkingDirectory, "workspace"));
|
|
83
|
+
await openOptions.initialize(initializedSession, { signal: openOptions.signal });
|
|
84
|
+
} } : {},
|
|
85
|
+
sessionId: openOptions?.id
|
|
86
|
+
});
|
|
87
|
+
return initializedSession ?? createSandboxSession(runtimeSession, openOptions, posix.join(runtimeSession.defaultWorkingDirectory, "workspace"));
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
async function resolveCrabboxInput(input, options) {
|
|
92
|
+
const cwd = input.cwd;
|
|
93
|
+
if (!cwd && !input.checkout) throw sandboxErrorDiagnostics.SANDBOX_R0091({ message: "[vitehub] The crabbox runtime requires sandbox.cwd or sandbox.checkout." });
|
|
94
|
+
if (input.plan.state.length && (!options.stateRoot || !posix.isAbsolute(options.stateRoot))) throw sandboxErrorDiagnostics.SANDBOX_R0092({ message: "[vitehub] The crabbox runtime requires an absolute stateRoot when sandbox.home.state is declared." });
|
|
95
|
+
if (input.plan.state.length && options.stateRoot && posix.dirname(posix.normalize(options.stateRoot)) === posix.normalize(options.stateRoot)) throw sandboxErrorDiagnostics.SANDBOX_R0093({ message: "[vitehub] Sandbox stateRoot must be a dedicated directory, not the filesystem root." });
|
|
96
|
+
const requestedWorkspace = cwd ? resolve(cwd) : void 0;
|
|
97
|
+
const workspace = requestedWorkspace ? await realpath(requestedWorkspace).catch(() => requestedWorkspace) : void 0;
|
|
98
|
+
const item = workspace ? await stat(workspace).catch(() => void 0) : void 0;
|
|
99
|
+
if (workspace && !item?.isDirectory()) throw sandboxErrorDiagnostics.SANDBOX_R0094({ message: `[vitehub] Sandbox workspace directory does not exist: ${workspace}` });
|
|
100
|
+
return { workspace };
|
|
101
|
+
}
|
|
102
|
+
function createCrabboxProvider(options) {
|
|
103
|
+
return { async createSession(createOptions = {}) {
|
|
104
|
+
const sessionOptions = {
|
|
105
|
+
...options,
|
|
106
|
+
staticId: `vitehub-${randomUUID()}`,
|
|
107
|
+
stateHome: await mkdtemp(join(tmpdir(), "vitehub-crabbox-state-"))
|
|
108
|
+
};
|
|
109
|
+
let releaseWorkspace = () => {};
|
|
110
|
+
let stateLease = emptyStateLease();
|
|
111
|
+
let leaseId;
|
|
112
|
+
let remoteRoot;
|
|
113
|
+
let initializedState = [];
|
|
114
|
+
try {
|
|
115
|
+
if (options.workspace) releaseWorkspace = await acquireWorkspace(options.workspace, createOptions.abortSignal);
|
|
116
|
+
leaseId = await warmup(sessionOptions, createOptions.abortSignal);
|
|
117
|
+
const hasState = options.plan.state.length > 0;
|
|
118
|
+
const setup = await runCrabbox(sessionOptions, leaseId, {
|
|
119
|
+
abortSignal: createOptions.abortSignal,
|
|
120
|
+
command: sessionSetupCommand(hasState ? options.stateRoot : void 0, Boolean(options.workspace)),
|
|
121
|
+
...options.workspace ? { localWorkingDirectory: options.workspace } : {},
|
|
122
|
+
sync: Boolean(options.workspace)
|
|
123
|
+
});
|
|
124
|
+
if (setup.exitCode !== 0) throw crabboxError("create disposable Sandbox cache", setup);
|
|
125
|
+
const [root, remoteWorkspace, remotePath, remoteUser, remoteStateRoot] = lastLines(setup.stdout, hasState ? 5 : 4);
|
|
126
|
+
if (!/^\/tmp\/vitehub-sandbox\.[A-Za-z0-9]+$/.test(root)) throw sandboxErrorDiagnostics.SANDBOX_R0095({ message: `[vitehub] Crabbox returned an invalid session root: ${root || "<empty>"}` });
|
|
127
|
+
if (!posix.isAbsolute(remoteWorkspace)) throw sandboxErrorDiagnostics.SANDBOX_R0096({ message: `[vitehub] Crabbox returned an invalid workspace path: ${remoteWorkspace || "<empty>"}` });
|
|
128
|
+
if (hasState && (!remoteStateRoot || !posix.isAbsolute(remoteStateRoot) || posix.dirname(remoteStateRoot) === remoteStateRoot)) throw sandboxErrorDiagnostics.SANDBOX_R0097({ message: "[vitehub] Sandbox stateRoot must resolve to a dedicated target directory." });
|
|
129
|
+
if (hasState && remotePathsOverlap(remoteStateRoot, remoteWorkspace)) throw sandboxErrorDiagnostics.SANDBOX_R0098({ message: "[vitehub] Sandbox stateRoot must be outside the authoritative workspace." });
|
|
130
|
+
if (hasState) sessionOptions.stateRoot = remoteStateRoot;
|
|
131
|
+
remoteRoot = root;
|
|
132
|
+
stateLease = await acquireRemoteState(sessionOptions, leaseId, createOptions.abortSignal);
|
|
133
|
+
const bootstrapSignal = combineAbortSignals(createOptions.abortSignal, stateLease.signal);
|
|
134
|
+
const materialized = await materializePlan(sessionOptions, leaseId, root, remotePath, remoteUser, bootstrapSignal);
|
|
135
|
+
initializedState = materialized.initializedState;
|
|
136
|
+
if (options.checkout) await materializeGitCheckout(options.checkout, remoteWorkspace, {
|
|
137
|
+
abortSignal: bootstrapSignal,
|
|
138
|
+
async run(args) {
|
|
139
|
+
const result = await runCrabbox(sessionOptions, leaseId, {
|
|
140
|
+
abortSignal: bootstrapSignal,
|
|
141
|
+
command: `${shellQuote(materialized.environmentFile)} git ${args.map(shellQuote).join(" ")}`
|
|
142
|
+
});
|
|
143
|
+
if (result.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0099({ message: "Git command failed." });
|
|
144
|
+
return { stdout: result.stdout };
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
const syncedWorkspacePaths = options.workspace ? await listRemoteWorkspacePaths(sessionOptions, leaseId, remoteWorkspace, bootstrapSignal) : [];
|
|
148
|
+
const session = createCrabboxSession({
|
|
149
|
+
environmentFile: materialized.environmentFile,
|
|
150
|
+
leaseId,
|
|
151
|
+
options: sessionOptions,
|
|
152
|
+
processes: /* @__PURE__ */ new Set(),
|
|
153
|
+
releaseWorkspace,
|
|
154
|
+
remoteWorkspace,
|
|
155
|
+
root,
|
|
156
|
+
stateLease,
|
|
157
|
+
syncedWorkspacePaths,
|
|
158
|
+
tunnels: /* @__PURE__ */ new Map()
|
|
159
|
+
}, createOptions.sessionId);
|
|
160
|
+
try {
|
|
161
|
+
await session.writeBinaryFile({
|
|
162
|
+
abortSignal: createOptions.abortSignal,
|
|
163
|
+
content: /* @__PURE__ */ new Uint8Array(),
|
|
164
|
+
path: ".vitehub-copy-probe"
|
|
165
|
+
});
|
|
166
|
+
const probeCleanup = await session.run({
|
|
167
|
+
abortSignal: createOptions.abortSignal,
|
|
168
|
+
command: `rm -- ${shellQuote(posix.join(root, ".vitehub-copy-probe"))}`
|
|
169
|
+
});
|
|
170
|
+
if (probeCleanup.exitCode !== 0) throw crabboxError("remove Crabbox copy probe", probeCleanup);
|
|
171
|
+
if (options.toolchain) await provisionCrabboxToolchain(options.toolchain, session, {
|
|
172
|
+
abortSignal: bootstrapSignal,
|
|
173
|
+
environment: materialized.environment,
|
|
174
|
+
environmentFile: materialized.environmentFile,
|
|
175
|
+
leaseId,
|
|
176
|
+
options: sessionOptions,
|
|
177
|
+
root,
|
|
178
|
+
workspace: remoteWorkspace
|
|
179
|
+
});
|
|
180
|
+
await validateRequirements(session, options.requirements, createOptions.abortSignal, materialized.secrets, options.plan.state.length === 0);
|
|
181
|
+
await createOptions.initialize?.(session);
|
|
182
|
+
return session;
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (initializedState.length) {
|
|
185
|
+
await runCrabbox(sessionOptions, leaseId, { command: `rm -rf -- ${initializedState.map(shellQuote).join(" ")}` }).catch(() => void 0);
|
|
186
|
+
initializedState = [];
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
await session.destroy?.();
|
|
190
|
+
} catch {}
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (leaseId && initializedState.length) await runCrabbox(sessionOptions, leaseId, { command: `rm -rf -- ${initializedState.map(shellQuote).join(" ")}` }).catch(() => void 0);
|
|
195
|
+
if (leaseId && remoteRoot) await runCrabbox(sessionOptions, leaseId, { command: removeDisposableRootCommand(remoteRoot) }).catch(() => void 0);
|
|
196
|
+
releaseWorkspace();
|
|
197
|
+
await stateLease.release().catch(() => void 0);
|
|
198
|
+
await rm(sessionOptions.stateHome, {
|
|
199
|
+
force: true,
|
|
200
|
+
recursive: true
|
|
201
|
+
}).catch(() => void 0);
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
} };
|
|
205
|
+
}
|
|
206
|
+
function sessionSetupCommand(stateRoot, authoritativeWorkspace) {
|
|
207
|
+
const state = stateRoot ? ` && mkdir -p -- ${shellQuote(stateRoot)} && state_root=$(realpath -- ${shellQuote(stateRoot)})` : "";
|
|
208
|
+
return `root=$(mktemp -d /tmp/vitehub-sandbox.XXXXXX) && trap 'rm -rf -- "$root"' EXIT && umask 077 && ${authoritativeWorkspace ? `workspace=$(pwd -P) && ln -s "$workspace" "$root/workspace"` : `workspace="$root/workspace" && mkdir -m 700 "$workspace"`} && home="$root/home" && mkdir -m 700 "$home"${state} && trap - EXIT && ${stateRoot ? `printf '%s\\n%s\\n%s\\n%s\\n%s\\n' "$root" "$workspace" "$PATH" "$(id -un)" "$state_root"` : `printf '%s\\n%s\\n%s\\n%s\\n' "$root" "$workspace" "$PATH" "$(id -un)"`}`;
|
|
209
|
+
}
|
|
210
|
+
async function materializePlan(options, leaseId, root, remotePath, remoteUser, abortSignal) {
|
|
211
|
+
if (!remotePath) throw sandboxErrorDiagnostics.SANDBOX_R0100({ message: "[vitehub] Crabbox returned an empty command PATH." });
|
|
212
|
+
if (!remoteUser) throw sandboxErrorDiagnostics.SANDBOX_R0101({ message: "[vitehub] Crabbox returned an empty command user." });
|
|
213
|
+
const home = posix.join(root, "home");
|
|
214
|
+
const environmentFile = posix.join(root, ".vitehub-environment");
|
|
215
|
+
const missingState = await findMissingState(options, leaseId, abortSignal);
|
|
216
|
+
const seeds = /* @__PURE__ */ new Map();
|
|
217
|
+
for (const index of missingState) seeds.set(index, await resolveFiles(options.plan.state[index].seed));
|
|
218
|
+
const files = await resolveFiles(options.plan.files);
|
|
219
|
+
const environment = Object.fromEntries(await Promise.all(Object.entries(options.plan.env).map(async ([name, resolveValue]) => [name, await resolveValue()])));
|
|
220
|
+
const cleanup = [];
|
|
221
|
+
const stateStaging = /* @__PURE__ */ new Map();
|
|
222
|
+
for (const index of missingState) {
|
|
223
|
+
const state = options.plan.state[index];
|
|
224
|
+
const staging = `${remoteStatePath(options.stateRoot, state.key)}.init-${randomUUID()}`;
|
|
225
|
+
stateStaging.set(index, staging);
|
|
226
|
+
cleanup.push(staging);
|
|
227
|
+
}
|
|
228
|
+
const script = [
|
|
229
|
+
"set -eu",
|
|
230
|
+
"umask 077",
|
|
231
|
+
`mkdir -p -- ${shellQuote(home)}`,
|
|
232
|
+
`chmod 700 ${shellQuote(home)}`
|
|
233
|
+
];
|
|
234
|
+
if (options.plan.state.length) script.push(`mkdir -p -- ${shellQuote(options.stateRoot)}`);
|
|
235
|
+
for (let index = 0; index < options.plan.state.length; index++) {
|
|
236
|
+
const state = options.plan.state[index];
|
|
237
|
+
const persistent = remoteStatePath(options.stateRoot, state.key);
|
|
238
|
+
if (missingState.has(index)) {
|
|
239
|
+
const staging = stateStaging.get(index);
|
|
240
|
+
cleanup.push(persistent);
|
|
241
|
+
script.push(`mkdir -m 700 -- ${shellQuote(staging)}`);
|
|
242
|
+
appendFiles(script, staging, seeds.get(index) || [], cleanup);
|
|
243
|
+
script.push(`mv -- ${shellQuote(staging)} ${shellQuote(persistent)}`);
|
|
244
|
+
} else script.push(`test -d ${shellQuote(persistent)}`);
|
|
245
|
+
appendProjectionReconciliation(script, state, persistent, cleanup);
|
|
246
|
+
script.push(`chmod 700 ${shellQuote(persistent)}`);
|
|
247
|
+
const target = posix.join(home, state.path);
|
|
248
|
+
script.push(`mkdir -p -- ${shellQuote(posix.dirname(target))}`, `ln -s -- ${shellQuote(persistent)} ${shellQuote(target)}`);
|
|
249
|
+
}
|
|
250
|
+
appendFiles(script, home, files, cleanup);
|
|
251
|
+
const assignments = {
|
|
252
|
+
HOME: home,
|
|
253
|
+
LANG: "C.UTF-8",
|
|
254
|
+
LOGNAME: remoteUser,
|
|
255
|
+
PATH: remotePath,
|
|
256
|
+
SHELL: "/bin/sh",
|
|
257
|
+
TMPDIR: "/tmp",
|
|
258
|
+
USER: remoteUser,
|
|
259
|
+
XDG_CACHE_HOME: posix.join(home, ".cache"),
|
|
260
|
+
XDG_CONFIG_HOME: posix.join(home, ".config"),
|
|
261
|
+
XDG_STATE_HOME: posix.join(home, ".local", "state"),
|
|
262
|
+
...environment,
|
|
263
|
+
[crabboxSessionEnvironmentKey]: root
|
|
264
|
+
};
|
|
265
|
+
appendFile(script, environmentFile, environmentWrapper(assignments), 448, cleanup);
|
|
266
|
+
if (cleanup.length) {
|
|
267
|
+
script.splice(2, 0, `trap ${shellQuote(`rm -rf -- ${cleanup.map(shellQuote).join(" ")}`)} EXIT HUP INT TERM`);
|
|
268
|
+
script.push("trap - EXIT HUP INT TERM");
|
|
269
|
+
}
|
|
270
|
+
await runCrabboxScript(options, leaseId, {
|
|
271
|
+
abortSignal,
|
|
272
|
+
script: `${script.join("\n")}\n`
|
|
273
|
+
});
|
|
274
|
+
return {
|
|
275
|
+
environment: assignments,
|
|
276
|
+
environmentFile,
|
|
277
|
+
initializedState: [...missingState].map((index) => remoteStatePath(options.stateRoot, options.plan.state[index].key)),
|
|
278
|
+
secrets: sandboxRequirementSecrets([
|
|
279
|
+
...Object.values(environment),
|
|
280
|
+
...files.map((file) => file.contents),
|
|
281
|
+
...[...seeds.values()].flatMap((seed) => seed.map((file) => file.contents))
|
|
282
|
+
])
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function environmentWrapper(assignments) {
|
|
286
|
+
const values = Object.entries(assignments).map(([name, value]) => `${name}=${shellQuote(value)}`).join(" ");
|
|
287
|
+
return new TextEncoder().encode(`#!/bin/sh\nexec env -i ${values} "$@"\n`);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Install into the shared target cache, then rewrite the command wrapper so
|
|
291
|
+
* every Sandbox command sees the toolchain first on PATH.
|
|
292
|
+
*/
|
|
293
|
+
async function provisionCrabboxToolchain(toolchain, session, context) {
|
|
294
|
+
const { abortSignal, leaseId, options } = context;
|
|
295
|
+
const { provisionToolchain, readProjectFilesWithShell, verifyToolchain } = await import("./toolchain-BUVXtQ2m.js").then((n) => n.i);
|
|
296
|
+
const run = async (script) => await runCrabbox(options, leaseId, {
|
|
297
|
+
abortSignal,
|
|
298
|
+
command: `sh -c ${shellQuote(script)}`
|
|
299
|
+
});
|
|
300
|
+
let cacheRoot = options.stateRoot && posix.isAbsolute(options.stateRoot) ? posix.join(options.stateRoot, "toolchains") : void 0;
|
|
301
|
+
if (!cacheRoot) {
|
|
302
|
+
const result = await run(`printf '%s' "\${XDG_CACHE_HOME:-$HOME/.cache}/vitehub/toolchains"`);
|
|
303
|
+
if (result.exitCode !== 0 || !posix.isAbsolute(result.stdout)) throw crabboxError("resolve the toolchain cache", result);
|
|
304
|
+
cacheRoot = result.stdout;
|
|
305
|
+
}
|
|
306
|
+
const provisioned = await provisionToolchain(toolchain, {
|
|
307
|
+
abortSignal,
|
|
308
|
+
cacheRoot,
|
|
309
|
+
readProjectFiles: async (paths) => await readProjectFilesWithShell(run, context.workspace, paths),
|
|
310
|
+
run,
|
|
311
|
+
scratch: context.root,
|
|
312
|
+
async write(path, content) {
|
|
313
|
+
await session.writeBinaryFile({
|
|
314
|
+
abortSignal,
|
|
315
|
+
content,
|
|
316
|
+
path
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
const environment = {
|
|
321
|
+
...context.environment,
|
|
322
|
+
PATH: [...provisioned.bin, context.environment.PATH].filter(Boolean).join(":")
|
|
323
|
+
};
|
|
324
|
+
const script = ["set -eu", "umask 077"];
|
|
325
|
+
appendFile(script, context.environmentFile, environmentWrapper(environment), 448, []);
|
|
326
|
+
await runCrabboxScript(options, leaseId, {
|
|
327
|
+
abortSignal,
|
|
328
|
+
script: `${script.join("\n")}\n`
|
|
329
|
+
});
|
|
330
|
+
await verifyToolchain(provisioned, cacheRoot, async (script) => await session.run({
|
|
331
|
+
abortSignal,
|
|
332
|
+
command: script
|
|
333
|
+
}));
|
|
334
|
+
session.toolchain = provisioned;
|
|
335
|
+
}
|
|
336
|
+
function appendProjectionReconciliation(script, state, persistent, cleanup) {
|
|
337
|
+
const manifest = `${persistent}.projections`;
|
|
338
|
+
const next = `${manifest}.next-${randomUUID()}`;
|
|
339
|
+
const contents = state.projections.map((path) => Buffer.from(path).toString("base64")).join("\n");
|
|
340
|
+
appendFile(script, next, new TextEncoder().encode(contents ? `${contents}\n` : ""), 384, cleanup);
|
|
341
|
+
cleanup.push(next);
|
|
342
|
+
for (const path of state.projections) {
|
|
343
|
+
const parent = posix.dirname(posix.join(persistent, path));
|
|
344
|
+
script.push(`projection_parent=${shellQuote(parent)}`, `while [ ! -e "$projection_parent" ] && [ ! -L "$projection_parent" ]; do projection_parent=$(dirname -- "$projection_parent"); done`, `projection_parent=$(CDPATH= cd -P -- "$projection_parent" && pwd -P)`, `case "$projection_parent" in ${shellQuote(persistent)}|${shellQuote(`${persistent}/`)}*) ;; *) printf '%s\\n' 'Sandbox projected path escapes writable state.' >&2; exit 1 ;; esac`);
|
|
345
|
+
}
|
|
346
|
+
script.push(`test ! -e ${shellQuote(manifest)} || test -f ${shellQuote(manifest)}`, `if [ -f ${shellQuote(manifest)} ]; then`, ` while IFS= read -r projection || [ -n "$projection" ]; do`, ` if ! grep -Fqx -- "$projection" ${shellQuote(next)}; then`, ` projection_path=$(printf '%s' "$projection" | base64 -d)`, ` projection_target=${shellQuote(`${persistent}/`)}$projection_path`, ` if [ -e "$projection_target" ] || [ -L "$projection_target" ]; then`, ` projection_parent=$(CDPATH= cd -P -- "$(dirname -- "$projection_target")" && pwd -P)`, ` case "$projection_parent" in`, ` ${shellQuote(persistent)}|${shellQuote(`${persistent}/`)}*) rm -rf -- "$projection_target" ;;`, ` *) printf '%s\n' 'Sandbox projected path escapes writable state.' >&2; exit 1 ;;`, ` esac`, ` fi`, ` fi`, ` done < ${shellQuote(manifest)}`, `fi`, `mv -f -- ${shellQuote(next)} ${shellQuote(manifest)}`);
|
|
347
|
+
}
|
|
348
|
+
async function findMissingState(options, leaseId, abortSignal) {
|
|
349
|
+
if (!options.plan.state.length) return /* @__PURE__ */ new Set();
|
|
350
|
+
const result = await runCrabbox(options, leaseId, {
|
|
351
|
+
abortSignal,
|
|
352
|
+
command: options.plan.state.map((state, index) => {
|
|
353
|
+
const path = shellQuote(remoteStatePath(options.stateRoot, state.key));
|
|
354
|
+
return `if [ -e ${path} ] || [ -L ${path} ]; then test -d ${path} || exit 1; else printf '%s\\n' ${shellQuote(String(index))}; fi`;
|
|
355
|
+
}).join("; ")
|
|
356
|
+
});
|
|
357
|
+
if (result.exitCode !== 0) throw crabboxError("inspect Sandbox state", result);
|
|
358
|
+
return new Set(result.stdout.trim().split(/\r?\n/).filter(Boolean).map(Number));
|
|
359
|
+
}
|
|
360
|
+
async function resolveFiles(files) {
|
|
361
|
+
return await Promise.all(Object.entries(files).map(async ([path, input]) => ({
|
|
362
|
+
contents: await input.resolve(),
|
|
363
|
+
path
|
|
364
|
+
})));
|
|
365
|
+
}
|
|
366
|
+
function appendFiles(script, root, files, cleanup) {
|
|
367
|
+
for (const file of files) appendFile(script, posix.join(root, file.path), file.contents, 384, cleanup);
|
|
368
|
+
}
|
|
369
|
+
function appendFile(script, path, contents, mode, cleanup) {
|
|
370
|
+
const temporary = `${path}.vitehub-${randomUUID()}`;
|
|
371
|
+
const marker = `VITEHUB_${randomUUID().replaceAll("-", "")}`;
|
|
372
|
+
cleanup.push(temporary);
|
|
373
|
+
script.push(`mkdir -p -- ${shellQuote(posix.dirname(path))}`, `base64 -d > ${shellQuote(temporary)} <<'${marker}'`, Buffer.from(contents).toString("base64"), marker, `chmod ${mode.toString(8)} ${shellQuote(temporary)}`, `rm -rf -- ${shellQuote(path)}`, `mv -f -- ${shellQuote(temporary)} ${shellQuote(path)}`);
|
|
374
|
+
}
|
|
375
|
+
function remoteStatePath(root, key) {
|
|
376
|
+
return posix.join(root, createHash("sha256").update(key).digest("hex"));
|
|
377
|
+
}
|
|
378
|
+
async function acquireRemoteState(options, leaseId, abortSignal) {
|
|
379
|
+
const locks = [...new Set(options.plan.state.map((state) => `${remoteStatePath(options.stateRoot, state.key)}.lock`))].sort();
|
|
380
|
+
if (!locks.length) return emptyStateLease();
|
|
381
|
+
const token = randomUUID();
|
|
382
|
+
const marker = `VITEHUB_STATE_READY_${token}`;
|
|
383
|
+
const owner = posix.join(options.stateRoot, `.vitehub-owner-${token}`);
|
|
384
|
+
const releaseCommands = locks.toReversed().map((lock) => {
|
|
385
|
+
return `if [ "$(sed -n '2p' ${shellQuote(lock)} 2>/dev/null || true)" = ${shellQuote(token)} ]; then rm -f -- ${shellQuote(lock)}; fi`;
|
|
386
|
+
});
|
|
387
|
+
const releaseScript = [...releaseCommands, `rm -f -- ${shellQuote(owner)}`].join("\n");
|
|
388
|
+
const script = [
|
|
389
|
+
"set -eu",
|
|
390
|
+
"umask 077",
|
|
391
|
+
`mkdir -p -- ${shellQuote(options.stateRoot)}`,
|
|
392
|
+
`printf '%s\\n%s\\n' "$$" ${shellQuote(token)} > ${shellQuote(owner)}`,
|
|
393
|
+
"release_vitehub_state() {",
|
|
394
|
+
" set +e",
|
|
395
|
+
...releaseCommands.map((command) => ` ${command}`),
|
|
396
|
+
` rm -f -- ${shellQuote(owner)}`,
|
|
397
|
+
"}",
|
|
398
|
+
"trap release_vitehub_state EXIT HUP INT TERM"
|
|
399
|
+
];
|
|
400
|
+
for (const lock of locks) script.push(`while ! ln -- ${shellQuote(owner)} ${shellQuote(lock)} 2>/dev/null; do`, ` lock_pid=$(sed -n '1p' ${shellQuote(lock)} 2>/dev/null || true)`, ` lock_token=$(sed -n '2p' ${shellQuote(lock)} 2>/dev/null || true)`, ` stale_lock=${shellQuote(`${lock}.stale-`)}"$lock_token"`, " case \"$lock_pid\" in", " ''|*[!0-9]*)", ` lock_time=$(stat -c %Y ${shellQuote(lock)} 2>/dev/null || date +%s)`, " now=$(date +%s)", ` if [ $((now - lock_time)) -gt 5 ] && [ -n "$lock_token" ] && ln -- ${shellQuote(lock)} "$stale_lock" 2>/dev/null; then`, ` if [ "$(sed -n '2p' ${shellQuote(lock)} 2>/dev/null || true)" = "$lock_token" ]; then rm -f -- ${shellQuote(lock)}; fi`, " fi", " ;;", " *)", ` if ! kill -0 "$lock_pid" 2>/dev/null && [ -n "$lock_token" ] && ln -- ${shellQuote(lock)} "$stale_lock" 2>/dev/null; then`, ` if [ "$(sed -n '2p' ${shellQuote(lock)} 2>/dev/null || true)" = "$lock_token" ]; then rm -f -- ${shellQuote(lock)}; fi`, " fi", " ;;", " esac", " sleep 0.05", "done");
|
|
401
|
+
script.push(`printf '%s\\n' ${shellQuote(marker)}`, "IFS= read -r _ || true");
|
|
402
|
+
const child = spawnCrabbox(options, runArgs(leaseId, script.join("\n"), true));
|
|
403
|
+
let stderr = "";
|
|
404
|
+
let output = "";
|
|
405
|
+
let ready = false;
|
|
406
|
+
let releasing = false;
|
|
407
|
+
let failure;
|
|
408
|
+
const controller = new AbortController();
|
|
409
|
+
let resolveReady = () => {};
|
|
410
|
+
let rejectReady = (_error) => {};
|
|
411
|
+
const readiness = new Promise((resolvePromise, reject) => {
|
|
412
|
+
resolveReady = resolvePromise;
|
|
413
|
+
rejectReady = reject;
|
|
414
|
+
});
|
|
415
|
+
child.stdout.on("data", (chunk) => {
|
|
416
|
+
if (!ready) output = `${output}${String(chunk)}`.slice(-marker.length * 2);
|
|
417
|
+
if (!ready && output.includes(marker)) {
|
|
418
|
+
ready = true;
|
|
419
|
+
resolveReady();
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
child.stderr.on("data", (chunk) => {
|
|
423
|
+
if (!ready) stderr = `${stderr}${String(chunk)}`.slice(-4096);
|
|
424
|
+
});
|
|
425
|
+
const loseLease = (error) => {
|
|
426
|
+
if (releasing || failure) return;
|
|
427
|
+
failure = error;
|
|
428
|
+
controller.abort(error);
|
|
429
|
+
};
|
|
430
|
+
child.once("error", (error) => {
|
|
431
|
+
if (ready) loseLease(sandboxErrorDiagnostics.SANDBOX_R0102({
|
|
432
|
+
message: "[vitehub] Crabbox state lease was lost.",
|
|
433
|
+
cause: error
|
|
434
|
+
}));
|
|
435
|
+
else rejectReady(error);
|
|
436
|
+
});
|
|
437
|
+
const completion = new Promise((resolvePromise) => child.once("close", (code) => resolvePromise(code ?? 1)));
|
|
438
|
+
child.once("close", (code) => {
|
|
439
|
+
if (!ready) {
|
|
440
|
+
const detail = stderr.trim();
|
|
441
|
+
rejectReady(sandboxErrorDiagnostics.SANDBOX_R0103({ message: `[vitehub] Failed to acquire Crabbox state lease${detail ? `: ${detail}` : code === 0 ? "." : ` (exit ${code ?? 1}).`}` }));
|
|
442
|
+
} else if (!releasing) loseLease(sandboxErrorDiagnostics.SANDBOX_R0104({ message: `[vitehub] Crabbox state lease was lost${code && code !== 0 ? ` (exit ${code}).` : "."}` }));
|
|
443
|
+
});
|
|
444
|
+
const abort = () => {
|
|
445
|
+
child.kill();
|
|
446
|
+
rejectReady(abortSignal?.reason || sandboxErrorDiagnostics.SANDBOX_R0105({ message: "Crabbox state lease aborted." }));
|
|
447
|
+
};
|
|
448
|
+
abortSignal?.addEventListener("abort", abort, { once: true });
|
|
449
|
+
try {
|
|
450
|
+
abortSignal?.throwIfAborted();
|
|
451
|
+
await readiness;
|
|
452
|
+
} catch (error) {
|
|
453
|
+
child.stdin.destroy();
|
|
454
|
+
child.kill();
|
|
455
|
+
await completion;
|
|
456
|
+
throw error;
|
|
457
|
+
} finally {
|
|
458
|
+
abortSignal?.removeEventListener("abort", abort);
|
|
459
|
+
}
|
|
460
|
+
let released = false;
|
|
461
|
+
let releasePromise;
|
|
462
|
+
return {
|
|
463
|
+
assertActive() {
|
|
464
|
+
if (failure) throw failure;
|
|
465
|
+
},
|
|
466
|
+
async release() {
|
|
467
|
+
if (!releasePromise) releasePromise = (async () => {
|
|
468
|
+
if (!released) {
|
|
469
|
+
released = true;
|
|
470
|
+
releasing = true;
|
|
471
|
+
if (!child.stdin.destroyed) child.stdin.end();
|
|
472
|
+
}
|
|
473
|
+
const exitCode = await completion;
|
|
474
|
+
if (failure || exitCode !== 0) {
|
|
475
|
+
const retry = await runCrabbox(options, leaseId, { command: releaseScript });
|
|
476
|
+
if (retry.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0106({ message: `[vitehub] Failed to release Crabbox state lease (exit ${retry.exitCode}).` });
|
|
477
|
+
}
|
|
478
|
+
})().catch((error) => {
|
|
479
|
+
releasePromise = void 0;
|
|
480
|
+
throw error;
|
|
481
|
+
});
|
|
482
|
+
return releasePromise;
|
|
483
|
+
},
|
|
484
|
+
signal: controller.signal
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
function createCrabboxSession(state, sessionId) {
|
|
488
|
+
let destroyPromise;
|
|
489
|
+
let retryDestroy = false;
|
|
490
|
+
return {
|
|
491
|
+
defaultWorkingDirectory: state.root,
|
|
492
|
+
id: sessionId || randomUUID(),
|
|
493
|
+
inspectionConcurrency: 1,
|
|
494
|
+
ports: [0],
|
|
495
|
+
async destroy() {
|
|
496
|
+
const currentDestroy = destroyPromise ??= (async () => {
|
|
497
|
+
retryDestroy = false;
|
|
498
|
+
let failure;
|
|
499
|
+
try {
|
|
500
|
+
await this.stop();
|
|
501
|
+
state.stateLease.assertActive();
|
|
502
|
+
const reclaim = await runCrabbox(state.options, state.leaseId, { command: reclaimDisposableRootProcessesCommand(state.root) });
|
|
503
|
+
if (reclaim.exitCode !== 0) throw crabboxError("reclaim disposable Sandbox processes", reclaim);
|
|
504
|
+
if (state.options.workspace) await syncWorkspaceBack(state);
|
|
505
|
+
} catch (error) {
|
|
506
|
+
failure = error;
|
|
507
|
+
} finally {
|
|
508
|
+
let cleanupFailure;
|
|
509
|
+
const result = await runCrabbox(state.options, state.leaseId, { command: removeDisposableRootCommand(state.root) }).catch((error) => {
|
|
510
|
+
cleanupFailure = error;
|
|
511
|
+
});
|
|
512
|
+
if (!cleanupFailure && result && result.exitCode !== 0) cleanupFailure = crabboxError("remove disposable Sandbox cache", result);
|
|
513
|
+
if (!cleanupFailure) {
|
|
514
|
+
await state.stateLease.release().catch((error) => cleanupFailure ||= error);
|
|
515
|
+
if (!cleanupFailure) await rm(state.options.stateHome, {
|
|
516
|
+
force: true,
|
|
517
|
+
recursive: true
|
|
518
|
+
}).catch((error) => cleanupFailure ||= error);
|
|
519
|
+
if (!cleanupFailure) try {
|
|
520
|
+
state.releaseWorkspace();
|
|
521
|
+
} catch (error) {
|
|
522
|
+
cleanupFailure ||= error;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
retryDestroy = Boolean(cleanupFailure);
|
|
526
|
+
if (!failure) failure = cleanupFailure;
|
|
527
|
+
}
|
|
528
|
+
if (failure) throw failure;
|
|
529
|
+
})();
|
|
530
|
+
try {
|
|
531
|
+
await currentDestroy;
|
|
532
|
+
} catch (error) {
|
|
533
|
+
if (destroyPromise === currentDestroy && retryDestroy) destroyPromise = void 0;
|
|
534
|
+
throw error;
|
|
535
|
+
}
|
|
536
|
+
},
|
|
537
|
+
async getPortUrl({ port, protocol = "http" }) {
|
|
538
|
+
if (state.options.network === "direct") return `${protocol}://127.0.0.1:${port}`;
|
|
539
|
+
return `${protocol}://127.0.0.1:${await (state.tunnels.get(port) || startTunnel(state, port)).localPort}`;
|
|
540
|
+
},
|
|
541
|
+
async existsFile({ abortSignal, path }) {
|
|
542
|
+
const target = resolveSessionPath(state.root, path);
|
|
543
|
+
return (await this.run({
|
|
544
|
+
abortSignal: stateAbortSignal(state, abortSignal),
|
|
545
|
+
command: `test -e ${shellQuote(target)} || test -L ${shellQuote(target)}`
|
|
546
|
+
})).exitCode === 0;
|
|
547
|
+
},
|
|
548
|
+
async listFiles({ abortSignal, path, recursive = false }) {
|
|
549
|
+
const target = resolveSessionPath(state.root, path);
|
|
550
|
+
return await listCommandFiles((options) => this.run(options), {
|
|
551
|
+
abortSignal: stateAbortSignal(state, abortSignal),
|
|
552
|
+
path: target,
|
|
553
|
+
recursive
|
|
554
|
+
}, (result) => crabboxError(`list ${path}`, result));
|
|
555
|
+
},
|
|
556
|
+
async makeDirectory({ abortSignal, path, recursive = false }) {
|
|
557
|
+
const target = resolveSessionPath(state.root, path);
|
|
558
|
+
const result = await this.run({
|
|
559
|
+
abortSignal: stateAbortSignal(state, abortSignal),
|
|
560
|
+
command: `mkdir ${recursive ? "-p " : ""}-- ${shellQuote(target)}`
|
|
561
|
+
});
|
|
562
|
+
if (result.exitCode !== 0) throw crabboxError(`create directory ${path}`, result);
|
|
563
|
+
},
|
|
564
|
+
async moveFile({ abortSignal, destination, source }) {
|
|
565
|
+
const target = resolveSessionPath(state.root, destination);
|
|
566
|
+
const sourcePath = resolveSessionPath(state.root, source);
|
|
567
|
+
const result = await this.run({
|
|
568
|
+
abortSignal: stateAbortSignal(state, abortSignal),
|
|
569
|
+
command: `mkdir -p -- ${shellQuote(posix.dirname(target))} && mv -- ${shellQuote(sourcePath)} ${shellQuote(target)}`
|
|
570
|
+
});
|
|
571
|
+
if (result.exitCode !== 0) throw crabboxError(`move ${source}`, result);
|
|
572
|
+
},
|
|
573
|
+
async readBinaryFile({ abortSignal, path }) {
|
|
574
|
+
const stateSignal = stateAbortSignal(state, abortSignal);
|
|
575
|
+
const remotePath = resolveSessionPath(state.root, path);
|
|
576
|
+
const probe = await this.run({
|
|
577
|
+
abortSignal: stateSignal,
|
|
578
|
+
command: `if ! test -f ${shellQuote(remotePath)}; then exit 1; elif test -L ${shellQuote(remotePath)}; then exit 2; fi`
|
|
579
|
+
});
|
|
580
|
+
if (probe.exitCode === 1) return null;
|
|
581
|
+
if (probe.exitCode !== 0 && probe.exitCode !== 2) throw crabboxError(`read ${path}`, probe);
|
|
582
|
+
const stagedPath = probe.exitCode === 2 ? posix.join(state.root, `.vitehub-read-${randomUUID()}`) : void 0;
|
|
583
|
+
try {
|
|
584
|
+
if (stagedPath) {
|
|
585
|
+
const staged = await this.run({
|
|
586
|
+
abortSignal: stateSignal,
|
|
587
|
+
command: `cp -L -- ${shellQuote(remotePath)} ${shellQuote(stagedPath)}`
|
|
588
|
+
});
|
|
589
|
+
if (staged.exitCode !== 0) throw crabboxError(`read ${path}`, staged);
|
|
590
|
+
}
|
|
591
|
+
return await withTemporaryFile(async (localPath) => {
|
|
592
|
+
await copyWithCrabbox(state.options, state.leaseId, `SANDBOX:${stagedPath || remotePath}`, localPath, stateSignal);
|
|
593
|
+
return new Uint8Array(await readFile(localPath));
|
|
594
|
+
});
|
|
595
|
+
} finally {
|
|
596
|
+
if (stagedPath) await runCrabbox(state.options, state.leaseId, { command: `rm -f -- ${shellQuote(stagedPath)}` }).catch(() => void 0);
|
|
597
|
+
}
|
|
598
|
+
},
|
|
599
|
+
async run(runOptions) {
|
|
600
|
+
const child = spawnCrabboxRun(state, runOptions);
|
|
601
|
+
const [stdout, stderr, { exitCode }] = await Promise.all([
|
|
602
|
+
collect(child.stdout),
|
|
603
|
+
collect(child.stderr),
|
|
604
|
+
child.wait()
|
|
605
|
+
]);
|
|
606
|
+
return {
|
|
607
|
+
exitCode,
|
|
608
|
+
stderr,
|
|
609
|
+
stdout
|
|
610
|
+
};
|
|
611
|
+
},
|
|
612
|
+
async spawn(runOptions) {
|
|
613
|
+
return spawnCrabboxRun(state, runOptions);
|
|
614
|
+
},
|
|
615
|
+
async stop() {
|
|
616
|
+
for (const { child } of state.tunnels.values()) child.kill();
|
|
617
|
+
for (const child of state.processes) child.kill();
|
|
618
|
+
await Promise.all([...[...state.tunnels.values()].map(({ child }) => waitForExit(child)), ...[...state.processes].map((child) => waitForExit(child))]);
|
|
619
|
+
state.tunnels.clear();
|
|
620
|
+
state.processes.clear();
|
|
621
|
+
},
|
|
622
|
+
async removeFile({ abortSignal, path, recursive = false }) {
|
|
623
|
+
const target = resolveSessionPath(state.root, path);
|
|
624
|
+
const result = await this.run({
|
|
625
|
+
abortSignal: stateAbortSignal(state, abortSignal),
|
|
626
|
+
command: recursive ? `rm -rf -- ${shellQuote(target)}` : `if test -d ${shellQuote(target)} && ! test -L ${shellQuote(target)}; then rmdir -- ${shellQuote(target)}; else rm -f -- ${shellQuote(target)}; fi`
|
|
627
|
+
});
|
|
628
|
+
if (result.exitCode !== 0) throw crabboxError(`remove ${path}`, result);
|
|
629
|
+
},
|
|
630
|
+
async writeBinaryFile({ abortSignal, content, path }) {
|
|
631
|
+
const stateSignal = stateAbortSignal(state, abortSignal);
|
|
632
|
+
const remotePath = resolveSessionPath(state.root, path);
|
|
633
|
+
const directory = posix.dirname(remotePath);
|
|
634
|
+
const prepared = await this.run({
|
|
635
|
+
abortSignal: stateSignal,
|
|
636
|
+
command: `mkdir -p -- ${shellQuote(directory)} && test ! -d ${shellQuote(remotePath)}`
|
|
637
|
+
});
|
|
638
|
+
if (prepared.exitCode !== 0) throw crabboxError(`prepare ${path}`, prepared);
|
|
639
|
+
const stagedPath = posix.join(state.root, `.vitehub-write-${randomUUID()}`);
|
|
640
|
+
try {
|
|
641
|
+
await withTemporaryFile(async (localPath) => {
|
|
642
|
+
await writeFile(localPath, content);
|
|
643
|
+
await copyWithCrabbox(state.options, state.leaseId, localPath, `SANDBOX:${stagedPath}`, stateSignal);
|
|
644
|
+
});
|
|
645
|
+
const written = await this.run({
|
|
646
|
+
abortSignal: stateSignal,
|
|
647
|
+
command: `cat -- ${shellQuote(stagedPath)} > ${shellQuote(remotePath)}`
|
|
648
|
+
});
|
|
649
|
+
if (written.exitCode !== 0) throw crabboxError(`write ${path}`, written);
|
|
650
|
+
} finally {
|
|
651
|
+
await runCrabbox(state.options, state.leaseId, { command: `rm -f -- ${shellQuote(stagedPath)}` }).catch(() => void 0);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function removeDisposableRootCommand(root) {
|
|
657
|
+
return `${reclaimDisposableRootProcessesCommand(root)}; chmod -R u+w -- ${shellQuote(root)} 2>/dev/null || true; rm -rf -- ${shellQuote(root)}`;
|
|
658
|
+
}
|
|
659
|
+
function reclaimDisposableRootProcessesCommand(root) {
|
|
660
|
+
return [
|
|
661
|
+
`root=${shellQuote(root)}; owner_uid=$(id -u)`,
|
|
662
|
+
`protected_pids=" $$ "; ancestor=$$; while test "$ancestor" -gt 1; do parent=$(awk '/^PPid:/ { print $2 }' "/proc/$ancestor/status" 2>/dev/null); case "$parent" in ''|*[!0-9]*) break ;; esac; case "$protected_pids" in *" $parent "*) break ;; esac; protected_pids="$protected_pids$parent "; ancestor=$parent; done`,
|
|
663
|
+
`owns_sandbox_process() { pid=$1; case "$protected_pids" in *" $pid "*) return 1 ;; esac; status=/proc/$pid/status; test -r "$status" || return 1; uid=; while IFS=: read -r key value; do case "$key" in State) set -- $value; test "$1" != Z || return 1 ;; Uid) set -- $value; uid=$1 ;; esac; done < "$status"; test "$uid" = "$owner_uid" && awk -v marker="${crabboxSessionEnvironmentKey}=$root" 'BEGIN { RS="\\0" } $0 == marker { found=1 } END { exit found ? 0 : 1 }' "/proc/$pid/environ" 2>/dev/null; }`,
|
|
664
|
+
`passes=0; while :; do pids=; for status in /proc/[0-9]*/status; do pid=\${status#/proc/}; pid=\${pid%/status}; if owns_sandbox_process "$pid"; then pids="$pids $pid"; kill -TERM "$pid" 2>/dev/null || true; fi; done; test -n "$pids" || break; passes=$((passes + 1)); test "$passes" -le 32 || exit 1; sleep 1; for pid in $pids; do owns_sandbox_process "$pid" && kill -KILL "$pid" 2>/dev/null || true; done; done`
|
|
665
|
+
].join("; ");
|
|
666
|
+
}
|
|
667
|
+
async function warmup(options, abortSignal) {
|
|
668
|
+
const result = await runProcess(spawnCrabbox(options, [
|
|
669
|
+
"warmup",
|
|
670
|
+
"--provider",
|
|
671
|
+
"ssh",
|
|
672
|
+
"--target",
|
|
673
|
+
"linux",
|
|
674
|
+
...options.reclaim ? ["--reclaim"] : [],
|
|
675
|
+
"--timing-json"
|
|
676
|
+
], abortSignal, options.workspace));
|
|
677
|
+
if (result.exitCode !== 0) throw crabboxError("warm Crabbox", result);
|
|
678
|
+
const timing = result.stderr.trim().split(/\r?\n/).reverse().find((line) => line.trim().startsWith("{"));
|
|
679
|
+
try {
|
|
680
|
+
const parsed = timing && JSON.parse(timing);
|
|
681
|
+
const leaseId = Reflect.get(Object(parsed), "leaseId");
|
|
682
|
+
if (Object.prototype.toString.call(leaseId) === "[object String]" && leaseId) return String(leaseId);
|
|
683
|
+
} catch {}
|
|
684
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0108({ message: "[vitehub] Crabbox warmup did not return a lease id." });
|
|
685
|
+
}
|
|
686
|
+
function spawnCrabboxRun(state, options) {
|
|
687
|
+
const abortSignal = stateAbortSignal(state, options.abortSignal);
|
|
688
|
+
const workingDirectory = resolveSessionPath(state.root, options.workingDirectory);
|
|
689
|
+
const command = shellCommand(options.command, workingDirectory, options.env, state.environmentFile);
|
|
690
|
+
const child = spawnCrabbox(state.options, runArgs(state.leaseId, command, options.sync !== true), abortSignal, options.localWorkingDirectory);
|
|
691
|
+
state.processes.add(child);
|
|
692
|
+
child.once("close", () => state.processes.delete(child));
|
|
693
|
+
return processHandle(child, abortSignal);
|
|
694
|
+
}
|
|
695
|
+
async function runCrabbox(options, leaseId, run) {
|
|
696
|
+
return await runProcess(spawnCrabbox(options, runArgs(leaseId, shellCommand(run.command, void 0, run.env), run.sync !== true), run.abortSignal, run.localWorkingDirectory));
|
|
697
|
+
}
|
|
698
|
+
function runArgs(leaseId, command, noSync) {
|
|
699
|
+
return [
|
|
700
|
+
"run",
|
|
701
|
+
"--provider",
|
|
702
|
+
"ssh",
|
|
703
|
+
"--target",
|
|
704
|
+
"linux",
|
|
705
|
+
"--id",
|
|
706
|
+
leaseId,
|
|
707
|
+
"--no-hydrate",
|
|
708
|
+
...noSync ? ["--no-sync"] : [],
|
|
709
|
+
"--shell",
|
|
710
|
+
command
|
|
711
|
+
];
|
|
712
|
+
}
|
|
713
|
+
async function runCrabboxScript(options, leaseId, run) {
|
|
714
|
+
const child = spawnCrabbox(options, [
|
|
715
|
+
"run",
|
|
716
|
+
"--provider",
|
|
717
|
+
"ssh",
|
|
718
|
+
"--target",
|
|
719
|
+
"linux",
|
|
720
|
+
"--id",
|
|
721
|
+
leaseId,
|
|
722
|
+
"--no-hydrate",
|
|
723
|
+
"--no-sync",
|
|
724
|
+
"--script-stdin"
|
|
725
|
+
], run.abortSignal);
|
|
726
|
+
let inputError;
|
|
727
|
+
child.stdin.on("error", (error) => {
|
|
728
|
+
inputError = error;
|
|
729
|
+
});
|
|
730
|
+
child.stdin.end(run.script);
|
|
731
|
+
const result = await runProcess(child);
|
|
732
|
+
if (result.exitCode !== 0) throw crabboxError("run Crabbox script", result);
|
|
733
|
+
if (inputError) throw inputError;
|
|
734
|
+
return result;
|
|
735
|
+
}
|
|
736
|
+
async function copyWithCrabbox(options, leaseId, source, destination, abortSignal) {
|
|
737
|
+
const result = await runProcess(spawnCrabbox(options, [
|
|
738
|
+
"cp",
|
|
739
|
+
"--provider",
|
|
740
|
+
"ssh",
|
|
741
|
+
"--target",
|
|
742
|
+
"linux",
|
|
743
|
+
"--id",
|
|
744
|
+
leaseId,
|
|
745
|
+
source,
|
|
746
|
+
destination
|
|
747
|
+
], abortSignal));
|
|
748
|
+
if (result.exitCode !== 0) throw crabboxError(`copy ${source}`, result);
|
|
749
|
+
}
|
|
750
|
+
function startTunnel(state, remotePort) {
|
|
751
|
+
const child = spawnCrabbox(state.options, [
|
|
752
|
+
"tunnel",
|
|
753
|
+
"--provider",
|
|
754
|
+
"ssh",
|
|
755
|
+
"--target",
|
|
756
|
+
"linux",
|
|
757
|
+
"--id",
|
|
758
|
+
state.leaseId,
|
|
759
|
+
String(remotePort)
|
|
760
|
+
], stateAbortSignal(state));
|
|
761
|
+
child.on("error", () => void 0);
|
|
762
|
+
let stderr = "";
|
|
763
|
+
const captureStderr = (chunk) => stderr = `${stderr}${String(chunk)}`.slice(-4096);
|
|
764
|
+
child.stderr.on("data", captureStderr);
|
|
765
|
+
const tunnel = {
|
|
766
|
+
child,
|
|
767
|
+
localPort: firstLine(child.stdout, child).then((line) => {
|
|
768
|
+
const url = new URL(line);
|
|
769
|
+
const localPort = Number(url.port);
|
|
770
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !Number.isInteger(localPort) || localPort < 1 || localPort > 65535) throw sandboxErrorDiagnostics.SANDBOX_R0109({ message: "Crabbox returned an invalid tunnel URL." });
|
|
771
|
+
return localPort;
|
|
772
|
+
}).catch(async (cause) => {
|
|
773
|
+
child.kill();
|
|
774
|
+
await waitForExit(child);
|
|
775
|
+
const detail = stderr.trim();
|
|
776
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0110({
|
|
777
|
+
message: `[vitehub] Crabbox tunnel failed${detail ? `: ${detail}` : "."}`,
|
|
778
|
+
cause
|
|
779
|
+
});
|
|
780
|
+
}).finally(() => child.stderr.off("data", captureStderr))
|
|
781
|
+
};
|
|
782
|
+
state.tunnels.set(remotePort, tunnel);
|
|
783
|
+
child.once("close", () => {
|
|
784
|
+
if (state.tunnels.get(remotePort) === tunnel) state.tunnels.delete(remotePort);
|
|
785
|
+
});
|
|
786
|
+
return tunnel;
|
|
787
|
+
}
|
|
788
|
+
async function validateRequirements(session, requirements, abortSignal, secrets, includeDiagnosticOutput) {
|
|
789
|
+
for (const requirement of requirements) {
|
|
790
|
+
const command = [
|
|
791
|
+
"command -v",
|
|
792
|
+
shellQuote(requirement.command),
|
|
793
|
+
">/dev/null"
|
|
794
|
+
];
|
|
795
|
+
if (requirement.args.length) command.push("&&", shellQuote(requirement.command), ...requirement.args.map(shellQuote));
|
|
796
|
+
let result;
|
|
797
|
+
try {
|
|
798
|
+
result = await session.run({
|
|
799
|
+
abortSignal: sandboxRequirementSignal(requirement, abortSignal),
|
|
800
|
+
command: command.join(" "),
|
|
801
|
+
workingDirectory: posix.join(session.defaultWorkingDirectory, "workspace")
|
|
802
|
+
});
|
|
803
|
+
} catch (cause) {
|
|
804
|
+
if (abortSignal?.aborted) throw abortSignal.reason;
|
|
805
|
+
throw sandboxRequirementError(requirement, cause, secrets, requirement.timeout, includeDiagnosticOutput);
|
|
806
|
+
}
|
|
807
|
+
if (result.exitCode !== 0) throw sandboxRequirementError(requirement, result, secrets, requirement.timeout, includeDiagnosticOutput);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
function spawnCrabbox(options, args, abortSignal, cwd = options.workspace) {
|
|
811
|
+
return spawn("crabbox", args, {
|
|
812
|
+
cwd,
|
|
813
|
+
env: {
|
|
814
|
+
...process.env,
|
|
815
|
+
XDG_STATE_HOME: options.stateHome,
|
|
816
|
+
...options.staticId ? { CRABBOX_STATIC_ID: options.staticId } : {},
|
|
817
|
+
...options.profile ? { CRABBOX_PROFILE: options.profile } : {}
|
|
818
|
+
},
|
|
819
|
+
signal: abortSignal
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
function processHandle(child, abortSignal) {
|
|
823
|
+
let abortReason;
|
|
824
|
+
const abort = () => abortReason = abortSignal?.reason || sandboxErrorDiagnostics.SANDBOX_R0111({ message: "Crabbox command aborted." });
|
|
825
|
+
abortSignal?.addEventListener("abort", abort, { once: true });
|
|
826
|
+
const wait = new Promise((resolvePromise, reject) => {
|
|
827
|
+
child.once("error", reject);
|
|
828
|
+
child.once("close", (code) => {
|
|
829
|
+
abortSignal?.removeEventListener("abort", abort);
|
|
830
|
+
if (abortReason) reject(abortReason);
|
|
831
|
+
else resolvePromise({ exitCode: code ?? 1 });
|
|
832
|
+
});
|
|
833
|
+
});
|
|
834
|
+
wait.catch(() => void 0);
|
|
835
|
+
let stdin;
|
|
836
|
+
return {
|
|
837
|
+
pid: child.pid,
|
|
838
|
+
stderr: Readable.toWeb(child.stderr),
|
|
839
|
+
get stdin() {
|
|
840
|
+
return stdin ??= Writable.toWeb(child.stdin);
|
|
841
|
+
},
|
|
842
|
+
stdout: Readable.toWeb(child.stdout),
|
|
843
|
+
wait: () => wait,
|
|
844
|
+
async kill() {
|
|
845
|
+
child.kill();
|
|
846
|
+
await wait.catch(() => void 0);
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
function emptyStateLease() {
|
|
851
|
+
return {
|
|
852
|
+
assertActive() {},
|
|
853
|
+
async release() {},
|
|
854
|
+
signal: new AbortController().signal
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
function combineAbortSignals(...signals) {
|
|
858
|
+
const active = signals.filter((signal) => Boolean(signal));
|
|
859
|
+
return active.length ? AbortSignal.any(active) : void 0;
|
|
860
|
+
}
|
|
861
|
+
function stateAbortSignal(state, signal) {
|
|
862
|
+
state.stateLease.assertActive();
|
|
863
|
+
return combineAbortSignals(signal, state.stateLease.signal);
|
|
864
|
+
}
|
|
865
|
+
async function runProcess(child) {
|
|
866
|
+
const handle = processHandle(child, void 0);
|
|
867
|
+
const [stdout, stderr, { exitCode }] = await Promise.all([
|
|
868
|
+
collect(handle.stdout),
|
|
869
|
+
collect(handle.stderr),
|
|
870
|
+
handle.wait()
|
|
871
|
+
]);
|
|
872
|
+
return {
|
|
873
|
+
exitCode,
|
|
874
|
+
stderr,
|
|
875
|
+
stdout
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
function shellCommand(command, workingDirectory, env, environmentFile) {
|
|
879
|
+
const parts = [];
|
|
880
|
+
if (workingDirectory) parts.push(`cd -P -- ${shellQuote(workingDirectory)}`);
|
|
881
|
+
const names = Object.keys(env || {});
|
|
882
|
+
for (const name of names) {
|
|
883
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw sandboxErrorDiagnostics.SANDBOX_R0112({ message: `[vitehub] Invalid Sandbox environment variable: ${name}` });
|
|
884
|
+
if (runtimeEnvironmentKeys.has(name)) throw sandboxErrorDiagnostics.SANDBOX_R0113({ message: `[vitehub] Sandbox commands cannot override ${name}.` });
|
|
885
|
+
}
|
|
886
|
+
const run = names.length ? `env ${names.map((name) => `${name}=${shellQuote(env[name])}`).join(" ")} sh -c ${shellQuote(command)}` : command;
|
|
887
|
+
parts.push(run);
|
|
888
|
+
const script = parts.join(" && ");
|
|
889
|
+
return environmentFile ? `${shellQuote(environmentFile)} sh -c ${shellQuote(script)}` : script;
|
|
890
|
+
}
|
|
891
|
+
function resolveSessionPath(root, path = "") {
|
|
892
|
+
const normalizedRoot = posix.normalize(root);
|
|
893
|
+
const candidate = posix.isAbsolute(path) ? path === normalizedRoot || path.startsWith(`${normalizedRoot}/`) ? posix.normalize(path) : posix.join(normalizedRoot, path.replace(/^\/+/, "")) : posix.join(normalizedRoot, path);
|
|
894
|
+
if (candidate !== normalizedRoot && !candidate.startsWith(`${normalizedRoot}/`)) throw sandboxErrorDiagnostics.SANDBOX_R0114({ message: `[vitehub] Crabbox path escapes the session root: ${path}` });
|
|
895
|
+
return candidate;
|
|
896
|
+
}
|
|
897
|
+
function remotePathsOverlap(first, second) {
|
|
898
|
+
const normalizedFirst = posix.normalize(first);
|
|
899
|
+
const normalizedSecond = posix.normalize(second);
|
|
900
|
+
return normalizedFirst === normalizedSecond || isRemoteDescendant(normalizedFirst, normalizedSecond) || isRemoteDescendant(normalizedSecond, normalizedFirst);
|
|
901
|
+
}
|
|
902
|
+
function isRemoteDescendant(path, parent) {
|
|
903
|
+
return path.startsWith(parent === "/" ? "/" : `${parent}/`);
|
|
904
|
+
}
|
|
905
|
+
async function collect(stream) {
|
|
906
|
+
return await new Response(stream).text();
|
|
907
|
+
}
|
|
908
|
+
async function withTemporaryFile(run) {
|
|
909
|
+
const directory = await mkdtemp(join(tmpdir(), "vitehub-sandbox-"));
|
|
910
|
+
try {
|
|
911
|
+
return await run(join(directory, "file"));
|
|
912
|
+
} finally {
|
|
913
|
+
await rm(directory, {
|
|
914
|
+
force: true,
|
|
915
|
+
recursive: true
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
async function acquireWorkspace(workspace, abortSignal) {
|
|
920
|
+
abortSignal?.throwIfAborted();
|
|
921
|
+
const previous = workspaceSessions.get(workspace) || Promise.resolve();
|
|
922
|
+
let unlock = () => {};
|
|
923
|
+
const gate = new Promise((resolve) => unlock = resolve);
|
|
924
|
+
const current = previous.catch(() => void 0).then(() => gate);
|
|
925
|
+
workspaceSessions.set(workspace, current);
|
|
926
|
+
let rejectAbort = (_reason) => {};
|
|
927
|
+
const onAbort = () => rejectAbort(abortSignal?.reason);
|
|
928
|
+
try {
|
|
929
|
+
await Promise.race([previous.catch(() => void 0), new Promise((_, reject) => {
|
|
930
|
+
rejectAbort = reject;
|
|
931
|
+
abortSignal?.addEventListener("abort", onAbort, { once: true });
|
|
932
|
+
})]);
|
|
933
|
+
abortSignal?.throwIfAborted();
|
|
934
|
+
} catch (error) {
|
|
935
|
+
unlock();
|
|
936
|
+
current.finally(() => {
|
|
937
|
+
if (workspaceSessions.get(workspace) === current) workspaceSessions.delete(workspace);
|
|
938
|
+
});
|
|
939
|
+
throw error;
|
|
940
|
+
} finally {
|
|
941
|
+
abortSignal?.removeEventListener("abort", onAbort);
|
|
942
|
+
}
|
|
943
|
+
let released = false;
|
|
944
|
+
return () => {
|
|
945
|
+
if (released) return;
|
|
946
|
+
released = true;
|
|
947
|
+
unlock();
|
|
948
|
+
current.finally(() => {
|
|
949
|
+
if (workspaceSessions.get(workspace) === current) workspaceSessions.delete(workspace);
|
|
950
|
+
});
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
async function syncWorkspaceBack(state) {
|
|
954
|
+
const workspace = state.options.workspace;
|
|
955
|
+
if (!workspace) return;
|
|
956
|
+
const abortSignal = stateAbortSignal(state);
|
|
957
|
+
const initialManifest = Buffer.from(state.syncedWorkspacePaths.map((path) => `${path}\0`).join("")).toString("base64");
|
|
958
|
+
const result = await runCrabboxScript(state.options, state.leaseId, {
|
|
959
|
+
abortSignal,
|
|
960
|
+
script: `temporary=$(mktemp -d /tmp/vitehub-workspace.XXXXXX) && archive="$temporary/workspace.tar" && manifest="$temporary/manifest" && existing_manifest="$temporary/existing-manifest" && ignore_failed_read=$(tar --ignore-failed-read -cf /dev/null -T /dev/null >/dev/null 2>&1 && printf %s --ignore-failed-read || true) && trap 'rm -rf -- "$temporary"' EXIT && if git -C ${shellQuote(state.remoteWorkspace)} rev-parse --is-inside-work-tree >/dev/null 2>&1; then printf %s ${shellQuote(initialManifest)} | base64 -d > "$manifest" && git -C ${shellQuote(state.remoteWorkspace)} ls-files -z --cached --others --exclude-standard >> "$manifest" && (cd ${shellQuote(state.remoteWorkspace)} && xargs -0 sh -c 'for path do if test -e "$path" || test -L "$path"; then printf "%s\\0" "$path"; fi; done' sh < "$manifest") > "$existing_manifest" && tar $ignore_failed_read --no-recursion --null -C ${shellQuote(state.remoteWorkspace)} -cf "$archive" -T "$existing_manifest"; else tar -C ${shellQuote(state.remoteWorkspace)} --exclude ./.git --exclude .git -cf "$archive" .; fi && base64 < "$archive"`
|
|
961
|
+
});
|
|
962
|
+
const archive = Buffer.from(result.stdout.replace(/\s+/g, ""), "base64");
|
|
963
|
+
const transactionRoot = await mkdtemp(join(dirname(workspace), ".vitehub-workspace-"));
|
|
964
|
+
const stagedWorkspace = join(transactionRoot, "workspace");
|
|
965
|
+
const backupWorkspace = join(transactionRoot, "backup");
|
|
966
|
+
await withTemporaryFile(async (localPath) => {
|
|
967
|
+
try {
|
|
968
|
+
await writeFile(localPath, archive);
|
|
969
|
+
await cp(workspace, stagedWorkspace, { recursive: true });
|
|
970
|
+
await rejectSymlinkedArchiveParents(stagedWorkspace, localPath);
|
|
971
|
+
await pruneWorkspaceForArchive(stagedWorkspace, localPath, state.syncedWorkspacePaths);
|
|
972
|
+
const extract = await runProcess(spawn("tar", [
|
|
973
|
+
"--no-same-owner",
|
|
974
|
+
"--no-same-permissions",
|
|
975
|
+
"-xf",
|
|
976
|
+
localPath,
|
|
977
|
+
"-C",
|
|
978
|
+
stagedWorkspace
|
|
979
|
+
]));
|
|
980
|
+
if (extract.exitCode !== 0) throw crabboxError("extract Crabbox workspace", extract);
|
|
981
|
+
await rename(workspace, backupWorkspace);
|
|
982
|
+
try {
|
|
983
|
+
await rename(stagedWorkspace, workspace);
|
|
984
|
+
} catch (error) {
|
|
985
|
+
await rename(backupWorkspace, workspace);
|
|
986
|
+
throw error;
|
|
987
|
+
}
|
|
988
|
+
} finally {
|
|
989
|
+
await rm(transactionRoot, {
|
|
990
|
+
force: true,
|
|
991
|
+
recursive: true
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
async function listRemoteWorkspacePaths(options, leaseId, workspace, abortSignal) {
|
|
997
|
+
const result = await runCrabbox(options, leaseId, {
|
|
998
|
+
abortSignal,
|
|
999
|
+
command: `if git -C ${shellQuote(workspace)} rev-parse --is-inside-work-tree >/dev/null 2>&1; then git -C ${shellQuote(workspace)} ls-files -z --cached --others --exclude-standard; else cd ${shellQuote(workspace)} && find . -mindepth 1 \\( -name .git -o -path '*/.git/*' \\) -prune -o \\( -type d -o -type f -o -type l \\) -exec printf '%s\\0' {} +; fi`
|
|
1000
|
+
});
|
|
1001
|
+
if (result.exitCode !== 0) throw crabboxError("inspect Crabbox workspace", result);
|
|
1002
|
+
const paths = result.stdout.split("\0").map((path) => normalizeRelativeArchivePath(path)).filter((path) => Boolean(path));
|
|
1003
|
+
return [...new Set(paths.flatMap((path) => {
|
|
1004
|
+
const parts = path.split("/");
|
|
1005
|
+
return [path, ...parts.slice(1).map((_, index) => parts.slice(0, index + 1).join("/"))];
|
|
1006
|
+
}))];
|
|
1007
|
+
}
|
|
1008
|
+
async function rejectSymlinkedArchiveParents(workspace, archivePath) {
|
|
1009
|
+
await rejectSymlinkedParents(workspace, (await listArchiveEntries(archivePath)).map((entry) => entry.path));
|
|
1010
|
+
}
|
|
1011
|
+
async function rejectSymlinkedParents(workspace, entries) {
|
|
1012
|
+
const checked = /* @__PURE__ */ new Set();
|
|
1013
|
+
for (const entry of entries) {
|
|
1014
|
+
const parts = entry.split("/");
|
|
1015
|
+
for (let length = 1; length < parts.length; length++) {
|
|
1016
|
+
const path = parts.slice(0, length).join("/");
|
|
1017
|
+
if (checked.has(path)) continue;
|
|
1018
|
+
checked.add(path);
|
|
1019
|
+
if ((await lstat(join(workspace, path)).catch(() => void 0))?.isSymbolicLink()) throw sandboxErrorDiagnostics.SANDBOX_R0115({ message: `[vitehub] Crabbox workspace archive conflicts with local symlink: ${path}` });
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
async function pruneWorkspaceForArchive(workspace, archivePath, manifest) {
|
|
1024
|
+
if (!manifest.length) return;
|
|
1025
|
+
const archive = await listArchiveEntries(archivePath);
|
|
1026
|
+
const archived = new Map(archive.map((entry) => [entry.path, entry.directory]));
|
|
1027
|
+
const removed = (await Promise.all(manifest.map(async (path) => {
|
|
1028
|
+
const archivedDirectory = archived.get(path);
|
|
1029
|
+
if (archivedDirectory === void 0) return path;
|
|
1030
|
+
const item = await lstat(join(workspace, path)).catch(() => void 0);
|
|
1031
|
+
return item && item.isDirectory() !== archivedDirectory ? path : void 0;
|
|
1032
|
+
}))).filter((path) => Boolean(path));
|
|
1033
|
+
await rejectSymlinkedParents(workspace, removed);
|
|
1034
|
+
await Promise.all(removed.map(async (path) => {
|
|
1035
|
+
await rm(join(workspace, path), {
|
|
1036
|
+
force: true,
|
|
1037
|
+
recursive: true
|
|
1038
|
+
});
|
|
1039
|
+
}));
|
|
1040
|
+
const parents = [...new Set(removed.flatMap((path) => {
|
|
1041
|
+
const parts = path.split("/");
|
|
1042
|
+
return parts.slice(1).map((_, index) => parts.slice(0, index + 1).join("/"));
|
|
1043
|
+
}))].sort((a, b) => b.length - a.length);
|
|
1044
|
+
for (const path of parents) await rmdir(join(workspace, path)).catch((error) => {
|
|
1045
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTEMPTY") throw error;
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
async function listArchiveEntries(archivePath) {
|
|
1049
|
+
const result = await runProcess(spawn("tar", ["-tf", archivePath]));
|
|
1050
|
+
if (result.exitCode !== 0) throw crabboxError("inspect Crabbox workspace", result);
|
|
1051
|
+
return result.stdout.split(/\r?\n/).flatMap((path) => {
|
|
1052
|
+
if (!path) return [];
|
|
1053
|
+
const normalized = normalizeRelativeArchivePath(path);
|
|
1054
|
+
if (!normalized && path !== "." && path !== "./") throw sandboxErrorDiagnostics.SANDBOX_R0116({ message: `[vitehub] Crabbox workspace archive contains an invalid path: ${path}` });
|
|
1055
|
+
return normalized ? [{
|
|
1056
|
+
directory: path.endsWith("/"),
|
|
1057
|
+
path: normalized
|
|
1058
|
+
}] : [];
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
function normalizeRelativeArchivePath(path) {
|
|
1062
|
+
const normalized = posix.normalize(path.replace(/^\.\//, "").replace(/\/$/, ""));
|
|
1063
|
+
if (!normalized || normalized === "." || normalized.startsWith("../") || posix.isAbsolute(normalized)) return void 0;
|
|
1064
|
+
return normalized;
|
|
1065
|
+
}
|
|
1066
|
+
function lastLines(value, count) {
|
|
1067
|
+
return value.trim().split(/\r?\n/).slice(-count);
|
|
1068
|
+
}
|
|
1069
|
+
function crabboxError(action, result) {
|
|
1070
|
+
const detail = result.stderr.trim() || result.stdout.trim();
|
|
1071
|
+
return sandboxErrorDiagnostics.SANDBOX_R0117({ message: `[vitehub] Failed to ${action}${detail ? `: ${detail}` : "."}` });
|
|
1072
|
+
}
|
|
1073
|
+
function firstLine(stream, child) {
|
|
1074
|
+
return new Promise((resolvePromise, reject) => {
|
|
1075
|
+
let value = "";
|
|
1076
|
+
const data = (chunk) => {
|
|
1077
|
+
value += chunk.toString();
|
|
1078
|
+
const index = value.indexOf("\n");
|
|
1079
|
+
if (index < 0) return;
|
|
1080
|
+
cleanup();
|
|
1081
|
+
resolvePromise(value.slice(0, index));
|
|
1082
|
+
};
|
|
1083
|
+
const close = () => {
|
|
1084
|
+
cleanup();
|
|
1085
|
+
reject(sandboxErrorDiagnostics.SANDBOX_R0118({ message: "[vitehub] Crabbox tunnel exited before readiness." }));
|
|
1086
|
+
};
|
|
1087
|
+
const error = (cause) => {
|
|
1088
|
+
cleanup();
|
|
1089
|
+
reject(cause);
|
|
1090
|
+
};
|
|
1091
|
+
const cleanup = () => {
|
|
1092
|
+
stream.off("data", data);
|
|
1093
|
+
child.off("close", close);
|
|
1094
|
+
child.off("error", error);
|
|
1095
|
+
};
|
|
1096
|
+
stream.on("data", data);
|
|
1097
|
+
child.once("close", close);
|
|
1098
|
+
child.once("error", error);
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
function waitForExit(child) {
|
|
1102
|
+
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
|
|
1103
|
+
return new Promise((resolvePromise) => child.once("close", () => resolvePromise()));
|
|
1104
|
+
}
|
|
1105
|
+
//#endregion
|
|
1106
|
+
export { createCrabboxRuntime };
|