Files
openshell_controller/app/lib/sandboxPrivilegedFiles.ts

54 lines
1.8 KiB
TypeScript

import { spawn } from "node:child_process"
import { OPENSHELL_BIN, hostCommandEnv } from "./hostCommands"
function shellQuote(value: string) {
return `'${value.replace(/'/g, `'\\''`)}'`
}
function runSandboxShell(sandboxName: string, script: string, input?: Buffer | string, timeoutMs = 60000) {
return new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve, reject) => {
const child = spawn(OPENSHELL_BIN, ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], {
env: hostCommandEnv({
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY?.trim() || undefined,
}),
stdio: ["pipe", "pipe", "pipe"],
})
let stdout = ""
let stderr = ""
const timer = setTimeout(() => child.kill("SIGTERM"), timeoutMs)
child.stdout.on("data", (chunk) => { stdout += String(chunk) })
child.stderr.on("data", (chunk) => { stderr += String(chunk) })
child.on("error", (error) => {
clearTimeout(timer)
reject(error)
})
child.on("close", (code) => {
clearTimeout(timer)
resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code })
})
if (input) child.stdin.end(input)
else child.stdin.end()
})
}
export async function writeSandboxFilePrivileged(
sandboxName: string,
targetPath: string,
payload: Buffer,
mode = "0644",
) {
const script = [
`mkdir -p ${shellQuote(targetPath.split("/").slice(0, -1).join("/") || "/")}`,
`cat > ${shellQuote(targetPath)}`,
`chmod ${shellQuote(mode)} ${shellQuote(targetPath)}`,
`chown root:root ${shellQuote(targetPath)} 2>/dev/null || true`,
].join(" && ")
const result = await runSandboxShell(sandboxName, script, payload)
if (result.code !== 0) throw new Error(result.stderr || `failed to write ${targetPath}`)
return {
sandboxName,
path: targetPath,
bytes: payload.byteLength,
}
}