@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,365 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { relayHome } from "../core/config.js";
|
|
6
|
+
import { addHolder, lookLeases, releaseOwn, takePort } from "./leases.js";
|
|
7
|
+
import { loopbackAliases } from "./probe.js";
|
|
8
|
+
import { canonicalAddress } from "./proxy.js";
|
|
9
|
+
import { STATIC_DENIED_TCP } from "./port-policy.js";
|
|
10
|
+
export { STATIC_DENIED_TCP, STATIC_DENIED_UDP } from "./port-policy.js";
|
|
11
|
+
export { portHeld, releaseLeasesOf } from "./leases.js";
|
|
12
|
+
/**
|
|
13
|
+
* Stage 2 (docs/codex-confinement-design.md §5): the ports a stage-2 Codex turn may and may not
|
|
14
|
+
* reach or bind, and the watch on this Mac's addresses. Owner: WP-A.
|
|
15
|
+
*/
|
|
16
|
+
/** relay's reserved range (§5.5): executors, job port blocks, and relay's own proxies once moved there. */
|
|
17
|
+
export const RELAY_PORT_RANGE = { first: 47200, count: 64 };
|
|
18
|
+
/** Ports in a job's own block (§5.9, decision D3), passed as PORT and PORTS only when bindable. */
|
|
19
|
+
export const JOB_BLOCK_SIZE = 4;
|
|
20
|
+
/** The ports of a range, in order. */
|
|
21
|
+
export const rangePorts = (r = RELAY_PORT_RANGE) => Array.from({ length: r.count }, (_, i) => r.first + i);
|
|
22
|
+
/**
|
|
23
|
+
* Leases free executor and broker ports and a job block; refuses when the reserved range is full.
|
|
24
|
+
*
|
|
25
|
+
* Leases are files in relay's control directory (`<relay home>/ports`, which every confined profile
|
|
26
|
+
* denies), one generation per port at a time, holding the leasing process's pid and start time
|
|
27
|
+
* (leases.ts), so that relay processes serving different sessions never hand out the same port. A
|
|
28
|
+
* lease whose process is gone is taken over, unless a process it names as holding it too (`hold`,
|
|
29
|
+
* the executor) is still that process; of the processes that find it so, one takes it. A port
|
|
30
|
+
* something already listens on is skipped (`busy`): a job's block is exempt from the range deny,
|
|
31
|
+
* so a block port with someone else's listener on it would be reachable.
|
|
32
|
+
*/
|
|
33
|
+
export function leaseTurnPorts(o = {}) {
|
|
34
|
+
const size = o.blockSize ?? JOB_BLOCK_SIZE;
|
|
35
|
+
if (!Number.isInteger(size) || size < 1)
|
|
36
|
+
throw new Error(`a job's port block needs at least one port: ${size}`);
|
|
37
|
+
const all = rangePorts(o.range);
|
|
38
|
+
const dir = o.dir ?? path.join(relayHome(), "ports");
|
|
39
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
40
|
+
const busy = o.busy ?? busyPorts;
|
|
41
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
42
|
+
const look = lookLeases(dir, all);
|
|
43
|
+
const held = look.held;
|
|
44
|
+
const candidates = all.filter((p) => !held.has(p));
|
|
45
|
+
const taken = busy(candidates);
|
|
46
|
+
const free = candidates.filter((p) => !taken.has(p));
|
|
47
|
+
const block = contiguous(free, size) ?? (free.length > size ? free.slice(0, size) : null);
|
|
48
|
+
const exec = block ? free.find((p) => !block.includes(p)) : undefined;
|
|
49
|
+
const broker = block ? free.find((p) => p !== exec && !block.includes(p)) : undefined;
|
|
50
|
+
const proxy = o.proxy ? free.find(p => p !== exec && p !== broker && !block?.includes(p)) : undefined;
|
|
51
|
+
if (!block || exec === undefined || broker === undefined || (o.proxy && proxy === undefined)) {
|
|
52
|
+
throw new Error(`relay's reserved port range ${all[0]}-${all.at(-1)} has no room for another stage-2 turn (${held.size} leased, ${taken.size} in use by something else); wait for a turn to end`);
|
|
53
|
+
}
|
|
54
|
+
o.afterLook?.();
|
|
55
|
+
const claimed = [];
|
|
56
|
+
let lost = false;
|
|
57
|
+
for (const p of [exec, broker, ...(proxy === undefined ? [] : [proxy]), ...block]) {
|
|
58
|
+
const file = takePort(dir, p, look.free.get(p));
|
|
59
|
+
if (file)
|
|
60
|
+
claimed.push(file);
|
|
61
|
+
else {
|
|
62
|
+
lost = true;
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (lost) {
|
|
67
|
+
// Another relay process took one between the look and the claim: give back what was claimed and look again.
|
|
68
|
+
for (const f of claimed)
|
|
69
|
+
releaseOwn(f);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
let released = false;
|
|
73
|
+
return {
|
|
74
|
+
exec,
|
|
75
|
+
broker,
|
|
76
|
+
...(proxy === undefined ? {} : { proxy }),
|
|
77
|
+
block,
|
|
78
|
+
range: all.filter((p) => !block.includes(p)),
|
|
79
|
+
hold(pid, start, record) {
|
|
80
|
+
if (released || !Number.isInteger(pid) || pid <= 1 || !start || /[\n]/.test(start))
|
|
81
|
+
return;
|
|
82
|
+
for (const f of claimed)
|
|
83
|
+
addHolder(f, pid, start, record);
|
|
84
|
+
},
|
|
85
|
+
release() {
|
|
86
|
+
if (released)
|
|
87
|
+
return;
|
|
88
|
+
released = true;
|
|
89
|
+
for (const f of claimed)
|
|
90
|
+
releaseOwn(f);
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
throw new Error("relay could not lease ports for a stage-2 turn: other relay processes kept taking them; try again");
|
|
95
|
+
}
|
|
96
|
+
/** The first run of `n` consecutive ports in `free` (ascending), or null. */
|
|
97
|
+
function contiguous(free, n) {
|
|
98
|
+
for (let i = 0; i + n <= free.length; i++) {
|
|
99
|
+
if (free[i + n - 1] - free[i] === n - 1)
|
|
100
|
+
return free.slice(i, i + n);
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The hosts a port is tried on to find out whether something listens on it. On macOS, with the
|
|
106
|
+
* SO_REUSEADDR every Node server sets, a wildcard bind succeeds beside another socket's specific
|
|
107
|
+
* address and the reverse, so each kind is tried: loopback, the dual-stack wildcard, and every
|
|
108
|
+
* address of this Mac's, link-local ones with their interface (review R6: a survivor listening on
|
|
109
|
+
* fe80::1%lo0 alone was not found, and the job could then reach it on its own block).
|
|
110
|
+
*/
|
|
111
|
+
export function bindHosts(interfaces = os.networkInterfaces()) {
|
|
112
|
+
const own = Object.entries(interfaces).flatMap(([name, list]) => (list ?? []).map((a) => {
|
|
113
|
+
const bare = a.address.split("%")[0];
|
|
114
|
+
return a.family === "IPv6" && /^fe[89ab][0-9a-f]:/i.test(bare) ? `${bare}%${name}` : bare;
|
|
115
|
+
}));
|
|
116
|
+
return [...new Set(["127.0.0.1", "::1", "::", ...own])];
|
|
117
|
+
}
|
|
118
|
+
/** The ports among these that something listens on, by a bind test in a child process (bind is asynchronous in Node). */
|
|
119
|
+
export function busyPorts(ports) {
|
|
120
|
+
if (!ports.length)
|
|
121
|
+
return new Set();
|
|
122
|
+
const script = `
|
|
123
|
+
const net = require("node:net");
|
|
124
|
+
const [ports, hosts] = JSON.parse(process.argv[1]);
|
|
125
|
+
const tryBind = (host, port) => new Promise((res) => {
|
|
126
|
+
const s = net.createServer();
|
|
127
|
+
s.once("error", (e) => res(e.code));
|
|
128
|
+
s.listen({ host, port, ipv6Only: host === "::1" ? true : host === "::" ? false : undefined }, () => s.close(() => res("ok")));
|
|
129
|
+
});
|
|
130
|
+
(async () => {
|
|
131
|
+
const busy = [];
|
|
132
|
+
for (const p of ports) for (const h of hosts) {
|
|
133
|
+
const r = await tryBind(h, p);
|
|
134
|
+
if (r !== "ok" && r !== "EADDRNOTAVAIL" && r !== "EAFNOSUPPORT") { busy.push(p); break; }
|
|
135
|
+
}
|
|
136
|
+
process.stdout.write(JSON.stringify(busy));
|
|
137
|
+
})();`;
|
|
138
|
+
const r = spawnSync(process.execPath, ["-e", script, JSON.stringify([ports, bindHosts()])], { encoding: "utf8", timeout: 20_000, env: { PATH: "/usr/bin:/bin" } });
|
|
139
|
+
if (r.status !== 0)
|
|
140
|
+
throw new Error(`relay could not test which reserved ports are free: ${(r.stderr || r.error?.message || `exit ${r.status}`).trim()}`);
|
|
141
|
+
return new Set(JSON.parse(r.stdout));
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* What marks a listener as an agent control plane, by its command line: something that runs or
|
|
145
|
+
* forwards whatever a client asks. Codex's own listeners (app-server and exec-server websockets, its
|
|
146
|
+
* network proxy), Claude Code and relay (remote-control hosts, sandbox and CONNECT proxies),
|
|
147
|
+
* Jupyter kernels and servers, Chrome or Electron remote debugging, Node's inspector, editor servers,
|
|
148
|
+
* and forwarders (ssh, socat).
|
|
149
|
+
*/
|
|
150
|
+
export const CONTROL_PLANE_PATTERNS = [
|
|
151
|
+
/(^|\/)codex(\s|$)/,
|
|
152
|
+
/(^|\/)claude(\s|$)/,
|
|
153
|
+
/(^|[\s/])relay(\/dist\/cli\.js|\s|$)/,
|
|
154
|
+
/remote-control/,
|
|
155
|
+
/jupyter/i,
|
|
156
|
+
/--remote-debugging-(port|pipe)/,
|
|
157
|
+
/--inspect(-brk)?(=|\s|$)/,
|
|
158
|
+
/(^|\/)(code-server|code-tunnel)(\s|$)/,
|
|
159
|
+
/(^|\/)(ssh|socat)(\s|$)/,
|
|
160
|
+
];
|
|
161
|
+
const isControlPlane = (args) => CONTROL_PLANE_PATTERNS.some((re) => re.test(args));
|
|
162
|
+
const validPort = (p) => Number.isInteger(p) && p >= 1 && p <= 65535;
|
|
163
|
+
/** The listeners in `lsof -F pcn` output (`-iTCP -sTCP:LISTEN`). */
|
|
164
|
+
export function lsofListeners(lsofFields) {
|
|
165
|
+
const out = [];
|
|
166
|
+
let pid = -1, command = "";
|
|
167
|
+
for (const line of lsofFields.split("\n")) {
|
|
168
|
+
const tag = line[0], value = line.slice(1);
|
|
169
|
+
if (tag === "p")
|
|
170
|
+
(pid = Number(value)), (command = "");
|
|
171
|
+
else if (tag === "c")
|
|
172
|
+
command = value;
|
|
173
|
+
else if (tag === "n") {
|
|
174
|
+
// -n -P names: "127.0.0.1:1025", "*:32400", "[::1]:7679"; a listening socket has no "->".
|
|
175
|
+
const m = /:(\d+)$/.exec(value);
|
|
176
|
+
if (!m || value.includes("->"))
|
|
177
|
+
continue;
|
|
178
|
+
const port = Number(m[1]);
|
|
179
|
+
if (validPort(port))
|
|
180
|
+
out.push({ pid, command, port });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The listeners in `nettop -L 1 -m tcp -n -J state` output: a CSV log with a `,state,` header, a
|
|
187
|
+
* line per process (`name.pid,,`) and after it a line per socket of that process (`tcp4
|
|
188
|
+
* 127.0.0.1:1025<->*:*,Listen,`, `tcp6 ::1.7679<->*.*,Listen,`). nettop reads the kernel's network
|
|
189
|
+
* statistics, which show every user's sockets to an unprivileged caller; lsof shows only this
|
|
190
|
+
* user's, and netstat no TCP socket at all (measured on macOS 27.0.1, review R8). Output of another
|
|
191
|
+
* shape throws, so that a changed nettop refuses the turn instead of hiding listeners.
|
|
192
|
+
*/
|
|
193
|
+
export function nettopListeners(csv) {
|
|
194
|
+
const lines = csv.split("\n").map((l) => l.trimEnd()).filter((l) => l !== "");
|
|
195
|
+
if (lines[0] !== ",state,")
|
|
196
|
+
throw new Error(`nettop's output does not start with the expected header: ${JSON.stringify((lines[0] ?? "").slice(0, 80))}`);
|
|
197
|
+
const out = [];
|
|
198
|
+
let pid = -1, command = "";
|
|
199
|
+
for (const line of lines.slice(1)) {
|
|
200
|
+
const flow = /^tcp[46] (\S*?)[:.](\d+|\*)<->\S*,(\w*),$/.exec(line);
|
|
201
|
+
if (flow) {
|
|
202
|
+
const port = Number(flow[2]);
|
|
203
|
+
if (flow[3] === "Listen" && validPort(port))
|
|
204
|
+
out.push({ pid, command, port });
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const proc = /^(.*)\.(\d+),\w*,$/.exec(line);
|
|
208
|
+
if (!proc)
|
|
209
|
+
throw new Error(`nettop printed a line relay does not recognise: ${JSON.stringify(line.slice(0, 80))}`);
|
|
210
|
+
(command = proc[1]), (pid = Number(proc[2]));
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* The snapshot from listeners and each one's command line (`ps` args by pid; the command name stands
|
|
216
|
+
* in where a process is gone or its arguments are not shown). Ports in numeric order within each group.
|
|
217
|
+
*/
|
|
218
|
+
export function snapshotOf(listeners, argsByPid) {
|
|
219
|
+
const control = new Set(), other = new Set();
|
|
220
|
+
for (const l of listeners)
|
|
221
|
+
(isControlPlane(argsByPid.get(l.pid) ?? l.command) ? control : other).add(l.port);
|
|
222
|
+
const controlPlanes = [...control].sort((a, b) => a - b);
|
|
223
|
+
return { ports: [...controlPlanes, ...[...other].filter((p) => !control.has(p)).sort((a, b) => a - b)], controlPlanes };
|
|
224
|
+
}
|
|
225
|
+
/** The snapshot from `lsof -F pcn` output alone (snapshotOf over lsofListeners). */
|
|
226
|
+
export function parseListeningSnapshot(lsofFields, argsByPid) {
|
|
227
|
+
return snapshotOf(lsofListeners(lsofFields), argsByPid);
|
|
228
|
+
}
|
|
229
|
+
const LSOF = "/usr/sbin/lsof";
|
|
230
|
+
const NETTOP = "/usr/bin/nettop";
|
|
231
|
+
/**
|
|
232
|
+
* Every TCP listener on this Mac now, any user's (decision D4, review R8): this user's from lsof,
|
|
233
|
+
* with their command lines, and everyone's from nettop, root's included (sshd and screen sharing
|
|
234
|
+
* through launchd, smbd, kdc, a VPN's own listeners). Either failing refuses the turn.
|
|
235
|
+
*/
|
|
236
|
+
export function listeningSnapshot(uid = process.getuid?.() ?? -1) {
|
|
237
|
+
if (!Number.isInteger(uid) || uid < 0)
|
|
238
|
+
throw new Error("relay cannot take the listening snapshot: no user id on this platform");
|
|
239
|
+
const r = spawnSync(LSOF, ["-nP", "-a", "-u", String(uid), "-iTCP", "-sTCP:LISTEN", "-F", "pcn"], { encoding: "utf8", timeout: 20_000, maxBuffer: 16 << 20 });
|
|
240
|
+
// lsof exits 1 when nothing matches; anything else, or output with an error, refuses the turn.
|
|
241
|
+
if (r.error || (r.status !== 0 && !(r.status === 1 && !r.stdout.trim()))) {
|
|
242
|
+
throw new Error(`relay could not list the ports this user listens on (lsof: ${(r.error?.message || r.stderr || `exit ${r.status}`).trim()}), so it cannot deny them`);
|
|
243
|
+
}
|
|
244
|
+
const n = spawnSync(NETTOP, ["-L", "1", "-m", "tcp", "-n", "-J", "state"], { encoding: "utf8", timeout: 20_000, maxBuffer: 64 << 20 });
|
|
245
|
+
if (n.error || n.status !== 0) {
|
|
246
|
+
throw new Error(`relay could not list every TCP listener on this Mac (nettop: ${(n.error?.message || n.stderr || `exit ${n.status}`).trim()}), so it cannot deny them`);
|
|
247
|
+
}
|
|
248
|
+
let everyone;
|
|
249
|
+
try {
|
|
250
|
+
everyone = nettopListeners(n.stdout);
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
throw new Error(`relay could not read the TCP listeners on this Mac (${err.message}), so it cannot deny them`);
|
|
254
|
+
}
|
|
255
|
+
const listeners = [...lsofListeners(r.stdout), ...everyone];
|
|
256
|
+
const pids = [...new Set(listeners.map((l) => l.pid))].filter((p) => p > 0);
|
|
257
|
+
const args = new Map();
|
|
258
|
+
if (pids.length) {
|
|
259
|
+
const ps = spawnSync("/bin/ps", ["-ww", "-o", "pid=,args=", "-p", pids.join(",")], { encoding: "utf8", timeout: 20_000, maxBuffer: 16 << 20 });
|
|
260
|
+
for (const line of (ps.stdout ?? "").split("\n")) {
|
|
261
|
+
const m = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
262
|
+
if (m)
|
|
263
|
+
args.set(Number(m[1]), m[2]);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return snapshotOf(listeners, args);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* The TCP ports a stage-2 turn denies: the static list, then the snapshot (control planes first).
|
|
270
|
+
* Ports in relay's reserved range are left to the profile's range deny, which covers all of them
|
|
271
|
+
* but the turn's own block, except that a listener on the block, executor or broker port refuses
|
|
272
|
+
* the turn (review R6): the block is exempt from the range deny, so the job could reach whatever
|
|
273
|
+
* listens there, and the executor could not take its port. The lease is taken before the snapshot
|
|
274
|
+
* and the executor started after it, so neither is the turn's own.
|
|
275
|
+
*/
|
|
276
|
+
export function deniedTcpPorts(snapshot, own) {
|
|
277
|
+
const taken = snapshot.ports.filter((p) => p === own.exec || p === own.broker || p === own.proxy || own.block.includes(p));
|
|
278
|
+
if (taken.length) {
|
|
279
|
+
const what = taken.map((p) => `${p} (${p === own.exec ? "the executor's port" : p === own.broker ? "the broker's port" : p === own.proxy ? "the mediated proxy's port" : "the job's block"})`).join(", ");
|
|
280
|
+
throw new Error(`something is already listening on this turn's own ports in relay's reserved range, ${what}, so relay does not start the turn; it may be a process left from an earlier turn`);
|
|
281
|
+
}
|
|
282
|
+
const r = RELAY_PORT_RANGE;
|
|
283
|
+
const reserved = (p) => p >= r.first && p < r.first + r.count;
|
|
284
|
+
return [...new Set([...STATIC_DENIED_TCP, ...snapshot.controlPlanes, ...snapshot.ports])].filter((p) => !reserved(p));
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* This Mac's interface addresses, as the probes and the watch compare them (canonical form).
|
|
288
|
+
* IPv4 dotted, IPv6 in full (canonicalAddress), link-local IPv6 with its interface (`%en1`) so that
|
|
289
|
+
* the same address on another interface counts as new and the probes can connect to it. Sorted, unique.
|
|
290
|
+
*/
|
|
291
|
+
export function interfaceAddresses(interfaces = os.networkInterfaces()) {
|
|
292
|
+
const out = new Set();
|
|
293
|
+
for (const [name, list] of Object.entries(interfaces)) {
|
|
294
|
+
for (const a of list ?? []) {
|
|
295
|
+
const c = canonicalAddress(a.address);
|
|
296
|
+
out.add(a.family === "IPv6" && /^fe[89ab]/.test(c) ? `${c}%${name}` : c);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return [...out].sort();
|
|
300
|
+
}
|
|
301
|
+
/** How often the watch reads the addresses. */
|
|
302
|
+
export const INTERFACE_POLL_MS = 3000;
|
|
303
|
+
/**
|
|
304
|
+
* A new address, one the turn's probes did not see, fails the turn: Seatbelt's local-address deny
|
|
305
|
+
* was measured for the addresses present (§5.2), and a VPN or a new interface can bring paths the
|
|
306
|
+
* design did not look at. Addresses that go away do not fail it: nothing new is reachable. A change,
|
|
307
|
+
* once seen, stays reported. `read` is for tests.
|
|
308
|
+
*/
|
|
309
|
+
/** An IPv6 link-local address as interfaceAddresses gives it (expanded, with its interface): fe80::/10. */
|
|
310
|
+
const LINK_LOCAL_V6 = /^fe[89ab][0-9a-f]:/i;
|
|
311
|
+
export function watchInterfaces(baseline, intervalMs = INTERFACE_POLL_MS, read = interfaceAddresses) {
|
|
312
|
+
const base = new Set(baseline);
|
|
313
|
+
let seen = null;
|
|
314
|
+
let fail = null;
|
|
315
|
+
let told = false;
|
|
316
|
+
const look = () => {
|
|
317
|
+
if (seen)
|
|
318
|
+
return seen;
|
|
319
|
+
let now;
|
|
320
|
+
try {
|
|
321
|
+
now = read();
|
|
322
|
+
}
|
|
323
|
+
catch (err) {
|
|
324
|
+
seen = `relay could not read this Mac's network addresses: ${err.message}`;
|
|
325
|
+
return seen;
|
|
326
|
+
}
|
|
327
|
+
// An IPv6 link-local address that comes or goes fails nothing: macOS rotates them on awdl0 and
|
|
328
|
+
// llw0 every few minutes, and the stage-2 rules deny the denied and reserved ports over IPv6 at
|
|
329
|
+
// every host (seatbelt-stage2.ts), so a new one opens nothing. Any other new address fails the
|
|
330
|
+
// turn: the per-turn probes did not cover it.
|
|
331
|
+
const added = now.filter((a) => !base.has(a) && !LINK_LOCAL_V6.test(a));
|
|
332
|
+
if (added.length) {
|
|
333
|
+
const gone = baseline.filter((a) => !now.includes(a));
|
|
334
|
+
seen = `this Mac's network addresses changed during the turn: new ${added.join(", ")}${gone.length ? `; gone ${gone.join(", ")}` : ""}. The turn's checks did not cover the new ones`;
|
|
335
|
+
}
|
|
336
|
+
return seen;
|
|
337
|
+
};
|
|
338
|
+
const tell = () => {
|
|
339
|
+
if (seen && fail && !told) {
|
|
340
|
+
told = true;
|
|
341
|
+
fail(seen);
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
const timer = setInterval(() => {
|
|
345
|
+
look();
|
|
346
|
+
tell();
|
|
347
|
+
}, intervalMs);
|
|
348
|
+
timer.unref();
|
|
349
|
+
return {
|
|
350
|
+
changed: () => look(),
|
|
351
|
+
onChange(f) {
|
|
352
|
+
fail = f;
|
|
353
|
+
tell();
|
|
354
|
+
},
|
|
355
|
+
stop: () => clearInterval(timer),
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
/** A refusal when lo0 carries aliases Seatbelt's "localhost" does not cover (§5.2), else null. Uses probe.ts loopbackAliases. */
|
|
359
|
+
export function loopbackAliasProblem(interfaces = os.networkInterfaces()) {
|
|
360
|
+
const aliases = loopbackAliases(interfaces);
|
|
361
|
+
if (!aliases.length)
|
|
362
|
+
return null;
|
|
363
|
+
return `the loopback interface carries ${aliases.length === 1 ? "an address" : "addresses"} besides 127.0.0.1, ::1 and fe80::1 (${aliases.join(", ")}). ` +
|
|
364
|
+
"A stage-2 profile's local-port denies do not cover such aliases, so relay does not run a stage-2 turn while they exist; remove them (sudo ifconfig lo0 -alias <address>) or run the job in strict mode";
|
|
365
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
// Outside every harness's shared temp allowance. Keep names short: Darwin's sockaddr_un
|
|
5
|
+
// accommodates only 103 pathname bytes. Grants may cover neither these roots nor an ancestor.
|
|
6
|
+
export const privateStateRoot = () => path.join(fs.realpathSync(os.homedir()), ".relay-t");
|
|
7
|
+
// Claude falls back to shared /tmp/claude-<uid> if its own subdir exceeds 44 bytes (CLAUDE_TEMP_LIMIT).
|
|
8
|
+
// This root plus a six-character turn name leaves room for that suffix under a short home; under
|
|
9
|
+
// a longer one, Claude is given the turn through nativeTempAlias instead.
|
|
10
|
+
export const nativeTempRoot = () => path.join(fs.realpathSync(os.homedir()), ".rn");
|
|
11
|
+
export function ensurePrivateRoot(dir) {
|
|
12
|
+
try {
|
|
13
|
+
fs.mkdirSync(dir, { mode: 0o700 });
|
|
14
|
+
}
|
|
15
|
+
catch (err) {
|
|
16
|
+
if (err.code !== "EEXIST")
|
|
17
|
+
throw err;
|
|
18
|
+
}
|
|
19
|
+
const st = fs.lstatSync(dir);
|
|
20
|
+
if (!st.isDirectory() || st.isSymbolicLink() || (process.getuid && st.uid !== process.getuid())) {
|
|
21
|
+
throw new Error(`relay's private directory ${dir} must be a plain directory owned by this user`);
|
|
22
|
+
}
|
|
23
|
+
if (st.mode & 0o077)
|
|
24
|
+
fs.chmodSync(dir, 0o700);
|
|
25
|
+
return dir;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Claude Code's own limit (in every version of VERIFIED.claudeTempLink, targets/verified.ts):
|
|
29
|
+
* `path.join(CLAUDE_CODE_TMPDIR, "claude-<uid>")`, measured as given, links unresolved. Past it,
|
|
30
|
+
* its sandboxed commands get the shared /tmp/claude-<uid> instead
|
|
31
|
+
* (docs/research/claude-temp-limit.md).
|
|
32
|
+
*/
|
|
33
|
+
export const CLAUDE_TEMP_LIMIT = 44;
|
|
34
|
+
const uid = () => process.getuid?.() ?? 0;
|
|
35
|
+
/** Whether Claude keeps `dir` as its CLAUDE_CODE_TMPDIR rather than fall back to shared temp. */
|
|
36
|
+
export const claudeTempFits = (dir) => Buffer.byteLength(path.join(dir, `claude-${uid()}`)) <= CLAUDE_TEMP_LIMIT;
|
|
37
|
+
const ALIAS_PARENT = "/Users/Shared";
|
|
38
|
+
let aliasParent = ALIAS_PARENT;
|
|
39
|
+
/** Tests only: another directory for the short link, or null for the real one. Nothing in relay calls this. */
|
|
40
|
+
export function setNativeTempAliasParentForTests(dir) {
|
|
41
|
+
aliasParent = dir ?? ALIAS_PARENT;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The short name of `~/.rn` that relay hands Claude when `~/.rn` is too long for it: a link of this
|
|
45
|
+
* user's in /Users/Shared, which is sticky (only an entry's owner or root can rename or remove it)
|
|
46
|
+
* and which no agent's sandbox writes by default. The turns' files stay in `~/.rn`.
|
|
47
|
+
*/
|
|
48
|
+
export const nativeTempAlias = () => path.join(aliasParent, `.rn-${uid()}`);
|
|
49
|
+
/**
|
|
50
|
+
* Throws unless every directory on the way to `dir` and `dir` itself is owned by root or this user
|
|
51
|
+
* and writable by no one else unless sticky, and every link on the way is owned by root or this
|
|
52
|
+
* user. Then no other user can replace an entry of this user's in `dir`, or anything on the way to
|
|
53
|
+
* it. The walk takes each name in the order the kernel does: a link's target from the directory
|
|
54
|
+
* holding the link (or from / when absolute), and `..` from the directory the walk has reached, so
|
|
55
|
+
* it checks the directories the path really passes. (ACLs are not read: one granting others
|
|
56
|
+
* that is an administrator's, like root.)
|
|
57
|
+
*/
|
|
58
|
+
function checkAncestry(dir, me) {
|
|
59
|
+
const names = (p) => p.split(path.sep).filter((n) => n !== "" && n !== ".");
|
|
60
|
+
const owned = (p, st) => {
|
|
61
|
+
if (st.uid !== 0 && st.uid !== me)
|
|
62
|
+
throw new Error(`${p} is owned by uid ${st.uid}, neither root nor this user`);
|
|
63
|
+
};
|
|
64
|
+
const safeDir = (p, st) => {
|
|
65
|
+
owned(p, st);
|
|
66
|
+
if (!st.isDirectory())
|
|
67
|
+
throw new Error(`${p} is not a directory`);
|
|
68
|
+
if ((st.mode & 0o022) && !(st.mode & 0o1000))
|
|
69
|
+
throw new Error(`${p} can be written by other users and is not sticky, so they could replace what is in it`);
|
|
70
|
+
};
|
|
71
|
+
if (!path.isAbsolute(dir))
|
|
72
|
+
throw new Error(`${dir} is not an absolute path`);
|
|
73
|
+
let rest = names(dir);
|
|
74
|
+
// Always a real directory already checked: the names walked so far, with every link followed.
|
|
75
|
+
let cur = path.sep;
|
|
76
|
+
safeDir(cur, fs.lstatSync(cur));
|
|
77
|
+
let links = 0;
|
|
78
|
+
for (let name = rest.shift(); name !== undefined; name = rest.shift()) {
|
|
79
|
+
if (name === "..") {
|
|
80
|
+
cur = path.dirname(cur);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const next = path.join(cur, name);
|
|
84
|
+
const st = fs.lstatSync(next);
|
|
85
|
+
if (st.isSymbolicLink()) {
|
|
86
|
+
owned(next, st);
|
|
87
|
+
if (++links > 16)
|
|
88
|
+
throw new Error(`there are too many links on the way to ${dir}`);
|
|
89
|
+
const to = fs.readlinkSync(next);
|
|
90
|
+
rest = [...names(to), ...rest];
|
|
91
|
+
if (path.isAbsolute(to))
|
|
92
|
+
cur = path.sep;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
safeDir(next, st);
|
|
96
|
+
cur = next;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Recognize a deleted private root by the owned link's canonical absolute `.rn` name. There is no
|
|
101
|
+
* inode left to check. Walk only plain, trusted ancestors, stopping at the first missing entry;
|
|
102
|
+
* never follow an old root or a link on its way, and never remove anything at the old destination.
|
|
103
|
+
*/
|
|
104
|
+
function missingNativeTempRoot(target, me) {
|
|
105
|
+
if (!path.isAbsolute(target) || path.normalize(target) !== target || path.basename(target) !== ".rn")
|
|
106
|
+
return false;
|
|
107
|
+
let cur = path.sep;
|
|
108
|
+
const names = target.split(path.sep).filter(Boolean);
|
|
109
|
+
for (const [i, name] of names.entries()) {
|
|
110
|
+
cur = path.join(cur, name);
|
|
111
|
+
const st = fs.lstatSync(cur, { throwIfNoEntry: false });
|
|
112
|
+
if (!st)
|
|
113
|
+
return true;
|
|
114
|
+
if (i === names.length - 1 || !st.isDirectory() || st.isSymbolicLink())
|
|
115
|
+
return false;
|
|
116
|
+
if (st.uid !== 0 && st.uid !== me)
|
|
117
|
+
return false;
|
|
118
|
+
if ((st.mode & 0o022) && !(st.mode & 0o1000))
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Checks the short link to `target` (the real `~/.rn`) and the way to it, making nothing. Each check
|
|
125
|
+
* reads the entry itself (no follow) until the last, which compares where it leads with `target`
|
|
126
|
+
* when `target` exists (relay makes `~/.rn` before it uses the link). Doctor reports this; turns use
|
|
127
|
+
* ensureNativeTempAlias, which makes a missing link or repoints a stale one and checks it again.
|
|
128
|
+
*/
|
|
129
|
+
export function checkNativeTempAlias(target) {
|
|
130
|
+
const me = uid();
|
|
131
|
+
const alias = nativeTempAlias();
|
|
132
|
+
const refused = (problem) => ({ state: "refused", problem: `relay's short link ${alias} to ${target} cannot be used: ${problem}` });
|
|
133
|
+
try {
|
|
134
|
+
checkAncestry(path.dirname(alias), me);
|
|
135
|
+
const st = fs.lstatSync(alias, { throwIfNoEntry: false });
|
|
136
|
+
if (!st)
|
|
137
|
+
return { state: "missing" };
|
|
138
|
+
if (!st.isSymbolicLink())
|
|
139
|
+
return refused("something that is not a link is already there. Relay does not remove it; once it is gone, relay makes its link");
|
|
140
|
+
if (st.uid !== me)
|
|
141
|
+
return refused(`it is owned by uid ${st.uid}, not this user (${me}): another user may have made it first. Relay does not use or remove it; an administrator can`);
|
|
142
|
+
const to = fs.readlinkSync(alias);
|
|
143
|
+
if (to !== target) {
|
|
144
|
+
if (missingNativeTempRoot(to, me))
|
|
145
|
+
return { state: "stale", target: to, dev: st.dev, ino: st.ino };
|
|
146
|
+
return refused(`it points to ${to}. Relay only replaces an owned link to a missing private .rn directory through trusted ancestors; remove this link yourself if it is no longer needed`);
|
|
147
|
+
}
|
|
148
|
+
const t = fs.lstatSync(target, { throwIfNoEntry: false });
|
|
149
|
+
if (t) {
|
|
150
|
+
const a = fs.statSync(alias);
|
|
151
|
+
if (a.dev !== t.dev || a.ino !== t.ino)
|
|
152
|
+
return refused("it does not lead to that directory");
|
|
153
|
+
}
|
|
154
|
+
return { state: "ok" };
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
return refused(err.message);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Makes the short link to `target` (the real `~/.rn`, already checked) if missing, or atomically
|
|
162
|
+
* repoints an owned link whose former private root is gone. The staged link is inside a fresh
|
|
163
|
+
* private directory in the same parent; rename replaces only the alias entry, never its target.
|
|
164
|
+
* Other destinations, foreign owners, non-links and unsafe ancestry still refuse.
|
|
165
|
+
*/
|
|
166
|
+
export function ensureNativeTempAlias(target) {
|
|
167
|
+
const alias = nativeTempAlias();
|
|
168
|
+
let found = checkNativeTempAlias(target);
|
|
169
|
+
if (found.state === "missing") {
|
|
170
|
+
try {
|
|
171
|
+
fs.symlinkSync(target, alias);
|
|
172
|
+
}
|
|
173
|
+
catch (err) {
|
|
174
|
+
if (err.code !== "EEXIST")
|
|
175
|
+
throw new Error(`relay's short link ${alias} to ${target} cannot be made: ${err.message}`);
|
|
176
|
+
}
|
|
177
|
+
found = checkNativeTempAlias(target);
|
|
178
|
+
}
|
|
179
|
+
if (found.state === "stale") {
|
|
180
|
+
const previous = found;
|
|
181
|
+
const staging = fs.mkdtempSync(path.join(path.dirname(alias), ".rn-swap-"));
|
|
182
|
+
try {
|
|
183
|
+
fs.chmodSync(staging, 0o700);
|
|
184
|
+
const staged = path.join(staging, "link");
|
|
185
|
+
fs.symlinkSync(target, staged);
|
|
186
|
+
// Another relay may have repaired it already. Never overwrite an entry that changed since
|
|
187
|
+
// the check; the sticky parent protects our link against replacement by another uid.
|
|
188
|
+
const current = checkNativeTempAlias(target);
|
|
189
|
+
if (current.state === "stale" && current.dev === previous.dev && current.ino === previous.ino && current.target === previous.target) {
|
|
190
|
+
fs.renameSync(staged, alias);
|
|
191
|
+
}
|
|
192
|
+
else if (current.state !== "ok") {
|
|
193
|
+
throw new Error(`relay's short link ${alias} changed while relay was preparing its replacement; retry this turn`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
198
|
+
}
|
|
199
|
+
found = checkNativeTempAlias(target);
|
|
200
|
+
}
|
|
201
|
+
if (found.state === "refused")
|
|
202
|
+
throw new Error(found.problem);
|
|
203
|
+
if (found.state === "missing")
|
|
204
|
+
throw new Error(`relay's short link ${alias} to ${target} is not there after relay made it`);
|
|
205
|
+
if (found.state === "stale")
|
|
206
|
+
throw new Error(`relay's short link ${alias} still points to a missing earlier private directory after relay replaced it`);
|
|
207
|
+
return alias;
|
|
208
|
+
}
|