opencode-codex-sandbox 0.0.0-stage → 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/src/bwrap.ts ADDED
@@ -0,0 +1,96 @@
1
+ // Ported from openai/codex (codex-rs/linux-sandbox/src/bwrap.rs). Apache-2.0; see NOTICE.
2
+ import fs from "node:fs"
3
+ import type { ResolvedPolicy } from "./policy.ts"
4
+
5
+ export interface BwrapCommand {
6
+ file: string
7
+ args: string[]
8
+ env: Record<string, string>
9
+ }
10
+
11
+ export interface WslInfo {
12
+ kind: "none" | "wsl1" | "wsl2"
13
+ }
14
+
15
+ export function detectWsl(): WslInfo {
16
+ try {
17
+ const version = fs.readFileSync("/proc/version", "utf8")
18
+ if (/WSL1/i.test(version)) return { kind: "wsl1" }
19
+ if (/microsoft/i.test(version)) return { kind: "wsl2" }
20
+ } catch {
21
+ // not linux or no procfs
22
+ }
23
+ return { kind: "none" }
24
+ }
25
+
26
+ const WSLG_DISTRO_ALIAS = "/mnt/wslg/distro"
27
+
28
+ export function buildBwrapCommand(
29
+ bwrapPath: string,
30
+ policy: ResolvedPolicy,
31
+ innerArgv: string[],
32
+ wsl: WslInfo = detectWsl(),
33
+ ): BwrapCommand {
34
+ if (wsl.kind === "wsl1") {
35
+ throw new Error("opencode-codex-sandbox: WSL1 has no user namespaces and is not supported; use WSL2 or native Linux")
36
+ }
37
+
38
+ const args: string[] = [
39
+ bwrapPath,
40
+ "--as-pid-1",
41
+ "--new-session",
42
+ "--die-with-parent",
43
+ "--ro-bind", "/", "/",
44
+ "--dev", "/dev",
45
+ ]
46
+
47
+ const roots = [...policy.writableRoots].sort(
48
+ (a, b) => a.path.split("/").length - b.path.split("/").length,
49
+ )
50
+ for (const root of roots) {
51
+ if (wsl.kind === "wsl2" && isUnder(root.path, WSLG_DISTRO_ALIAS)) {
52
+ throw new Error(`opencode-codex-sandbox: writable root under ${WSLG_DISTRO_ALIAS} is a duplicate of / on WSL2 and cannot be sandboxed: ${root.path}`)
53
+ }
54
+ args.push("--bind", root.path, root.path)
55
+ for (const sub of root.excluded) {
56
+ let stat: fs.Stats | undefined
57
+ try {
58
+ stat = fs.statSync(sub)
59
+ } catch {
60
+ stat = undefined
61
+ }
62
+ if (stat) {
63
+ args.push("--ro-bind", sub, sub)
64
+ } else {
65
+ // Non-existent metadata dir: create a read-only placeholder so the
66
+ // sandboxed process cannot mkdir it and escape the carveout.
67
+ args.push("--perms", "555", "--tmpfs", sub, "--remount-ro", sub)
68
+ }
69
+ }
70
+ }
71
+
72
+ if (wsl.kind === "wsl2") {
73
+ // The WSL interop socket can launch arbitrary Windows processes: mask it.
74
+ args.push("--tmpfs", "/run/WSL")
75
+ if (fs.existsSync(WSLG_DISTRO_ALIAS)) {
76
+ args.push("--perms", "000", "--tmpfs", WSLG_DISTRO_ALIAS, "--remount-ro", WSLG_DISTRO_ALIAS)
77
+ }
78
+ for (const arg of innerArgv.slice(0, 1)) {
79
+ if (isUnder(arg, WSLG_DISTRO_ALIAS)) {
80
+ throw new Error(`opencode-codex-sandbox: shell under ${WSLG_DISTRO_ALIAS} cannot be sandboxed on WSL2: ${arg}`)
81
+ }
82
+ }
83
+ }
84
+
85
+ args.push("--unshare-user", "--unshare-pid", "--unshare-ipc")
86
+ if (!policy.network) args.push("--unshare-net")
87
+ args.push("--proc", "/proc", "--cap-drop", "ALL", "--", ...innerArgv)
88
+
89
+ const env: Record<string, string> = { CODEX_SANDBOX: "bwrap" }
90
+ if (!policy.network) env.CODEX_SANDBOX_NETWORK_DISABLED = "1"
91
+ return { file: bwrapPath, args, env }
92
+ }
93
+
94
+ function isUnder(p: string, parent: string): boolean {
95
+ return p === parent || p.startsWith(parent + "/")
96
+ }
package/src/desktop.ts ADDED
@@ -0,0 +1,115 @@
1
+ import crypto from "node:crypto"
2
+
3
+ export interface PrivateDesktop {
4
+ name: string
5
+ close(): void
6
+ }
7
+
8
+ const DESKTOP_PREFIX = "CodexSandboxDesktop-"
9
+ // DESKTOP_ALL_ACCESS: specific desktop rights (0x1FF) | STANDARD_RIGHTS_REQUIRED (0xF0000)
10
+ const DESKTOP_ALL_ACCESS = 0x000f01ff
11
+ const TOKEN_QUERY = 0x0008
12
+ const TOKEN_LOGON_SID_CLASS = 28
13
+ let structSeq = 0
14
+
15
+ function wide(s: string): Buffer {
16
+ return Buffer.from(s + "\0", "utf16le")
17
+ }
18
+
19
+ // The logon SID (S-1-5-5-x-y) is not exposed by whoami or WindowsIdentity.Groups;
20
+ // read it straight from the process token via GetTokenInformation(TokenLogonSid).
21
+ function getLogonSid(koffi: any, advapi32: any, kernel32: any): string {
22
+ const OpenProcessToken = advapi32.func(
23
+ "int __stdcall OpenProcessToken(void *process, uint32_t access, _Out_ void **token)",
24
+ )
25
+ const GetTokenInformation = advapi32.func(
26
+ "int __stdcall GetTokenInformation(void *token, uint32_t infoClass, void *info, uint32_t len, _Out_ uint32_t *retLen)",
27
+ )
28
+ const GetCurrentProcess = kernel32.func("void * __stdcall GetCurrentProcess()")
29
+ const CloseHandle = kernel32.func("int __stdcall CloseHandle(void *handle)")
30
+ const SID_AND_ATTRIBUTES = koffi.struct({ Sid: "void *", Attributes: "uint32_t" })
31
+ const TOKEN_LOGON_SID = koffi.struct({ SidCount: "uint32_t", Sids: koffi.array(SID_AND_ATTRIBUTES, 1) })
32
+
33
+ const tokenOut: unknown[] = [null]
34
+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, tokenOut)) {
35
+ throw new Error("opencode-codex-sandbox: OpenProcessToken failed")
36
+ }
37
+ const token = tokenOut[0]
38
+ try {
39
+ const buf = Buffer.alloc(512)
40
+ const retLen: number[] = [0]
41
+ if (!GetTokenInformation(token, TOKEN_LOGON_SID_CLASS, buf, buf.length, retLen)) {
42
+ throw new Error("opencode-codex-sandbox: GetTokenInformation(TokenLogonSid) failed")
43
+ }
44
+ const info = koffi.decode(buf, TOKEN_LOGON_SID)
45
+ if (info.SidCount < 1) throw new Error("opencode-codex-sandbox: token has no logon SID")
46
+ const sidPtr = info.Sids[0].Sid
47
+ const head: number[] = koffi.decode(sidPtr, koffi.array("uint8_t", 8))
48
+ const subAuthorityCount = head[1]
49
+ const bytes: number[] = koffi.decode(sidPtr, koffi.array("uint8_t", 8 + 4 * subAuthorityCount))
50
+ let authority = 0
51
+ for (let i = 2; i < 8; i++) authority = authority * 256 + bytes[i]
52
+ const subs: string[] = []
53
+ for (let i = 0; i < subAuthorityCount; i++) {
54
+ const o = 8 + 4 * i
55
+ subs.push(String(((bytes[o] | (bytes[o + 1] << 8) | (bytes[o + 2] << 16) | (bytes[o + 3] << 24)) >>> 0)))
56
+ }
57
+ return `S-${head[0]}-${authority}-${subs.join("-")}`
58
+ } finally {
59
+ CloseHandle(token)
60
+ }
61
+ }
62
+
63
+ // Creates a private desktop and keeps its handle open for the plugin lifetime.
64
+ // The codex wrapper only OpenDesktopW's an existing desktop; the last closed
65
+ // handle destroys it, so the handle must outlive every sandboxed command.
66
+ export async function createPrivateDesktop(): Promise<PrivateDesktop> {
67
+ const koffi = (await import("koffi")).default
68
+ const user32 = koffi.load("user32.dll")
69
+ const advapi32 = koffi.load("advapi32.dll")
70
+ const kernel32 = koffi.load("kernel32.dll")
71
+
72
+ const saTypeName = `SBX_SECURITY_ATTRIBUTES_${++structSeq}`
73
+ const SECURITY_ATTRIBUTES = koffi.struct(saTypeName, {
74
+ nLength: "uint32_t",
75
+ lpSecurityDescriptor: "void *",
76
+ bInheritHandle: "int32_t",
77
+ })
78
+ const CreateDesktopW = user32.func(
79
+ `void * __stdcall CreateDesktopW(const void *name, const void *device, void *devmode, uint32_t flags, uint32_t access, ${saTypeName} *sa)`,
80
+ )
81
+ const CloseDesktop = user32.func("int __stdcall CloseDesktop(void *handle)")
82
+ const ConvertStringSecurityDescriptorToSecurityDescriptorW = advapi32.func(
83
+ "int __stdcall ConvertStringSecurityDescriptorToSecurityDescriptorW(const void *sddl, uint32_t revision, _Out_ void **sd, void *size)",
84
+ )
85
+ const LocalFree = kernel32.func("void * __stdcall LocalFree(void *ptr)")
86
+ const GetLastError = kernel32.func("uint32_t __stdcall GetLastError()")
87
+
88
+ const logonSid = getLogonSid(koffi, advapi32, kernel32)
89
+ // Grant the logon SID full desktop access: both the wrapper process and the
90
+ // restricted-token child carry this SID (mirrors codex grant_desktop_access).
91
+ const sddl = `D:(A;;0x${DESKTOP_ALL_ACCESS.toString(16)};;;${logonSid})`
92
+ const sdOut: unknown[] = [null]
93
+ const ok = ConvertStringSecurityDescriptorToSecurityDescriptorW(wide(sddl), 1, sdOut, null)
94
+ if (!ok) throw new Error(`opencode-codex-sandbox: ConvertStringSecurityDescriptorToSecurityDescriptorW failed: ${GetLastError()}`)
95
+ const sd = sdOut[0]
96
+
97
+ const name = DESKTOP_PREFIX + crypto.randomBytes(16).toString("hex")
98
+ const sa = { nLength: koffi.sizeof(SECURITY_ATTRIBUTES), lpSecurityDescriptor: sd, bInheritHandle: 0 }
99
+ const handle = CreateDesktopW(wide(name), null, null, 0, DESKTOP_ALL_ACCESS, sa)
100
+ LocalFree(sd)
101
+ if (!handle) {
102
+ throw new Error(`opencode-codex-sandbox: CreateDesktopW failed: ${GetLastError()}`)
103
+ }
104
+
105
+ let closed = false
106
+ return {
107
+ name,
108
+ close() {
109
+ if (!closed) {
110
+ closed = true
111
+ CloseDesktop(handle)
112
+ }
113
+ },
114
+ }
115
+ }
package/src/index.ts ADDED
@@ -0,0 +1,112 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+ import { Plugin } from "@opencode/plugin"
4
+ import { canonicalPath, resolvePolicy, type SandboxOptions } from "./policy.ts"
5
+ import { buildSeatbeltCommand } from "./seatbelt.ts"
6
+ import { buildBwrapCommand } from "./bwrap.ts"
7
+ import { buildWindowsLaunch, scrubTransportEnv } from "./windows.ts"
8
+ import { createPrivateDesktop, type PrivateDesktop } from "./desktop.ts"
9
+ import { defaultCacheDir, ensureBwrap, ensureCodexExe } from "./binaries.ts"
10
+ import { joinCommand, shellArgs, shellKind } from "./shell.ts"
11
+
12
+ interface Ready {
13
+ bwrapPath?: string
14
+ codexExe?: string
15
+ codexHome?: string
16
+ desktop?: PrivateDesktop
17
+ }
18
+
19
+ async function init(opts: SandboxOptions): Promise<Ready> {
20
+ const cacheDir = opts.cacheDir ?? defaultCacheDir()
21
+ if (process.platform === "win32") {
22
+ const codexExe = await ensureCodexExe({ version: opts.codexVersion, cacheDir, codexPath: opts.codexPath, launcherUrl: opts.launcherUrl })
23
+ const codexHome = opts.codexHome ?? path.join(cacheDir, "codex-home")
24
+ fs.mkdirSync(codexHome, { recursive: true })
25
+ const desktop = await createPrivateDesktop()
26
+ return { codexExe, codexHome, desktop }
27
+ }
28
+ if (process.platform === "linux") {
29
+ const bwrapPath = await ensureBwrap({ version: opts.codexVersion, cacheDir, bwrapPath: opts.bwrapPath })
30
+ return { bwrapPath }
31
+ }
32
+ return {}
33
+ }
34
+
35
+ export default Plugin.define({
36
+ id: "codex-sandbox",
37
+ async setup(ctx) {
38
+ const opts = (ctx.options ?? {}) as SandboxOptions
39
+ if (opts.enabled === false) return
40
+
41
+ let readyPromise: Promise<Ready> | undefined
42
+ const getReady = (): Promise<Ready> => {
43
+ if (!readyPromise) {
44
+ readyPromise = init(opts).catch((err) => {
45
+ readyPromise = undefined
46
+ throw err
47
+ })
48
+ }
49
+ return readyPromise
50
+ }
51
+
52
+ const registration = await ctx.shell.hook("create.before", async (inv) => {
53
+ const cwd = inv.cwd || ctx.location.directory
54
+ const policy = resolvePolicy(opts, cwd)
55
+ if (policy.mode === "danger-full-access") return
56
+
57
+ const ready = await getReady()
58
+ const kind = shellKind(inv.shell)
59
+ // The codex wrapper only recognizes backslash-separated cmd.exe paths for
60
+ // its /s /c script quoting; forward slashes silently break quoted commands.
61
+ const shellPath = process.platform === "win32" ? inv.shell.replace(/\//g, "\\") : inv.shell
62
+ const innerArgv = [shellPath, ...shellArgs(kind, inv.command)]
63
+
64
+ if (process.platform === "darwin") {
65
+ const cmd = buildSeatbeltCommand(policy, innerArgv)
66
+ inv.command = joinCommand(kind, [cmd.file, ...cmd.args])
67
+ Object.assign(inv.env, cmd.env)
68
+ return
69
+ }
70
+
71
+ if (process.platform === "linux") {
72
+ const cmd = buildBwrapCommand(ready.bwrapPath!, policy, innerArgv)
73
+ inv.command = joinCommand(kind, [cmd.file, ...cmd.args])
74
+ Object.assign(inv.env, cmd.env)
75
+ return
76
+ }
77
+
78
+ if (process.platform === "win32") {
79
+ const projectRoots: string[] = []
80
+ for (const root of [cwd, ...(opts.writableRoots ?? [])]) {
81
+ const canonical = canonicalPath(root)
82
+ if (!projectRoots.includes(canonical)) projectRoots.push(canonical)
83
+ }
84
+ scrubTransportEnv(inv.env)
85
+ const childEnv: Record<string, string> = {}
86
+ for (const [key, value] of Object.entries(inv.env)) {
87
+ if (value !== undefined) childEnv[key] = value
88
+ }
89
+ const launch = buildWindowsLaunch({
90
+ policy,
91
+ codexHome: ready.codexHome!,
92
+ cwd: canonicalPath(cwd),
93
+ workspaceRoots: projectRoots,
94
+ desktopName: ready.desktop!.name,
95
+ childEnv,
96
+ innerArgv,
97
+ })
98
+ inv.command = joinCommand(kind, [ready.codexExe!, ...launch.args])
99
+ Object.assign(inv.env, launch.env)
100
+ return
101
+ }
102
+
103
+ throw new Error(`opencode-codex-sandbox: unsupported platform ${process.platform}`)
104
+ })
105
+
106
+ return async () => {
107
+ await registration.dispose()
108
+ const ready = await readyPromise?.catch(() => undefined)
109
+ ready?.desktop?.close()
110
+ }
111
+ },
112
+ })
package/src/policy.ts ADDED
@@ -0,0 +1,82 @@
1
+ // Sandbox policy model derived from openai/codex permissions. Apache-2.0; see NOTICE.
2
+ import fs from "node:fs"
3
+ import path from "node:path"
4
+
5
+ export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access"
6
+
7
+ export interface SandboxOptions {
8
+ enabled?: boolean
9
+ policy?: SandboxMode
10
+ network?: boolean
11
+ writableRoots?: string[]
12
+ excludeTmp?: boolean
13
+ protectedNames?: string[]
14
+ codexVersion?: string
15
+ codexPath?: string
16
+ launcherUrl?: string
17
+ bwrapPath?: string
18
+ cacheDir?: string
19
+ codexHome?: string
20
+ }
21
+
22
+ export interface WritableRoot {
23
+ path: string
24
+ excluded: string[]
25
+ }
26
+
27
+ export interface ResolvedPolicy {
28
+ mode: SandboxMode
29
+ network: boolean
30
+ writableRoots: WritableRoot[]
31
+ protectedNames: string[]
32
+ }
33
+
34
+ export const DEFAULT_PROTECTED_NAMES = [".git", ".codex", ".agents", ".aws"]
35
+ export const DEFAULT_CODEX_VERSION = "0.169.0"
36
+
37
+ export function canonicalPath(p: string): string {
38
+ const abs = path.resolve(p)
39
+ try {
40
+ return fs.realpathSync(abs)
41
+ } catch {
42
+ return abs
43
+ }
44
+ }
45
+
46
+ function validateProtectedName(name: string): void {
47
+ if (!name || name.includes("/") || name.includes("\\") || name === "." || name === "..") {
48
+ throw new Error(`invalid protected path name: ${JSON.stringify(name)}`)
49
+ }
50
+ }
51
+
52
+ export function resolvePolicy(opts: SandboxOptions, cwd: string): ResolvedPolicy {
53
+ const mode = opts.policy ?? "workspace-write"
54
+ const network = opts.network ?? false
55
+ const protectedNames = opts.protectedNames ?? DEFAULT_PROTECTED_NAMES
56
+ for (const name of protectedNames) validateProtectedName(name)
57
+
58
+ if (mode === "danger-full-access" || mode === "read-only") {
59
+ return { mode, network: mode === "danger-full-access" ? true : network, writableRoots: [], protectedNames }
60
+ }
61
+
62
+ const roots: string[] = [canonicalPath(cwd)]
63
+ for (const extra of opts.writableRoots ?? []) roots.push(canonicalPath(extra))
64
+
65
+ if (!opts.excludeTmp && process.platform !== "win32") {
66
+ if (fs.existsSync("/tmp")) roots.push(canonicalPath("/tmp"))
67
+ const tmpdir = process.env.TMPDIR
68
+ if (tmpdir && fs.existsSync(tmpdir)) roots.push(canonicalPath(tmpdir))
69
+ }
70
+
71
+ const seen = new Set<string>()
72
+ const writableRoots: WritableRoot[] = []
73
+ for (const root of roots) {
74
+ if (seen.has(root)) continue
75
+ seen.add(root)
76
+ writableRoots.push({
77
+ path: root,
78
+ excluded: protectedNames.map((name) => path.join(root, name)),
79
+ })
80
+ }
81
+ return { mode, network, writableRoots, protectedNames }
82
+ }
package/src/sbpl.ts ADDED
@@ -0,0 +1,165 @@
1
+ // Seatbelt profile fragments copied from openai/codex (codex-rs/sandboxing/src/*.sbpl).
2
+
3
+ export const BASE_POLICY = `(version 1)
4
+
5
+ ; inspired by Chrome's sandbox policy:
6
+ ; https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/common.sb;l=273-319;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd
7
+ ; https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/renderer.sb;l=64;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd
8
+
9
+ ; start with closed-by-default
10
+ (deny default)
11
+
12
+ ; child processes inherit the policy of their parent
13
+ (allow process-exec)
14
+ (allow process-fork)
15
+ (allow signal (target same-sandbox))
16
+
17
+ ; process-info
18
+ (allow process-info* (target same-sandbox))
19
+
20
+ (allow file-write-data
21
+ (require-all
22
+ (path "/dev/null")
23
+ (vnode-type CHARACTER-DEVICE)))
24
+
25
+ ; sysctls permitted.
26
+ (allow sysctl-read
27
+ (sysctl-name "hw.activecpu")
28
+ (sysctl-name "hw.busfrequency_compat")
29
+ (sysctl-name "hw.byteorder")
30
+ (sysctl-name "hw.cacheconfig")
31
+ (sysctl-name "hw.cachelinesize_compat")
32
+ (sysctl-name "hw.cpufamily")
33
+ (sysctl-name "hw.cpufrequency_compat")
34
+ (sysctl-name "hw.cputype")
35
+ (sysctl-name "hw.l1dcachesize_compat")
36
+ (sysctl-name "hw.l1icachesize_compat")
37
+ (sysctl-name "hw.l2cachesize_compat")
38
+ (sysctl-name "hw.l3cachesize_compat")
39
+ (sysctl-name "hw.logicalcpu_max")
40
+ (sysctl-name "hw.machine")
41
+ (sysctl-name "hw.model")
42
+ (sysctl-name "hw.memsize")
43
+ (sysctl-name "hw.ncpu")
44
+ (sysctl-name "hw.nperflevels")
45
+ ; Chrome locks these CPU feature detection down a bit more tightly,
46
+ ; but mostly for fingerprinting concerns which isn't an issue for codex.
47
+ (sysctl-name-prefix "hw.optional.arm.")
48
+ (sysctl-name-prefix "hw.optional.armv8_")
49
+ (sysctl-name "hw.packages")
50
+ (sysctl-name "hw.pagesize_compat")
51
+ (sysctl-name "hw.pagesize")
52
+ (sysctl-name "hw.physicalcpu")
53
+ (sysctl-name "hw.physicalcpu_max")
54
+ (sysctl-name "hw.logicalcpu")
55
+ (sysctl-name "hw.cpufrequency")
56
+ (sysctl-name "hw.tbfrequency_compat")
57
+ (sysctl-name "hw.vectorunit")
58
+ (sysctl-name "machdep.cpu.brand_string")
59
+ (sysctl-name "kern.argmax")
60
+ (sysctl-name "kern.hostname")
61
+ (sysctl-name "kern.maxfilesperproc")
62
+ (sysctl-name "kern.maxproc")
63
+ (sysctl-name "kern.osproductversion")
64
+ (sysctl-name "kern.osrelease")
65
+ (sysctl-name "kern.ostype")
66
+ (sysctl-name "kern.osvariant_status")
67
+ (sysctl-name "kern.osversion")
68
+ (sysctl-name "kern.secure_kernel")
69
+ ; Python's ProcessPoolExecutor queries this through sysconf(_SC_SEM_NSEMS_MAX).
70
+ (sysctl-name "kern.sysv.semmns")
71
+ (sysctl-name "kern.usrstack64")
72
+ (sysctl-name "kern.version")
73
+ (sysctl-name "sysctl.proc_cputype")
74
+ (sysctl-name "vm.loadavg")
75
+ (sysctl-name-prefix "hw.perflevel")
76
+ (sysctl-name-prefix "kern.proc.pgrp.")
77
+ (sysctl-name-prefix "kern.proc.pid.")
78
+ (sysctl-name-prefix "net.routetable.")
79
+ )
80
+
81
+ ; Allow Java to read some CPU info. This is misclassified as a "write" because
82
+ ; userspace passes a memory buffer to the sysctl, but conceptually it is a read.
83
+ (allow sysctl-write
84
+ (sysctl-name "kern.grade_cputype"))
85
+
86
+ ; IOKit
87
+ (allow iokit-open
88
+ (iokit-registry-entry-class "RootDomainUserClient")
89
+ )
90
+
91
+ ; needed to look up user info, see https://crbug.com/792228
92
+ (allow mach-lookup
93
+ (global-name "com.apple.system.opendirectoryd.libinfo")
94
+ )
95
+
96
+ ; Needed for python multiprocessing on MacOS for the SemLock
97
+ (allow ipc-posix-sem)
98
+
99
+ ; Needed for PyTorch/libomp on macOS to register OpenMP runtimes.
100
+ (allow ipc-posix-shm-read-data
101
+ ipc-posix-shm-write-create
102
+ ipc-posix-shm-write-unlink
103
+ (ipc-posix-name-regex #"^/__KMP_REGISTERED_LIB_[0-9]+$"))
104
+
105
+ (allow mach-lookup
106
+ (global-name "com.apple.PowerManagement.control")
107
+ )
108
+
109
+ ; allow openpty()
110
+ (allow pseudo-tty)
111
+ (allow file-read* file-write* file-ioctl (literal "/dev/ptmx"))
112
+ (allow file-read* file-write*
113
+ (require-all
114
+ (regex #"^/dev/ttys[0-9]+")
115
+ (extension "com.apple.sandbox.pty")))
116
+ ; PTYs created before entering seatbelt may lack the extension; allow ioctl
117
+ ; on those slave ttys so interactive shells detect a TTY and remain functional.
118
+ (allow file-ioctl (regex #"^/dev/ttys[0-9]+"))
119
+ `
120
+
121
+ export const PREFERENCES_POLICY = `; Preferences IPC can expose data outside the filesystem read roots.
122
+ ; Include this policy only when filesystem reads are unrestricted.
123
+ (allow ipc-posix-shm-read* (ipc-posix-name-prefix "apple.cfprefs."))
124
+ (allow mach-lookup
125
+ (global-name "com.apple.cfprefsd.daemon")
126
+ (global-name "com.apple.cfprefsd.agent")
127
+ (local-name "com.apple.cfprefsd.agent"))
128
+ (allow user-preference-read)
129
+ `
130
+
131
+ export const NETWORK_POLICY = `; when network access is enabled, these policies are added after those in seatbelt_base_policy.sbpl
132
+ ; proxy-specific allow rules are injected by codex-core based on environment.
133
+ ; Ref https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/network.sb;drc=f8f264d5e4e7509c913f4c60c2639d15905a07e4
134
+
135
+ ; allow only safe AF_SYSTEM sockets used for local platform services.
136
+ (allow system-socket
137
+ (require-all
138
+ (socket-domain AF_SYSTEM)
139
+ (socket-protocol 2)
140
+ )
141
+ )
142
+
143
+ (allow mach-lookup
144
+ ; Used by platform helpers that resolve user directory locations.
145
+ (global-name "com.apple.bsd.dirhelper")
146
+ (global-name "com.apple.system.opendirectoryd.membership")
147
+
148
+ ; Communicate with the security server for TLS certificate information.
149
+ (global-name "com.apple.SecurityServer")
150
+ (global-name "com.apple.networkd")
151
+ (global-name "com.apple.ocspd")
152
+ (global-name "com.apple.trustd.agent")
153
+
154
+ ; Read network configuration.
155
+ (global-name "com.apple.SystemConfiguration.DNSConfiguration")
156
+ (global-name "com.apple.SystemConfiguration.configd")
157
+ )
158
+
159
+ (allow sysctl-read
160
+ (sysctl-name-regex #"^net.routetable")
161
+ )
162
+ `
163
+
164
+ export const TLS_TRUST_POLICY = `(allow mach-lookup (global-name "com.apple.TrustEvaluationAgent"))
165
+ `
@@ -0,0 +1,74 @@
1
+ // Ported from openai/codex (codex-rs/sandboxing/src/seatbelt.rs). Apache-2.0; see NOTICE.
2
+ import fs from "node:fs"
3
+ import type { ResolvedPolicy } from "./policy.ts"
4
+ import { BASE_POLICY, PREFERENCES_POLICY, NETWORK_POLICY, TLS_TRUST_POLICY } from "./sbpl.ts"
5
+
6
+ export const SANDBOX_EXEC = "/usr/bin/sandbox-exec"
7
+
8
+ export interface SeatbeltCommand {
9
+ file: string
10
+ args: string[]
11
+ env: Record<string, string>
12
+ }
13
+
14
+ function writeRuleForRoot(index: number, excludedKeys: string[]): string {
15
+ const root = `(subpath (param "WRITABLE_ROOT_${index}"))`
16
+ if (excludedKeys.length === 0) return root
17
+ const parts = [root]
18
+ for (const key of excludedKeys) {
19
+ parts.push(`(require-not (literal (param "${key}")))`)
20
+ parts.push(`(require-not (subpath (param "${key}")))`)
21
+ }
22
+ return `(require-all ${parts.join(" ")})`
23
+ }
24
+
25
+ export function buildSeatbeltCommand(policy: ResolvedPolicy, innerArgv: string[]): SeatbeltCommand {
26
+ const params: Array<[string, string]> = []
27
+ const sections: string[] = [BASE_POLICY, "; allow read-only file operations\n(allow file-read*)"]
28
+
29
+ if (policy.writableRoots.length > 0) {
30
+ const rules: string[] = []
31
+ const anchorDenies: string[] = []
32
+ policy.writableRoots.forEach((root, i) => {
33
+ params.push([`WRITABLE_ROOT_${i}`, root.path])
34
+ const excludedKeys: string[] = []
35
+ root.excluded.forEach((p, j) => {
36
+ const key = `WRITABLE_ROOT_${i}_EXCLUDED_${j}`
37
+ params.push([key, p])
38
+ excludedKeys.push(key)
39
+ // Also bind the resolved target of a symlinked carveout so it cannot
40
+ // be written through the symlink destination.
41
+ try {
42
+ const resolved = fs.realpathSync(p)
43
+ if (resolved !== p) {
44
+ const resolvedKey = `${key}_RESOLVED`
45
+ params.push([resolvedKey, resolved])
46
+ excludedKeys.push(resolvedKey)
47
+ }
48
+ } catch {
49
+ // missing carveout: logical path binding is enough
50
+ }
51
+ })
52
+ rules.push(writeRuleForRoot(i, excludedKeys))
53
+ anchorDenies.push(
54
+ `(deny file-write-unlink (require-all (literal (param "WRITABLE_ROOT_${i}")) (vnode-type DIRECTORY)))`,
55
+ )
56
+ })
57
+ sections.push(`(allow file-write*\n ${rules.join("\n ")})`)
58
+ sections.push(anchorDenies.join("\n"))
59
+ }
60
+
61
+ if (policy.network) {
62
+ sections.push(`(allow network-outbound)\n(allow network-inbound)\n${NETWORK_POLICY}${TLS_TRUST_POLICY}`)
63
+ }
64
+
65
+ sections.push(PREFERENCES_POLICY)
66
+ sections.push('(deny mach-lookup (xpc-service-name-prefix ""))')
67
+ sections.push("(deny system-fcntl (fcntl-command 80 110))")
68
+
69
+ const profile = sections.join("\n")
70
+ const args = ["-p", profile, ...params.map(([k, v]) => `-D${k}=${v}`), "--", ...innerArgv]
71
+ const env: Record<string, string> = { CODEX_SANDBOX: "seatbelt" }
72
+ if (!policy.network) env.CODEX_SANDBOX_NETWORK_DISABLED = "1"
73
+ return { file: SANDBOX_EXEC, args, env }
74
+ }