@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,7 @@
1
+ // Data only: safe to import before a fixture captures its synthetic root environment.
2
+ import { TARGETS } from "../dist/targets/index.js";
3
+
4
+ /** Host identity and endpoint intent belong to each fixture, never the developer's shell. */
5
+ export const hostVar = (k: string) => k === "CLAUDECODE" || k.startsWith("CLAUDE_CODE_") || k.startsWith("CLAUDE_AGENT_SDK_")
6
+ || k === "CODEX_INTERNAL_ORIGINATOR_OVERRIDE" || TARGETS.some((t) => t.endpointEnv.test(k))
7
+ || /^ANTHROPIC_(MODEL|DEFAULT_(OPUS|SONNET|HAIKU)_MODEL)$/.test(k);
@@ -0,0 +1,197 @@
1
+ // Decoy-keychain checks (qualification item 33 for Codex; the claude-floor release check for Claude):
2
+ // a throwaway keychain with one generic-password item, tried from an agent's sandboxed commands in
3
+ // pairs. Floored: the decoy's directory is in never.paths, as ~/Library/Keychains is in the floor, and
4
+ // the item must stay out of reach whatever the keychain IPC (the security daemons). Control: the same
5
+ // turn without that entry, which must match doctor's documented keychain IPC (core/never-coverage.ts
6
+ // neverKeychainIpc). Where that IPC is open (Codex with the network, and Claude's network-on turns,
7
+ // the only ones its check runs), the control retrieves the item, which shows that a floored refusal
8
+ // comes from the file deny, not from a broken command: that pair is the causal control. Where it is
9
+ // closed (Codex without the network) the control is refused too, so that pair only observes that
10
+ // the refusal is consistent with the documented IPC; it is no evidence about the file deny.
11
+ // Reading an item in a file-based keychain needs both its keychain file and the daemons
12
+ // (measured by hand with sandbox-exec on Darwin 27.0, 2026-11-04). Host only, behind
13
+ // RELAY_TEST_KEYCHAIN_LIVE=1: it creates a keychain file in a scratch directory (never under
14
+ // ~/Library/Keychains) and deletes it afterwards.
15
+ //
16
+ // It runs only under the test harness's scratch HOME (test/helpers.ts) and refuses otherwise:
17
+ // `security` keeps the user search list and default keychain under $HOME, so the person's are never
18
+ // written. Every decoy command names the keychain by its path. Checked by hand on Darwin 27.0: under a
19
+ // scratch HOME, create-keychain at an explicit path changes neither the scratch nor the person's
20
+ // search list or default, and the item is added, read and deleted by that path. The person's search
21
+ // list and default keychain are read (HOME set to the account's home) before and after, never set;
22
+ // if they differ afterwards, cleanup throws with both readings and how to put them back by hand.
23
+ import crypto from "node:crypto";
24
+ import fs from "node:fs";
25
+ import os from "node:os";
26
+ import path from "node:path";
27
+ import { spawnSync } from "node:child_process";
28
+
29
+ export const KEYCHAIN_LIVE = process.env.RELAY_TEST_KEYCHAIN_LIVE === "1";
30
+ export const keychainSkip = process.platform !== "darwin" ? "macOS only" : !KEYCHAIN_LIVE ? "host only: RELAY_TEST_KEYCHAIN_LIVE=1" : false;
31
+
32
+ export const SECURITY = "/usr/bin/security";
33
+ /** What a `security` invocation returned; the part of spawnSync's result that matters here. */
34
+ export type SecurityResult = { status: number | null; signal?: NodeJS.Signals | null; error?: Error; stdout?: string; stderr?: string };
35
+ /** Runs `security` with the inherited (scratch) HOME, or with HOME set to `opts.home`. */
36
+ export type SecurityRunner = (args: string[], opts?: { home?: string }) => SecurityResult;
37
+ export const runSecurity: SecurityRunner = (args, opts = {}) =>
38
+ spawnSync(SECURITY, args, { encoding: "utf8", timeout: 30000, ...(opts.home ? { env: { ...process.env, HOME: opts.home } } : {}) });
39
+
40
+ const how = (r: SecurityResult) => (r.error ? String(r.error) : r.signal ? `signal ${r.signal}` : `exit ${r.status}`);
41
+ /** Runs `security` with the inherited HOME, and throws unless it ran and exited 0. */
42
+ function must(run: SecurityRunner, args: string[]): string {
43
+ const r = run(args);
44
+ if (r.error || r.signal || r.status !== 0) throw new Error(`decoy keychain: security ${args.join(" ")} failed (${how(r)}): ${(r.stderr ?? "").trim()}`);
45
+ return r.stdout ?? "";
46
+ }
47
+ const paths = (out: string): string[] => out.split("\n").map((l) => l.trim().replace(/^"|"$/g, "")).filter(Boolean);
48
+
49
+ /**
50
+ * The account's home from the user database, after checking that HOME is somewhere else: the decoy
51
+ * runs only under the test harness's scratch HOME, so `security` never writes the person's keychain
52
+ * preferences. Throws before anything is run or created.
53
+ */
54
+ function scratchHomeOnly(): string {
55
+ const accountHome = os.userInfo().homedir;
56
+ const real = (p: string) => { try { return fs.realpathSync(p); } catch { return undefined; } };
57
+ const home = process.env.HOME ? real(process.env.HOME) : undefined, account = real(accountHome);
58
+ if (!home || !account || home === account) {
59
+ throw new Error(`decoy keychain: refusing to run with HOME=${JSON.stringify(process.env.HOME ?? "")}: the decoy runs only under the test harness's scratch HOME (test/helpers.ts), so the person's keychain preferences (search list and default keychain, kept under the real home) are never written`);
60
+ }
61
+ return accountHome;
62
+ }
63
+
64
+ /** One read of the person's keychain preferences. A non-zero exit is part of it (there may be no default). */
65
+ type Reading = { status: number | null; stdout: string };
66
+ type Fingerprint = { list: Reading; dflt: Reading };
67
+ const LIST = ["list-keychains", "-d", "user"], DEFAULT = ["default-keychain", "-d", "user"];
68
+ function read(run: SecurityRunner, args: string[], home: string): Reading {
69
+ const r = run(args, { home });
70
+ // A read that did not run to completion (spawn error, timeout, signal) says nothing about the state.
71
+ if (r.error || r.signal) throw new Error(`decoy keychain: could not read the person's keychain preferences: security ${args.join(" ")} did not complete (${how(r)})`);
72
+ return { status: r.status, stdout: r.stdout ?? "" };
73
+ }
74
+ /** The person's search list and default keychain, read with HOME set to the account's home. Writes nothing. */
75
+ const fingerprint = (run: SecurityRunner, home: string): Fingerprint => ({ list: read(run, LIST, home), dflt: read(run, DEFAULT, home) });
76
+ const sameReading = (a: Reading, b: Reading) => a.status === b.status && a.stdout === b.stdout;
77
+ const shown = (r: Reading) => `exit ${r.status} ${JSON.stringify(r.stdout.trim())}`;
78
+ const quoted = (ps: string[]) => ps.map((p) => JSON.stringify(p)).join(" ");
79
+
80
+ /** Throws, with both readings and how to put back what changed, unless `after` reads as `before`. */
81
+ function unchanged(before: Fingerprint, after: Fingerprint): void {
82
+ const fixes: string[] = [];
83
+ if (!sameReading(before.list, after.list)) {
84
+ const list = paths(before.list.stdout);
85
+ fixes.push(before.list.status === 0 && list.length
86
+ ? `security list-keychains -d user -s ${quoted(list)}`
87
+ : `the search list read back ${before.list.status === 0 ? "empty" : `as ${shown(before.list)}`} before; check it with security list-keychains -d user`);
88
+ }
89
+ if (!sameReading(before.dflt, after.dflt)) {
90
+ const dflt = paths(before.dflt.stdout)[0];
91
+ fixes.push(before.dflt.status === 0 && dflt
92
+ ? `security default-keychain -d user -s ${quoted([dflt])}`
93
+ : `there was no default keychain before (${shown(before.dflt)}); check it with security default-keychain -d user`);
94
+ }
95
+ if (!fixes.length) return;
96
+ throw new Error("decoy keychain: the person's user keychain search list or default keychain changed while the decoy existed (this helper only reads them).\n" +
97
+ ` before: search list ${shown(before.list)}; default ${shown(before.dflt)}\n` +
98
+ ` after: search list ${shown(after.list)}; default ${shown(after.dflt)}\n` +
99
+ `Put them back by hand, in a shell with your own HOME: ${fixes.join("; ")}`);
100
+ }
101
+
102
+ export type DecoyKeychain = { dir: string; keychain: string; service: string; account: string; secret: string; command: string[]; cleanup(): void };
103
+
104
+ /**
105
+ * A decoy keychain in `dir` (which a floored attempt lists in never.paths, as ~/Library/Keychains is
106
+ * in the floor, and its control does not), unlocked, holding one item whose access list trusts
107
+ * /usr/bin/security, as go-keyring's items for `gh` do. Callers create it inside their `try` and
108
+ * call cleanup() in `finally`; a failure while it is being set up cleans up before rethrowing. Runs
109
+ * only under a scratch HOME (see above).
110
+ */
111
+ export function decoyKeychain(dir: string, run: SecurityRunner = runSecurity): DecoyKeychain {
112
+ const accountHome = scratchHomeOnly();
113
+ const keychain = path.join(dir, "relay-decoy.keychain-db");
114
+ const password = crypto.randomBytes(16).toString("hex");
115
+ const secret = `RELAY_DECOY_KEYCHAIN_${crypto.randomBytes(8).toString("hex")}`;
116
+ const service = "relay-decoy-keychain-item", account = "relay-decoy";
117
+ const before = fingerprint(run, accountHome);
118
+ let created = false;
119
+ const cleanup = () => {
120
+ const problems: string[] = [];
121
+ if (created || fs.existsSync(keychain)) {
122
+ try { must(run, ["delete-keychain", keychain]); created = false; } catch (err) { problems.push((err as Error).message); }
123
+ }
124
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch (err) { problems.push(`decoy keychain: could not remove ${dir}: ${(err as Error).message}`); }
125
+ try { unchanged(before, fingerprint(run, accountHome)); } catch (err) { problems.push((err as Error).message); }
126
+ if (problems.length) throw new Error(problems.join("\n"));
127
+ };
128
+ try {
129
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
130
+ must(run, ["create-keychain", "-p", password, keychain]);
131
+ created = true;
132
+ must(run, ["set-keychain-settings", keychain]); // No auto-lock during the turn.
133
+ must(run, ["unlock-keychain", "-p", password, keychain]);
134
+ must(run, ["add-generic-password", "-a", account, "-s", service, "-w", secret, "-T", SECURITY, keychain]);
135
+ } catch (err) {
136
+ try { cleanup(); } catch (also) { throw new Error(`${(err as Error).message}\n${(also as Error).message}`); }
137
+ throw err;
138
+ }
139
+ const command = [SECURITY, "find-generic-password", "-a", account, "-s", service, "-w", keychain];
140
+ return { dir, keychain, service, account, secret, command, cleanup };
141
+ }
142
+
143
+ /** One step of a caller's teardown, named for the error that reports its failure. */
144
+ export type TeardownStep = readonly [name: string, step: () => unknown];
145
+
146
+ /**
147
+ * Runs `body`, then every teardown step in the order given, each attempted whatever `body` or an
148
+ * earlier step threw, so a decoy cleanup that throws (by design: a failed delete, changed keychain
149
+ * preferences) cannot skip restoring the environment or removing scratch directories. The order is
150
+ * the caller's to keep: decoy cleanup first, while HOME is still the scratch one, since its
151
+ * mutating `security` commands use the inherited HOME. Failures: the body's own error alone, unchanged,
152
+ * when teardown succeeded; a teardown error alone, unchanged, when only one step failed after a
153
+ * passing body; otherwise an AggregateError holding the body's error first, then each step's, with
154
+ * every message in its own.
155
+ */
156
+ export async function withTeardown<T>(body: () => T | Promise<T>, steps: readonly TeardownStep[]): Promise<T> {
157
+ const failures: { name: string; error: unknown }[] = [];
158
+ let result: T | undefined;
159
+ try { result = await body(); } catch (error) { failures.push({ name: "", error }); }
160
+ for (const [name, step] of steps) {
161
+ try { await step(); } catch (error) { failures.push({ name, error }); }
162
+ }
163
+ if (!failures.length) return result as T;
164
+ if (failures.length === 1) throw failures[0].error;
165
+ const text = (e: unknown) => (e instanceof Error ? e.message : String(e));
166
+ const message = failures.map(({ name, error }) => (name ? `teardown step ${JSON.stringify(name)} also failed: ${text(error)}` : text(error))).join("\n");
167
+ throw new AggregateError(failures.map((f) => f.error), message);
168
+ }
169
+
170
+ /**
171
+ * The decoy command as one shell command line that leaves evidence of having run:
172
+ * `<command> && echo KEYCHAIN_DECOY_EXIT:0 || echo KEYCHAIN_DECOY_EXIT:1`. It uses no shell
173
+ * variables (no `$?`): Claude Code refuses an unattended command whose variables it can't check
174
+ * before it runs, and that refusal leaves no marker. Without the marker the command did not run (a
175
+ * refusal, a launch failure, a timeout, a signal), which is never evidence about the keychain. The
176
+ * line's own text names both markers, so the text echoed back without output reads as two, not one.
177
+ */
178
+ export const EXIT_MARKER = "KEYCHAIN_DECOY_EXIT";
179
+ export const wrapped = (decoy: DecoyKeychain): string => `${decoy.command.map((a) => `'${a.replaceAll("'", "'\\''")}'`).join(" ")} && echo ${EXIT_MARKER}:0 || echo ${EXIT_MARKER}:1`;
180
+
181
+ /**
182
+ * Judges one attempt's output, which must carry exactly one exit marker (wrapped() prints one; its
183
+ * text, echoed back, holds two). The secret with a marker of 0 is a retrieval; a nonzero marker
184
+ * without the secret is a refusal; anything else (no marker, several, a 0 without the secret, the
185
+ * secret with a nonzero marker) is not evidence, and throws.
186
+ */
187
+ export function attempt(decoy: DecoyKeychain, output: string): "retrieved" | "refused" {
188
+ const markers = [...output.matchAll(new RegExp(`${EXIT_MARKER}:(\\d+)`, "g"))].map((m) => Number(m[1]));
189
+ if (markers.length !== 1) throw new Error(`decoy keychain: expected one ${EXIT_MARKER} marker in the attempt's output, found ${markers.length}; the command did not run as expected, which is not evidence. Its output (last 600 characters, secret redacted): ${JSON.stringify(output.replaceAll(decoy.secret, "<secret>").slice(-600))}`);
190
+ const got = output.includes(decoy.secret);
191
+ if (got && markers[0] === 0) return "retrieved";
192
+ if (!got && markers[0] !== 0) return "refused";
193
+ throw new Error(`decoy keychain: inconsistent attempt (exit ${markers[0]}, secret ${got ? "printed" : "absent"}); not evidence`);
194
+ }
195
+
196
+ /** Whether `output` shows the decoy's secret (the unsandboxed positive control). */
197
+ export const retrieved = (decoy: DecoyKeychain, output: string): boolean => output.includes(decoy.secret);
@@ -0,0 +1,44 @@
1
+ /** Resources acquired by one live test, including ones acquired while it is being cancelled. */
2
+ export class LiveScope {
3
+ readonly controller = new AbortController();
4
+ readonly signal = this.controller.signal;
5
+ private stops: { stop: () => Promise<void>; priority: number }[] = [];
6
+ private closing?: Promise<void>;
7
+
8
+ defer(stop: () => void | Promise<void>, priority = 0): () => Promise<void> {
9
+ let stopped: Promise<void> | undefined;
10
+ const once = () => stopped ??= Promise.resolve().then(stop);
11
+ this.stops.push({ stop: once, priority });
12
+ // An allocation already in progress may finish after the deadline. It must still be stopped.
13
+ if (this.signal.aborted) void once().catch(() => {});
14
+ return once;
15
+ }
16
+
17
+ wait<T>(work: Promise<T>): Promise<T> {
18
+ if (this.signal.aborted) {
19
+ void work.catch(() => {});
20
+ return Promise.reject(this.signal.reason);
21
+ }
22
+ return new Promise((resolve, reject) => {
23
+ const abort = () => {
24
+ this.signal.removeEventListener("abort", abort);
25
+ reject(this.signal.reason);
26
+ };
27
+ this.signal.addEventListener("abort", abort, { once: true });
28
+ work.then(resolve, reject).finally(() => this.signal.removeEventListener("abort", abort));
29
+ });
30
+ }
31
+
32
+ close(): Promise<void> {
33
+ return this.closing ??= (async () => {
34
+ this.controller.abort(new Error("live test ended"));
35
+ const errors: unknown[] = [];
36
+ // LIFO: turns stop before their brokers, models and environment authorities.
37
+ while (this.stops.length) {
38
+ this.stops.sort((a, b) => a.priority - b.priority);
39
+ try { await this.stops.pop()!.stop(); } catch (err) { errors.push(err); }
40
+ }
41
+ if (errors.length) throw new AggregateError(errors, "live test cleanup failed");
42
+ })();
43
+ }
44
+ }
@@ -0,0 +1,192 @@
1
+ import "./helpers.ts";
2
+ import assert from "node:assert/strict";
3
+ import { test } from "node:test";
4
+ import { createMediatedNetworkProvider, MEDIATED_NETWORK_EFFECT, mediatedLookup, mediatedNetworkProblem, setMediatedNetworkProviderForTests } from "../dist/core/mediated-network-provider.js";
5
+ import { Resolver } from "node:dns/promises";
6
+ import dns from "node:dns";
7
+ import { resolveNeverPolicy } from "../dist/core/never-policy.js";
8
+ import { stage2NetworkRules, checkStage2Network } from "../dist/confine/seatbelt-stage2.js";
9
+ import { neverSeatbeltRules } from "../dist/confine/seatbelt-never.js";
10
+ import { screenAddresses } from "../dist/confine/proxy.js";
11
+ import { requiredDecider, escalationEffect } from "../dist/core/escalation-policy.js";
12
+ import { withDefaults } from "../dist/core/config.js";
13
+
14
+ const base = { mode: "stage2", deniedTcp: [49160], deniedUdp: [49161], relayRange: [49201, 49202, 49203], execPort: 49201, bindPorts: [], worktreeSockets: false, egress: "none" } as const;
15
+ const policy = (never = {}) => resolveNeverPolicy({ builtins: false, never });
16
+ const caps = [{ kind: "network", mode: "mediated" }] as const;
17
+ const deferred = () => { let resolve; const promise = new Promise(r => resolve = r); return { promise, resolve: v => resolve(v) }; };
18
+
19
+ test("worker DNS fakes: follows full CNAME chain, refuses loops, cancellation reaches resolver", async t => {
20
+ let looping = false, pending = false, rejectPending, cancels = 0;
21
+ t.mock.method(Resolver.prototype, "resolveCname", async name => {
22
+ if (pending) return new Promise((_ok, reject) => rejectPending = reject);
23
+ return looping ? [name] : name === "origin.test" ? ["middle.test"] : name === "middle.test" ? ["target.test"] : [];
24
+ });
25
+ t.mock.method(Resolver.prototype, "resolve4", async name => { assert.equal(name, "target.test"); return ["8.8.8.8"]; });
26
+ t.mock.method(Resolver.prototype, "resolve6", async () => []);
27
+ t.mock.method(Resolver.prototype, "cancel", () => { cancels++; rejectPending?.(new Error("DNS cancelled")); });
28
+ const c = new AbortController();
29
+ assert.deepEqual(await mediatedLookup("origin.test", c.signal), { addresses: ["8.8.8.8"], cnames: ["middle.test", "target.test"] });
30
+ looping = true; await assert.rejects(mediatedLookup("origin.test", c.signal), /CNAME loop/);
31
+ pending = true;
32
+ const answer = mediatedLookup("origin.test", c.signal); const rejected = assert.rejects(answer, /cancelled/);
33
+ await Promise.resolve(); c.abort(); await rejected;
34
+ assert.ok(cancels >= 3);
35
+ });
36
+
37
+ test("provider fakes: cancellation during listener preparation closes partial resource", async () => {
38
+ const controller = new AbortController(), opened = deferred(), release = deferred(); let closed = 0;
39
+ const provider = createMediatedNetworkProvider({ open: async () => {
40
+ opened.resolve(); await release.promise; return { port: 49202, close: async () => { closed++; } };
41
+ } });
42
+ const preparing = provider.prepare({ capabilities: caps, policy: policy(), baseline: undefined, network: base, spec: { signal: controller.signal }, env: {}, tmpDir: "/tmp", proxyPort: 49202 });
43
+ const rejected = assert.rejects(preparing, /ended/);
44
+ await opened.promise; controller.abort(); release.resolve(); await rejected;
45
+ assert.equal(closed, 1);
46
+ });
47
+
48
+ async function fixture(p = policy(), lookup = async () => ({ addresses: ["8.8.8.8"], cnames: [] }), signal?) {
49
+ let options, closes = 0;
50
+ const provider = createMediatedNetworkProvider({ lookup, open: async o => {
51
+ options = o;
52
+ return { port: o.listen.port, close: async () => { closes++; } };
53
+ } });
54
+ const context = { capabilities: caps, baseline: undefined, policy: p, network: base, spec: { signal }, env: {}, tmpDir: "/tmp", proxyPort: 49202 };
55
+ const launch = await provider.prepare(context);
56
+ return { provider, context, launch, options, closes: () => closes, resolve: (host, port = 443) => options.publicPolicy.resolve(host, port) };
57
+ }
58
+
59
+ test("mediated provider without never hosts: OS lookup and underscore names retain port and resolved-address denies", async t => {
60
+ const lookedUp = [];
61
+ t.mock.method(Resolver.prototype, "resolveCname", () => assert.fail("must use the OS resolver"));
62
+ t.mock.method(dns.promises, "lookup", async (host, options) => {
63
+ lookedUp.push(host); assert.deepEqual(options, { all: true, verbatim: true });
64
+ return (host === "mixed_name.test" ? ["8.8.8.8", "::ffff:909:909"] : ["8.8.8.8"]).map(address => ({ address }));
65
+ });
66
+ const p = { ...policy({ ports: [{ port: 49444 }, { port: 49445, destinations: "this-machine" }] }), localAddresses: ["9.9.9.9"] };
67
+ let screen;
68
+ const provider = createMediatedNetworkProvider({ open: async o => { screen = o.publicPolicy; return { port: 49202, close: async () => {} }; } });
69
+ const launch = await provider.prepare({ capabilities: caps, baseline: undefined, policy: p, network: base, spec: {}, env: {}, tmpDir: "/tmp", proxyPort: 49202 });
70
+ try {
71
+ assert.deepEqual(await screen.resolve("os_name.test", 443), ["8.8.8.8"]);
72
+ await assert.rejects(screen.resolve("os_name.test", 49444), /never.*49444/);
73
+ await assert.rejects(screen.resolve("mixed_name.test", 49445), /never.*49445/);
74
+ await assert.rejects(screen.resolve("-invalid.test", 443), /not a host name/);
75
+ assert.deepEqual(lookedUp, ["os_name.test", "mixed_name.test"]);
76
+ } finally { await launch.close(); }
77
+ });
78
+
79
+ test("mediated provider with never hosts: direct DNS traverses CNAMEs and rejects forbidden aliases", async t => {
80
+ t.mock.method(dns.promises, "lookup", () => assert.fail("a host floor requires CNAME-aware DNS"));
81
+ const names = [];
82
+ t.mock.method(Resolver.prototype, "resolveCname", async host => {
83
+ names.push(host); return ["forbidden.test", "alias.test"].includes(host) ? ["common.test"] : [];
84
+ });
85
+ t.mock.method(Resolver.prototype, "resolve4", async () => ["8.8.8.8"]);
86
+ t.mock.method(Resolver.prototype, "resolve6", async () => []);
87
+ let screen;
88
+ const provider = createMediatedNetworkProvider({ open: async o => { screen = o.publicPolicy; return { port: 49202, close: async () => {} }; } });
89
+ const launch = await provider.prepare({ capabilities: caps, baseline: undefined, policy: policy({ hosts: ["forbidden.test"] }), network: base, spec: {}, env: {}, tmpDir: "/tmp", proxyPort: 49202 });
90
+ try {
91
+ await assert.rejects(screen.resolve("alias.test", 443), /forbidden CNAME/);
92
+ assert.ok(names.includes("alias.test")); assert.ok(names.includes("common.test"));
93
+ } finally { await launch.close(); }
94
+ });
95
+
96
+ test("mediated provider: leased IPv4 proxy, executor variables only, egress none and authority wording", async () => {
97
+ const f = await fixture();
98
+ try {
99
+ assert.deepEqual(f.options.listen, { port: 49202, ipv4Only: true });
100
+ assert.equal(f.options.mode, "public"); assert.deepEqual(f.options.allow, []);
101
+ assert.equal(f.launch.network.egress, "none"); assert.equal(f.launch.network.mediatedPort, 49202);
102
+ assert.equal(f.launch.appEnv, undefined, "the app server and broker secret get no proxy variables");
103
+ for (const key of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"]) assert.equal(f.launch.executorEnv[key], "http://127.0.0.1:49202");
104
+ assert.equal(f.launch.executorEnv.NO_PROXY, ""); assert.equal(f.launch.executorEnv.no_proxy, "");
105
+ const cfg = withDefaults({});
106
+ assert.equal(requiredDecider(caps, cfg), "owning_run_root");
107
+ for (const mode of ["raw", "local"]) assert.equal(requiredDecider([{ kind: "network", mode }], cfg), "person");
108
+ assert.match(escalationEffect({ capabilities: caps }), /Public hosts.*Tools must honour proxy settings/);
109
+ assert.match(MEDIATED_NETWORK_EFFECT, /Opaque tunnels/);
110
+ assert.equal(f.provider.qualify({ ...f.context, baseline: { network: true, raw_network: true } })?.includes("cannot be combined"), true);
111
+ assert.match(f.provider.qualify({ ...f.context, capabilities: [] }), /standing network grant or an explicit one-turn/);
112
+ assert.equal(f.provider.qualify({ ...f.context, capabilities: [], baseline: { network: true } }), null);
113
+ setMediatedNetworkProviderForTests(undefined);
114
+ assert.match(mediatedNetworkProblem(f.context), /no qualified mediated provider/);
115
+ await assert.rejects(f.provider.prepare({ ...f.context, proxyPort: undefined }), /leased proxy port/);
116
+ } finally { setMediatedNetworkProviderForTests(null); await f.launch.close(); await f.launch.close(); }
117
+ assert.equal(f.closes(), 1);
118
+ });
119
+
120
+ test("mediated never: authority, every address, mapped spellings, CNAME and redirect ports", async () => {
121
+ const p = policy({ hosts: ["forbidden.test", "9.9.9.9"], ports: [{ port: 49444, destinations: "any" }] });
122
+ const f = await fixture(p, async host => host === "forbidden.test" ? { addresses: ["1.1.1.1"], cnames: ["blocked-alias.test"] }
123
+ : host === "cname.test" ? { addresses: ["8.8.8.8"], cnames: ["blocked-alias.test"] }
124
+ : host === "bad-target.test" ? { addresses: ["8.8.8.8", "::ffff:909:909"], cnames: [] }
125
+ : { addresses: ["8.8.8.8"], cnames: [] });
126
+ try {
127
+ for (const host of ["forbidden.test", "FORBIDDEN.test.", "9.9.9.9", "::ffff:9.9.9.9", "::9.9.9.9", "::ffff:0:909:909", "0:0:0:0:0:ffff:909:909", "1.1.1.1", "cname.test", "bad-target.test"]) await assert.rejects(f.resolve(host), /never/, host);
128
+ for (const host of ["2130706433", "0177.0.0.1", "127.1"]) await assert.rejects(f.resolve(host), /never|canonical/);
129
+ assert.deepEqual(await f.resolve("allowed.test"), ["8.8.8.8"]);
130
+ // The proxy does not follow redirects: the client's next request is a fresh screen.
131
+ await assert.rejects(f.resolve("allowed.test", 49444), /never.*49444/);
132
+ } finally { await f.launch.close(); }
133
+ });
134
+
135
+ test("mediated never refresh: fail closed on unavailable/stale DNS; retain rebinding endpoints", async () => {
136
+ let forbidden = "1.1.1.1", broken = false;
137
+ const f = await fixture(policy({ hosts: ["forbidden.test"] }), async host => {
138
+ if (broken) throw new Error("DNS unavailable");
139
+ return { addresses: [host === "forbidden.test" ? forbidden : "8.8.8.8"], cnames: [] };
140
+ });
141
+ try {
142
+ forbidden = "9.9.9.9";
143
+ await assert.rejects(f.resolve("9.9.9.9"), /never/);
144
+ await assert.rejects(f.resolve("1.1.1.1"), /never/);
145
+ broken = true;
146
+ await assert.rejects(f.resolve("allowed.test"), /DNS unavailable/);
147
+ } finally { await f.launch.close(); }
148
+ let time = 0;
149
+ // Capture the policy through the fake proxy instead of opening any listener.
150
+ let screen;
151
+ const delayed = createMediatedNetworkProvider({ now: () => time, lookup: async host => {
152
+ if (host === "allowed.test") time += 60000;
153
+ return { addresses: [host === "forbidden.test" ? "1.1.1.1" : "8.8.8.8"], cnames: [] };
154
+ }, open: async o => { screen = o.publicPolicy.resolve; return { port: 49202, close: async () => {} }; } });
155
+ const launch = await delayed.prepare({ ...f.context, spec: {} });
156
+ try { await assert.rejects(screen("allowed.test", 443), /fresh validated/); } finally { await launch.close(); }
157
+ await assert.rejects(fixture(policy({ hosts: ["unresolvable.test"] }), async () => ({ addresses: [], cnames: [] })), /cannot resolve/);
158
+ });
159
+
160
+ test("mediated teardown cancels pending worker DNS and forbids subsequent requests", async () => {
161
+ const entered = deferred(); let cancelled = false;
162
+ const f = await fixture(policy(), async (_host, signal) => {
163
+ entered.resolve();
164
+ return new Promise((_resolve, reject) => signal.addEventListener("abort", () => { cancelled = true; reject(new Error("DNS cancelled")); }, { once: true }));
165
+ });
166
+ const pending = f.resolve("allowed.test"); await entered.promise;
167
+ const rejected = assert.rejects(pending, /cancelled/);
168
+ await f.launch.close(); await rejected;
169
+ assert.equal(cancelled, true); assert.equal(f.closes(), 1);
170
+ await assert.rejects(f.resolve("8.8.8.8"), /ended/);
171
+ });
172
+
173
+ test("mediated profile keeps final never/control floors and additive IPv4 connects", async () => {
174
+ const f = await fixture();
175
+ try {
176
+ const params = new Map(); const param = (k, v) => { params.set(k, v); return `(param "${k}")`; };
177
+ const rules = stage2NetworkRules(f.launch.network, param, "", { tmpDir: "/tmp", worktree: "/tmp/work" });
178
+ assert.match(rules, /remote ip4 \(string-append "localhost:" \(param "MEDIATED_PORT"\)\)/);
179
+ assert.doesNotMatch(rules, /remote ip4 "\*:\*"|mDNSResponder|local udp/);
180
+ assert.doesNotThrow(() => checkStage2Network({ ...f.launch.network, connectPorts: [49220] }));
181
+ assert.throws(() => checkStage2Network({ ...f.launch.network, connectPorts: [49202] }), /protected/);
182
+ const floor = { ...policy(), authorityPorts: [49201, 49202, 49204] };
183
+ const final = neverSeatbeltRules(floor, param, "", { worktree: "/tmp/work", tmpDir: "/tmp", execPort: 49201, bindPorts: [49203], mediatedPort: 49202 }).join("\n");
184
+ assert.match(final, /remote ip6.*NEVER_CONTROL_1/);
185
+ assert.doesNotMatch(final, /remote ip4.*NEVER_CONTROL_1/);
186
+ assert.match(final, /network-bind network-inbound.*NEVER_CONTROL_1/);
187
+ assert.match(final, /remote ip4.*NEVER_CONTROL_2/);
188
+ assert.ok("reason" in screenAddresses(["8.8.8.8"], new Set(["8.8.8.8"]), []), "own public address refused");
189
+ assert.ok("reason" in screenAddresses(["8.8.8.9"], new Set(), ["8.8.8.0/24"]), "on-link public address refused");
190
+ assert.ok("reason" in screenAddresses(["::ffff:127.0.0.1"], new Set(), []));
191
+ } finally { await f.launch.close(); }
192
+ });