@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,783 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import dns from "node:dns";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import { appendLog, logMaxBytes } from "../core/storage.js";
|
|
6
|
+
import { checkProxyHost, createNeverProxyPolicy, mediatedLookup, proxyHostName as hostName } from "../core/never-proxy-policy.js";
|
|
7
|
+
import { neverEndpointProblem } from "../core/never-policy.js";
|
|
8
|
+
// Taken as the CommonJS builtin, not imported: the registry reaches this module (for its address
|
|
9
|
+
// helpers), and Node's ES-module wrapper of node:http reads every lazy export as it is imported,
|
|
10
|
+
// which compiles its fetch implementation (undici) too: about 9 ms of every relay process's start.
|
|
11
|
+
const http = process.getBuiltinModule("node:http");
|
|
12
|
+
/**
|
|
13
|
+
* The per-turn proxy, in one of two modes.
|
|
14
|
+
*
|
|
15
|
+
* "allowlist" (the default), for a confined turn with the network off. The sandbox lets the harness
|
|
16
|
+
* reach exactly this proxy's loopback port and nothing else on the network, DNS included; the proxy
|
|
17
|
+
* tunnels HTTPS (CONNECT to port 443) to the exact host names it was given, resolving them itself,
|
|
18
|
+
* and to nothing else: no IP literals, no private, loopback or link-local addresses, no plain HTTP.
|
|
19
|
+
* Every CONNECT must carry the turn's token, so a loopback port that any local process can reach
|
|
20
|
+
* still serves only this turn.
|
|
21
|
+
*
|
|
22
|
+
* "public", for a Claude turn with the network: Claude Code's sandbox sends every connection its
|
|
23
|
+
* commands make here (sandbox.network.httpProxyPort and socksProxyPort), and the Claude process
|
|
24
|
+
* itself comes here through HTTPS_PROXY (its WebFetch and its model traffic). It reaches any public
|
|
25
|
+
* host on any port, by CONNECT, plain-HTTP forwarding or SOCKS5 CONNECT, and nothing that is not
|
|
26
|
+
* public: no loopback, private, shared (CGNAT, Tailscale), link-local, unique-local or metadata
|
|
27
|
+
* address, none of this machine's own addresses and nothing on the same link as them. Names are
|
|
28
|
+
* resolved once, here, and the screened address is what is dialled, so a name cannot be rebound
|
|
29
|
+
* between the check and the connection.
|
|
30
|
+
*
|
|
31
|
+
* Each decision is a JSON line in the turn's log. Ported from
|
|
32
|
+
* docs/research/seatbelt-prototype/proxy.ts. Zero dependencies.
|
|
33
|
+
*/
|
|
34
|
+
/** The only port tunnelled in allowlist mode. Model APIs are HTTPS. */
|
|
35
|
+
export const PROXY_PORT_ALLOWED = 443;
|
|
36
|
+
/** How long the upstream connect may take before the client gets 502. */
|
|
37
|
+
const CONNECT_TIMEOUT_MS = 15000;
|
|
38
|
+
/** How long a client of the public mode has to say what it wants before it is dropped. */
|
|
39
|
+
const HANDSHAKE_TIMEOUT_MS = 30000;
|
|
40
|
+
const HOST_LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/;
|
|
41
|
+
/** A host name relay will put on an allowlist: lower case, no trailing dot, no IP literal, no wildcard. */
|
|
42
|
+
export function allowlistHost(h) {
|
|
43
|
+
if (typeof h !== "string")
|
|
44
|
+
throw new Error(`allowlisted host is not a string: ${String(h)}`);
|
|
45
|
+
const host = h.trim().toLowerCase().replace(/\.$/, "");
|
|
46
|
+
if (net.isIP(host.replace(/^\[|\]$/g, "")))
|
|
47
|
+
throw new Error(`an IP literal cannot be allowlisted, only a host name: ${h}`);
|
|
48
|
+
if (host.length > 253 || !host.split(".").every((l) => HOST_LABEL.test(l)))
|
|
49
|
+
throw new Error(`not a host name: ${JSON.stringify(h)}`);
|
|
50
|
+
return host;
|
|
51
|
+
}
|
|
52
|
+
/** Addresses the proxy never connects to: unspecified, loopback, private, shared, link-local, multicast, reserved and documentation ranges. */
|
|
53
|
+
const BLOCKED = new net.BlockList();
|
|
54
|
+
for (const [a, p] of [
|
|
55
|
+
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12],
|
|
56
|
+
["192.0.0.0", 24], ["192.0.2.0", 24], ["192.88.99.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24],
|
|
57
|
+
["203.0.113.0", 24], ["224.0.0.0", 4], ["240.0.0.0", 4],
|
|
58
|
+
// Cloud-platform metadata endpoints in otherwise-public ranges (srt resolved-address-guard): Azure's
|
|
59
|
+
// WireServer/IMDS 168.63.129.16, which is not in any private range. (Most metadata IPs — AWS/GCP/Oracle
|
|
60
|
+
// 169.254.169.254, Alibaba 100.100.100.200 — already fall under link-local or the shared 100.64/10 range.)
|
|
61
|
+
["168.63.129.16", 32],
|
|
62
|
+
])
|
|
63
|
+
BLOCKED.addSubnet(a, p, "ipv4");
|
|
64
|
+
for (const [a, p] of [
|
|
65
|
+
["::", 128], ["::1", 128], ["64:ff9b::", 96], ["64:ff9b:1::", 48], ["100::", 64], ["2001::", 23], ["2001:db8::", 32],
|
|
66
|
+
["2002::", 16], ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8],
|
|
67
|
+
])
|
|
68
|
+
BLOCKED.addSubnet(a, p, "ipv6");
|
|
69
|
+
/** The addresses of this machine's own network interfaces, loopback included, in canonical form. */
|
|
70
|
+
export function localInterfaceAddresses() {
|
|
71
|
+
const out = new Set();
|
|
72
|
+
for (const addrs of Object.values(os.networkInterfaces())) {
|
|
73
|
+
for (const a of addrs ?? [])
|
|
74
|
+
out.add(canonicalAddress(a.address));
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* An address in one canonical form, so two spellings of the same address compare equal: the zone id
|
|
80
|
+
* is dropped; an IPv4-mapped or -compatible IPv6 address (`::ffff:1.2.3.4`, the hex `::ffff:0102:0304`,
|
|
81
|
+
* `::1.2.3.4`) becomes the dotted IPv4 it carries; any other IPv6 is expanded to its eight zero-padded
|
|
82
|
+
* groups. So the machine's own `93.184.216.34` matches a name that resolves to `::ffff:93.184.216.34`.
|
|
83
|
+
*/
|
|
84
|
+
export function canonicalAddress(ip) {
|
|
85
|
+
const a = ip.split("%")[0].toLowerCase();
|
|
86
|
+
const v4 = /^::(?:ffff:(?:0:)?)?(\d+\.\d+\.\d+\.\d+)$/.exec(a)?.[1];
|
|
87
|
+
if (v4)
|
|
88
|
+
return v4;
|
|
89
|
+
const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(a);
|
|
90
|
+
if (mapped) {
|
|
91
|
+
const [hi, lo] = [parseInt(mapped[1], 16), parseInt(mapped[2], 16)];
|
|
92
|
+
return `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
|
|
93
|
+
}
|
|
94
|
+
return net.isIPv6(a) ? expandIPv6(a) : a;
|
|
95
|
+
}
|
|
96
|
+
/** An IPv6 address as eight colon-separated four-hex-digit groups (so compressed and full forms compare equal). */
|
|
97
|
+
function expandIPv6(ip) {
|
|
98
|
+
const [head, tail] = ip.split("::");
|
|
99
|
+
const left = head ? head.split(":") : [];
|
|
100
|
+
const right = tail !== undefined ? (tail ? tail.split(":") : []) : [];
|
|
101
|
+
const gap = tail !== undefined ? 8 - left.length - right.length : 0;
|
|
102
|
+
const groups = [...left, ...Array(Math.max(gap, 0)).fill("0"), ...right];
|
|
103
|
+
return groups.map((g) => (g || "0").padStart(4, "0")).join(":");
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The subnets this machine's network interfaces are on, as `address/prefix` (os.networkInterfaces()
|
|
107
|
+
* cidr), read afresh on every call: a laptop changes networks in the middle of a turn. A device on
|
|
108
|
+
* the same link (a printer, a NAS, the router) is the person's own network even when its address
|
|
109
|
+
* is a public one, as a LAN's global IPv6 addresses are.
|
|
110
|
+
*/
|
|
111
|
+
export function localSubnets() {
|
|
112
|
+
const out = [];
|
|
113
|
+
for (const addrs of Object.values(os.networkInterfaces())) {
|
|
114
|
+
for (const a of addrs ?? [])
|
|
115
|
+
if (a.cidr)
|
|
116
|
+
out.push(a.cidr);
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** Whether `ip` lies in one of `subnets` (`address/prefix`, the interface's own address allowed in place of the network's). */
|
|
121
|
+
export function onLink(ip, subnets) {
|
|
122
|
+
const list = new net.BlockList();
|
|
123
|
+
for (const cidr of subnets) {
|
|
124
|
+
const at = cidr.lastIndexOf("/");
|
|
125
|
+
const addr = cidr.slice(0, at).split("%")[0];
|
|
126
|
+
const prefix = Number(cidr.slice(at + 1));
|
|
127
|
+
const kind = net.isIP(addr);
|
|
128
|
+
if (at < 0 || !kind || !Number.isInteger(prefix))
|
|
129
|
+
continue;
|
|
130
|
+
// An IPv4-mapped interface address is judged by the IPv4 address it carries, like a destination.
|
|
131
|
+
const v4 = kind === 6 ? canonicalAddress(addr) : addr;
|
|
132
|
+
try {
|
|
133
|
+
if (net.isIPv4(v4))
|
|
134
|
+
list.addSubnet(v4, kind === 6 ? Math.max(prefix - 96, 0) : prefix, "ipv4");
|
|
135
|
+
else
|
|
136
|
+
list.addSubnet(addr, prefix, "ipv6");
|
|
137
|
+
}
|
|
138
|
+
catch { }
|
|
139
|
+
}
|
|
140
|
+
const a = canonicalAddress(ip);
|
|
141
|
+
const kind = net.isIP(a);
|
|
142
|
+
return kind === 4 ? list.check(a, "ipv4") : kind === 6 ? list.check(a, "ipv6") : false;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Screens the addresses a name resolved to (or an IP literal, given alone). A name on the allowlist
|
|
146
|
+
* that resolves to anything but a public unicast address — a private, loopback or link-local
|
|
147
|
+
* address, cloud-metadata endpoints (169.254.169.254 and the IPv6 metadata addresses are link-local
|
|
148
|
+
* or unique-local, so already caught), an address bound to one of this machine's own interfaces (its
|
|
149
|
+
* own public IP, which would otherwise pass), or an address on the same link as one of them (a LAN
|
|
150
|
+
* device's global IPv6 address) — is never meant, and one such answer refuses the whole name. (srt
|
|
151
|
+
* resolved-address-guard.ts: the reasoning is theirs; the on-link check is relay's.) Returns the
|
|
152
|
+
* public addresses to try, or the reason to refuse.
|
|
153
|
+
*/
|
|
154
|
+
export function screenAddresses(addresses, local = localInterfaceAddresses(), subnets = localSubnets()) {
|
|
155
|
+
for (const a of addresses) {
|
|
156
|
+
if (!publicAddress(a))
|
|
157
|
+
return { reason: "private-address", address: a };
|
|
158
|
+
if (local.has(canonicalAddress(a)))
|
|
159
|
+
return { reason: "local-interface-address", address: a };
|
|
160
|
+
if (onLink(a, subnets))
|
|
161
|
+
return { reason: "on-link-address", address: a };
|
|
162
|
+
}
|
|
163
|
+
return { addresses };
|
|
164
|
+
}
|
|
165
|
+
/** Whether an address is one the proxy may connect to: a public unicast address. */
|
|
166
|
+
export function publicAddress(ip) {
|
|
167
|
+
const kind = net.isIP(ip);
|
|
168
|
+
if (kind === 4)
|
|
169
|
+
return !BLOCKED.check(ip, "ipv4");
|
|
170
|
+
if (kind !== 6)
|
|
171
|
+
return false;
|
|
172
|
+
// IPv4-mapped and -compatible forms are judged by the IPv4 address they carry.
|
|
173
|
+
const v4 = /^::(?:ffff:(?:0:)?)?(\d+\.\d+\.\d+\.\d+)$/i.exec(ip)?.[1];
|
|
174
|
+
if (v4)
|
|
175
|
+
return publicAddress(v4);
|
|
176
|
+
const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(ip);
|
|
177
|
+
if (mapped) {
|
|
178
|
+
const [hi, lo] = [parseInt(mapped[1], 16), parseInt(mapped[2], 16)];
|
|
179
|
+
return publicAddress(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
|
|
180
|
+
}
|
|
181
|
+
return !BLOCKED.check(ip, "ipv6");
|
|
182
|
+
}
|
|
183
|
+
/** The environment that points a harness at the turn's proxy. Both cases, as tools differ; Node needs NODE_USE_ENV_PROXY. */
|
|
184
|
+
export function proxyEnv(port, token) {
|
|
185
|
+
const url = `http://relay:${token}@127.0.0.1:${port}`;
|
|
186
|
+
const env = { NO_PROXY: "", no_proxy: "", NODE_USE_ENV_PROXY: "1" };
|
|
187
|
+
for (const k of ["HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY"])
|
|
188
|
+
env[k] = env[k.toLowerCase()] = url;
|
|
189
|
+
return env;
|
|
190
|
+
}
|
|
191
|
+
/** A per-turn token: URL-safe, so it can sit in a proxy URL as is. */
|
|
192
|
+
export const PROXY_TOKEN = /^[A-Za-z0-9_-]{22,}$/;
|
|
193
|
+
function authorised(req, token) {
|
|
194
|
+
const h = req.headers["proxy-authorization"];
|
|
195
|
+
const m = /^Basic\s+([A-Za-z0-9+/=]+)\s*$/i.exec(typeof h === "string" ? h : "");
|
|
196
|
+
if (!m)
|
|
197
|
+
return false;
|
|
198
|
+
const decoded = Buffer.from(m[1], "base64").toString("utf8");
|
|
199
|
+
const pass = Buffer.from(decoded.slice(decoded.indexOf(":") + 1));
|
|
200
|
+
const want = Buffer.from(token);
|
|
201
|
+
return decoded.includes(":") && pass.length === want.length && crypto.timingSafeEqual(pass, want);
|
|
202
|
+
}
|
|
203
|
+
/** CONNECT's target: `host:port` or `[v6]:port`. */
|
|
204
|
+
function parseTarget(target) {
|
|
205
|
+
const m = /^(?:\[([0-9A-Fa-f:.]+)\]|([^:[\]\s]+)):(\d{1,5})$/.exec(target);
|
|
206
|
+
if (!m)
|
|
207
|
+
return null;
|
|
208
|
+
const port = Number(m[3]);
|
|
209
|
+
return port >= 1 && port <= 65535 ? { host: (m[1] ?? m[2]).toLowerCase().replace(/\.$/, ""), port } : null;
|
|
210
|
+
}
|
|
211
|
+
/** Appends a decision to the turn's log and tells the caller. */
|
|
212
|
+
function decisionLog(opts, maxBytes) {
|
|
213
|
+
return (d) => {
|
|
214
|
+
const decision = { t: new Date().toISOString(), ...(opts.label ? { turn: opts.label } : {}), ...d };
|
|
215
|
+
// A log that cannot be written must not take the turn's network down with it.
|
|
216
|
+
try {
|
|
217
|
+
if (opts.logFile)
|
|
218
|
+
appendLog(opts.logFile, JSON.stringify(decision) + "\n", { maxBytes });
|
|
219
|
+
}
|
|
220
|
+
catch { }
|
|
221
|
+
try {
|
|
222
|
+
opts.onDecision?.(decision);
|
|
223
|
+
}
|
|
224
|
+
catch { }
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/** Starts the proxy for one turn on 127.0.0.1 at an ephemeral port (public mode: on ::1 too), with a fresh token. */
|
|
228
|
+
export async function openProxy(opts) {
|
|
229
|
+
if (!opts.neverPolicy || opts.publicPolicy)
|
|
230
|
+
return openScreenedProxy(opts);
|
|
231
|
+
const controller = new AbortController();
|
|
232
|
+
const signal = controller.signal;
|
|
233
|
+
const stub = opts.mode === "public" ? opts.modelStub : undefined;
|
|
234
|
+
const publicPolicy = createNeverProxyPolicy(opts.neverPolicy, { signal,
|
|
235
|
+
...(stub ? { lookup: async (host) => host === stub.host
|
|
236
|
+
? { addresses: ["127.0.0.1"], cnames: [] }
|
|
237
|
+
: opts.neverPolicy.hosts.length ? mediatedLookup(host, signal)
|
|
238
|
+
: { addresses: (await dns.promises.lookup(host, { all: true, verbatim: true })).map(a => a.address), cnames: [] } } : {}),
|
|
239
|
+
});
|
|
240
|
+
try {
|
|
241
|
+
await publicPolicy.refresh();
|
|
242
|
+
const proxy = await openScreenedProxy({ ...opts, publicPolicy });
|
|
243
|
+
return { ...proxy, close: async () => { controller.abort(new Error("proxy closed")); await proxy.close(); } };
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
controller.abort();
|
|
247
|
+
throw e;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async function openScreenedProxy(opts) {
|
|
251
|
+
if (opts.mode === "public")
|
|
252
|
+
return openPublicProxy(opts);
|
|
253
|
+
// Like an agent log, this proxy keeps the policy its turn started with. Reopen at each entry
|
|
254
|
+
// (appendLog), so a rotation never leaves a descriptor appending into the renamed generation.
|
|
255
|
+
const maxBytes = logMaxBytes();
|
|
256
|
+
const allow = new Set(opts.allow.map(allowlistHost));
|
|
257
|
+
const token = crypto.randomBytes(24).toString("base64url");
|
|
258
|
+
const sockets = new Set();
|
|
259
|
+
/** Set by close(): from then on nothing new is opened, lookups still pending included. */
|
|
260
|
+
let closed = false;
|
|
261
|
+
const log = decisionLog(opts, maxBytes);
|
|
262
|
+
let sawToken = false;
|
|
263
|
+
const hostsWithToken = new Set();
|
|
264
|
+
const resolve = async (host, port) => {
|
|
265
|
+
if (!opts.publicPolicy && opts.testing?.resolve)
|
|
266
|
+
return opts.testing.resolve(host);
|
|
267
|
+
const found = opts.publicPolicy ? await opts.publicPolicy.resolve(host, port)
|
|
268
|
+
: (await dns.promises.lookup(host, { all: true, verbatim: true })).map(a => a.address);
|
|
269
|
+
const screened = screenAddresses(found, opts.testing?.local, opts.testing?.subnets);
|
|
270
|
+
if ("reason" in screened)
|
|
271
|
+
throw Object.assign(new Error(`resolves to ${screened.reason === "local-interface-address" ? "this machine's own address" : "a non-public address"} (${screened.address})`), { reason: screened.reason });
|
|
272
|
+
return screened.addresses;
|
|
273
|
+
};
|
|
274
|
+
const track = (s) => {
|
|
275
|
+
sockets.add(s);
|
|
276
|
+
s.once("close", () => sockets.delete(s));
|
|
277
|
+
};
|
|
278
|
+
const server = http.createServer((req, res) => {
|
|
279
|
+
// Plain-HTTP forwarding is not offered: it would need its own allowlist and header handling.
|
|
280
|
+
log({ event: "deny", reason: "not-connect", target: `${req.method} ${req.url}` });
|
|
281
|
+
res.writeHead(405, { "content-type": "text/plain", connection: "close" }).end("relay proxy: only CONNECT to port 443 is supported\n");
|
|
282
|
+
});
|
|
283
|
+
server.on("connection", track);
|
|
284
|
+
server.on("clientError", (_err, sock) => sock.destroy());
|
|
285
|
+
server.on("connect", (req, client, head) => {
|
|
286
|
+
const target = req.url ?? "";
|
|
287
|
+
client.on("error", () => { });
|
|
288
|
+
if (closed)
|
|
289
|
+
return void client.destroy();
|
|
290
|
+
const refuse = (code, reason) => {
|
|
291
|
+
log({ event: "deny", reason, target });
|
|
292
|
+
const challenge = code === 407 ? 'Proxy-Authenticate: Basic realm="relay"\r\n' : "";
|
|
293
|
+
client.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\nProxy-Agent: relay\r\n${challenge}Connection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
294
|
+
};
|
|
295
|
+
if (!authorised(req, token))
|
|
296
|
+
return refuse(407, "bad-or-missing-token");
|
|
297
|
+
sawToken = true;
|
|
298
|
+
const t = parseTarget(target);
|
|
299
|
+
if (t)
|
|
300
|
+
hostsWithToken.add(t.host);
|
|
301
|
+
if (!t)
|
|
302
|
+
return refuse(400, "bad-target");
|
|
303
|
+
if (net.isIP(t.host))
|
|
304
|
+
return refuse(403, "ip-literal");
|
|
305
|
+
if (t.port !== PROXY_PORT_ALLOWED)
|
|
306
|
+
return refuse(403, "port-not-443");
|
|
307
|
+
if (!allow.has(t.host))
|
|
308
|
+
return refuse(403, "host-not-allowlisted");
|
|
309
|
+
client.pause();
|
|
310
|
+
resolve(t.host, t.port).then((addresses) => {
|
|
311
|
+
// The proxy closed, or the client left, while the name was being looked up: open nothing.
|
|
312
|
+
if (closed || client.destroyed)
|
|
313
|
+
return void client.destroy();
|
|
314
|
+
if (!addresses.length)
|
|
315
|
+
return refuse(502, "no-address");
|
|
316
|
+
const port = opts.testing?.upstreamPort ?? t.port;
|
|
317
|
+
const badGateway = () => client.end("HTTP/1.1 502 Bad Gateway\r\nProxy-Agent: relay\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
318
|
+
let connected = false;
|
|
319
|
+
let current = null;
|
|
320
|
+
// The resolved addresses in turn: the first that connects carries the tunnel; if one fails to
|
|
321
|
+
// connect, the next is tried, so a name with a dead address still reaches a live one.
|
|
322
|
+
const tryAt = (i) => {
|
|
323
|
+
if (closed || client.destroyed)
|
|
324
|
+
return void client.destroy();
|
|
325
|
+
if (i >= addresses.length)
|
|
326
|
+
return void badGateway();
|
|
327
|
+
const address = addresses[i];
|
|
328
|
+
const upstream = net.connect({ host: address, port });
|
|
329
|
+
current = upstream;
|
|
330
|
+
track(upstream);
|
|
331
|
+
upstream.setTimeout(CONNECT_TIMEOUT_MS, () => upstream.destroy(new Error("connect timed out")));
|
|
332
|
+
upstream.once("connect", () => {
|
|
333
|
+
if (closed || client.destroyed)
|
|
334
|
+
return void upstream.destroy();
|
|
335
|
+
connected = true;
|
|
336
|
+
upstream.setTimeout(0);
|
|
337
|
+
log({ event: "allow", target, address });
|
|
338
|
+
client.write("HTTP/1.1 200 Connection Established\r\nProxy-Agent: relay\r\n\r\n");
|
|
339
|
+
if (head.length)
|
|
340
|
+
upstream.write(head);
|
|
341
|
+
upstream.pipe(client);
|
|
342
|
+
client.pipe(upstream);
|
|
343
|
+
client.resume();
|
|
344
|
+
});
|
|
345
|
+
upstream.on("error", (e) => {
|
|
346
|
+
if (connected)
|
|
347
|
+
return void client.destroy();
|
|
348
|
+
log({ event: "upstream-error", reason: e.message, target, address });
|
|
349
|
+
tryAt(i + 1);
|
|
350
|
+
});
|
|
351
|
+
};
|
|
352
|
+
client.on("close", () => current?.destroy());
|
|
353
|
+
tryAt(0);
|
|
354
|
+
}, (err) => refuse(403, err.reason ?? `unresolved: ${err.message}`));
|
|
355
|
+
});
|
|
356
|
+
await new Promise((ok, fail) => {
|
|
357
|
+
server.once("error", fail);
|
|
358
|
+
server.listen(0, "127.0.0.1", () => {
|
|
359
|
+
server.off("error", fail);
|
|
360
|
+
ok();
|
|
361
|
+
});
|
|
362
|
+
});
|
|
363
|
+
server.on("error", () => { });
|
|
364
|
+
const port = server.address().port;
|
|
365
|
+
return {
|
|
366
|
+
port,
|
|
367
|
+
token,
|
|
368
|
+
network: { mode: "off-except-proxy", proxyPort: port, proxyToken: token },
|
|
369
|
+
authenticated: () => sawToken,
|
|
370
|
+
tokenHosts: () => hostsWithToken,
|
|
371
|
+
close: async () => {
|
|
372
|
+
if (closed)
|
|
373
|
+
return;
|
|
374
|
+
closed = true;
|
|
375
|
+
for (const s of sockets)
|
|
376
|
+
s.destroy();
|
|
377
|
+
await new Promise((ok) => server.close(() => ok()));
|
|
378
|
+
},
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
/** Headers that belong to one connection, not to the request or response carried on it (RFC 9110 §7.6.1). */
|
|
382
|
+
const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-authorization", "proxy-authenticate", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
|
|
383
|
+
function endToEnd(headers) {
|
|
384
|
+
const named = String(headers.connection ?? "").toLowerCase().split(",").map((h) => h.trim()).filter(Boolean);
|
|
385
|
+
const out = {};
|
|
386
|
+
for (const [k, v] of Object.entries(headers))
|
|
387
|
+
if (v !== undefined && !HOP_BY_HOP.has(k) && !named.includes(k))
|
|
388
|
+
out[k] = v;
|
|
389
|
+
out.connection = "close";
|
|
390
|
+
return out;
|
|
391
|
+
}
|
|
392
|
+
/** What a public-mode refusal tells the client, by reason. */
|
|
393
|
+
const REFUSED = "relay: a job's network reaches public addresses only, not loopback, private, link-local or this machine's own network";
|
|
394
|
+
/**
|
|
395
|
+
* The public mode (see the top of this file). The token is optional here, by design: Claude Code's
|
|
396
|
+
* sandbox hands its commands a proxy URL with no credentials when the proxy is external
|
|
397
|
+
* (sandbox.network.httpProxyPort), so the sandbox's connections arrive without it. That gives a
|
|
398
|
+
* caller without the token nothing it lacks anyway: the proxy reaches public addresses only, which
|
|
399
|
+
* any process of the person's can reach directly, and other jobs' sandboxes cannot reach this port
|
|
400
|
+
* (each sandbox allows only its own proxy's). The token marks the harness process's own requests
|
|
401
|
+
* (authenticated()), which is how relay knows the harness uses the proxy at all.
|
|
402
|
+
*/
|
|
403
|
+
async function openPublicProxy(opts) {
|
|
404
|
+
if (opts.allow.length)
|
|
405
|
+
throw new Error("the public proxy takes no allowlist");
|
|
406
|
+
const stub = opts.modelStub;
|
|
407
|
+
if (stub && (!hostName(stub.host) || !Number.isInteger(stub.port) || stub.port < 1 || stub.port > 65535))
|
|
408
|
+
throw new Error("a model stub is a host name and a port");
|
|
409
|
+
const log = decisionLog(opts, logMaxBytes());
|
|
410
|
+
const token = crypto.randomBytes(24).toString("base64url");
|
|
411
|
+
const sockets = new Set();
|
|
412
|
+
let closed = false;
|
|
413
|
+
let sawToken = false;
|
|
414
|
+
const hostsWithToken = new Set();
|
|
415
|
+
/** A request carrying the token, for `host`: counted, and its host kept (tokenHosts). */
|
|
416
|
+
const tokened = (host) => {
|
|
417
|
+
sawToken = true;
|
|
418
|
+
hostsWithToken.add(host);
|
|
419
|
+
};
|
|
420
|
+
const t = opts.testing;
|
|
421
|
+
const track = (s) => {
|
|
422
|
+
sockets.add(s);
|
|
423
|
+
s.once("close", () => sockets.delete(s));
|
|
424
|
+
};
|
|
425
|
+
/** The addresses `host` (a name or an IP literal) may be dialled at, or a thrown error with the reason. */
|
|
426
|
+
const screen = async (host, port, toStub = false) => {
|
|
427
|
+
if (closed)
|
|
428
|
+
throw new Error("proxy closed");
|
|
429
|
+
// The authenticated development mapping is the endpoint, so its synthetic name need
|
|
430
|
+
// not exist in DNS. Retain the floor for both the named authority and the actual dial.
|
|
431
|
+
if (toStub) {
|
|
432
|
+
if (opts.neverPolicy) {
|
|
433
|
+
const why = neverEndpointProblem(opts.neverPolicy, { host, port, transport: "tcp", addresses: ["127.0.0.1"] })
|
|
434
|
+
?? neverEndpointProblem(opts.neverPolicy, { host: "127.0.0.1", port: stub.port, transport: "tcp" });
|
|
435
|
+
if (why)
|
|
436
|
+
throw Object.assign(new Error(why), { reason: why });
|
|
437
|
+
}
|
|
438
|
+
// Include resolved aliases of forbidden hosts at the mapped destination too.
|
|
439
|
+
if (opts.publicPolicy)
|
|
440
|
+
await opts.publicPolicy.resolve(host, stub.port);
|
|
441
|
+
return ["127.0.0.1"];
|
|
442
|
+
}
|
|
443
|
+
const checked = opts.publicPolicy ? await opts.publicPolicy.resolve(host, port) : undefined;
|
|
444
|
+
const literal = net.isIP(host) !== 0;
|
|
445
|
+
if (!checked && !literal && t?.resolve)
|
|
446
|
+
return t.resolve(host);
|
|
447
|
+
checkProxyHost(host);
|
|
448
|
+
let found;
|
|
449
|
+
try {
|
|
450
|
+
found = checked ?? (literal ? [host] : t?.lookup ? await t.lookup(host) : (await dns.promises.lookup(host, { all: true, verbatim: true })).map((a) => a.address));
|
|
451
|
+
}
|
|
452
|
+
catch (e) {
|
|
453
|
+
throw Object.assign(new Error(e.message), { reason: `unresolved: ${e.code ?? "error"}` });
|
|
454
|
+
}
|
|
455
|
+
const screened = screenAddresses(found, t?.local ?? localInterfaceAddresses(), t?.subnets ?? localSubnets());
|
|
456
|
+
if ("reason" in screened)
|
|
457
|
+
throw Object.assign(new Error(screened.reason), { reason: screened.reason });
|
|
458
|
+
if (!screened.addresses.length)
|
|
459
|
+
throw Object.assign(new Error("no address"), { reason: "no-address" });
|
|
460
|
+
return screened.addresses;
|
|
461
|
+
};
|
|
462
|
+
const reasonOf = (e) => e.reason ?? "refused";
|
|
463
|
+
/** Connects to the first of `addresses` that answers on `port`, logging each that does not; null when none did or the proxy closed. */
|
|
464
|
+
const dial = (addresses, port, d) => new Promise((done) => {
|
|
465
|
+
const at = (i) => {
|
|
466
|
+
if (closed || i >= addresses.length)
|
|
467
|
+
return done(null);
|
|
468
|
+
const address = addresses[i];
|
|
469
|
+
const up = net.connect({ host: address, port: d.stub ? stub.port : t?.upstreamPort ?? port });
|
|
470
|
+
track(up);
|
|
471
|
+
up.setTimeout(CONNECT_TIMEOUT_MS, () => up.destroy(new Error("connect timed out")));
|
|
472
|
+
let settled = false;
|
|
473
|
+
up.once("close", () => { if (!settled)
|
|
474
|
+
done(null); });
|
|
475
|
+
const failed = (e) => {
|
|
476
|
+
settled = true;
|
|
477
|
+
log({ event: "upstream-error", reason: e.message, ...d, address });
|
|
478
|
+
at(i + 1);
|
|
479
|
+
};
|
|
480
|
+
up.once("error", failed);
|
|
481
|
+
up.once("connect", () => {
|
|
482
|
+
settled = true;
|
|
483
|
+
up.off("error", failed);
|
|
484
|
+
up.on("error", () => { });
|
|
485
|
+
up.setTimeout(0);
|
|
486
|
+
if (closed)
|
|
487
|
+
return void (up.destroy(), done(null));
|
|
488
|
+
done({ socket: up, address });
|
|
489
|
+
});
|
|
490
|
+
};
|
|
491
|
+
at(0);
|
|
492
|
+
});
|
|
493
|
+
/** Joins a client and an upstream socket both ways; either closing closes the other. */
|
|
494
|
+
const join = (client, up, head) => {
|
|
495
|
+
if (head?.length)
|
|
496
|
+
up.write(head);
|
|
497
|
+
up.pipe(client);
|
|
498
|
+
client.pipe(up);
|
|
499
|
+
client.on("close", () => up.destroy());
|
|
500
|
+
up.on("close", () => client.destroy());
|
|
501
|
+
client.resume();
|
|
502
|
+
};
|
|
503
|
+
const server = http.createServer(async (req, res) => {
|
|
504
|
+
const withToken = authorised(req, token);
|
|
505
|
+
if (withToken)
|
|
506
|
+
sawToken = true;
|
|
507
|
+
req.on("error", () => { });
|
|
508
|
+
let u = null;
|
|
509
|
+
try {
|
|
510
|
+
u = new URL(req.url ?? "");
|
|
511
|
+
}
|
|
512
|
+
catch { }
|
|
513
|
+
// Absolute-form plain HTTP only: what a client sends a proxy. Its path is never logged.
|
|
514
|
+
if (!u || u.protocol !== "http:" || !u.hostname) {
|
|
515
|
+
log({ event: "deny", reason: "not-absolute-http", target: `${req.method} ${(req.url ?? "").slice(0, 40)}`, via: req.method, token: withToken });
|
|
516
|
+
return void res.writeHead(400, { "content-type": "text/plain", connection: "close" }).end("relay proxy: send an absolute http:// URL, or CONNECT\n");
|
|
517
|
+
}
|
|
518
|
+
const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase().replace(/\.$/, "");
|
|
519
|
+
const port = Number(u.port || 80);
|
|
520
|
+
// Host must select the same service as the screened absolute request-target.
|
|
521
|
+
let header;
|
|
522
|
+
try {
|
|
523
|
+
header = req.headers.host ? new URL(`http://${req.headers.host}`) : undefined;
|
|
524
|
+
}
|
|
525
|
+
catch { }
|
|
526
|
+
if (u.username || u.password || (req.headers.host && (!header || header.host.toLowerCase() !== u.host.toLowerCase()))) {
|
|
527
|
+
log({ event: "deny", reason: "authority-disagreement", target: u.host, via: req.method, token: withToken });
|
|
528
|
+
return void res.writeHead(400, { connection: "close" }).end("relay proxy: Host and request-target disagree\n");
|
|
529
|
+
}
|
|
530
|
+
if (withToken)
|
|
531
|
+
tokened(host);
|
|
532
|
+
const toStub = Boolean(stub && withToken && host === stub.host);
|
|
533
|
+
const d = { target: `${net.isIPv6(host) ? `[${host}]` : host}:${port}`, via: req.method, token: withToken, ...(toStub ? { stub: true } : {}) };
|
|
534
|
+
req.pause();
|
|
535
|
+
let addresses;
|
|
536
|
+
try {
|
|
537
|
+
addresses = await screen(host, port, toStub);
|
|
538
|
+
}
|
|
539
|
+
catch (e) {
|
|
540
|
+
log({ event: "deny", reason: reasonOf(e), ...d });
|
|
541
|
+
return void res.writeHead(403, { "content-type": "text/plain", connection: "close" }).end(`${REFUSED} (${host}: ${reasonOf(e)})\n`);
|
|
542
|
+
}
|
|
543
|
+
const up = await dial(addresses, port, d);
|
|
544
|
+
if (!up)
|
|
545
|
+
return void (res.headersSent ? res.destroy() : res.writeHead(502, { connection: "close" }).end());
|
|
546
|
+
log({ event: "allow", ...d, address: up.address });
|
|
547
|
+
const headers = endToEnd(req.headers);
|
|
548
|
+
headers.host = u.host;
|
|
549
|
+
const out = http.request({ createConnection: () => up.socket, method: req.method, path: u.pathname + u.search, headers });
|
|
550
|
+
out.on("response", (r) => {
|
|
551
|
+
res.writeHead(r.statusCode ?? 502, r.statusMessage, endToEnd(r.headers));
|
|
552
|
+
r.pipe(res);
|
|
553
|
+
});
|
|
554
|
+
out.on("error", () => (res.headersSent ? res.destroy() : res.writeHead(502, { connection: "close" }).end()));
|
|
555
|
+
res.on("close", () => up.socket.destroy());
|
|
556
|
+
req.pipe(out);
|
|
557
|
+
req.resume();
|
|
558
|
+
});
|
|
559
|
+
server.on("clientError", (_err, sock) => sock.destroy());
|
|
560
|
+
server.on("connect", async (req, client, head) => {
|
|
561
|
+
client.on("error", () => { });
|
|
562
|
+
if (closed)
|
|
563
|
+
return void client.destroy();
|
|
564
|
+
const target = req.url ?? "";
|
|
565
|
+
const withToken = authorised(req, token);
|
|
566
|
+
if (withToken)
|
|
567
|
+
sawToken = true;
|
|
568
|
+
const p0 = parseTarget(target);
|
|
569
|
+
if (withToken && p0)
|
|
570
|
+
tokened(p0.host);
|
|
571
|
+
const d = { target, via: "CONNECT", token: withToken };
|
|
572
|
+
const refuse = (code, reason) => {
|
|
573
|
+
log({ event: "deny", reason, ...d });
|
|
574
|
+
client.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\nProxy-Agent: relay\r\nX-Relay-Refused: ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
575
|
+
};
|
|
576
|
+
const p = p0;
|
|
577
|
+
if (!p)
|
|
578
|
+
return refuse(400, "bad-target");
|
|
579
|
+
client.pause();
|
|
580
|
+
let addresses;
|
|
581
|
+
try {
|
|
582
|
+
addresses = await screen(p.host, p.port);
|
|
583
|
+
}
|
|
584
|
+
catch (e) {
|
|
585
|
+
return refuse(403, reasonOf(e));
|
|
586
|
+
}
|
|
587
|
+
if (closed || client.destroyed)
|
|
588
|
+
return void client.destroy();
|
|
589
|
+
const up = await dial(addresses, p.port, d);
|
|
590
|
+
if (!up)
|
|
591
|
+
return void (closed || client.destroyed ? client.destroy() : client.end("HTTP/1.1 502 Bad Gateway\r\nProxy-Agent: relay\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"));
|
|
592
|
+
if (client.destroyed)
|
|
593
|
+
return void up.socket.destroy();
|
|
594
|
+
log({ event: "allow", ...d, address: up.address });
|
|
595
|
+
client.write("HTTP/1.1 200 Connection Established\r\nProxy-Agent: relay\r\n\r\n");
|
|
596
|
+
join(client, up.socket, head);
|
|
597
|
+
});
|
|
598
|
+
/**
|
|
599
|
+
* SOCKS5 (RFC 1928), CONNECT only: what Claude Code's sandbox gives non-HTTP tools (git over ssh
|
|
600
|
+
* through `nc -X 5`). No authentication is asked for; user and password (RFC 1929) are accepted
|
|
601
|
+
* when a client offers only that, the password counting as the token.
|
|
602
|
+
*/
|
|
603
|
+
const socks = (c, first) => {
|
|
604
|
+
let buf = first;
|
|
605
|
+
let stage = "greet";
|
|
606
|
+
let withToken = false;
|
|
607
|
+
const reply = (code) => Buffer.from([5, code, 0, 1, 0, 0, 0, 0, 0, 0]);
|
|
608
|
+
const step = () => {
|
|
609
|
+
if (stage === "greet") {
|
|
610
|
+
if (buf.length < 2 || buf.length < 2 + buf[1])
|
|
611
|
+
return;
|
|
612
|
+
if (buf[0] !== 5)
|
|
613
|
+
return void c.destroy();
|
|
614
|
+
const methods = [...buf.subarray(2, 2 + buf[1])];
|
|
615
|
+
buf = buf.subarray(2 + buf[1]);
|
|
616
|
+
if (methods.includes(0))
|
|
617
|
+
stage = "request";
|
|
618
|
+
else if (methods.includes(2))
|
|
619
|
+
stage = "auth";
|
|
620
|
+
else
|
|
621
|
+
return void ((stage = "done"), c.end(Buffer.from([5, 0xff])));
|
|
622
|
+
c.write(Buffer.from([5, stage === "auth" ? 2 : 0]));
|
|
623
|
+
}
|
|
624
|
+
if (stage === "auth") {
|
|
625
|
+
if (buf.length < 2 || buf.length < 3 + buf[1] || buf.length < 3 + buf[1] + buf[2 + buf[1]])
|
|
626
|
+
return;
|
|
627
|
+
const ul = buf[1];
|
|
628
|
+
const pass = buf.subarray(3 + ul, 3 + ul + buf[2 + ul]);
|
|
629
|
+
buf = buf.subarray(3 + ul + buf[2 + ul]);
|
|
630
|
+
const want = Buffer.from(token);
|
|
631
|
+
withToken = pass.length === want.length && crypto.timingSafeEqual(pass, want);
|
|
632
|
+
if (withToken)
|
|
633
|
+
sawToken = true;
|
|
634
|
+
c.write(Buffer.from([1, 0]));
|
|
635
|
+
stage = "request";
|
|
636
|
+
}
|
|
637
|
+
if (stage === "request") {
|
|
638
|
+
if (buf.length < 5)
|
|
639
|
+
return;
|
|
640
|
+
if (buf[0] !== 5)
|
|
641
|
+
return void c.destroy();
|
|
642
|
+
const [, cmd, , atyp] = buf;
|
|
643
|
+
let host;
|
|
644
|
+
let off;
|
|
645
|
+
if (atyp === 1) {
|
|
646
|
+
if (buf.length < 10)
|
|
647
|
+
return;
|
|
648
|
+
host = [...buf.subarray(4, 8)].join(".");
|
|
649
|
+
off = 8;
|
|
650
|
+
}
|
|
651
|
+
else if (atyp === 3) {
|
|
652
|
+
if (buf.length < 5 + buf[4] + 2)
|
|
653
|
+
return;
|
|
654
|
+
host = buf.subarray(5, 5 + buf[4]).toString("latin1").toLowerCase().replace(/\.$/, "");
|
|
655
|
+
off = 5 + buf[4];
|
|
656
|
+
}
|
|
657
|
+
else if (atyp === 4) {
|
|
658
|
+
if (buf.length < 22)
|
|
659
|
+
return;
|
|
660
|
+
host = Array.from({ length: 8 }, (_, i) => buf.readUInt16BE(4 + 2 * i).toString(16)).join(":");
|
|
661
|
+
off = 20;
|
|
662
|
+
}
|
|
663
|
+
else {
|
|
664
|
+
stage = "done";
|
|
665
|
+
log({ event: "deny", reason: "bad-address-type", target: "?", via: "SOCKS5", token: withToken });
|
|
666
|
+
return void c.end(reply(8));
|
|
667
|
+
}
|
|
668
|
+
const port = buf.readUInt16BE(off);
|
|
669
|
+
const rest = buf.subarray(off + 2);
|
|
670
|
+
stage = "done";
|
|
671
|
+
c.off("data", more);
|
|
672
|
+
c.pause();
|
|
673
|
+
if (withToken)
|
|
674
|
+
tokened(host);
|
|
675
|
+
const d = { target: `${net.isIPv6(host) ? `[${host}]` : host}:${port}`, via: "SOCKS5", token: withToken };
|
|
676
|
+
if (cmd !== 1) {
|
|
677
|
+
log({ event: "deny", reason: "not-connect", ...d });
|
|
678
|
+
return void c.end(reply(7));
|
|
679
|
+
}
|
|
680
|
+
void (async () => {
|
|
681
|
+
let addresses;
|
|
682
|
+
try {
|
|
683
|
+
addresses = await screen(host, port);
|
|
684
|
+
}
|
|
685
|
+
catch (e) {
|
|
686
|
+
log({ event: "deny", reason: reasonOf(e), ...d });
|
|
687
|
+
return void c.end(reply(reasonOf(e).startsWith("unresolved") ? 4 : 2));
|
|
688
|
+
}
|
|
689
|
+
if (closed || c.destroyed)
|
|
690
|
+
return void c.destroy();
|
|
691
|
+
const up = await dial(addresses, port, d);
|
|
692
|
+
if (!up)
|
|
693
|
+
return void (c.destroyed ? undefined : c.end(reply(1)));
|
|
694
|
+
if (c.destroyed)
|
|
695
|
+
return void up.socket.destroy();
|
|
696
|
+
log({ event: "allow", ...d, address: up.address });
|
|
697
|
+
c.setTimeout(0);
|
|
698
|
+
c.write(reply(0));
|
|
699
|
+
join(c, up.socket, rest);
|
|
700
|
+
})();
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
const more = (chunk) => {
|
|
704
|
+
buf = Buffer.concat([buf, chunk]);
|
|
705
|
+
if (buf.length > 1024)
|
|
706
|
+
return void c.destroy();
|
|
707
|
+
step();
|
|
708
|
+
};
|
|
709
|
+
c.on("data", more);
|
|
710
|
+
step();
|
|
711
|
+
};
|
|
712
|
+
/** Each client: SOCKS5 if its first byte says so (version 5), HTTP otherwise. */
|
|
713
|
+
const accept = (c) => {
|
|
714
|
+
track(c);
|
|
715
|
+
c.on("error", () => { });
|
|
716
|
+
if (closed)
|
|
717
|
+
return void c.destroy();
|
|
718
|
+
c.setTimeout(HANDSHAKE_TIMEOUT_MS, () => c.destroy());
|
|
719
|
+
c.once("readable", () => {
|
|
720
|
+
const first = c.read();
|
|
721
|
+
if (!first)
|
|
722
|
+
return void c.destroy();
|
|
723
|
+
if (first[0] === 5)
|
|
724
|
+
return socks(c, first);
|
|
725
|
+
c.setTimeout(0);
|
|
726
|
+
c.unshift(first);
|
|
727
|
+
server.emit("connection", c);
|
|
728
|
+
});
|
|
729
|
+
};
|
|
730
|
+
// One port on both loopback addresses: the sandbox is told `localhost`, which may resolve to either.
|
|
731
|
+
const servers = [];
|
|
732
|
+
const listen = (host, port, ipv6Only = false) => new Promise((ok, fail) => {
|
|
733
|
+
const s = net.createServer(accept);
|
|
734
|
+
s.once("error", fail);
|
|
735
|
+
s.listen({ host, port, ipv6Only }, () => {
|
|
736
|
+
s.off("error", fail);
|
|
737
|
+
s.on("error", () => { });
|
|
738
|
+
ok(s);
|
|
739
|
+
});
|
|
740
|
+
});
|
|
741
|
+
let port = 0;
|
|
742
|
+
for (let attempt = 0; !port; attempt++) {
|
|
743
|
+
const v4 = await listen("127.0.0.1", opts.listen?.port ?? 0);
|
|
744
|
+
if (opts.listen?.ipv4Only) {
|
|
745
|
+
servers.push(v4);
|
|
746
|
+
port = v4.address().port;
|
|
747
|
+
break;
|
|
748
|
+
}
|
|
749
|
+
const p = v4.address().port;
|
|
750
|
+
try {
|
|
751
|
+
servers.push(v4, await listen("::1", p, true));
|
|
752
|
+
port = p;
|
|
753
|
+
}
|
|
754
|
+
catch (e) {
|
|
755
|
+
const code = e.code;
|
|
756
|
+
// No IPv6 loopback on this machine: IPv4 alone, which `localhost` then resolves to.
|
|
757
|
+
if (code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT") {
|
|
758
|
+
servers.push(v4);
|
|
759
|
+
port = p;
|
|
760
|
+
}
|
|
761
|
+
else {
|
|
762
|
+
await new Promise((r) => v4.close(() => r()));
|
|
763
|
+
if (code !== "EADDRINUSE" || attempt >= 20)
|
|
764
|
+
throw e;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return {
|
|
769
|
+
port,
|
|
770
|
+
token,
|
|
771
|
+
network: { mode: "off-except-proxy", proxyPort: port, proxyToken: token },
|
|
772
|
+
authenticated: () => sawToken,
|
|
773
|
+
tokenHosts: () => hostsWithToken,
|
|
774
|
+
close: async () => {
|
|
775
|
+
if (closed)
|
|
776
|
+
return;
|
|
777
|
+
closed = true;
|
|
778
|
+
for (const s of sockets)
|
|
779
|
+
s.destroy();
|
|
780
|
+
await Promise.all(servers.map((s) => new Promise((r) => s.close(() => r()))));
|
|
781
|
+
},
|
|
782
|
+
};
|
|
783
|
+
}
|