@jbkjr/relay 0.0.0-stage → 1.2.2

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 +393 -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 +1539 -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 +345 -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 +641 -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 +345 -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 +635 -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 +1518 -0
  186. package/docs/pinned-codex.md +333 -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,423 @@
1
+ // The API key of a key-only target (Gemini CLI, which has no account login relay can use):
2
+ // where the person keeps it, which local, never-synced config may move it, and how relay reads it.
3
+ // docs/gemini.md §2 is the design; this is the one place relay reads a vendor credential.
4
+ //
5
+ // Relay never writes, copies, logs or prints a key. It reads the file in the worker that launches
6
+ // the turn, after every other refusal has passed, hands the value to that target's process only
7
+ // (backends/gemini.ts), and redacts it from everything it reads back (backends/acp.ts redactor).
8
+ // Every refusal names the file and what is wrong with it, never what it holds.
9
+ import fs from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { z } from "zod";
13
+ import { TARGETS } from "../targets/index.js";
14
+ import { configPath, expandHome, harnessHome, inside, relayHome, underTemp, worktreesHome } from "./config.js";
15
+ import { git } from "./git.js";
16
+ import { localConfigPath } from "./protected-config.js";
17
+ export { localConfigPath };
18
+ /** The targets that sign in with an API key only (capabilities.login "key-only"). */
19
+ export const keyOnlyTargets = () => TARGETS.filter((t) => t.capabilities.login === "key-only").map((t) => t.id);
20
+ /**
21
+ * Where the person keeps relay's API keys by default: `~/.config/relay-keys`, a directory of its
22
+ * own (mode 0700) beside relay's config directory, never inside it: `~/.config/relay/config.json`
23
+ * may be a link into a synced directory, and nothing that syncs or backs up that one carries this.
24
+ */
25
+ export const defaultKeyDir = () => path.join(os.homedir(), ".config", "relay-keys");
26
+ /** The default key file of a target: `~/.config/relay-keys/<target>-api-key`. */
27
+ export const defaultKeyFile = (target) => path.join(defaultKeyDir(), `${target}-api-key`);
28
+ /** A path the person wrote: absolute, or starting with `~/`; no line breaks or NUL. */
29
+ const keyPath = z.string().min(1).refine((p) => (p.startsWith("/") || p.startsWith("~/")) && !/[\0\r\n]/.test(p), "must be an absolute path (or start with ~/)");
30
+ function localSchema() {
31
+ const keyOnly = keyOnlyTargets();
32
+ return z.object({
33
+ targets: z.object(Object.fromEntries(keyOnly.map((id) => [id, z.object({ api_key_file: keyPath }).partial().strict()]))).partial().strict(),
34
+ }).partial().strict();
35
+ }
36
+ /** Mode bits that let anyone but the owner write. */
37
+ const OTHERS_WRITE = 0o022;
38
+ /** Mode bits that give the group or others any access. */
39
+ const OTHERS_ANY = 0o077;
40
+ const uid = () => (typeof process.getuid === "function" ? process.getuid() : -1);
41
+ const octal = (mode) => (mode & 0o7777).toString(8).padStart(4, "0");
42
+ /** Whether `dir` is or holds the home folder or relay's state, worktrees or confined agents' homes: too broad to treat as one thing. */
43
+ const broad = (dir) => [os.homedir(), relayHome(), worktreesHome(), harnessHome()].some((d) => inside(d, dir));
44
+ /**
45
+ * The real directories relay's config is shared through: where config.json leads when it, or the
46
+ * directory it is in, is a link (as when the person syncs their config from another folder), and
47
+ * the git work tree that directory is in, which is what a sync job commits and pushes (for
48
+ * example a dotfiles repository holding ~/.config/relay). A work tree that is or holds the home folder or
49
+ * relay's own directories is left out: refusing all of it would refuse every place a key could be.
50
+ * A file relay reads a secret from, or the local config that names it, must not be in one. Relay
51
+ * knows only these; any other synced folder is the person's to avoid.
52
+ */
53
+ function syncedDirs() {
54
+ const out = new Set();
55
+ for (const cfg of new Set([configPath(), path.join(os.homedir(), ".config", "relay", "config.json")])) {
56
+ let dir;
57
+ try {
58
+ if (!fs.lstatSync(cfg, { throwIfNoEntry: false }))
59
+ continue;
60
+ if (fs.lstatSync(cfg).isSymbolicLink())
61
+ dir = path.dirname(fs.realpathSync(cfg));
62
+ else if (fs.lstatSync(path.dirname(cfg)).isSymbolicLink())
63
+ dir = fs.realpathSync(path.dirname(cfg));
64
+ else
65
+ continue;
66
+ }
67
+ catch {
68
+ // A config that cannot be followed shares nothing relay can find.
69
+ continue;
70
+ }
71
+ out.add(dir);
72
+ const top = git(dir, ["rev-parse", "--show-toplevel"]);
73
+ if (!top.ok || !top.out)
74
+ continue;
75
+ try {
76
+ const tree = fs.realpathSync(top.out);
77
+ if (!broad(tree))
78
+ out.add(tree);
79
+ }
80
+ catch {
81
+ // A work tree git names but relay cannot follow: the directory itself is still refused.
82
+ }
83
+ }
84
+ return [...out];
85
+ }
86
+ /** The synced directory `dir` lies in, or null. */
87
+ function inSynced(dir) {
88
+ let real;
89
+ try {
90
+ real = fs.realpathSync(dir);
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ return syncedDirs().find((s) => real === s || real.startsWith(s.endsWith(path.sep) ? s : s + path.sep)) ?? null;
96
+ }
97
+ /**
98
+ * Where agents relay launches write without any grant, for a key file's directory, or null: a temp
99
+ * directory (os.tmpdir(), /tmp, /var/tmp), which Claude's and Codex's own sandboxes leave writable
100
+ * (core/config.ts underTemp), and relay's own state, worktrees and confined harnesses' homes. Ownership
101
+ * and mode do not stop those agents, which run as the person. A directory under the person's home is
102
+ * not one of them however the home is placed (the grant check keeps jobs from it, caller.ts), so the
103
+ * check applies to a temp directory outside the home.
104
+ */
105
+ function agentWritable(dir) {
106
+ for (const [what, d] of [["relay's state directory", relayHome()], ["the directory of relay's job worktrees", worktreesHome()], ["the directory of confined agents' state", harnessHome()]]) {
107
+ if (inside(dir, d))
108
+ return `${what} (${d}), which agents relay launches write in`;
109
+ }
110
+ if (underTemp(dir) && !inside(dir, os.homedir()))
111
+ return "a temporary directory, which Claude's and Codex's own sandboxes leave writable";
112
+ return null;
113
+ }
114
+ /** Why the local config is refused when it is a link (an lstat's, or an open that would not follow one). */
115
+ const LOCAL_LINK = "is a link; relay reads it only as a file of its own there, since it says which private file relay reads a key from";
116
+ /**
117
+ * What is wrong with the local config at `file`, from its status (the open file's, as
118
+ * loadLocalConfig reads it), or null: a regular file with one name, the person's own, that no one
119
+ * else can write.
120
+ */
121
+ export function localConfigStatProblem(st, file, me = uid()) {
122
+ if (st.isSymbolicLink?.())
123
+ return LOCAL_LINK;
124
+ if (!st.isFile())
125
+ return "is not a regular file";
126
+ if (st.uid !== me)
127
+ return "is not owned by you";
128
+ if (st.mode & OTHERS_WRITE)
129
+ return `can be changed by group or others (mode ${octal(st.mode)}); make it yours alone: chmod 600 ${file}`;
130
+ if (st.nlink !== 1)
131
+ return "has more than one name (a hard link), so a write to another file could change it";
132
+ return null;
133
+ }
134
+ /** What is wrong with the key file directory `dir`, from its lstat, or null: a real directory of the person's own that no one else can write (who could swap the key). */
135
+ export function keyDirStatProblem(st, dir, me = uid()) {
136
+ if (st.isSymbolicLink?.())
137
+ return "is a link; keep the key in a real directory of your own";
138
+ if (!st.isDirectory?.())
139
+ return "is not a directory";
140
+ if (st.uid !== me)
141
+ return "is not owned by you";
142
+ if (st.mode & OTHERS_WRITE)
143
+ return `can be changed by group or others (mode ${octal(st.mode)}), who could swap the key; make it yours alone: chmod 700 ${dir}`;
144
+ return null;
145
+ }
146
+ /**
147
+ * Relay's local config, or {} when there is none. It decides which private file relay reads and
148
+ * sends to a vendor, so it is held to the key file's standard: a regular file with one name, the
149
+ * person's own, not a link, writable by no one else, and not in a synced directory. It is opened
150
+ * as the key file is (never through a link, a FIFO not waited on) and checked and read through that
151
+ * one descriptor, so that what is checked is what is read. Throws naming every problem.
152
+ */
153
+ export function loadLocalConfig() {
154
+ const file = localConfigPath();
155
+ const where = `relay's local config at ${file}`;
156
+ let fd;
157
+ try {
158
+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
159
+ }
160
+ catch (err) {
161
+ const code = err.code;
162
+ if (code === "ENOENT")
163
+ return {};
164
+ if (code === "ELOOP" || code === "EMLINK")
165
+ throw new Error(`${where} ${LOCAL_LINK}`);
166
+ throw new Error(`relay could not open ${where} (${code ?? err.message})`);
167
+ }
168
+ let text;
169
+ try {
170
+ const problem = localConfigStatProblem(fs.fstatSync(fd), file);
171
+ if (problem)
172
+ throw new Error(`${where} ${problem}`);
173
+ const synced = inSynced(path.dirname(file));
174
+ if (synced)
175
+ throw new Error(`${where} is beside relay's synced config (in ${synced}), so it would be synced; keep it in a directory of this machine's own`);
176
+ text = fs.readFileSync(fd, "utf8");
177
+ }
178
+ finally {
179
+ fs.closeSync(fd);
180
+ }
181
+ let raw;
182
+ try {
183
+ raw = JSON.parse(text);
184
+ }
185
+ catch (err) {
186
+ throw new Error(`${where} is not valid JSON: ${err.message}`);
187
+ }
188
+ const r = localSchema().safeParse(raw);
189
+ if (!r.success) {
190
+ const problems = r.error.issues.map((i) => `${i.path.join(".") || "(top level)"}: ${i.message}`).join("; ");
191
+ throw new Error(`${where} is not valid, so relay does not read an API key with it. It may hold only targets.<id>.api_key_file, for ${keyOnlyTargets().join(", ") || "no target"}. ${problems}`);
192
+ }
193
+ return r.data;
194
+ }
195
+ /** The file relay reads `target`'s API key from: the local config's targets.<id>.api_key_file, else the default. Throws on a bad local config. */
196
+ export function apiKeyFile(target) {
197
+ const set = loadLocalConfig().targets?.[target]?.api_key_file;
198
+ return set ? path.resolve(expandHome(set)) : defaultKeyFile(target);
199
+ }
200
+ /**
201
+ * What relay's own sandbox denies to every agent it confines (src/confine, as
202
+ * ConfinementPolicy.denied, with relay's control directory), whatever its target: no read, no test
203
+ * for a name, no write. The default key directory, whole, so that a confined agent can neither
204
+ * read a key there nor list the directory; and each key-only target's key file where the local
205
+ * config moves it elsewhere, that file alone, since its directory may hold anything else of the
206
+ * person's (a denied directory above a worktree would leave a turn nothing to work in). The
207
+ * denied list takes a single file as it takes relay's config files (src/confine/probe.ts probes
208
+ * one with a read, a test for its name and an open for writing that writes nothing). When the
209
+ * local config cannot be loaded, the files it names are denied as best relay can (namedKeyFiles);
210
+ * a Gemini turn is refused then anyway. A path that is or holds the home folder or relay's own
211
+ * directories is left out: relay never reads a key there (checkKeyFile), and denying it would
212
+ * refuse every confined turn, whose worktree would lie inside it.
213
+ */
214
+ export function keyPathsToDeny() {
215
+ let named;
216
+ try {
217
+ named = keyOnlyTargets().map((t) => [t, apiKeyFile(t)]);
218
+ }
219
+ catch {
220
+ named = namedKeyFiles();
221
+ }
222
+ return [...new Set([defaultKeyDir(), ...named.map(([, file]) => file).filter((file) => !inDefaultDir(file) && !broad(file))])];
223
+ }
224
+ /**
225
+ * The directories that decide which API key relay hands a key-only target, and so whose account
226
+ * it runs on, which no job may be given or change: relay's config directory, whose local config
227
+ * names each key file; the default key directory; and each key-only target's key file directory
228
+ * where the local config moves it (unless that is too broad to hold a key, which relay refuses:
229
+ * the home folder or one holding relay's own directories). Shared, as relay's config protection
230
+ * is (protected-config.ts), by the grant check and the check of a grant a session keeps
231
+ * (caller.ts), file approvals (approvals.ts) and Claude's write denials (backends/claude.ts).
232
+ * Reading the key is another matter: agents relay confines are denied the default key directory
233
+ * and a moved key file outright, and Claude's turns may read neither (keyPathsToDeny).
234
+ *
235
+ * `problem` says why a local config that is there cannot be loaded. Relay then cannot be sure
236
+ * where it would move a key: the key files it names are read from it as best relay can, and no job
237
+ * is given a write path, or a file outside its own worktree, until it is fixed (caller.ts,
238
+ * approvals.ts): either would outlast the fix.
239
+ */
240
+ export function keyAuthority() {
241
+ const dirs = [
242
+ ["relay's config directory, whose local config says which API key file relay reads", path.dirname(localConfigPath())],
243
+ ["the directory of relay's API keys", defaultKeyDir()],
244
+ ];
245
+ let problem = null;
246
+ let moved;
247
+ try {
248
+ moved = keyOnlyTargets().map((t) => [t, apiKeyFile(t)]);
249
+ }
250
+ catch (err) {
251
+ problem = err.message;
252
+ moved = namedKeyFiles();
253
+ }
254
+ for (const [t, file] of moved) {
255
+ const dir = path.dirname(file);
256
+ if (dir !== defaultKeyDir() && !broad(dir))
257
+ dirs.push([`the directory of ${t}'s API key file`, dir]);
258
+ }
259
+ return { dirs, problem };
260
+ }
261
+ /** Best effort, for a local config relay cannot load: each targets.<id>.api_key_file in it that is a path, whatever else is wrong with it. */
262
+ function namedKeyFiles() {
263
+ let fd;
264
+ try {
265
+ // As the key file is opened: never through a link, and a FIFO in its place is not waited on.
266
+ fd = fs.openSync(localConfigPath(), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
267
+ }
268
+ catch {
269
+ return [];
270
+ }
271
+ try {
272
+ if (!fs.fstatSync(fd).isFile())
273
+ return [];
274
+ const raw = JSON.parse(fs.readFileSync(fd, "utf8"));
275
+ return Object.entries(raw?.targets ?? {}).flatMap(([t, v]) => {
276
+ const file = v?.api_key_file;
277
+ return typeof file === "string" && keyPath.safeParse(file).success ? [[t, path.resolve(expandHome(file))]] : [];
278
+ });
279
+ }
280
+ catch {
281
+ return [];
282
+ }
283
+ finally {
284
+ fs.closeSync(fd);
285
+ }
286
+ }
287
+ /** How the person saves a key at `file`: one line, typed at a hidden prompt, in a directory and file of their own. */
288
+ export function keySetup(file) {
289
+ const dir = path.dirname(file);
290
+ const q = (p) => `'${p.replace(/'/g, "'\\''")}'`;
291
+ return `Save the key there as one line, typed at a hidden prompt: mkdir -p ${q(dir)} && chmod 700 ${q(dir)} && (umask 077; printf 'API key: '; IFS= read -rs KEY; echo; printf '%s\\n' "$KEY" > ${q(file)}; unset KEY)`;
292
+ }
293
+ /** What is wrong with an open key file's status, or null: it must be a regular file with one name, the person's own, readable and writable by no one else. */
294
+ export function keyStatProblem(st, me = uid()) {
295
+ if (!st.isFile())
296
+ return "is not a regular file";
297
+ if (st.uid !== me)
298
+ return "is not owned by you";
299
+ if (st.mode & OTHERS_ANY)
300
+ return `can be read or written by group or others (mode ${octal(st.mode)}); make it yours alone: chmod 600`;
301
+ if (st.nlink !== 1)
302
+ return "has more than one name (a hard link), so another file could be it";
303
+ return null;
304
+ }
305
+ /** A key's content: one line of 20 to 512 of the characters API keys are made of (Google's are 39). */
306
+ const KEY_TEXT = /^[A-Za-z0-9._~-]{20,512}$/;
307
+ /**
308
+ * Other vendors' one-line secrets, which KEY_TEXT alone would take: a local config pointed at one of
309
+ * these files would have relay send it to Google. Refused by their published prefixes. Not a barrier
310
+ * against every secret of that alphabet (what is, is that only the person can write the local
311
+ * config); it catches the likeliest mistake. Google's own keys begin "AIza".
312
+ */
313
+ const OTHER_VENDORS = [
314
+ [/^sk-ant-/, "Anthropic's"],
315
+ [/^sk-/, "OpenAI's (or another sk- key)"],
316
+ [/^(gh[pousr]_|github_pat_)/, "GitHub's"],
317
+ [/^xai-/, "xAI's"],
318
+ [/^glpat-/, "GitLab's"],
319
+ [/^xox[abeprs]-/, "Slack's"],
320
+ [/^(AKIA|ASIA)[A-Z0-9]{16}$/, "AWS's"],
321
+ ];
322
+ /** More than a key and a line break could ever take. */
323
+ const MAX_BYTES = 1024;
324
+ /**
325
+ * Reads the API key in `file`, after checking that nobody but the person could have put it there
326
+ * or can read it: its directory is a real directory of theirs that no one else can write; the file
327
+ * itself, checked on the descriptor relay reads (opened without following a link, so nothing can be
328
+ * swapped in between the check and the read), is a regular file with one name, theirs, readable by
329
+ * no one else; and it holds exactly one key and one optional line break. Anything else (a JSON
330
+ * credential, a key with a variable name in front, two lines) is refused, not sent. Errors name
331
+ * the file and the problem, never the content.
332
+ */
333
+ export function readKeyFile(file) {
334
+ return checkKeyFile(file, { content: true });
335
+ }
336
+ /**
337
+ * readKeyFile's checks, with `content` false stopping before the file's content is read: the
338
+ * directory's and the open file's status only (doctor, where the person has not opted in). Returns
339
+ * the key when `content` is true, else null; throws as readKeyFile does.
340
+ */
341
+ export function checkKeyFile(file, { content }) {
342
+ const where = `the API key file ${file}`;
343
+ const dir = path.dirname(file);
344
+ const dst = fs.lstatSync(dir, { throwIfNoEntry: false });
345
+ if (!dst)
346
+ throw new Error(`there is no API key file at ${file}. ${keySetup(file)}`);
347
+ const dirProblem = keyDirStatProblem(dst, dir);
348
+ if (dirProblem)
349
+ throw new Error(`the directory of ${where} (${dir}) ${dirProblem}`);
350
+ const synced = inSynced(dir);
351
+ if (synced)
352
+ throw new Error(`${where} is in relay's synced config directory (${synced}), so it would be synced; keep it in a directory of this machine's own, such as ${defaultKeyDir()}`);
353
+ if (broad(dir))
354
+ throw new Error(`${where} is in ${dir}, which is or holds your home folder or relay's own directories, so relay cannot keep jobs from writing beside it; keep the key in a directory of its own, such as ${defaultKeyDir()}`);
355
+ const open = agentWritable(dir);
356
+ if (open)
357
+ throw new Error(`${where} is in ${open}, so an agent relay launches could swap in a key of another account; keep it in a directory of your own, such as ${defaultKeyDir()}`);
358
+ let fd;
359
+ try {
360
+ // O_NONBLOCK: a FIFO in its place opens at once (and is then refused) instead of waiting for a writer.
361
+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
362
+ }
363
+ catch (err) {
364
+ const code = err.code;
365
+ if (code === "ENOENT")
366
+ throw new Error(`there is no API key file at ${file}. ${keySetup(file)}`);
367
+ if (code === "ELOOP" || code === "EMLINK")
368
+ throw new Error(`${where} is a link; relay reads a key only from a file of your own at that path`);
369
+ throw new Error(`relay could not open ${where} (${code ?? err.message})`);
370
+ }
371
+ try {
372
+ const problem = keyStatProblem(fs.fstatSync(fd));
373
+ if (problem)
374
+ throw new Error(`${where} ${problem}`);
375
+ if (!content)
376
+ return null;
377
+ const buf = Buffer.alloc(MAX_BYTES + 1);
378
+ let n = 0;
379
+ for (let got; n < buf.length && (got = fs.readSync(fd, buf, n, buf.length - n, null)) > 0;)
380
+ n += got;
381
+ if (n > MAX_BYTES)
382
+ throw new Error(`${where} is too large to hold one API key`);
383
+ const text = buf.subarray(0, n).toString("utf8").replace(/\r?\n$/, "");
384
+ if (!KEY_TEXT.test(text))
385
+ throw new Error(`${where} does not hold one API key: it must be one line of 20 to 512 letters, digits and . _ ~ - (Google's keys are 39), with nothing before or after it`);
386
+ const other = OTHER_VENDORS.find(([shape]) => shape.test(text));
387
+ if (other)
388
+ throw new Error(`${where} holds what looks like ${other[1]} secret, not a Google API key, so relay does not send it to Google`);
389
+ return text;
390
+ }
391
+ finally {
392
+ fs.closeSync(fd);
393
+ }
394
+ }
395
+ /** `target`'s API key, from its key file (apiKeyFile), checked as readKeyFile says. */
396
+ export const readApiKey = (target) => readKeyFile(apiKeyFile(target));
397
+ /** Whether `file` lies in the default key directory, which relay's sandbox denies whole to confined agents (keyPathsToDeny). */
398
+ const inDefaultDir = (file) => path.resolve(file).startsWith(defaultKeyDir() + path.sep);
399
+ /**
400
+ * For doctor: where `target`'s key file is and whether relay would read it, never what it holds.
401
+ * `problem` is why relay would refuse it (as a turn would), or null; `denied` how relay's sandbox
402
+ * keeps confined agents from it (keyPathsToDeny): its whole directory where it is in the default
403
+ * one, the file itself where the local config moves it, null where relay cannot tell which file it
404
+ * is. With `content` false (the person has not opted in, so no turn would read it), the file's
405
+ * content is not read: only where it is and its status.
406
+ */
407
+ export function keyFileStatus(target, { content }) {
408
+ let file;
409
+ try {
410
+ file = apiKeyFile(target);
411
+ }
412
+ catch (err) {
413
+ return { file: null, problem: err.message, denied: null };
414
+ }
415
+ const denied = inDefaultDir(file) ? "directory" : "file";
416
+ try {
417
+ checkKeyFile(file, { content });
418
+ }
419
+ catch (err) {
420
+ return { file, problem: err.message, denied };
421
+ }
422
+ return { file, problem: null, denied };
423
+ }