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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 OpenAI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,50 @@
1
+ opencode-codex-sandbox
2
+
3
+ This product includes software derived from the following projects.
4
+
5
+ --------------------------------------------------------------------------------
6
+ OpenAI Codex — https://github.com/openai/codex
7
+ Copyright 2025 OpenAI
8
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
9
+
10
+ The Windows sandbox crate closure under rust/vendor/ is copied from OpenAI
11
+ Codex (regenerated by scripts/sync-rust.ts); its Cargo manifests are rewritten
12
+ to form a standalone cargo workspace. The TypeScript modules under src/ that
13
+ implement the macOS Seatbelt profile and the Linux bubblewrap invocation are
14
+ ports of the corresponding Codex sources. Upstream's own notices about Ratatui
15
+ apply to its terminal UI, which is not included here.
16
+
17
+ --------------------------------------------------------------------------------
18
+ WezTerm — https://github.com/wezterm/wezterm (MIT License)
19
+ Copyright (c) 2018-Present Wez Furlong
20
+
21
+ The ConPTY helpers under rust/vendor/codex-utils-pty/src/win/ are copied from
22
+ WezTerm.
23
+
24
+ --------------------------------------------------------------------------------
25
+ path-absolutize — https://github.com/magiclen/path-absolutize (MIT License)
26
+ Copyright (c) 2018 magiclen.org (Ron Li)
27
+
28
+ rust/vendor/codex-utils-absolute-path/src/absolutize.rs is adapted from
29
+ path-absolutize 3.1.1.
30
+
31
+ --------------------------------------------------------------------------------
32
+ MIT License (applies to the WezTerm and path-absolutize portions above)
33
+
34
+ Permission is hereby granted, free of charge, to any person obtaining a copy
35
+ of this software and associated documentation files (the "Software"), to deal
36
+ in the Software without restriction, including without limitation the rights
37
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
38
+ copies of the Software, and to permit persons to whom the Software is
39
+ furnished to do so, subject to the following conditions:
40
+
41
+ The above copyright notice and this permission notice shall be included in all
42
+ copies or substantial portions of the Software.
43
+
44
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
45
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
46
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
47
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
48
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
49
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
50
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # opencode-codex-sandbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把 [OpenAI Codex CLI](https://github.com/openai/codex) 的操作系统级沙盒剥离成 [opencode](https://opencode.ai) V2 插件:opencode 里每条 shell 命令默认在沙盒中执行——全盘可读、仅工作区可写、默认禁网。
4
+
5
+ ## 平台实现
6
+
7
+ | 平台 | 机制 | 来源 |
8
+ |---|---|---|
9
+ | macOS | Seatbelt:JS 移植 Codex 的 profile 生成,`/usr/bin/sandbox-exec -p <profile> -D WRITABLE_ROOT_n=… -- <shell> -c <cmd>` | `codex-rs/sandboxing/src/seatbelt.rs` + `*.sbpl` |
10
+ | Linux | bubblewrap:`--ro-bind / /` + 可写根 `--bind` + `.git` 等只读回填 + `--unshare-net` 禁网;静态 musl bwrap 自动下载 | `codex-rs/linux-sandbox/src/bwrap.rs` |
11
+ | Windows | Codex 官方 `codex.exe --run-as-windows-sandbox`(restricted token + WRITE_RESTRICTED + 工作区 capability SID ACE),**无需管理员、无需 setup**;插件通过 FFI 创建并持有私有桌面,payload 走 `CODEX_SANDBOX_LAUNCH_*` 环境分块传输 | `codex-rs/windows-sandbox-rs/` |
12
+
13
+ 接入点:`ctx.shell.hook("create.before")` 原地改写命令与环境变量,保留 opencode 内置 shell 工具的权限询问、后台执行、输出截断等全部行为。`danger-full-access` 策略下不包装,直接透传。
14
+
15
+ ## 安装
16
+
17
+ 需要 opencode V2(`@opencode/plugin` 2.x)与 Node ≥ 22.6(或 Bun)。
18
+
19
+ 项目级:把本仓库放到 `.opencode/plugins/codex-sandbox/`(目录内含 `package.json` 与 `src/`),并在该目录执行 `npm install`(Windows 需要 koffi 的原生预编译)。
20
+
21
+ 或在 `opencode.json` 中引用:
22
+
23
+ ```jsonc
24
+ {
25
+ "plugins": [
26
+ { "package": "opencode-codex-sandbox", "options": { "policy": "workspace-write" } }
27
+ ]
28
+ }
29
+ ```
30
+
31
+ 本地路径形式:
32
+
33
+ ```jsonc
34
+ {
35
+ "plugins": [
36
+ { "package": "./.opencode/plugins/codex-sandbox", "options": { "network": false } }
37
+ ]
38
+ }
39
+ ```
40
+
41
+ ## 配置项(options)
42
+
43
+ | 选项 | 默认 | 说明 |
44
+ |---|---|---|
45
+ | `enabled` | `true` | 关闭后命令不套沙盒 |
46
+ | `policy` | `"workspace-write"` | `read-only` / `workspace-write` / `danger-full-access` |
47
+ | `network` | `false` | 允许沙盒内联网(Windows 见下方限制) |
48
+ | `writableRoots` | `[]` | 额外可写目录;工作区目录始终可写 |
49
+ | `excludeTmp` | `false` | 不把 `/tmp`、`$TMPDIR` 列为可写(仅 POSIX) |
50
+ | `protectedNames` | `[".git",".codex",".agents",".aws"]` | 可写根下保持只读的子目录名 |
51
+ | `codexVersion` | `"0.169.0"` | Windows codex.exe / Linux bwrap 的下载版本(release tag `rust-v<ver>`) |
52
+ | `codexPath` / `bwrapPath` | 自动 | 手动指定二进制,跳过下载 |
53
+ | `launcherUrl` | 自动 | Windows launcher 下载模板,`{version}`/`{arch}` 占位;也可用环境变量 `CODEX_SANDBOX_LAUNCHER_URL`。默认取 `package.json` 的 GitHub `repository`(`/releases/latest/download/codex-sandbox-launcher-win32-{arch}.exe`),未声明则不下载 |
54
+ | `cacheDir` | `~/.cache/opencode-codex-sandbox` | 二进制与状态缓存目录 |
55
+ | `codexHome` | `<cacheDir>/codex-home` | Windows 沙盒状态目录(capability SID 等) |
56
+
57
+ ## 二进制获取
58
+
59
+ Windows 按以下顺序解析沙盒可执行文件:
60
+
61
+ 1. `codexPath` 选项手动指定;
62
+ 2. **独立 launcher**(约 3.5MB,与 `codex.exe --run-as-windows-sandbox` 完全同协议):
63
+ - 本机构建产物:`rust/target/{release,debug}/codex-sandbox-launcher.exe`,或 `CODEX_SANDBOX_LAUNCHER` 环境变量指定;
64
+ - 否则按 `launcherUrl` / `CODEX_SANDBOX_LAUNCHER_URL` / `package.json` 的 GitHub `repository` 运行时下载并缓存到 `cacheDir`(见下方「Rust 独立 launcher」);
65
+ 3. **本机已安装的 codex**:npm 全局包(`npm root -g` 下 `@openai/codex` 的平台子包,含嵌套/提升/旧版 vendor 三种布局)、`~/.local/bin/codex.exe`、`%LOCALAPPDATA%\Programs\codex\`、PATH 中的 `codex.exe`。要求版本 **≥ 0.169.0**(该版本起才有 `cmd.exe /s /c` 引号处理,旧版会破坏带引号路径的命令),并探测 `--run-as-windows-sandbox --launch-payload-env` 协议兼容性,不满足则跳过;
66
+ 4. 缓存目录中已下载的 codex.exe;
67
+ 5. 首次下载:npm registry 的 `@openai/codex@<ver>-win32-<arch>` tarball,提取 `vendor/<triple>/bin/codex.exe`(**约 365MB**,0.169.0 实测)。
68
+
69
+ Linux:GitHub release 资产 `bwrap-<arch>-unknown-linux-musl.tar.gz`(静态链接,非 setuid,依赖 unprivileged user namespaces,体积小)。
70
+ macOS:无二进制依赖。
71
+
72
+ ## Rust 独立 launcher(体积优化)
73
+
74
+ 完整 `codex.exe` 约 365MB,但 Windows 沙盒实际只用到其中 `windows-sandbox-rs` crate。`rust/` 把该 crate 及其依赖闭包剥离成独立 cargo workspace,编出仅数 MB 的 `codex-sandbox-launcher.exe`,与 `codex.exe --run-as-windows-sandbox` 同协议、可直接替换。
75
+
76
+ - **零保真损失**:沙盒 crate 源码逐字 vendor(`rust/vendor/codex-windows-sandbox` 等),不改一行;仅 `codex-protocol` 用锚点片段拼出最小 shim(permissions/config_types 逐字,models/protocol/openai_models 只取沙盒相关类型),`otel`/`http-client`/`runfiles` 用 no-op stub(独立 launcher 不上报遥测、不走 elevated setup)。
77
+ - **`rust/vendor/` 是生成物(已 `.gitignore`)**:由 `scripts/sync-rust.ts` 从上游重建,不进仓库。本地构建前必须先跑一次 sync;CI 每次构建都会重新生成。
78
+ - **构建**:`node scripts/sync-rust.ts [codex-rs-dir]` 从上游生成 `rust/vendor/`(默认读本地 `codex/codex-rs`,该克隆已 gitignore、需自行 clone;CI 用 sparse-checkout 自带),再 `cd rust && cargo build --release -p codex-sandbox-launcher`。产物在 `rust/target/release/codex-sandbox-launcher.exe`,插件自动优先使用。
79
+ - **运行时下载**:`ensureLauncher` 按 `launcherUrl` / `CODEX_SANDBOX_LAUNCHER_URL` / `package.json` 的 GitHub `repository` 拼出 `.../releases/latest/download/codex-sandbox-launcher-win32-{arch}.exe`,首次运行下到 `cacheDir` 并做协议探测;任何一步失败都静默回退到 codex.exe。`.github/workflows/release-launcher.yml`(打 `launcher-v*` tag 或手动)构建 x64/arm64 两个 .exe 并附到 GitHub release。
80
+ - **测试**:`cargo test -p codex-protocol --lib`(58)+ `cargo test -p codex-windows-sandbox --lib -- --skip unified_exec::tests::`(263)。`unified_exec::tests::*` 是需要安装 elevated setup 服务的端到端 exec 测试,独立 launcher 不带该服务,故跳过;该路径由 `npm run live:windows` 实测覆盖。
81
+ - **CI 跟进上游**:`.github/workflows/sync-upstream.yml` 每周(或手动)拉取最新 `rust-v*` tag,sparse-checkout crate 闭包 → 重生成 → Windows 构建+测试 → 开 PR;patch 升级可自动合并,minor/major 留人工 review。`rust/UPSTREAM_VERSION` 记录上次同步版本。
82
+
83
+ ## 卸载
84
+
85
+ opencode 没有插件卸载钩子(setup 返回的 cleanup 只在服务关闭/插件重载时运行,用于释放桌面句柄,不会删缓存)。完整卸载步骤:
86
+
87
+ 1. 从 `opencode.json` 的 `plugins` 中移除本插件;
88
+ 2. 运行 `npm run clean`(即 `node scripts/clean.ts [cacheDir]`),删除下载的二进制与 codex-home 状态;本机已安装的 codex 不受影响;
89
+ 3. 可选:Windows 沙盒曾在工作区目录写入 capability SID 的持久 ACE,如需清理,删除这些目录 ACL 中未知的 `S-1-5-21-*` 账户条目。
90
+
91
+ ## 安全边界与已知限制
92
+
93
+ - **Windows 禁网是环境级的**(`SBX_NONET_ACTIVE=1`、代理指向 `127.0.0.1:9`、npm/pip/cargo offline 标记、ssh 桩),不是内核强制:绕过代理的原始 socket 仍可联网。内核级禁网(WFP 按沙盒账户 SID)只有 Codex 的 elevated 档才有,本插件不实现。macOS/Linux 的禁网是内核级的(Seatbelt deny-default / 空 network namespace)。
94
+ - **Windows 会在工作区根写入持久 ACE**(授予随机 capability SID 写权限),卸载插件后如需清理,可删除目录 ACL 中对应 `S-1-5-21-…` 未知账户条目,或参考 Codex 的卸载逻辑。
95
+ - Linux 纯 bwrap 不套 seccomp:AF_INET 在空 netns 中本就不通,但路径型 AF_UNIX socket(docker.sock、dbus 等)经全盘只读绑定仍可达;WSL2 已遮蔽 `/run/WSL` interop 逃逸口,AF_VSOCK 残余风险与 Codex 经典版一致。WSL1 无 user namespace,直接拒绝。
96
+ - macOS 移植为最小可用版:保留 base/read/write/network/preferences 段与锚点 deny、fcntl deny;未移植 deny-read glob、代理网络、seatbelt daemon 保护(全盘读模型下不需要)。
97
+ - 沙盒内命令失败(`operation not permitted` / `permission denied` / `read-only file system` 等)通常意味着策略限制,可调整 `writableRoots` 或临时设 `policy: "danger-full-access"`。
98
+
99
+ ## 开发
100
+
101
+ ```sh
102
+ npm install
103
+ npm test # 34 个单元测试(node --test,Node 原生 TS 剥离)
104
+ npm run typecheck
105
+ npm run live:windows # Windows 实测:优先用本机构建的 launcher,否则 codex.exe,验证读写/禁网标记
106
+ ```
107
+
108
+ ## 许可证与归属
109
+
110
+ 本项目以 **Apache-2.0** 发布(见 [LICENSE](./LICENSE))。它包含并移植自 [OpenAI Codex](https://github.com/openai/codex)(Apache-2.0)的代码,并随附 WezTerm、path-absolutize 的 MIT 代码;完整归属声明与全文见 [NOTICE](./NOTICE)。
111
+
112
+ - `rust/vendor/` 由 `scripts/sync-rust.ts` 从上游 Codex 逐字生成(crate 闭包),仅重写 Cargo manifest 以组成独立 workspace;
113
+ - `src/` 中的 macOS Seatbelt profile 与 Linux bubblewrap 调用为 Codex 源码的 TypeScript 移植。
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "opencode-codex-sandbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Codex-style OS sandbox for opencode shell commands: Seatbelt on macOS, bubblewrap on Linux, restricted-token sandbox on Windows",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/NetheritePickaxe/opencode-codex-sandbox.git"
9
+ },
10
+ "type": "module",
11
+ "main": "src/index.ts",
12
+ "exports": {
13
+ ".": "./src/index.ts"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "README.md",
18
+ "LICENSE",
19
+ "NOTICE"
20
+ ],
21
+ "scripts": {
22
+ "test": "node --test test/*.test.ts",
23
+ "typecheck": "tsc --noEmit",
24
+ "live:windows": "node scripts/live-windows.ts",
25
+ "clean": "node scripts/clean.ts"
26
+ },
27
+ "dependencies": {
28
+ "koffi": "^2.9.0"
29
+ },
30
+ "devDependencies": {
31
+ "@opencode/plugin": "2.3.0",
32
+ "@types/node": "^24.0.0",
33
+ "typescript": "^5.6.0"
34
+ },
35
+ "engines": {
36
+ "node": ">=22.6.0"
37
+ },
38
+ "allowScripts": {
39
+ "koffi@2.16.4": true
40
+ }
41
+ }
@@ -0,0 +1,251 @@
1
+ import fs from "node:fs"
2
+ import os from "node:os"
3
+ import path from "node:path"
4
+ import { spawnSync } from "node:child_process"
5
+ import { DEFAULT_CODEX_VERSION } from "./policy.ts"
6
+ import { extractTarGz } from "./tar.ts"
7
+
8
+ export function defaultCacheDir(): string {
9
+ return path.join(os.homedir(), ".cache", "opencode-codex-sandbox")
10
+ }
11
+
12
+ const PACKAGE_ROOT = path.resolve(import.meta.dirname, "..")
13
+
14
+ // The standalone Rust launcher (rust/launcher) is a drop-in for
15
+ // `codex.exe --run-as-windows-sandbox`: same args, same env-chunk transport,
16
+ // but a few MB instead of the full ~365MB codex binary. Prefer a locally built
17
+ // artifact (or an explicit override) before falling back to a full codex.exe.
18
+ export function localLauncherCandidates(env: NodeJS.ProcessEnv = process.env): string[] {
19
+ if (process.platform !== "win32") return []
20
+ const candidates: string[] = []
21
+ if (env.CODEX_SANDBOX_LAUNCHER) candidates.push(env.CODEX_SANDBOX_LAUNCHER)
22
+ for (const profile of ["release", "debug"]) {
23
+ candidates.push(path.join(PACKAGE_ROOT, "rust", "target", profile, "codex-sandbox-launcher.exe"))
24
+ }
25
+ return candidates
26
+ }
27
+
28
+ export function findLocalLauncher(): string | undefined {
29
+ for (const candidate of localLauncherCandidates()) {
30
+ if (fs.existsSync(candidate) && probeCodexWrapper(candidate)) return candidate
31
+ }
32
+ return undefined
33
+ }
34
+
35
+ export const LAUNCHER_URL_ENV = "CODEX_SANDBOX_LAUNCHER_URL"
36
+
37
+ // Expands a launcher download template. `{version}` and `{arch}` are replaced;
38
+ // the URL should point at the raw .exe (e.g. a GitHub release asset).
39
+ export function fillLauncherUrl(template: string, version: string, arch: string): string {
40
+ return template.split("{version}").join(version).split("{arch}").join(arch)
41
+ }
42
+
43
+ // Defaults the launcher download to this package's GitHub "latest" release once
44
+ // package.json declares a GitHub `repository`; otherwise download stays off.
45
+ // Data-driven so no repository slug is hardcoded.
46
+ function defaultLauncherUrl(): string | undefined {
47
+ try {
48
+ const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf8"))
49
+ const repo = typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url
50
+ if (typeof repo !== "string") return undefined
51
+ const match = /github\.com[/:]([^/]+)\/([^/.]+)/.exec(repo)
52
+ if (!match) return undefined
53
+ return `https://github.com/${match[1]}/${match[2]}/releases/latest/download/codex-sandbox-launcher-win32-{arch}.exe`
54
+ } catch {
55
+ return undefined
56
+ }
57
+ }
58
+
59
+ // Downloads a prebuilt launcher when a source is configured (option, env, or
60
+ // package repository), caching it per version+arch. Any failure (missing URL,
61
+ // network, bad probe) returns undefined so the caller falls back to codex.exe.
62
+ export async function ensureLauncher(opts: {
63
+ version?: string
64
+ cacheDir?: string
65
+ launcherUrl?: string
66
+ }): Promise<string | undefined> {
67
+ if (process.platform !== "win32") return undefined
68
+ const template = opts.launcherUrl ?? process.env[LAUNCHER_URL_ENV] ?? defaultLauncherUrl()
69
+ if (!template) return undefined
70
+ const { arch } = windowsArch()
71
+ const version = opts.version ?? DEFAULT_CODEX_VERSION
72
+ const exe = path.join(opts.cacheDir ?? defaultCacheDir(), `launcher-${version}-win32-${arch}`, "codex-sandbox-launcher.exe")
73
+ if (fs.existsSync(exe) && probeCodexWrapper(exe)) return exe
74
+ try {
75
+ const url = fillLauncherUrl(template, version, arch)
76
+ const target = await cached(exe, async () => {
77
+ process.stderr.write(`[codex-sandbox] downloading sandbox launcher (${version}) ...\n`)
78
+ return downloadBuffer(url)
79
+ })
80
+ if (probeCodexWrapper(target)) return target
81
+ process.stderr.write(`[codex-sandbox] downloaded launcher failed the wrapper probe; discarding\n`)
82
+ fs.rmSync(path.dirname(target), { recursive: true, force: true })
83
+ return undefined
84
+ } catch (err) {
85
+ process.stderr.write(`[codex-sandbox] launcher download failed (${(err as Error).message}); falling back\n`)
86
+ return undefined
87
+ }
88
+ }
89
+
90
+ function windowsArch(): { arch: string; triple: string } {
91
+ return process.arch === "arm64"
92
+ ? { arch: "arm64", triple: "aarch64-pc-windows-msvc" }
93
+ : { arch: "x64", triple: "x86_64-pc-windows-msvc" }
94
+ }
95
+
96
+ export function localCodexCandidates(npmGlobalRoot: string | undefined, env: NodeJS.ProcessEnv = process.env): string[] {
97
+ if (process.platform !== "win32") return []
98
+ const { arch, triple } = windowsArch()
99
+ const vendorRel = path.join("vendor", triple, "bin", "codex.exe")
100
+ const candidates: string[] = []
101
+ if (npmGlobalRoot) {
102
+ candidates.push(
103
+ path.join(npmGlobalRoot, "@openai", "codex", "node_modules", `@openai/codex-win32-${arch}`, vendorRel),
104
+ path.join(npmGlobalRoot, `@openai/codex-win32-${arch}`, vendorRel),
105
+ path.join(npmGlobalRoot, "@openai", "codex", vendorRel),
106
+ )
107
+ }
108
+ candidates.push(path.join(os.homedir(), ".local", "bin", "codex.exe"))
109
+ if (env.LOCALAPPDATA) candidates.push(path.join(env.LOCALAPPDATA, "Programs", "codex", "codex.exe"))
110
+ for (const dir of (env.PATH ?? "").split(path.delimiter)) {
111
+ if (dir) candidates.push(path.join(dir, "codex.exe"))
112
+ }
113
+ return candidates
114
+ }
115
+
116
+ function npmGlobalRoot(): string | undefined {
117
+ try {
118
+ const result = spawnSync("npm.cmd", ["root", "-g"], { encoding: "utf8", timeout: 20_000, windowsHide: true, shell: true })
119
+ const line = (result.stdout ?? "").trim().split(/\r?\n/).pop()
120
+ return line && path.isAbsolute(line) ? line : undefined
121
+ } catch {
122
+ return undefined
123
+ }
124
+ }
125
+
126
+ // The wrapper must understand both --run-as-windows-sandbox and the env
127
+ // transport; older codex builds lack them, so probe before trusting a local exe.
128
+ export function probeCodexWrapper(exe: string): boolean {
129
+ const result = spawnSync(exe, ["--run-as-windows-sandbox", "--launch-payload-env"], {
130
+ encoding: "utf8",
131
+ timeout: 20_000,
132
+ windowsHide: true,
133
+ })
134
+ const stderr = result.stderr ?? ""
135
+ return stderr.includes("chunk count") && !stderr.includes("unexpected")
136
+ }
137
+
138
+ // 0.169.0 added the cmd.exe /s /c script quoting; older builds CRT-escape the
139
+ // script's inner quotes, which breaks any command containing quoted paths.
140
+ export const MIN_LOCAL_CODEX_VERSION = "0.169.0"
141
+
142
+ export function versionAtLeast(version: string, minimum: string): boolean {
143
+ const parse = (v: string) => v.trim().split(".").map((part) => Number.parseInt(part, 10))
144
+ const a = parse(version)
145
+ const b = parse(minimum)
146
+ if (a.some(Number.isNaN) || b.some(Number.isNaN)) return false
147
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
148
+ const diff = (a[i] ?? 0) - (b[i] ?? 0)
149
+ if (diff !== 0) return diff > 0
150
+ }
151
+ return true
152
+ }
153
+
154
+ export function codexExeVersion(exe: string): string | undefined {
155
+ const result = spawnSync(exe, ["--version"], { encoding: "utf8", timeout: 20_000, windowsHide: true })
156
+ const match = /(\d+\.\d+\.\d+)/.exec(result.stdout ?? "")
157
+ return match?.[1]
158
+ }
159
+
160
+ export function findLocalCodex(): string | undefined {
161
+ for (const candidate of localCodexCandidates(npmGlobalRoot())) {
162
+ if (!fs.existsSync(candidate)) continue
163
+ const version = codexExeVersion(candidate)
164
+ if (!version || !versionAtLeast(version, MIN_LOCAL_CODEX_VERSION)) {
165
+ process.stderr.write(`[codex-sandbox] skipping local codex ${version ?? "(unknown version)"}: need >= ${MIN_LOCAL_CODEX_VERSION}\n`)
166
+ continue
167
+ }
168
+ if (probeCodexWrapper(candidate)) return candidate
169
+ }
170
+ return undefined
171
+ }
172
+
173
+ const inflight = new Map<string, Promise<string>>()
174
+
175
+ async function downloadBuffer(url: string): Promise<Buffer> {
176
+ const res = await fetch(url, { redirect: "follow" })
177
+ if (!res.ok) throw new Error(`opencode-codex-sandbox: download failed (${res.status} ${res.statusText}): ${url}`)
178
+ return Buffer.from(await res.arrayBuffer())
179
+ }
180
+
181
+ function cached(target: string, produce: () => Promise<Buffer>): Promise<string> {
182
+ if (fs.existsSync(target)) return Promise.resolve(target)
183
+ const existing = inflight.get(target)
184
+ if (existing) return existing
185
+ const task = (async () => {
186
+ const data = await produce()
187
+ fs.mkdirSync(path.dirname(target), { recursive: true })
188
+ const tmp = `${target}.tmp-${process.pid}`
189
+ fs.writeFileSync(tmp, data)
190
+ fs.renameSync(tmp, target)
191
+ return target
192
+ })().finally(() => inflight.delete(target))
193
+ inflight.set(target, task)
194
+ return task
195
+ }
196
+
197
+ export async function ensureCodexExe(opts: {
198
+ version?: string
199
+ cacheDir?: string
200
+ codexPath?: string
201
+ launcherUrl?: string
202
+ }): Promise<string> {
203
+ if (opts.codexPath) return opts.codexPath
204
+ const launcher = findLocalLauncher()
205
+ if (launcher) {
206
+ process.stderr.write(`[codex-sandbox] using local sandbox launcher: ${launcher}\n`)
207
+ return launcher
208
+ }
209
+ const downloaded = await ensureLauncher({ version: opts.version, cacheDir: opts.cacheDir, launcherUrl: opts.launcherUrl })
210
+ if (downloaded) {
211
+ process.stderr.write(`[codex-sandbox] using downloaded sandbox launcher: ${downloaded}\n`)
212
+ return downloaded
213
+ }
214
+ const local = findLocalCodex()
215
+ if (local) {
216
+ process.stderr.write(`[codex-sandbox] using local codex: ${local}\n`)
217
+ return local
218
+ }
219
+ const version = opts.version ?? DEFAULT_CODEX_VERSION
220
+ const { arch, triple } = windowsArch()
221
+ const exe = path.join(opts.cacheDir ?? defaultCacheDir(), `codex-${version}-win32-${arch}`, "codex.exe")
222
+ return cached(exe, async () => {
223
+ // Platform packages are published as @openai/codex@<ver>-win32-<arch>.
224
+ const url = `https://registry.npmjs.org/@openai/codex/-/codex-${version}-win32-${arch}.tgz`
225
+ process.stderr.write(`[codex-sandbox] downloading codex.exe (${version}) ...\n`)
226
+ const entries = extractTarGz(await downloadBuffer(url))
227
+ const entry = entries.find((e) => e.name === `package/vendor/${triple}/bin/codex.exe`)
228
+ if (!entry) throw new Error(`opencode-codex-sandbox: codex.exe not found in ${url}`)
229
+ return entry.data
230
+ })
231
+ }
232
+
233
+ export async function ensureBwrap(opts: {
234
+ version?: string
235
+ cacheDir?: string
236
+ bwrapPath?: string
237
+ }): Promise<string> {
238
+ if (opts.bwrapPath) return opts.bwrapPath
239
+ const version = opts.version ?? DEFAULT_CODEX_VERSION
240
+ const arch = process.arch === "arm64" ? "aarch64" : "x86_64"
241
+ const bin = path.join(opts.cacheDir ?? defaultCacheDir(), `bwrap-${version}-${arch}`, "bwrap")
242
+ const result = await cached(bin, async () => {
243
+ const url = `https://github.com/openai/codex/releases/download/rust-v${version}/bwrap-${arch}-unknown-linux-musl.tar.gz`
244
+ const entries = extractTarGz(await downloadBuffer(url))
245
+ const entry = entries.find((e) => e.type === "0" && path.posix.basename(e.name) === "bwrap")
246
+ if (!entry) throw new Error(`opencode-codex-sandbox: bwrap binary not found in ${url}`)
247
+ return entry.data
248
+ })
249
+ fs.chmodSync(result, 0o755)
250
+ return result
251
+ }