Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(device): add opt-in SRT sandbox runtime (#17476)

Arvin Xue3d25e43b3bb
diff --git a/apps/cli/pnpm-workspace.yaml b/apps/cli/pnpm-workspace.yaml
index 748dba99202..6b2496a4615 100644
--- a/apps/cli/pnpm-workspace.yaml
+++ b/apps/cli/pnpm-workspace.yaml
@@ -1,6 +1,7 @@
packages:
- '../../packages/agent-gateway-client'
- '../../packages/device-control'
+ - '../../packages/device-sandbox'
- '../../packages/device-gateway-client'
- '../../packages/device-identity'
- '../../packages/heterogeneous-agents'
diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yaml
index f8c368559b0..b0ed3e4b278 100644
--- a/apps/desktop/pnpm-workspace.yaml
+++ b/apps/desktop/pnpm-workspace.yaml
@@ -9,6 +9,7 @@ packages:
- '../../packages/file-loaders'
- '../../packages/desktop-bridge'
- '../../packages/device-control'
+ - '../../packages/device-sandbox'
- '../../packages/device-gateway-client'
- '../../packages/device-identity'
- '../../packages/local-file-shell'
diff --git a/packages/device-sandbox/package.json b/packages/device-sandbox/package.json
new file mode 100644
index 00000000000..4097a8be884
--- /dev/null
+++ b/packages/device-sandbox/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@lobechat/device-sandbox",
+ "version": "1.0.0",
+ "private": true,
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "scripts": {
+ "test": "bunx vitest run --silent='passed-only'",
+ "test:coverage": "bunx vitest run --coverage"
+ },
+ "dependencies": {
+ "@anthropic-ai/sandbox-runtime": "0.0.66"
+ },
+ "devDependencies": {
+ "vitest": "3.2.6"
+ }
+}
diff --git a/packages/device-sandbox/scripts/verify-boundaries.ts b/packages/device-sandbox/scripts/verify-boundaries.ts
new file mode 100644
index 00000000000..9a6c0ba54cc
--- /dev/null
+++ b/packages/device-sandbox/scripts/verify-boundaries.ts
@@ -0,0 +1,205 @@
+import { spawn } from 'node:child_process';
+import { mkdtemp, rm, symlink } from 'node:fs/promises';
+import { createServer } from 'node:net';
+import os from 'node:os';
+import path from 'node:path';
+
+import { createSandboxLaunchPlan, srtSandboxRuntime } from '../src';
+
+interface CommandResult {
+ exitCode: number | null;
+ stderr: string;
+ stdout: string;
+}
+
+interface VerificationCase {
+ actual: string;
+ expected: string;
+ name: string;
+ passed: boolean;
+}
+
+const execute = async (command: string, writableRoots: string[]): Promise<CommandResult> => {
+ const launchPlan = await createSandboxLaunchPlan({
+ command: { args: ['-c', command], cmd: '/bin/sh' },
+ env: { ...process.env, LOBE_TEST_SECRET: 'must-not-leak' },
+ policy: { allowNetwork: false, onUnavailable: 'deny', writableRoots },
+ });
+
+ return new Promise((resolve, reject) => {
+ const child = spawn(launchPlan.cmd, launchPlan.args, {
+ env: launchPlan.env as NodeJS.ProcessEnv,
+ });
+ let stderr = '';
+ let stdout = '';
+ child.stderr.on('data', (chunk) => {
+ stderr += String(chunk);
+ });
+ child.stdout.on('data', (chunk) => {
+ stdout += String(chunk);
+ });
+ child.once('error', (error) => {
+ launchPlan.release?.();
+ reject(error);
+ });
+ child.once('close', (exitCode) => {
+ launchPlan.release?.();
+ resolve({ exitCode, stderr, stdout });
+ });
+ });
+};
+
+const printCase = ({ actual, expected, name, passed }: VerificationCase) => {
+ console.log(`\n[${passed ? 'PASS' : 'FAIL'}] ${name}`);
+ console.log(` 预期: ${expected}`);
+ console.log(` 实际: ${actual}`);
+};
+
+const fileExists = async (filePath: string) => {
+ try {
+ await import('node:fs/promises').then(({ access }) => access(filePath));
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const main = async () => {
+ if (process.platform !== 'darwin') {
+ throw new Error('This evidence runner currently requires macOS Seatbelt');
+ }
+
+ const allowedRoot = await mkdtemp(path.join(os.tmpdir(), 'device-evidence-allowed-'));
+ const deniedRoot = await mkdtemp(path.join(os.tmpdir(), 'device-evidence-denied-'));
+ const cases: VerificationCase[] = [];
+
+ console.log('Device Sandbox 可读验证证据');
+ console.log(`平台: ${process.platform} ${process.arch}`);
+ console.log('backend: @anthropic-ai/sandbox-runtime (macOS Seatbelt)');
+ console.log(`授权目录: ${allowedRoot}`);
+ console.log(`未授权目录: ${deniedRoot}`);
+
+ try {
+ const allowedTarget = path.join(allowedRoot, 'allowed.txt');
+ const allowed = await execute(`printf allowed > ${JSON.stringify(allowedTarget)}`, [
+ allowedRoot,
+ ]);
+ const allowedExists = await fileExists(allowedTarget);
+ cases.push({
+ actual: `exit=${allowed.exitCode}; fileExists=${allowedExists}; stderr=${JSON.stringify(allowed.stderr.trim())}`,
+ expected: 'exit=0 且文件真实存在',
+ name: '控制组:写入授权目录',
+ passed: allowed.exitCode === 0 && allowedExists,
+ });
+
+ const absoluteTarget = path.join(deniedRoot, 'absolute.txt');
+ const absolute = await execute(`printf denied > ${JSON.stringify(absoluteTarget)}`, [
+ allowedRoot,
+ ]);
+ const absoluteExists = await fileExists(absoluteTarget);
+ cases.push({
+ actual: `exit=${absolute.exitCode}; fileExists=${absoluteExists}; stderr=${JSON.stringify(absolute.stderr.trim())}`,
+ expected: '非零退出码、Operation not permitted、文件不存在',
+ name: '攻击 1:使用绝对路径写入未授权目录',
+ passed:
+ absolute.exitCode !== 0 &&
+ !absoluteExists &&
+ absolute.stderr.includes('Operation not permitted'),
+ });
+
+ const traversalTarget = path.join(
+ allowedRoot,
+ '..',
+ path.basename(deniedRoot),
+ 'traversal.txt',
+ );
+ const traversal = await execute(`printf denied > ${JSON.stringify(traversalTarget)}`, [
+ allowedRoot,
+ ]);
+ const traversalExists = await fileExists(traversalTarget);
+ cases.push({
+ actual: `exit=${traversal.exitCode}; fileExists=${traversalExists}; stderr=${JSON.stringify(traversal.stderr.trim())}`,
+ expected: '非零退出码、Operation not permitted、文件不存在',
+ name: '攻击 2:使用 ../ 穿越到未授权目录',
+ passed:
+ traversal.exitCode !== 0 &&
+ !traversalExists &&
+ traversal.stderr.includes('Operation not permitted'),
+ });
+
+ const childTarget = path.join(deniedRoot, 'child-shell.txt');
+ const child = await execute(`/bin/sh -c 'printf denied > ${JSON.stringify(childTarget)}'`, [
+ allowedRoot,
+ ]);
+ const childExists = await fileExists(childTarget);
+ cases.push({
+ actual: `exit=${child.exitCode}; fileExists=${childExists}; stderr=${JSON.stringify(child.stderr.trim())}`,
+ expected: '子 shell 同样被约束,文件不存在',
+ name: '攻击 3:启动子 shell 后重定向写入',
+ passed:
+ child.exitCode !== 0 && !childExists && child.stderr.includes('Operation not permitted'),
+ });
+
+ const outsideLink = path.join(allowedRoot, 'outside-link');
+ await symlink(deniedRoot, outsideLink);
+ const linkedTarget = path.join(outsideLink, 'linked.txt');
+ const linked = await execute(`printf denied > ${JSON.stringify(linkedTarget)}`, [allowedRoot]);
+ const linkedExists = await fileExists(linkedTarget);
+ cases.push({
+ actual: `exit=${linked.exitCode}; fileExists=${linkedExists}; stderr=${JSON.stringify(linked.stderr.trim())}`,
+ expected: '按 symlink 的真实目标判定,文件不存在',
+ name: '攻击 4:通过授权目录内的 symlink 写到目录外',
+ passed:
+ linked.exitCode !== 0 && !linkedExists && linked.stderr.includes('Operation not permitted'),
+ });
+
+ const secret = await execute('printf %s "${LOBE_TEST_SECRET-unset}"', [allowedRoot]);
+ cases.push({
+ actual: `exit=${secret.exitCode}; stdout=${JSON.stringify(secret.stdout)}; leaked=${secret.stdout.includes('must-not-leak')}`,
+ expected: 'stdout="unset" 且 leaked=false',
+ name: '凭证攻击:读取未加入 allowlist 的宿主环境变量',
+ passed:
+ secret.exitCode === 0 &&
+ secret.stdout === 'unset' &&
+ !secret.stdout.includes('must-not-leak'),
+ });
+
+ let acceptedConnections = 0;
+ const server = createServer(() => {
+ acceptedConnections += 1;
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Failed to bind evidence server');
+
+ try {
+ const network = await execute(
+ `node -e "require('net').connect(${address.port}, '127.0.0.1').once('connect', () => process.exit(0)).once('error', (error) => { console.error(error.code); process.exit(7) })"`,
+ [allowedRoot],
+ );
+ cases.push({
+ actual: `exit=${network.exitCode}; hostAcceptedConnections=${acceptedConnections}; stderr=${JSON.stringify(network.stderr.trim())}`,
+ expected: '连接失败,宿主 server 接收到 0 个连接',
+ name: '网络攻击:绕过应用直接连接 127.0.0.1 TCP server',
+ passed: network.exitCode !== 0 && acceptedConnections === 0,
+ });
+ } finally {
+ server.close();
+ }
+
+ for (const item of cases) printCase(item);
+
+ const passed = cases.filter((item) => item.passed).length;
+ console.log(`\n结论: ${passed}/${cases.length} 项符合预期`);
+ console.log('说明: 这些结果来自本次真实进程执行,不是对测试代码的静态推断。');
+ if (passed !== cases.length) process.exitCode = 1;
+ } finally {
+ await srtSandboxRuntime.shutdown();
+ await Promise.all([
+ rm(allowedRoot, { force: true, recursive: true }),
+ rm(deniedRoot, { force: true, recursive: true }),
+ ]);
+ }
+};
+
+await main();
diff --git a/packages/device-sandbox/src/__tests__/launchPlan.test.ts b/packages/device-sandbox/src/__tests__/launchPlan.test.ts
new file mode 100644
index 00000000000..7ef2a928fa0
--- /dev/null
+++ b/packages/device-sandbox/src/__tests__/launchPlan.test.ts
@@ -0,0 +1,116 @@
+import { realpathSync } from 'node:fs';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { createSandboxEnv } from '../env';
+import { createSandboxLaunchPlan } from '../launchPlan';
+import { normalizeSandboxPolicy } from '../policy';
+import { srtSandboxRuntime } from '../runtime';
+import { createSrtConfig } from '../srt';
+
+const policy = {
+ allowNetwork: false,
+ onUnavailable: 'deny',
+ writableRoots: ['/tmp'],
+} as const;
+
+describe('device sandbox launch plan', () => {
+ afterEach(async () => {
+ await srtSandboxRuntime.shutdown();
+ });
+
+ it('fails closed when Sandbox Runtime is unavailable', async () => {
+ await expect(
+ createSandboxLaunchPlan({
+ capability: {
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'missing Sandbox Runtime dependency',
+ },
+ command: { args: [], cmd: '/bin/echo' },
+ policy,
+ }),
+ ).rejects.toMatchObject({
+ code: 'SANDBOX_UNAVAILABLE',
+ message: 'missing Sandbox Runtime dependency',
+ });
+ });
+
+ it('returns an explicit unsandboxed plan only for warn-allow', async () => {
+ const plan = await createSandboxLaunchPlan({
+ capability: {
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'missing Sandbox Runtime dependency',
+ },
+ command: { args: ['ok'], cmd: '/bin/echo' },
+ policy: { ...policy, onUnavailable: 'warn-allow' },
+ });
+
+ expect(plan).toMatchObject({
+ args: ['ok'],
+ cmd: '/bin/echo',
+ sandboxed: false,
+ warning: 'missing Sandbox Runtime dependency',
+ });
+ });
+
+ it('keeps only the default environment and explicit allowlist', () => {
+ expect(
+ createSandboxEnv(
+ { HOME: '/Users/test', LOBE_TEST_ALLOWED: 'yes', LOBE_TEST_SECRET: 'no' },
+ { envAllowlist: ['LOBE_TEST_ALLOWED'] },
+ ),
+ ).toEqual({ HOME: '/Users/test', LOBE_TEST_ALLOWED: 'yes' });
+ });
+
+ it('normalizes roots and rejects relative paths', () => {
+ expect(
+ normalizeSandboxPolicy({ ...policy, writableRoots: ['/tmp/../tmp', '/tmp'] }).writableRoots,
+ ).toEqual([realpathSync.native('/tmp')]);
+ expect(() => normalizeSandboxPolicy({ ...policy, writableRoots: ['relative'] })).toThrow(
+ 'must be absolute',
+ );
+ });
+
+ it('requires an explicit domain allowlist when networking is enabled', () => {
+ expect(() => normalizeSandboxPolicy({ ...policy, allowNetwork: true })).toThrow(
+ 'requires an explicit non-empty domain allowlist',
+ );
+ });
+
+ it('maps the LobeHub policy to a fail-closed Sandbox Runtime configuration', () => {
+ expect(
+ createSrtConfig({
+ ...policy,
+ allowedNetworkDomains: ['api.github.com'],
+ allowNetwork: true,
+ deniedReadRoots: ['/tmp'],
+ deniedWriteRoots: ['/tmp'],
+ readableRoots: ['/tmp'],
+ }),
+ ).toEqual({
+ allowAppleEvents: false,
+ allowPty: false,
+ enableWeakerNestedSandbox: false,
+ enableWeakerNetworkIsolation: false,
+ filesystem: {
+ allowRead: [realpathSync.native('/tmp')],
+ allowWrite: [realpathSync.native('/tmp')],
+ allowGitConfig: false,
+ denyRead: [realpathSync.native('/tmp')],
+ denyWrite: [realpathSync.native('/tmp')],
+ },
+ network: {
+ allowedDomains: ['api.github.com'],
+ allowAllUnixSockets: false,
+ allowLocalBinding: false,
+ allowUnixSockets: [],
+ deniedDomains: [],
+ strictAllowlist: true,
+ },
+ });
+ });
+});
diff --git a/packages/device-sandbox/src/__tests__/srt.integration.test.ts b/packages/device-sandbox/src/__tests__/srt.integration.test.ts
new file mode 100644
index 00000000000..8a05f04a749
--- /dev/null
+++ b/packages/device-sandbox/src/__tests__/srt.integration.test.ts
@@ -0,0 +1,221 @@
+import { spawn } from 'node:child_process';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import type { Socket } from 'node:net';
+import { createServer } from 'node:net';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { createSandboxLaunchPlan } from '../launchPlan';
+import { srtSandboxRuntime } from '../runtime';
+import type { SandboxLaunchPlan, SandboxPolicy } from '../types';
+
+const run = async (plan: SandboxLaunchPlan) =>
+ new Promise<{ exitCode: number | null; stderr: string; stdout: string }>((resolve, reject) => {
+ const child = spawn(plan.cmd, plan.args, { env: plan.env as NodeJS.ProcessEnv });
+ let stderr = '';
+ let stdout = '';
+ child.stderr.on('data', (chunk) => {
+ stderr += String(chunk);
+ });
+ child.stdout.on('data', (chunk) => {
+ stdout += String(chunk);
+ });
+ child.once('error', (error) => {
+ plan.release?.();
+ reject(error);
+ });
+ child.once('close', (exitCode) => {
+ plan.release?.();
+ resolve({ exitCode, stderr, stdout });
+ });
+ });
+
+describe.skipIf(process.platform !== 'darwin')('Anthropic sandbox-runtime integration', () => {
+ let allowedRoot: string;
+ let deniedRoot: string;
+ let policy: SandboxPolicy;
+
+ beforeEach(async () => {
+ allowedRoot = await mkdtemp(path.join(os.tmpdir(), 'device-srt-allowed-'));
+ deniedRoot = await mkdtemp(path.join(os.tmpdir(), 'device-srt-denied-'));
+ policy = {
+ allowNetwork: false,
+ deniedReadRoots: [deniedRoot],
+ onUnavailable: 'deny',
+ readableRoots: [allowedRoot],
+ writableRoots: [allowedRoot],
+ };
+ });
+
+ afterEach(async () => {
+ await srtSandboxRuntime.shutdown();
+ await Promise.all([
+ rm(allowedRoot, { force: true, recursive: true }),
+ rm(deniedRoot, { force: true, recursive: true }),
+ ]);
+ });
+
+ const runShell = async (command: string) => {
+ const plan = await createSandboxLaunchPlan({
+ command: { args: ['-c', command], cmd: '/bin/sh' },
+ env: process.env,
+ policy,
+ });
+ return run(plan);
+ };
+
+ it('allows approved writes and denies writes outside the root', async () => {
+ const allowedTarget = path.join(allowedRoot, 'allowed.txt');
+ const deniedTarget = path.join(deniedRoot, 'denied.txt');
+
+ const allowed = await runShell(`printf allowed > ${JSON.stringify(allowedTarget)}`);
+ const denied = await runShell(`printf denied > ${JSON.stringify(deniedTarget)}`);
+
+ expect(allowed.exitCode).toBe(0);
+ await expect(readFile(allowedTarget, 'utf8')).resolves.toBe('allowed');
+ expect(denied.exitCode).not.toBe(0);
+ });
+
+ it('denies reads from configured sensitive roots', async () => {
+ const secretPath = path.join(deniedRoot, 'secret.txt');
+ await writeFile(secretPath, 'secret');
+
+ const result = await runShell(`cat ${JSON.stringify(secretPath)}`);
+
+ expect(result.exitCode).not.toBe(0);
+ });
+
+ it('does not expose environment variables outside the allowlist', async () => {
+ const plan = await createSandboxLaunchPlan({
+ command: {
+ args: ['-c', 'printf "%s" "${LOB_TEST_SRT_SECRET-unset}"'],
+ cmd: '/bin/sh',
+ },
+ env: { ...process.env, LOB_TEST_SRT_SECRET: 'must-not-leak' },
+ policy,
+ });
+
+ const result = await run(plan);
+
+ expect(result).toMatchObject({ exitCode: 0, stdout: 'unset' });
+ });
+
+ it('blocks direct loopback connections before they reach the host server', async () => {
+ let acceptedConnections = 0;
+ const server = createServer((socket) => {
+ acceptedConnections += 1;
+ socket.destroy();
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('TCP server did not bind');
+
+ try {
+ const result = await runShell(
+ `node -e "require('net').connect(${address.port}, '127.0.0.1').on('error', () => process.exit(7))"`,
+ );
+
+ expect(result.exitCode).toBe(7);
+ expect(acceptedConnections).toBe(0);
+ } finally {
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ }
+ });
+
+ it('allows only explicitly listed domains through the Sandbox Runtime proxy', async () => {
+ let acceptedConnections = 0;
+ const sockets = new Set<Socket>();
+ const server = createServer((socket) => {
+ acceptedConnections += 1;
+ socket.end('HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 7\r\n\r\nallowed');
+ });
+ server.on('connection', (socket) => {
+ sockets.add(socket);
+ socket.once('close', () => sockets.delete(socket));
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('HTTP server did not bind');
+ policy = {
+ ...policy,
+ allowedNetworkDomains: ['localhost'],
+ allowNetwork: true,
+ };
+
+ try {
+ const allowed = await runShell(
+ `/usr/bin/curl --max-time 2 --silent --fail --noproxy '' http://localhost:${address.port}`,
+ );
+ const denied = await runShell(
+ `/usr/bin/curl --max-time 2 --silent --fail --noproxy '' http://127.0.0.1:${address.port}`,
+ );
+
+ expect(allowed).toMatchObject({ exitCode: 0, stdout: 'allowed' });
+ expect(denied.exitCode).not.toBe(0);
+ expect(acceptedConnections).toBe(1);
+ } finally {
+ for (const socket of sockets) socket.destroy();
+ server.close();
+ }
+ }, 10_000);
+
+ it('keeps one fixed policy while commands overlap and refuses premature reset', async () => {
+ const first = await createSandboxLaunchPlan({
+ command: { args: ['-c', 'printf first'], cmd: '/bin/sh' },
+ policy,
+ });
+ const second = await createSandboxLaunchPlan({
+ command: { args: ['-c', 'printf second'], cmd: '/bin/sh' },
+ policy,
+ });
+
+ await expect(srtSandboxRuntime.shutdown()).rejects.toMatchObject({ code: 'SANDBOX_BUSY' });
+
+ const [firstResult, secondResult] = await Promise.all([run(first), run(second)]);
+ expect(firstResult).toMatchObject({ exitCode: 0, stdout: 'first' });
+ expect(secondResult).toMatchObject({ exitCode: 0, stdout: 'second' });
+ });
+
+ it('rejects a different device policy until the current session is reset', async () => {
+ const first = await createSandboxLaunchPlan({
+ command: { args: ['-c', 'true'], cmd: '/bin/sh' },
+ policy,
+ });
+ await run(first);
+
+ await expect(
+ createSandboxLaunchPlan({
+ command: { args: ['-c', 'true'], cmd: '/bin/sh' },
+ policy: { ...policy, writableRoots: [deniedRoot] },
+ }),
+ ).rejects.toMatchObject({ code: 'SANDBOX_POLICY_CONFLICT' });
+
+ await srtSandboxRuntime.shutdown();
+ const next = await createSandboxLaunchPlan({
+ command: { args: ['-c', 'true'], cmd: '/bin/sh' },
+ policy: { ...policy, writableRoots: [deniedRoot] },
+ });
+ await expect(run(next)).resolves.toMatchObject({ exitCode: 0 });
+ });
+
+ it('preserves shell arguments containing quotes without host-shell injection', async () => {
+ const marker = path.join(deniedRoot, 'injected.txt');
+ const plan = await createSandboxLaunchPlan({
+ command: {
+ args: ["value with spaces and 'quotes'; touch " + marker],
+ cmd: '/bin/echo',
+ },
+ policy,
+ });
+
+ const result = await run(plan);
+
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain("value with spaces and 'quotes'; touch");
+ await expect(readFile(marker, 'utf8')).rejects.toThrow();
+ });
+});
diff --git a/packages/device-sandbox/src/capability.ts b/packages/device-sandbox/src/capability.ts
new file mode 100644
index 00000000000..a459518da33
--- /dev/null
+++ b/packages/device-sandbox/src/capability.ts
@@ -0,0 +1,32 @@
+import { SandboxManager } from '@anthropic-ai/sandbox-runtime';
+
+import type { SandboxCapability } from './types';
+
+export const probeSandboxCapability = async (): Promise<SandboxCapability> => {
+ if (!SandboxManager.isSupportedPlatform()) {
+ return {
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: `Sandbox Runtime does not support ${process.platform}`,
+ };
+ }
+
+ const dependencies = SandboxManager.checkDependencies();
+ if (dependencies.errors.length > 0) {
+ return {
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: `Sandbox Runtime dependencies are unavailable: ${dependencies.errors.join(', ')}`,
+ warnings: dependencies.warnings,
+ };
+ }
+
+ return {
+ available: true,
+ backend: 'srt',
+ networkIsolation: true,
+ warnings: dependencies.warnings,
+ };
+};
diff --git a/packages/device-sandbox/src/env.ts b/packages/device-sandbox/src/env.ts
new file mode 100644
index 00000000000..75db23d0086
--- /dev/null
+++ b/packages/device-sandbox/src/env.ts
@@ -0,0 +1,30 @@
+import type { SandboxEnvironment, SandboxPolicy } from './types';
+
+const DEFAULT_ENV_KEYS = [
+ 'COLORTERM',
+ 'HOME',
+ 'LANG',
+ 'LC_ALL',
+ 'LC_CTYPE',
+ 'PATH',
+ 'SHELL',
+ 'TERM',
+ 'TMPDIR',
+ 'TMP',
+ 'TEMP',
+] as const;
+
+export const createSandboxEnv = (
+ source: SandboxEnvironment,
+ policy: Pick<SandboxPolicy, 'envAllowlist'>,
+): SandboxEnvironment => {
+ const allowedKeys = new Set([...DEFAULT_ENV_KEYS, ...(policy.envAllowlist ?? [])]);
+ const env: SandboxEnvironment = {};
+
+ for (const key of allowedKeys) {
+ const value = source[key];
+ if (value !== undefined) env[key] = value;
+ }
+
+ return env;
+};
diff --git a/packages/device-sandbox/src/index.ts b/packages/device-sandbox/src/index.ts
new file mode 100644
index 00000000000..b1f5b9f3660
--- /dev/null
+++ b/packages/device-sandbox/src/index.ts
@@ -0,0 +1,18 @@
+export { probeSandboxCapability } from './capability';
+export { createSandboxEnv } from './env';
+export { createSandboxLaunchPlan } from './launchPlan';
+export { normalizeSandboxPolicy, normalizeWritableRoots } from './policy';
+export { SrtSandboxRuntime, srtSandboxRuntime } from './runtime';
+export { createSrtConfig } from './srt';
+export type {
+ CreateSandboxLaunchPlanOptions,
+ SandboxBackend,
+ SandboxCapability,
+ SandboxCommand,
+ SandboxEnvironment,
+ SandboxErrorCode,
+ SandboxLaunchPlan,
+ SandboxPolicy,
+ SandboxUnavailableBehavior,
+} from './types';
+export { SandboxError } from './types';
diff --git a/packages/device-sandbox/src/launchPlan.ts b/packages/device-sandbox/src/launchPlan.ts
new file mode 100644
index 00000000000..5fd5b6828d8
--- /dev/null
+++ b/packages/device-sandbox/src/launchPlan.ts
@@ -0,0 +1,50 @@
+import { probeSandboxCapability } from './capability';
+import { createSandboxEnv } from './env';
+import { normalizeSandboxPolicy } from './policy';
+import { srtSandboxRuntime } from './runtime';
+import type { CreateSandboxLaunchPlanOptions, SandboxCapability, SandboxLaunchPlan } from './types';
+import { SandboxError } from './types';
+
+const unavailablePlan = (
+ options: CreateSandboxLaunchPlanOptions,
+ capability: SandboxCapability,
+): SandboxLaunchPlan => {
+ const reason = capability.reason ?? 'Device sandbox is unavailable';
+ if (options.policy.onUnavailable === 'deny') {
+ throw new SandboxError('SANDBOX_UNAVAILABLE', reason);
+ }
+
+ return {
+ ...options.command,
+ capability,
+ env: createSandboxEnv(options.env ?? process.env, options.policy),
+ sandboxed: false,
+ warning: reason,
+ };
+};
+
+export const createSandboxLaunchPlan = async (
+ options: CreateSandboxLaunchPlanOptions,
+): Promise<SandboxLaunchPlan> => {
+ const policy = normalizeSandboxPolicy(options.policy);
+ const capability = options.capability ?? (await probeSandboxCapability());
+
+ if (!capability.available || capability.backend === 'none') {
+ return unavailablePlan({ ...options, policy }, capability);
+ }
+
+ try {
+ return await srtSandboxRuntime.createLaunchPlan({ ...options, policy }, capability);
+ } catch (error) {
+ if (
+ policy.onUnavailable === 'warn-allow' &&
+ !(error instanceof SandboxError && error.code === 'SANDBOX_POLICY_CONFLICT')
+ ) {
+ return unavailablePlan(
+ { ...options, policy },
+ { ...capability, available: false, reason: (error as Error).message },
+ );
+ }
+ throw error;
+ }
+};
diff --git a/packages/device-sandbox/src/policy.ts b/packages/device-sandbox/src/policy.ts
new file mode 100644
index 00000000000..f5eee40bf7a
--- /dev/null
+++ b/packages/device-sandbox/src/policy.ts
@@ -0,0 +1,52 @@
+import { realpathSync } from 'node:fs';
+import path from 'node:path';
+
+import type { SandboxPolicy } from './types';
+import { SandboxError } from './types';
+
+export const normalizeWritableRoots = (roots: readonly string[]): string[] => {
+ const normalized = roots.map((root) => {
+ if (!path.isAbsolute(root)) {
+ throw new SandboxError(
+ 'SANDBOX_POLICY_INVALID',
+ `Sandbox writable root must be absolute: ${root}`,
+ );
+ }
+
+ try {
+ return realpathSync.native(path.resolve(root));
+ } catch {
+ throw new SandboxError(
+ 'SANDBOX_POLICY_INVALID',
+ `Sandbox writable root must exist and be resolvable: ${root}`,
+ );
+ }
+ });
+
+ return [...new Set(normalized)].sort();
+};
+
+export const normalizeSandboxPolicy = (policy: SandboxPolicy): SandboxPolicy => {
+ if (policy.allowNetwork && !policy.allowedNetworkDomains?.length) {
+ throw new SandboxError(
+ 'SANDBOX_POLICY_INVALID',
+ 'Sandbox network access requires an explicit non-empty domain allowlist',
+ );
+ }
+
+ return {
+ ...policy,
+ allowedNetworkDomains: policy.allowedNetworkDomains
+ ? [...new Set(policy.allowedNetworkDomains)].sort()
+ : undefined,
+ deniedReadRoots: policy.deniedReadRoots
+ ? normalizeWritableRoots(policy.deniedReadRoots)
+ : undefined,
+ deniedWriteRoots: policy.deniedWriteRoots
+ ? normalizeWritableRoots(policy.deniedWriteRoots)
+ : undefined,
+ envAllowlist: policy.envAllowlist ? [...new Set(policy.envAllowlist)].sort() : undefined,
+ readableRoots: policy.readableRoots ? normalizeWritableRoots(policy.readableRoots) : undefined,
+ writableRoots: normalizeWritableRoots(policy.writableRoots),
+ };
+};
diff --git a/packages/device-sandbox/src/runtime.ts b/packages/device-sandbox/src/runtime.ts
new file mode 100644
index 00000000000..6be8445dfe1
--- /dev/null
+++ b/packages/device-sandbox/src/runtime.ts
@@ -0,0 +1,102 @@
+import type { SandboxRuntimeConfig } from '@anthropic-ai/sandbox-runtime';
+import { SandboxManager } from '@anthropic-ai/sandbox-runtime';
+
+import { createSandboxEnv } from './env';
+import { createSrtConfig } from './srt';
+import type { CreateSandboxLaunchPlanOptions, SandboxCapability, SandboxLaunchPlan } from './types';
+import { SandboxError } from './types';
+
+const quoteShellArgument = (value: string): string => `'${value.replaceAll("'", `'"'"'`)}'`;
+
+const serializeCommand = (command: { args: string[]; cmd: string }): string =>
+ [command.cmd, ...command.args].map(quoteShellArgument).join(' ');
+
+const configFingerprint = (config: SandboxRuntimeConfig): string => JSON.stringify(config);
+
+export class SrtSandboxRuntime {
+ private activeCommands = 0;
+ private initialization?: Promise<void>;
+ private initializedFingerprint?: string;
+
+ private async ensureInitialized(config: SandboxRuntimeConfig): Promise<void> {
+ const requestedFingerprint = configFingerprint(config);
+
+ if (this.initialization) await this.initialization;
+
+ if (this.initializedFingerprint) {
+ if (this.initializedFingerprint !== requestedFingerprint) {
+ throw new SandboxError(
+ 'SANDBOX_POLICY_CONFLICT',
+ 'Sandbox Runtime is already initialized with a different device policy',
+ );
+ }
+ return;
+ }
+
+ this.initialization = SandboxManager.initialize(config, undefined, true);
+ try {
+ await this.initialization;
+ const initializedConfig = SandboxManager.getConfig();
+ if (!initializedConfig || configFingerprint(initializedConfig) !== requestedFingerprint) {
+ throw new SandboxError(
+ 'SANDBOX_POLICY_CONFLICT',
+ 'Sandbox Runtime is owned by another caller with a different device policy',
+ );
+ }
+ this.initializedFingerprint = requestedFingerprint;
+ } finally {
+ this.initialization = undefined;
+ }
+ }
+
+ async createLaunchPlan(
+ options: CreateSandboxLaunchPlanOptions,
+ capability: SandboxCapability,
+ ): Promise<SandboxLaunchPlan> {
+ const config = createSrtConfig(options.policy);
+ await this.ensureInitialized(config);
+
+ const wrapped = await SandboxManager.wrapWithSandboxArgv(
+ serializeCommand(options.command),
+ '/bin/sh',
+ undefined,
+ undefined,
+ options.cwd ?? process.cwd(),
+ );
+
+ this.activeCommands += 1;
+ let released = false;
+
+ return {
+ args: wrapped.argv.slice(1),
+ capability,
+ cmd: wrapped.argv[0],
+ env:
+ process.platform === 'win32'
+ ? wrapped.env
+ : createSandboxEnv(options.env ?? process.env, options.policy),
+ release: () => {
+ if (released) return;
+ released = true;
+ this.activeCommands -= 1;
+ SandboxManager.cleanupAfterCommand();
+ },
+ sandboxed: true,
+ };
+ }
+
+ async shutdown(): Promise<void> {
+ if (this.initialization) await this.initialization;
+ if (this.activeCommands > 0) {
+ throw new SandboxError(
+ 'SANDBOX_BUSY',
+ `Cannot reset Sandbox Runtime while ${this.activeCommands} command(s) are active`,
+ );
+ }
+
+ if (SandboxManager.isSandboxingEnabled()) await SandboxManager.reset();
+ this.initializedFingerprint = undefined;
+ }
+}
+
+export const srtSandboxRuntime = new SrtSandboxRuntime();
diff --git a/packages/device-sandbox/src/srt.ts b/packages/device-sandbox/src/srt.ts
new file mode 100644
index 00000000000..fb15e6c73f6
--- /dev/null
+++ b/packages/device-sandbox/src/srt.ts
@@ -0,0 +1,30 @@
+import type { SandboxRuntimeConfig } from '@anthropic-ai/sandbox-runtime';
+
+import { normalizeSandboxPolicy } from './policy';
+import type { SandboxPolicy } from './types';
+
+export const createSrtConfig = (input: SandboxPolicy): SandboxRuntimeConfig => {
+ const policy = normalizeSandboxPolicy(input);
+
+ return {
+ filesystem: {
+ allowRead: [...(policy.readableRoots ?? [])],
+ allowWrite: [...policy.writableRoots],
+ allowGitConfig: false,
+ denyRead: [...(policy.deniedReadRoots ?? [])],
+ denyWrite: [...(policy.deniedWriteRoots ?? [])],
+ },
+ network: {
+ allowedDomains: policy.allowNetwork ? [...(policy.allowedNetworkDomains ?? [])] : [],
+ allowAllUnixSockets: false,
+ allowLocalBinding: false,
+ allowUnixSockets: [],
+ deniedDomains: [],
+ strictAllowlist: true,
+ },
+ allowAppleEvents: false,
+ allowPty: false,
+ enableWeakerNestedSandbox: false,
+ enableWeakerNetworkIsolation: false,
+ };
+};
diff --git a/packages/device-sandbox/src/types.ts b/packages/device-sandbox/src/types.ts
new file mode 100644
index 00000000000..c970010bea1
--- /dev/null
+++ b/packages/device-sandbox/src/types.ts
@@ -0,0 +1,59 @@
+export type SandboxBackend = 'none' | 'srt';
+
+export type SandboxUnavailableBehavior = 'deny' | 'warn-allow';
+
+export type SandboxEnvironment = Record<string, string | undefined>;
+
+export interface SandboxPolicy {
+ allowedNetworkDomains?: readonly string[];
+ allowNetwork: boolean;
+ deniedReadRoots?: readonly string[];
+ deniedWriteRoots?: readonly string[];
+ envAllowlist?: readonly string[];
+ onUnavailable: SandboxUnavailableBehavior;
+ readableRoots?: readonly string[];
+ writableRoots: readonly string[];
+}
+
+export interface SandboxCapability {
+ available: boolean;
+ backend: SandboxBackend;
+ networkIsolation: boolean;
+ reason?: string;
+ warnings?: string[];
+}
+
+export interface SandboxCommand {
+ args: string[];
+ cmd: string;
+}
+
+export interface SandboxLaunchPlan extends SandboxCommand {
+ capability: SandboxCapability;
+ env: SandboxEnvironment;
+ release?: () => void;
+ sandboxed: boolean;
+ warning?: string;
+}
+
+export interface CreateSandboxLaunchPlanOptions {
+ capability?: SandboxCapability;
+ command: SandboxCommand;
+ cwd?: string;
+ env?: SandboxEnvironment;
+ platform?: NodeJS.Platform;
+ policy: SandboxPolicy;
+}
+
+export type SandboxErrorCode =
+ 'SANDBOX_BUSY' | 'SANDBOX_POLICY_CONFLICT' | 'SANDBOX_POLICY_INVALID' | 'SANDBOX_UNAVAILABLE';
+
+export class SandboxError extends Error {
+ readonly code: SandboxErrorCode;
+
+ constructor(code: SandboxErrorCode, message: string) {
+ super(message);
+ this.code = code;
+ this.name = 'SandboxError';
+ }
+}
diff --git a/packages/device-sandbox/vitest.config.mts b/packages/device-sandbox/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/device-sandbox/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/local-file-shell/package.json b/packages/local-file-shell/package.json
index 52cb6cfd367..7f0018fccc7 100644
--- a/packages/local-file-shell/package.json
+++ b/packages/local-file-shell/package.json
@@ -6,6 +6,7 @@
"main": "./src/index.ts",
"types": "./src/index.ts",
"dependencies": {
+ "@lobechat/device-sandbox": "workspace:*",
"@lobechat/file-loaders": "workspace:*",
"debug": "^4.4.3",
"diff": "^8.0.4",
diff --git a/packages/local-file-shell/src/shell/__tests__/runner.test.ts b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
index 5b3c1f37a0c..8841606cb46 100644
--- a/packages/local-file-shell/src/shell/__tests__/runner.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { srtSandboxRuntime } from '@lobechat/device-sandbox';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { ShellProcessManager } from '../process-manager';
@@ -16,8 +17,9 @@ describe('runCommand', () => {
processManager = new ShellProcessManager(tmpDir);
});
- afterEach(() => {
+ afterEach(async () => {
processManager.cleanupAll();
+ await srtSandboxRuntime.shutdown();
fs.rmSync(tmpDir, { force: true, recursive: true });
});
@@ -115,6 +117,88 @@ describe('runCommand', () => {
expect(result.success).toBe(true);
expect(result.stdout).toContain('from-runner');
});
+
+ it('should keep the existing unsandboxed behavior when no sandbox policy is provided', async () => {
+ const target = path.join(tmpDir, 'default-path.txt');
+ const result = await runCommand(
+ {
+ command: `printf "%s" "$LOB_TEST_DEFAULT_PATH" > ${JSON.stringify(target)}`,
+ env: { LOB_TEST_DEFAULT_PATH: 'sandbox-disabled' },
+ },
+ { processManager },
+ );
+
+ expect(result).toMatchObject({ exit_code: 0, success: true });
+ expect(fs.readFileSync(target, 'utf8')).toBe('sandbox-disabled');
+ });
+
+ it.skipIf(process.platform !== 'darwin')(
+ 'should execute through the device sandbox and reject writes outside its policy',
+ async () => {
+ const allowedRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'local-shell-sandbox-allowed-'));
+ const deniedTarget = path.join(tmpDir, 'denied.txt');
+
+ try {
+ const result = await runCommand(
+ { command: `printf denied > ${JSON.stringify(deniedTarget)}` },
+ {
+ processManager,
+ sandboxPolicy: {
+ allowNetwork: false,
+ onUnavailable: 'deny',
+ writableRoots: [allowedRoot],
+ },
+ },
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.exit_code).not.toBe(0);
+ expect(fs.existsSync(deniedTarget)).toBe(false);
+ } finally {
+ fs.rmSync(allowedRoot, { force: true, recursive: true });
+ }
+ },
+ );
+
+ it.skipIf(process.platform !== 'darwin')(
+ 'should preserve output and hide non-allowlisted environment variables in the sandbox',
+ async () => {
+ const result = await runCommand(
+ {
+ command: 'printf "output:%s" "${LOB_TEST_SANDBOX_SECRET-unset}"',
+ env: { LOB_TEST_SANDBOX_SECRET: 'must-not-leak' },
+ },
+ {
+ processManager,
+ sandboxPolicy: {
+ allowNetwork: false,
+ onUnavailable: 'deny',
+ writableRoots: [tmpDir],
+ },
+ },
+ );
+
+ expect(result).toMatchObject({ exit_code: 0, success: true });
+ expect(result.stdout).toContain('output:unset');
+ },
+ );
+
+ it('should fail before spawn when a required sandbox backend is unavailable', async () => {
+ const result = await runCommand(
+ { command: 'echo should-not-run' },
+ {
+ processManager,
+ sandboxPolicy: {
+ allowNetwork: false,
+ onUnavailable: 'deny',
+ writableRoots: ['relative-root'],
+ },
+ },
+ );
+
+ expect(result).toMatchObject({ success: false });
+ expect(result.error).toContain('must be absolute');
+ });
});
describe('background mode', () => {
@@ -159,6 +243,56 @@ describe('runCommand', () => {
const second = await processManager.getOutput({ shell_id: bgResult.shell_id!, timeout: 0 });
expect(second.stdout).toContain('second');
});
+
+ it.skipIf(process.platform !== 'darwin')(
+ 'should preserve background execution through the device sandbox',
+ async () => {
+ const result = await runCommand(
+ { command: 'sleep 0.05 && echo sandbox-background', run_in_background: true },
+ {
+ processManager,
+ sandboxPolicy: {
+ allowNetwork: false,
+ onUnavailable: 'deny',
+ writableRoots: [tmpDir],
+ },
+ },
+ );
+
+ const output = await processManager.getOutput({ shell_id: result.shell_id! });
+ expect(output).toMatchObject({ exit_code: 0, success: true });
+ expect(output.stdout).toContain('sandbox-background');
+ },
+ );
+
+ it.skipIf(process.platform !== 'darwin')(
+ 'should release the sandbox runtime after a background command is killed',
+ async () => {
+ const result = await runCommand(
+ { command: 'sleep 60', run_in_background: true },
+ {
+ processManager,
+ sandboxPolicy: {
+ allowNetwork: false,
+ onUnavailable: 'deny',
+ writableRoots: [tmpDir],
+ },
+ },
+ );
+
+ expect(processManager.kill(result.shell_id!).success).toBe(true);
+
+ const startedAt = Date.now();
+ while (Date.now() - startedAt < 2000) {
+ const output = await processManager.getOutput({ shell_id: result.shell_id!, timeout: 0 });
+ if (output.exit_code !== undefined) break;
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+
+ await expect(srtSandboxRuntime.shutdown()).resolves.toBeUndefined();
+ },
+ 10_000,
+ );
});
describe('process management', () => {
diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.ts
index db0a99f7a6e..1610cfca9ae 100644
--- a/packages/local-file-shell/src/shell/runner.ts
+++ b/packages/local-file-shell/src/shell/runner.ts
@@ -1,5 +1,7 @@
import { spawn } from 'node:child_process';
+import type { SandboxPolicy } from '@lobechat/device-sandbox';
+
import type { RunCommandParams, RunCommandResult } from '../types';
import type { ShellOutputFiles, ShellProcess, ShellProcessManager } from './process-manager';
import { getShellConfig } from './utils';
@@ -11,6 +13,7 @@ export interface RunCommandOptions {
info: (...args: any[]) => void;
};
processManager: ShellProcessManager;
+ sandboxPolicy?: SandboxPolicy;
}
export async function runCommand(
@@ -22,7 +25,7 @@ export async function runCommand(
run_in_background,
timeout = 30_000,
}: RunCommandParams,
- { processManager, logger }: RunCommandOptions,
+ { processManager, logger, sandboxPolicy }: RunCommandOptions,
): Promise<RunCommandResult> {
if (!command) {
return { error: 'command is required', success: false };
@@ -32,17 +35,35 @@ export async function runCommand(
logger?.debug(`${logPrefix} Starting`, { background: run_in_background, cwd, timeout });
const shellConfig = getShellConfig(command);
- const childEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env;
+ const requestedEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env;
let outputFiles: ShellOutputFiles | undefined;
+ let releaseSandbox: (() => void) | undefined;
try {
+ let launchCommand = shellConfig;
+ let launchEnv: NodeJS.ProcessEnv = requestedEnv;
+
+ // The device sandbox is an opt-in PoC. Keep the existing runner path untouched unless a caller
+ // explicitly supplies a policy, and avoid loading the experimental runtime on the default path.
+ if (sandboxPolicy) {
+ const { createSandboxLaunchPlan } = await import('@lobechat/device-sandbox');
+ const launchPlan = await createSandboxLaunchPlan({
+ command: shellConfig,
+ cwd,
+ env: requestedEnv,
+ policy: sandboxPolicy,
+ });
+ launchCommand = launchPlan;
+ launchEnv = launchPlan.env as NodeJS.ProcessEnv;
+ releaseSandbox = launchPlan.release;
+ }
const shellId = processManager.createShellId();
const shellOutputFiles = processManager.createOutputFiles(shellId);
outputFiles = shellOutputFiles;
- const childProcess = spawn(shellConfig.cmd, shellConfig.args, {
+ const childProcess = spawn(launchCommand.cmd, launchCommand.args, {
cwd,
detached: process.platform !== 'win32',
- env: childEnv,
+ env: launchEnv,
shell: false,
stdio: ['pipe', shellOutputFiles.stdout.fd, shellOutputFiles.stderr.fd],
});
@@ -62,6 +83,7 @@ export async function runCommand(
logger?.error(`${logPrefix} Command failed:`, error);
shellProcess.exitCode = 1;
});
+ childProcess.once('close', () => releaseSandbox?.());
processManager.register(shellId, shellProcess);
// Close our fd copy only after error/close listeners are registered; spawn errors are asynchronous.
@@ -87,6 +109,7 @@ export async function runCommand(
shell_id: shellId,
};
} catch (error) {
+ releaseSandbox?.();
if (outputFiles) processManager.closeOutputFiles(outputFiles);
return { error: (error as Error).message, success: false };
}