@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.
- package/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +201 -0
- package/LICENSES/README.md +19 -0
- package/LICENSES/codex-NOTICE.txt +6 -0
- package/README.md +393 -2
- package/SECURITY.md +145 -0
- package/adapters/briefs/claude.md +43 -0
- package/adapters/briefs/codex.md +56 -0
- package/adapters/briefs/models.json +33 -0
- package/adapters/build.mjs +8 -0
- package/adapters/claude/.claude-plugin/marketplace.json +13 -0
- package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/relay/agents/codex.md +21 -0
- package/adapters/claude/relay/agents/operator.md +21 -0
- package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
- package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
- package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
- package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
- package/adapters/claude/relay/skills/review/SKILL.md +21 -0
- package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
- package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
- package/adapters/codex/.agents/plugins/marketplace.json +20 -0
- package/adapters/codex/AGENTS.snippet.md +5 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
- package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
- package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
- package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
- package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
- package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
- package/adapters/generate.mjs +124 -0
- package/bin/relay +59 -0
- package/codex-pin.json +12 -0
- package/dist/backends/acp.js +1424 -0
- package/dist/backends/claude.js +890 -0
- package/dist/backends/cli-version.js +112 -0
- package/dist/backends/codex-app.js +1539 -0
- package/dist/backends/codex-daybreak.js +75 -0
- package/dist/backends/codex-env.js +656 -0
- package/dist/backends/codex-network.js +304 -0
- package/dist/backends/codex-pin.js +345 -0
- package/dist/backends/codex-shell-policy.js +182 -0
- package/dist/backends/codex-stage2.js +998 -0
- package/dist/backends/codex-subagents.js +47 -0
- package/dist/backends/codex.js +641 -0
- package/dist/backends/copilot.js +246 -0
- package/dist/backends/env.js +147 -0
- package/dist/backends/gemini.js +607 -0
- package/dist/backends/grok.js +337 -0
- package/dist/backends/index.js +8 -0
- package/dist/backends/native-temp.js +187 -0
- package/dist/backends/never-admission.js +90 -0
- package/dist/backends/run.js +67 -0
- package/dist/backends/stream.js +230 -0
- package/dist/backends/tool-discovery.js +15 -0
- package/dist/backends/types.js +264 -0
- package/dist/build-info.json +5 -0
- package/dist/cli.js +344 -0
- package/dist/confine/bridge.js +113 -0
- package/dist/confine/broker-core.js +76 -0
- package/dist/confine/broker-http.js +650 -0
- package/dist/confine/broker-names.js +9 -0
- package/dist/confine/broker.js +258 -0
- package/dist/confine/canary.js +380 -0
- package/dist/confine/diagnostics.js +122 -0
- package/dist/confine/gemini-tools-main.js +8 -0
- package/dist/confine/gemini-tools.js +181 -0
- package/dist/confine/hardlinks.js +58 -0
- package/dist/confine/harness-config.js +16 -0
- package/dist/confine/index.js +117 -0
- package/dist/confine/leases.js +217 -0
- package/dist/confine/paths.js +6 -0
- package/dist/confine/peer.js +115 -0
- package/dist/confine/port-policy.js +8 -0
- package/dist/confine/ports.js +365 -0
- package/dist/confine/private-root.js +208 -0
- package/dist/confine/probe-stage2.js +501 -0
- package/dist/confine/probe.js +1109 -0
- package/dist/confine/proxy.js +783 -0
- package/dist/confine/sbcheck.js +208 -0
- package/dist/confine/seatbelt-never.js +41 -0
- package/dist/confine/seatbelt-stage2.js +139 -0
- package/dist/confine/seatbelt.js +1129 -0
- package/dist/confine/sockets.js +36 -0
- package/dist/confine/turn-probe.js +19 -0
- package/dist/confine/turn.js +86 -0
- package/dist/core/adoption.js +124 -0
- package/dist/core/api-keys.js +423 -0
- package/dist/core/approvals.js +740 -0
- package/dist/core/build-identity.js +248 -0
- package/dist/core/caller.js +749 -0
- package/dist/core/calls.js +102 -0
- package/dist/core/claude-settings.js +1045 -0
- package/dist/core/config.js +453 -0
- package/dist/core/context.js +186 -0
- package/dist/core/db.js +753 -0
- package/dist/core/dispatch.js +110 -0
- package/dist/core/env-broker.js +505 -0
- package/dist/core/env-policy.js +182 -0
- package/dist/core/escalation-authority.js +76 -0
- package/dist/core/escalation-contract.js +13 -0
- package/dist/core/escalation-person-path.js +131 -0
- package/dist/core/escalation-policy.js +79 -0
- package/dist/core/escalation-runtime.js +135 -0
- package/dist/core/escalation-state.js +42 -0
- package/dist/core/escalations.js +191 -0
- package/dist/core/events.js +235 -0
- package/dist/core/executables.js +147 -0
- package/dist/core/extensions.js +645 -0
- package/dist/core/families.js +204 -0
- package/dist/core/git.js +657 -0
- package/dist/core/identity.js +113 -0
- package/dist/core/liveness.js +68 -0
- package/dist/core/mediated-network-provider.js +81 -0
- package/dist/core/never-checkpoint.js +76 -0
- package/dist/core/never-coverage.js +97 -0
- package/dist/core/never-network.js +49 -0
- package/dist/core/never-policy.js +302 -0
- package/dist/core/never-proxy-policy.js +109 -0
- package/dist/core/never-schema.js +61 -0
- package/dist/core/never-tools.js +56 -0
- package/dist/core/notices.js +48 -0
- package/dist/core/ops.js +959 -0
- package/dist/core/outcome.js +224 -0
- package/dist/core/params.js +32 -0
- package/dist/core/presence.js +174 -0
- package/dist/core/procs.js +546 -0
- package/dist/core/prompts.js +363 -0
- package/dist/core/protected-config.js +238 -0
- package/dist/core/raw-network.js +192 -0
- package/dist/core/redact.js +152 -0
- package/dist/core/refusal.js +33 -0
- package/dist/core/relay-command.js +310 -0
- package/dist/core/reported.js +3 -0
- package/dist/core/restart-overlay.js +651 -0
- package/dist/core/retention.js +1135 -0
- package/dist/core/secrets.js +329 -0
- package/dist/core/session-token.js +175 -0
- package/dist/core/session.js +744 -0
- package/dist/core/shell.js +2 -0
- package/dist/core/shipped-pin.js +47 -0
- package/dist/core/shown.js +42 -0
- package/dist/core/slots.js +67 -0
- package/dist/core/stage2-executors.js +453 -0
- package/dist/core/stage2-switch.js +5 -0
- package/dist/core/steering.js +149 -0
- package/dist/core/storage.js +358 -0
- package/dist/core/toml.js +175 -0
- package/dist/core/views.js +324 -0
- package/dist/core/wait.js +114 -0
- package/dist/core/wake.js +207 -0
- package/dist/core/watch.js +247 -0
- package/dist/core/worktree.js +213 -0
- package/dist/hosts/claude-desktop.js +274 -0
- package/dist/hosts/claude.js +249 -0
- package/dist/hosts/codex.js +345 -0
- package/dist/hosts/desktop-shared.js +20 -0
- package/dist/hosts/index.js +11 -0
- package/dist/hosts/types.js +4 -0
- package/dist/install/basics.js +18 -0
- package/dist/install/claude-init.js +133 -0
- package/dist/install/common.js +655 -0
- package/dist/install/doctor.js +635 -0
- package/dist/install/qualify-codex.js +205 -0
- package/dist/install.js +524 -0
- package/dist/mcp/elicit.js +209 -0
- package/dist/mcp/gateway.js +218 -0
- package/dist/mcp/host.js +253 -0
- package/dist/mcp/server.js +1124 -0
- package/dist/mcp/stdio.js +37 -0
- package/dist/modes/discussion.js +393 -0
- package/dist/modes/review.js +722 -0
- package/dist/native/relay-sbcheck +0 -0
- package/dist/targets/briefs.js +86 -0
- package/dist/targets/claude.js +94 -0
- package/dist/targets/codex.js +66 -0
- package/dist/targets/copilot.js +93 -0
- package/dist/targets/gemini.js +119 -0
- package/dist/targets/grok.js +126 -0
- package/dist/targets/index.js +192 -0
- package/dist/targets/types.js +18 -0
- package/dist/targets/verified.js +35 -0
- package/dist/worker.js +113 -0
- package/docs/UPGRADING.md +1518 -0
- package/docs/pinned-codex.md +333 -0
- package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
- package/experiments/stage2-redteam/lib/report.mjs +35 -0
- package/npm-shrinkwrap.json +1632 -0
- package/package.json +82 -4
- package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
- package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
- package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
- package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
- package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
- package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
- package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
- package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
- package/scripts/codex-qualify/main-module.mjs +14 -0
- package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
- package/scripts/codex-qualify/scratch-env.mjs +31 -0
- package/scripts/codex-qualify/session.mjs +96 -0
- package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
- package/test/codex-permissions.test.ts +875 -0
- package/test/fixtures/boundary-probes.mjs +17 -0
- package/test/fixtures/denial-stream-host.mjs +7 -0
- package/test/fixtures/families.json +246 -0
- package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
- package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
- package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
- package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
- package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
- package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
- package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
- package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
- package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
- package/test/fixtures/link-parent.mjs +6 -0
- package/test/fixtures/mediated-command.cjs +72 -0
- package/test/fixtures/native-skill-isolation.json +280 -0
- package/test/fixtures/pinned-codex-app-server.mjs +25 -0
- package/test/fixtures/qualified-ext-adapters.mjs +36 -0
- package/test/fixtures/refusals/README.md +52 -0
- package/test/fixtures/refusals/claude-source-result.json +7 -0
- package/test/fixtures/refusals/openai-app-capacity.json +24 -0
- package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
- package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
- package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
- package/test/fixtures/refusals/openai-review-capacity.json +24 -0
- package/test/fixtures/relay-0.2.0.sql +57 -0
- package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
- package/test/fixtures/relay-0.9.1.sql +340 -0
- package/test/fixtures/slow-boundary-probes.mjs +37 -0
- package/test/fixtures/stable-surfaces/config.json +1122 -0
- package/test/fixtures/stable-surfaces/escalation.json +128 -0
- package/test/fixtures/stable-surfaces/events.json +37 -0
- package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
- package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
- package/test/fixtures/stable-surfaces/notice.txt +1 -0
- package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
- package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
- package/test/fixtures/stable-surfaces/registry.json +49 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
- package/test/fixtures/stable-surfaces/tools.json +716 -0
- package/test/fixtures/stable-surfaces/usage.txt +46 -0
- package/test/fixtures/stage2-acp-native.mjs +138 -0
- package/test/fixtures/stage2-app-server.mjs +23 -0
- package/test/fixtures/stage2-catalog.json +91 -0
- package/test/fixtures/stage2-hostile-web.mjs +35 -0
- package/test/fixtures/stage2-native-network.mjs +62 -0
- package/test/fixtures/stage2-worker.ts +87 -0
- package/test/fixtures/status-views/expected.json +7825 -0
- package/test/fixtures/status-views/registries.json +1 -0
- package/test/fixtures/steering.json +209 -0
- package/test/helpers.ts +740 -0
- package/test/host-env.ts +7 -0
- package/test/keychain-decoy.ts +197 -0
- package/test/live-scope.ts +44 -0
- package/test/mediated-network.test.ts +192 -0
- package/test/mediated-proxy.test.ts +264 -0
- package/test/native-temp-alias.ts +10 -0
- package/test/never-policy.test.ts +629 -0
- package/test/never-tools.test.ts +136 -0
- package/test/process-home.ts +18 -0
- package/test/proxy.test.ts +531 -0
- package/test/restart-overlay-live.test.ts +85 -0
- package/test/restart-overlay-profile.test.ts +66 -0
- package/test/restart-overlay.test.ts +416 -0
- package/test/stable-surfaces.test.ts +249 -0
- package/test/stage2-escalation-live.test.ts +544 -0
- package/test/stage2-escalation-qualification.test.ts +170 -0
- package/test/stage2-escalation.test.ts +747 -0
- package/test/stage2-executor.test.ts +849 -0
- package/test/stage2-grant.test.ts +603 -0
- package/test/stage2-native-live.test.ts +647 -0
- package/test/stage2-network-decisions.test.ts +70 -0
- package/test/stage2-probe.test.ts +845 -0
- package/test/stage2-standing-live.test.ts +203 -0
- package/test/stubs/broker-host.mjs +59 -0
- package/test/stubs/broker-peer.mjs +20 -0
- package/test/stubs/confined-harness.mjs +91 -0
- package/test/stubs/ext-broken-server.mjs +2 -0
- package/test/stubs/ext-odd-server.mjs +21 -0
- package/test/stubs/ext-server.mjs +31 -0
- package/test/stubs/fake-host-cli.mjs +218 -0
- package/test/stubs/procargs.mjs +30 -0
- package/test/stubs/stub-acp +4 -0
- package/test/stubs/stub-agent.mjs +322 -0
- package/test/stubs/stub-claude +4 -0
- package/test/stubs/stub-codex +4 -0
- package/test/stubs/targets/acp.mjs +307 -0
- package/test/stubs/targets/claude.mjs +149 -0
- package/test/stubs/targets/codex.mjs +479 -0
- package/test/stubs/targets/gemini.mjs +604 -0
- package/test/temp-root.ts +11 -0
- package/test/wp4-adapters.test.ts +353 -0
- package/test/wp4-interlock.test.ts +136 -0
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// The network a Codex turn gets when it is given one (a grant or child_network), and what relay
|
|
2
|
+
// checks before it trusts it. Codex's own sandbox with `network.enabled = true` alone opens every
|
|
3
|
+
// outbound connection, Unix sockets anywhere and all of loopback (sandboxing/src/seatbelt.rs
|
|
4
|
+
// dynamic_network_policy_for_network). With its network proxy on (features.network_proxy, experimental
|
|
5
|
+
// in 0.163.0 and 0.164.0), the shell's traffic goes through a proxy Codex runs outside the sandbox,
|
|
6
|
+
// Seatbelt lets commands reach only that proxy's two loopback ports, and the proxy refuses loopback,
|
|
7
|
+
// private and other non-public destinations unless allow_local_binding is on. So relay gives a
|
|
8
|
+
// network grant one of three modes:
|
|
9
|
+
//
|
|
10
|
+
// - strict: the proxy, allow_local_binding off, Unix sockets only under the turn's TMPDIR and (a
|
|
11
|
+
// write turn) the job's worktree;
|
|
12
|
+
// - local: the same with allow_local_binding on (all of loopback and the LAN), a write job's only,
|
|
13
|
+
// with the person's consent (grant.local_network);
|
|
14
|
+
// - hosted: no shell network at all, Codex's hosted web search only, where relay cannot verify the
|
|
15
|
+
// proxy (an unknown feature key is silently ignored by Codex, so reading back the key proves nothing).
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import net from "node:net";
|
|
18
|
+
import os from "node:os";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import { publicAddress } from "../confine/proxy.js";
|
|
21
|
+
/** What a proxied turn's network does and does not reach, in the words the agent and the caller are told. */
|
|
22
|
+
export const NETWORK_MODE_TEXT = {
|
|
23
|
+
strict: "strict: shell network through Codex's proxy. HTTP(S) works (curl, git over https, npm, pip); raw TCP, ssh remotes, direct DNS, this Mac's loopback and the local network do not. Residual: system trustd certificate fetches can bypass these network restrictions",
|
|
24
|
+
local: "local: shell network through Codex's proxy, with this Mac's loopback and the local network open (the person consented). HTTP(S) works; raw TCP to other hosts, ssh remotes and direct DNS do not. Residual: system trustd certificate fetches can bypass these network restrictions",
|
|
25
|
+
hosted: "hosted search only: Codex's hosted web search works; the shell has no network",
|
|
26
|
+
};
|
|
27
|
+
// --- Addresses ---
|
|
28
|
+
/** An IPv4 address as its four octets, or null. */
|
|
29
|
+
function octets(ip) {
|
|
30
|
+
if (net.isIPv4(ip))
|
|
31
|
+
return ip.split(".").map(Number);
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
/** An IPv6 address (zone id dropped) as its eight 16-bit groups, an embedded dotted IPv4 tail included, or null. */
|
|
35
|
+
export function ipv6Groups(ip) {
|
|
36
|
+
const a = ip.split("%")[0];
|
|
37
|
+
if (!net.isIPv6(a))
|
|
38
|
+
return null;
|
|
39
|
+
// A dotted IPv4 tail (`::ffff:127.0.0.1`) as the two hex groups it stands for.
|
|
40
|
+
const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(a)?.[1];
|
|
41
|
+
const o = tail ? octets(tail) : null;
|
|
42
|
+
const text = o ? `${a.slice(0, -tail.length)}${((o[0] << 8) | o[1]).toString(16)}:${((o[2] << 8) | o[3]).toString(16)}` : a;
|
|
43
|
+
const [head, rest] = text.split("::");
|
|
44
|
+
const left = head ? head.split(":") : [];
|
|
45
|
+
const right = rest ? rest.split(":") : [];
|
|
46
|
+
const gap = rest !== undefined ? 8 - left.length - right.length : 0;
|
|
47
|
+
const groups = [...left, ...Array(Math.max(gap, 0)).fill("0"), ...right].map((g) => parseInt(g, 16));
|
|
48
|
+
return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) ? groups : null;
|
|
49
|
+
}
|
|
50
|
+
const inV4 = (o, base, prefix) => {
|
|
51
|
+
const n = ((o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3]) >>> 0;
|
|
52
|
+
const b = ((base[0] << 24) | (base[1] << 16) | (base[2] << 8) | base[3]) >>> 0;
|
|
53
|
+
const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
|
|
54
|
+
return (n & mask) === (b & mask);
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Codex's proxy's own classification of an IPv4 address as non-public, which it refuses with
|
|
58
|
+
* allow_local_binding off: network-proxy/src/policy.rs is_non_public_ipv4 (rust-v0.164.0 lines
|
|
59
|
+
* 62-80; unchanged in 0.163.0 and 0.165.0). Rust's is_loopback, is_private, is_link_local,
|
|
60
|
+
* is_unspecified, is_multicast and is_broadcast, then its CIDR list.
|
|
61
|
+
*/
|
|
62
|
+
function codexNonPublicV4(o) {
|
|
63
|
+
return inV4(o, [127, 0, 0, 0], 8) // is_loopback
|
|
64
|
+
|| inV4(o, [10, 0, 0, 0], 8) || inV4(o, [172, 16, 0, 0], 12) || inV4(o, [192, 168, 0, 0], 16) // is_private
|
|
65
|
+
|| inV4(o, [169, 254, 0, 0], 16) // is_link_local
|
|
66
|
+
|| inV4(o, [0, 0, 0, 0], 32) // is_unspecified
|
|
67
|
+
|| inV4(o, [224, 0, 0, 0], 4) // is_multicast
|
|
68
|
+
|| inV4(o, [255, 255, 255, 255], 32) // is_broadcast
|
|
69
|
+
|| inV4(o, [0, 0, 0, 0], 8) // "this network" (RFC 1122)
|
|
70
|
+
|| inV4(o, [100, 64, 0, 0], 10) // CGNAT (RFC 6598)
|
|
71
|
+
|| inV4(o, [192, 0, 0, 0], 24) // IETF Protocol Assignments (RFC 6890)
|
|
72
|
+
|| inV4(o, [192, 0, 2, 0], 24) // TEST-NET-1
|
|
73
|
+
|| inV4(o, [198, 18, 0, 0], 15) // Benchmarking (RFC 2544)
|
|
74
|
+
|| inV4(o, [198, 51, 100, 0], 24) // TEST-NET-2
|
|
75
|
+
|| inV4(o, [203, 0, 113, 0], 24) // TEST-NET-3
|
|
76
|
+
|| inV4(o, [240, 0, 0, 0], 4); // Reserved (RFC 6890)
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Codex's proxy's classification of an address as non-public (policy.rs is_non_public_ip, lines
|
|
80
|
+
* 55-60, and is_non_public_ipv6, lines 105-119, rust-v0.164.0): an IPv6 address Rust's to_ipv4
|
|
81
|
+
* turns into an IPv4 one (`::a.b.c.d` and `::ffff:a.b.c.d`, so `::1` as 0.0.0.1) is judged as that,
|
|
82
|
+
* or loopback; otherwise loopback, unspecified, multicast (ff00::/8), unique local (fc00::/7) and
|
|
83
|
+
* unicast link-local (fe80::/10). Anything else, a global IPv6 address included, is public to it.
|
|
84
|
+
*/
|
|
85
|
+
export function codexNonPublicIp(ip) {
|
|
86
|
+
const v4 = octets(ip);
|
|
87
|
+
if (v4)
|
|
88
|
+
return codexNonPublicV4(v4);
|
|
89
|
+
const g = ipv6Groups(ip);
|
|
90
|
+
if (!g)
|
|
91
|
+
return true;
|
|
92
|
+
const loopback = g.slice(0, 7).every((x) => x === 0) && g[7] === 1;
|
|
93
|
+
if (g.slice(0, 5).every((x) => x === 0) && (g[5] === 0 || g[5] === 0xffff)) {
|
|
94
|
+
return codexNonPublicV4([g[6] >> 8, g[6] & 255, g[7] >> 8, g[7] & 255]) || loopback;
|
|
95
|
+
}
|
|
96
|
+
return loopback || g.every((x) => x === 0) || (g[0] & 0xff00) === 0xff00 || (g[0] & 0xfe00) === 0xfc00 || (g[0] & 0xffc0) === 0xfe80;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The first address of this Mac's own interfaces, internal ones included (a public address aliased
|
|
100
|
+
* on lo0 is still this Mac's), that either Codex's proxy or relay's own proxy (confine/proxy.ts
|
|
101
|
+
* publicAddress) treats as public, with why that matters, or null. Codex's
|
|
102
|
+
* proxy decides by the address alone: one of the Mac's own public addresses (a global IPv6 address,
|
|
103
|
+
* say) is a public destination to it, so a command could reach every service listening on all
|
|
104
|
+
* interfaces of this Mac (sshd among them) through the proxy. Strict mode is not offered then.
|
|
105
|
+
*/
|
|
106
|
+
export function ownPublicAddress(interfaces = os.networkInterfaces()) {
|
|
107
|
+
for (const [name, addrs] of Object.entries(interfaces)) {
|
|
108
|
+
for (const a of addrs ?? []) {
|
|
109
|
+
const address = a.address.split("%")[0];
|
|
110
|
+
const codex = !codexNonPublicIp(address);
|
|
111
|
+
if (codex || publicAddress(address)) {
|
|
112
|
+
return {
|
|
113
|
+
address,
|
|
114
|
+
why: `this Mac's interface ${name} has the address ${address}, which ${codex ? "Codex's network proxy" : "relay"} treats as public, so a command could reach this Mac's own services through the proxy at that address`,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
// --- Exec-policy rules ---
|
|
122
|
+
/**
|
|
123
|
+
* The folders Codex reads `rules/*.rules` from for a turn in `cwd` (core/src/exec_policy.rs
|
|
124
|
+
* load_exec_policy, rust-v0.164.0 lines 667-686: each config layer's folder, config/src/state.rs
|
|
125
|
+
* config_folder: the user layer's ($CODEX_HOME), the system layer's (/etc/codex) and each project
|
|
126
|
+
* layer's `.codex`). Taken from the layers config/read reports, and, so that a layer it leaves out
|
|
127
|
+
* still counts, also $CODEX_HOME (or ~/.codex), /etc/codex and the `.codex` folder of the turn's
|
|
128
|
+
* directory and of every directory above it (config/src/loader/mod.rs discover_project_layers reads
|
|
129
|
+
* those between the project root and cwd; every ancestor is a superset).
|
|
130
|
+
*/
|
|
131
|
+
export function codexRuleFolders(o) {
|
|
132
|
+
const out = new Set();
|
|
133
|
+
if (Array.isArray(o.layers)) {
|
|
134
|
+
for (const l of o.layers) {
|
|
135
|
+
const n = l?.name;
|
|
136
|
+
if (!n || typeof n !== "object")
|
|
137
|
+
continue;
|
|
138
|
+
if ((n.type === "user" || n.type === "system") && typeof n.file === "string")
|
|
139
|
+
out.add(path.dirname(n.file));
|
|
140
|
+
if (n.type === "project" && typeof n.dotCodexFolder === "string")
|
|
141
|
+
out.add(n.dotCodexFolder);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const home = o.env.HOME || os.homedir();
|
|
145
|
+
out.add(o.env.CODEX_HOME || path.join(home, ".codex"));
|
|
146
|
+
out.add("/etc/codex");
|
|
147
|
+
for (let d = path.resolve(o.cwd);; d = path.dirname(d)) {
|
|
148
|
+
out.add(path.join(d, ".codex"));
|
|
149
|
+
if (path.dirname(d) === d)
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
return [...out];
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Exec-policy rules files in these folders that hold `network_rule`, read as plain text, or why they
|
|
156
|
+
* could not all be read. A rule allowing an exact local host (`127.0.0.1`, `localhost`) counts in
|
|
157
|
+
* Codex's proxy as an explicit local allowlist entry, which opens that host even with
|
|
158
|
+
* allow_local_binding off (network-proxy/src/runtime.rs:866-868, is_explicit_local_allowlisted
|
|
159
|
+
* at :1343; connect_policy.rs:103-110), and relay cannot read rules back from the app server. Any
|
|
160
|
+
* `network_rule` at all, in any form, keeps a turn out of strict mode: the text is not parsed.
|
|
161
|
+
*/
|
|
162
|
+
export function networkRuleFiles(folders) {
|
|
163
|
+
const files = [];
|
|
164
|
+
for (const folder of folders) {
|
|
165
|
+
const dir = path.join(folder, "rules");
|
|
166
|
+
let names;
|
|
167
|
+
try {
|
|
168
|
+
names = fs.readdirSync(dir);
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
const code = err.code;
|
|
172
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
173
|
+
continue;
|
|
174
|
+
return { error: `relay could not read Codex's rules folder ${dir} (${code ?? err.message})` };
|
|
175
|
+
}
|
|
176
|
+
for (const name of names.sort()) {
|
|
177
|
+
if (!name.endsWith(".rules"))
|
|
178
|
+
continue;
|
|
179
|
+
const file = path.join(dir, name);
|
|
180
|
+
try {
|
|
181
|
+
if (fs.statSync(file).isDirectory())
|
|
182
|
+
continue;
|
|
183
|
+
if (fs.readFileSync(file, "utf8").includes("network_rule"))
|
|
184
|
+
files.push(file);
|
|
185
|
+
}
|
|
186
|
+
catch (err) {
|
|
187
|
+
return { error: `relay could not read Codex's rules file ${file} (${err.code ?? err.message})` };
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return { files };
|
|
192
|
+
}
|
|
193
|
+
// --- The canary ---
|
|
194
|
+
/**
|
|
195
|
+
* Run by Codex itself in the turn's sandbox (command/exec with relay's profile) before any agent
|
|
196
|
+
* runs: whether it was given a proxy, and what becomes of a direct loopback connection, a Unix
|
|
197
|
+
* socket outside the places allowed, and a request for loopback through the proxy. argv: the port
|
|
198
|
+
* and socket of relay's own listeners. Prints one JSON line.
|
|
199
|
+
*/
|
|
200
|
+
export const CANARY_SCRIPT = `(()=>{const net=require("net");const [port,sock]=process.argv.slice(1);const r={proxy:process.env.HTTP_PROXY||null};let n=0;
|
|
201
|
+
const done=()=>{if(++n===3){process.stdout.write(JSON.stringify(r)+"\\n");process.exit(0)}};
|
|
202
|
+
const t=(k,o)=>{const s=net.connect(o);s.setTimeout(5000);s.on("connect",()=>{r[k]="connected";s.destroy();done()});s.on("error",(e)=>{r[k]=e.code||String(e.message);done()});s.on("timeout",()=>{r[k]="timeout";s.destroy();done()})};
|
|
203
|
+
t("loop",{host:"127.0.0.1",port:+port});t("unix",{path:sock});
|
|
204
|
+
if(!r.proxy){r.viaProxy="no proxy";done()}else{let u;try{u=new URL(r.proxy)}catch{r.viaProxy="bad proxy";done();return}
|
|
205
|
+
const q=net.connect({host:u.hostname,port:+u.port},()=>q.write("GET http://127.0.0.1:"+port+"/relay-canary HTTP/1.1\\r\\nHost: 127.0.0.1:"+port+"\\r\\nConnection: close\\r\\n\\r\\n"));
|
|
206
|
+
let b="";q.setTimeout(5000);q.on("data",(d)=>{b+=d});q.on("end",()=>{r.viaProxy=b.split("\\r\\n")[0];done()});q.on("timeout",()=>{r.viaProxy="timeout";q.destroy()});q.on("error",(e)=>{if(r.viaProxy===undefined){r.viaProxy=e.code||"error";done()}})}})()`;
|
|
207
|
+
export async function openCanaryTargets() {
|
|
208
|
+
// Short, under /tmp (a Unix socket path is limited to 104 bytes), private to this user, and outside
|
|
209
|
+
// the turn's TMPDIR and worktree.
|
|
210
|
+
const dir = fs.realpathSync(fs.mkdtempSync("/tmp/relay-cn-"));
|
|
211
|
+
fs.chmodSync(dir, 0o700);
|
|
212
|
+
const sock = path.join(dir, "s");
|
|
213
|
+
const hits = { tcp: 0, unix: 0 };
|
|
214
|
+
const tcp = net.createServer((s) => { hits.tcp++; s.destroy(); });
|
|
215
|
+
const unix = net.createServer((s) => { hits.unix++; s.destroy(); });
|
|
216
|
+
try {
|
|
217
|
+
await new Promise((resolve, reject) => { tcp.once("error", reject); tcp.listen(0, "127.0.0.1", () => resolve()); });
|
|
218
|
+
await new Promise((resolve, reject) => { unix.once("error", reject); unix.listen(sock, () => resolve()); });
|
|
219
|
+
}
|
|
220
|
+
catch (err) {
|
|
221
|
+
tcp.close();
|
|
222
|
+
unix.close();
|
|
223
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
224
|
+
throw err;
|
|
225
|
+
}
|
|
226
|
+
return {
|
|
227
|
+
port: tcp.address().port, sock, hits: () => ({ ...hits }),
|
|
228
|
+
close: () => { tcp.close(); unix.close(); fs.rmSync(dir, { recursive: true, force: true }); },
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
const SANDBOX_DENIED = new Set(["EPERM", "EACCES"]);
|
|
232
|
+
/**
|
|
233
|
+
* What the canary's output says is wrong with the turn's network for `mode`, or null. Strict: a
|
|
234
|
+
* proxy on loopback, Seatbelt refusing a direct loopback connection and the Unix socket, the proxy
|
|
235
|
+
* refusing loopback (403), and nothing reaching relay's listeners. Local: the proxy, and the socket
|
|
236
|
+
* refused, nothing reaching it (loopback is open by design, relay's port included).
|
|
237
|
+
*/
|
|
238
|
+
export function canaryProblem(stdout, mode, hits) {
|
|
239
|
+
let r;
|
|
240
|
+
try {
|
|
241
|
+
r = JSON.parse(stdout.trim().split("\n").pop() ?? "");
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return `its sandbox check printed no result (${JSON.stringify(stdout.slice(0, 200))})`;
|
|
245
|
+
}
|
|
246
|
+
if (typeof r.proxy !== "string" || !/^http:\/\/127\.0\.0\.1:\d+\/?$/.test(r.proxy))
|
|
247
|
+
return `a command in its sandbox was not given Codex's network proxy (HTTP_PROXY ${JSON.stringify(r.proxy ?? null)})`;
|
|
248
|
+
if (!SANDBOX_DENIED.has(String(r.unix)))
|
|
249
|
+
return `a command in its sandbox could reach a Unix socket outside the places relay allows (${JSON.stringify(r.unix)})`;
|
|
250
|
+
if (mode === "strict") {
|
|
251
|
+
if (!SANDBOX_DENIED.has(String(r.loop)))
|
|
252
|
+
return `a command in its sandbox could connect to this Mac's loopback directly (${JSON.stringify(r.loop)})`;
|
|
253
|
+
if (typeof r.viaProxy !== "string" || !r.viaProxy.startsWith("HTTP/1.1 403"))
|
|
254
|
+
return `Codex's proxy did not refuse a request for this Mac's loopback (${JSON.stringify(r.viaProxy ?? null)})`;
|
|
255
|
+
}
|
|
256
|
+
const reached = hits.unix + (mode === "strict" ? hits.tcp : 0);
|
|
257
|
+
if (reached > 0)
|
|
258
|
+
return `a command in its sandbox reached relay's own test listener (${reached} connection${reached === 1 ? "" : "s"})`;
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* For relay doctor: the non-empty exec-policy rules files Codex loads for every directory
|
|
263
|
+
* ($CODEX_HOME/rules, or ~/.codex/rules, and /etc/codex/rules; project rules depend on a job's
|
|
264
|
+
* directory, which doctor has none of), and what they mean for relay's jobs. Reads a few small files.
|
|
265
|
+
*/
|
|
266
|
+
export function codexRulesDoctor(env = process.env) {
|
|
267
|
+
const folders = [env.CODEX_HOME || path.join(env.HOME || os.homedir(), ".codex"), "/etc/codex"];
|
|
268
|
+
const found = [];
|
|
269
|
+
const networked = [];
|
|
270
|
+
const unread = [];
|
|
271
|
+
for (const folder of folders) {
|
|
272
|
+
const dir = path.join(folder, "rules");
|
|
273
|
+
let names = [];
|
|
274
|
+
try {
|
|
275
|
+
names = fs.readdirSync(dir).filter((n) => n.endsWith(".rules")).sort();
|
|
276
|
+
}
|
|
277
|
+
catch (err) {
|
|
278
|
+
if (err.code !== "ENOENT")
|
|
279
|
+
unread.push(dir);
|
|
280
|
+
}
|
|
281
|
+
for (const n of names) {
|
|
282
|
+
const file = path.join(dir, n);
|
|
283
|
+
try {
|
|
284
|
+
const text = fs.readFileSync(file, "utf8");
|
|
285
|
+
if (!text.trim())
|
|
286
|
+
continue;
|
|
287
|
+
found.push(file);
|
|
288
|
+
if (text.includes("network_rule"))
|
|
289
|
+
networked.push(file);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
unread.push(file);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const where = folders.map((f) => path.join(f, "rules")).join(" or ");
|
|
297
|
+
if (!found.length && !unread.length)
|
|
298
|
+
return `no exec-policy rules in ${where} (project .codex/rules are read per job)`;
|
|
299
|
+
return [
|
|
300
|
+
found.length ? `exec-policy rules in ${found.join(", ")}: relay's Codex jobs run the commands they allow inside the sandbox (relay's profile denies reads of credential stores, so no rule takes a command out of it)` : "",
|
|
301
|
+
networked.length ? `${networked.join(", ")} hold network_rule, so network-granted Codex jobs fall back to hosted web search only` : "",
|
|
302
|
+
unread.length ? `relay could not read ${unread.join(", ")}, so network-granted Codex jobs fall back to hosted web search only` : "",
|
|
303
|
+
].filter(Boolean).join("; ");
|
|
304
|
+
}
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
// Selection is per turn, never cached by the mutable `current` name. Published trees are sealed
|
|
2
|
+
// by the qualifier and the entire store is write-denied to every launched agent.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
import { canonical, relayCodexHome, relayCodexPinStore } from "../core/config.js";
|
|
8
|
+
import { buildIdentity, dependencyDrift, describeBuild, sameBuild } from "../core/build-identity.js";
|
|
9
|
+
import { relayPackageRoot } from "../core/protected-config.js";
|
|
10
|
+
import { readShippedPin } from "../core/shipped-pin.js";
|
|
11
|
+
const frozen = new WeakSet();
|
|
12
|
+
const versions = new WeakMap();
|
|
13
|
+
const pins = new WeakMap();
|
|
14
|
+
/** Version from the validated, selected manifest; never follows `current` again. */
|
|
15
|
+
export function codexPinVersion(cfg) { return versions.get(cfg); }
|
|
16
|
+
export const CODEX_QUALIFIER = "scripts/codex-qualify/codex-qualifier.mjs";
|
|
17
|
+
/** The module that puts a release's shipped pin in place (`relay install codex`, `relay qualify-codex --shipped`). */
|
|
18
|
+
export const CODEX_SHIPPED_PIN = "scripts/codex-qualify/codex-shipped-pin.mjs";
|
|
19
|
+
export function codexPinInfo(cfg) { return pins.get(cfg); }
|
|
20
|
+
/** One line for people: which pin is in force, and for what. */
|
|
21
|
+
export function describeCodexPin(info) {
|
|
22
|
+
return info.kind === "local"
|
|
23
|
+
? `local: Codex ${info.version}, qualified on this Mac at ${info.qualifiedAt} (${info.verdictSchema ?? "stage2-v1"})`
|
|
24
|
+
: `shipped: Codex ${info.version} (npm ${info.npmIntegrity.slice(0, 23)}…), this release's pin, qualified by the maintainer with ${describeBuild(info.shipped.relay)}`;
|
|
25
|
+
}
|
|
26
|
+
let packageRootOverride = null;
|
|
27
|
+
/** Code-only seam: the relay package whose shipped pin and build a test's shipped tree is checked against. Production always uses relay's own. */
|
|
28
|
+
export function setRelayPackageRootForTests(root) { packageRootOverride = root; }
|
|
29
|
+
/** Relay's own package (or a test's, through the seam above): where its shipped pin and build are read. */
|
|
30
|
+
export const shippedPinPackageRoot = () => packageRootOverride ?? relayPackageRoot();
|
|
31
|
+
const packageRoot = shippedPinPackageRoot;
|
|
32
|
+
/**
|
|
33
|
+
* The build this process loaded (review r_96c6b786 X1). A worker or server keeps the modules it
|
|
34
|
+
* loaded at start; after relay is upgraded in place, the disk holds the next release's build and
|
|
35
|
+
* its shipped pin, which match each other but not the code still running here. Relay's own is
|
|
36
|
+
* taken when this module loads, which is at process start (the worker and the servers import it
|
|
37
|
+
* through backends/run.ts and backends/codex.ts). A test package's is taken on first use.
|
|
38
|
+
*/
|
|
39
|
+
const loadedBuilds = new Map();
|
|
40
|
+
function loadedBuild(root) {
|
|
41
|
+
if (!loadedBuilds.has(root)) {
|
|
42
|
+
try {
|
|
43
|
+
loadedBuilds.set(root, buildIdentity(root));
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
loadedBuilds.set(root, err);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return loadedBuilds.get(root);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Whether the dependencies this process loaded were the locked ones (dependencyDrift as it stood
|
|
53
|
+
* when the build was first identified), like loadedBuild: a repair on disk afterwards does not
|
|
54
|
+
* change the modules already loaded. Taken with the build, at process start for relay's own.
|
|
55
|
+
*/
|
|
56
|
+
const loadedDrift = new Map();
|
|
57
|
+
function loadedDependencyDrift(root) {
|
|
58
|
+
if (!loadedDrift.has(root)) {
|
|
59
|
+
try {
|
|
60
|
+
loadedDrift.set(root, dependencyDrift(root));
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
loadedDrift.set(root, err.message);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return loadedDrift.get(root);
|
|
67
|
+
}
|
|
68
|
+
loadedBuild(relayPackageRoot());
|
|
69
|
+
loadedDependencyDrift(relayPackageRoot());
|
|
70
|
+
const exactKeys = (value, keys) => !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).sort().join(",") === [...keys].sort().join(",");
|
|
71
|
+
/**
|
|
72
|
+
* A shipped/ tree is run only for the release that ships its pin: the package relay runs from must
|
|
73
|
+
* ship a pin (codex-pin.json) naming exactly this tree's Codex (version and npm integrity, which
|
|
74
|
+
* relay verified the download against), and that pin's relay build must be the build running now.
|
|
75
|
+
*/
|
|
76
|
+
function checkShippedTree(m, version) {
|
|
77
|
+
if (!exactKeys(m, ["version", "binarySha256", "npmIntegrity", "codesign", "installedAt"]) || m.version !== version ||
|
|
78
|
+
!/^[a-f0-9]{64}$/.test(m.binarySha256 ?? "") || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(m.npmIntegrity ?? "") ||
|
|
79
|
+
m.codesign?.teamId !== "2DC432GLL2" || typeof m.codesign.identity !== "string" || !m.codesign.identity ||
|
|
80
|
+
typeof m.installedAt !== "string" || !Number.isFinite(Date.parse(m.installedAt)))
|
|
81
|
+
throw new Error("invalid shipped pin tree manifest");
|
|
82
|
+
const root = packageRoot();
|
|
83
|
+
const shipped = readShippedPin(root);
|
|
84
|
+
if (!shipped)
|
|
85
|
+
throw new Error("current is a release's shipped pin, and the relay running now ships none");
|
|
86
|
+
if (shipped.codex.version !== m.version || shipped.codex.npmIntegrity !== m.npmIntegrity) {
|
|
87
|
+
throw new Error(`current is the shipped pin for Codex ${m.version} (${m.npmIntegrity.slice(0, 23)}…), and this release ships Codex ${shipped.codex.version} (${shipped.codex.npmIntegrity.slice(0, 23)}…)`);
|
|
88
|
+
}
|
|
89
|
+
const build = buildIdentity(root);
|
|
90
|
+
if (!sameBuild(build, shipped.relay))
|
|
91
|
+
throw new Error(`this release's shipped pin was qualified with ${describeBuild(shipped.relay)}, and the relay running now is ${describeBuild(build)}`);
|
|
92
|
+
// The pin's identity covers relay's dependency lock; the dependencies that run must be the locked ones.
|
|
93
|
+
// At start (what this process loaded) and now (what the disk holds).
|
|
94
|
+
const atStart = loadedDependencyDrift(root);
|
|
95
|
+
if (atStart)
|
|
96
|
+
throw new Error(`when this process started, ${atStart}, so this release's shipped pin does not cover the code running here. Reinstall relay (npm install -g @jbkjr/relay@${build.version}) and restart the session, or qualify a Codex here with relay qualify-codex`);
|
|
97
|
+
const drift = dependencyDrift(root);
|
|
98
|
+
if (drift)
|
|
99
|
+
throw new Error(`${drift}, so this release's shipped pin does not cover them. Reinstall relay (npm install -g @jbkjr/relay@${build.version}), or qualify a Codex here with relay qualify-codex`);
|
|
100
|
+
// The pin and the build on disk match; the code this process runs must be that build too.
|
|
101
|
+
const loaded = loadedBuild(root);
|
|
102
|
+
if (loaded instanceof Error)
|
|
103
|
+
throw new Error(`relay could not identify the build this process started from (${loaded.message}), so it cannot match a shipped pin to it`);
|
|
104
|
+
if (!sameBuild(loaded, build))
|
|
105
|
+
throw new Error(`relay was changed on disk after this process started: it runs ${describeBuild(loaded)}, and the disk now holds ${describeBuild(build)}, whose shipped pin does not cover the code running here. Restart the session (its relay server and workers)`);
|
|
106
|
+
return shipped;
|
|
107
|
+
}
|
|
108
|
+
export function freezeCodexConfig(cfg) {
|
|
109
|
+
if (frozen.has(cfg))
|
|
110
|
+
return cfg;
|
|
111
|
+
const store = relayCodexPinStore(cfg);
|
|
112
|
+
// Missing stores and older saved configurations fail closed too. Only an explicit opt-out
|
|
113
|
+
// selects targets.codex.bin; filesystem state must never silently select interactive Codex.
|
|
114
|
+
const pinned = cfg.targets.codex.pinned !== false;
|
|
115
|
+
let bin = cfg.targets.codex.bin;
|
|
116
|
+
let version;
|
|
117
|
+
let info;
|
|
118
|
+
if (pinned) {
|
|
119
|
+
try {
|
|
120
|
+
const current = path.join(store, "current");
|
|
121
|
+
if (!fs.lstatSync(current).isSymbolicLink())
|
|
122
|
+
throw new Error("current must be a symlink");
|
|
123
|
+
const target = fs.readlinkSync(current);
|
|
124
|
+
const match = /^(versions|shipped)\/(\d+\.\d+\.\d+)-([a-f0-9]{12})$/.exec(target);
|
|
125
|
+
if (!match)
|
|
126
|
+
throw new Error("current must name a relative versions/<version>-<sha12> or shipped/<version>-<sha12> tree");
|
|
127
|
+
const dir = path.join(fs.realpathSync(store), target);
|
|
128
|
+
if (fs.realpathSync(dir) !== dir || (fs.statSync(dir).mode & 0o222))
|
|
129
|
+
throw new Error("pin tree is not immutable (symlink or unsealed directory)");
|
|
130
|
+
const manifestPath = path.join(dir, "manifest.json");
|
|
131
|
+
const manifestStat = fs.lstatSync(manifestPath);
|
|
132
|
+
if (!manifestStat.isFile() || (manifestStat.mode & 0o222))
|
|
133
|
+
throw new Error("invalid or unsealed pin manifest file");
|
|
134
|
+
const m = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
|
135
|
+
if (match[1] === "shipped") {
|
|
136
|
+
const shipped = checkShippedTree(m, match[2]);
|
|
137
|
+
if (m.binarySha256.slice(0, 12) !== match[3])
|
|
138
|
+
throw new Error("invalid shipped pin tree manifest");
|
|
139
|
+
info = { kind: "shipped", version: m.version, target, npmIntegrity: m.npmIntegrity, shipped };
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
if (m?.version !== match[2] || !/^[a-f0-9]{64}$/.test(m.binarySha256 ?? "") ||
|
|
143
|
+
m.binarySha256.slice(0, 12) !== match[3] || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(m.npmIntegrity ?? "") ||
|
|
144
|
+
m.codesign?.teamId !== "2DC432GLL2" || typeof m.codesign.identity !== "string" || !m.codesign.identity ||
|
|
145
|
+
typeof m.qualifiedAt !== "string" || !Number.isFinite(Date.parse(m.qualifiedAt)) ||
|
|
146
|
+
typeof m.verdictPath !== "string" || !path.isAbsolute(m.verdictPath) || !/^[a-f0-9]{40}$/.test(m.sourceCommit ?? "") ||
|
|
147
|
+
Object.hasOwn(m, "installedAt"))
|
|
148
|
+
throw new Error("invalid pin manifest");
|
|
149
|
+
info = { kind: "local", version: m.version, target, qualifiedAt: m.qualifiedAt, verdictSchema: m.verdictSchema };
|
|
150
|
+
}
|
|
151
|
+
bin = path.join(dir, "bin", "codex");
|
|
152
|
+
if (fs.realpathSync(bin) !== bin || (fs.statSync(path.dirname(bin)).mode & 0o222) || !fs.statSync(bin).isFile() || (fs.statSync(bin).mode & 0o222))
|
|
153
|
+
throw new Error("pin binary is not an immutable regular file");
|
|
154
|
+
fs.accessSync(bin, fs.constants.X_OK);
|
|
155
|
+
if (crypto.createHash("sha256").update(fs.readFileSync(bin)).digest("hex") !== m.binarySha256)
|
|
156
|
+
throw new Error("pin binary digest mismatch");
|
|
157
|
+
version = Object.freeze(m.version.split(".").map(Number));
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
let ships = false;
|
|
161
|
+
try {
|
|
162
|
+
ships = readShippedPin(packageRoot()) !== null;
|
|
163
|
+
}
|
|
164
|
+
catch { /* an invalid one: the qualify-codex route */ }
|
|
165
|
+
const fix = ships
|
|
166
|
+
? "Run `relay install codex --write` (or `relay qualify-codex --shipped`) to put this release's shipped pin in place, a download of a few minutes, or `relay qualify-codex` to qualify a Codex here (about an hour and a half)"
|
|
167
|
+
: `Run \`relay qualify-codex\` once from your own terminal (it runs the qualifier, ${CODEX_QUALIFIER}, and takes about an hour and a half)`;
|
|
168
|
+
throw new Error(`relay refuses Codex: no valid qualified pin in ${store}: ${err.message}. ${fix}; relay will not fall back to interactive Codex.`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const resolved = { ...cfg, targets: { ...cfg.targets, codex: { ...cfg.targets.codex, bin, pinned } } };
|
|
172
|
+
frozen.add(resolved);
|
|
173
|
+
if (version)
|
|
174
|
+
versions.set(resolved, version);
|
|
175
|
+
if (info)
|
|
176
|
+
pins.set(resolved, info);
|
|
177
|
+
return resolved;
|
|
178
|
+
}
|
|
179
|
+
// Deliberately independent of ~/.codex and the inherited CODEX_HOME. Per-turn flags still set
|
|
180
|
+
// model, permissions, endpoints, MCP and feature policy and read them back from the app server.
|
|
181
|
+
export const RELAY_CODEX_CONFIG = '# Managed by relay. Changes are replaced on the next turn.\ncli_auth_credentials_store = "file"\n';
|
|
182
|
+
let fixtureConfig = null;
|
|
183
|
+
/** Code-only fixture seam for model-free qualification's synthetic endpoints/catalogs. No
|
|
184
|
+
* environment variable or person-set config enables it; production always generates its own file. */
|
|
185
|
+
export function setCodexHomeConfigForTests(factory) { fixtureConfig = factory; }
|
|
186
|
+
/**
|
|
187
|
+
* The file relay puts in a Codex home it made or adopted, so that it can tell later that the
|
|
188
|
+
* directory is its own even after someone rewrote config.toml without relay's first line.
|
|
189
|
+
*/
|
|
190
|
+
export const RELAY_CODEX_HOME_MARKER = ".relay-codex-home";
|
|
191
|
+
const MARKER_TEXT = "This directory is relay's own Codex home (targets.codex.home). Relay rewrites its config.toml on every Codex turn.\n";
|
|
192
|
+
const MANAGED_LINE = RELAY_CODEX_CONFIG.split("\n")[0];
|
|
193
|
+
/**
|
|
194
|
+
* Why relay must not use `targets.codex.home` as its Codex home, or null. Read-only: doctor reports
|
|
195
|
+
* it, and prepareCodexHome refuses before its first write. A configured home is any absolute path,
|
|
196
|
+
* so it could name the person's own Codex home or a directory of theirs: relay makes its home
|
|
197
|
+
* private (0700) and replaces its config.toml, which would clobber theirs.
|
|
198
|
+
* - Never the person's interactive Codex home: ~/.codex, or the CODEX_HOME this process was given
|
|
199
|
+
* (compared by canonical path). A CODEX_HOME that already carries relay's evidence below is
|
|
200
|
+
* relay's own home handed down to a nested relay (a launched Codex agent's relay tools), not theirs.
|
|
201
|
+
* - An existing directory only with evidence that relay owns it: the marker file relay writes, or a
|
|
202
|
+
* config.toml that starts with relay's managed line (a home made by an earlier relay), or nothing
|
|
203
|
+
* in it at all. Anything else (a config.toml of someone else's, a login, sessions) is not relay's.
|
|
204
|
+
*/
|
|
205
|
+
export function codexHomeProblem(cfg, env = process.env) {
|
|
206
|
+
const home = relayCodexHome(cfg);
|
|
207
|
+
const at = canonical(home);
|
|
208
|
+
const named = (p) => !!p && path.isAbsolute(p) && canonical(p) === at;
|
|
209
|
+
const fix = "Set targets.codex.home in relay's config to a directory of relay's own (the default is ~/.local/share/relay-codex-home), then run `relay install codex --write`";
|
|
210
|
+
if (named(path.join(os.homedir(), ".codex")))
|
|
211
|
+
return `targets.codex.home is ${home}, your own Codex's home (~/.codex), which relay never uses for its jobs: it would replace your config.toml there. ${fix}`;
|
|
212
|
+
let st;
|
|
213
|
+
try {
|
|
214
|
+
st = fs.lstatSync(home, { throwIfNoEntry: false });
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
return `relay cannot examine its Codex home ${home} (${err.message})`;
|
|
218
|
+
}
|
|
219
|
+
if (st && !st.isDirectory())
|
|
220
|
+
return `relay's Codex home must be a directory, not ${st.isSymbolicLink() ? "a symlink" : "a file"}: ${home}`;
|
|
221
|
+
if (fixtureConfig?.(home) !== undefined)
|
|
222
|
+
return null;
|
|
223
|
+
const evidence = st ? ownershipEvidence(home) : null;
|
|
224
|
+
if (named(env.CODEX_HOME) && !evidence)
|
|
225
|
+
return `targets.codex.home is ${home}, the Codex home your environment names (CODEX_HOME), which relay never uses for its jobs: it would replace the config.toml your own Codex reads there. ${fix}`;
|
|
226
|
+
if (!st || evidence)
|
|
227
|
+
return null;
|
|
228
|
+
let entries;
|
|
229
|
+
try {
|
|
230
|
+
entries = fs.readdirSync(home);
|
|
231
|
+
}
|
|
232
|
+
catch (err) {
|
|
233
|
+
return `relay cannot read its Codex home ${home} (${err.message})`;
|
|
234
|
+
}
|
|
235
|
+
if (!entries.length)
|
|
236
|
+
return null;
|
|
237
|
+
const what = entries.includes("config.toml") ? "a config.toml relay did not write" : `files relay did not put there (${entries.slice(0, 3).join(", ")}${entries.length > 3 ? ", …" : ""})`;
|
|
238
|
+
return `${home} (targets.codex.home) holds ${what}, so relay will not take it as its Codex home: it would make it private and replace its config.toml. Relay uses only a new or empty directory, or one it made. ${fix}, or move that directory's contents away`;
|
|
239
|
+
}
|
|
240
|
+
/** What shows that an existing directory is relay's Codex home: its marker file, or relay's managed config.toml. */
|
|
241
|
+
function ownershipEvidence(home) {
|
|
242
|
+
try {
|
|
243
|
+
if (fs.lstatSync(path.join(home, RELAY_CODEX_HOME_MARKER)).isFile())
|
|
244
|
+
return "marker";
|
|
245
|
+
}
|
|
246
|
+
catch { /* absent */ }
|
|
247
|
+
try {
|
|
248
|
+
const config = path.join(home, "config.toml");
|
|
249
|
+
if (fs.lstatSync(config).isFile() && fs.readFileSync(config, "utf8").split("\n")[0] === MANAGED_LINE)
|
|
250
|
+
return "config";
|
|
251
|
+
}
|
|
252
|
+
catch { /* absent */ }
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
export function prepareCodexHome(cfg) {
|
|
256
|
+
const home = relayCodexHome(cfg);
|
|
257
|
+
// Before the first write: never a home that is not relay's (codexHomeProblem).
|
|
258
|
+
const problem = codexHomeProblem(cfg);
|
|
259
|
+
if (problem)
|
|
260
|
+
throw new Error(problem);
|
|
261
|
+
fs.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
262
|
+
if (!fs.lstatSync(home).isDirectory())
|
|
263
|
+
throw new Error(`relay's Codex home must be a directory, not a symlink: ${home}`);
|
|
264
|
+
fs.chmodSync(home, 0o700);
|
|
265
|
+
const marker = path.join(home, RELAY_CODEX_HOME_MARKER);
|
|
266
|
+
try {
|
|
267
|
+
fs.writeFileSync(marker, MARKER_TEXT, { flag: "wx", mode: 0o600 });
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
if (err.code !== "EEXIST")
|
|
271
|
+
throw err;
|
|
272
|
+
}
|
|
273
|
+
const config = path.join(home, "config.toml");
|
|
274
|
+
const contents = fixtureConfig?.(home) ?? RELAY_CODEX_CONFIG;
|
|
275
|
+
let same = false;
|
|
276
|
+
try {
|
|
277
|
+
same = fs.lstatSync(config).isFile() && fs.readFileSync(config, "utf8") === contents;
|
|
278
|
+
}
|
|
279
|
+
catch { /* create below */ }
|
|
280
|
+
if (!same) {
|
|
281
|
+
const tmp = path.join(home, `.config-${crypto.randomUUID()}.toml`);
|
|
282
|
+
try {
|
|
283
|
+
fs.writeFileSync(tmp, contents, { flag: "wx", mode: 0o600 });
|
|
284
|
+
fs.renameSync(tmp, config);
|
|
285
|
+
}
|
|
286
|
+
finally {
|
|
287
|
+
fs.rmSync(tmp, { force: true });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
// AGENTS.md belongs to the person. Never read, replace or unlink it.
|
|
291
|
+
return home;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The one-time sign-in of relay's Codex home: Codex's own `login`, run with that home, from the pin
|
|
295
|
+
* store's current Codex when relay runs pinned (else the configured binary). The home must exist
|
|
296
|
+
* first (Codex refuses a CODEX_HOME that does not), with relay's config.toml in it (prepareCodexHome),
|
|
297
|
+
* so that the login goes to the file store relay's turns read; `relay install codex --write` makes it.
|
|
298
|
+
*/
|
|
299
|
+
export function codexLoginCommand(cfg) {
|
|
300
|
+
const bin = cfg.targets.codex.pinned === false ? cfg.targets.codex.bin : path.join(relayCodexPinStore(cfg), "current", "bin", "codex");
|
|
301
|
+
return `CODEX_HOME=${JSON.stringify(relayCodexHome(cfg))} ${JSON.stringify(bin)} login`;
|
|
302
|
+
}
|
|
303
|
+
/** Where relay's Codex home cannot open a browser (a remote or headless Mac), Codex signs in with a device code instead. */
|
|
304
|
+
export const DEVICE_AUTH_NOTE = "on a remote or headless Mac, add --device-auth, which needs device code sign-in switched on in ChatGPT's Security settings";
|
|
305
|
+
/** How to sign relay's Codex home in (`again`: a login is stored there that Codex no longer accepts). */
|
|
306
|
+
export function codexSignIn(cfg, again = false) {
|
|
307
|
+
return `${again ? "Sign in again" : "Sign in once"} with ${codexLoginCommand(cfg)} (${DEVICE_AUTH_NOTE})`;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Whether relay's Codex home holds a stored login: auth.json is there, as a regular file. Metadata
|
|
311
|
+
* only, like codexHomeStatus: the file is never opened.
|
|
312
|
+
*/
|
|
313
|
+
export function codexLoginStored(home) {
|
|
314
|
+
try {
|
|
315
|
+
return fs.lstatSync(path.join(home, "auth.json")).isFile();
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Codex reports no account (account/read) though relay's Codex home holds a login: the stored login
|
|
323
|
+
* is one Codex no longer accepts. Seen on 2026-11-18 with an access token that had expired and a
|
|
324
|
+
* refresh token that had been revoked: Codex tries the refresh when its app server starts, and when
|
|
325
|
+
* that fails it reports no account. (An expired token whose refresh still works recovers by itself.)
|
|
326
|
+
*/
|
|
327
|
+
export const STORED_LOGIN_REJECTED = "Codex no longer accepts it, most likely because it expired and Codex could not refresh it (its refresh token revoked, for one)";
|
|
328
|
+
/**
|
|
329
|
+
* Metadata only: never open or parse the credential file. Symlinks are not private credentials.
|
|
330
|
+
* `problem`: why relay will not use this home (codexHomeProblem); doctor reports it and changes nothing.
|
|
331
|
+
*/
|
|
332
|
+
export function codexHomeStatus(cfg) {
|
|
333
|
+
const home = relayCodexHome(cfg);
|
|
334
|
+
let present = false, login = "missing";
|
|
335
|
+
try {
|
|
336
|
+
present = fs.lstatSync(home).isDirectory();
|
|
337
|
+
}
|
|
338
|
+
catch { /* absent */ }
|
|
339
|
+
try {
|
|
340
|
+
const st = fs.lstatSync(path.join(home, "auth.json"));
|
|
341
|
+
login = st.isFile() && (st.mode & 0o777) === 0o600 ? "present" : "unsafe permissions";
|
|
342
|
+
}
|
|
343
|
+
catch { /* absent */ }
|
|
344
|
+
return { home, present, login, problem: codexHomeProblem(cfg) };
|
|
345
|
+
}
|