@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,258 @@
1
+ import { brokerCore, TURN_ENDED, MAX_MESSAGE } from "./broker-core.js";
2
+ export { TURN_ENDED, turnRefusal, turnContext } from "./broker-core.js";
3
+ import crypto from "node:crypto";
4
+ import fs from "node:fs";
5
+ import net from "node:net";
6
+ import path from "node:path";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { RELAY_CLI } from "../core/config.js";
9
+ import { inProcessTree, sameProcess } from "../core/procs.js";
10
+ import { socketPeer } from "./peer.js";
11
+ import { ensureRelaySocketsDir } from "./sockets.js";
12
+ import { BRIDGE_SECRET_ENV } from "./broker-names.js";
13
+ export { BRIDGE_SECRET_ENV };
14
+ /**
15
+ * The broker: relay's MCP tools for one confined turn, served by the worker, outside the sandbox,
16
+ * on a Unix socket in a private directory. The confined agent reaches it only through
17
+ * `relay bridge <socket>` (bridge.ts), which forwards stdio to the socket and holds no authority of
18
+ * its own. The directory is inside relay's sockets directory (sockets.ts), which the profile of
19
+ * every confined turn closes but for that turn's own bridge. The registry and worker creation stay outside the sandbox; every request is checked
20
+ * against the live turn, and the socket is gone once the turn ends.
21
+ */
22
+ /** macOS keeps 104 bytes for a socket path, its terminating NUL included. */
23
+ const MAX_SOCKET_PATH = 103;
24
+ /** How long a new connection has to present the turn's secret, and how long its first line may be. */
25
+ const HANDSHAKE_MS = 5000;
26
+ const MAX_HANDSHAKE = 512;
27
+ /**
28
+ * Reads a connection's first line, which must be `{"relay_bridge_secret":"<the turn's secret>"}`,
29
+ * and leaves whatever follows it unread. True when it matches, compared in constant time.
30
+ */
31
+ function handshake(sock, secret) {
32
+ return new Promise((resolve) => {
33
+ let buf = Buffer.alloc(0);
34
+ let settled = false;
35
+ const done = (ok) => {
36
+ if (settled)
37
+ return;
38
+ settled = true;
39
+ clearTimeout(timer);
40
+ sock.off("data", onData);
41
+ sock.off("close", onClose);
42
+ resolve(ok);
43
+ };
44
+ const onClose = () => done(false);
45
+ const onData = (chunk) => {
46
+ buf = Buffer.concat([buf, chunk]);
47
+ const nl = buf.indexOf(0x0a);
48
+ if (nl < 0)
49
+ return void (buf.length > MAX_HANDSHAKE && done(false));
50
+ // A first line longer than any secret line is refused unread (review r_f0fce42b C2).
51
+ if (nl > MAX_HANDSHAKE)
52
+ return done(false);
53
+ sock.pause();
54
+ const rest = buf.subarray(nl + 1);
55
+ if (rest.length)
56
+ sock.unshift(rest);
57
+ let given;
58
+ try {
59
+ given = JSON.parse(buf.subarray(0, nl).toString("utf8")).relay_bridge_secret;
60
+ }
61
+ catch {
62
+ return done(false);
63
+ }
64
+ const a = Buffer.from(typeof given === "string" ? given : "");
65
+ const b = Buffer.from(secret);
66
+ done(a.length === b.length && crypto.timingSafeEqual(a, b));
67
+ };
68
+ const timer = setTimeout(() => done(false), HANDSHAKE_MS);
69
+ sock.on("data", onData);
70
+ sock.once("close", onClose);
71
+ sock.resume();
72
+ });
73
+ }
74
+ /** The stdio bridge itself receives only its own credential, even from an inheriting harness. */
75
+ export function bridgeCommand(socketPath, secret) {
76
+ return {
77
+ command: "/bin/sh",
78
+ // The shell expands only this turn's bridge secret. Stored command text contains no value.
79
+ args: ["-c", 'exec /usr/bin/env -i RELAY_BRIDGE_SECRET="$RELAY_BRIDGE_SECRET" "$@"', "relay-bridge", process.execPath, RELAY_CLI, "bridge", socketPath],
80
+ env: { [BRIDGE_SECRET_ENV]: secret },
81
+ };
82
+ }
83
+ /**
84
+ * A transport over one socket connection that passes the agent's messages to the server only while
85
+ * `refusal` returns null. Afterwards requests are answered with an error and everything else is dropped.
86
+ */
87
+ class GatedTransport {
88
+ sock;
89
+ refusal;
90
+ accepted;
91
+ onclose;
92
+ onerror;
93
+ onmessage;
94
+ inner;
95
+ closed = false;
96
+ gone;
97
+ constructor(sock, refusal, accepted) {
98
+ this.sock = sock;
99
+ this.refusal = refusal;
100
+ this.accepted = accepted;
101
+ this.inner = new StdioServerTransport(sock, sock, { maxBufferSize: MAX_MESSAGE });
102
+ this.gone = new Promise((resolve) => sock.once("close", () => resolve()));
103
+ }
104
+ async start() {
105
+ this.inner.onmessage = (message) => {
106
+ let reason;
107
+ try {
108
+ reason = this.refusal();
109
+ }
110
+ catch (err) {
111
+ reason = `relay could not check this agent's turn: ${err.message}`;
112
+ }
113
+ if (reason === null) {
114
+ this.accepted?.(message);
115
+ return this.onmessage?.(message);
116
+ }
117
+ if ("method" in message && "id" in message) {
118
+ void this.send({ jsonrpc: "2.0", id: message.id, error: { code: TURN_ENDED, message: `Refused: ${reason}` } });
119
+ }
120
+ };
121
+ this.inner.onerror = (error) => this.onerror?.(error);
122
+ // The inner transport closes itself on an oversized message; the connection goes with it.
123
+ this.inner.onclose = () => {
124
+ this.closed = true;
125
+ this.sock.destroy();
126
+ this.onclose?.();
127
+ };
128
+ void this.gone.then(() => this.close());
129
+ await this.inner.start();
130
+ }
131
+ async send(message) {
132
+ if (this.closed || this.sock.destroyed)
133
+ return;
134
+ // A write the agent never reads must not hold a reply open after the connection is gone.
135
+ await Promise.race([this.inner.send(message), this.gone]);
136
+ }
137
+ async close() {
138
+ if (this.closed)
139
+ return;
140
+ this.closed = true;
141
+ this.sock.destroy();
142
+ await this.inner.close();
143
+ }
144
+ }
145
+ /**
146
+ * Starts serving one confined turn. Call it once the turn is running in the registry (the worker
147
+ * has marked it so before it starts the agent), and close it when the turn ends.
148
+ */
149
+ export async function openBroker(turn, opts = {}) {
150
+ const core = brokerCore(turn, { toolHandler: opts.toolHandler });
151
+ // In relay's sockets directory, which every confined turn's profile closes but for its own bridge.
152
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(opts.parent ?? ensureRelaySocketsDir(), "relay-turn-")));
153
+ fs.chmodSync(dir, 0o700);
154
+ const socketPath = path.join(dir, "relay.sock");
155
+ if (Buffer.byteLength(socketPath) > MAX_SOCKET_PATH) {
156
+ fs.rmSync(dir, { recursive: true, force: true });
157
+ throw new Error(`the broker socket path is too long for a Unix socket (${Buffer.byteLength(socketPath)} bytes): ${socketPath}`);
158
+ }
159
+ let closed = false;
160
+ let harness = null;
161
+ const sockets = new Set();
162
+ const authenticating = new Set();
163
+ // The turn's own: handed to its bridge through the harness, and written nowhere but, when a harness
164
+ // needs it there, its own file in this private directory (secretFile), which only this turn may read.
165
+ const secret = crypto.randomBytes(24).toString("base64url");
166
+ const refusal = () => (closed ? "the relay turn this agent was started for has ended. Continue without relay." : core.refusal());
167
+ /** The server a connection gets: one instance each, made from the worker's record of the turn alone. */
168
+ const serve = core.serve;
169
+ const refuse = (sock, reason) => {
170
+ sock.destroy();
171
+ (opts.onRefusal ?? ((why) => process.stderr.write(`[broker] refused: ${why}\n`)))(reason);
172
+ };
173
+ const server = net.createServer({ pauseOnConnect: true }, (sock) => {
174
+ // An agent going away mid-reply must never take the worker down.
175
+ sock.on("error", () => { });
176
+ if (closed)
177
+ return void sock.destroy();
178
+ sockets.add(sock);
179
+ sock.once("close", () => sockets.delete(sock));
180
+ const auth = (async () => {
181
+ try {
182
+ if (!harness)
183
+ return refuse(sock, "the launched harness identity has not been bound");
184
+ const peer = await (opts.peerIdentity ?? socketPeer)(sock);
185
+ if (closed || sock.destroyed)
186
+ return;
187
+ if (peer.uid !== process.getuid?.())
188
+ return refuse(sock, `kernel peer uid ${peer.uid} is not the relay user's uid`);
189
+ if (!inProcessTree(harness, peer))
190
+ return refuse(sock, `kernel peer pid ${peer.pid} is outside the live launched harness process tree (or its process identity changed)`);
191
+ if (!await handshake(sock, secret))
192
+ return refuse(sock, "the bridge secret is missing or invalid");
193
+ if (closed || sock.destroyed)
194
+ return;
195
+ // The handshake can take seconds. Do not carry an identity/tree decision across that wait.
196
+ if (!inProcessTree(harness, peer))
197
+ return refuse(sock, `kernel peer pid ${peer.pid} left the live launched harness process tree (or its process identity changed)`);
198
+ // One instance per connection, as each `relay mcp` process had its own.
199
+ const mcp = serve();
200
+ await mcp.connect(new GatedTransport(sock, refusal, (message) => opts.onAcceptedMessage?.(message, peer)));
201
+ sock.resume();
202
+ }
203
+ catch (err) {
204
+ refuse(sock, `could not authenticate broker peer: ${err.message}`);
205
+ }
206
+ })();
207
+ authenticating.add(auth);
208
+ void auth.finally(() => authenticating.delete(auth));
209
+ });
210
+ server.on("error", () => { });
211
+ await new Promise((resolve, reject) => {
212
+ server.once("error", reject);
213
+ server.listen(socketPath, () => {
214
+ server.off("error", reject);
215
+ resolve();
216
+ });
217
+ }).catch((err) => {
218
+ fs.rmSync(dir, { recursive: true, force: true });
219
+ throw err;
220
+ });
221
+ fs.chmodSync(socketPath, 0o600);
222
+ return {
223
+ dir,
224
+ socketPath,
225
+ bridgeCommand: bridgeCommand(socketPath, secret),
226
+ secretFile() {
227
+ if (closed)
228
+ throw new Error("the broker is closed");
229
+ const file = path.join(dir, "bridge-secret");
230
+ if (!fs.existsSync(file))
231
+ fs.writeFileSync(file, secret, { mode: 0o600, flag: "wx" });
232
+ return file;
233
+ },
234
+ async listTools() {
235
+ const why = refusal();
236
+ if (why)
237
+ throw new Error(`relay cannot list this turn's tools: ${why}`);
238
+ return core.listTools();
239
+ },
240
+ bindHarness(identity) {
241
+ if (closed || harness)
242
+ throw new Error("the broker's launched harness identity is already bound or the broker is closed");
243
+ if (!identity.start || !sameProcess(identity.pid, identity.start, { fresh: true }))
244
+ throw new Error("cannot bind broker to an unknown, dead or reused harness process");
245
+ harness = { ...identity };
246
+ },
247
+ close: async () => {
248
+ if (closed)
249
+ return;
250
+ closed = true;
251
+ for (const s of sockets)
252
+ s.destroy();
253
+ await new Promise((resolve) => server.close(() => resolve()));
254
+ await Promise.allSettled(authenticating);
255
+ fs.rmSync(dir, { recursive: true, force: true });
256
+ },
257
+ };
258
+ }
@@ -0,0 +1,380 @@
1
+ /**
2
+ * The boundary canary: run by probe.ts under the exact confinement a turn is about to get, before the
3
+ * harness starts. It tries each thing in its plan and prints one JSON object, probe name to outcome:
4
+ * "allowed", an errno code ("EPERM"), "exit <n>" for a command that failed, or "timeout".
5
+ * Opt-in port-0 retries instead return a JSON-encoded ListenPortOutcome string with every attempt.
6
+ * It judges nothing; probe.ts does. Node built-ins only, so it starts fast; the few system calls
7
+ * Node has no binding for go through osascript's JavaScript bridge (NativeCheck), in one process.
8
+ *
9
+ * usage: node canary.js '<plan JSON>'
10
+ */
11
+ import { execFileSync, spawn } from "node:child_process";
12
+ import dgram from "node:dgram";
13
+ import dns from "node:dns";
14
+ import fs from "node:fs";
15
+ import net from "node:net";
16
+ import os from "node:os";
17
+ /** How long the native checks may take together. */
18
+ const NATIVE_TIMEOUT_MS = 5000;
19
+ /**
20
+ * The osascript (JavaScript) side of the native checks: takes the checks as JSON and returns a JSON
21
+ * object, check name to outcome. Errors are errno numbers here; the canary names them.
22
+ */
23
+ const NATIVE_SCRIPT = `function run(argv) {
24
+ var checks = JSON.parse(argv[0]);
25
+ ObjC.bindFunction("__error", ["int *", []]);
26
+ ObjC.bindFunction("open", ["int", ["char *", "int"]]);
27
+ ObjC.bindFunction("close", ["int", ["int"]]);
28
+ ObjC.bindFunction("fcntl", ["int", ["int", "int", "void *"]]);
29
+ ObjC.bindFunction("malloc", ["void *", ["long"]]);
30
+ ObjC.bindFunction("getpid", ["int", []]);
31
+ ObjC.bindFunction("proc_pidpath", ["int", ["int", "void *", "unsigned int"]]);
32
+ ObjC.bindFunction("proc_pidinfo", ["int", ["int", "int", "unsigned long long", "void *", "int"]]);
33
+ ObjC.bindFunction("proc_listpids", ["int", ["unsigned int", "unsigned int", "void *", "int"]]);
34
+ ObjC.bindFunction("sysctl", ["int", ["void *", "unsigned int", "void *", "long *", "void *", "long"]]);
35
+ ObjC.bindFunction("sysctlbyname", ["int", ["char *", "void *", "long *", "void *", "long"]]);
36
+ ObjC.bindFunction("socket", ["int", ["int", "int", "int"]]);
37
+ ObjC.bindFunction("connect", ["int", ["int", "void *", "unsigned int"]]);
38
+ ObjC.bindFunction("mach_task_self", ["unsigned int", []]);
39
+ ObjC.bindFunction("task_get_special_port", ["int", ["unsigned int", "int", "unsigned int *"]]);
40
+ ObjC.bindFunction("bootstrap_look_up", ["int", ["unsigned int", "char *", "unsigned int *"]]);
41
+ ObjC.bindFunction("openpty", ["int", ["int *", "int *", "char *", "void *", "void *"]]);
42
+ ObjC.import("IOKit");
43
+ ObjC.bindFunction("IOServiceMatching", ["void *", ["char *"]]);
44
+ ObjC.bindFunction("IOServiceGetMatchingService", ["unsigned int", ["unsigned int", "void *"]]);
45
+ ObjC.bindFunction("IOServiceOpen", ["int", ["unsigned int", "unsigned int", "unsigned int", "unsigned int *"]]);
46
+ ObjC.bindFunction("IOServiceClose", ["int", ["unsigned int"]]);
47
+ ObjC.bindFunction("sem_open", ["long", ["char *", "int"]]);
48
+ ObjC.bindFunction("sem_post", ["int", ["long"]]);
49
+ ObjC.bindFunction("sem_unlink", ["int", ["char *"]]);
50
+ ObjC.bindFunction("renamex_np", ["int", ["char *", "char *", "unsigned int"]]);
51
+ ObjC.bindFunction("setxattr", ["int", ["char *", "char *", "char *", "long", "unsigned int", "int"]]);
52
+ var kr = function (k) { return k === 0 ? "allowed" : "kr " + (k >>> 0).toString(16); };
53
+ var buf = $.malloc(4096);
54
+ var errno = function () { return { errno: $.__error()[0] }; };
55
+ var out = {};
56
+ Object.keys(checks).forEach(function (name) {
57
+ var c = checks[name];
58
+ try {
59
+ if (c.op === "fcntl") {
60
+ var fd = $.open(c.path, 0);
61
+ if (fd < 0) { out[name] = errno(); return; }
62
+ out[name] = $.fcntl(fd, c.cmd, null) < 0 ? errno() : "allowed";
63
+ $.close(fd);
64
+ } else if (c.op === "pidpath") out[name] = $.proc_pidpath(c.pid === -1 ? $.getpid() : c.pid, buf, 4096) <= 0 ? errno() : "allowed";
65
+ else if (c.op === "pidinfo") out[name] = $.proc_pidinfo(c.pid === -1 ? $.getpid() : c.pid, 3, 0, buf, 136) <= 0 ? errno() : "allowed";
66
+ else if (c.op === "listpids") out[name] = $.proc_listpids(1, 0, null, 0) <= 0 ? errno() : "allowed";
67
+ else if (c.op === "sysctl-read" && c.name) out[name] = $.sysctlbyname(c.name, null, Ref(), null, 0) < 0 ? errno() : "allowed";
68
+ else if (c.op === "sysctl-read") {
69
+ var mib = $.NSData.alloc.initWithBase64EncodedStringOptions(c.mib64, 0);
70
+ out[name] = $.sysctl(mib.bytes, c.mibLength, null, Ref(), null, 0) < 0 ? errno() : "allowed";
71
+ } else if (c.op === "socket") {
72
+ var sd = $.socket(c.domain, c.type, c.protocol);
73
+ out[name] = sd < 0 ? errno() : "allowed";
74
+ if (sd >= 0) $.close(sd);
75
+ } else if (c.op === "unix-dgram-connect") {
76
+ var u = $.socket(1, 2, 0);
77
+ if (u < 0) { out[name] = errno(); return; }
78
+ var addr = $.NSData.alloc.initWithBase64EncodedStringOptions(c.addr64, 0);
79
+ out[name] = $.connect(u, addr.bytes, c.addrLength) < 0 ? errno() : "allowed";
80
+ $.close(u);
81
+ } else if (c.op === "mach") {
82
+ var bp = Ref();
83
+ var k = $.task_get_special_port($.mach_task_self(), 4, bp);
84
+ out[name] = k !== 0 ? "bootstrap port: " + kr(k) : kr($.bootstrap_look_up(bp[0], c.name, Ref()));
85
+ } else if (c.op === "openpty") {
86
+ var m = Ref(), sl = Ref();
87
+ if ($.openpty(m, sl, null, null, null) < 0) { out[name] = errno(); return; }
88
+ $.close(m[0]);
89
+ $.close(sl[0]);
90
+ out[name] = "allowed";
91
+ } else if (c.op === "iokit-open") {
92
+ var svc = $.IOServiceGetMatchingService(0, $.IOServiceMatching(c.serviceClass));
93
+ if (!svc) { out[name] = "no-service"; return; }
94
+ var conn = Ref();
95
+ var k = $.IOServiceOpen(svc, $.mach_task_self(), 0, conn);
96
+ out[name] = kr(k);
97
+ if (k === 0) $.IOServiceClose(conn[0]);
98
+ } else if (c.op === "sysctl-write") {
99
+ var v = $.NSData.alloc.initWithBase64EncodedStringOptions(c.value64, 0);
100
+ out[name] = $.sysctlbyname(c.name, null, null, v.bytes, v.length) < 0 ? errno() : "allowed";
101
+ } else if (c.op === "sem-unlink") {
102
+ out[name] = $.sem_unlink(c.name) < 0 ? errno() : "allowed";
103
+ } else if (c.op === "sem-open" || c.op === "sem-post") {
104
+ var sp = $.sem_open(c.name, 0);
105
+ if (sp < 0) { out[name] = errno(); return; }
106
+ out[name] = c.op === "sem-open" ? "allowed" : ($.sem_post(sp) < 0 ? errno() : "allowed");
107
+ } else if (c.op === "rename-swap") out[name] = $.renamex_np(c.from, c.to, 2) < 0 ? errno() : "allowed";
108
+ else if (c.op === "setxattr") out[name] = $.setxattr(c.path, "com.relay.probe", "1", 1, 0, 1) < 0 ? errno() : "allowed";
109
+ else out[name] = "unknown check " + c.op;
110
+ } catch (e) { out[name] = "exception: " + e; }
111
+ });
112
+ return JSON.stringify(out);
113
+ }`;
114
+ function wireCheck(c) {
115
+ if (c.op === "sysctl-read" && "mib" in c)
116
+ return { op: c.op, mib64: Buffer.from(new Int32Array(c.mib).buffer).toString("base64"), mibLength: c.mib.length };
117
+ if (c.op === "sysctl-write")
118
+ return { op: c.op, name: c.name, value64: Buffer.from(c.value).toString("base64") };
119
+ if (c.op === "unix-dgram-connect") {
120
+ const p = Buffer.from(c.path);
121
+ if (p.length > 103)
122
+ throw new Error(`socket path too long: ${c.path}`);
123
+ const addr = Buffer.alloc(106);
124
+ addr[0] = 106;
125
+ addr[1] = 1; // AF_UNIX
126
+ p.copy(addr, 2);
127
+ return { op: c.op, addr64: addr.toString("base64"), addrLength: addr.length };
128
+ }
129
+ return c;
130
+ }
131
+ const ERRNO_NAMES = new Map(Object.entries(os.constants.errno).map(([k, v]) => [v, k]));
132
+ /** Runs the native checks in one osascript process: name to outcome. */
133
+ function native(checks) {
134
+ const names = Object.keys(checks);
135
+ if (!names.length)
136
+ return Promise.resolve({});
137
+ return new Promise((resolve) => {
138
+ const all = (outcome) => resolve(Object.fromEntries(names.map((n) => [n, outcome])));
139
+ // A MIB travels as base64 of its 32-bit integers, which the script hands to sysctl as bytes.
140
+ // So does a socket address, built here (struct sockaddr_un: length, family, path).
141
+ const wire = Object.fromEntries(Object.entries(checks).map(([n, c]) => [n, wireCheck(c)]));
142
+ const c = spawn("/usr/bin/osascript", ["-l", "JavaScript", "-e", NATIVE_SCRIPT, JSON.stringify(wire)], { stdio: ["ignore", "pipe", "pipe"] });
143
+ let stdout = "";
144
+ let stderr = "";
145
+ const timer = setTimeout(() => (c.kill("SIGKILL"), all("timeout")), NATIVE_TIMEOUT_MS);
146
+ c.stdout.on("data", (d) => (stdout += d));
147
+ c.stderr.on("data", (d) => (stderr += d));
148
+ c.once("error", (e) => (clearTimeout(timer), all(errCode(e))));
149
+ c.once("close", (code) => {
150
+ clearTimeout(timer);
151
+ let got;
152
+ try {
153
+ got = JSON.parse(stdout);
154
+ }
155
+ catch {
156
+ return all(`exit ${code}: ${stderr.trim().replace(/\s+/g, " ").slice(0, 200)}`);
157
+ }
158
+ resolve(Object.fromEntries(names.map((n) => {
159
+ const g = got[n];
160
+ if (g && typeof g === "object" && typeof g.errno === "number")
161
+ return [n, ERRNO_NAMES.get(g.errno) ?? `errno ${g.errno}`];
162
+ return [n, typeof g === "string" ? g : "missing"];
163
+ })));
164
+ });
165
+ });
166
+ }
167
+ const errCode = (err) => err?.code ?? String(err?.message ?? err);
168
+ const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r("timeout"), ms).unref())]);
169
+ async function listenPort(s) {
170
+ const attempts = [];
171
+ // Only positive, non-connecting port-0 probes opt in. Fixed ports and controls stay single-shot,
172
+ // even if a caller mistakenly sets the flag. All sockets stay in this canary's same profile.
173
+ // The dynamic range has 16384 ports; even a full-range deny plus the planner's margin is finite.
174
+ const limit = s.retryOnEperm && s.port === 0 && !s.connect && Number.isInteger(s.retryOnEperm.maxAttempts)
175
+ ? Math.max(1, Math.min(16386, s.retryOnEperm.maxAttempts)) : 1;
176
+ let outcome = "missing";
177
+ for (let i = 0; i < limit; i++) {
178
+ const result = await new Promise((resolve) => {
179
+ const srv = net.createServer((c) => c.destroy());
180
+ const finish = (got) => {
181
+ const address = srv.address();
182
+ const attempt = { errorCode: got === "allowed" ? null : got, port: address && typeof address === "object" ? address.port : null };
183
+ srv.close(() => resolve({ outcome: got, attempt }));
184
+ };
185
+ srv.once("error", (e) => finish(errCode(e)));
186
+ try {
187
+ srv.listen(s.port, s.host, () => void (s.connect ? connect({ host: s.host, port: srv.address().port }) : Promise.resolve("allowed")).then(finish));
188
+ }
189
+ catch (err) {
190
+ finish(errCode(err));
191
+ }
192
+ });
193
+ attempts.push(result.attempt);
194
+ outcome = result.outcome;
195
+ if (outcome !== "EPERM")
196
+ break;
197
+ }
198
+ return { outcome, attemptCount: attempts.length, attempts, ...(s.retryOnEperm ? { retryBudget: s.retryOnEperm } : {}) };
199
+ }
200
+ function connect(opts) {
201
+ return new Promise((resolve) => {
202
+ const s = net.connect(opts);
203
+ s.once("connect", () => {
204
+ s.destroy();
205
+ resolve("allowed");
206
+ });
207
+ s.once("error", (e) => resolve(errCode(e)));
208
+ });
209
+ }
210
+ async function step(s) {
211
+ try {
212
+ switch (s.kind) {
213
+ case "write":
214
+ fs.writeFileSync(s.path, "relay probe\n");
215
+ return "allowed";
216
+ case "open-append":
217
+ fs.closeSync(fs.openSync(s.path, "a"));
218
+ return "allowed";
219
+ case "write-excl":
220
+ fs.writeFileSync(s.path, s.marker, { flag: "wx" });
221
+ return "allowed";
222
+ case "open":
223
+ fs.closeSync(fs.openSync(s.path, (s.flags === "r" ? fs.constants.O_RDONLY : fs.constants.O_WRONLY) | fs.constants.O_NOCTTY | fs.constants.O_NONBLOCK));
224
+ return "allowed";
225
+ case "readdir":
226
+ fs.readdirSync(s.path);
227
+ return "allowed";
228
+ case "exists":
229
+ fs.accessSync(s.path, fs.constants.F_OK);
230
+ return "allowed";
231
+ case "hardlink":
232
+ fs.linkSync(s.from, s.to);
233
+ return "allowed";
234
+ case "rename":
235
+ fs.renameSync(s.from, s.to);
236
+ try {
237
+ fs.renameSync(s.to, s.from);
238
+ }
239
+ catch { }
240
+ return "allowed";
241
+ case "symlink-write":
242
+ fs.symlinkSync(s.target, s.link);
243
+ fs.writeFileSync(s.file, "relay probe\n");
244
+ return "allowed";
245
+ case "refresh": {
246
+ const fd = fs.openSync(s.temp, "wx", 0o600);
247
+ try {
248
+ fs.writeSync(fd, "relay probe\n");
249
+ fs.fsyncSync(fd);
250
+ }
251
+ finally {
252
+ fs.closeSync(fd);
253
+ }
254
+ fs.chmodSync(s.temp, 0o600);
255
+ fs.renameSync(s.temp, s.onto);
256
+ fs.chmodSync(s.onto, 0o600);
257
+ return "allowed";
258
+ }
259
+ case "lock": {
260
+ const fd = fs.openSync(s.path, "a+", 0o600);
261
+ try {
262
+ fs.ftruncateSync(fd, 0);
263
+ fs.writeSync(fd, "relay probe\n");
264
+ }
265
+ finally {
266
+ fs.closeSync(fd);
267
+ }
268
+ return "allowed";
269
+ }
270
+ case "symlink":
271
+ fs.symlinkSync(s.target, s.link);
272
+ return "allowed";
273
+ case "symlink-rename":
274
+ fs.symlinkSync(s.target, s.link);
275
+ fs.renameSync(s.link, s.onto);
276
+ return "allowed";
277
+ case "mkdir":
278
+ fs.mkdirSync(s.path);
279
+ return "allowed";
280
+ case "mkdir-rename":
281
+ fs.mkdirSync(s.dir);
282
+ fs.renameSync(s.dir, s.onto);
283
+ return "allowed";
284
+ case "fifo-rename":
285
+ execFileSync("/usr/bin/mkfifo", [s.fifo], { stdio: "ignore", timeout: 5000 });
286
+ fs.renameSync(s.fifo, s.onto);
287
+ return "allowed";
288
+ case "pair-rename":
289
+ fs.writeFileSync(s.a, "relay probe\n");
290
+ fs.linkSync(s.a, s.b);
291
+ fs.renameSync(s.b, s.onto);
292
+ return "allowed";
293
+ case "unlink":
294
+ fs.unlinkSync(s.path);
295
+ return "allowed";
296
+ case "chmod":
297
+ fs.chmodSync(s.path, s.mode);
298
+ return "allowed";
299
+ case "tcp":
300
+ return await withTimeout(connect({ host: s.host, port: s.port }), s.timeoutMs);
301
+ case "udp":
302
+ return await withTimeout(new Promise((resolve) => {
303
+ // IPv6 destinations (stage 2's ::1) need an IPv6 socket; IPv4 ones get the IPv4 socket they always did.
304
+ const sock = dgram.createSocket(net.isIPv6(s.host) ? "udp6" : "udp4");
305
+ sock.once("error", (e) => (sock.close(), resolve(errCode(e))));
306
+ sock.send("relay probe", s.port, s.host, (e) => {
307
+ resolve(e ? errCode(e) : "allowed");
308
+ try {
309
+ sock.close();
310
+ }
311
+ catch { }
312
+ });
313
+ }), s.timeoutMs);
314
+ case "signal":
315
+ process.kill(s.pid, s.signal);
316
+ return "allowed";
317
+ case "listen":
318
+ return await new Promise((resolve) => {
319
+ const srv = net.createServer();
320
+ srv.once("error", (e) => resolve(errCode(e)));
321
+ srv.listen(0, s.host, () => srv.close(() => resolve("allowed")));
322
+ });
323
+ case "listen-port": {
324
+ const result = await listenPort(s);
325
+ return s.retryOnEperm ? JSON.stringify(result) : result.outcome;
326
+ }
327
+ case "udp-bind":
328
+ return await new Promise((resolve) => {
329
+ const sock = dgram.createSocket(net.isIPv6(s.host) ? "udp6" : "udp4");
330
+ sock.once("error", (e) => (sock.close(), resolve(errCode(e))));
331
+ sock.bind(s.port, s.host, () => sock.close(() => resolve("allowed")));
332
+ });
333
+ case "unix":
334
+ return await connect({ path: s.path });
335
+ case "listen-unix":
336
+ return await new Promise((resolve) => {
337
+ const srv = net.createServer((c) => c.destroy());
338
+ srv.once("error", (e) => resolve(errCode(e)));
339
+ srv.listen(s.path, () => void (s.connect ? connect({ path: s.path }) : Promise.resolve("allowed")).then((r) => srv.close(() => resolve(r))));
340
+ });
341
+ case "dns": {
342
+ // Both resolvers: the system's (getaddrinfo, through mDNSResponder) and c-ares (UDP to the configured servers).
343
+ const resolver = new dns.promises.Resolver({ timeout: s.timeoutMs, tries: 1 });
344
+ const outcomes = await Promise.all([
345
+ withTimeout(dns.promises.lookup(s.name).then(() => "allowed", errCode), s.timeoutMs),
346
+ withTimeout(resolver.resolve4(s.name).then(() => "allowed", errCode), s.timeoutMs * 2),
347
+ ]);
348
+ return outcomes.includes("allowed") ? "allowed" : outcomes.includes("timeout") ? "timeout" : outcomes[0];
349
+ }
350
+ case "exec":
351
+ return await withTimeout(new Promise((resolve) => {
352
+ const c = spawn(s.command, s.args, { stdio: ["ignore", "ignore", "pipe"] });
353
+ let stderr = "";
354
+ c.stderr.on("data", (d) => (stderr += d));
355
+ c.once("error", (e) => resolve(errCode(e)));
356
+ c.once("close", (code, signal) => {
357
+ const why = stderr.trim().replace(/\s+/g, " ").slice(0, 300);
358
+ resolve(code === 0 ? "allowed" : signal ? `signal ${signal}` : `exit ${code}${why ? `: ${why}` : ""}`);
359
+ });
360
+ }), s.timeoutMs);
361
+ case "native":
362
+ return "native steps run together";
363
+ }
364
+ }
365
+ catch (err) {
366
+ return errCode(err);
367
+ }
368
+ }
369
+ const plan = JSON.parse(process.argv[2] ?? "{}");
370
+ // The commands first: they run in processes of their own, the slowest of the canary's steps (an
371
+ // Apple event's osascript takes most of its time), so they are started before the steps tried here
372
+ // one after another, and run while those are. Each step is the same attempt whenever it starts.
373
+ const names = [
374
+ ...Object.keys(plan).filter((n) => plan[n].kind === "exec"),
375
+ ...Object.keys(plan).filter((n) => plan[n].kind !== "exec" && plan[n].kind !== "native"),
376
+ ];
377
+ const nativeChecks = Object.fromEntries(Object.entries(plan).flatMap(([n, s]) => (s.kind === "native" ? [[n, s.check]] : [])));
378
+ const [outcomes, nativeOutcomes] = await Promise.all([Promise.all(names.map((n) => step(plan[n]))), native(nativeChecks)]);
379
+ process.stdout.write(JSON.stringify({ ...Object.fromEntries(names.map((n, i) => [n, outcomes[i]])), ...nativeOutcomes }) + "\n");
380
+ process.exit(0);