@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,1129 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { relayHome } from "../core/config.js";
6
+ import { configProtection, relayWriteProtected, relayCredentialProtected } from "../core/protected-config.js";
7
+ import { within } from "./paths.js";
8
+ import { PROXY_TOKEN, proxyEnv } from "./proxy.js";
9
+ import { relaySocketsDir } from "./sockets.js";
10
+ import { stage2NetworkRules } from "./seatbelt-stage2.js";
11
+ import { neverSeatbeltRules } from "./seatbelt-never.js";
12
+ import { assertOverlayRoot } from "../core/restart-overlay.js";
13
+ import { HARNESS_CONFIG } from "./harness-config.js";
14
+ export { HARNESS_CONFIG } from "./harness-config.js";
15
+ /**
16
+ * macOS Seatbelt through `sandbox-exec`, ported from docs/research/seatbelt-prototype/profile.ts.
17
+ *
18
+ * The profile is deny-default with a condensed version of Codex's base allowlist. It holds no path:
19
+ * every path reaches sandbox-exec as a `-D` parameter, resolved and checked first, so no path can
20
+ * change the profile's meaning.
21
+ *
22
+ * Rule precedence, as measured on macOS 27.0.1 (26A434; docs/design-token-store.md): between rules on
23
+ * the same operation, the last that matches wins, so the hard denies come last. But a rule that names
24
+ * a specific operation (file-write-data, file-write-create, file-write-unlink, file-test-existence, …)
25
+ * takes precedence over one on its wildcard family (file-write*, file-read*) whatever their order: a
26
+ * later `(deny file-write* X)` does not override an earlier `(allow file-write-create X)`, and an
27
+ * earlier `(deny file-write-create X)` is not overridden by a later `(allow file-write* X)`. So every
28
+ * deny that must beat an operation-specific allow names that operation too, and comes after it; a
29
+ * generator test (test/confine.test.ts, "rule precedence") checks the whole profile for both.
30
+ */
31
+ export const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
32
+ /** fcntl commands that modify a file through a read-only descriptor (<sys/fcntl.h>; 80 is private). */
33
+ export const F_MAKECOMPRESSED = 80;
34
+ export const F_TRANSFEREXTENTS = 110;
35
+ /**
36
+ * A path as Seatbelt sees it. Seatbelt matches resolved paths (`/tmp` is `/private/tmp`), so the
37
+ * longest existing prefix is resolved and the rest appended. Refuses what cannot be a safe parameter.
38
+ */
39
+ export function canonical(p, what = "path") {
40
+ if (typeof p !== "string" || !p)
41
+ throw new Error(`${what} is empty`);
42
+ if (/[\0\r\n]/.test(p))
43
+ throw new Error(`${what} contains a NUL or line break: ${JSON.stringify(p)}`);
44
+ if (!path.isAbsolute(p))
45
+ throw new Error(`${what} is not absolute: ${JSON.stringify(p)}`);
46
+ let abs = path.resolve(p);
47
+ const tail = [];
48
+ for (;;) {
49
+ try {
50
+ const real = path.join(fs.realpathSync.native(abs), ...tail);
51
+ if (/[\0\r\n]/.test(real))
52
+ throw new Error(`${what} resolves through a name with a line break: ${JSON.stringify(real)}`);
53
+ return real;
54
+ }
55
+ catch (err) {
56
+ if (err.code !== "ENOENT" && err.code !== "ENOTDIR")
57
+ throw err;
58
+ tail.unshift(path.basename(abs));
59
+ const up = path.dirname(abs);
60
+ if (up === abs)
61
+ return path.join(abs, ...tail);
62
+ abs = up;
63
+ }
64
+ }
65
+ }
66
+ /**
67
+ * A short label for this turn's sandbox, put on the profile's `(deny default)` rule and appended to
68
+ * every denial the kernel logs, so relay can stream just this turn's denials (diagnostics.ts) and a
69
+ * harness that cannot work inside the profile says which rule stopped it. Deterministic from the
70
+ * policy (the turn's temp dir is unique to it), so wrapping a policy twice gives one profile; a
71
+ * caller may pass its own readable label in `policy.tag`.
72
+ */
73
+ export function diagnosticTag(policy) {
74
+ if (policy.tag !== undefined) {
75
+ if (!/^[A-Za-z0-9 ._:/-]{1,64}$/.test(policy.tag))
76
+ throw new Error(`the turn's diagnostic tag may only be short and plain: ${JSON.stringify(policy.tag)}`);
77
+ return `relay-sandbox ${policy.tag}`;
78
+ }
79
+ return `relay-sandbox ${crypto.createHash("sha256").update(canonical(policy.tmpDir, "tmpDir")).digest("hex").slice(0, 16)}`;
80
+ }
81
+ const hardDeniedCovers = (p, denied) => denied.some((d) => within(p, d));
82
+ const BASE = `
83
+ ; --- process model: children inherit this profile; no signals or inspection outside it.
84
+ ; What may be executed is listed per turn (see EXEC below); forking is free.
85
+ (allow process-fork)
86
+ (allow signal (target same-sandbox))
87
+ ; deny-default leaves process information open, so it is closed explicitly, then opened to the
88
+ ; turn's own processes (the process itself among them).
89
+ (deny process-info*)
90
+ (allow process-info* (target same-sandbox))
91
+
92
+ ; --- reads: broad, as Claude's and Codex's sandboxes allow (denied directories are carved out below)
93
+ (allow file-read*)
94
+ (allow file-test-existence)
95
+
96
+ ; --- devices and terminals
97
+ (allow file-read* file-write-data file-ioctl
98
+ (literal "/dev/null") (literal "/dev/zero") (literal "/dev/tty") (literal "/dev/dtracehelper")
99
+ (literal "/dev/ptmx") (regex #"^/dev/fd/[0-9]+$"))
100
+ ; (no terminal by pattern: /dev/ttysNNN would reach the person's other sessions; the turn's own, if any, is a parameter)
101
+ (allow pseudo-tty)
102
+
103
+ ; --- sysctls: by name, what the system's libraries, Node, git and the shells read (found from the
104
+ ; sandbox's own denials). No kern.* prefix: kern.proc.* and kern.procargs2 would describe every
105
+ ; process, and the command line and environment of each.
106
+ (allow sysctl-read
107
+ (sysctl-name-prefix "hw.optional.") (sysctl-name-prefix "hw.perflevel")
108
+ (sysctl-name "hw.activecpu") (sysctl-name "hw.byteorder") (sysctl-name "hw.cacheconfig") (sysctl-name "hw.cachelinesize")
109
+ (sysctl-name "hw.cachesize") (sysctl-name "hw.cpufamily") (sysctl-name "hw.cpufrequency") (sysctl-name "hw.cpufrequency_max")
110
+ (sysctl-name "hw.cpusubfamily") (sysctl-name "hw.cpusubtype") (sysctl-name "hw.cputype") (sysctl-name "hw.l1dcachesize")
111
+ (sysctl-name "hw.l1icachesize") (sysctl-name "hw.l2cachesize") (sysctl-name "hw.l3cachesize") (sysctl-name "hw.logicalcpu")
112
+ (sysctl-name "hw.logicalcpu_max") (sysctl-name "hw.machine") (sysctl-name "hw.memsize") (sysctl-name "hw.model") (sysctl-name "hw.ncpu")
113
+ (sysctl-name "hw.nperflevels") (sysctl-name "hw.packages") (sysctl-name "hw.pagesize") (sysctl-name "hw.physicalcpu")
114
+ (sysctl-name "hw.physicalcpu_max") (sysctl-name "hw.tbfrequency") (sysctl-name "hw.vectorunit")
115
+ (sysctl-name "hw.pagesize_compat") (sysctl-name "hw.cachelinesize_compat") (sysctl-name "hw.busfrequency_compat")
116
+ (sysctl-name "hw.cpufrequency_compat") (sysctl-name "hw.tbfrequency_compat") (sysctl-name "hw.l1dcachesize_compat")
117
+ (sysctl-name "hw.l1icachesize_compat") (sysctl-name "hw.l2cachesize_compat") (sysctl-name "hw.l3cachesize_compat")
118
+ (sysctl-name-prefix "machdep.cpu.")
119
+ (sysctl-name "kern.argmax") (sysctl-name "kern.boottime") (sysctl-name "kern.hostname") (sysctl-name "kern.maxfiles")
120
+ (sysctl-name "kern.maxfilesperproc") (sysctl-name "kern.maxproc") (sysctl-name "kern.ngroups") (sysctl-name "kern.osproductversion")
121
+ (sysctl-name "kern.osrelease") (sysctl-name "kern.ostype") (sysctl-name "kern.osvariant_status") (sysctl-name "kern.osversion")
122
+ (sysctl-name "kern.secure_kernel") (sysctl-name "kern.usrstack64") (sysctl-name "kern.version") (sysctl-name "kern.iossupportversion")
123
+ (sysctl-name "kern.safeboot")
124
+ ; read-only limits and versions behind the sysconf() values runtimes read (Python's
125
+ ; multiprocessing: SC_SEM_NSEMS_MAX, SC_AIO_MAX, SC_SAVED_IDS, SC_VERSION). None names a process.
126
+ (sysctl-name-prefix "kern.sysv.") (sysctl-name "kern.aiomax") (sysctl-name "kern.aioprocmax")
127
+ (sysctl-name "kern.saved_ids") (sysctl-name "kern.posix1version")
128
+ (sysctl-name "sysctl.proc_cputype") (sysctl-name "sysctl.name2oid") (sysctl-name "vm.loadavg") (sysctl-name-prefix "net.routetable."))
129
+ (allow sysctl-write (sysctl-name "kern.grade_cputype"))
130
+
131
+ ; --- IPC that libSystem, Node, Rust std and git need. Named POSIX semaphores only under /mp-, the
132
+ ; prefix Python's multiprocessing names its own with (/mp-<random>; decided 2026-10-16): that namespace
133
+ ; is machine-wide, so another process's /mp- semaphore is reachable by its random name, which there
134
+ ; is no call to list; any other name (another program's semaphores) stays closed. No system-fsctl (FSIOC_CAS_BSDFLAGS,
135
+ ; an alternate chflags, would change a file's BSD flags through a mutating fsctl); nothing needs it.
136
+ ; No iokit-open: RootDomainUserClient (IOPMrootDomain) carries power-policy setters, not only queries,
137
+ ; and no harness relay launches opens it (Codex's base and srt allow it for power assertions, which
138
+ ; relay's harnesses do not make).
139
+ (allow ipc-posix-sem (ipc-posix-name-prefix "/mp-"))
140
+ (allow ipc-posix-shm-read* (ipc-posix-name-prefix "apple.cfprefs.") (ipc-posix-name "apple.shm.notification_center"))
141
+ (allow user-preference-read)
142
+ (allow system-mac-syscall (mac-policy-name "vnguard"))
143
+ (allow system-mac-syscall (require-all (mac-policy-name "Sandbox") (mac-syscall-number 67)))
144
+ ; Mach services by global name, each for what it serves every process: user and group lookups
145
+ ; (opendirectoryd), per-user temporary directories (dirhelper), preferences (cfprefsd: allowed because
146
+ ; reads are broad anyway; under narrower reads it would expose files outside them), notifications
147
+ ; (notifyd), and logging (without diagnosticd every process floods the log with denials). The
148
+ ; certificate trust daemons are a per-harness downgrade (TRUST below); nothing else is reachable.
149
+ (allow mach-lookup
150
+ (global-name "com.apple.system.opendirectoryd.libinfo")
151
+ (global-name "com.apple.system.opendirectoryd.membership")
152
+ (global-name "com.apple.system.DirectoryService.libinfo_v1")
153
+ (global-name "com.apple.bsd.dirhelper")
154
+ (global-name "com.apple.cfprefsd.daemon") (global-name "com.apple.cfprefsd.agent")
155
+ (global-name "com.apple.system.notification_center")
156
+ (global-name "com.apple.logd") (global-name "com.apple.system.logger") (global-name "com.apple.diagnosticd"))
157
+ ; the system log's socket: a local log, which Codex's profile allows too (no other Unix socket is
158
+ ; reachable but the turn's own and its bridge, below)
159
+ (allow network-outbound (literal "/private/var/run/syslog"))
160
+ `;
161
+ const KEYCHAIN = `
162
+ ; --- keychain (a stated downgrade: other items its tools are trusted for become readable)
163
+ (allow mach-lookup (global-name "com.apple.SecurityServer") (global-name "com.apple.securityd.xpc")
164
+ (global-name "com.apple.security.agent") (global-name "com.apple.security.keychainsyncingoveridsproxy"))
165
+ ; The keychain-change notification segment is read only: reading it lets a keychain reader notice a
166
+ ; change; writing it is how a keychain modifier announces one, which relay's login-reading harnesses never do.
167
+ (allow ipc-posix-shm-read* (ipc-posix-name "com.apple.AppleDatabaseChanged"))
168
+ `;
169
+ const TRUST = `
170
+ ; --- certificate trust (a stated downgrade: these daemons fetch from URLs their caller supplies, for
171
+ ; revocation and issuer lookups, a way out the network rules do not see). Go's TLS and the Security
172
+ ; framework need them; Node does not.
173
+ (allow mach-lookup (global-name "com.apple.trustd") (global-name "com.apple.trustd.agent") (global-name "com.apple.ocspd"))
174
+ `;
175
+ const NETWORK_ON = `
176
+ ; --- network on: IPv4 anywhere but this Mac's own addresses, and DNS; no IPv6. Still no Unix sockets
177
+ ; but the turn's own and the bridge, and no listening. Creating IP and Unix sockets needs no rule;
178
+ ; kernel-control sockets (AF_SYSTEM, SYSPROTO_CONTROL), which the network stack uses, do. Not every
179
+ ; domain: that would open routing sockets (AF_ROUTE) too.
180
+ ; IPv4 only (review R1, measured on macOS 27.0.1): "localhost" matches this Mac's addresses but not
181
+ ; their IPv4-mapped spellings, loopback's apart, so ::ffff:0.0.0.0 and ::ffff:<an interface address>
182
+ ; reached its services past (remote ip "localhost:*"); only (remote ip6 "*:*") refuses them, all IPv6
183
+ ; with them. No rule says "ip": beside an ip4 or ip6 rule, an "ip" rule matched other addresses (measured).
184
+ (allow network-outbound (remote ip4 "*:*"))
185
+ (deny network-outbound (remote ip4 "localhost:*"))
186
+ (allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))
187
+ (allow mach-lookup (global-name "com.apple.dnssd.service") (global-name "com.apple.mDNSResponder")
188
+ (global-name "com.apple.SystemConfiguration.configd") (global-name "com.apple.SystemConfiguration.DNSConfiguration")
189
+ (global-name "com.apple.networkd") (global-name "com.apple.nehelper"))
190
+ (allow network-outbound (literal "/private/var/run/mDNSResponder"))
191
+ `;
192
+ /**
193
+ * Executables every turn may run, by resolved path: the system's (SIP-protected) and the usual
194
+ * package-manager and developer-tool locations. The harness, relay's own Node (the bridge, the
195
+ * probes), the policy's `execPaths` and the turn's writable directories are added per turn.
196
+ */
197
+ const EXEC_SYSTEM = `
198
+ (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec")
199
+ (subpath "/System/Library") (subpath "/System/Cryptexes") (subpath "/System/Volumes/Preboot/Cryptexes") (subpath "/Library/Apple")
200
+ (subpath "/Library/Developer/CommandLineTools") (regex #"^/Applications/Xcode[^/]*\\.app/Contents/Developer/")
201
+ (subpath "/opt/homebrew") (subpath "/usr/local")`;
202
+ /** A file is allowed by name, a directory with everything under it. */
203
+ const execFilter = (p, param) => {
204
+ let dir = false;
205
+ try {
206
+ dir = fs.statSync(p).isDirectory();
207
+ }
208
+ catch { }
209
+ return dir ? `(subpath ${param})` : `(literal ${param})`;
210
+ };
211
+ /** The interpreter a script names on its `#!` line, when it names one directly (not through `env`). */
212
+ function shebang(file) {
213
+ let fd;
214
+ try {
215
+ fd = fs.openSync(file, "r");
216
+ const buf = Buffer.alloc(256);
217
+ const line = buf.subarray(0, fs.readSync(fd, buf, 0, 256, 0)).toString("latin1").split("\n")[0];
218
+ const m = /^#!\s*(\/\S+)/.exec(line);
219
+ return m && m[1] !== "/usr/bin/env" ? m[1] : undefined;
220
+ }
221
+ catch {
222
+ return undefined;
223
+ }
224
+ finally {
225
+ if (fd !== undefined)
226
+ fs.closeSync(fd);
227
+ }
228
+ }
229
+ /**
230
+ * The resolved paths a policy's boundary is made of, checked: what the profile writes as parameters,
231
+ * and what the host-side checks (hard links, probes) must agree with. `hardDenied` are the paths
232
+ * the profile denies whatever else allows (last-match), among them the denied directories. `fixed`
233
+ * are the paths that may not be removed, renamed or made again (see below).
234
+ *
235
+ * Seatbelt decides by path, and a writable `subpath` also allows unlinking or renaming the root
236
+ * itself and any directory inside it. So a turn could rename its worktree away and leave a link,
237
+ * which the next turn's resolved paths would follow, or carry a protected path out from under its
238
+ * rule (move the worktree into its temp dir, rewrite `.git` there, move it back). Hence `fixed`:
239
+ * every writable root, the worktree, and every ancestor, inside a writable root, of those and of
240
+ * every hard-denied path; the profile denies unlink and create on each, as final rules. And before
241
+ * every turn the worktree and each writable root are checked without following links (rootDir,
242
+ * checkPin), so a swap that got through anyway refuses the turn.
243
+ */
244
+ export function boundaryPaths(policy) {
245
+ const worktree = canonical(policy.worktree, "worktree");
246
+ const tmpDir = canonical(policy.tmpDir, "tmpDir");
247
+ // Relay's control directory is denied whatever the caller passes.
248
+ // So is the directory holding relay's own sockets (every turn's broker, sockets.ts).
249
+ const config = configProtection();
250
+ const relayProtected = [canonical(relayHome(), "relay's control directory"), canonical(relaySocketsDir(), "relay's sockets directory"), ...config.paths.flatMap((p) => [canonical(p, "relay's config or install file"), p]),
251
+ ...relayCredentialProtected().flatMap((p) => [canonical(p.path, p.what), p.path])];
252
+ const denied = [...new Set([...relayProtected, ...policy.denied.map((d, i) => canonical(d, `denied[${i}]`))])];
253
+ // What relay runs outside the sandbox (review r_0c11d860 X1): its own package (dist/, its native
254
+ // helper), the Node it runs on, its git, every target's CLI (name, file, installation) and the
255
+ // directories on its PATH. Readable, since a harness may run them, but never written, whatever
256
+ // the caller passes.
257
+ const installDenied = [...new Set([
258
+ ...relayWriteProtected().flatMap((x) => [canonical(x.path, "relay's installation"), path.resolve(x.path)]),
259
+ ...(policy.writeDenied ?? []).flatMap((p) => [canonical(p, "write-denied runtime tree"), path.resolve(p)]),
260
+ ])].filter((x) => !hardDeniedCovers(x, denied));
261
+ // State directories are the turn's own: anything that outlives the turn is reached only through token files.
262
+ const stateDirs = (policy.stateDirs ?? []).map((p, i) => canonical(p, `stateDirs[${i}]`));
263
+ for (const d of stateDirs)
264
+ if (!within(d, tmpDir))
265
+ throw new Error(`state directory ${d} is not inside the turn's temporary directory ${tmpDir}`);
266
+ const grants = (policy.writable ?? []).map((p, i) => canonical(p, `writable[${i}]`));
267
+ // A granted directory relay pinned at authorisation: it must still be that same directory, reached
268
+ // through real directories only, so an agent granted an ancestor cannot redirect another grant
269
+ // through an intermediate symlink (review C4/X2). When pins are supplied there must be exactly one
270
+ // per grant and each must be valid — a missing or malformed pin fails the turn closed, so a legacy
271
+ // grant authorised before relay pinned grants is refused until the root grants it again (review X2).
272
+ if (policy.writablePins !== undefined) {
273
+ if (policy.writablePins.length !== grants.length) {
274
+ throw new Error(`relay-enforced confinement needs exactly one pin per granted directory (${grants.length} grants, ${policy.writablePins.length} pins). A grant authorised before relay pinned grants must be granted again by the root session.`);
275
+ }
276
+ grants.forEach((g, i) => checkGrantPin(policy.writablePins[i], g, i));
277
+ }
278
+ const granted = [...(policy.worktreeWritable ? [worktree] : []), ...grants, ...stateDirs];
279
+ const persistent = policy.state?.persistent ? persistentState(policy.state.persistent) : null;
280
+ if (persistent) {
281
+ // Read-only means no writable root may reach into it, nor it into one.
282
+ for (const w of [...granted, tmpDir, worktree]) {
283
+ if (within(persistent.root, w) || within(w, persistent.root))
284
+ throw new Error(`relay-owned state ${persistent.root} overlaps ${w}, which would make it writable or put the turn inside it`);
285
+ }
286
+ }
287
+ const writable = [...granted, ...(persistent?.writable ?? []), tmpDir];
288
+ const tokenFiles = (policy.state?.tokenFiles ?? []).map((f, i) => tokenFile(f, `state.tokenFiles[${i}]`));
289
+ // A writable root inside a denied directory would be silently unusable: a mistake in the caller.
290
+ for (const w of [...writable, ...tokenFiles, ...(persistent ? [persistent.root] : [])]) {
291
+ const d = [...denied, ...installDenied].find((x) => within(w, x));
292
+ if (d)
293
+ throw new Error(`writable path ${w} lies inside denied directory ${d}`);
294
+ }
295
+ // Each root as found now, without following links: the worktree when writable or pinned (a read
296
+ // turn's may be the person's own directory, reached through their own link, and carries no
297
+ // writes), against relay's pin when it has one; the grants, the state directories and the temp
298
+ // dir. Persistent state is checked above.
299
+ if (policy.worktreeWritable || policy.worktreePin !== undefined)
300
+ rootDir(policy.worktree, "the worktree");
301
+ if (policy.worktreePin !== undefined)
302
+ checkPin(policy.worktreePin, worktree);
303
+ (policy.writable ?? []).forEach((p, i) => rootDir(p, `writable[${i}]`));
304
+ (policy.stateDirs ?? []).forEach((p, i) => rootDir(p, `stateDirs[${i}]`));
305
+ rootDir(policy.tmpDir, "tmpDir");
306
+ const git = policy.gitEnv ? trustedGitDirs(worktree, policy.gitEnv) : gitDirs(worktree);
307
+ const gitPointer = git.pointer;
308
+ // A .git made between the worktree and the repository's top (the worktree's own included) would
309
+ // hide the real repository from the next turn's discovery: denied wherever it could be written.
310
+ const nestedGitPointers = [];
311
+ for (let dir = worktree; dir !== git.top; dir = path.dirname(dir)) {
312
+ const p = path.join(dir, ".git");
313
+ if (p !== gitPointer && (dir === worktree || writable.some((w) => within(p, w))))
314
+ nestedGitPointers.push(p);
315
+ if (path.dirname(dir) === dir)
316
+ break;
317
+ }
318
+ const gitDenied = [...new Set([git.gitDir, git.commonDir].filter((d) => !!d && d !== gitPointer))];
319
+ // A granted directory may be a git repository of its own (a sibling project granted for writing):
320
+ // its `.git` holds hooks and config that relay's own git, outside the sandbox, may read, so it is
321
+ // hard-denied for every grant, present or not, like the worktree's (review C3).
322
+ const alreadyDenied = (p) => p === gitPointer || hardDeniedCovers(p, [gitPointer, ...nestedGitPointers, ...gitDenied, ...denied]);
323
+ const grantGitPointers = [...new Set(grants.map((g) => path.join(g, ".git")))].filter((p) => !alreadyDenied(p));
324
+ // Harness and tool configuration at the top of each writable root the agent owns (not the temp dir's
325
+ // home or relay-owned state): denied whether present or not. Only the top level. A copy deeper in a
326
+ // subtree is not blocked, though the harnesses do load such copies:
327
+ // - Gemini CLI 0.64.0, in a trusted folder, reads `.gemini/settings.json` from its working
328
+ // directory and `.gemini/.env` from there or the nearest directory above that has one
329
+ // (`_doLoadSettings`, `findEnvFile`);
330
+ // - Codex 0.163.0 loads a `.codex/` layer, hooks included, from every directory between the
331
+ // project root and its working directory, subject to its trust decision for each
332
+ // (config/src/loader/mod.rs, the `cwd.ancestors()` walk), and `.agents/skills` and
333
+ // `.codex/skills` the same way (core/extensions.ts here mirrors it);
334
+ // - Claude Code reads `.claude/settings.json` from its working directory, `.claude/skills` and
335
+ // `.claude/commands` from there up to the repository's top, and nested `.claude/skills` below it
336
+ // as it reads files in that subtree, so a session at the root loads them too (as relay models it
337
+ // in core/claude-settings.ts).
338
+ // Relay starts every turn at the worktree's root and runs Gemini untrusted, so a deeper copy reaches
339
+ // its own turns only through Claude's nested skills; it reaches the person's agents once merged,
340
+ // when one runs in that subdirectory. Denying the names at any depth is possible without a path in
341
+ // the profile (a regex anchored by the root's depth inside `(subpath ROOT)`), but it would also
342
+ // stop legitimate edits (relay's own adapters/codex/.agents, a monorepo's per-package skills); the
343
+ // decision is deferred, for .claude, .codex, .agents and .gemini together.
344
+ const configRoots = [...(policy.worktreeWritable ? [worktree] : []), ...grants];
345
+ const configDenied = [...new Set(configRoots.flatMap((w) => HARNESS_CONFIG.map((n) => path.join(w, n))))]
346
+ .filter((c) => c !== gitPointer && !hardDeniedCovers(c, [gitPointer, ...nestedGitPointers, ...gitDenied, ...denied]) && !grantGitPointers.some((g) => within(c, g)));
347
+ const hardDenied = [gitPointer, ...nestedGitPointers, ...gitDenied, ...grantGitPointers, ...denied, ...installDenied];
348
+ // A token file's allow names file-write-data, which the hard denies (file-write*) would not override
349
+ // (see the top): one inside a denied or protected path would be writable there, so it is refused.
350
+ for (const t of tokenFiles) {
351
+ const inside = [...hardDenied, ...configDenied].find((d) => within(t, d));
352
+ if (inside)
353
+ throw new Error(`token file ${t} lies inside ${inside}, which the sandbox protects, so relay does not make it writable`);
354
+ }
355
+ // A login store's allows name operations too: it must stay clear of every path the profile writes
356
+ // or protects, either way round, or a rule meant for one would decide for the other. (A read
357
+ // turn's worktree is neither, so it may hold the store: a read job from the home folder.)
358
+ const store = policy.state?.tokenStore ? tokenStore(policy.state.tokenStore) : null;
359
+ if (store) {
360
+ // Not the installation's denies: they name every operation the store's allows name and come after
361
+ // them, so they win either way round (Grok keeps its binary in ~/.grok/bin, inside its store).
362
+ const clash = [...writable, ...(persistent ? [persistent.root] : []), ...tokenFiles, ...hardDenied.filter((d) => !installDenied.includes(d)), ...configDenied]
363
+ .find((o) => within(o, store.dir) || within(store.dir, o));
364
+ if (clash)
365
+ throw new Error(`${store.name} (${store.dir}) overlaps ${clash}, which the sandbox writes or protects, so relay does not open it`);
366
+ }
367
+ const fixed = new Set();
368
+ for (const p of [...writable, worktree, ...hardDenied]) {
369
+ // Up from each, while inside a writable root: once outside every one, so is every ancestor.
370
+ for (let a = p; writable.some((w) => within(a, w)); a = path.dirname(a)) {
371
+ fixed.add(a);
372
+ if (path.dirname(a) === a)
373
+ break;
374
+ }
375
+ }
376
+ // Relay's own directories (its control directory and its sockets directory) cannot be moved either,
377
+ // from anywhere above them: their ancestors, outside the writable roots too.
378
+ const relayAncestors = new Set();
379
+ for (const d of [...denied.slice(0, 2), ...config.directories, ...installDenied])
380
+ for (let a = path.dirname(d); a !== path.dirname(a); a = path.dirname(a))
381
+ relayAncestors.add(a);
382
+ return {
383
+ worktree, tmpDir, denied, installDenied, writable, tokenFiles, persistent, gitPointer, nestedGitPointers, grantGitPointers, gitDir: git.gitDir, commonDir: git.commonDir,
384
+ hardDenied, fixed: [...fixed], relayAncestors: [...relayAncestors].filter((a) => !fixed.has(a)), configDenied, store,
385
+ };
386
+ }
387
+ /** What relay records for a directory it has just created (a job's worktree), to pin it across turns. */
388
+ export function dirIdentity(p) {
389
+ const real = canonical(p, "directory");
390
+ const st = fs.lstatSync(real);
391
+ if (!st.isDirectory())
392
+ throw new Error(`${real} is not a directory`);
393
+ return { path: real, dev: st.dev, ino: st.ino };
394
+ }
395
+ const isOwn = (st) => typeof process.getuid !== "function" || st.uid === process.getuid();
396
+ /** Every component of an absolute path from `from` down, looked at without following links: each a real directory. */
397
+ function realDirs(p, what, from = path.parse(p).root) {
398
+ let at = from;
399
+ for (const part of path.relative(from, p).split(path.sep).filter(Boolean)) {
400
+ at = path.join(at, part);
401
+ const st = fs.lstatSync(at, { throwIfNoEntry: false });
402
+ if (!st)
403
+ throw new Error(`${what}: ${at} is missing`);
404
+ if (st.isSymbolicLink())
405
+ throw new Error(`${what}: ${at} is a symbolic link, which the sandbox would follow, so relay does not run on it`);
406
+ if (!st.isDirectory())
407
+ throw new Error(`${what}: ${at} is not a directory`);
408
+ }
409
+ }
410
+ /**
411
+ * A writable root or the worktree, as named, checked before every turn without following links: it
412
+ * must exist and be a directory itself, not a link (a turn that swapped it for one would carry the
413
+ * next turn's writes wherever it points), and be this user's own.
414
+ */
415
+ function rootDir(p, what) {
416
+ const at = path.resolve(p);
417
+ const st = fs.lstatSync(at, { throwIfNoEntry: false });
418
+ if (!st)
419
+ throw new Error(`${what} is missing: ${at}. A writable directory must exist before the turn, or the agent could make it a link`);
420
+ if (st.isSymbolicLink())
421
+ throw new Error(`${what} is a symbolic link: ${at}. The sandbox would follow it, so relay does not run on it`);
422
+ if (!st.isDirectory())
423
+ throw new Error(`${what} is not a directory: ${at}`);
424
+ if (!isOwn(st))
425
+ throw new Error(`${what} is not owned by this user: ${at}`);
426
+ }
427
+ /**
428
+ * A granted directory relay pinned at authorisation: the pin's path must still be reached through
429
+ * real directories only and still be that same directory (device and inode), the person's own, and
430
+ * the grant must still resolve to exactly it. A symlink put at any component since would make the
431
+ * resolved path differ, or make a component not a real directory; either refuses the turn.
432
+ */
433
+ export function checkGrantPin(pin, resolved, i) {
434
+ const what = `the directory relay granted for writable[${i}]`;
435
+ if (!pin || typeof pin.path !== "string" || !path.isAbsolute(pin.path) || !Number.isFinite(pin.dev) || !Number.isFinite(pin.ino)) {
436
+ throw new Error(`the pin for writable[${i}] is not a pinned directory: ${JSON.stringify(pin)}`);
437
+ }
438
+ realDirs(pin.path, what);
439
+ const st = fs.lstatSync(pin.path);
440
+ if (st.dev !== pin.dev || st.ino !== pin.ino)
441
+ throw new Error(`${what} (${pin.path}) is not the directory relay granted (it has been replaced since), so relay does not run on it`);
442
+ if (!isOwn(st))
443
+ throw new Error(`${what} (${pin.path}) is not owned by this user`);
444
+ if (resolved !== pin.path)
445
+ throw new Error(`writable[${i}] now resolves to ${resolved}, not the ${pin.path} relay granted (an intermediate component has been changed to a link), so relay does not run on it`);
446
+ }
447
+ /** Applied by native backends too, immediately before constructing their launch policy. */
448
+ export function checkWriteGrant(paths, pins = []) {
449
+ if (pins.length !== paths.length)
450
+ throw new Error("write paths need exactly one recorded directory pin each; the root session must grant these paths again");
451
+ paths.forEach((p, i) => checkGrantPin(pins[i], canonical(p, `writable[${i}]`), i));
452
+ }
453
+ /**
454
+ * The worktree's root as relay created it: the pinned path must still be reached through real
455
+ * directories only and still be the same directory (device and inode), the person's own, and the
456
+ * worktree must lie inside it, reached from it through real directories too.
457
+ */
458
+ function checkPin(pin, worktree) {
459
+ if (!pin || typeof pin.path !== "string" || !path.isAbsolute(pin.path) || !Number.isFinite(pin.dev) || !Number.isFinite(pin.ino)) {
460
+ throw new Error(`the worktree's pin is not a pinned directory: ${JSON.stringify(pin)}`);
461
+ }
462
+ realDirs(pin.path, "the directory relay pinned for the worktree");
463
+ const st = fs.lstatSync(pin.path);
464
+ if (st.dev !== pin.dev || st.ino !== pin.ino)
465
+ throw new Error(`${pin.path} is not the directory relay created for this job (it has been replaced since), so relay does not run on it`);
466
+ if (!isOwn(st))
467
+ throw new Error(`${pin.path} is not owned by this user`);
468
+ if (!within(worktree, pin.path))
469
+ throw new Error(`the worktree ${worktree} is not inside the directory relay pinned for it (${pin.path}), so relay does not run on it`);
470
+ realDirs(worktree, "the worktree", pin.path);
471
+ }
472
+ /**
473
+ * The repository the worktree belongs to: the first `.git` found walking up from the worktree, as git
474
+ * itself finds it (a turn may start in a subdirectory). `pointer` is that `.git` (or the worktree's
475
+ * own, where there is none), `top` the directory holding it; `gitDir` the worktree's git directory
476
+ * and `commonDir` the repository's shared one, read from the pointer and the git directory's
477
+ * `commondir` file, which the sandbox never lets the agent write. Undefined where there is none.
478
+ */
479
+ function gitDirs(worktree) {
480
+ for (let dir = worktree;; dir = path.dirname(dir)) {
481
+ const pointer = path.join(dir, ".git");
482
+ const st = fs.lstatSync(pointer, { throwIfNoEntry: false });
483
+ if (st)
484
+ return { pointer, top: dir, ...gitDirsAt(dir, pointer, st) };
485
+ if (path.dirname(dir) === dir)
486
+ return { pointer: path.join(worktree, ".git") };
487
+ }
488
+ }
489
+ /**
490
+ * The same, for a turn in a job's worktree, from the git directories the repository records for it
491
+ * (the trusted git env relay's own git uses, git.ts jobTree), never from the worktree's `.git` file,
492
+ * which the job's agent can rewrite: a pointer it aimed elsewhere would have the profile deny that
493
+ * place and leave the real git directories writable. `commondir` is read from the recorded git
494
+ * directory, inside the repository's own, which no agent can write.
495
+ */
496
+ function trustedGitDirs(worktree, env) {
497
+ const top = canonical(env.GIT_WORK_TREE, "the worktree relay's git runs in");
498
+ if (!within(worktree, top))
499
+ throw new Error(`the turn's directory ${worktree} is not inside the worktree relay's git runs in (${top})`);
500
+ const gitDir = canonical(env.GIT_DIR, "the worktree's git directory");
501
+ return { pointer: path.join(top, ".git"), top, gitDir, commonDir: commonDirOf(gitDir) };
502
+ }
503
+ /** The repository's shared git directory, from a worktree git directory's `commondir` file; the git directory itself when it has none (a main checkout). */
504
+ function commonDirOf(gitDir) {
505
+ try {
506
+ return canonical(path.resolve(gitDir, fs.readFileSync(path.join(gitDir, "commondir"), "utf8").trim()), "the repository's git directory");
507
+ }
508
+ catch (err) {
509
+ if (err.code !== "ENOENT")
510
+ throw err;
511
+ return gitDir;
512
+ }
513
+ }
514
+ function gitDirsAt(top, pointer, st) {
515
+ if (st.isDirectory())
516
+ return { gitDir: pointer, commonDir: pointer };
517
+ if (!st.isFile())
518
+ throw new Error(`.git is neither a file nor a directory: ${pointer}`);
519
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(fs.readFileSync(pointer, "utf8"));
520
+ if (!m)
521
+ return {};
522
+ const raw = path.resolve(top, m[1]);
523
+ if (!fs.existsSync(raw))
524
+ return {};
525
+ const gitDir = canonical(raw, "the worktree's git directory");
526
+ return { gitDir, commonDir: commonDirOf(gitDir) };
527
+ }
528
+ /** The profile for a policy's shape, and the parameters that carry its paths. `harness` is the command the launch runs. */
529
+ export function seatbeltProfile(policy, harness) {
530
+ const params = [];
531
+ const param = (name, value) => {
532
+ params.push([name, value]);
533
+ return `(param "${name}")`;
534
+ };
535
+ const { tmpDir, denied, installDenied, writable, tokenFiles, gitPointer, nestedGitPointers, grantGitPointers, gitDir, commonDir, fixed, relayAncestors, configDenied, store } = boundaryPaths(policy);
536
+ let proxyPort;
537
+ if (policy.network.mode === "off-except-proxy") {
538
+ proxyPort = policy.network.proxyPort;
539
+ if (!Number.isInteger(proxyPort) || proxyPort < 1 || proxyPort > 65535)
540
+ throw new Error(`proxy port is not a port: ${proxyPort}`);
541
+ if (typeof policy.network.proxyToken !== "string" || !PROXY_TOKEN.test(policy.network.proxyToken))
542
+ throw new Error("the proxy token is missing or not a per-turn token");
543
+ }
544
+ else if (policy.network.mode !== "on" && policy.network.mode !== "stage2") {
545
+ throw new Error(`unknown network mode ${policy.network.mode}`);
546
+ }
547
+ // Every deny carries the turn's tag, so relay can stream exactly this turn's denials from the
548
+ // system log and a harness the profile stops says which rule stopped it (diagnostics.ts, review C4).
549
+ const diagMsg = `(with message ${param("DIAG_TAG", diagnosticTag(policy))})`;
550
+ const L = ["(version 1)", `(deny default ${diagMsg})`, BASE.replace("(deny process-info*)", `(deny process-info* ${diagMsg})`)];
551
+ if (policy.keychain)
552
+ L.push(KEYCHAIN);
553
+ if (policy.certificateTrust)
554
+ L.push(TRUST);
555
+ // Executables: the fixed list, then this turn's. Writable directories stay executable so that the
556
+ // agent can run what it builds; see "What the exec list does not do" in docs/architecture.md.
557
+ const exec = [
558
+ ...(harness ? [["HARNESS", canonical(harness, "the harness command")]] : []),
559
+ ...(harness && shebang(harness) ? [["INTERPRETER", canonical(shebang(harness), "the harness's interpreter")]] : []),
560
+ ["RELAY_NODE", canonical(process.execPath, "relay's Node")],
561
+ ...(policy.execPaths ?? []).map((p, i) => [`EXEC_${i}`, canonical(p, `execPaths[${i}]`)]),
562
+ ];
563
+ L.push(`; --- executables\n(allow process-exec${EXEC_SYSTEM}\n ${exec.map(([k, v]) => execFilter(v, param(k, v))).join(" ")}\n ${writable.map((_, i) => `(subpath (param "WRITABLE_${i}"))`).join(" ")})`);
564
+ L.push(`; --- writes: these directories only\n(allow file-write*\n ${writable.map((w, i) => `(subpath ${param(`WRITABLE_${i}`, w)})`).join("\n ")})`);
565
+ (policy.overlayFiles ?? []).forEach((root, i) => {
566
+ assertOverlayRoot(root);
567
+ if (root.scope !== "file")
568
+ throw new Error("overlayFiles requires exact files");
569
+ const file = param(`OVERLAY_FILE_${i}`, root.root);
570
+ L.push(`(allow file-write* (literal ${file}))`);
571
+ L.push(`(deny file-link (literal ${file}) ${diagMsg})\n(deny file-write-create (require-all (literal ${file}) (vnode-type SYMLINK)) ${diagMsg})`);
572
+ });
573
+ // Unix sockets of the turn's own, under its temp dir: made, listened on and connected to there only.
574
+ const tmp = param("TMPDIR", tmpDir);
575
+ L.push(`; --- the turn's own Unix sockets\n(allow network-bind (local unix-socket (subpath ${tmp})))\n(allow network-outbound (remote unix-socket (subpath ${tmp})))`);
576
+ if (tokenFiles.length) {
577
+ L.push(`; --- the harness's login token files in its real store: their data only, nothing beside them\n(allow file-write-data\n ${tokenFiles.map((f, i) => `(literal ${param(`TOKEN_FILE_${i}`, f)})`).join("\n ")})`);
578
+ }
579
+ if (store) {
580
+ // A login store (TokenStore, a stated downgrade): its exact names and its temp names, as regular
581
+ // files, and the modes of its temp and token files, which a refresh sets (Grok: fs_atomic.rs).
582
+ // Measured on decoys (docs/design-token-store.md): the denies name the operations they mean and
583
+ // come after the allows, since a file-write* deny would not override these (see the top).
584
+ const dir = param("TOKEN_STORE", store.dir);
585
+ const names = [
586
+ ...store.files.map((f, i) => `(literal ${param(`TOKEN_STORE_FILE_${i}`, f)})`),
587
+ ...store.locks.map((f, i) => `(literal ${param(`TOKEN_STORE_LOCK_${i}`, f)})`),
588
+ // The one pattern written into the profile: of the reviewed form tokenStore checks, never a path.
589
+ `(require-all (subpath ${dir}) (regex #"${store.temp}"))`,
590
+ ];
591
+ L.push([
592
+ "; --- the harness's login store: its token, lock and temp names, regular files only; nothing else in it",
593
+ `(allow file-write-data\n ${names.join("\n ")})`,
594
+ `(allow file-write-create\n ${names.map((n) => `(require-all (vnode-type REGULAR-FILE) ${n})`).join("\n ")})`,
595
+ // Unlink only where a rename needs it: the token (replaced by the rename) and temp names (moved
596
+ // from). Not the lock, which Grok never removes: an exchange (renamex_np RENAME_SWAP) needs an
597
+ // unlink at the name, and could otherwise put a link there that the harness, outside the
598
+ // sandbox, would open and write through (measured; review r_75bf1f48).
599
+ `(allow file-write-unlink\n ${[...names.slice(0, store.files.length), names.at(-1)].join("\n ")})`,
600
+ // Modes: a temp file's, set before its rename, and the token's, made owner-only after it and on
601
+ // every read (Grok); no more than a temp file's mode and a rename already allow.
602
+ `(allow file-write-mode\n ${[...names.slice(0, store.files.length), names.at(-1)].join("\n ")})`,
603
+ `(deny file-write-create (require-all (subpath ${dir}) (vnode-type SYMLINK)) ${diagMsg})`,
604
+ `(deny file-link (subpath ${dir}) ${diagMsg})`,
605
+ ...store.subdirs.map((d, j) => `(deny file-write-create file-write-data file-write-unlink file-write-mode (subpath ${param(`TOKEN_STORE_SUBDIR_${j}`, d)}) ${diagMsg})`),
606
+ ].join("\n"));
607
+ }
608
+ if (policy.network.mode === "stage2") {
609
+ // Stage 2 (WP-A): its own network block, every port and path a parameter. Worktree sockets only
610
+ // on a write turn in a worktree relay made and pinned (review C4). No certificate trust: trustd
611
+ // fetches the URLs a certificate names, past every rule here (§3.1).
612
+ if (policy.network.worktreeSockets && !(policy.worktreeWritable && policy.worktreePin))
613
+ throw new Error("stage 2 allows Unix sockets in the worktree only on write turns in a worktree relay created and pinned");
614
+ if (policy.certificateTrust)
615
+ throw new Error("stage 2 does not run with certificate trust: trustd would fetch URLs past the profile's network rules");
616
+ L.push(stage2NetworkRules(policy.network, param, diagMsg, { tmpDir, worktree: canonical(policy.worktree, "worktree") }));
617
+ }
618
+ else if (policy.network.mode === "on") {
619
+ L.push(NETWORK_ON.replace('(deny network-outbound (remote ip4 "localhost:*"))', `(deny network-outbound (remote ip4 "localhost:*") ${diagMsg})`));
620
+ }
621
+ else {
622
+ // A validated integer, so it is written into the profile; no DNS, which would be a channel out.
623
+ L.push(`; --- network off except relay's CONNECT proxy\n(allow network-outbound (remote tcp "localhost:${proxyPort}"))`);
624
+ }
625
+ // Hard denies, last so that they win.
626
+ const git = param("GIT_POINTER", gitPointer);
627
+ L.push(`; --- hard denies (last match wins)\n; the worktree's .git: host-side git must never be redirected or given hooks or config by the agent\n(deny file-write* (literal ${git}) (subpath ${git}) ${diagMsg})`);
628
+ // The worktree's git directory and the repository's shared one hold config and hooks that relay's
629
+ // own git, outside the sandbox, reads: never writable, whatever a grant covers.
630
+ if (gitDir && gitDir !== gitPointer)
631
+ L.push(`(deny file-write* (subpath ${param("GIT_DIR", gitDir)}) ${diagMsg})`);
632
+ if (commonDir && commonDir !== gitPointer && commonDir !== gitDir)
633
+ L.push(`(deny file-write* (subpath ${param("GIT_COMMON_DIR", commonDir)}) ${diagMsg})`);
634
+ // A .git of its own below the repository's would hide the real one from the next turn's discovery.
635
+ nestedGitPointers.forEach((p, i) => L.push(`(deny file-write* (literal ${param(`NESTED_GIT_${i}`, p)}) (subpath (param "NESTED_GIT_${i}")) ${diagMsg})`));
636
+ // A granted repository's own .git (hooks, config): never writable, present or not (review C3).
637
+ grantGitPointers.forEach((p, i) => L.push(`(deny file-write* (literal ${param(`GRANT_GIT_${i}`, p)}) (subpath (param "GRANT_GIT_${i}")) ${diagMsg})`));
638
+ // Denied directories, relay's control and sockets directories first: nothing in them read, written
639
+ // or connected to (another turn's broker socket included).
640
+ // file-test-existence by name: the base allows it unfiltered, and file-read* would not override that (see the top).
641
+ denied.forEach((d, i) => L.push(`(deny file-read* file-write* file-test-existence (subpath ${param(`DENIED_${i}`, d)}) ${diagMsg})\n(deny network-outbound (remote unix-socket (subpath (param "DENIED_${i}"))) ${diagMsg})`));
642
+ // What relay runs outside the sandbox and its PATH: never written, created, removed or renamed
643
+ // (review r_0c11d860 X1). Each operation named as well, so no operation-specific allow could
644
+ // outrank it (see the top).
645
+ if (installDenied.length)
646
+ L.push(`; --- relay's installation, which relay runs outside the sandbox\n(deny file-write* file-write-data file-write-create file-write-unlink file-write-mode file-link\n ${installDenied.map((d, i) => `(literal ${param(`INSTALL_${i}`, d)}) (subpath (param "INSTALL_${i}"))`).join("\n ")} ${diagMsg})`);
647
+ if (relayAncestors.length)
648
+ L.push(`(deny file-write-unlink file-write-create\n ${relayAncestors.map((a, i) => `(literal ${param(`RELAY_ANCESTOR_${i}`, a)})`).join("\n ")} ${diagMsg})`);
649
+ // Harness and tool configuration at the top of each writable root: never written, created or removed.
650
+ if (configDenied.length)
651
+ L.push(`; --- harness and tool configuration an agent could plant\n(deny file-write*\n ${configDenied.map((c, i) => `(literal ${param(`CONFIG_${i}`, c)}) (subpath (param "CONFIG_${i}"))`).join("\n ")} ${diagMsg})`);
652
+ // Writable roots, the worktree, and the ancestors of protected paths inside writable roots: never
653
+ // removed, renamed (rename needs unlink at the source, create at the destination) or made again,
654
+ // so no rule's path can be moved out from under it (see boundaryPaths).
655
+ if (fixed.length)
656
+ L.push(`(deny file-write-unlink file-write-create\n ${fixed.map((f, i) => `(literal ${param(`FIXED_${i}`, f)})`).join("\n ")} ${diagMsg})`);
657
+ // Terminals: reads are broad, so the person's other sessions' terminals are denied explicitly,
658
+ // reading included; then the turn's own, if it has one, by name.
659
+ // Existence tests stay allowed here (the base allows them unfiltered): which terminals exist is no
660
+ // secret (/dev is listable), and openpty tests a new one's name before its extension applies.
661
+ L.push(`(deny file-read* file-write* file-ioctl (regex #"^/dev/ttys[0-9]+$") ${diagMsg})`);
662
+ // A pseudo-terminal the turn opens itself (through /dev/ptmx) carries the kernel's sandbox
663
+ // extension for it, which no other terminal has.
664
+ // This rule is from OpenAI Codex (codex-rs/sandboxing/src/seatbelt.rs at 0e67502), Copyright 2025
665
+ // OpenAI, licensed under the Apache License, Version 2.0; copied unchanged. The licence and Codex's
666
+ // NOTICE are in LICENSES/ (Apache-2.0.txt, codex-NOTICE.txt; see LICENSES/README.md).
667
+ L.push(`(allow file-read* file-write* file-ioctl (require-all (regex #"^/dev/ttys[0-9]+$") (extension "com.apple.sandbox.pty")))`);
668
+ if (policy.tty !== undefined) {
669
+ if (typeof policy.tty !== "string" || !/^\/dev\/ttys[0-9]+$/.test(policy.tty))
670
+ throw new Error(`tty must be the turn's own pseudo-terminal, /dev/ttysNNN: ${JSON.stringify(policy.tty)}`);
671
+ L.push(`(allow file-read* file-write-data file-ioctl (literal ${param("TTY", policy.tty)}))`);
672
+ }
673
+ // The turn's bridge to relay, after the denies above: the one socket in relay's sockets directory it may reach.
674
+ if (policy.bridgeSocket !== undefined) {
675
+ // Its path's existence too: connecting looks the name up, which the sockets directory's deny of
676
+ // existence tests would otherwise refuse (measured: the socket's own name is enough).
677
+ L.push(`; --- the turn's bridge to relay\n(allow network-outbound (remote unix-socket (path-literal ${param("BRIDGE_SOCKET", canonical(policy.bridgeSocket, "bridgeSocket"))})))\n(allow file-test-existence (literal (param "BRIDGE_SOCKET")))`);
678
+ }
679
+ // The bridge secret's file, for a harness whose own tool helper presents it (Gemini's tool
680
+ // discovery): by name, beside the turn's own socket, after the denies above. Reading it, its
681
+ // status and the lookup of its name; nothing else in the broker directory, which stays denied
682
+ // (listing it included), and nothing written. Another turn's profile names no such file.
683
+ if (policy.bridgeSecret !== undefined) {
684
+ if (policy.bridgeSocket === undefined)
685
+ throw new Error("bridgeSecret needs bridgeSocket: the secret's file is the turn's own only beside its own socket");
686
+ const secret = canonical(policy.bridgeSecret, "bridgeSecret");
687
+ const socket = canonical(policy.bridgeSocket, "bridgeSocket");
688
+ if (path.dirname(secret) !== path.dirname(socket) || secret === socket)
689
+ throw new Error(`bridgeSecret must be a file beside the turn's bridge socket, in its broker directory ${path.dirname(socket)}: ${JSON.stringify(policy.bridgeSecret)}`);
690
+ if (!within(secret, canonical(relaySocketsDir(), "relay's sockets directory")))
691
+ throw new Error(`bridgeSecret must be in relay's sockets directory, which every other turn's profile denies: ${JSON.stringify(policy.bridgeSecret)}`);
692
+ L.push(`; --- the bridge secret's file, the turn's own\n(allow file-read-data file-read-metadata file-test-existence (literal ${param("BRIDGE_SECRET_FILE", secret)}))`);
693
+ }
694
+ // LaunchServices and AppleEvents would start processes outside the sandbox.
695
+ L.push(`(deny mach-lookup (global-name "com.apple.coreservices.launchservicesd") (global-name "com.apple.coreservices.appleevents") ${diagMsg})`);
696
+ // No XPC service of any name, whatever a rule above allows: a final rule, so that no later
697
+ // downgrade can open them by accident.
698
+ L.push(`(deny mach-lookup (xpc-service-name-prefix "") ${diagMsg})`);
699
+ // F_MAKECOMPRESSED (80) and F_TRANSFEREXTENTS (110) change a file through a descriptor opened
700
+ // read-only, so reads being broad would make every readable file changeable. "deny default" does
701
+ // not cover them (fcntl is allowed unless a rule names the command), hence an explicit rule.
702
+ L.push(`(deny system-fcntl (fcntl-command ${F_MAKECOMPRESSED} ${F_TRANSFEREXTENTS}) ${diagMsg})`);
703
+ if (policy.neverPolicy)
704
+ L.push(...neverSeatbeltRules(policy.neverPolicy, param, diagMsg, {
705
+ worktree: canonical(policy.worktree, "worktree"), tmpDir,
706
+ ...(policy.network.mode === "stage2" ? { execPort: policy.network.execPort, bindPorts: policy.network.bindPorts, mediatedPort: policy.network.mediatedPort } : {}),
707
+ }));
708
+ return { profile: L.join("\n") + "\n", params };
709
+ }
710
+ /** The path a token file is named by, with its directory resolved and its own name not followed. */
711
+ function tokenPath(f, what) {
712
+ const p = typeof f === "string" ? f : f?.path;
713
+ if (typeof p !== "string" || !p)
714
+ throw new Error(`${what} is empty`);
715
+ return path.join(canonical(path.dirname(p), what), path.basename(p));
716
+ }
717
+ /** What relay records for a token file at trusted setup, to pin it across turns. Looks at the file's identity only; never opens it. */
718
+ export function tokenFileIdentity(p) {
719
+ const real = tokenPath(p, "token file");
720
+ const st = fs.lstatSync(real);
721
+ return { path: real, dev: st.dev, ino: st.ino };
722
+ }
723
+ /**
724
+ * A token file the harness may rewrite in place, checked before every turn without following
725
+ * links: it must exist, be a regular file (not a link, directory or executable) with exactly one
726
+ * name, owned by this user and, when pinned, still the file relay set up. The profile then allows
727
+ * only data writes to it (truncate, write, append): no unlink, rename, create, link or mode change,
728
+ * so the agent cannot swap it for a link that a later turn's profile would follow. Relay looks at
729
+ * the file's metadata only; it never opens it.
730
+ */
731
+ export function tokenFile(f, what) {
732
+ const real = tokenPath(f, what);
733
+ const st = fs.lstatSync(real, { throwIfNoEntry: false });
734
+ if (!st)
735
+ throw new Error(`${what} is missing: ${real}. A token file must exist before the turn; the sandbox lets the harness rewrite it, not create it`);
736
+ if (st.isSymbolicLink())
737
+ throw new Error(`${what} is a symbolic link: ${real}. Relay grants writes to the file itself, never through a link, so it does not run on this`);
738
+ if (!st.isFile())
739
+ throw new Error(`${what} is not a regular file: ${real}. Only specific token files can be writable, never directories`);
740
+ if (st.mode & 0o111)
741
+ throw new Error(`${what} is executable: ${real}. Token files only, never binaries or scripts`);
742
+ if (st.nlink !== 1)
743
+ throw new Error(`${what} has ${st.nlink} hard links: ${real}. Another name for it could be outside the store, so relay does not run on it`);
744
+ if (typeof process.getuid === "function" && st.uid !== process.getuid())
745
+ throw new Error(`${what} is not owned by this user: ${real}`);
746
+ if (typeof f !== "string" && (st.dev !== f.dev || st.ino !== f.ino)) {
747
+ throw new Error(`${what} is not the file relay set up (${real} has been replaced since), so relay does not run on it`);
748
+ }
749
+ return real;
750
+ }
751
+ /** A login store's temp-name pattern: anchored; literals, `\.` and character classes, each perhaps repeated; one at least repeated. */
752
+ const TEMP_ATOM = String.raw `(?:[A-Za-z0-9_-]|\\\.|\[[A-Za-z0-9-]+\])[+*]?`;
753
+ const TEMP_NAME = new RegExp(String.raw `^\^(?:${TEMP_ATOM})+\$$`);
754
+ /** A name in a login store: one plain component. */
755
+ const STORE_ENTRY = /^(?!\.\.?$)[A-Za-z0-9._-]+$/;
756
+ /**
757
+ * Checks a login store (TokenStore) before a turn, without following links, and returns what the
758
+ * profile is written from. Every name relay would make writable that exists (the files, the locks
759
+ * and every name matching the temp pattern) must be a regular file with one name, the person's own
760
+ * and not executable: a hard link planted there before the turn would carry the turn's writes to the
761
+ * file's other name (measured; review r_64e5a9ce X1). Relay looks at metadata only, never opens a
762
+ * file there, and deletes nothing: an unsafe entry refuses the turn and is named.
763
+ */
764
+ function inspectTokenStore(s, what = "state.tokenStore") {
765
+ if (!s || typeof s !== "object")
766
+ throw new Error(`${what} is not a login store`);
767
+ if (typeof s.name !== "string" || !/^[^\0\r\n]{1,80}$/.test(s.name))
768
+ throw new Error(`${what}.name must be one line: ${JSON.stringify(s.name)}`);
769
+ if (typeof s.dir !== "string" || !path.isAbsolute(s.dir) || /[\0\r\n]/.test(s.dir))
770
+ throw new Error(`${what}.dir must be an absolute path: ${JSON.stringify(s.dir)}`);
771
+ const top = fs.lstatSync(s.dir, { throwIfNoEntry: false });
772
+ if (!top || top.isSymbolicLink() || !top.isDirectory())
773
+ throw new Error(`${s.name} (${s.dir}) is ${top ? "not a plain directory" : "missing"}; relay makes a login store writable only where it is a real directory`);
774
+ if (typeof process.getuid === "function" && top.uid !== process.getuid())
775
+ throw new Error(`${s.name} (${s.dir}) is not owned by this user`);
776
+ if (top.mode & 0o022)
777
+ throw new Error(`${s.name} (${s.dir}) is writable by others (mode ${(top.mode & 0o777).toString(8)})`);
778
+ const dir = canonical(s.dir, `${what}.dir`);
779
+ const names = (list, field) => {
780
+ if (!Array.isArray(list))
781
+ throw new Error(`${what}.${field} must be a list of names`);
782
+ return list.map((n, i) => {
783
+ if (typeof n !== "string" || !STORE_ENTRY.test(n))
784
+ throw new Error(`${what}.${field}[${i}] must be a plain file name: ${JSON.stringify(n)}`);
785
+ return n;
786
+ });
787
+ };
788
+ const files = names(s.files, "files");
789
+ const locks = names(s.locks, "locks");
790
+ if (!files.length)
791
+ throw new Error(`${what} names no file`);
792
+ if (new Set([...files, ...locks]).size !== files.length + locks.length)
793
+ throw new Error(`${what} names a file twice`);
794
+ if (typeof s.tempName !== "string" || !TEMP_NAME.test(s.tempName) || !/[+*]/.test(s.tempName)) {
795
+ throw new Error(`${what}.tempName must be an anchored pattern of literals, \\. and character classes, one at least repeated: ${JSON.stringify(s.tempName)}`);
796
+ }
797
+ // A class's range must not take in "/", so that the pattern cannot match across a path (review r_75bf1f48 C4).
798
+ for (const [, cls] of s.tempName.matchAll(/\[([A-Za-z0-9-]+)\]/g)) {
799
+ for (let i = 0; i < cls.length; i++) {
800
+ if (cls[i + 1] === "-" && i + 2 < cls.length) {
801
+ if (cls.charCodeAt(i) <= 0x2f && cls.charCodeAt(i + 2) >= 0x2f)
802
+ throw new Error(`${what}.tempName has a class whose range takes in "/": ${JSON.stringify(s.tempName)}`);
803
+ i += 2;
804
+ }
805
+ }
806
+ }
807
+ const tempName = new RegExp(s.tempName);
808
+ for (const n of [".", "..", ...files, ...locks])
809
+ if (tempName.test(n))
810
+ throw new Error(`${what}.tempName matches ${JSON.stringify(n)}`);
811
+ if (tempName.test(path.basename(dir)))
812
+ throw new Error(`${what}.tempName matches the store's own name, ${path.basename(dir)}, which would let the store itself be removed`);
813
+ const entries = fs.readdirSync(dir);
814
+ const problems = [];
815
+ // A volume that ignores case or Unicode form in names (macOS's default) reaches AUTH.json through
816
+ // auth.json, so a name relay makes writable reaches whatever entry folds to it (measured: writes
817
+ // through auth.json reached an outside file planted as AUTH.json; review r_75bf1f48 C1). Each
818
+ // declared name is looked up as the turn will, and must reach an entry of exactly that name; and
819
+ // every entry that folds to a declared or temp name is checked as one, and must be exactly one.
820
+ const fold = (n) => n.normalize("NFC").toUpperCase().toLowerCase();
821
+ const folded = new Set([...files, ...locks].map(fold));
822
+ const foldedTemp = new RegExp(s.tempName, "i");
823
+ for (const n of [...files, ...locks]) {
824
+ const p = path.join(dir, n);
825
+ if (fs.lstatSync(p, { throwIfNoEntry: false }) && !entries.includes(n) && !entries.some((e) => fold(e) === fold(n))) {
826
+ throw new Error(`${p} reaches an entry of another name that relay cannot identify, so relay does not run`);
827
+ }
828
+ }
829
+ const subdirs = [];
830
+ for (const n of entries) {
831
+ const p = path.join(dir, n);
832
+ const st = fs.lstatSync(p, { throwIfNoEntry: false });
833
+ if (!st)
834
+ continue;
835
+ const exact = files.includes(n) || locks.includes(n) || tempName.test(n);
836
+ let reason = null;
837
+ if (!exact && (folded.has(fold(n)) || foldedTemp.test(fold(n)))) {
838
+ reason = `${p} differs only in case or form from a name relay makes writable in ${s.name}, and on such a volume the turn's writes would reach it, so relay does not run; it leaves it for you to look at`;
839
+ }
840
+ else if (exact) {
841
+ if (st.isSymbolicLink())
842
+ reason = `${p} is a symbolic link. Every name relay makes writable in ${s.name} must be the file itself, so it does not run; relay leaves it for you to look at`;
843
+ else if (!st.isFile())
844
+ reason = `${p} is not a regular file. Only files can be writable in ${s.name}, so relay does not run; it leaves it for you to look at`;
845
+ else if (st.mode & 0o111)
846
+ reason = `${p} is executable. Relay makes only plain token files writable, so it does not run on it`;
847
+ else if (st.nlink !== 1)
848
+ reason = `${p} has ${st.nlink} hard links: another name for it could be anywhere, and the turn's writes would reach it. Relay does not run until the extra name is gone`;
849
+ else if (typeof process.getuid === "function" && st.uid !== process.getuid())
850
+ reason = `${p} is not owned by this user`;
851
+ }
852
+ else if (st.isDirectory())
853
+ subdirs.push(p);
854
+ if (reason)
855
+ problems.push({ name: n, stat: st, reason });
856
+ }
857
+ if (subdirs.length > 64)
858
+ throw new Error(`${s.name} (${dir}) has ${subdirs.length} subdirectories; relay denies each by name and stops at 64`);
859
+ return { name: s.name, dir, files: files.map((f) => path.join(dir, f)), locks: locks.map((f) => path.join(dir, f)), temp: `/${s.tempName.slice(1)}`, tempName, subdirs, problems };
860
+ }
861
+ export function tokenStore(s, what = "state.tokenStore") {
862
+ const { problems, ...checked } = inspectTokenStore(s, what);
863
+ if (problems.length)
864
+ throw new Error(problems[0].reason);
865
+ return checked;
866
+ }
867
+ /**
868
+ * After the harness and its children stop, move unsafe entries themselves, never their targets.
869
+ * Also remove token names from use, so even a bad lock or temp file requires a fresh login.
870
+ * `destination` is below relay's denied control directory, with run/node/turn components supplied
871
+ * by relay, never by the harness. No file is opened, copied, deleted or overwritten here.
872
+ */
873
+ export function quarantineTokenStore(s, destination, turn) {
874
+ const result = { problem: null, moved: [], errors: [] };
875
+ let checked;
876
+ try {
877
+ checked = inspectTokenStore(s);
878
+ }
879
+ catch (err) {
880
+ result.problem = err.message;
881
+ result.errors.push(`QUARANTINE FAILED for ${s.dir}: ${err.message}`);
882
+ return result;
883
+ }
884
+ if (!checked.problems.length)
885
+ return result;
886
+ result.problem = checked.problems.map((p) => p.reason.replace(/; (?:relay|it) leaves it for you to look at$/, "")).join("; ");
887
+ const entries = new Map(checked.problems.map((p) => [p.name, p.stat]));
888
+ for (const p of checked.files) {
889
+ try {
890
+ const st = fs.lstatSync(p, { throwIfNoEntry: false });
891
+ const fold = (n) => n.normalize("NFC").toUpperCase().toLowerCase();
892
+ // On a case-insensitive volume the declared name may reach the alias already listed. On
893
+ // a case-sensitive volume both can exist, so keep the token too when it is another inode.
894
+ if (st && !entries.has(path.basename(p)) && ![...entries].some(([n, other]) => fold(n) === fold(path.basename(p)) && other.dev === st.dev && other.ino === st.ino))
895
+ entries.set(path.basename(p), st);
896
+ }
897
+ catch (err) {
898
+ result.errors.push(`QUARANTINE FAILED for ${p}: ${err.message}`);
899
+ }
900
+ }
901
+ // New directories are private; existing components below the control directory must be too.
902
+ // The final directory must be new so a repeated turn cannot overwrite evidence.
903
+ const privateDirectory = (dir, fresh = false) => {
904
+ const st = fs.lstatSync(dir, { throwIfNoEntry: false });
905
+ if (st) {
906
+ if (fresh)
907
+ throw new Error(`quarantine destination already exists: ${dir}`);
908
+ if (!st.isDirectory() || st.isSymbolicLink() || (typeof process.getuid === "function" && st.uid !== process.getuid()) || (st.mode & 0o022)) {
909
+ throw new Error(`quarantine ancestor is not a directory owned by this user and writable only by them: ${dir}`);
910
+ }
911
+ return;
912
+ }
913
+ privateDirectory(path.dirname(dir));
914
+ fs.mkdirSync(dir, { mode: 0o700 });
915
+ const made = fs.lstatSync(dir);
916
+ if (!made.isDirectory() || made.isSymbolicLink() || (made.mode & 0o077) || (typeof process.getuid === "function" && made.uid !== process.getuid()))
917
+ throw new Error(`unsafe quarantine directory: ${dir}`);
918
+ };
919
+ let directoryError;
920
+ try {
921
+ if (!/^[A-Za-z0-9_-]+$/.test(turn))
922
+ throw new Error(`invalid quarantine turn: ${JSON.stringify(turn)}`);
923
+ privateDirectory(path.resolve(destination), true);
924
+ }
925
+ catch (err) {
926
+ directoryError = err;
927
+ }
928
+ const identity = (a, b) => b && a.dev === b.dev && a.ino === b.ino && a.mode === b.mode && a.uid === b.uid && a.nlink === b.nlink;
929
+ for (const [name, before] of entries) {
930
+ const source = path.join(checked.dir, name);
931
+ let to = path.join(destination, name);
932
+ try {
933
+ if (directoryError)
934
+ throw directoryError;
935
+ if (!identity(before, fs.lstatSync(source, { throwIfNoEntry: false })))
936
+ throw new Error("entry identity changed before quarantine");
937
+ try {
938
+ fs.renameSync(source, to);
939
+ }
940
+ catch (err) {
941
+ if (err.code !== "EXDEV")
942
+ throw err;
943
+ to = path.join(checked.dir, `.relay-quarantine.${turn}.${name}`);
944
+ if (fs.lstatSync(to, { throwIfNoEntry: false }))
945
+ throw new Error(`fallback already exists: ${to}`);
946
+ fs.renameSync(source, to);
947
+ }
948
+ result.moved.push({ name, to });
949
+ // lstat sees the moved link itself. Check both names for a concurrent replacement as well.
950
+ const after = fs.lstatSync(to, { throwIfNoEntry: false });
951
+ const remaining = fs.lstatSync(source, { throwIfNoEntry: false });
952
+ if (!identity(before, after))
953
+ throw new Error(`entry identity differs after rename to ${to}`);
954
+ if (remaining)
955
+ throw new Error(`entry remains at ${source} after rename to ${to}`);
956
+ }
957
+ catch (err) {
958
+ const e = err;
959
+ result.errors.push(`QUARANTINE FAILED for ${JSON.stringify(name)} (${source} -> ${to}): ${e.code ? `${e.code}: ` : ""}${e.message}`);
960
+ }
961
+ }
962
+ return result;
963
+ }
964
+ /**
965
+ * What is wrong with a login store now, or null: the same checks as before a turn, for after one.
966
+ * An exchange of two names (renamex_np RENAME_SWAP) is checked by Seatbelt as a create and an unlink
967
+ * at the store's name with that name's own file in view, so it can put a link or a directory at the
968
+ * token's name or a temp name, which no rule can tell from a rename (measured; review r_75bf1f48).
969
+ */
970
+ export function tokenStoreProblem(s) {
971
+ try {
972
+ tokenStore(s);
973
+ return null;
974
+ }
975
+ catch (err) {
976
+ return err.message;
977
+ }
978
+ }
979
+ /**
980
+ * Checks relay-owned persistent state before a turn and returns its resolved root and writable
981
+ * subdirectories. The root must be a real directory (not a link), the person's own and writable by
982
+ * no one else; each writable subdirectory, and every directory on the way to it, must be a real
983
+ * directory, checked without following links; a missing one is created (mode 0700). Throws, so the
984
+ * turn is refused, when something has been swapped for a link or a file.
985
+ */
986
+ export function persistentState(p) {
987
+ if (typeof p?.root !== "string" || !path.isAbsolute(p.root))
988
+ throw new Error(`relay-owned state needs an absolute root: ${JSON.stringify(p?.root)}`);
989
+ const top = fs.lstatSync(p.root, { throwIfNoEntry: false });
990
+ if (!top || top.isSymbolicLink() || !top.isDirectory())
991
+ throw new Error(`relay-owned state ${p.root} is ${top ? "not a plain directory" : "missing"}; relay creates it before the turn and does not run on anything else`);
992
+ if (typeof process.getuid === "function" && top.uid !== process.getuid())
993
+ throw new Error(`relay-owned state ${p.root} is not owned by this user`);
994
+ if (top.mode & 0o022)
995
+ throw new Error(`relay-owned state ${p.root} is writable by others (mode ${(top.mode & 0o777).toString(8)})`);
996
+ const root = canonical(p.root, "state.persistent.root");
997
+ const writable = (p.writable ?? []).map((rel, i) => {
998
+ const what = `state.persistent.writable[${i}]`;
999
+ if (typeof rel !== "string" || !rel || path.isAbsolute(rel) || /[\0\r\n]/.test(rel) || path.normalize(rel) !== rel.replace(/\/+$/, "") || rel.split("/").includes("..") || rel === ".") {
1000
+ throw new Error(`${what} must be a plain relative path inside the state: ${JSON.stringify(rel)}`);
1001
+ }
1002
+ let at = root;
1003
+ for (const part of rel.split("/").filter(Boolean)) {
1004
+ at = path.join(at, part);
1005
+ const st = fs.lstatSync(at, { throwIfNoEntry: false });
1006
+ if (!st)
1007
+ fs.mkdirSync(at, { mode: 0o700 });
1008
+ else if (st.isSymbolicLink() || !st.isDirectory()) {
1009
+ throw new Error(`relay-owned state ${at} has been replaced by something other than a directory, which the sandbox would follow, so relay does not run on it`);
1010
+ }
1011
+ }
1012
+ return at;
1013
+ });
1014
+ return { root, writable };
1015
+ }
1016
+ /** Variables relay sets for every confined launch, which a harness profile's environment may not replace. */
1017
+ const RESERVED_ENV = /^(HOME|TMPDIR|PATH|XDG_[A-Z_]+|(HTTPS?|ALL|NO)_PROXY|(https?|all|no)_proxy|NODE_USE_ENV_PROXY|NODE_OPTIONS|DYLD_.*|LD_.*)$/;
1018
+ /**
1019
+ * The environment for the harness's state: with a temporary home, the home itself (created inside
1020
+ * the turn's temp dir, mode 0700), the harness's home variables and the XDG directories pointing into
1021
+ * it, and links to the real token files it must read; then the harness profile's own variables
1022
+ * (auto-updaters off). Creates the home; touches nothing outside the turn's temp dir.
1023
+ */
1024
+ function stateEnv(policy, tmpDir) {
1025
+ const state = policy.state ?? { home: "temp" };
1026
+ const env = {};
1027
+ const homeVars = state.homeVars ?? {};
1028
+ if (state.home === "temp") {
1029
+ const home = path.join(tmpDir, "home");
1030
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
1031
+ const inside = (rel, what) => {
1032
+ const at = path.resolve(home, rel);
1033
+ if (path.isAbsolute(rel) || !within(at, home))
1034
+ throw new Error(`${what} must be a path inside the temporary home: ${JSON.stringify(rel)}`);
1035
+ return at;
1036
+ };
1037
+ Object.assign(env, {
1038
+ HOME: home,
1039
+ XDG_CONFIG_HOME: path.join(home, ".config"), XDG_DATA_HOME: path.join(home, ".local", "share"),
1040
+ XDG_STATE_HOME: path.join(home, ".local", "state"), XDG_CACHE_HOME: path.join(home, ".cache"),
1041
+ });
1042
+ for (const [name, rel] of Object.entries(homeVars)) {
1043
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || RESERVED_ENV.test(name))
1044
+ throw new Error(`state.homeVars cannot set ${name}`);
1045
+ env[name] = inside(rel, `state.homeVars.${name}`);
1046
+ fs.mkdirSync(env[name], { recursive: true, mode: 0o700 });
1047
+ }
1048
+ // Links, not copies: the harness reads its login through them; relay never opens the files.
1049
+ for (const [rel, real] of Object.entries(state.links ?? {})) {
1050
+ const at = inside(rel, `state.links[${JSON.stringify(rel)}]`);
1051
+ fs.mkdirSync(path.dirname(at), { recursive: true, mode: 0o700 });
1052
+ fs.rmSync(at, { force: true });
1053
+ fs.symlinkSync(canonical(real, `state.links[${JSON.stringify(rel)}]`), at);
1054
+ }
1055
+ }
1056
+ else if (state.home === "real") {
1057
+ if (Object.keys(homeVars).length || Object.keys(state.links ?? {}).length)
1058
+ throw new Error("state.homeVars and state.links apply only to a temporary home");
1059
+ }
1060
+ else {
1061
+ throw new Error(`unknown state.home ${state.home}`);
1062
+ }
1063
+ for (const [name, value] of Object.entries(state.env ?? {})) {
1064
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || RESERVED_ENV.test(name) || name in env)
1065
+ throw new Error(`state.env cannot set ${name}`);
1066
+ if (typeof value !== "string" || value.includes("\0"))
1067
+ throw new Error(`state.env.${name} is not a string`);
1068
+ env[name] = value;
1069
+ }
1070
+ return env;
1071
+ }
1072
+ /**
1073
+ * The sandbox-exec command line for a policy. The command must be an absolute path. With a
1074
+ * temporary home (the default) this creates it inside the turn's temp dir.
1075
+ */
1076
+ export function seatbeltLaunch(policy, command, args) {
1077
+ if (!path.isAbsolute(command))
1078
+ throw new Error(`the confined command must be an absolute path: ${command}`);
1079
+ const { profile, params } = seatbeltProfile(policy, command);
1080
+ const prefix = ["-p", profile, ...params.flatMap(([k, v]) => ["-D", `${k}=${v}`])];
1081
+ const tmpDir = canonical(policy.tmpDir, "tmpDir");
1082
+ const env = {
1083
+ ...stateEnv(policy, tmpDir),
1084
+ TMPDIR: tmpDir,
1085
+ ...(policy.network.mode === "off-except-proxy" ? proxyEnv(policy.network.proxyPort, policy.network.proxyToken) : {}),
1086
+ };
1087
+ return {
1088
+ command: SANDBOX_EXEC,
1089
+ args: [...prefix, command, ...args],
1090
+ rewrap: (c, a) => ({ command: SANDBOX_EXEC, args: [...prefix, c, ...a] }),
1091
+ // The profile, every parameter, and the variables relay sets for the launch.
1092
+ fingerprint: crypto.createHash("sha256").update(JSON.stringify({ prefix, env })).digest("hex"),
1093
+ rules: crypto.createHash("sha256").update(profile).digest("hex"),
1094
+ env,
1095
+ diagnosticTag: diagnosticTag(policy),
1096
+ };
1097
+ }
1098
+ /**
1099
+ * Whether a process runs under a Seatbelt profile: sandbox_check(pid, NULL, 0), asked through
1100
+ * osascript's JavaScript bridge, which every Mac has. After exec the harness keeps sandbox-exec's
1101
+ * pid, so the pid relay spawned is the one to check. Any failure reads as not confined.
1102
+ */
1103
+ export function sandboxed(pid) {
1104
+ if (!Number.isInteger(pid) || pid <= 0)
1105
+ return false;
1106
+ const jxa = `ObjC.bindFunction('sandbox_check',['int',['int','void *','int']]); $.sandbox_check(${pid}, null, 0)`;
1107
+ try {
1108
+ return execFileSync("/usr/bin/osascript", ["-l", "JavaScript", "-e", jxa], { encoding: "utf8", timeout: 10000 }).trim() === "1";
1109
+ }
1110
+ catch {
1111
+ return false;
1112
+ }
1113
+ }
1114
+ export const seatbelt = {
1115
+ id: "seatbelt",
1116
+ unavailable() {
1117
+ if (process.platform !== "darwin")
1118
+ return "Seatbelt exists only on macOS";
1119
+ try {
1120
+ fs.accessSync(SANDBOX_EXEC, fs.constants.X_OK);
1121
+ }
1122
+ catch {
1123
+ return `${SANDBOX_EXEC} is missing`;
1124
+ }
1125
+ return null;
1126
+ },
1127
+ wrap: seatbeltLaunch,
1128
+ confined: sandboxed,
1129
+ };