import { execSync } from "child_process";
import { readFileSync, writeFileSync, existsSync, appendFileSync } from "fs";
import { resolve, relative } from "path";
interface SandboxConfig {
workDir: string;
allowedPaths: string[];
deniedPaths: string[];
blockedCommands: string[];
maxFileSize: number;
auditLog: string;
readOnly: boolean;
}
const DEFAULT_BLOCKED = [
"rm -rf /", "rm -rf ~", "rm -rf .",
"mkfs", "dd if=", "> /dev/sd",
"DROP DATABASE", "DROP TABLE", "TRUNCATE",
"curl.*|.*sh", "wget.*|.*bash",
"chmod 777", "chmod -R 777",
"env | curl", "printenv | curl",
"ssh-keygen", "ssh-copy-id",
];
export class AgentSandbox {
private config: SandboxConfig;
private killed = false;
constructor(config: Partial<SandboxConfig> & { workDir: string }) {
this.config = {
allowedPaths: ["**"],
deniedPaths: ["**/.env", "**/.ssh/**", "**/node_modules/**"],
blockedCommands: DEFAULT_BLOCKED,
maxFileSize: 1024 * 1024,
auditLog: "./agent-audit.jsonl",
readOnly: false,
...config,
};
}
readFile(filePath: string): string {
this.checkKilled();
const absPath = resolve(this.config.workDir, filePath);
this.checkPathAllowed(absPath, "read");
this.audit("read", filePath);
return readFileSync(absPath, "utf-8");
}
writeFile(filePath: string, content: string): void {
this.checkKilled();
if (this.config.readOnly) {
throw new SandboxError("Write blocked: sandbox is read-only");
}
const absPath = resolve(this.config.workDir, filePath);
this.checkPathAllowed(absPath, "write");
if (Buffer.byteLength(content) > this.config.maxFileSize) {
throw new SandboxError(
`Write blocked: file exceeds max size (${this.config.maxFileSize} bytes)`
);
}
this.audit("write", filePath, { size: Buffer.byteLength(content) });
writeFileSync(absPath, content);
}
exec(command: string, timeoutMs: number = 30000): string {
this.checkKilled();
this.checkCommandAllowed(command);
this.audit("exec", command);
try {
return execSync(command, {
cwd: this.config.workDir,
encoding: "utf-8",
timeout: timeoutMs,
maxBuffer: 10 * 1024 * 1024,
});
} catch (error: any) {
this.audit("exec_error", command, { error: error.message });
throw error;
}
}
kill(reason: string): void {
this.killed = true;
this.audit("killed", reason);
console.error(`🛑 Agent sandbox killed: ${reason}`);
}
private checkKilled(): void {
if (this.killed) throw new SandboxError("Agent has been killed");
}
private checkPathAllowed(absPath: string, operation: string): void {
const relPath = relative(this.config.workDir, absPath);
if (relPath.startsWith("..")) {
throw new SandboxError(`${operation} blocked: path escapes sandbox (${relPath})`);
}
for (const pattern of this.config.deniedPaths) {
if (matchGlob(relPath, pattern)) {
throw new SandboxError(`${operation} blocked: path matches denylist (${pattern})`);
}
}
}
private checkCommandAllowed(command: string): void {
const lower = command.toLowerCase();
for (const blocked of this.config.blockedCommands) {
if (lower.includes(blocked.toLowerCase())) {
throw new SandboxError(`Command blocked: matches "${blocked}"`);
}
}
}
private audit(action: string, target: string, extra?: Record<string, unknown>): void {
const entry = {
timestamp: new Date().toISOString(),
action,
target,
...extra,
};
appendFileSync(this.config.auditLog, JSON.stringify(entry) + "\n");
}
}
class SandboxError extends Error {
constructor(message: string) {
super(message);
this.name = "SandboxError";
}
}
function matchGlob(path: string, pattern: string): boolean {
const regex = pattern
.replace(/\*\*/g, ".*")
.replace(/\*/g, "[^/]*")
.replace(/\?/g, ".");
return new RegExp(`^${regex}$`).test(path);
}
import { execSync, spawn } from "child_process";
interface DockerSandboxConfig {
image: string;
workDir: string;
readOnly: boolean;
cpuLimit: string;
memoryLimit: string;
networkMode: string;
timeoutSeconds: number;
allowedEnvVars: string[];
}
export class DockerSandbox {
private config: DockerSandboxConfig;
private containerId: string | null = null;
constructor(config: Partial<DockerSandboxConfig> & { workDir: string }) {
this.config = {
image: "node:20-slim",
readOnly: false,
cpuLimit: "1.0",
memoryLimit: "512m",
networkMode: "none",
timeoutSeconds: 300,
allowedEnvVars: [],
...config,
};
}
async start(): Promise<string> {
const mountFlag = this.config.readOnly ? "ro" : "rw";
const envFlags = this.config.allowedEnvVars
.map((v) => `-e ${v}`)
.join(" ");
const cmd = [
"docker run -d",
`--cpus=${this.config.cpuLimit}`,
`--memory=${this.config.memoryLimit}`,
`--network=${this.config.networkMode}`,
"--security-opt=no-new-privileges",
"--read-only",
"--tmpfs /tmp:size=100m",
`-v ${this.config.workDir}:/workspace:${mountFlag}`,
`-w /workspace`,
envFlags,
this.config.image,
"tail -f /dev/null",
].join(" ");
this.containerId = execSync(cmd, { encoding: "utf-8" }).trim();
setTimeout(() => this.kill("timeout"), this.config.timeoutSeconds * 1000);
return this.containerId;
}
exec(command: string): string {
if (!this.containerId) throw new Error("Sandbox not started");
return execSync(
`docker exec ${this.containerId} sh -c '${command.replace(/'/g, "'\\''")}'`,
{ encoding: "utf-8", timeout: 60000 }
);
}
/**
* Kill the sandbox container and remove it.
*/
kill(reason: string = "manual"): void {
if (this.containerId) {
console.log(`🛑 Killing sandbox: ${reason}`);
execSync(`docker kill ${this.containerId} && docker rm ${this.containerId}`, {
encoding: "utf-8",
});
this.containerId = null;
}
}
}