@jbkjr/relay 0.0.0-stage → 1.2.1

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.
Files changed (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/Apache-2.0.txt +201 -0
  3. package/LICENSES/README.md +19 -0
  4. package/LICENSES/codex-NOTICE.txt +6 -0
  5. package/README.md +386 -2
  6. package/SECURITY.md +145 -0
  7. package/adapters/briefs/claude.md +43 -0
  8. package/adapters/briefs/codex.md +56 -0
  9. package/adapters/briefs/models.json +33 -0
  10. package/adapters/build.mjs +8 -0
  11. package/adapters/claude/.claude-plugin/marketplace.json +13 -0
  12. package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
  13. package/adapters/claude/relay/agents/codex.md +21 -0
  14. package/adapters/claude/relay/agents/operator.md +21 -0
  15. package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
  16. package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
  17. package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
  18. package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
  19. package/adapters/claude/relay/skills/review/SKILL.md +21 -0
  20. package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
  21. package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
  22. package/adapters/codex/.agents/plugins/marketplace.json +20 -0
  23. package/adapters/codex/AGENTS.snippet.md +5 -0
  24. package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
  25. package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
  26. package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
  27. package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
  28. package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
  29. package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
  30. package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
  31. package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
  32. package/adapters/generate.mjs +124 -0
  33. package/bin/relay +59 -0
  34. package/codex-pin.json +12 -0
  35. package/dist/backends/acp.js +1424 -0
  36. package/dist/backends/claude.js +890 -0
  37. package/dist/backends/cli-version.js +112 -0
  38. package/dist/backends/codex-app.js +1525 -0
  39. package/dist/backends/codex-daybreak.js +75 -0
  40. package/dist/backends/codex-env.js +656 -0
  41. package/dist/backends/codex-network.js +304 -0
  42. package/dist/backends/codex-pin.js +320 -0
  43. package/dist/backends/codex-shell-policy.js +182 -0
  44. package/dist/backends/codex-stage2.js +998 -0
  45. package/dist/backends/codex-subagents.js +47 -0
  46. package/dist/backends/codex.js +637 -0
  47. package/dist/backends/copilot.js +246 -0
  48. package/dist/backends/env.js +147 -0
  49. package/dist/backends/gemini.js +607 -0
  50. package/dist/backends/grok.js +337 -0
  51. package/dist/backends/index.js +8 -0
  52. package/dist/backends/native-temp.js +187 -0
  53. package/dist/backends/never-admission.js +90 -0
  54. package/dist/backends/run.js +67 -0
  55. package/dist/backends/stream.js +230 -0
  56. package/dist/backends/tool-discovery.js +15 -0
  57. package/dist/backends/types.js +264 -0
  58. package/dist/build-info.json +5 -0
  59. package/dist/cli.js +344 -0
  60. package/dist/confine/bridge.js +113 -0
  61. package/dist/confine/broker-core.js +76 -0
  62. package/dist/confine/broker-http.js +650 -0
  63. package/dist/confine/broker-names.js +9 -0
  64. package/dist/confine/broker.js +258 -0
  65. package/dist/confine/canary.js +380 -0
  66. package/dist/confine/diagnostics.js +122 -0
  67. package/dist/confine/gemini-tools-main.js +8 -0
  68. package/dist/confine/gemini-tools.js +181 -0
  69. package/dist/confine/hardlinks.js +58 -0
  70. package/dist/confine/harness-config.js +16 -0
  71. package/dist/confine/index.js +117 -0
  72. package/dist/confine/leases.js +217 -0
  73. package/dist/confine/paths.js +6 -0
  74. package/dist/confine/peer.js +115 -0
  75. package/dist/confine/port-policy.js +8 -0
  76. package/dist/confine/ports.js +365 -0
  77. package/dist/confine/private-root.js +208 -0
  78. package/dist/confine/probe-stage2.js +501 -0
  79. package/dist/confine/probe.js +1109 -0
  80. package/dist/confine/proxy.js +783 -0
  81. package/dist/confine/sbcheck.js +208 -0
  82. package/dist/confine/seatbelt-never.js +41 -0
  83. package/dist/confine/seatbelt-stage2.js +139 -0
  84. package/dist/confine/seatbelt.js +1129 -0
  85. package/dist/confine/sockets.js +36 -0
  86. package/dist/confine/turn-probe.js +19 -0
  87. package/dist/confine/turn.js +86 -0
  88. package/dist/core/adoption.js +124 -0
  89. package/dist/core/api-keys.js +423 -0
  90. package/dist/core/approvals.js +740 -0
  91. package/dist/core/build-identity.js +248 -0
  92. package/dist/core/caller.js +749 -0
  93. package/dist/core/calls.js +102 -0
  94. package/dist/core/claude-settings.js +1045 -0
  95. package/dist/core/config.js +453 -0
  96. package/dist/core/context.js +186 -0
  97. package/dist/core/db.js +753 -0
  98. package/dist/core/dispatch.js +110 -0
  99. package/dist/core/env-broker.js +505 -0
  100. package/dist/core/env-policy.js +182 -0
  101. package/dist/core/escalation-authority.js +76 -0
  102. package/dist/core/escalation-contract.js +13 -0
  103. package/dist/core/escalation-person-path.js +131 -0
  104. package/dist/core/escalation-policy.js +79 -0
  105. package/dist/core/escalation-runtime.js +135 -0
  106. package/dist/core/escalation-state.js +42 -0
  107. package/dist/core/escalations.js +191 -0
  108. package/dist/core/events.js +235 -0
  109. package/dist/core/executables.js +147 -0
  110. package/dist/core/extensions.js +645 -0
  111. package/dist/core/families.js +204 -0
  112. package/dist/core/git.js +657 -0
  113. package/dist/core/identity.js +113 -0
  114. package/dist/core/liveness.js +68 -0
  115. package/dist/core/mediated-network-provider.js +81 -0
  116. package/dist/core/never-checkpoint.js +76 -0
  117. package/dist/core/never-coverage.js +97 -0
  118. package/dist/core/never-network.js +49 -0
  119. package/dist/core/never-policy.js +302 -0
  120. package/dist/core/never-proxy-policy.js +109 -0
  121. package/dist/core/never-schema.js +61 -0
  122. package/dist/core/never-tools.js +56 -0
  123. package/dist/core/notices.js +48 -0
  124. package/dist/core/ops.js +959 -0
  125. package/dist/core/outcome.js +224 -0
  126. package/dist/core/params.js +32 -0
  127. package/dist/core/presence.js +174 -0
  128. package/dist/core/procs.js +546 -0
  129. package/dist/core/prompts.js +363 -0
  130. package/dist/core/protected-config.js +238 -0
  131. package/dist/core/raw-network.js +192 -0
  132. package/dist/core/redact.js +152 -0
  133. package/dist/core/refusal.js +33 -0
  134. package/dist/core/relay-command.js +310 -0
  135. package/dist/core/reported.js +3 -0
  136. package/dist/core/restart-overlay.js +651 -0
  137. package/dist/core/retention.js +1135 -0
  138. package/dist/core/secrets.js +329 -0
  139. package/dist/core/session-token.js +175 -0
  140. package/dist/core/session.js +744 -0
  141. package/dist/core/shell.js +2 -0
  142. package/dist/core/shipped-pin.js +47 -0
  143. package/dist/core/shown.js +42 -0
  144. package/dist/core/slots.js +67 -0
  145. package/dist/core/stage2-executors.js +453 -0
  146. package/dist/core/stage2-switch.js +5 -0
  147. package/dist/core/steering.js +149 -0
  148. package/dist/core/storage.js +358 -0
  149. package/dist/core/toml.js +175 -0
  150. package/dist/core/views.js +324 -0
  151. package/dist/core/wait.js +114 -0
  152. package/dist/core/wake.js +207 -0
  153. package/dist/core/watch.js +247 -0
  154. package/dist/core/worktree.js +213 -0
  155. package/dist/hosts/claude-desktop.js +274 -0
  156. package/dist/hosts/claude.js +249 -0
  157. package/dist/hosts/codex.js +329 -0
  158. package/dist/hosts/desktop-shared.js +20 -0
  159. package/dist/hosts/index.js +11 -0
  160. package/dist/hosts/types.js +4 -0
  161. package/dist/install/basics.js +18 -0
  162. package/dist/install/claude-init.js +133 -0
  163. package/dist/install/common.js +655 -0
  164. package/dist/install/doctor.js +629 -0
  165. package/dist/install/qualify-codex.js +205 -0
  166. package/dist/install.js +524 -0
  167. package/dist/mcp/elicit.js +209 -0
  168. package/dist/mcp/gateway.js +218 -0
  169. package/dist/mcp/host.js +253 -0
  170. package/dist/mcp/server.js +1124 -0
  171. package/dist/mcp/stdio.js +37 -0
  172. package/dist/modes/discussion.js +393 -0
  173. package/dist/modes/review.js +722 -0
  174. package/dist/native/relay-sbcheck +0 -0
  175. package/dist/targets/briefs.js +86 -0
  176. package/dist/targets/claude.js +94 -0
  177. package/dist/targets/codex.js +66 -0
  178. package/dist/targets/copilot.js +93 -0
  179. package/dist/targets/gemini.js +119 -0
  180. package/dist/targets/grok.js +126 -0
  181. package/dist/targets/index.js +192 -0
  182. package/dist/targets/types.js +18 -0
  183. package/dist/targets/verified.js +35 -0
  184. package/dist/worker.js +113 -0
  185. package/docs/UPGRADING.md +1502 -0
  186. package/docs/pinned-codex.md +321 -0
  187. package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
  188. package/experiments/stage2-redteam/lib/report.mjs +35 -0
  189. package/npm-shrinkwrap.json +1632 -0
  190. package/package.json +82 -4
  191. package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
  192. package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
  193. package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
  194. package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
  195. package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
  196. package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
  197. package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
  198. package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
  199. package/scripts/codex-qualify/main-module.mjs +14 -0
  200. package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
  201. package/scripts/codex-qualify/scratch-env.mjs +31 -0
  202. package/scripts/codex-qualify/session.mjs +96 -0
  203. package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
  204. package/test/codex-permissions.test.ts +875 -0
  205. package/test/fixtures/boundary-probes.mjs +17 -0
  206. package/test/fixtures/denial-stream-host.mjs +7 -0
  207. package/test/fixtures/families.json +246 -0
  208. package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
  209. package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
  210. package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
  211. package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
  212. package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
  213. package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
  214. package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
  215. package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
  216. package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
  217. package/test/fixtures/link-parent.mjs +6 -0
  218. package/test/fixtures/mediated-command.cjs +72 -0
  219. package/test/fixtures/native-skill-isolation.json +280 -0
  220. package/test/fixtures/pinned-codex-app-server.mjs +25 -0
  221. package/test/fixtures/qualified-ext-adapters.mjs +36 -0
  222. package/test/fixtures/refusals/README.md +52 -0
  223. package/test/fixtures/refusals/claude-source-result.json +7 -0
  224. package/test/fixtures/refusals/openai-app-capacity.json +24 -0
  225. package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
  226. package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
  227. package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
  228. package/test/fixtures/refusals/openai-review-capacity.json +24 -0
  229. package/test/fixtures/relay-0.2.0.sql +57 -0
  230. package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
  231. package/test/fixtures/relay-0.9.1.sql +340 -0
  232. package/test/fixtures/slow-boundary-probes.mjs +37 -0
  233. package/test/fixtures/stable-surfaces/config.json +1122 -0
  234. package/test/fixtures/stable-surfaces/escalation.json +128 -0
  235. package/test/fixtures/stable-surfaces/events.json +37 -0
  236. package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
  237. package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
  238. package/test/fixtures/stable-surfaces/notice.txt +1 -0
  239. package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
  240. package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
  241. package/test/fixtures/stable-surfaces/registry.json +49 -0
  242. package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
  243. package/test/fixtures/stable-surfaces/tools.json +716 -0
  244. package/test/fixtures/stable-surfaces/usage.txt +46 -0
  245. package/test/fixtures/stage2-acp-native.mjs +138 -0
  246. package/test/fixtures/stage2-app-server.mjs +23 -0
  247. package/test/fixtures/stage2-catalog.json +91 -0
  248. package/test/fixtures/stage2-hostile-web.mjs +35 -0
  249. package/test/fixtures/stage2-native-network.mjs +62 -0
  250. package/test/fixtures/stage2-worker.ts +87 -0
  251. package/test/fixtures/status-views/expected.json +7825 -0
  252. package/test/fixtures/status-views/registries.json +1 -0
  253. package/test/fixtures/steering.json +209 -0
  254. package/test/helpers.ts +740 -0
  255. package/test/host-env.ts +7 -0
  256. package/test/keychain-decoy.ts +197 -0
  257. package/test/live-scope.ts +44 -0
  258. package/test/mediated-network.test.ts +192 -0
  259. package/test/mediated-proxy.test.ts +264 -0
  260. package/test/native-temp-alias.ts +10 -0
  261. package/test/never-policy.test.ts +629 -0
  262. package/test/never-tools.test.ts +136 -0
  263. package/test/process-home.ts +18 -0
  264. package/test/proxy.test.ts +531 -0
  265. package/test/restart-overlay-live.test.ts +85 -0
  266. package/test/restart-overlay-profile.test.ts +66 -0
  267. package/test/restart-overlay.test.ts +416 -0
  268. package/test/stable-surfaces.test.ts +249 -0
  269. package/test/stage2-escalation-live.test.ts +544 -0
  270. package/test/stage2-escalation-qualification.test.ts +170 -0
  271. package/test/stage2-escalation.test.ts +747 -0
  272. package/test/stage2-executor.test.ts +849 -0
  273. package/test/stage2-grant.test.ts +603 -0
  274. package/test/stage2-native-live.test.ts +647 -0
  275. package/test/stage2-network-decisions.test.ts +70 -0
  276. package/test/stage2-probe.test.ts +845 -0
  277. package/test/stage2-standing-live.test.ts +203 -0
  278. package/test/stubs/broker-host.mjs +59 -0
  279. package/test/stubs/broker-peer.mjs +20 -0
  280. package/test/stubs/confined-harness.mjs +91 -0
  281. package/test/stubs/ext-broken-server.mjs +2 -0
  282. package/test/stubs/ext-odd-server.mjs +21 -0
  283. package/test/stubs/ext-server.mjs +31 -0
  284. package/test/stubs/fake-host-cli.mjs +218 -0
  285. package/test/stubs/procargs.mjs +30 -0
  286. package/test/stubs/stub-acp +4 -0
  287. package/test/stubs/stub-agent.mjs +322 -0
  288. package/test/stubs/stub-claude +4 -0
  289. package/test/stubs/stub-codex +4 -0
  290. package/test/stubs/targets/acp.mjs +307 -0
  291. package/test/stubs/targets/claude.mjs +149 -0
  292. package/test/stubs/targets/codex.mjs +479 -0
  293. package/test/stubs/targets/gemini.mjs +604 -0
  294. package/test/temp-root.ts +11 -0
  295. package/test/wp4-adapters.test.ts +353 -0
  296. package/test/wp4-interlock.test.ts +136 -0
@@ -0,0 +1,208 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ const OPERATIONS = ["file-write-data", "file-write-create", "file-read-data"];
7
+ let helperOverride = null;
8
+ let selfTest = null;
9
+ /** Relay's own package, as protected-config.ts relayPackageRoot finds it (this module is dist/confine/sbcheck.js). */
10
+ const PACKAGE_ROOT = path.resolve(import.meta.dirname, "..", "..");
11
+ /** Where `npm run build` puts the helper: dist/native/relay-sbcheck, beside dist/confine, in relay's own package. */
12
+ const BUILT_HELPER = path.join(PACKAGE_ROOT, "dist", "native", "relay-sbcheck");
13
+ const digest = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
14
+ function recordHelper(helper) {
15
+ try {
16
+ const st = fs.lstatSync(helper);
17
+ if (!st.isFile())
18
+ return `relay's sandbox_check helper ${helper} was not a regular file when relay started`;
19
+ return { path: helper, dev: st.dev, ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, ctimeMs: st.ctimeMs, sha256: digest(helper) };
20
+ }
21
+ catch {
22
+ return `relay's sandbox_check helper ${helper} was not there when relay started (it is built by \`npm run build\` where the developer tools are installed)`;
23
+ }
24
+ }
25
+ /** Recorded when relay's process loads this module, at its start: the helper it may run, and nothing else. */
26
+ let recorded = recordHelper(BUILT_HELPER);
27
+ /** Test-only seam: use another helper binary (or a missing path), recorded now, and forget the cached self-test. */
28
+ export function setSandboxCheckHelperForTests(helper) {
29
+ helperOverride = helper;
30
+ recorded = recordHelper(helper ?? BUILT_HELPER);
31
+ selfTest = null;
32
+ }
33
+ /** The helper relay runs: dist/native/relay-sbcheck in its own package. */
34
+ export function sandboxCheckHelper() {
35
+ return helperOverride ?? BUILT_HELPER;
36
+ }
37
+ /**
38
+ * Why the helper may not be run: missing, not a regular file, not this user's, writable by others,
39
+ * not relay's own package's, or not the file, with the contents, relay recorded at its start.
40
+ */
41
+ function helperProblem(helper) {
42
+ let st;
43
+ try {
44
+ st = fs.lstatSync(helper);
45
+ }
46
+ catch {
47
+ return `relay's sandbox_check helper ${helper} is not there (it is built by \`npm run build\` where the developer tools are installed)`;
48
+ }
49
+ if (!st.isFile())
50
+ return `relay's sandbox_check helper ${helper} is not a regular file`;
51
+ if (process.getuid && st.uid !== process.getuid())
52
+ return `relay's sandbox_check helper ${helper} is not owned by this user`;
53
+ if (st.mode & 0o022)
54
+ return `relay's sandbox_check helper ${helper} is writable by others`;
55
+ if (!(st.mode & 0o100))
56
+ return `relay's sandbox_check helper ${helper} is not executable`;
57
+ // Only from relay's own package, reached through real directories (no link on the way), and
58
+ // only the file relay recorded at its start, unchanged: same identity, same contents.
59
+ if (helperOverride === null) {
60
+ let real;
61
+ try {
62
+ real = fs.realpathSync.native(helper);
63
+ }
64
+ catch {
65
+ return `relay's sandbox_check helper ${helper} cannot be resolved`;
66
+ }
67
+ let root;
68
+ try {
69
+ root = fs.realpathSync.native(PACKAGE_ROOT);
70
+ }
71
+ catch {
72
+ return `relay's own package ${PACKAGE_ROOT} cannot be resolved`;
73
+ }
74
+ if (real !== path.join(root, "dist", "native", "relay-sbcheck"))
75
+ return `relay's sandbox_check helper ${helper} resolves to ${real}, not into relay's own package (${root}), so relay does not run it`;
76
+ }
77
+ if (typeof recorded === "string")
78
+ return recorded;
79
+ if (recorded.path !== helper)
80
+ return `relay's sandbox_check helper ${helper} is not the one relay recorded at its start (${recorded.path})`;
81
+ if (st.dev !== recorded.dev || st.ino !== recorded.ino || st.size !== recorded.size || st.mtimeMs !== recorded.mtimeMs || st.ctimeMs !== recorded.ctimeMs) {
82
+ return `relay's sandbox_check helper ${helper} has been replaced or changed since relay started, so relay does not run it (restart relay after rebuilding it)`;
83
+ }
84
+ let now;
85
+ try {
86
+ now = digest(helper);
87
+ }
88
+ catch (err) {
89
+ return `relay cannot read its sandbox_check helper ${helper}: ${err.message}`;
90
+ }
91
+ if (now !== recorded.sha256)
92
+ return `relay's sandbox_check helper ${helper} no longer has the contents relay recorded at its start (sha256 ${recorded.sha256.slice(0, 12)}…, now ${now.slice(0, 12)}…), so relay does not run it`;
93
+ return null;
94
+ }
95
+ const field = (s) => {
96
+ if (s === "0")
97
+ return 0;
98
+ if (s === "1")
99
+ return 1;
100
+ const m = /^-1:(\d+)$/.exec(s);
101
+ return `error: sandbox_check failed${m ? ` (errno ${m[1]})` : ` (${JSON.stringify(s)})`}`;
102
+ };
103
+ /**
104
+ * Asks about many processes at once: for each pid, whether it is sandboxed and whether its sandbox
105
+ * allows `operation` on each path (which must exist). A string when the helper could not be run.
106
+ * Does not run the self-test; callers that act on the answer check sandboxCheckUnavailable first.
107
+ */
108
+ export function sandboxReports(operation, paths, pids) {
109
+ if (!OPERATIONS.includes(operation))
110
+ return `unknown operation ${operation}`;
111
+ if (!paths.length || paths.some((p) => !path.isAbsolute(p) || /[\0\n]/.test(p)))
112
+ return "each path must be absolute";
113
+ const helper = sandboxCheckHelper();
114
+ const bad = helperProblem(helper);
115
+ if (bad)
116
+ return bad;
117
+ const out = new Map();
118
+ const wanted = [...new Set(pids.filter((p) => Number.isInteger(p) && p > 0))];
119
+ // In slices, to keep each command line well under ARG_MAX however many processes there are.
120
+ for (let i = 0; i < wanted.length; i += 512) {
121
+ const slice = wanted.slice(i, i + 512);
122
+ // Checked again right before every run, not once per call: it runs outside any sandbox.
123
+ const changed = i > 0 ? helperProblem(helper) : null;
124
+ if (changed)
125
+ return changed;
126
+ const r = spawnSync(helper, [operation, ...paths, "--", ...slice.map(String)], { encoding: "utf8", timeout: 20000, env: { PATH: "/usr/bin:/bin" } });
127
+ if (r.error || r.status !== 0)
128
+ return `relay's sandbox_check helper failed: ${r.error?.message ?? `exit ${r.status}: ${(r.stderr ?? "").trim()}`}`;
129
+ for (const line of r.stdout.split("\n")) {
130
+ const parts = line.trim().split(/\s+/);
131
+ if (parts.length !== paths.length + 2 || !/^\d+$/.test(parts[0]))
132
+ continue;
133
+ const s = field(parts[1]);
134
+ out.set(Number(parts[0]), {
135
+ sandboxed: typeof s === "string" ? s : s === 1,
136
+ answers: parts.slice(2).map((a) => {
137
+ const v = field(a);
138
+ return typeof v === "string" ? v : v === 0 ? "allow" : "deny";
139
+ }),
140
+ });
141
+ }
142
+ }
143
+ return out;
144
+ }
145
+ export function sandboxAllows(pid, operation, target) {
146
+ const reports = sandboxReports(operation, [target], [pid]);
147
+ if (typeof reports === "string")
148
+ return `error: ${reports}`;
149
+ return reports.get(pid)?.answers[0] ?? "error: the helper gave no answer for this process";
150
+ }
151
+ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
152
+ /** The known-answer test, run once per process (and helper). */
153
+ function runSelfTest(helper) {
154
+ const bad = helperProblem(helper);
155
+ if (bad)
156
+ return bad;
157
+ if (process.platform !== "darwin")
158
+ return "sandbox_check exists only on macOS";
159
+ const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "relay-sbcheck-")));
160
+ const allowed = path.join(base, "a"), denied = path.join(base, "d");
161
+ fs.mkdirSync(allowed);
162
+ fs.mkdirSync(denied);
163
+ const child = spawn("/usr/bin/sandbox-exec", ["-p", '(version 1)(allow default)(deny file-write* (subpath (param "D")))', "-D", `D=${denied}`, "/bin/sleep", "30"], { stdio: "ignore", detached: true });
164
+ child.on("error", () => { });
165
+ const pid = child.pid ?? -1;
166
+ try {
167
+ if (pid <= 0)
168
+ return "relay could not start the sandbox_check helper's control process";
169
+ let report;
170
+ for (let i = 0; i < 40; i++) {
171
+ const r = sandboxReports("file-write-data", [allowed, denied], [pid, process.pid]);
172
+ if (typeof r === "string")
173
+ return r;
174
+ report = r.get(pid);
175
+ const self = r.get(process.pid);
176
+ if (self?.sandboxed !== false)
177
+ return `relay's sandbox_check helper misreads relay's own process (${JSON.stringify(self)})`;
178
+ if (report?.sandboxed === true)
179
+ break;
180
+ pause(50);
181
+ }
182
+ if (report?.sandboxed !== true)
183
+ return `relay's sandbox_check helper did not see its control process as sandboxed (${JSON.stringify(report)})`;
184
+ if (report.answers[0] !== "allow" || report.answers[1] !== "deny")
185
+ return `relay's sandbox_check helper gave the wrong answers for its control process: ${JSON.stringify(report.answers)} where allow, deny was expected`;
186
+ return null;
187
+ }
188
+ finally {
189
+ try {
190
+ if (pid > 0)
191
+ process.kill(pid, "SIGKILL");
192
+ }
193
+ catch {
194
+ // Already gone.
195
+ }
196
+ child.unref();
197
+ fs.rmSync(base, { recursive: true, force: true });
198
+ }
199
+ }
200
+ /** Whether this machine can ask (the helper is present and answers a known control). Null when it can. */
201
+ export function sandboxCheckUnavailable() {
202
+ const helper = sandboxCheckHelper();
203
+ if (selfTest?.helper !== helper)
204
+ selfTest = { helper, problem: runSelfTest(helper) };
205
+ // The self-test runs once; the helper's identity and contents are checked on every ask, so a
206
+ // helper changed since then reads as unavailable (and the caller reports it) rather than as an empty sweep.
207
+ return selfTest.problem ?? helperProblem(helper);
208
+ }
@@ -0,0 +1,41 @@
1
+ import { neverIdentityProblem, neverProfileInputs } from "../core/never-policy.js";
2
+ import { within } from "./paths.js";
3
+ /** Final operation-specific floor, shared by every overlay profile. No path/port interpolation. */
4
+ export function neverSeatbeltRules(policy, param, diag, own) {
5
+ const problem = neverIdentityProblem(policy);
6
+ if (problem)
7
+ throw new Error(problem);
8
+ const p = neverProfileInputs(policy), rules = [];
9
+ const writes = "file-write* file-write-data file-write-create file-write-unlink file-write-mode file-link";
10
+ const paths = (paths, ops, prefix, managed = false) => paths.forEach((root, i) => {
11
+ const value = param(`${prefix}_${i}`, root);
12
+ const exceptions = managed ? [own.worktree, own.tmpDir].filter(x => within(x, root)).map((x, j) => `(require-not (subpath ${param(`${prefix}_${i}_OWN_${j}`, x)}))`) : [];
13
+ const filter = exceptions.length ? `(require-all (subpath ${value}) ${exceptions.join(" ")})` : `(subpath ${value})`;
14
+ rules.push(`(deny ${ops} ${filter} ${diag})`);
15
+ });
16
+ paths(p.denyAll, `file-read* file-read-data file-read-metadata file-test-existence ${writes}`, "NEVER_ALL");
17
+ paths(p.denyWrite, writes, "NEVER_WRITE");
18
+ paths(p.authorityRoots, `file-read* file-read-data file-read-metadata file-test-existence ${writes}`, "NEVER_AUTHORITY", true);
19
+ if (p.denyKeychain)
20
+ rules.push(`(deny mach-lookup (global-name "com.apple.SecurityServer") (global-name "com.apple.securityd") (global-name "com.apple.trustd") ${diag})`);
21
+ p.ports.forEach((r, i) => {
22
+ const port = param(`NEVER_PORT_${i}`, String(r.port));
23
+ for (const transport of r.transport === "both" ? ["tcp", "udp"] : [r.transport]) {
24
+ const host = r.destinations === "any" ? "*" : "localhost";
25
+ rules.push(`(deny network-outbound (require-all (remote ${transport} (string-append "${host}:" ${port}))) ${diag})`);
26
+ // Explicit families retain mapped-IPv6 service-port overblocking. Final inbound deny beats broad TCP inbound.
27
+ rules.push(`(deny network-outbound (require-all (remote ip6 (string-append "*:" ${port})) (remote ${transport} (string-append "*:" ${port}))) ${diag})`);
28
+ rules.push(`(deny network-bind network-inbound (local ${transport} (string-append "*:" ${port})) ${diag})`);
29
+ }
30
+ });
31
+ p.authorityPorts.forEach((port, i) => {
32
+ const value = param(`NEVER_CONTROL_${i}`, String(port));
33
+ if (!own.bindPorts?.includes(port) && port !== own.mediatedPort)
34
+ rules.push(`(deny network-outbound (remote ip4 (string-append "localhost:" ${value})) (remote ip6 (string-append "*:" ${value})) ${diag})`);
35
+ if (port === own.mediatedPort)
36
+ rules.push(`(deny network-outbound (remote ip6 (string-append "*:" ${value})) ${diag})`);
37
+ if (port !== own.execPort && !own.bindPorts?.includes(port))
38
+ rules.push(`(deny network-bind network-inbound (local ip4 (string-append "*:" ${value})) (local ip6 (string-append "*:" ${value})) ${diag})`);
39
+ });
40
+ return rules;
41
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Stage 2's network block for relay's Seatbelt profile (docs/codex-confinement-design.md §5.1).
3
+ * Owner: WP-A. seatbelt.ts calls stage2NetworkRules for `network.mode === "stage2"`.
4
+ */
5
+ import { STATIC_DENIED_TCP } from "./port-policy.js";
6
+ /**
7
+ * The most ports one profile names (denied, range, block and executor together). Far above what a
8
+ * turn needs (the static list, a snapshot of a few dozen listeners, a 64-port range); past it the
9
+ * turn is refused rather than given a shortened denylist.
10
+ */
11
+ export const STAGE2_MAX_PORTS = 1024;
12
+ // Seatbelt accepts only * and localhost as address hosts. Owner-approved IPv4
13
+ // localhost:P includes this Mac's LAN/tailnet addresses. No IPv6 allow is added.
14
+ /**
15
+ * The profile text for a stage-2 network, written with `param` (seatbelt.ts's parameter writer) so
16
+ * that no port or path is in the text: the probe's decoy variant then has the same rules hash.
17
+ * `diag` is the turn's `(with message …)` clause for every deny. `paths` are the canonical TMPDIR and worktree.
18
+ *
19
+ * The text depends only on how many ports each list holds and on `worktreeSockets`; every value is
20
+ * a parameter. The turn's own Unix sockets under TMPDIR are allowed by seatbeltProfile in every
21
+ * mode, so this block adds only the worktree's, and only when `worktreeSockets` is set.
22
+ *
23
+ * Order: baseline allows first, then denies, since Seatbelt takes the last matching rule. Explicit
24
+ * localhost connect/listen exceptions follow the baseline snapshot denies, before final never/control rules. Each deny
25
+ * must win over the outbound IP allow and the UDP bind allow above it. The block's allows never meet a
26
+ * deny: checkStage2Network refuses a block port that is also denied or in the range.
27
+ *
28
+ * Every IP rule names its family (ip4, ip6), never "ip": beside an ip6 rule, `(remote ip
29
+ * "localhost:P")` stopped matching IPv4 (127.0.0.1, 0.0.0.0, the LAN address connected), and an ip6
30
+ * deny beside `(remote ip "*:*")` refused IPv4 egress too (measured on macOS 27.0.1, review R1).
31
+ */
32
+ export function stage2NetworkRules(net, param, diag, paths) {
33
+ checkStage2Network(net);
34
+ const local = (p) => `(string-append "localhost:" ${p})`;
35
+ const anyHost = (p) => `(string-append "*:" ${p})`;
36
+ const L = [];
37
+ if (net.egress !== "none")
38
+ L.push(`; --- network, stage 2 (docs/codex-confinement-design.md §5.1): IP anywhere, then the local denies.
39
+ ; Creating IP and Unix sockets needs no rule; kernel-control sockets (AF_SYSTEM, SYSPROTO_CONTROL),
40
+ ; which the network stack uses, do. DNS through mDNSResponder, as with the network on.
41
+ ; Every IP rule names its family: an "ip" rule beside ip4 or ip6 ones matched other addresses (measured).
42
+ (allow network-outbound (remote ip4 "*:*") (remote ip6 "*:*"))
43
+ (allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))
44
+ (allow mach-lookup (global-name "com.apple.dnssd.service") (global-name "com.apple.mDNSResponder")
45
+ (global-name "com.apple.SystemConfiguration.configd") (global-name "com.apple.SystemConfiguration.DNSConfiguration")
46
+ (global-name "com.apple.networkd") (global-name "com.apple.nehelper"))
47
+ (allow network-outbound (literal "/private/var/run/mDNSResponder"))`);
48
+ if (net.broadBind)
49
+ L.push(`; --- approved port-0 scope: TCP listeners may bind 0.0.0.0, on the LAN\n(allow network-bind network-inbound (local tcp "*:*"))`);
50
+ // Listening: always the executor's port; the job's block only when its plan carries authority. Seatbelt's
51
+ // "localhost" in a local rule matches 127.0.0.1, ::1 and the wildcard address alike (measured).
52
+ L.push(`; --- listening: TCP on the executor's port, plus an authorized job block when present\n(allow network-bind network-inbound (local tcp ${local(param("EXEC_PORT", String(net.execPort)))}))`);
53
+ net.bindPorts.forEach((p, i) => L.push(`(allow network-bind network-inbound (local tcp ${local(param(`BIND_PORT_${i}`, String(p)))}))`));
54
+ // UDP: a client binds implicitly on its first send, and its replies arrive as inbound datagrams;
55
+ // without these every UDP send fails, and every reply (a direct DNS query, QUIC) is refused (measured).
56
+ if (net.egress !== "none")
57
+ L.push(`(allow network-bind network-inbound (local udp "localhost:*"))`);
58
+ if (net.worktreeSockets) {
59
+ // Write turns in a worktree relay made and pinned (seatbeltProfile checks both). A read turn's
60
+ // directory may be the person's own checkout or home, whose sockets are theirs (review C4).
61
+ const wt = param("WORKTREE", paths.worktree);
62
+ L.push(`; --- Unix sockets in the job's own worktree\n(allow network-bind (local unix-socket (subpath ${wt})))\n(allow network-outbound (remote unix-socket (subpath ${wt})))`);
63
+ }
64
+ // The denies, after every allow they must win over. IPv4: "localhost" in a remote rule matches every
65
+ // IPv4 address of this Mac's own (loopback, LAN, tailnet) and 0.0.0.0 (measured, §5.2). IPv6: the
66
+ // port is denied at every host, since "localhost" misses the IPv4-mapped spellings of this Mac's
67
+ // addresses (::ffff:0.0.0.0 reaches loopback, ::ffff:<LAN address> the LAN address; review R1) and
68
+ // Seatbelt names no host but * and localhost. The cost: IPv6, and IPv4 through an IPv6 socket, to
69
+ // these port numbers on every host. Binding: denied at every local address of either family.
70
+ const denyOut = (port) => `(deny network-outbound (remote ip4 ${local(port)}) ${diag})\n(deny network-outbound (remote ip6 ${anyHost(port)}) ${diag})`;
71
+ L.push(`; --- denied ports: the static list and the listening snapshot, at every local address (IPv6: every host), and never bound`);
72
+ net.deniedTcp.forEach((p, i) => {
73
+ const port = param(`DENY_PORT_${i}`, String(p));
74
+ L.push(`${denyOut(port)}\n(deny network-bind (local ip4 ${anyHost(port)}) (local ip6 ${anyHost(port)}) ${diag})\n(deny network-inbound (local ip4 ${anyHost(port)}) (local ip6 ${anyHost(port)}) ${diag})`);
75
+ });
76
+ // Approved listener ports appear in the snapshot deny too: override that deny only,
77
+ // before the reserved/control and final never denies. Values remain parameters, no literal IP.
78
+ (net.connectPorts ?? []).forEach((p, i) => L.push(`(allow network-outbound (remote ip4 ${local(param(`CONNECT_PORT_${i}`, String(p)))}))`));
79
+ (net.listenPorts ?? []).forEach((p, i) => L.push(`(allow network-bind network-inbound (local tcp ${local(param(`LISTEN_PORT_${i}`, String(p)))}))`));
80
+ L.push(`; --- relay's reserved range but this turn's block: other turns' executors and blocks, this turn's executor, relay's own proxies`);
81
+ net.relayRange.forEach((p, i) => L.push(denyOut(param(`RELAY_PORT_${i}`, String(p)))));
82
+ // Broad bind cannot impersonate any other relay listener. The executor needs its own port to start.
83
+ net.relayRange.filter(p => p !== net.execPort).forEach((p, i) => L.push(`(deny network-bind network-inbound (local ip4 ${anyHost(param(`RELAY_LISTEN_DENY_${i}`, String(p)))}) (local ip6 ${anyHost(`(param "RELAY_LISTEN_DENY_${i}")`)}) ${diag})`));
84
+ L.push(`; --- UDP port mappings (SSDP/UPnP, NAT-PMP/PCP), to any host`);
85
+ net.deniedUdp.forEach((p, i) => L.push(`(deny network-outbound (remote udp (string-append "*:" ${param(`UDP_DENY_${i}`, String(p))})) ${diag})`));
86
+ if (net.mediatedPort !== undefined)
87
+ L.push(`; --- trusted worker proxy only; final never rules still follow
88
+ (allow network-outbound (remote ip4 ${local(param("MEDIATED_PORT", String(net.mediatedPort)))}))`);
89
+ return L.join("\n");
90
+ }
91
+ /** Checks a Stage2Network before it is written (ports in range, no overlap between block, exec port and denies). Throws what is wrong. */
92
+ export function checkStage2Network(net) {
93
+ if (!net || net.mode !== "stage2")
94
+ throw new Error(`not a stage-2 network: ${JSON.stringify(net?.mode)}`);
95
+ const isPort = (p) => typeof p === "number" && Number.isInteger(p) && p >= 1 && p <= 65535;
96
+ const list = (name) => {
97
+ const v = net[name];
98
+ if (!Array.isArray(v))
99
+ throw new Error(`stage-2 network: ${name} is not a list of ports`);
100
+ for (const p of v)
101
+ if (!isPort(p))
102
+ throw new Error(`stage-2 network: ${name} holds ${JSON.stringify(p)}, which is not a port (1-65535)`);
103
+ if (new Set(v).size !== v.length)
104
+ throw new Error(`stage-2 network: ${name} names a port twice`);
105
+ return v;
106
+ };
107
+ const deniedTcp = list("deniedTcp"), deniedUdp = list("deniedUdp"), relayRange = list("relayRange"), bindPorts = list("bindPorts");
108
+ if (net.egress !== undefined && !["raw", "none"].includes(net.egress))
109
+ throw new Error("stage-2 network: invalid overlay egress");
110
+ for (const key of ["connectPorts", "listenPorts"]) {
111
+ if (net[key] !== undefined && (!Array.isArray(net[key]) || net[key].some(p => !isPort(p) || relayRange.includes(p))))
112
+ throw new Error(`stage-2 network: invalid or protected overlay ${key}`);
113
+ const staticPort = net[key]?.find(p => STATIC_DENIED_TCP.includes(p));
114
+ if (staticPort !== undefined)
115
+ throw new Error(`stage-2 network: static denied TCP port ${staticPort} cannot be an overlay ${key === "connectPorts" ? "connect" : "listen"} exception`);
116
+ }
117
+ if (net.mediatedPort !== undefined && (!isPort(net.mediatedPort) || net.egress !== "none" || !relayRange.includes(net.mediatedPort) || net.mediatedPort === net.execPort || bindPorts.includes(net.mediatedPort) || deniedTcp.includes(net.mediatedPort) || net.listenPorts?.includes(net.mediatedPort)))
118
+ throw new Error("stage-2 network: invalid internal mediated proxy port");
119
+ if (!isPort(net.execPort))
120
+ throw new Error(`stage-2 network: the executor's port ${JSON.stringify(net.execPort)} is not a port (1-65535)`);
121
+ if (net.egress === "none" && bindPorts.length && !net.broadBind && !net.listenPorts?.length)
122
+ throw new Error("stage-2 network: the job's block cannot bind without raw network, an explicit listen, or a port-0 overlay");
123
+ if (typeof net.worktreeSockets !== "boolean")
124
+ throw new Error("stage-2 network: worktreeSockets must be true or false");
125
+ if (bindPorts.includes(net.execPort))
126
+ throw new Error(`stage-2 network: the executor's port ${net.execPort} is also in the job's block`);
127
+ // The executor's port falls under the range deny, so the job cannot open a second session on its own executor (§5.1).
128
+ if (!relayRange.includes(net.execPort))
129
+ throw new Error(`stage-2 network: the executor's port ${net.execPort} is not in the relay-range deny, so the job could reach its own executor`);
130
+ const inRange = bindPorts.filter((p) => relayRange.includes(p));
131
+ if (inRange.length)
132
+ throw new Error(`stage-2 network: block port(s) ${inRange.join(", ")} are also in the relay-range deny`);
133
+ const deniedOwn = [net.execPort, ...bindPorts].filter((p) => deniedTcp.includes(p));
134
+ if (deniedOwn.length)
135
+ throw new Error(`stage-2 network: port(s) ${deniedOwn.join(", ")} are both the turn's own and denied`);
136
+ const total = deniedTcp.length + deniedUdp.length + relayRange.length + bindPorts.length + 1 + (net.connectPorts?.length ?? 0) + (net.listenPorts?.length ?? 0);
137
+ if (total > STAGE2_MAX_PORTS)
138
+ throw new Error(`stage-2 network: ${total} ports is more than one profile carries (${STAGE2_MAX_PORTS}); relay does not shorten the denylist, so the turn is refused`);
139
+ }