@vite-hub/sandbox 0.0.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +395 -37
- package/dist/abortable-CR01hzfi.js +57 -0
- package/dist/cloudflare-Cog_r2Me.js +910 -0
- package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
- package/dist/cloudflare-failure-CFQhalfh.js +50 -0
- package/dist/container-CqfD8yuE.js +868 -0
- package/dist/crabbox-sbV3Zjuo.js +1110 -0
- package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
- package/dist/error-diagnostics-BJtLRL9w.js +536 -0
- package/dist/file-listing-CHtRrfo1.js +26 -0
- package/dist/file-lock-D0-XPogS.js +74 -0
- package/dist/index-DsoQAUb7.d.ts +594 -0
- package/dist/index.d.ts +2 -69
- package/dist/index.js +281 -1182
- package/dist/internal/cloudflare.d.ts +176 -0
- package/dist/internal/cloudflare.js +8 -0
- package/dist/internal/host-toolchain.d.ts +22 -0
- package/dist/internal/host-toolchain.js +96 -0
- package/dist/internal/vercel.d.ts +4 -0
- package/dist/internal/vercel.js +8 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/module-types-B0LQ5H2S.js +7 -0
- package/dist/module-types-DCeJbS9Z.d.ts +110 -0
- package/dist/process-sweep-CMaujWE5.js +33 -0
- package/dist/provider-resolution-C6AQzuFG.js +133 -0
- package/dist/remote-70ZVZZlq.js +265 -0
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime-DHp6ImeP.js +32 -0
- package/dist/runtime-type-Deo4qzxN.js +9 -0
- package/dist/session-e0lyzjJ3.js +338 -0
- package/dist/shell-quote-Q3u3plif.js +6 -0
- package/dist/size-7AkVwGZb.js +118 -0
- package/dist/ssh.d.ts +63 -0
- package/dist/ssh.js +286 -0
- package/dist/task/index.d.ts +69 -0
- package/dist/task/index.js +1414 -0
- package/dist/task/runtime/empty-registry.d.ts +6 -0
- package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
- package/dist/task/runtime/provider-loader.d.ts +18 -0
- package/dist/task/runtime/provider-loader.js +16 -0
- package/dist/task/runtime/providers/cloudflare.d.ts +14 -0
- package/dist/task/runtime/providers/cloudflare.js +27 -0
- package/dist/task/runtime/providers/vercel.d.ts +12 -0
- package/dist/task/runtime/providers/vercel.js +85 -0
- package/dist/task/runtime/state.d.ts +27 -0
- package/dist/task/runtime/state.js +82 -0
- package/dist/task/vite.d.ts +486 -0
- package/dist/task/vite.js +3966 -0
- package/dist/toolchain-BIVGMRty.js +528 -0
- package/dist/trusted-host-kxkpaQcs.js +714 -0
- package/dist/vercel-BGGrNpza.js +352 -0
- package/package.json +105 -51
- package/dist/cloudflare-env-QQV4uzCT.js +0 -14
- package/dist/module-types-DKYItiOu.d.ts +0 -93
- package/dist/module-types-Dj1MFmHT.js +0 -7
- package/dist/provider-loader-D0UihePq.d.ts +0 -21
- package/dist/runtime/empty-registry.d.ts +0 -6
- package/dist/runtime/provider-loader.d.ts +0 -2
- package/dist/runtime/provider-loader.js +0 -15
- package/dist/runtime/providers/cloudflare.d.ts +0 -29
- package/dist/runtime/providers/cloudflare.js +0 -25
- package/dist/runtime/providers/vercel.d.ts +0 -121
- package/dist/runtime/providers/vercel.js +0 -51
- package/dist/runtime/state.d.ts +0 -26
- package/dist/runtime/state.js +0 -72
- package/dist/vite.d.ts +0 -48
- package/dist/vite.js +0 -3324
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { t as sandboxTaskErrorDiagnostics } from "./error-diagnostics-5QT_BjbQ.js";
|
|
2
|
+
//#region src/task/size.ts
|
|
3
|
+
const cloudflareInstanceTypes = [
|
|
4
|
+
{
|
|
5
|
+
name: "lite",
|
|
6
|
+
vcpu: 1 / 16,
|
|
7
|
+
memoryMib: 256
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
name: "basic",
|
|
11
|
+
vcpu: 1 / 4,
|
|
12
|
+
memoryMib: 1024
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
name: "standard-1",
|
|
16
|
+
vcpu: 1 / 2,
|
|
17
|
+
memoryMib: 4096
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
name: "standard-2",
|
|
21
|
+
vcpu: 1,
|
|
22
|
+
memoryMib: 6144
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
name: "standard-3",
|
|
26
|
+
vcpu: 2,
|
|
27
|
+
memoryMib: 8192
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: "standard-4",
|
|
31
|
+
vcpu: 4,
|
|
32
|
+
memoryMib: 12288
|
|
33
|
+
}
|
|
34
|
+
];
|
|
35
|
+
const cloudflareInstanceTypeAliases = {
|
|
36
|
+
dev: "lite",
|
|
37
|
+
standard: "standard-1"
|
|
38
|
+
};
|
|
39
|
+
/** Same memory as the 2 vCPU default of Vercel. `lite` has too little memory for a package install. */
|
|
40
|
+
const defaultCloudflareInstanceType = "standard-1";
|
|
41
|
+
const vercelMemoryPerVcpu = 2048;
|
|
42
|
+
const vercelMaxVcpus = 32;
|
|
43
|
+
function readPositiveNumber(options, key, integer = false) {
|
|
44
|
+
const value = options[key];
|
|
45
|
+
if (value === void 0) return void 0;
|
|
46
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || integer && !Number.isInteger(value)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_SIZE_INVALID({
|
|
47
|
+
key,
|
|
48
|
+
value: String(value)
|
|
49
|
+
});
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
/** Reads `cpu`, `memory`, and `maxInstances`, and rejects values that are not positive numbers. */
|
|
53
|
+
function readSandboxTaskSize(options) {
|
|
54
|
+
return {
|
|
55
|
+
cpu: readPositiveNumber(options, "cpu"),
|
|
56
|
+
memory: readPositiveNumber(options, "memory"),
|
|
57
|
+
maxInstances: readPositiveNumber(options, "maxInstances", true)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function formatVcpu(vcpu) {
|
|
61
|
+
return vcpu >= 1 ? String(vcpu) : `1/${Math.round(1 / vcpu)}`;
|
|
62
|
+
}
|
|
63
|
+
/** The vCPUs and memory of a Wrangler instance type. Undefined for a name that ViteHub does not know. */
|
|
64
|
+
function describeCloudflareInstanceType(instanceType) {
|
|
65
|
+
if (typeof instanceType === "object") return {
|
|
66
|
+
label: `custom (${formatVcpu(instanceType.vcpu)} vCPU, ${instanceType.memory_mib} MiB memory)`,
|
|
67
|
+
vcpu: instanceType.vcpu,
|
|
68
|
+
memoryMib: instanceType.memory_mib
|
|
69
|
+
};
|
|
70
|
+
const canonical = cloudflareInstanceTypeAliases[instanceType] ?? instanceType;
|
|
71
|
+
const named = cloudflareInstanceTypes.find((entry) => entry.name === canonical);
|
|
72
|
+
return named && {
|
|
73
|
+
label: `${instanceType} (${formatVcpu(named.vcpu)} vCPU, ${named.memoryMib} MiB memory)`,
|
|
74
|
+
vcpu: named.vcpu,
|
|
75
|
+
memoryMib: named.memoryMib
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** The smallest Cloudflare instance type that gives at least `cpu` vCPUs and `memory` MiB. */
|
|
79
|
+
function resolveCloudflareSandboxTaskInstanceType(options) {
|
|
80
|
+
const { cpu, memory } = readSandboxTaskSize(options);
|
|
81
|
+
if (cpu === void 0 && memory === void 0) return defaultCloudflareInstanceType;
|
|
82
|
+
const fit = cloudflareInstanceTypes.find((entry) => entry.vcpu >= (cpu ?? 0) && entry.memoryMib >= (memory ?? 0));
|
|
83
|
+
if (!fit) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_SIZE_TOO_LARGE({
|
|
84
|
+
provider: "Cloudflare",
|
|
85
|
+
size: formatRequest(cpu, memory),
|
|
86
|
+
max: "standard-4 (4 vCPU, 12288 MiB memory)"
|
|
87
|
+
});
|
|
88
|
+
return fit.name;
|
|
89
|
+
}
|
|
90
|
+
/** Throws when an app-owned Wrangler instance type gives less than the requested `cpu` or `memory`. */
|
|
91
|
+
function assertCloudflareInstanceTypeFits(instanceType, options, className) {
|
|
92
|
+
const { cpu, memory } = readSandboxTaskSize(options);
|
|
93
|
+
const size = describeCloudflareInstanceType(instanceType);
|
|
94
|
+
if (!size || size.vcpu >= (cpu ?? 0) && size.memoryMib >= (memory ?? 0)) return;
|
|
95
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_CLOUDFLARE_INSTANCE_TYPE_TOO_SMALL({
|
|
96
|
+
className,
|
|
97
|
+
instanceType: size.label,
|
|
98
|
+
size: formatRequest(cpu, memory)
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** The Vercel vCPU count for `cpu` and `memory`: 1 or an even number up to 32. Undefined keeps the Vercel default. */
|
|
102
|
+
function resolveVercelSandboxTaskVcpus(options) {
|
|
103
|
+
const { cpu, memory } = readSandboxTaskSize(options);
|
|
104
|
+
if (cpu === void 0 && memory === void 0) return void 0;
|
|
105
|
+
const needed = Math.max(Math.ceil(cpu ?? 0), Math.ceil((memory ?? 0) / vercelMemoryPerVcpu), 1);
|
|
106
|
+
const vcpus = needed === 1 ? 1 : needed + needed % 2;
|
|
107
|
+
if (vcpus > vercelMaxVcpus) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_SIZE_TOO_LARGE({
|
|
108
|
+
provider: "Vercel",
|
|
109
|
+
size: formatRequest(cpu, memory),
|
|
110
|
+
max: `${vercelMaxVcpus} vCPU (${vercelMaxVcpus * vercelMemoryPerVcpu} MiB memory)`
|
|
111
|
+
});
|
|
112
|
+
return vcpus;
|
|
113
|
+
}
|
|
114
|
+
function formatRequest(cpu, memory) {
|
|
115
|
+
return [cpu === void 0 ? "" : `cpu: ${cpu}`, memory === void 0 ? "" : `memory: ${memory}`].filter(Boolean).join(", ");
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
export { resolveVercelSandboxTaskVcpus as a, resolveCloudflareSandboxTaskInstanceType as i, describeCloudflareInstanceType as n, readSandboxTaskSize as r, assertCloudflareInstanceTypeFits as t };
|
package/dist/ssh.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
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
|
+
* How long, in milliseconds, to connect again while the SSH port refuses connections, for example while a sidecar
|
|
15
|
+
* starts. Other SSH failures are not retried. Defaults to 30000. Set 0 to fail on the first refused connection.
|
|
16
|
+
*/
|
|
17
|
+
connectRetryMs?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface SshLaunchContext {
|
|
20
|
+
command: string;
|
|
21
|
+
cwd: string;
|
|
22
|
+
environment?: Readonly<Record<string, string | undefined>>;
|
|
23
|
+
requiredEnvironment?: readonly string[];
|
|
24
|
+
}
|
|
25
|
+
/** Launch a command on a trusted SSH host with the same working-directory path. */
|
|
26
|
+
export declare function sshLaunch(options: SshLaunchOptions): (context: SshLaunchContext) => {
|
|
27
|
+
command: string;
|
|
28
|
+
args: string[];
|
|
29
|
+
prepare: (context: {
|
|
30
|
+
abortSignal?: AbortSignal;
|
|
31
|
+
}) => Promise<void>;
|
|
32
|
+
};
|
|
33
|
+
export interface SshServerOptions {
|
|
34
|
+
hostKeyFile: string;
|
|
35
|
+
authorizedKeyFile: string;
|
|
36
|
+
user: string;
|
|
37
|
+
cwd: string;
|
|
38
|
+
port?: number;
|
|
39
|
+
host?: string;
|
|
40
|
+
/** Restrict accepted env names. Omit to accept valid names from the trusted client. */
|
|
41
|
+
acceptEnvironment?: readonly string[];
|
|
42
|
+
}
|
|
43
|
+
export interface SshServerCloseOptions {
|
|
44
|
+
/**
|
|
45
|
+
* Wait up to this many milliseconds for open connections to close before the server ends them and their commands.
|
|
46
|
+
* Defaults to 0, which ends them at once.
|
|
47
|
+
*/
|
|
48
|
+
drainTimeoutMs?: number;
|
|
49
|
+
}
|
|
50
|
+
export interface SshServer {
|
|
51
|
+
port: number;
|
|
52
|
+
/** Open client connections, including connections that have not finished authentication. */
|
|
53
|
+
readonly connections: number;
|
|
54
|
+
/**
|
|
55
|
+
* Stops accepting connections at once, then ends open connections and stops their commands. Clients that are
|
|
56
|
+
* already connected can still run commands while `drainTimeoutMs` lasts. Another call without `drainTimeoutMs`
|
|
57
|
+
* ends the wait early. All calls return the same promise.
|
|
58
|
+
*/
|
|
59
|
+
close(options?: SshServerCloseOptions): Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
/** An authenticated command server, not a filesystem or network sandbox. */
|
|
62
|
+
export declare function serveSsh(options: SshServerOptions): Promise<SshServer>;
|
|
63
|
+
//#endregion
|
package/dist/ssh.js
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
|
|
2
|
+
import { t as invariant } from "./invariant-DolT9EEx.js";
|
|
3
|
+
import { t as stopMarkedProcesses } from "./process-sweep-CMaujWE5.js";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { execFile, spawn } from "node:child_process";
|
|
7
|
+
import { once } from "node:events";
|
|
8
|
+
import { createServer } from "node:net";
|
|
9
|
+
import { promisify } from "node:util";
|
|
10
|
+
//#region src/ssh-launcher.injected.ts
|
|
11
|
+
/**
|
|
12
|
+
* Source text of the SSH launcher. It runs in its own Node process outside the application bundle, with only Node and
|
|
13
|
+
* OpenSSH, so its errors are plain. Its exit status and stderr reach the caller of `sshLaunch()`.
|
|
14
|
+
*/
|
|
15
|
+
const launcherSource = String.raw`
|
|
16
|
+
import { spawn } from "node:child_process"
|
|
17
|
+
import { mkdtemp, readFile, writeFile, rm } from "node:fs/promises"
|
|
18
|
+
import { tmpdir } from "node:os"
|
|
19
|
+
import { join } from "node:path"
|
|
20
|
+
const config = JSON.parse(process.argv[1])
|
|
21
|
+
const quote = value => "'" + value.replaceAll("'", "'\"'\"'") + "'"
|
|
22
|
+
const temporary = await mkdtemp(join(tmpdir(), "vitehub-ssh-"))
|
|
23
|
+
try {
|
|
24
|
+
const diagnostics = join(temporary, "diagnostics")
|
|
25
|
+
let knownHostsFile = config.knownHostsFile
|
|
26
|
+
if (config.hostKeyFile) {
|
|
27
|
+
knownHostsFile = join(temporary, "known_hosts")
|
|
28
|
+
const key = (await readFile(config.hostKeyFile, "utf8")).trim()
|
|
29
|
+
if (!/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-\S+) [A-Za-z0-9+/=]+(?: .*)?$/.test(key)) throw new Error("Invalid SSH host public key")
|
|
30
|
+
await writeFile(knownHostsFile, "vitehub-runner " + key + "\n", { mode: 0o600 })
|
|
31
|
+
}
|
|
32
|
+
const sshArgs = [
|
|
33
|
+
"-E", diagnostics, "-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10",
|
|
34
|
+
"-o", "LogLevel=ERROR", "-o", "ServerAliveInterval=30",
|
|
35
|
+
"-o", "ServerAliveCountMax=3", "-o", "StrictHostKeyChecking=yes",
|
|
36
|
+
...(knownHostsFile ? ["-o", "UserKnownHostsFile=" + knownHostsFile] : []),
|
|
37
|
+
...(config.hostKeyFile ? ["-o", "HostKeyAlias=vitehub-runner"] : []),
|
|
38
|
+
"-i", config.identityFile, "-p", String(config.port),
|
|
39
|
+
...config.forwardEnvironment.flatMap(name => ["-o", "SendEnv=" + name]),
|
|
40
|
+
config.user + "@" + config.host,
|
|
41
|
+
"cd " + quote(config.cwd) + " && exec " + [config.command, ...process.argv.slice(2)].map(quote).join(" "),
|
|
42
|
+
]
|
|
43
|
+
// -E separates local OpenSSH diagnostics from remote stderr, which may itself contain an SSH refusal.
|
|
44
|
+
// Only a local connection refusal establishes that the remote command did not start.
|
|
45
|
+
const refused = /^ssh: connect to host \S+ port \d+: Connection refused\r?$/m
|
|
46
|
+
const deadline = Date.now() + config.connectRetryMs
|
|
47
|
+
let child
|
|
48
|
+
let stopped
|
|
49
|
+
let wake
|
|
50
|
+
const handlers = new Map(["SIGINT", "SIGTERM", "SIGHUP"].map(signal => [signal, () => {
|
|
51
|
+
stopped = signal
|
|
52
|
+
if (child) child.kill(signal)
|
|
53
|
+
wake?.()
|
|
54
|
+
}]))
|
|
55
|
+
for (const [signal, handler] of handlers) process.on(signal, handler)
|
|
56
|
+
try {
|
|
57
|
+
for (let delay = 250; ; delay = Math.min(delay * 2, 4000)) {
|
|
58
|
+
await writeFile(diagnostics, "", { mode: 0o600 })
|
|
59
|
+
if (stopped) {
|
|
60
|
+
process.exitCode = 255
|
|
61
|
+
break
|
|
62
|
+
}
|
|
63
|
+
child = spawn("ssh", sshArgs, { stdio: ["inherit", "inherit", "pipe"] })
|
|
64
|
+
child.stderr.on("data", chunk => {
|
|
65
|
+
if (!process.stderr.write(chunk)) {
|
|
66
|
+
child.stderr.pause()
|
|
67
|
+
process.stderr.once("drain", () => child.stderr.resume())
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
const result = await new Promise((resolve, reject) => {
|
|
71
|
+
child.once("error", reject)
|
|
72
|
+
child.once("close", (code, signal) => resolve({ code, signal }))
|
|
73
|
+
})
|
|
74
|
+
const localDiagnostics = await readFile(diagnostics, "utf8")
|
|
75
|
+
process.stderr.write(localDiagnostics)
|
|
76
|
+
const wait = Math.min(delay, deadline - Date.now())
|
|
77
|
+
if (stopped || result.code !== 255 || !refused.test(localDiagnostics) || wait <= 0) {
|
|
78
|
+
process.exitCode = result.code ?? 1
|
|
79
|
+
break
|
|
80
|
+
}
|
|
81
|
+
await new Promise(resolve => {
|
|
82
|
+
const timer = setTimeout(resolve, wait)
|
|
83
|
+
wake = () => { clearTimeout(timer); resolve() }
|
|
84
|
+
})
|
|
85
|
+
wake = undefined
|
|
86
|
+
if (stopped) {
|
|
87
|
+
process.exitCode = 255
|
|
88
|
+
break
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
} finally {
|
|
92
|
+
for (const [signal, handler] of handlers) process.off(signal, handler)
|
|
93
|
+
}
|
|
94
|
+
} finally {
|
|
95
|
+
if (temporary) await rm(temporary, { recursive: true, force: true })
|
|
96
|
+
}
|
|
97
|
+
`;
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/ssh.ts
|
|
100
|
+
const maxTimeoutMs = 2147483647;
|
|
101
|
+
const environmentName = /^[A-Z_][A-Z0-9_]*$/;
|
|
102
|
+
/** Every process of one SSH command starts with this variable, so the server can stop the ones that leave its process group. */
|
|
103
|
+
const commandEnvironmentKey = "VITEHUB_SSH_COMMAND";
|
|
104
|
+
/** Launch a command on a trusted SSH host with the same working-directory path. */
|
|
105
|
+
function sshLaunch(options) {
|
|
106
|
+
if (!options.host || options.host.startsWith("-") || /[\s\0]/.test(options.host)) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "host" });
|
|
107
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_.-]*$/.test(options.user)) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "user" });
|
|
108
|
+
if (!options.identityFile || options.identityFile.includes("\0")) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "identityFile" });
|
|
109
|
+
const port = options.port ?? 22;
|
|
110
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "port" });
|
|
111
|
+
if (options.hostKeyFile && options.knownHostsFile) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "hostKey" });
|
|
112
|
+
const connectRetryMs = options.connectRetryMs ?? 3e4;
|
|
113
|
+
if (!Number.isSafeInteger(connectRetryMs) || connectRetryMs < 0) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "connectRetryMs" });
|
|
114
|
+
const forwardEnvironment = [...new Set(options.forwardEnvironment ?? [])];
|
|
115
|
+
if (forwardEnvironment.some((name) => !environmentName.test(name))) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "environment" });
|
|
116
|
+
return ({ command, cwd, environment, requiredEnvironment }) => {
|
|
117
|
+
const names = options.forwardEnvironment === void 0 ? Object.keys(environment || {}).filter((name) => environmentName.test(name)) : forwardEnvironment;
|
|
118
|
+
const forwarded = [.../* @__PURE__ */ new Set([...names, ...requiredEnvironment || []])];
|
|
119
|
+
if (forwarded.some((name) => !environmentName.test(name))) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "environment" });
|
|
120
|
+
if (!command || !cwd || command.includes("\0") || cwd.includes("\0")) throw sandboxErrorDiagnostics.SANDBOX_SSH_LAUNCH_INVALID({ problem: "command" });
|
|
121
|
+
const args = (command, cwd) => [
|
|
122
|
+
"--input-type=module",
|
|
123
|
+
"-e",
|
|
124
|
+
launcherSource,
|
|
125
|
+
JSON.stringify({
|
|
126
|
+
...options,
|
|
127
|
+
port,
|
|
128
|
+
connectRetryMs,
|
|
129
|
+
forwardEnvironment: forwarded,
|
|
130
|
+
command,
|
|
131
|
+
cwd
|
|
132
|
+
})
|
|
133
|
+
];
|
|
134
|
+
return {
|
|
135
|
+
command: process.execPath,
|
|
136
|
+
args: args(command, cwd),
|
|
137
|
+
prepare: async ({ abortSignal }) => {
|
|
138
|
+
await promisify(execFile)(process.execPath, args("/bin/true", "/"), { signal: abortSignal });
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/** An authenticated command server, not a filesystem or network sandbox. */
|
|
144
|
+
async function serveSsh(options) {
|
|
145
|
+
if (process.platform === "win32") throw sandboxErrorDiagnostics.SANDBOX_SSH_POSIX_REQUIRED();
|
|
146
|
+
const { default: ssh2 } = await import("ssh2");
|
|
147
|
+
const [hostKey, authorizedKey] = await Promise.all([readFile(options.hostKeyFile), readFile(options.authorizedKeyFile)]);
|
|
148
|
+
const parsedKey = ssh2.utils.parseKey(authorizedKey);
|
|
149
|
+
if (parsedKey instanceof Error) throw parsedKey;
|
|
150
|
+
const publicKey = Array.isArray(parsedKey) ? parsedKey[0] : parsedKey;
|
|
151
|
+
const clients = /* @__PURE__ */ new Set();
|
|
152
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
153
|
+
const children = /* @__PURE__ */ new Set();
|
|
154
|
+
const markers = /* @__PURE__ */ new Map();
|
|
155
|
+
const terminations = /* @__PURE__ */ new Map();
|
|
156
|
+
const allowed = options.acceptEnvironment && new Set(options.acceptEnvironment);
|
|
157
|
+
function stop(child) {
|
|
158
|
+
const pending = terminations.get(child);
|
|
159
|
+
if (pending) return pending;
|
|
160
|
+
const signalGroup = (signal) => {
|
|
161
|
+
if (!child.pid) return;
|
|
162
|
+
try {
|
|
163
|
+
process.kill(-child.pid, signal);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ESRCH") throw error;
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const done = (async () => {
|
|
169
|
+
signalGroup("SIGTERM");
|
|
170
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
171
|
+
signalGroup("SIGKILL");
|
|
172
|
+
const marker = markers.get(child);
|
|
173
|
+
if (marker) await stopMarkedProcesses(commandEnvironmentKey, marker);
|
|
174
|
+
})();
|
|
175
|
+
terminations.set(child, done);
|
|
176
|
+
return done;
|
|
177
|
+
}
|
|
178
|
+
const server = new ssh2.Server({ hostKeys: [hostKey] }, (client) => {
|
|
179
|
+
clients.add(client);
|
|
180
|
+
client.once("close", () => clients.delete(client));
|
|
181
|
+
client.on("error", () => client.end());
|
|
182
|
+
client.on("authentication", (context) => {
|
|
183
|
+
if (context.method !== "publickey" || context.username !== options.user || !context.key.data.equals(publicKey.getPublicSSH())) return context.reject(["publickey"]);
|
|
184
|
+
if (!context.signature || publicKey.verify(context.blob, context.signature, context.hashAlgo) === true) return context.accept();
|
|
185
|
+
context.reject(["publickey"]);
|
|
186
|
+
});
|
|
187
|
+
client.on("ready", () => client.on("session", (accept) => {
|
|
188
|
+
const session = accept();
|
|
189
|
+
const environment = Object.create(null);
|
|
190
|
+
session.on("env", (acceptEnv, rejectEnv, info) => {
|
|
191
|
+
if (!environmentName.test(info.key) || allowed && !allowed.has(info.key)) return rejectEnv?.();
|
|
192
|
+
environment[info.key] = info.val;
|
|
193
|
+
acceptEnv?.();
|
|
194
|
+
});
|
|
195
|
+
session.on("exec", (acceptExec, _reject, info) => {
|
|
196
|
+
const stream = acceptExec();
|
|
197
|
+
stream.allowHalfOpen = true;
|
|
198
|
+
const marker = randomUUID();
|
|
199
|
+
const child = spawn("/bin/sh", ["-c", info.command], {
|
|
200
|
+
cwd: options.cwd,
|
|
201
|
+
detached: true,
|
|
202
|
+
env: {
|
|
203
|
+
...process.env,
|
|
204
|
+
...environment,
|
|
205
|
+
[commandEnvironmentKey]: marker
|
|
206
|
+
},
|
|
207
|
+
stdio: [
|
|
208
|
+
"pipe",
|
|
209
|
+
"pipe",
|
|
210
|
+
"pipe"
|
|
211
|
+
]
|
|
212
|
+
});
|
|
213
|
+
children.add(child);
|
|
214
|
+
markers.set(child, marker);
|
|
215
|
+
stream.pipe(child.stdin);
|
|
216
|
+
child.stdin.on("error", () => {});
|
|
217
|
+
child.stdout.pipe(stream, { end: false });
|
|
218
|
+
child.stderr.pipe(stream.stderr, { end: false });
|
|
219
|
+
const terminate = () => {
|
|
220
|
+
stop(child).catch(() => client.end());
|
|
221
|
+
};
|
|
222
|
+
stream.once("close", terminate);
|
|
223
|
+
stream.on("error", terminate);
|
|
224
|
+
child.once("exit", terminate);
|
|
225
|
+
child.once("error", () => {
|
|
226
|
+
stream.exit(127);
|
|
227
|
+
stream.end();
|
|
228
|
+
});
|
|
229
|
+
child.once("close", (code) => {
|
|
230
|
+
stop(child).finally(() => {
|
|
231
|
+
children.delete(child);
|
|
232
|
+
markers.delete(child);
|
|
233
|
+
terminations.delete(child);
|
|
234
|
+
});
|
|
235
|
+
stream.exit(code ?? 1);
|
|
236
|
+
stream.end();
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
}));
|
|
240
|
+
});
|
|
241
|
+
let endDrain;
|
|
242
|
+
const listener = createServer((socket) => {
|
|
243
|
+
sockets.add(socket);
|
|
244
|
+
socket.once("close", () => {
|
|
245
|
+
sockets.delete(socket);
|
|
246
|
+
if (!sockets.size) endDrain?.();
|
|
247
|
+
});
|
|
248
|
+
server.injectSocket(socket);
|
|
249
|
+
});
|
|
250
|
+
const listening = once(listener, "listening");
|
|
251
|
+
listener.listen(options.port ?? 2222, options.host ?? "127.0.0.1");
|
|
252
|
+
await listening;
|
|
253
|
+
const address = listener.address();
|
|
254
|
+
invariant(address && address instanceof Object, "an SSH listener on a TCP host and port has a TCP address");
|
|
255
|
+
let closing;
|
|
256
|
+
return {
|
|
257
|
+
port: address.port,
|
|
258
|
+
get connections() {
|
|
259
|
+
return sockets.size;
|
|
260
|
+
},
|
|
261
|
+
close({ drainTimeoutMs = 0 } = {}) {
|
|
262
|
+
if (!Number.isSafeInteger(drainTimeoutMs) || drainTimeoutMs < 0 || drainTimeoutMs > maxTimeoutMs) throw sandboxErrorDiagnostics.SANDBOX_SSH_DRAIN_TIMEOUT_INVALID();
|
|
263
|
+
if (closing) {
|
|
264
|
+
if (!drainTimeoutMs) endDrain?.();
|
|
265
|
+
return closing;
|
|
266
|
+
}
|
|
267
|
+
return closing = (async () => {
|
|
268
|
+
const closed = new Promise((resolve, reject) => listener.close((error) => error ? reject(error) : resolve()));
|
|
269
|
+
if (drainTimeoutMs && sockets.size) await new Promise((resolve) => {
|
|
270
|
+
const timer = setTimeout(() => endDrain?.(), drainTimeoutMs);
|
|
271
|
+
endDrain = () => {
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
endDrain = void 0;
|
|
274
|
+
resolve();
|
|
275
|
+
};
|
|
276
|
+
});
|
|
277
|
+
for (const client of clients) client.end();
|
|
278
|
+
await Promise.all([...children].map(stop));
|
|
279
|
+
for (const socket of sockets) socket.destroy();
|
|
280
|
+
await closed;
|
|
281
|
+
})();
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
//#endregion
|
|
286
|
+
export { serveSsh, sshLaunch };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { _ as getSandboxTaskFeatureDriver, a as SandboxTaskDefinitionBundle, c as SandboxTaskDefinitionHandler, d as SandboxTaskDriver, f as SandboxTaskExecutionOptions, g as VercelSandboxTaskDriverOptions, h as SandboxTaskRunResult, i as SandboxTaskDefinition, l as SandboxTaskDefinitionInput, m as SandboxTaskRunArguments, n as CloudflareSandboxTaskDefinitionDriverOptions, o as SandboxTaskDefinitionDriverOptions, p as SandboxTaskProjectOptions, r as CloudflareSandboxTaskOptions, s as SandboxTaskDefinitionFromHandler, t as AgentSandboxTaskConfig, u as SandboxTaskDefinitionOptions, v as SandboxTaskSizeOptions } from "../module-types-DCeJbS9Z.js";
|
|
2
|
+
import { ExecutionAuthority, ViteHubContext } from "@vite-hub/runtime";
|
|
3
|
+
import { SandboxTaskDefinitionModules } from "#vitehub-sandbox-task-registry";
|
|
4
|
+
//#region src/task/runtime/registry.d.ts
|
|
5
|
+
export declare function defineSandboxTask<THandler extends (...args: any[]) => any>(input: SandboxTaskDefinitionInput<Parameters<THandler>[0], Awaited<ReturnType<THandler>>> & {
|
|
6
|
+
handler: THandler;
|
|
7
|
+
}): SandboxTaskDefinitionFromHandler<THandler>;
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/task/internal/shared/request-payload.d.ts
|
|
10
|
+
/** Read the JSON body of the request in the event's Standard Context, or `fallback` when the body is not JSON. */
|
|
11
|
+
export declare function readRequestPayload(event: ViteHubContext, fallback?: unknown): Promise<unknown>;
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/task/internal/shared/validation.d.ts
|
|
14
|
+
interface ValidationIssue {
|
|
15
|
+
message: string;
|
|
16
|
+
path?: readonly unknown[];
|
|
17
|
+
}
|
|
18
|
+
type StandardSchemaValidationResult<TOutput = unknown> = {
|
|
19
|
+
value: TOutput;
|
|
20
|
+
issues?: undefined;
|
|
21
|
+
} | {
|
|
22
|
+
issues: readonly ValidationIssue[];
|
|
23
|
+
};
|
|
24
|
+
interface StandardSchemaValidator<TInput = unknown, TOutput = TInput> {
|
|
25
|
+
'~standard': {
|
|
26
|
+
validate: (input: TInput) => StandardSchemaValidationResult<TOutput> | Promise<StandardSchemaValidationResult<TOutput>>;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
type ValidationFunction<TInput = unknown, TResult = TInput> = (input: TInput) => TResult | Promise<TResult>;
|
|
30
|
+
type ValidationResult<TInput, TResult> = TResult extends false | true | null | undefined ? TInput : TResult;
|
|
31
|
+
interface ValidationErrorContext<TValue = unknown> {
|
|
32
|
+
value?: TValue;
|
|
33
|
+
issues?: readonly ValidationIssue[];
|
|
34
|
+
}
|
|
35
|
+
interface ValidationOptions<TValue = unknown> {
|
|
36
|
+
onError?: (context: ValidationErrorContext<TValue>) => unknown;
|
|
37
|
+
}
|
|
38
|
+
export declare function readValidatedPayload<TInput, TOutput>(payload: TInput, validate: StandardSchemaValidator<TInput, TOutput>, options?: ValidationOptions<TInput>): Promise<TOutput>;
|
|
39
|
+
export declare function readValidatedPayload<TInput, TResult>(payload: TInput, validate: ValidationFunction<TInput, TResult>, options?: ValidationOptions<TInput>): Promise<ValidationResult<TInput, Awaited<TResult>>>;
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/task/runtime/registry-types.d.ts
|
|
42
|
+
type SandboxTaskDefinitionName = keyof SandboxTaskDefinitionModules;
|
|
43
|
+
type SandboxTaskRegistryDefinition<TName extends keyof SandboxTaskDefinitionModules> = SandboxTaskDefinitionModules[TName];
|
|
44
|
+
type SandboxTaskPayload<TDefinition> = TDefinition extends {
|
|
45
|
+
payload: infer TPayload;
|
|
46
|
+
} ? TPayload : unknown;
|
|
47
|
+
type SandboxTaskResult<TDefinition> = TDefinition extends {
|
|
48
|
+
result: infer TResult;
|
|
49
|
+
} ? TResult : unknown;
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/task/runtime/public.d.ts
|
|
52
|
+
export declare function runSandboxTask<const TName extends string>(name: TName, ...args: SandboxTaskRunArguments<TName extends SandboxTaskDefinitionName ? SandboxTaskPayload<SandboxTaskRegistryDefinition<TName>> : unknown>): Promise<SandboxTaskRunResult>;
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region src/task/runtime/provider-resolution.d.ts
|
|
55
|
+
export declare function unsupportedHostedSandboxTaskProviderError(provider: unknown): Error;
|
|
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>(...args: SandboxTaskRunArguments<TPayload>) => Promise<TResult>;
|
|
62
|
+
}
|
|
63
|
+
type ResolvedSandboxTaskRunner<TPayload, TResult> = Omit<SandboxTaskRunner, 'run'> & {
|
|
64
|
+
run: (...args: SandboxTaskRunArguments<TPayload>) => Promise<TResult>;
|
|
65
|
+
};
|
|
66
|
+
export declare function resolveSandboxTaskRunner<const TName extends SandboxTaskDefinitionName>(name: TName): Promise<ResolvedSandboxTaskRunner<SandboxTaskPayload<SandboxTaskRegistryDefinition<TName>>, SandboxTaskResult<SandboxTaskRegistryDefinition<TName>>>>;
|
|
67
|
+
export declare function resolveSandboxTaskRunner<TPayload = unknown, TResult = unknown>(name?: string): Promise<ResolvedSandboxTaskRunner<TPayload, TResult>>;
|
|
68
|
+
//#endregion
|
|
69
|
+
export type { AgentSandboxTaskConfig, CloudflareSandboxTaskDefinitionDriverOptions, CloudflareSandboxTaskOptions, SandboxTaskDefinition, SandboxTaskDefinitionBundle, SandboxTaskDefinitionDriverOptions, SandboxTaskDefinitionFromHandler, SandboxTaskDefinitionHandler, SandboxTaskDefinitionInput, SandboxTaskDefinitionOptions, SandboxTaskDriver, SandboxTaskExecutionOptions, SandboxTaskProjectOptions, SandboxTaskRunArguments, SandboxTaskRunResult, SandboxTaskRunner, SandboxTaskSizeOptions, VercelSandboxTaskDriverOptions, getSandboxTaskFeatureDriver };
|