@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,337 @@
|
|
|
1
|
+
import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
|
|
2
|
+
import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
|
|
3
|
+
import { posix } from "node:path";
|
|
4
|
+
//#region src/internal/git-checkout.ts
|
|
5
|
+
async function materializeGitCheckout(checkout, workspace, runner) {
|
|
6
|
+
await run("initialize", [
|
|
7
|
+
"init",
|
|
8
|
+
"--quiet",
|
|
9
|
+
...checkout.sha.length === 64 ? ["--object-format=sha256"] : [],
|
|
10
|
+
workspace
|
|
11
|
+
]);
|
|
12
|
+
await run("configure remote", [
|
|
13
|
+
"-C",
|
|
14
|
+
workspace,
|
|
15
|
+
"remote",
|
|
16
|
+
"add",
|
|
17
|
+
"--",
|
|
18
|
+
"origin",
|
|
19
|
+
checkout.remote
|
|
20
|
+
]);
|
|
21
|
+
await run("fetch ref", [
|
|
22
|
+
"-C",
|
|
23
|
+
workspace,
|
|
24
|
+
"fetch",
|
|
25
|
+
"--quiet",
|
|
26
|
+
"--no-tags",
|
|
27
|
+
"--depth=100",
|
|
28
|
+
"origin",
|
|
29
|
+
"--",
|
|
30
|
+
checkout.ref
|
|
31
|
+
]);
|
|
32
|
+
const revision = (await run("resolve revision", [
|
|
33
|
+
"-C",
|
|
34
|
+
workspace,
|
|
35
|
+
"rev-parse",
|
|
36
|
+
"--verify",
|
|
37
|
+
"FETCH_HEAD^{commit}"
|
|
38
|
+
])).stdout.trim().toLowerCase();
|
|
39
|
+
if (revision !== checkout.sha) throw sandboxErrorDiagnostics.SANDBOX_R0119({ message: `[vitehub] Sandbox checkout revision mismatch: expected ${checkout.sha}, received ${revision || "<empty>"}.` });
|
|
40
|
+
await run("check out revision", [
|
|
41
|
+
"-C",
|
|
42
|
+
workspace,
|
|
43
|
+
"checkout",
|
|
44
|
+
"--quiet",
|
|
45
|
+
"--detach",
|
|
46
|
+
checkout.sha
|
|
47
|
+
]);
|
|
48
|
+
async function run(operation, args) {
|
|
49
|
+
runner.abortSignal?.throwIfAborted();
|
|
50
|
+
try {
|
|
51
|
+
const result = await runner.run(args);
|
|
52
|
+
runner.abortSignal?.throwIfAborted();
|
|
53
|
+
return result;
|
|
54
|
+
} catch {
|
|
55
|
+
runner.abortSignal?.throwIfAborted();
|
|
56
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0120({ message: `[vitehub] Sandbox checkout failed to ${operation}.` });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
//#endregion
|
|
61
|
+
//#region src/internal/requirements.ts
|
|
62
|
+
const maximumDiagnosticLength = 4e3;
|
|
63
|
+
function sandboxRequirementPlan(requirements) {
|
|
64
|
+
return requirements.map(({ command, name, timeout }) => ({
|
|
65
|
+
command,
|
|
66
|
+
name,
|
|
67
|
+
...timeout === void 0 ? {} : { timeout }
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
function sandboxRequirementSignal(requirement, signal) {
|
|
71
|
+
if (requirement.timeout === void 0) return signal;
|
|
72
|
+
const timeout = AbortSignal.timeout(requirement.timeout);
|
|
73
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
74
|
+
}
|
|
75
|
+
function sandboxRequirementSecrets(values) {
|
|
76
|
+
return values.map((value) => typeof value === "string" ? value : new TextDecoder().decode(value)).filter(Boolean);
|
|
77
|
+
}
|
|
78
|
+
async function collectSandboxRequirementOutput(stream, secrets) {
|
|
79
|
+
const reader = stream.getReader();
|
|
80
|
+
const decoder = new TextDecoder();
|
|
81
|
+
const patterns = [...new Set(secrets)].filter(Boolean).sort((left, right) => right.length - left.length);
|
|
82
|
+
const maximumSecretLength = Math.max(1, ...patterns.map((value) => value.length));
|
|
83
|
+
let pending = "";
|
|
84
|
+
let output = "";
|
|
85
|
+
let truncated = false;
|
|
86
|
+
const append = (value) => {
|
|
87
|
+
if (!value || truncated) return;
|
|
88
|
+
if (output.length + value.length <= maximumDiagnosticLength) {
|
|
89
|
+
output += value;
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
output = `${(output + value).slice(0, 3999)}…`;
|
|
93
|
+
truncated = true;
|
|
94
|
+
};
|
|
95
|
+
const flush = (final) => {
|
|
96
|
+
while (pending && (final || pending.length >= maximumSecretLength)) {
|
|
97
|
+
const secret = patterns.find((value) => pending.startsWith(value));
|
|
98
|
+
if (secret) {
|
|
99
|
+
append("[redacted]");
|
|
100
|
+
pending = pending.slice(secret.length);
|
|
101
|
+
} else {
|
|
102
|
+
append(pending[0]);
|
|
103
|
+
pending = pending.slice(1);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
try {
|
|
108
|
+
while (true) {
|
|
109
|
+
const { done, value } = await reader.read();
|
|
110
|
+
pending += decoder.decode(value, { stream: !done });
|
|
111
|
+
flush(done);
|
|
112
|
+
if (done) return output;
|
|
113
|
+
}
|
|
114
|
+
} finally {
|
|
115
|
+
reader.releaseLock();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function sandboxRequirementError(requirement, failure, secrets = [], timeout = requirement.timeout, includeDiagnosticOutput = true) {
|
|
119
|
+
const details = commandFailureDetails(failure, secrets, timeout, includeDiagnosticOutput);
|
|
120
|
+
const name = diagnosticText(requirement.name, secrets);
|
|
121
|
+
return sandboxErrorDiagnostics.SANDBOX_R0124({ message: `[vitehub] Sandbox requirement "${name}" failed${details ? `: ${details}` : "."}` });
|
|
122
|
+
}
|
|
123
|
+
function commandFailureDetails(failure, secrets, timeout, includeDiagnosticOutput) {
|
|
124
|
+
const error = failure && typeof failure === "object" ? failure : void 0;
|
|
125
|
+
const status = (error?.name === "TimeoutError" || error?.code === "ETIMEDOUT" || error?.killed === true) && timeout !== void 0 ? `timed out after ${timeout}ms` : typeof error?.exitCode === "number" ? `exit code ${error.exitCode}` : typeof error?.code === "number" ? `exit code ${error.code}` : typeof error?.signal === "string" ? `terminated by ${error.signal}` : error?.name === "AbortError" ? "aborted" : "";
|
|
126
|
+
const output = includeDiagnosticOutput ? diagnosticText(error?.stderr, secrets) || diagnosticText(error?.stdout, secrets) : "";
|
|
127
|
+
const message = includeDiagnosticOutput && !output ? diagnosticText(error?.message ?? failure, secrets) : "";
|
|
128
|
+
return [status, output || message].filter(Boolean).join(": ");
|
|
129
|
+
}
|
|
130
|
+
function diagnosticText(value, secrets) {
|
|
131
|
+
if (value === void 0 || value === null) return "";
|
|
132
|
+
const patterns = [...new Set(secrets)].filter(Boolean).sort((left, right) => right.length - left.length);
|
|
133
|
+
let text;
|
|
134
|
+
if (typeof value === "object") try {
|
|
135
|
+
text = JSON.stringify(value, (_key, nested) => typeof nested === "string" ? redactDiagnosticString(nested, patterns) : nested);
|
|
136
|
+
text = redactDiagnosticJson(text, patterns);
|
|
137
|
+
} catch {}
|
|
138
|
+
text ||= String(value);
|
|
139
|
+
text = redactDiagnosticString(text, patterns);
|
|
140
|
+
text = text.trim();
|
|
141
|
+
if (text.length > maximumDiagnosticLength) text = `${text.slice(0, 3999)}…`;
|
|
142
|
+
return text;
|
|
143
|
+
}
|
|
144
|
+
function redactDiagnosticString(value, patterns) {
|
|
145
|
+
for (const secret of patterns) value = value.replaceAll(secret, "[redacted]");
|
|
146
|
+
return value;
|
|
147
|
+
}
|
|
148
|
+
function redactDiagnosticJson(value, patterns) {
|
|
149
|
+
for (const secret of patterns) {
|
|
150
|
+
const encoded = JSON.stringify(secret).slice(1, -1);
|
|
151
|
+
value = value.replaceAll(encoded, "[redacted]");
|
|
152
|
+
}
|
|
153
|
+
return value;
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
//#region src/internal/session.ts
|
|
157
|
+
function isExcludedSandboxPath(path, excluded) {
|
|
158
|
+
const normalized = posix.normalize(path);
|
|
159
|
+
return excluded.some((item) => {
|
|
160
|
+
const excludedPath = posix.normalize(item);
|
|
161
|
+
return normalized === excludedPath || excludedPath === "/" || normalized.startsWith(`${excludedPath}/`);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
async function listSessionFiles(runtime, path, options = {}) {
|
|
165
|
+
const excluded = options.exclude || [];
|
|
166
|
+
if (isExcludedSandboxPath(path, excluded)) return [];
|
|
167
|
+
if (!options.recursive || !excluded.length) return (await runtime.listFiles({
|
|
168
|
+
abortSignal: options.signal,
|
|
169
|
+
path,
|
|
170
|
+
recursive: options.recursive
|
|
171
|
+
})).filter((entry) => !isExcludedSandboxPath(entry.path, excluded));
|
|
172
|
+
const entries = [];
|
|
173
|
+
const directories = [path];
|
|
174
|
+
for (let index = 0; index < directories.length; index++) {
|
|
175
|
+
const directory = directories[index];
|
|
176
|
+
if (isExcludedSandboxPath(directory, excluded)) continue;
|
|
177
|
+
for (const entry of await runtime.listFiles({
|
|
178
|
+
abortSignal: options.signal,
|
|
179
|
+
path: directory,
|
|
180
|
+
recursive: false
|
|
181
|
+
})) {
|
|
182
|
+
if (isExcludedSandboxPath(entry.path, excluded)) continue;
|
|
183
|
+
entries.push(entry);
|
|
184
|
+
if (entry.type === "directory") directories.push(entry.path);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return entries.sort((left, right) => left.path.localeCompare(right.path));
|
|
188
|
+
}
|
|
189
|
+
function createSandboxSession(runtime, openOptions, cwd = runtime.defaultWorkingDirectory) {
|
|
190
|
+
let closePromise;
|
|
191
|
+
let closed = false;
|
|
192
|
+
const assertOpen = () => {
|
|
193
|
+
if (closed) throw sandboxErrorDiagnostics.SANDBOX_R0125({ message: "[vitehub] Sandbox session is closed." });
|
|
194
|
+
};
|
|
195
|
+
const operationSignal = (signal, timeout) => {
|
|
196
|
+
assertOpen();
|
|
197
|
+
const signals = [openOptions.signal, signal].filter((value) => value !== void 0);
|
|
198
|
+
if (timeout !== void 0) {
|
|
199
|
+
if (!Number.isFinite(timeout) || timeout <= 0) throw sandboxErrorDiagnostics.SANDBOX_R0126({ message: "[vitehub] Sandbox command timeout must be a positive number." });
|
|
200
|
+
signals.push(AbortSignal.timeout(timeout));
|
|
201
|
+
}
|
|
202
|
+
const combined = signals.length === 0 ? void 0 : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
|
|
203
|
+
combined?.throwIfAborted();
|
|
204
|
+
return combined;
|
|
205
|
+
};
|
|
206
|
+
const session = {
|
|
207
|
+
cwd,
|
|
208
|
+
executionAuthority: openOptions.executionAuthority,
|
|
209
|
+
files: {
|
|
210
|
+
async exists(path, options) {
|
|
211
|
+
return await runtime.existsFile({
|
|
212
|
+
abortSignal: operationSignal(options?.signal),
|
|
213
|
+
path
|
|
214
|
+
});
|
|
215
|
+
},
|
|
216
|
+
async list(path, options) {
|
|
217
|
+
return await listSessionFiles(runtime, path, {
|
|
218
|
+
...options,
|
|
219
|
+
signal: operationSignal(options?.signal)
|
|
220
|
+
});
|
|
221
|
+
},
|
|
222
|
+
async mkdir(path, options) {
|
|
223
|
+
await runtime.makeDirectory({
|
|
224
|
+
abortSignal: operationSignal(options?.signal),
|
|
225
|
+
path,
|
|
226
|
+
recursive: options?.recursive
|
|
227
|
+
});
|
|
228
|
+
},
|
|
229
|
+
...runtime.moveFile ? { async move(source, destination, options) {
|
|
230
|
+
await runtime.moveFile({
|
|
231
|
+
abortSignal: operationSignal(options?.signal),
|
|
232
|
+
destination,
|
|
233
|
+
source
|
|
234
|
+
});
|
|
235
|
+
} } : {},
|
|
236
|
+
async read(path, options) {
|
|
237
|
+
const contents = await runtime.readBinaryFile({
|
|
238
|
+
abortSignal: operationSignal(options?.signal),
|
|
239
|
+
path
|
|
240
|
+
});
|
|
241
|
+
return contents === null ? null : new Uint8Array(contents);
|
|
242
|
+
},
|
|
243
|
+
async remove(path, options) {
|
|
244
|
+
await runtime.removeFile({
|
|
245
|
+
abortSignal: operationSignal(options?.signal),
|
|
246
|
+
path,
|
|
247
|
+
recursive: options?.recursive
|
|
248
|
+
});
|
|
249
|
+
},
|
|
250
|
+
async write(path, contents, options) {
|
|
251
|
+
await runtime.writeBinaryFile({
|
|
252
|
+
abortSignal: operationSignal(options?.signal),
|
|
253
|
+
content: contents,
|
|
254
|
+
path
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
id: runtime.id,
|
|
259
|
+
get toolchain() {
|
|
260
|
+
return runtime.toolchain;
|
|
261
|
+
},
|
|
262
|
+
...runtime.inspectionConcurrency === void 0 ? {} : { inspectionConcurrency: runtime.inspectionConcurrency },
|
|
263
|
+
...runtime.getPortUrl ? { ports: {
|
|
264
|
+
values: runtime.ports ?? [0],
|
|
265
|
+
async expose(port, options) {
|
|
266
|
+
operationSignal();
|
|
267
|
+
assertPort(port);
|
|
268
|
+
return new URL(await runtime.getPortUrl({
|
|
269
|
+
port,
|
|
270
|
+
protocol: options?.protocol
|
|
271
|
+
}));
|
|
272
|
+
}
|
|
273
|
+
} } : {},
|
|
274
|
+
...runtime.spawn ? { async spawn(command, args = [], options) {
|
|
275
|
+
return adaptProcess(await runtime.spawn({
|
|
276
|
+
abortSignal: operationSignal(options?.signal, options?.timeout),
|
|
277
|
+
command: commandLine(command, args),
|
|
278
|
+
env: options?.env ? { ...options.env } : void 0,
|
|
279
|
+
timeout: options?.timeout,
|
|
280
|
+
workingDirectory: options?.cwd ?? cwd
|
|
281
|
+
}));
|
|
282
|
+
} } : {},
|
|
283
|
+
async close() {
|
|
284
|
+
if (closePromise) return await closePromise;
|
|
285
|
+
closed = true;
|
|
286
|
+
closePromise = runtime.destroy ? runtime.destroy() : runtime.stop();
|
|
287
|
+
try {
|
|
288
|
+
await closePromise;
|
|
289
|
+
} catch (error) {
|
|
290
|
+
closePromise = void 0;
|
|
291
|
+
throw error;
|
|
292
|
+
}
|
|
293
|
+
},
|
|
294
|
+
async exec(command, args = [], options) {
|
|
295
|
+
const result = await runtime.run({
|
|
296
|
+
abortSignal: operationSignal(options?.signal, options?.timeout),
|
|
297
|
+
command: commandLine(command, args),
|
|
298
|
+
env: options?.env ? { ...options.env } : void 0,
|
|
299
|
+
timeout: options?.timeout,
|
|
300
|
+
workingDirectory: options?.cwd ?? cwd
|
|
301
|
+
});
|
|
302
|
+
return {
|
|
303
|
+
code: result.exitCode,
|
|
304
|
+
ok: result.exitCode === 0,
|
|
305
|
+
stderr: result.stderr,
|
|
306
|
+
stdout: result.stdout
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
return Object.freeze(session);
|
|
311
|
+
}
|
|
312
|
+
function adaptProcess(process) {
|
|
313
|
+
return {
|
|
314
|
+
pid: process.pid,
|
|
315
|
+
stderr: process.stderr,
|
|
316
|
+
get stdin() {
|
|
317
|
+
return process.stdin;
|
|
318
|
+
},
|
|
319
|
+
stdout: process.stdout,
|
|
320
|
+
async kill(signal) {
|
|
321
|
+
await process.kill(signal);
|
|
322
|
+
},
|
|
323
|
+
async wait() {
|
|
324
|
+
return { code: (await process.wait()).exitCode };
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
function commandLine(command, args) {
|
|
329
|
+
if (!command || command.includes("\0")) throw sandboxErrorDiagnostics.SANDBOX_R0127({ message: "[vitehub] Sandbox commands must be non-empty and cannot contain NUL." });
|
|
330
|
+
if (args.some((argument) => argument.includes("\0"))) throw sandboxErrorDiagnostics.SANDBOX_R0128({ message: "[vitehub] Sandbox command arguments cannot contain NUL." });
|
|
331
|
+
return args.length === 0 ? command : [shellQuote(command), ...args.map(shellQuote)].join(" ");
|
|
332
|
+
}
|
|
333
|
+
function assertPort(port) {
|
|
334
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw sandboxErrorDiagnostics.SANDBOX_R0129({ message: "[vitehub] Sandbox ports must be integers between 1 and 65535." });
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
export { sandboxRequirementSecrets as a, sandboxRequirementPlan as i, collectSandboxRequirementOutput as n, sandboxRequirementSignal as o, sandboxRequirementError as r, materializeGitCheckout as s, createSandboxSession as t };
|
package/dist/ssh.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
//#region src/ssh.d.ts
|
|
2
|
+
export interface SshLaunchOptions {
|
|
3
|
+
host: string;
|
|
4
|
+
user: string;
|
|
5
|
+
identityFile: string;
|
|
6
|
+
port?: number;
|
|
7
|
+
/** A known_hosts file. The normal OpenSSH host verification applies when omitted. */
|
|
8
|
+
knownHostsFile?: string;
|
|
9
|
+
/** A trusted SSH public host key, for a sidecar whose keys share a volume. */
|
|
10
|
+
hostKeyFile?: string;
|
|
11
|
+
/** Environment names only. Defaults to the launch context environment and required names. Values travel through SSH env requests. */
|
|
12
|
+
forwardEnvironment?: readonly string[];
|
|
13
|
+
}
|
|
14
|
+
export interface SshLaunchContext {
|
|
15
|
+
command: string;
|
|
16
|
+
cwd: string;
|
|
17
|
+
environment?: Readonly<Record<string, string | undefined>>;
|
|
18
|
+
requiredEnvironment?: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
/** Launch a command on a trusted SSH host with the same working-directory path. */
|
|
21
|
+
export declare function sshLaunch(options: SshLaunchOptions): (context: SshLaunchContext) => {
|
|
22
|
+
command: string;
|
|
23
|
+
args: string[];
|
|
24
|
+
};
|
|
25
|
+
export interface SshServerOptions {
|
|
26
|
+
hostKeyFile: string;
|
|
27
|
+
authorizedKeyFile: string;
|
|
28
|
+
user: string;
|
|
29
|
+
cwd: string;
|
|
30
|
+
port?: number;
|
|
31
|
+
host?: string;
|
|
32
|
+
/** Restrict accepted env names. Omit to accept valid names from the trusted client. */
|
|
33
|
+
acceptEnvironment?: readonly string[];
|
|
34
|
+
}
|
|
35
|
+
export interface SshServerCloseOptions {
|
|
36
|
+
/**
|
|
37
|
+
* Wait up to this many milliseconds for open connections to close before the server ends them and their commands.
|
|
38
|
+
* Defaults to 0, which ends them at once.
|
|
39
|
+
*/
|
|
40
|
+
drainTimeoutMs?: number;
|
|
41
|
+
}
|
|
42
|
+
export interface SshServer {
|
|
43
|
+
port: number;
|
|
44
|
+
/** Open client connections, including connections that have not finished authentication. */
|
|
45
|
+
readonly connections: number;
|
|
46
|
+
/**
|
|
47
|
+
* Stops accepting connections at once, then ends open connections and stops their commands. Clients that are
|
|
48
|
+
* already connected can still run commands while `drainTimeoutMs` lasts. Another call without `drainTimeoutMs`
|
|
49
|
+
* ends the wait early. All calls return the same promise.
|
|
50
|
+
*/
|
|
51
|
+
close(options?: SshServerCloseOptions): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/** An authenticated command server, not a filesystem or network sandbox. */
|
|
54
|
+
export declare function serveSsh(options: SshServerOptions): Promise<SshServer>;
|
|
55
|
+
//#endregion
|
package/dist/ssh.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { once } from "node:events";
|
|
4
|
+
import { createServer } from "node:net";
|
|
5
|
+
//#region src/ssh.ts
|
|
6
|
+
const maxTimeoutMs = 2147483647;
|
|
7
|
+
const environmentName = /^[A-Z_][A-Z0-9_]*$/;
|
|
8
|
+
const launcherSource = String.raw`
|
|
9
|
+
import { spawn } from "node:child_process"
|
|
10
|
+
import { mkdtemp, readFile, writeFile, rm } from "node:fs/promises"
|
|
11
|
+
import { tmpdir } from "node:os"
|
|
12
|
+
import { join } from "node:path"
|
|
13
|
+
const config = JSON.parse(process.argv[1])
|
|
14
|
+
const quote = value => "'" + value.replaceAll("'", "'\"'\"'") + "'"
|
|
15
|
+
let temporary
|
|
16
|
+
try {
|
|
17
|
+
let knownHostsFile = config.knownHostsFile
|
|
18
|
+
if (config.hostKeyFile) {
|
|
19
|
+
temporary = await mkdtemp(join(tmpdir(), "vitehub-ssh-"))
|
|
20
|
+
knownHostsFile = join(temporary, "known_hosts")
|
|
21
|
+
const key = (await readFile(config.hostKeyFile, "utf8")).trim()
|
|
22
|
+
if (!/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-\S+) [A-Za-z0-9+/=]+(?: .*)?$/.test(key)) throw new Error("Invalid SSH host public key")
|
|
23
|
+
await writeFile(knownHostsFile, "vitehub-runner " + key + "\n", { mode: 0o600 })
|
|
24
|
+
}
|
|
25
|
+
const child = spawn("ssh", [
|
|
26
|
+
"-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10",
|
|
27
|
+
"-o", "LogLevel=ERROR", "-o", "ServerAliveInterval=30",
|
|
28
|
+
"-o", "ServerAliveCountMax=3", "-o", "StrictHostKeyChecking=yes",
|
|
29
|
+
...(knownHostsFile ? ["-o", "UserKnownHostsFile=" + knownHostsFile] : []),
|
|
30
|
+
...(config.hostKeyFile ? ["-o", "HostKeyAlias=vitehub-runner"] : []),
|
|
31
|
+
"-i", config.identityFile, "-p", String(config.port),
|
|
32
|
+
...config.forwardEnvironment.flatMap(name => ["-o", "SendEnv=" + name]),
|
|
33
|
+
config.user + "@" + config.host,
|
|
34
|
+
"cd " + quote(config.cwd) + " && exec " + [config.command, ...process.argv.slice(2)].map(quote).join(" "),
|
|
35
|
+
], { stdio: "inherit" })
|
|
36
|
+
const handlers = new Map(["SIGINT", "SIGTERM", "SIGHUP"].map(signal => [signal, () => child.kill(signal)]))
|
|
37
|
+
for (const [signal, handler] of handlers) process.on(signal, handler)
|
|
38
|
+
try {
|
|
39
|
+
const result = await new Promise((resolve, reject) => {
|
|
40
|
+
child.once("error", reject)
|
|
41
|
+
child.once("close", (code, signal) => resolve({ code, signal }))
|
|
42
|
+
})
|
|
43
|
+
process.exitCode = result.code ?? 1
|
|
44
|
+
} finally {
|
|
45
|
+
for (const [signal, handler] of handlers) process.off(signal, handler)
|
|
46
|
+
}
|
|
47
|
+
} finally {
|
|
48
|
+
if (temporary) await rm(temporary, { recursive: true, force: true })
|
|
49
|
+
}
|
|
50
|
+
`;
|
|
51
|
+
/** Launch a command on a trusted SSH host with the same working-directory path. */
|
|
52
|
+
function sshLaunch(options) {
|
|
53
|
+
if (!options.host || options.host.startsWith("-") || /[\s\0]/.test(options.host)) throw new TypeError("[vitehub] SSH host is invalid.");
|
|
54
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_.-]*$/.test(options.user)) throw new TypeError("[vitehub] SSH user is invalid.");
|
|
55
|
+
if (!options.identityFile || options.identityFile.includes("\0")) throw new TypeError("[vitehub] SSH identityFile is required.");
|
|
56
|
+
const port = options.port ?? 22;
|
|
57
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new TypeError("[vitehub] SSH port must be between 1 and 65535.");
|
|
58
|
+
if (options.hostKeyFile && options.knownHostsFile) throw new TypeError("[vitehub] Select hostKeyFile or knownHostsFile.");
|
|
59
|
+
const forwardEnvironment = [...new Set(options.forwardEnvironment ?? [])];
|
|
60
|
+
if (forwardEnvironment.some((name) => !environmentName.test(name))) throw new TypeError("[vitehub] SSH environment names must be uppercase shell identifiers.");
|
|
61
|
+
return ({ command, cwd, environment, requiredEnvironment }) => {
|
|
62
|
+
const names = options.forwardEnvironment === void 0 ? Object.keys(environment || {}).filter((name) => environmentName.test(name)) : forwardEnvironment;
|
|
63
|
+
const forwarded = [.../* @__PURE__ */ new Set([...names, ...requiredEnvironment || []])];
|
|
64
|
+
if (forwarded.some((name) => !environmentName.test(name))) throw new TypeError("[vitehub] SSH environment names must be uppercase shell identifiers.");
|
|
65
|
+
if (!command || !cwd || command.includes("\0") || cwd.includes("\0")) throw new TypeError("[vitehub] SSH command and cwd are required and cannot contain NUL.");
|
|
66
|
+
return {
|
|
67
|
+
command: process.execPath,
|
|
68
|
+
args: [
|
|
69
|
+
"--input-type=module",
|
|
70
|
+
"-e",
|
|
71
|
+
launcherSource,
|
|
72
|
+
JSON.stringify({
|
|
73
|
+
...options,
|
|
74
|
+
port,
|
|
75
|
+
forwardEnvironment: forwarded,
|
|
76
|
+
command,
|
|
77
|
+
cwd
|
|
78
|
+
})
|
|
79
|
+
]
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** An authenticated command server, not a filesystem or network sandbox. */
|
|
84
|
+
async function serveSsh(options) {
|
|
85
|
+
if (process.platform === "win32") throw new Error("[vitehub] SSH command supervision requires a POSIX host.");
|
|
86
|
+
const { default: ssh2 } = await import("ssh2");
|
|
87
|
+
const [hostKey, authorizedKey] = await Promise.all([readFile(options.hostKeyFile), readFile(options.authorizedKeyFile)]);
|
|
88
|
+
const parsedKey = ssh2.utils.parseKey(authorizedKey);
|
|
89
|
+
if (parsedKey instanceof Error) throw parsedKey;
|
|
90
|
+
const publicKey = Array.isArray(parsedKey) ? parsedKey[0] : parsedKey;
|
|
91
|
+
const clients = /* @__PURE__ */ new Set();
|
|
92
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
93
|
+
const children = /* @__PURE__ */ new Set();
|
|
94
|
+
const terminations = /* @__PURE__ */ new Map();
|
|
95
|
+
const allowed = options.acceptEnvironment && new Set(options.acceptEnvironment);
|
|
96
|
+
function stop(child) {
|
|
97
|
+
const pending = terminations.get(child);
|
|
98
|
+
if (pending) return pending;
|
|
99
|
+
const signalGroup = (signal) => {
|
|
100
|
+
if (!child.pid) return;
|
|
101
|
+
try {
|
|
102
|
+
process.kill(-child.pid, signal);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ESRCH") throw error;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const done = (async () => {
|
|
108
|
+
signalGroup("SIGTERM");
|
|
109
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
110
|
+
signalGroup("SIGKILL");
|
|
111
|
+
})();
|
|
112
|
+
terminations.set(child, done);
|
|
113
|
+
return done;
|
|
114
|
+
}
|
|
115
|
+
const server = new ssh2.Server({ hostKeys: [hostKey] }, (client) => {
|
|
116
|
+
clients.add(client);
|
|
117
|
+
client.once("close", () => clients.delete(client));
|
|
118
|
+
client.on("error", () => client.end());
|
|
119
|
+
client.on("authentication", (context) => {
|
|
120
|
+
if (context.method !== "publickey" || context.username !== options.user || !context.key.data.equals(publicKey.getPublicSSH())) return context.reject(["publickey"]);
|
|
121
|
+
if (!context.signature || publicKey.verify(context.blob, context.signature, context.hashAlgo) === true) return context.accept();
|
|
122
|
+
context.reject(["publickey"]);
|
|
123
|
+
});
|
|
124
|
+
client.on("ready", () => client.on("session", (accept) => {
|
|
125
|
+
const session = accept();
|
|
126
|
+
const environment = Object.create(null);
|
|
127
|
+
session.on("env", (acceptEnv, rejectEnv, info) => {
|
|
128
|
+
if (!environmentName.test(info.key) || allowed && !allowed.has(info.key)) return rejectEnv?.();
|
|
129
|
+
environment[info.key] = info.val;
|
|
130
|
+
acceptEnv?.();
|
|
131
|
+
});
|
|
132
|
+
session.on("exec", (acceptExec, _reject, info) => {
|
|
133
|
+
const stream = acceptExec();
|
|
134
|
+
stream.allowHalfOpen = true;
|
|
135
|
+
const child = spawn("/bin/sh", ["-lc", info.command], {
|
|
136
|
+
cwd: options.cwd,
|
|
137
|
+
detached: true,
|
|
138
|
+
env: {
|
|
139
|
+
...process.env,
|
|
140
|
+
...environment
|
|
141
|
+
},
|
|
142
|
+
stdio: [
|
|
143
|
+
"pipe",
|
|
144
|
+
"pipe",
|
|
145
|
+
"pipe"
|
|
146
|
+
]
|
|
147
|
+
});
|
|
148
|
+
children.add(child);
|
|
149
|
+
stream.pipe(child.stdin);
|
|
150
|
+
child.stdin.on("error", () => {});
|
|
151
|
+
child.stdout.pipe(stream, { end: false });
|
|
152
|
+
child.stderr.pipe(stream.stderr, { end: false });
|
|
153
|
+
const terminate = () => {
|
|
154
|
+
stop(child).catch(() => client.end());
|
|
155
|
+
};
|
|
156
|
+
stream.once("close", terminate);
|
|
157
|
+
stream.on("error", terminate);
|
|
158
|
+
child.once("exit", terminate);
|
|
159
|
+
child.once("error", () => {
|
|
160
|
+
stream.exit(127);
|
|
161
|
+
stream.end();
|
|
162
|
+
});
|
|
163
|
+
child.once("close", (code) => {
|
|
164
|
+
stop(child).finally(() => {
|
|
165
|
+
children.delete(child);
|
|
166
|
+
terminations.delete(child);
|
|
167
|
+
});
|
|
168
|
+
stream.exit(code ?? 1);
|
|
169
|
+
stream.end();
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
}));
|
|
173
|
+
});
|
|
174
|
+
let endDrain;
|
|
175
|
+
const listener = createServer((socket) => {
|
|
176
|
+
sockets.add(socket);
|
|
177
|
+
socket.once("close", () => {
|
|
178
|
+
sockets.delete(socket);
|
|
179
|
+
if (!sockets.size) endDrain?.();
|
|
180
|
+
});
|
|
181
|
+
server.injectSocket(socket);
|
|
182
|
+
});
|
|
183
|
+
const listening = once(listener, "listening");
|
|
184
|
+
listener.listen(options.port ?? 2222, options.host ?? "127.0.0.1");
|
|
185
|
+
await listening;
|
|
186
|
+
const address = listener.address();
|
|
187
|
+
if (!address || !(address instanceof Object)) throw new Error("[vitehub] SSH listener has no TCP address.");
|
|
188
|
+
let closing;
|
|
189
|
+
return {
|
|
190
|
+
port: address.port,
|
|
191
|
+
get connections() {
|
|
192
|
+
return sockets.size;
|
|
193
|
+
},
|
|
194
|
+
close({ drainTimeoutMs = 0 } = {}) {
|
|
195
|
+
if (!Number.isSafeInteger(drainTimeoutMs) || drainTimeoutMs < 0 || drainTimeoutMs > maxTimeoutMs) throw new TypeError("[vitehub] drainTimeoutMs must be a non-negative integer of milliseconds.");
|
|
196
|
+
if (closing) {
|
|
197
|
+
if (!drainTimeoutMs) endDrain?.();
|
|
198
|
+
return closing;
|
|
199
|
+
}
|
|
200
|
+
return closing = (async () => {
|
|
201
|
+
const closed = new Promise((resolve, reject) => listener.close((error) => error ? reject(error) : resolve()));
|
|
202
|
+
if (drainTimeoutMs && sockets.size) await new Promise((resolve) => {
|
|
203
|
+
const timer = setTimeout(() => endDrain?.(), drainTimeoutMs);
|
|
204
|
+
endDrain = () => {
|
|
205
|
+
clearTimeout(timer);
|
|
206
|
+
endDrain = void 0;
|
|
207
|
+
resolve();
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
for (const client of clients) client.end();
|
|
211
|
+
await Promise.all([...children].map(stop));
|
|
212
|
+
for (const socket of sockets) socket.destroy();
|
|
213
|
+
await closed;
|
|
214
|
+
})();
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
//#endregion
|
|
219
|
+
export { serveSsh, sshLaunch };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { a as SandboxTaskDefinitionBundle, c as SandboxTaskDefinitionInput, d as SandboxTaskExecutionOptions, f as SandboxTaskProjectOptions, g as getSandboxTaskFeatureProvider, h as VercelSandboxTaskProviderOptions, i as SandboxTaskDefinition, l as SandboxTaskDefinitionOptions, m as SandboxTaskRunResult, n as CloudflareSandboxTaskDefinitionProviderOptions, o as SandboxTaskDefinitionFromHandler, p as SandboxTaskProvider, r as CloudflareSandboxTaskOptions, s as SandboxTaskDefinitionHandler, t as AgentSandboxTaskConfig, u as SandboxTaskDefinitionProviderOptions } from "../module-types-Cis4hrF1.js";
|
|
2
|
+
import { unsupportedHostedSandboxTaskProviderError } from "./runtime/provider-loader.js";
|
|
3
|
+
import { ExecutionAuthority } from "@vite-hub/runtime";
|
|
4
|
+
import { SandboxTaskDefinitionModules } from "#vitehub-sandbox-task-registry";
|
|
5
|
+
//#region src/task/runtime/registry.d.ts
|
|
6
|
+
export declare function defineSandboxTask<THandler extends (...args: any[]) => any>(input: SandboxTaskDefinitionInput<Parameters<THandler>[0], Awaited<ReturnType<THandler>>> & {
|
|
7
|
+
run: THandler;
|
|
8
|
+
}): SandboxTaskDefinitionFromHandler<THandler>;
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/task/internal/shared/request-payload.d.ts
|
|
11
|
+
interface RequestPayloadEvent {
|
|
12
|
+
req: {
|
|
13
|
+
json: () => Promise<unknown>;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export declare function readRequestPayload(event: RequestPayloadEvent, fallback?: unknown): Promise<unknown>;
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region src/task/internal/shared/validation.d.ts
|
|
19
|
+
interface ValidationIssue {
|
|
20
|
+
message: string;
|
|
21
|
+
path?: readonly unknown[];
|
|
22
|
+
}
|
|
23
|
+
type StandardSchemaValidationResult<TOutput = unknown> = {
|
|
24
|
+
value: TOutput;
|
|
25
|
+
issues?: undefined;
|
|
26
|
+
} | {
|
|
27
|
+
issues: readonly ValidationIssue[];
|
|
28
|
+
};
|
|
29
|
+
interface StandardSchemaValidator<TInput = unknown, TOutput = TInput> {
|
|
30
|
+
'~standard': {
|
|
31
|
+
validate: (input: TInput) => StandardSchemaValidationResult<TOutput> | Promise<StandardSchemaValidationResult<TOutput>>;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
type ValidationFunction<TInput = unknown, TResult = TInput> = (input: TInput) => TResult | Promise<TResult>;
|
|
35
|
+
type ValidationResult<TInput, TResult> = TResult extends false | true | null | undefined ? TInput : TResult;
|
|
36
|
+
interface ValidationErrorContext<TValue = unknown> {
|
|
37
|
+
value?: TValue;
|
|
38
|
+
issues?: readonly ValidationIssue[];
|
|
39
|
+
}
|
|
40
|
+
interface ValidationOptions<TValue = unknown> {
|
|
41
|
+
onError?: (context: ValidationErrorContext<TValue>) => unknown;
|
|
42
|
+
}
|
|
43
|
+
export declare function readValidatedPayload<TInput, TOutput>(payload: TInput, validate: StandardSchemaValidator<TInput, TOutput>, options?: ValidationOptions<TInput>): Promise<TOutput>;
|
|
44
|
+
export declare function readValidatedPayload<TInput, TResult>(payload: TInput, validate: ValidationFunction<TInput, TResult>, options?: ValidationOptions<TInput>): Promise<ValidationResult<TInput, Awaited<TResult>>>;
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/task/runtime/registry-types.d.ts
|
|
47
|
+
type SandboxTaskDefinitionName = keyof SandboxTaskDefinitionModules;
|
|
48
|
+
type SandboxTaskRegistryDefinition<TName extends keyof SandboxTaskDefinitionModules> = SandboxTaskDefinitionModules[TName];
|
|
49
|
+
type SandboxTaskPayload<TDefinition> = TDefinition extends {
|
|
50
|
+
payload: infer TPayload;
|
|
51
|
+
} ? TPayload : unknown;
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/task/runtime/public.d.ts
|
|
54
|
+
export declare function runSandboxTask<const TName extends SandboxTaskDefinitionName>(name: TName, payload?: SandboxTaskPayload<SandboxTaskRegistryDefinition<TName>>, options?: SandboxTaskExecutionOptions): Promise<SandboxTaskRunResult>;
|
|
55
|
+
export declare function runSandboxTask(name: string, payload?: unknown, options?: SandboxTaskExecutionOptions): Promise<SandboxTaskRunResult>;
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/task/runtime/runtime.d.ts
|
|
58
|
+
interface SandboxTaskRunner {
|
|
59
|
+
readonly executionAuthority: ExecutionAuthority;
|
|
60
|
+
name: string;
|
|
61
|
+
run: <TPayload = unknown, TResult = unknown>(payload?: TPayload, options?: SandboxTaskExecutionOptions) => Promise<TResult>;
|
|
62
|
+
}
|
|
63
|
+
export declare function resolveSandboxTaskRunner<TPayload = unknown, TResult = unknown>(name?: string): Promise<SandboxTaskRunner & {
|
|
64
|
+
run: (payload?: TPayload, options?: SandboxTaskExecutionOptions) => Promise<TResult>;
|
|
65
|
+
}>;
|
|
66
|
+
//#endregion
|
|
67
|
+
export { type AgentSandboxTaskConfig, type CloudflareSandboxTaskDefinitionProviderOptions, type CloudflareSandboxTaskOptions, type RequestPayloadEvent, type SandboxTaskDefinition, type SandboxTaskDefinitionBundle, type SandboxTaskDefinitionFromHandler, type SandboxTaskDefinitionHandler, type SandboxTaskDefinitionInput, type SandboxTaskDefinitionOptions, type SandboxTaskDefinitionProviderOptions, type SandboxTaskExecutionOptions, type SandboxTaskProjectOptions, type SandboxTaskProvider, type SandboxTaskRunResult, type SandboxTaskRunner, type VercelSandboxTaskProviderOptions, type getSandboxTaskFeatureProvider, unsupportedHostedSandboxTaskProviderError };
|