@jbkjr/relay 0.0.0-stage → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +386 -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 +1525 -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 +320 -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 +637 -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 +329 -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 +629 -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 +1502 -0
- package/docs/pinned-codex.md +321 -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,531 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import http from "node:http";
|
|
5
|
+
import net from "node:net";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { test } from "node:test";
|
|
9
|
+
import { confinement } from "../dist/confine/index.js";
|
|
10
|
+
import { allowlistHost, canonicalAddress, localInterfaceAddresses, localSubnets, onLink, openProxy, proxyEnv, publicAddress, screenAddresses } from "../dist/confine/proxy.js";
|
|
11
|
+
import { SANDBOX_EXEC } from "../dist/confine/seatbelt.js";
|
|
12
|
+
// For its side effect: the test process gets a scratch HOME (see helpers.ts).
|
|
13
|
+
import "./helpers.ts";
|
|
14
|
+
import { useStoragePolicy } from "../dist/core/storage.js";
|
|
15
|
+
|
|
16
|
+
test("proxy: log_max_mb rotates proxy.jsonl between complete decision records", async () => {
|
|
17
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "relay-proxy-rotation-"));
|
|
18
|
+
const file = path.join(dir, "proxy.jsonl");
|
|
19
|
+
useStoragePolicy({ log_max_mb: 0.001 });
|
|
20
|
+
const decisions: unknown[] = [];
|
|
21
|
+
const proxy = await openProxy({ allow: [], logFile: file, onDecision: (d) => decisions.push(d) });
|
|
22
|
+
try {
|
|
23
|
+
// Cross one boundary: both files together must contain every decision, in order.
|
|
24
|
+
for (let i = 0; i < 10; i++) await connectVia(proxy.port, `denied-${i}.example:443`, auth(proxy.token));
|
|
25
|
+
assert.ok(fs.existsSync(`${file}.1`), "proxy.jsonl was rotated at the agent log's limit");
|
|
26
|
+
assert.deepEqual([...readLog(`${file}.1`), ...readLog(file)], decisions, "no record was split or lost at rotation");
|
|
27
|
+
for (const f of [file, `${file}.1`]) assert.ok(fs.statSync(f).size <= Math.round(0.001 * 1024 * 1024));
|
|
28
|
+
} finally {
|
|
29
|
+
await proxy.close();
|
|
30
|
+
useStoragePolicy({ log_max_mb: null });
|
|
31
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const macOS = process.platform === "darwin" && fs.existsSync(SANDBOX_EXEC);
|
|
36
|
+
|
|
37
|
+
/** A plain TCP echo server on loopback: the stand-in for a vendor API, reached under a fake allowlisted name. */
|
|
38
|
+
async function echoServer() {
|
|
39
|
+
const server = net.createServer((s) => s.pipe(s));
|
|
40
|
+
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
|
41
|
+
return { port: (server.address() as net.AddressInfo).port, close: () => new Promise<void>((r) => server.close(() => r())) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const auth = (token: string, user = "relay") => `Basic ${Buffer.from(`${user}:${token}`).toString("base64")}`;
|
|
45
|
+
|
|
46
|
+
/** Sends one CONNECT and returns the status line; on 200, also what the tunnel echoes back for `ping`. */
|
|
47
|
+
function connectVia(port: number, target: string, authorization?: string): Promise<{ status: number; head: string; echoed?: string }> {
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const s = net.connect(port, "127.0.0.1");
|
|
50
|
+
let buf = "";
|
|
51
|
+
let status = 0;
|
|
52
|
+
let head = "";
|
|
53
|
+
s.setEncoding("utf8");
|
|
54
|
+
s.on("connect", () => s.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n${authorization ? `Proxy-Authorization: ${authorization}\r\n` : ""}\r\n`));
|
|
55
|
+
s.on("data", (d: string) => {
|
|
56
|
+
buf += d;
|
|
57
|
+
if (!status) {
|
|
58
|
+
const end = buf.indexOf("\r\n\r\n");
|
|
59
|
+
if (end < 0) return;
|
|
60
|
+
head = buf.slice(0, end);
|
|
61
|
+
status = Number(/^HTTP\/1\.1 (\d{3})/.exec(head)?.[1] ?? 0);
|
|
62
|
+
buf = buf.slice(end + 4);
|
|
63
|
+
if (status === 200) return void s.write("ping");
|
|
64
|
+
}
|
|
65
|
+
if (status === 200 && buf.length >= 4) {
|
|
66
|
+
s.destroy();
|
|
67
|
+
resolve({ status, head, echoed: buf });
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
s.on("error", reject);
|
|
71
|
+
s.on("close", () => resolve({ status, head }));
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const readLog = (f: string) => fs.readFileSync(f, "utf8").trim().split("\n").map((l) => JSON.parse(l));
|
|
76
|
+
|
|
77
|
+
test("proxy: an allowlisted name tunnels; other hosts, IP literals, other ports and plain HTTP are refused, and every decision is logged", async () => {
|
|
78
|
+
const echo = await echoServer();
|
|
79
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "relay-proxy-"));
|
|
80
|
+
const logFile = path.join(dir, "turn.log");
|
|
81
|
+
const resolved: string[] = [];
|
|
82
|
+
const proxy = await openProxy({
|
|
83
|
+
allow: ["API.Vendor.test.", "other.vendor.test"], logFile, label: "j_1/7",
|
|
84
|
+
testing: { resolve: async (h) => (resolved.push(h), ["127.0.0.1"]), upstreamPort: echo.port },
|
|
85
|
+
});
|
|
86
|
+
try {
|
|
87
|
+
assert.deepEqual(proxy.network, { mode: "off-except-proxy", proxyPort: proxy.port, proxyToken: proxy.token });
|
|
88
|
+
const ok = await connectVia(proxy.port, "api.vendor.test:443", auth(proxy.token));
|
|
89
|
+
assert.equal(ok.status, 200, ok.head);
|
|
90
|
+
assert.equal(ok.echoed, "ping", "bytes flow through the tunnel");
|
|
91
|
+
assert.equal((await connectVia(proxy.port, "API.VENDOR.TEST.:443", auth(proxy.token))).status, 200, "names compare case- and trailing-dot-insensitively");
|
|
92
|
+
|
|
93
|
+
for (const [target, code] of [
|
|
94
|
+
["example.com:443", 403], ["api.vendor.test:80", 403], ["api.vendor.test.evil.test:443", 403],
|
|
95
|
+
["127.0.0.1:443", 403], ["[::1]:443", 403], ["93.184.215.14:443", 403], ["no-port", 400],
|
|
96
|
+
] as const) {
|
|
97
|
+
const r = await connectVia(proxy.port, target, auth(proxy.token));
|
|
98
|
+
assert.equal(r.status, code, `${target}: ${r.head}`);
|
|
99
|
+
assert.equal(r.echoed, undefined);
|
|
100
|
+
}
|
|
101
|
+
assert.deepEqual([...new Set(resolved)], ["api.vendor.test"], "only allowlisted names are ever resolved");
|
|
102
|
+
|
|
103
|
+
const plain = await fetch(`http://127.0.0.1:${proxy.port}/`).then((r) => r.status);
|
|
104
|
+
assert.equal(plain, 405);
|
|
105
|
+
|
|
106
|
+
const log = readLog(logFile);
|
|
107
|
+
assert.ok(log.every((d) => d.turn === "j_1/7" && typeof d.t === "string"));
|
|
108
|
+
assert.deepEqual(log.filter((d) => d.event === "allow").map((d) => [d.target, d.address]), [["api.vendor.test:443", "127.0.0.1"], ["API.VENDOR.TEST.:443", "127.0.0.1"]]);
|
|
109
|
+
const reasons = Object.fromEntries(log.filter((d) => d.event === "deny").map((d) => [d.target, d.reason]));
|
|
110
|
+
assert.equal(reasons["example.com:443"], "host-not-allowlisted");
|
|
111
|
+
assert.equal(reasons["api.vendor.test:80"], "port-not-443");
|
|
112
|
+
assert.equal(reasons["127.0.0.1:443"], "ip-literal");
|
|
113
|
+
assert.equal(reasons["[::1]:443"], "ip-literal");
|
|
114
|
+
assert.equal(reasons["GET /"], "not-connect");
|
|
115
|
+
assert.ok(!fs.readFileSync(logFile, "utf8").includes(proxy.token), "the token is never logged");
|
|
116
|
+
} finally {
|
|
117
|
+
await proxy.close();
|
|
118
|
+
await echo.close();
|
|
119
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("proxy: a missing or wrong token, or another turn's, gets 407 with a challenge", async () => {
|
|
124
|
+
const echo = await echoServer();
|
|
125
|
+
const testing = { resolve: async () => ["127.0.0.1"], upstreamPort: echo.port };
|
|
126
|
+
const a = await openProxy({ allow: ["api.vendor.test"], testing });
|
|
127
|
+
const b = await openProxy({ allow: ["api.vendor.test"], testing });
|
|
128
|
+
try {
|
|
129
|
+
assert.notEqual(a.token, b.token);
|
|
130
|
+
assert.notEqual(a.port, b.port);
|
|
131
|
+
for (const authorization of [undefined, auth("wrong"), auth(b.token), `Bearer ${a.token}`, auth(a.token.slice(0, -1)), `Basic ${Buffer.from(a.token).toString("base64")}`]) {
|
|
132
|
+
const r = await connectVia(a.port, "api.vendor.test:443", authorization);
|
|
133
|
+
assert.equal(r.status, 407, `${authorization}: ${r.head}`);
|
|
134
|
+
assert.match(r.head, /Proxy-Authenticate: Basic realm="relay"/);
|
|
135
|
+
assert.match(r.head, /Connection: close/);
|
|
136
|
+
}
|
|
137
|
+
assert.equal((await connectVia(a.port, "api.vendor.test:443", auth(a.token, "anyone"))).status, 200, "the user name is not checked, the token is");
|
|
138
|
+
assert.equal((await connectVia(b.port, "api.vendor.test:443", auth(b.token))).status, 200);
|
|
139
|
+
} finally {
|
|
140
|
+
await a.close();
|
|
141
|
+
await b.close();
|
|
142
|
+
await echo.close();
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("proxy: names that resolve to loopback or private addresses are refused; closing drops open tunnels", async () => {
|
|
147
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "relay-proxy-"));
|
|
148
|
+
const logFile = path.join(dir, "turn.log");
|
|
149
|
+
// `localhost` resolves without any network: the real resolver path, with its public-address check.
|
|
150
|
+
const proxy = await openProxy({ allow: ["localhost"], logFile });
|
|
151
|
+
try {
|
|
152
|
+
const r = await connectVia(proxy.port, "localhost:443", auth(proxy.token));
|
|
153
|
+
assert.equal(r.status, 403, r.head);
|
|
154
|
+
assert.equal(readLog(logFile).at(-1).reason, "private-address");
|
|
155
|
+
} finally {
|
|
156
|
+
await proxy.close();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const echo = await echoServer();
|
|
160
|
+
const p2 = await openProxy({ allow: ["api.vendor.test"], testing: { resolve: async () => ["127.0.0.1"], upstreamPort: echo.port } });
|
|
161
|
+
const s = net.connect(p2.port, "127.0.0.1");
|
|
162
|
+
await new Promise<void>((res) => s.on("connect", () => res()));
|
|
163
|
+
s.write(`CONNECT api.vendor.test:443 HTTP/1.1\r\nProxy-Authorization: ${auth(p2.token)}\r\n\r\n`);
|
|
164
|
+
await new Promise<void>((res) => s.once("data", () => res()));
|
|
165
|
+
const gone = new Promise<void>((res) => s.on("close", () => res()));
|
|
166
|
+
await p2.close();
|
|
167
|
+
await gone;
|
|
168
|
+
await assert.rejects(connectVia(p2.port, "api.vendor.test:443", auth(p2.token)), /ECONNREFUSED/);
|
|
169
|
+
await echo.close();
|
|
170
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("proxy: address and host-name checks", () => {
|
|
174
|
+
for (const ip of ["127.0.0.1", "10.1.2.3", "172.16.0.1", "172.31.255.255", "192.168.1.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "224.0.0.1", "255.255.255.255",
|
|
175
|
+
"::1", "::", "fe80::1", "fc00::1", "fd12:3456::1", "ff02::1", "::ffff:127.0.0.1", "::ffff:7f00:1", "::ffff:10.0.0.1", "64:ff9b::a00:1", "2001:db8::1", "not an ip",
|
|
176
|
+
// Azure's metadata endpoint, a public-range address, and its IPv4-mapped IPv6 forms (review X3).
|
|
177
|
+
"168.63.129.16", "::ffff:168.63.129.16", "::ffff:a83f:8110"]) {
|
|
178
|
+
assert.equal(publicAddress(ip), false, ip);
|
|
179
|
+
}
|
|
180
|
+
for (const ip of ["93.184.215.14", "8.8.8.8", "172.32.0.1", "2606:4700::1111", "::ffff:8.8.8.8"]) assert.equal(publicAddress(ip), true, ip);
|
|
181
|
+
|
|
182
|
+
assert.equal(allowlistHost(" API.Example.COM. "), "api.example.com");
|
|
183
|
+
for (const bad of ["1.2.3.4", "::1", "[::1]", "*.googleapis.com", "a..b", "-a.com", "a b.com", "", "x".repeat(64) + ".com", "host:443"]) {
|
|
184
|
+
assert.throws(() => allowlistHost(bad), /IP literal|not a host name/, bad);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const env = proxyEnv(4321, "tok");
|
|
188
|
+
for (const k of ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"]) assert.equal(env[k], "http://relay:tok@127.0.0.1:4321", k);
|
|
189
|
+
assert.equal(env.NO_PROXY, "");
|
|
190
|
+
assert.equal(env.no_proxy, "");
|
|
191
|
+
assert.equal(env.NODE_USE_ENV_PROXY, "1");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("proxy e2e: under the Seatbelt profile the harness reaches an allowlisted host only through the turn's proxy", { skip: !macOS && "macOS only" }, async () => {
|
|
195
|
+
const found = confinement();
|
|
196
|
+
assert.ok("mechanism" in found);
|
|
197
|
+
const echo = await echoServer();
|
|
198
|
+
const proxy = await openProxy({ allow: ["api.vendor.test"], testing: { resolve: async () => ["127.0.0.1"], upstreamPort: echo.port } });
|
|
199
|
+
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "relay-proxy-e2e-")));
|
|
200
|
+
try {
|
|
201
|
+
const wt = path.join(root, "wt");
|
|
202
|
+
const tmp = path.join(root, "tmp");
|
|
203
|
+
fs.mkdirSync(wt);
|
|
204
|
+
fs.mkdirSync(tmp);
|
|
205
|
+
const launch = found.mechanism.wrap({ worktree: wt, worktreeWritable: true, tmpDir: tmp, denied: [], network: proxy.network }, process.execPath, [
|
|
206
|
+
"-e",
|
|
207
|
+
`
|
|
208
|
+
const net = require("node:net");
|
|
209
|
+
const u = new URL(process.env.HTTPS_PROXY);
|
|
210
|
+
const tryConnect = (port, send) => new Promise((res) => {
|
|
211
|
+
const s = net.connect(port, "127.0.0.1");
|
|
212
|
+
let got = "";
|
|
213
|
+
s.on("connect", () => send ? s.write(send) : (s.destroy(), res("connected")));
|
|
214
|
+
s.on("data", (d) => { got += d; if (got.includes("ping")) { s.destroy(); res(got.slice(0, 12) + "|" + got.slice(-4)); } else if (got.includes("\\r\\n\\r\\n")) s.write("ping"); });
|
|
215
|
+
s.on("error", (e) => res(e.code));
|
|
216
|
+
});
|
|
217
|
+
(async () => {
|
|
218
|
+
const auth = "Basic " + Buffer.from("relay:" + decodeURIComponent(u.password)).toString("base64");
|
|
219
|
+
const viaProxy = await tryConnect(Number(u.port), "CONNECT api.vendor.test:443 HTTP/1.1\\r\\nProxy-Authorization: " + auth + "\\r\\n\\r\\n");
|
|
220
|
+
const direct = await tryConnect(${echo.port});
|
|
221
|
+
console.log(JSON.stringify({ viaProxy, direct, noProxy: process.env.NO_PROXY, nodeEnvProxy: process.env.NODE_USE_ENV_PROXY }));
|
|
222
|
+
})();
|
|
223
|
+
`,
|
|
224
|
+
]);
|
|
225
|
+
// Not spawnSync: the proxy runs in this process and must keep answering.
|
|
226
|
+
const r = await new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve) => {
|
|
227
|
+
const c = spawn(launch.command, launch.args, { cwd: wt, env: { PATH: "/usr/bin:/bin", ...launch.env } });
|
|
228
|
+
let stdout = "";
|
|
229
|
+
let stderr = "";
|
|
230
|
+
c.stdout.on("data", (d) => (stdout += d));
|
|
231
|
+
c.stderr.on("data", (d) => (stderr += d));
|
|
232
|
+
c.on("close", (status) => resolve({ status, stdout, stderr }));
|
|
233
|
+
});
|
|
234
|
+
assert.equal(r.status, 0, r.stderr);
|
|
235
|
+
const out = JSON.parse(r.stdout);
|
|
236
|
+
assert.equal(out.viaProxy, "HTTP/1.1 200|ping", "the tunnel through the proxy works from inside");
|
|
237
|
+
assert.equal(out.direct, "EPERM", "the same server, connected to directly, is refused by the sandbox");
|
|
238
|
+
assert.equal(out.noProxy, "");
|
|
239
|
+
assert.equal(out.nodeEnvProxy, "1");
|
|
240
|
+
} finally {
|
|
241
|
+
await proxy.close();
|
|
242
|
+
await echo.close();
|
|
243
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test("proxy: a lookup that finishes after close() opens no upstream connection (review r_faba9d17 X3)", async () => {
|
|
248
|
+
let connections = 0;
|
|
249
|
+
const live = new Set<net.Socket>();
|
|
250
|
+
const server = net.createServer((s) => (connections++, live.add(s), s.pipe(s)));
|
|
251
|
+
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
|
252
|
+
const port = (server.address() as net.AddressInfo).port;
|
|
253
|
+
let release!: () => void;
|
|
254
|
+
const gate = new Promise<void>((r) => (release = r));
|
|
255
|
+
let asked!: () => void;
|
|
256
|
+
const lookedUp = new Promise<void>((r) => (asked = r));
|
|
257
|
+
const proxy = await openProxy({ allow: ["api.vendor.test"], testing: { resolve: async () => (asked(), await gate, ["127.0.0.1"]), upstreamPort: port } });
|
|
258
|
+
const s = net.connect(proxy.port, "127.0.0.1");
|
|
259
|
+
s.on("error", () => {});
|
|
260
|
+
try {
|
|
261
|
+
await new Promise<void>((r) => s.on("connect", () => r()));
|
|
262
|
+
s.write(`CONNECT api.vendor.test:443 HTTP/1.1\r\nProxy-Authorization: ${auth(proxy.token)}\r\n\r\n`);
|
|
263
|
+
await lookedUp;
|
|
264
|
+
await proxy.close();
|
|
265
|
+
release();
|
|
266
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
267
|
+
assert.equal(connections, 0, "nothing was opened upstream after the proxy closed");
|
|
268
|
+
} finally {
|
|
269
|
+
s.destroy();
|
|
270
|
+
for (const c of live) c.destroy();
|
|
271
|
+
await new Promise<void>((r) => server.close(() => r()));
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
test("proxy: a name resolving to one of this machine's own interface addresses is refused, even though it is a public address (hardening 7)", () => {
|
|
276
|
+
// A public address that is not on this machine passes; the same address, were it one of ours, does not.
|
|
277
|
+
const publicIp = "93.184.215.14";
|
|
278
|
+
assert.deepEqual(screenAddresses([publicIp], new Set()), { addresses: [publicIp] });
|
|
279
|
+
assert.deepEqual(screenAddresses([publicIp], new Set([publicIp])), { reason: "local-interface-address", address: publicIp });
|
|
280
|
+
// A private answer still refuses first, whatever the interface list.
|
|
281
|
+
assert.deepEqual(screenAddresses(["10.0.0.1", publicIp], new Set()), { reason: "private-address", address: "10.0.0.1" });
|
|
282
|
+
// An IPv6 interface address compares in canonical form, so a zone id, compression and case do not matter (review C5).
|
|
283
|
+
const ownV6 = (addr: string) => new Set([canonicalAddress(addr)]);
|
|
284
|
+
assert.deepEqual(screenAddresses(["2606:4700::1111"], ownV6("2606:4700::1111%en0")), { reason: "local-interface-address", address: "2606:4700::1111" }, "a zone on the interface side");
|
|
285
|
+
assert.deepEqual(screenAddresses(["2606:4700::1111%en0"], ownV6("2606:4700:0000:0000:0000:0000:0000:1111")), { reason: "local-interface-address", address: "2606:4700::1111%en0" }, "full form vs compressed");
|
|
286
|
+
// An IPv4-mapped/compatible or hex IPv6 form of the machine's own public address is caught too (review C5).
|
|
287
|
+
for (const mapped of ["::ffff:93.184.216.34", "::ffff:5db8:d822", "::93.184.216.34"]) {
|
|
288
|
+
assert.deepEqual(screenAddresses([mapped], ownV6("93.184.216.34")), { reason: "local-interface-address", address: mapped }, mapped);
|
|
289
|
+
}
|
|
290
|
+
// The machine's loopback is in the set but is caught as private first; the set is non-empty here.
|
|
291
|
+
assert.ok(localInterfaceAddresses().has("127.0.0.1"));
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
test("proxy: when a name resolves to several addresses, a dead one is passed over for a live one (hardening 7)", async () => {
|
|
295
|
+
const echo = await echoServer();
|
|
296
|
+
// 127.0.0.2 has nothing listening (ECONNREFUSED at once); 127.0.0.1 is the echo server.
|
|
297
|
+
const proxy = await openProxy({ allow: ["api.vendor.test"], testing: { resolve: async () => ["127.0.0.2", "127.0.0.1"], upstreamPort: echo.port } });
|
|
298
|
+
try {
|
|
299
|
+
const r = await connectVia(proxy.port, "api.vendor.test:443", auth(proxy.token));
|
|
300
|
+
assert.equal(r.status, 200, r.head);
|
|
301
|
+
assert.equal(r.echoed, "ping", "the tunnel reached the live address");
|
|
302
|
+
} finally {
|
|
303
|
+
await proxy.close();
|
|
304
|
+
await echo.close();
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
// ---- Public mode (Claude turns with the network, relay 1.0.5) ----
|
|
309
|
+
|
|
310
|
+
/** An IPv6 address as its sixteen bytes (an IPv4-mapped one as ::ffff: and its four). */
|
|
311
|
+
function v6Bytes(ip: string): Buffer {
|
|
312
|
+
const c = canonicalAddress(ip);
|
|
313
|
+
if (net.isIPv4(c)) return Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, ...c.split(".").map(Number)]);
|
|
314
|
+
return Buffer.from(c.split(":").flatMap((g) => [parseInt(g, 16) >> 8, parseInt(g, 16) & 255]));
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Sends one SOCKS5 CONNECT (no authentication) for `host` (a name, or an IPv4 or IPv6 literal) and returns the reply code; on 0, also what the tunnel echoes back for `ping`. */
|
|
318
|
+
function socksVia(port: number, host: string, dport: number, cmd = 1, at = "127.0.0.1"): Promise<{ code: number; echoed?: string }> {
|
|
319
|
+
return new Promise((resolve, reject) => {
|
|
320
|
+
const s = net.connect(port, at);
|
|
321
|
+
let buf = Buffer.alloc(0);
|
|
322
|
+
let stage = 0;
|
|
323
|
+
s.on("connect", () => s.write(Buffer.from([5, 1, 0])));
|
|
324
|
+
s.on("data", (d: Buffer) => {
|
|
325
|
+
buf = Buffer.concat([buf, d]);
|
|
326
|
+
if (stage === 0 && buf.length >= 2) {
|
|
327
|
+
buf = buf.subarray(2);
|
|
328
|
+
stage = 1;
|
|
329
|
+
const kind = net.isIP(host);
|
|
330
|
+
const addr = kind === 4 ? Buffer.from([1, ...host.split(".").map(Number)])
|
|
331
|
+
: kind === 6 ? Buffer.concat([Buffer.from([4]), v6Bytes(host)])
|
|
332
|
+
: Buffer.concat([Buffer.from([3, host.length]), Buffer.from(host)]);
|
|
333
|
+
const p = Buffer.alloc(2);
|
|
334
|
+
p.writeUInt16BE(dport);
|
|
335
|
+
s.write(Buffer.concat([Buffer.from([5, cmd, 0]), addr, p]));
|
|
336
|
+
}
|
|
337
|
+
if (stage === 1 && buf.length >= 10) {
|
|
338
|
+
const code = buf[1];
|
|
339
|
+
buf = buf.subarray(10);
|
|
340
|
+
stage = 2;
|
|
341
|
+
if (code !== 0) return void (s.destroy(), resolve({ code }));
|
|
342
|
+
s.write("ping");
|
|
343
|
+
}
|
|
344
|
+
if (stage === 2 && buf.length >= 4) {
|
|
345
|
+
s.destroy();
|
|
346
|
+
resolve({ code: 0, echoed: buf.toString() });
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
s.on("error", reject);
|
|
350
|
+
s.on("close", () => resolve({ code: -1 }));
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** A plain-HTTP request through the proxy (absolute-form), returning the status and body. */
|
|
355
|
+
function httpVia(port: number, url: string, headers: Record<string, string> = {}, at = "127.0.0.1"): Promise<{ status: number; body: string }> {
|
|
356
|
+
return new Promise((resolve, reject) => {
|
|
357
|
+
let authority; try { authority = new URL(url).host; } catch {}
|
|
358
|
+
const req = http.request({ host: at, port, path: url, headers: { ...(authority ? { host: authority } : {}), ...headers }, agent: false }, (res) => {
|
|
359
|
+
let body = "";
|
|
360
|
+
res.setEncoding("utf8");
|
|
361
|
+
res.on("data", (d) => (body += d));
|
|
362
|
+
res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));
|
|
363
|
+
});
|
|
364
|
+
req.on("error", reject);
|
|
365
|
+
req.end();
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
test("proxy public: one port on 127.0.0.1 and ::1 tunnels, forwards plain HTTP and SOCKS5 to a name, with or without the token", async () => {
|
|
370
|
+
const echo = await echoServer();
|
|
371
|
+
const seen: { url?: string; headers?: http.IncomingHttpHeaders } = {};
|
|
372
|
+
const web = http.createServer((req, res) => {
|
|
373
|
+
seen.url = req.url;
|
|
374
|
+
seen.headers = req.headers;
|
|
375
|
+
res.writeHead(200, { "content-type": "text/plain", "keep-alive": "timeout=5" }).end("hello");
|
|
376
|
+
});
|
|
377
|
+
await new Promise<void>((r) => web.listen(0, "127.0.0.1", r));
|
|
378
|
+
const decisions: { event: string; via?: string; target: string; token?: boolean; reason?: string }[] = [];
|
|
379
|
+
const tunnel = await openProxy({ mode: "public", allow: [], onDecision: (d) => decisions.push(d), testing: { resolve: async () => ["127.0.0.1"], upstreamPort: echo.port } });
|
|
380
|
+
const plain = await openProxy({ mode: "public", allow: [], testing: { resolve: async () => ["127.0.0.1"], upstreamPort: (web.address() as net.AddressInfo).port } });
|
|
381
|
+
try {
|
|
382
|
+
assert.equal(tunnel.authenticated(), false);
|
|
383
|
+
for (const target of ["api.vendor.test:443", "git.vendor.test:22", "api.vendor.test:8443"]) {
|
|
384
|
+
const r = await connectVia(tunnel.port, target);
|
|
385
|
+
assert.equal(r.status, 200, `${target} without a token: ${r.head}`);
|
|
386
|
+
assert.equal(r.echoed, "ping");
|
|
387
|
+
}
|
|
388
|
+
assert.equal(tunnel.authenticated(), false, "requests without the token do not count as the harness's");
|
|
389
|
+
assert.equal((await connectVia(tunnel.port, "api.vendor.test:443", auth("wrong"))).status, 200, "a wrong token is no token: still public egress only");
|
|
390
|
+
assert.equal(tunnel.authenticated(), false);
|
|
391
|
+
assert.equal((await connectVia(tunnel.port, "api.vendor.test:443", auth(tunnel.token))).status, 200);
|
|
392
|
+
assert.equal(tunnel.authenticated(), true);
|
|
393
|
+
assert.deepEqual(await socksVia(tunnel.port, "git.vendor.test", 22), { code: 0, echoed: "ping" });
|
|
394
|
+
assert.deepEqual(await socksVia(tunnel.port, "git.vendor.test", 22, 1, "::1"), { code: 0, echoed: "ping" }, "the same port answers on ::1");
|
|
395
|
+
assert.equal((await connectVia(tunnel.port, "no-port")).status, 400);
|
|
396
|
+
assert.equal((await socksVia(tunnel.port, "git.vendor.test", 22, 2)).code, 7, "SOCKS BIND is not offered");
|
|
397
|
+
const viaLog = decisions.filter((d) => d.event === "allow").map((d) => `${d.via} ${d.target} ${d.token}`);
|
|
398
|
+
assert.ok(viaLog.includes("CONNECT git.vendor.test:22 false") && viaLog.includes("SOCKS5 git.vendor.test:22 false") && viaLog.includes("CONNECT api.vendor.test:443 true"), viaLog.join("\n"));
|
|
399
|
+
|
|
400
|
+
const r = await httpVia(plain.port, "http://www.vendor.test:8080/p?q=1", { host: "www.vendor.test:8080", "proxy-authorization": auth(plain.token), "proxy-connection": "keep-alive", "x-keep": "1" });
|
|
401
|
+
assert.deepEqual(r, { status: 200, body: "hello" });
|
|
402
|
+
assert.equal(seen.url, "/p?q=1", "the request goes upstream in origin form");
|
|
403
|
+
assert.equal(seen.headers?.host, "www.vendor.test:8080", "the client's Host is kept");
|
|
404
|
+
assert.equal(seen.headers?.["proxy-authorization"], undefined, "the token never goes upstream");
|
|
405
|
+
assert.equal(seen.headers?.["proxy-connection"], undefined);
|
|
406
|
+
assert.equal(seen.headers?.["x-keep"], "1");
|
|
407
|
+
assert.equal(plain.authenticated(), true);
|
|
408
|
+
assert.equal((await httpVia(plain.port, "/origin-form")).status, 400, "only absolute http:// URLs are forwarded");
|
|
409
|
+
} finally {
|
|
410
|
+
await tunnel.close();
|
|
411
|
+
await plain.close();
|
|
412
|
+
await echo.close();
|
|
413
|
+
await new Promise<void>((r) => web.close(() => r()));
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
test("proxy public: loopback, private, shared, link-local, unique-local and metadata literals are refused on every route, and nothing is dialled", async () => {
|
|
418
|
+
const decisions: { event: string; reason?: string }[] = [];
|
|
419
|
+
const proxy = await openProxy({ mode: "public", allow: [], onDecision: (d) => decisions.push(d), testing: { local: new Set(), subnets: [] } });
|
|
420
|
+
try {
|
|
421
|
+
const v4 = ["127.0.0.1", "127.0.0.2", "0.0.0.0", "10.1.2.3", "172.16.0.1", "192.168.1.20", "100.100.1.1", "169.254.169.254", "168.63.129.16", "224.0.0.1"];
|
|
422
|
+
const v6 = ["::1", "::", "::ffff:127.0.0.1", "::ffff:7f00:1", "fe80::1", "fd7a:115c:a1e0::1", "fc00::1"];
|
|
423
|
+
for (const ip of [...v4, ...v6]) {
|
|
424
|
+
const hostport = `${net.isIPv6(ip) ? `[${ip}]` : ip}:8080`;
|
|
425
|
+
const c = await connectVia(proxy.port, hostport);
|
|
426
|
+
assert.equal(c.status, 403, `CONNECT ${hostport}: ${c.head}`);
|
|
427
|
+
assert.match(c.head, /X-Relay-Refused: private-address/);
|
|
428
|
+
const h = await httpVia(proxy.port, `http://${hostport}/`);
|
|
429
|
+
assert.equal(h.status, 403, `GET ${hostport}`);
|
|
430
|
+
assert.match(h.body, /public addresses only/);
|
|
431
|
+
assert.equal((await socksVia(proxy.port, ip, 8080)).code, 2, `SOCKS5 ${ip}`);
|
|
432
|
+
}
|
|
433
|
+
// Legacy spellings never reach a name lookup that would read them as loopback: refused as names
|
|
434
|
+
// with a lookup (getaddrinfo reads 2130706433 as 127.0.0.1), or as malformed.
|
|
435
|
+
for (const odd of ["2130706433", "127.1", "0x7f.1"]) assert.equal((await connectVia(proxy.port, `${odd}:8080`)).status, 403, odd);
|
|
436
|
+
assert.ok(decisions.every((d) => d.event === "deny"), "no connection was opened");
|
|
437
|
+
} finally {
|
|
438
|
+
await proxy.close();
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
test("proxy public: a name resolving to a non-public, own or on-link address is refused, looked up once per request", async () => {
|
|
443
|
+
const lookups: string[] = [];
|
|
444
|
+
const answers: Record<string, string[]> = {
|
|
445
|
+
"lo.test": ["127.0.0.1"], "mixed.test": ["8.8.8.8", "10.0.0.1"], "own.test": ["93.184.215.14"],
|
|
446
|
+
"lan6.test": ["2606:4700:20:abcd::99"], "lan4.test": ["203.0.114.7"], "mapped.test": ["::ffff:203.0.114.9"],
|
|
447
|
+
};
|
|
448
|
+
const proxy = await openProxy({
|
|
449
|
+
mode: "public", allow: [],
|
|
450
|
+
testing: {
|
|
451
|
+
lookup: async (h) => (lookups.push(h), answers[h] ?? []),
|
|
452
|
+
local: new Set(["93.184.215.14"]), subnets: ["2606:4700:20:abcd:1:2:3:4/64", "203.0.114.1/24"],
|
|
453
|
+
},
|
|
454
|
+
});
|
|
455
|
+
try {
|
|
456
|
+
const want: Record<string, string> = {
|
|
457
|
+
"lo.test": "private-address", "mixed.test": "private-address", "own.test": "local-interface-address",
|
|
458
|
+
"lan6.test": "on-link-address", "lan4.test": "on-link-address", "mapped.test": "on-link-address",
|
|
459
|
+
};
|
|
460
|
+
for (const [name, reason] of Object.entries(want)) {
|
|
461
|
+
const r = await connectVia(proxy.port, `${name}:443`);
|
|
462
|
+
assert.equal(r.status, 403, name);
|
|
463
|
+
assert.match(r.head, new RegExp(`X-Relay-Refused: ${reason}`), name);
|
|
464
|
+
}
|
|
465
|
+
assert.equal((await socksVia(proxy.port, "lan6.test", 22)).code, 2);
|
|
466
|
+
assert.equal((await httpVia(proxy.port, "http://lan4.test/")).status, 403);
|
|
467
|
+
assert.equal((await connectVia(proxy.port, "nothing.test:443")).status, 403, "a name with no address");
|
|
468
|
+
const bad = await connectVia(proxy.port, "bad!name.test:443");
|
|
469
|
+
assert.equal(bad.status, 403);
|
|
470
|
+
assert.match(bad.head, /X-Relay-Refused: bad-host/, "a malformed name is never looked up");
|
|
471
|
+
assert.deepEqual(lookups, [...Object.keys(want), "lan6.test", "lan4.test", "nothing.test"], "one lookup per request, the dialled address being the screened one");
|
|
472
|
+
} finally {
|
|
473
|
+
await proxy.close();
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
test("proxy: the on-link check covers this machine's subnets, IPv4-mapped forms included, in both modes' screening", () => {
|
|
478
|
+
const subnets = ["192.168.0.20/24", "2606:4700:20:abcd:1:2:3:4/64", "fe80::1%en0/64", "not-a-cidr"];
|
|
479
|
+
assert.equal(onLink("2606:4700:20:abcd::99", subnets), true);
|
|
480
|
+
assert.equal(onLink("2606:4700:20:abce::99", subnets), false);
|
|
481
|
+
assert.equal(onLink("192.168.0.9", subnets), true);
|
|
482
|
+
assert.equal(onLink("::ffff:192.168.0.9", subnets), true);
|
|
483
|
+
assert.equal(onLink("192.168.1.9", subnets), false);
|
|
484
|
+
assert.deepEqual(screenAddresses(["2606:4700:20:abcd::99"], new Set(), subnets), { reason: "on-link-address", address: "2606:4700:20:abcd::99" });
|
|
485
|
+
assert.deepEqual(screenAddresses(["2606:4700::1111"], new Set(), subnets), { addresses: ["2606:4700::1111"] });
|
|
486
|
+
// Read afresh from the machine: its loopback subnet is there.
|
|
487
|
+
assert.ok(localSubnets().some((c) => c.startsWith("127.")));
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
test("proxy: allowlist mode reports a token-authenticated CONNECT, and the public mode refuses an allowlist", async () => {
|
|
491
|
+
const echo = await echoServer();
|
|
492
|
+
const p = await openProxy({ allow: ["api.vendor.test"], testing: { resolve: async () => ["127.0.0.1"], upstreamPort: echo.port } });
|
|
493
|
+
try {
|
|
494
|
+
assert.equal(p.authenticated(), false);
|
|
495
|
+
await connectVia(p.port, "api.vendor.test:443");
|
|
496
|
+
assert.equal(p.authenticated(), false);
|
|
497
|
+
await connectVia(p.port, "api.vendor.test:443", auth(p.token));
|
|
498
|
+
assert.equal(p.authenticated(), true);
|
|
499
|
+
} finally {
|
|
500
|
+
await p.close();
|
|
501
|
+
await echo.close();
|
|
502
|
+
}
|
|
503
|
+
await assert.rejects(openProxy({ mode: "public", allow: ["api.vendor.test"] }), /no allowlist/);
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
test("proxy public: token hosts are recorded; a model stub serves only plain-HTTP token requests for its name", async () => {
|
|
507
|
+
const echo = await echoServer();
|
|
508
|
+
const web = http.createServer((_req, res) => res.writeHead(200).end("stub"));
|
|
509
|
+
await new Promise<void>((r) => web.listen(0, "127.0.0.1", r));
|
|
510
|
+
const p = await openProxy({ mode: "public", allow: [], modelStub: { host: "api.anthropic.com", port: (web.address() as net.AddressInfo).port }, testing: { lookup: async () => ["10.0.0.1"], local: new Set(), subnets: [] } });
|
|
511
|
+
const tunnel = await openProxy({ mode: "public", allow: [], testing: { resolve: async () => ["127.0.0.1"], upstreamPort: echo.port } });
|
|
512
|
+
try {
|
|
513
|
+
assert.equal((await httpVia(p.port, "http://api.anthropic.com/v1/messages")).status, 403, "without the token the name is screened as usual (here it resolves to a private address)");
|
|
514
|
+
assert.deepEqual([...p.tokenHosts()], []);
|
|
515
|
+
assert.deepEqual(await httpVia(p.port, "http://api.anthropic.com/v1/messages", { "proxy-authorization": auth(p.token) }), { status: 200, body: "stub" });
|
|
516
|
+
assert.equal((await connectVia(p.port, "127.0.0.1:443", auth(p.token))).status, 403, "the token opens nothing else on loopback");
|
|
517
|
+
assert.deepEqual([...p.tokenHosts()].sort(), ["127.0.0.1", "api.anthropic.com"]);
|
|
518
|
+
// A tunnel's host is recorded when its CONNECT carries the token, not otherwise.
|
|
519
|
+
await connectVia(tunnel.port, "plain.vendor.test:443");
|
|
520
|
+
assert.equal((await connectVia(tunnel.port, "api.vendor.test:443", auth(tunnel.token))).echoed, "ping");
|
|
521
|
+
assert.deepEqual([...tunnel.tokenHosts()], ["api.vendor.test"]);
|
|
522
|
+
} finally {
|
|
523
|
+
await p.close();
|
|
524
|
+
await tunnel.close();
|
|
525
|
+
await echo.close();
|
|
526
|
+
await new Promise<void>((r) => web.close(() => r()));
|
|
527
|
+
}
|
|
528
|
+
for (const bad of [{ host: "not a host", port: 1 }, { host: "x.invalid", port: 1.5 }, { host: "x.invalid", port: 70000 }]) {
|
|
529
|
+
await assert.rejects(openProxy({ mode: "public", allow: [], modelStub: bad }), /host name and a port/);
|
|
530
|
+
}
|
|
531
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Host only. This file does not launch anything unless the explicit live switch is set.
|
|
2
|
+
import "./helpers.ts";
|
|
3
|
+
import assert from "node:assert/strict";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import net from "node:net";
|
|
7
|
+
import os from "node:os";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { test } from "node:test";
|
|
10
|
+
import { executorPolicy } from "../dist/backends/codex-env.js";
|
|
11
|
+
import { seatbeltProfile, SANDBOX_EXEC } from "../dist/confine/seatbelt.js";
|
|
12
|
+
import { privateTurnTemp } from "../dist/confine/turn.js";
|
|
13
|
+
import { neverPathIdentity, resolveNeverPolicy } from "../dist/core/never-policy.js";
|
|
14
|
+
import { withDefaults } from "../dist/core/config.js";
|
|
15
|
+
import { targetDef } from "../dist/targets/index.js";
|
|
16
|
+
|
|
17
|
+
const skip = process.env.RELAY_TEST_STAGE2_LIVE !== "1" ? "set RELAY_TEST_STAGE2_LIVE=1 outside the sandbox" : process.platform !== "darwin" ? "macOS only" : false;
|
|
18
|
+
const listen = async (host = "127.0.0.1") => {
|
|
19
|
+
const s = net.createServer(c => {
|
|
20
|
+
// Reach probes destroy their client immediately after connecting. A reset while this
|
|
21
|
+
// owned decoy replies is expected; listener errors and client reach assertions still fail.
|
|
22
|
+
c.on("error", () => {});
|
|
23
|
+
c.end("owned-decoy");
|
|
24
|
+
});
|
|
25
|
+
await new Promise<void>((ok, fail) => { s.once("error", fail); s.listen(0, host, ok); });
|
|
26
|
+
return s;
|
|
27
|
+
};
|
|
28
|
+
const port = (s: net.Server) => (s.address() as net.AddressInfo).port;
|
|
29
|
+
const close = (s: net.Server) => new Promise<void>(ok => s.close(() => ok()));
|
|
30
|
+
|
|
31
|
+
test("overlay live production profile: port0/write controls, IPv4 localhost connect reach and final never decoys", { skip, timeout: 30_000 }, async () => {
|
|
32
|
+
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "overlay-live-")));
|
|
33
|
+
const tmp = privateTurnTemp(); const work = path.join(root, "work"), outside = path.join(root, "outside"), sibling = path.join(root, "sibling"), denied = path.join(root, "never-secret");
|
|
34
|
+
for (const d of [work, outside, sibling]) fs.mkdirSync(d);
|
|
35
|
+
fs.writeFileSync(denied, "owned forbidden decoy");
|
|
36
|
+
const listeners: net.Server[] = []; let child: ReturnType<typeof spawn> | undefined;
|
|
37
|
+
try {
|
|
38
|
+
// Never contact real services. Every endpoint is allocated and owned by this test.
|
|
39
|
+
const allowed = await listen("0.0.0.0"), other = await listen("0.0.0.0"), forbidden = await listen(); listeners.push(allowed, other, forbidden);
|
|
40
|
+
const holders = await Promise.all(Array.from({ length: 4 }, () => listen()));
|
|
41
|
+
const [execPort, reserved, block, neverBind] = holders.map(port); await Promise.all(holders.map(close));
|
|
42
|
+
for (const p of [port(allowed), port(other), port(forbidden), execPort, reserved, block, neverBind]) assert.ok(p > 10000);
|
|
43
|
+
const floor = resolveNeverPolicy({ builtins: false, never: { paths: [{ path: denied }], ports: [{ port: port(forbidden), transport: "both", destinations: "this-machine" }, { port: neverBind, transport: "both", destinations: "this-machine" }] } });
|
|
44
|
+
const spec = { target: targetDef("codex"), cwd: work, access: "write", grant: undefined, config: withDefaults({}), neverPolicy: floor,
|
|
45
|
+
overlay: { request: { roots: [{ root: outside, scope: "tree", pins: neverPathIdentity(outside), existed: true }] } },
|
|
46
|
+
} as any;
|
|
47
|
+
const network = { mode: "stage2" as const, egress: "none" as const, deniedTcp: [port(allowed), port(forbidden), neverBind], deniedUdp: [], relayRange: [execPort, reserved], execPort, bindPorts: [block], broadBind: true, worktreeSockets: false, connectPorts: [port(allowed)] };
|
|
48
|
+
// The approved rule uses Seatbelt's supported localhost token, whose IPv4 scope includes
|
|
49
|
+
// this Mac's LAN/tailnet addresses. Snapshot denies are overridden only at the approved port.
|
|
50
|
+
const policy = executorPolicy(spec, tmp, network);
|
|
51
|
+
const generated = seatbeltProfile(policy, process.execPath);
|
|
52
|
+
assert.doesNotMatch(generated.profile, /\((?:remote|local)\s+(?:ip[46]?|tcp|udp)\s+(?:\(string-append\s+)?"(?:\d+\.\d+\.\d+\.\d+|\[?::1)/);
|
|
53
|
+
const hosts = [...new Set(["127.0.0.1", ...Object.values(os.networkInterfaces()).flatMap(as => as ?? [])
|
|
54
|
+
.filter(a => a.family === "IPv4" && !a.address.startsWith("127.")).map(a => a.address)])];
|
|
55
|
+
const script = `
|
|
56
|
+
const fs = require('node:fs'), net = require('node:net');
|
|
57
|
+
const out = {};
|
|
58
|
+
const write = p => { try { fs.writeFileSync(p, 'decoy'); return 'ok'; } catch(e) { return e.code; } };
|
|
59
|
+
const bind = p => new Promise(ok => { const s = net.createServer(); s.once('error', e => ok(e.code)); s.listen(p, '0.0.0.0', () => s.close(() => ok('ok'))); });
|
|
60
|
+
const connect = (p, host='127.0.0.1') => new Promise(ok => { const s = net.connect(p, host); const timer = setTimeout(() => { s.destroy(); ok('TIMEOUT'); }, 2000); s.once('connect', () => { clearTimeout(timer); s.destroy(); ok('ok'); }); s.once('error', e => { clearTimeout(timer); ok(e.code); }); });
|
|
61
|
+
(async () => {
|
|
62
|
+
out.write = write(${JSON.stringify(path.join(outside, "allowed"))}); out.sibling = write(${JSON.stringify(path.join(sibling, "denied"))});
|
|
63
|
+
try { fs.readFileSync(${JSON.stringify(denied)}); out.neverRead = 'ok'; } catch(e) { out.neverRead = e.code; }
|
|
64
|
+
out.broad = await bind(0); out.executor = await bind(${execPort}); out.reserved = await bind(${reserved}); out.neverBind = await bind(${neverBind});
|
|
65
|
+
out.connect = await connect(${port(allowed)}); out.neverConnect = await connect(${port(forbidden)});
|
|
66
|
+
out.allowedHosts = {}; out.otherHosts = {};
|
|
67
|
+
for(const host of ${JSON.stringify(hosts)}) { out.allowedHosts[host] = await connect(${port(allowed)},host); out.otherHosts[host] = await connect(${port(other)},host); }
|
|
68
|
+
out.alias = await connect(${port(allowed)},'127.0.0.2'); out.ipv6 = await connect(${port(allowed)},'::1'); out.mapped = await connect(${port(allowed)},'::ffff:127.0.0.1');
|
|
69
|
+
console.log(JSON.stringify(out));
|
|
70
|
+
})().catch(e => { console.error(e); process.exitCode = 1; });`;
|
|
71
|
+
const result = await new Promise<string>((ok, fail) => {
|
|
72
|
+
child = spawn(SANDBOX_EXEC, ["-p", generated.profile, ...generated.params.flatMap(([k,v]) => ["-D", `${k}=${v}`]), process.execPath, "-e", script], { cwd: work, timeout: 15000, killSignal: "SIGKILL", env: { PATH: process.env.PATH, HOME: os.homedir(), TMPDIR: tmp }, stdio: ["ignore", "pipe", "pipe"] });
|
|
73
|
+
let stdout = "", stderr = ""; child.stdout!.on("data", d => stdout += d); child.stderr!.on("data", d => stderr += d);
|
|
74
|
+
child.once("error", fail); child.once("exit", code => code === 0 ? ok(stdout) : fail(new Error(`sandbox exit ${code}: ${stderr}`)));
|
|
75
|
+
});
|
|
76
|
+
const r = JSON.parse(result);
|
|
77
|
+
for (const key of ["write", "broad", "executor", "connect"]) assert.equal(r[key], "ok", key);
|
|
78
|
+
for (const host of hosts) { assert.equal(r.allowedHosts[host], "ok", host); assert.equal(r.otherHosts[host], "EPERM", host); }
|
|
79
|
+
for (const key of ["sibling", "neverRead", "reserved", "neverBind", "neverConnect", "alias", "ipv6", "mapped"]) assert.match(r[key], /^(EPERM|EACCES)$/, `${key}: use a denial oracle, never timeout/EADDRINUSE`);
|
|
80
|
+
} finally {
|
|
81
|
+
if (child && child.exitCode === null && child.signalCode === null) { child.kill("SIGKILL"); await new Promise(ok => child!.once("exit", ok)); }
|
|
82
|
+
await Promise.all(listeners.map(close));
|
|
83
|
+
fs.rmSync(root, { recursive: true, force: true }); fs.rmSync(tmp, { recursive: true, force: true });
|
|
84
|
+
}
|
|
85
|
+
});
|