@jbkjr/relay 0.0.0-stage → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +201 -0
- package/LICENSES/README.md +19 -0
- package/LICENSES/codex-NOTICE.txt +6 -0
- package/README.md +393 -2
- package/SECURITY.md +145 -0
- package/adapters/briefs/claude.md +43 -0
- package/adapters/briefs/codex.md +56 -0
- package/adapters/briefs/models.json +33 -0
- package/adapters/build.mjs +8 -0
- package/adapters/claude/.claude-plugin/marketplace.json +13 -0
- package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/relay/agents/codex.md +21 -0
- package/adapters/claude/relay/agents/operator.md +21 -0
- package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
- package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
- package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
- package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
- package/adapters/claude/relay/skills/review/SKILL.md +21 -0
- package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
- package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
- package/adapters/codex/.agents/plugins/marketplace.json +20 -0
- package/adapters/codex/AGENTS.snippet.md +5 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
- package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
- package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
- package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
- package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
- package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
- package/adapters/generate.mjs +124 -0
- package/bin/relay +59 -0
- package/codex-pin.json +12 -0
- package/dist/backends/acp.js +1424 -0
- package/dist/backends/claude.js +890 -0
- package/dist/backends/cli-version.js +112 -0
- package/dist/backends/codex-app.js +1539 -0
- package/dist/backends/codex-daybreak.js +75 -0
- package/dist/backends/codex-env.js +656 -0
- package/dist/backends/codex-network.js +304 -0
- package/dist/backends/codex-pin.js +345 -0
- package/dist/backends/codex-shell-policy.js +182 -0
- package/dist/backends/codex-stage2.js +998 -0
- package/dist/backends/codex-subagents.js +47 -0
- package/dist/backends/codex.js +641 -0
- package/dist/backends/copilot.js +246 -0
- package/dist/backends/env.js +147 -0
- package/dist/backends/gemini.js +607 -0
- package/dist/backends/grok.js +337 -0
- package/dist/backends/index.js +8 -0
- package/dist/backends/native-temp.js +187 -0
- package/dist/backends/never-admission.js +90 -0
- package/dist/backends/run.js +67 -0
- package/dist/backends/stream.js +230 -0
- package/dist/backends/tool-discovery.js +15 -0
- package/dist/backends/types.js +264 -0
- package/dist/build-info.json +5 -0
- package/dist/cli.js +344 -0
- package/dist/confine/bridge.js +113 -0
- package/dist/confine/broker-core.js +76 -0
- package/dist/confine/broker-http.js +650 -0
- package/dist/confine/broker-names.js +9 -0
- package/dist/confine/broker.js +258 -0
- package/dist/confine/canary.js +380 -0
- package/dist/confine/diagnostics.js +122 -0
- package/dist/confine/gemini-tools-main.js +8 -0
- package/dist/confine/gemini-tools.js +181 -0
- package/dist/confine/hardlinks.js +58 -0
- package/dist/confine/harness-config.js +16 -0
- package/dist/confine/index.js +117 -0
- package/dist/confine/leases.js +217 -0
- package/dist/confine/paths.js +6 -0
- package/dist/confine/peer.js +115 -0
- package/dist/confine/port-policy.js +8 -0
- package/dist/confine/ports.js +365 -0
- package/dist/confine/private-root.js +208 -0
- package/dist/confine/probe-stage2.js +501 -0
- package/dist/confine/probe.js +1109 -0
- package/dist/confine/proxy.js +783 -0
- package/dist/confine/sbcheck.js +208 -0
- package/dist/confine/seatbelt-never.js +41 -0
- package/dist/confine/seatbelt-stage2.js +139 -0
- package/dist/confine/seatbelt.js +1129 -0
- package/dist/confine/sockets.js +36 -0
- package/dist/confine/turn-probe.js +19 -0
- package/dist/confine/turn.js +86 -0
- package/dist/core/adoption.js +124 -0
- package/dist/core/api-keys.js +423 -0
- package/dist/core/approvals.js +740 -0
- package/dist/core/build-identity.js +248 -0
- package/dist/core/caller.js +749 -0
- package/dist/core/calls.js +102 -0
- package/dist/core/claude-settings.js +1045 -0
- package/dist/core/config.js +453 -0
- package/dist/core/context.js +186 -0
- package/dist/core/db.js +753 -0
- package/dist/core/dispatch.js +110 -0
- package/dist/core/env-broker.js +505 -0
- package/dist/core/env-policy.js +182 -0
- package/dist/core/escalation-authority.js +76 -0
- package/dist/core/escalation-contract.js +13 -0
- package/dist/core/escalation-person-path.js +131 -0
- package/dist/core/escalation-policy.js +79 -0
- package/dist/core/escalation-runtime.js +135 -0
- package/dist/core/escalation-state.js +42 -0
- package/dist/core/escalations.js +191 -0
- package/dist/core/events.js +235 -0
- package/dist/core/executables.js +147 -0
- package/dist/core/extensions.js +645 -0
- package/dist/core/families.js +204 -0
- package/dist/core/git.js +657 -0
- package/dist/core/identity.js +113 -0
- package/dist/core/liveness.js +68 -0
- package/dist/core/mediated-network-provider.js +81 -0
- package/dist/core/never-checkpoint.js +76 -0
- package/dist/core/never-coverage.js +97 -0
- package/dist/core/never-network.js +49 -0
- package/dist/core/never-policy.js +302 -0
- package/dist/core/never-proxy-policy.js +109 -0
- package/dist/core/never-schema.js +61 -0
- package/dist/core/never-tools.js +56 -0
- package/dist/core/notices.js +48 -0
- package/dist/core/ops.js +959 -0
- package/dist/core/outcome.js +224 -0
- package/dist/core/params.js +32 -0
- package/dist/core/presence.js +174 -0
- package/dist/core/procs.js +546 -0
- package/dist/core/prompts.js +363 -0
- package/dist/core/protected-config.js +238 -0
- package/dist/core/raw-network.js +192 -0
- package/dist/core/redact.js +152 -0
- package/dist/core/refusal.js +33 -0
- package/dist/core/relay-command.js +310 -0
- package/dist/core/reported.js +3 -0
- package/dist/core/restart-overlay.js +651 -0
- package/dist/core/retention.js +1135 -0
- package/dist/core/secrets.js +329 -0
- package/dist/core/session-token.js +175 -0
- package/dist/core/session.js +744 -0
- package/dist/core/shell.js +2 -0
- package/dist/core/shipped-pin.js +47 -0
- package/dist/core/shown.js +42 -0
- package/dist/core/slots.js +67 -0
- package/dist/core/stage2-executors.js +453 -0
- package/dist/core/stage2-switch.js +5 -0
- package/dist/core/steering.js +149 -0
- package/dist/core/storage.js +358 -0
- package/dist/core/toml.js +175 -0
- package/dist/core/views.js +324 -0
- package/dist/core/wait.js +114 -0
- package/dist/core/wake.js +207 -0
- package/dist/core/watch.js +247 -0
- package/dist/core/worktree.js +213 -0
- package/dist/hosts/claude-desktop.js +274 -0
- package/dist/hosts/claude.js +249 -0
- package/dist/hosts/codex.js +345 -0
- package/dist/hosts/desktop-shared.js +20 -0
- package/dist/hosts/index.js +11 -0
- package/dist/hosts/types.js +4 -0
- package/dist/install/basics.js +18 -0
- package/dist/install/claude-init.js +133 -0
- package/dist/install/common.js +655 -0
- package/dist/install/doctor.js +635 -0
- package/dist/install/qualify-codex.js +205 -0
- package/dist/install.js +524 -0
- package/dist/mcp/elicit.js +209 -0
- package/dist/mcp/gateway.js +218 -0
- package/dist/mcp/host.js +253 -0
- package/dist/mcp/server.js +1124 -0
- package/dist/mcp/stdio.js +37 -0
- package/dist/modes/discussion.js +393 -0
- package/dist/modes/review.js +722 -0
- package/dist/native/relay-sbcheck +0 -0
- package/dist/targets/briefs.js +86 -0
- package/dist/targets/claude.js +94 -0
- package/dist/targets/codex.js +66 -0
- package/dist/targets/copilot.js +93 -0
- package/dist/targets/gemini.js +119 -0
- package/dist/targets/grok.js +126 -0
- package/dist/targets/index.js +192 -0
- package/dist/targets/types.js +18 -0
- package/dist/targets/verified.js +35 -0
- package/dist/worker.js +113 -0
- package/docs/UPGRADING.md +1518 -0
- package/docs/pinned-codex.md +333 -0
- package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
- package/experiments/stage2-redteam/lib/report.mjs +35 -0
- package/npm-shrinkwrap.json +1632 -0
- package/package.json +82 -4
- package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
- package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
- package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
- package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
- package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
- package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
- package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
- package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
- package/scripts/codex-qualify/main-module.mjs +14 -0
- package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
- package/scripts/codex-qualify/scratch-env.mjs +31 -0
- package/scripts/codex-qualify/session.mjs +96 -0
- package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
- package/test/codex-permissions.test.ts +875 -0
- package/test/fixtures/boundary-probes.mjs +17 -0
- package/test/fixtures/denial-stream-host.mjs +7 -0
- package/test/fixtures/families.json +246 -0
- package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
- package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
- package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
- package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
- package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
- package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
- package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
- package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
- package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
- package/test/fixtures/link-parent.mjs +6 -0
- package/test/fixtures/mediated-command.cjs +72 -0
- package/test/fixtures/native-skill-isolation.json +280 -0
- package/test/fixtures/pinned-codex-app-server.mjs +25 -0
- package/test/fixtures/qualified-ext-adapters.mjs +36 -0
- package/test/fixtures/refusals/README.md +52 -0
- package/test/fixtures/refusals/claude-source-result.json +7 -0
- package/test/fixtures/refusals/openai-app-capacity.json +24 -0
- package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
- package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
- package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
- package/test/fixtures/refusals/openai-review-capacity.json +24 -0
- package/test/fixtures/relay-0.2.0.sql +57 -0
- package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
- package/test/fixtures/relay-0.9.1.sql +340 -0
- package/test/fixtures/slow-boundary-probes.mjs +37 -0
- package/test/fixtures/stable-surfaces/config.json +1122 -0
- package/test/fixtures/stable-surfaces/escalation.json +128 -0
- package/test/fixtures/stable-surfaces/events.json +37 -0
- package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
- package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
- package/test/fixtures/stable-surfaces/notice.txt +1 -0
- package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
- package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
- package/test/fixtures/stable-surfaces/registry.json +49 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
- package/test/fixtures/stable-surfaces/tools.json +716 -0
- package/test/fixtures/stable-surfaces/usage.txt +46 -0
- package/test/fixtures/stage2-acp-native.mjs +138 -0
- package/test/fixtures/stage2-app-server.mjs +23 -0
- package/test/fixtures/stage2-catalog.json +91 -0
- package/test/fixtures/stage2-hostile-web.mjs +35 -0
- package/test/fixtures/stage2-native-network.mjs +62 -0
- package/test/fixtures/stage2-worker.ts +87 -0
- package/test/fixtures/status-views/expected.json +7825 -0
- package/test/fixtures/status-views/registries.json +1 -0
- package/test/fixtures/steering.json +209 -0
- package/test/helpers.ts +740 -0
- package/test/host-env.ts +7 -0
- package/test/keychain-decoy.ts +197 -0
- package/test/live-scope.ts +44 -0
- package/test/mediated-network.test.ts +192 -0
- package/test/mediated-proxy.test.ts +264 -0
- package/test/native-temp-alias.ts +10 -0
- package/test/never-policy.test.ts +629 -0
- package/test/never-tools.test.ts +136 -0
- package/test/process-home.ts +18 -0
- package/test/proxy.test.ts +531 -0
- package/test/restart-overlay-live.test.ts +85 -0
- package/test/restart-overlay-profile.test.ts +66 -0
- package/test/restart-overlay.test.ts +416 -0
- package/test/stable-surfaces.test.ts +249 -0
- package/test/stage2-escalation-live.test.ts +544 -0
- package/test/stage2-escalation-qualification.test.ts +170 -0
- package/test/stage2-escalation.test.ts +747 -0
- package/test/stage2-executor.test.ts +849 -0
- package/test/stage2-grant.test.ts +603 -0
- package/test/stage2-native-live.test.ts +647 -0
- package/test/stage2-network-decisions.test.ts +70 -0
- package/test/stage2-probe.test.ts +845 -0
- package/test/stage2-standing-live.test.ts +203 -0
- package/test/stubs/broker-host.mjs +59 -0
- package/test/stubs/broker-peer.mjs +20 -0
- package/test/stubs/confined-harness.mjs +91 -0
- package/test/stubs/ext-broken-server.mjs +2 -0
- package/test/stubs/ext-odd-server.mjs +21 -0
- package/test/stubs/ext-server.mjs +31 -0
- package/test/stubs/fake-host-cli.mjs +218 -0
- package/test/stubs/procargs.mjs +30 -0
- package/test/stubs/stub-acp +4 -0
- package/test/stubs/stub-agent.mjs +322 -0
- package/test/stubs/stub-claude +4 -0
- package/test/stubs/stub-codex +4 -0
- package/test/stubs/targets/acp.mjs +307 -0
- package/test/stubs/targets/claude.mjs +149 -0
- package/test/stubs/targets/codex.mjs +479 -0
- package/test/stubs/targets/gemini.mjs +604 -0
- package/test/temp-root.ts +11 -0
- package/test/wp4-adapters.test.ts +353 -0
- package/test/wp4-interlock.test.ts +136 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { relayHome } from "../core/config.js";
|
|
5
|
+
import { procStart, sameProcess } from "../core/procs.js";
|
|
6
|
+
// Stage 2's port leases as files (ports.ts leaseTurnPorts): what a lease file says, who holds it, and
|
|
7
|
+
// how a port changes hands. A leaf of ports.ts with light imports, so that the registry's reap
|
|
8
|
+
// (core/db.ts, through core/stage2-executors.ts) can give back an orphaned executor's leases without
|
|
9
|
+
// loading the rest of the confinement code.
|
|
10
|
+
//
|
|
11
|
+
// A port's lease is a numbered file, `<port>.<generation>`; the newest generation is the lease. A
|
|
12
|
+
// port is taken by creating the generation after the one judged free, with O_EXCL: of the relay
|
|
13
|
+
// processes that judged the same lease free, exactly one creates the next file, and one that judged
|
|
14
|
+
// an older generation creates a file that is not the newest and backs off. The newest file is never
|
|
15
|
+
// removed (a release marks it released), so a generation is never made twice. Older ones are removed
|
|
16
|
+
// by whoever finds them. (Before, a lease judged stale was removed and the port claimed under one
|
|
17
|
+
// name: a process that judged it stale, then removed it after another had already taken it back,
|
|
18
|
+
// removed that one's fresh lease, and both held the port. Review R6.)
|
|
19
|
+
export const alive = (pid) => {
|
|
20
|
+
try {
|
|
21
|
+
process.kill(pid, 0);
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
return err.code === "EPERM";
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
const norm = (start) => start.replace(/\s+/g, " ");
|
|
29
|
+
export function parseLease(text) {
|
|
30
|
+
const [first, ...rest] = text.split("\n");
|
|
31
|
+
const holders = [];
|
|
32
|
+
const records = [];
|
|
33
|
+
for (const line of rest) {
|
|
34
|
+
const r = /^record (\/.+)$/.exec(line.trim());
|
|
35
|
+
if (r) {
|
|
36
|
+
records.push(r[1]);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const m = /^(\d+) (.+)$/.exec(line.trim());
|
|
40
|
+
if (m)
|
|
41
|
+
holders.push({ pid: Number(m[1]), start: m[2] });
|
|
42
|
+
}
|
|
43
|
+
const m = /^(\d+)(?: (.+))?$/.exec(first.trim());
|
|
44
|
+
return { leaser: m ? { pid: Number(m[1]), start: m[2] ?? null } : null, holders, records };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Whether anyone still holds a lease: its leasing process is still that process, a holder (but
|
|
48
|
+
* `but`) is, or an executor record it names is still there. A released lease keeps its holder and
|
|
49
|
+
* record lines, so a record still quarantines it. Unreadable leases are held by no one.
|
|
50
|
+
*/
|
|
51
|
+
export const leaseHeld = (l, but) => Boolean(l.leaser && l.leaser.pid > 0 && (l.leaser.start ? sameProcess(l.leaser.pid, l.leaser.start) : alive(l.leaser.pid)))
|
|
52
|
+
|| l.holders.some((h) => !(but && h.pid === but.pid && h.start === but.start) && sameProcess(h.pid, h.start))
|
|
53
|
+
|| l.records.some((f) => fs.existsSync(f));
|
|
54
|
+
/** A port's lease file name: `<port>.<generation>`; `<port>` alone, from before generations, is generation 0. */
|
|
55
|
+
const NAME = /^(\d+)(?:\.(\d+))?$/;
|
|
56
|
+
export const leaseFile = (dir, port, gen) => path.join(dir, gen ? `${port}.${gen}` : String(port));
|
|
57
|
+
/** Each port's newest lease generation, and the older files beside it. */
|
|
58
|
+
function generations(dir) {
|
|
59
|
+
let names;
|
|
60
|
+
try {
|
|
61
|
+
names = fs.readdirSync(dir);
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
if (err.code === "ENOENT")
|
|
65
|
+
return new Map();
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
const out = new Map();
|
|
69
|
+
for (const name of names) {
|
|
70
|
+
const m = NAME.exec(name);
|
|
71
|
+
if (!m)
|
|
72
|
+
continue;
|
|
73
|
+
const port = Number(m[1]), gen = Number(m[2] ?? 0);
|
|
74
|
+
const cur = out.get(port);
|
|
75
|
+
if (!cur)
|
|
76
|
+
out.set(port, { gen, older: [] });
|
|
77
|
+
else if (gen > cur.gen)
|
|
78
|
+
out.set(port, { gen, older: [...cur.older, cur.gen] });
|
|
79
|
+
else
|
|
80
|
+
cur.older.push(gen);
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
function readLease(file) {
|
|
85
|
+
try {
|
|
86
|
+
return parseLease(fs.readFileSync(file, "utf8"));
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
if (err.code === "ENOENT")
|
|
90
|
+
return null;
|
|
91
|
+
throw err;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Looks at the leases of these ports, removing the older generations it finds (never the newest). */
|
|
95
|
+
export function lookLeases(dir, ports) {
|
|
96
|
+
const gens = generations(dir);
|
|
97
|
+
const held = new Set();
|
|
98
|
+
const free = new Map();
|
|
99
|
+
for (const p of ports) {
|
|
100
|
+
const g = gens.get(p);
|
|
101
|
+
if (!g) {
|
|
102
|
+
free.set(p, 0);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
for (const old of g.older)
|
|
106
|
+
fs.rmSync(leaseFile(dir, p, old), { force: true });
|
|
107
|
+
const lease = readLease(leaseFile(dir, p, g.gen));
|
|
108
|
+
// A lease that vanished under the look was an older generation by now: look again next time.
|
|
109
|
+
if (!lease)
|
|
110
|
+
held.add(p);
|
|
111
|
+
else if (leaseHeld(lease))
|
|
112
|
+
held.add(p);
|
|
113
|
+
else
|
|
114
|
+
free.set(p, g.gen);
|
|
115
|
+
}
|
|
116
|
+
return { held, free };
|
|
117
|
+
}
|
|
118
|
+
/** This process, as a lease names its leaser. */
|
|
119
|
+
function me() {
|
|
120
|
+
const start = procStart(process.pid);
|
|
121
|
+
return start ? `${process.pid} ${norm(start)}` : String(process.pid);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Takes `port`, judged free at generation `gen`: creates generation gen + 1 with O_EXCL, then checks
|
|
125
|
+
* it is the newest. Returns its file, or null when another process took the port first.
|
|
126
|
+
*/
|
|
127
|
+
export function takePort(dir, port, gen) {
|
|
128
|
+
const file = leaseFile(dir, port, gen + 1);
|
|
129
|
+
// Made whole beside it and linked into place (link fails if the name exists): no look ever reads
|
|
130
|
+
// the new generation empty, and so free.
|
|
131
|
+
const tmp = path.join(dir, `.${port}.${gen + 1}.${crypto.randomBytes(4).toString("hex")}.tmp`);
|
|
132
|
+
try {
|
|
133
|
+
fs.writeFileSync(tmp, `${me()}\n`, { flag: "wx", mode: 0o600 });
|
|
134
|
+
fs.linkSync(tmp, file);
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
if (err.code === "EEXIST")
|
|
138
|
+
return null;
|
|
139
|
+
throw err;
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
fs.rmSync(tmp, { force: true });
|
|
143
|
+
}
|
|
144
|
+
// Judged from a generation since superseded (its successor removed as older): not the lease.
|
|
145
|
+
const now = generations(dir).get(port);
|
|
146
|
+
if (now?.gen !== gen + 1) {
|
|
147
|
+
fs.rmSync(file, { force: true });
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
for (const old of now.older)
|
|
151
|
+
fs.rmSync(leaseFile(dir, port, old), { force: true });
|
|
152
|
+
return file;
|
|
153
|
+
}
|
|
154
|
+
/** Rewrites a lease file whole (a temp file beside it, renamed into place). */
|
|
155
|
+
function rewrite(file, text) {
|
|
156
|
+
const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${crypto.randomBytes(4).toString("hex")}.tmp`);
|
|
157
|
+
try {
|
|
158
|
+
fs.writeFileSync(tmp, text, { flag: "wx", mode: 0o600 });
|
|
159
|
+
fs.renameSync(tmp, file);
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
fs.rmSync(tmp, { force: true });
|
|
163
|
+
throw err;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** The lines after the leaser's: holders and records, kept by a release. */
|
|
167
|
+
const holderLines = (l) => [...l.holders.map((h) => `${h.pid} ${h.start}\n`), ...l.records.map((f) => `record ${f}\n`)].join("");
|
|
168
|
+
/**
|
|
169
|
+
* Marks a lease this process took released, if it is still this process's. The file stays, as the
|
|
170
|
+
* port's newest generation, and so do its holder and record lines: a holder still running, or a
|
|
171
|
+
* record still there, keeps the port from being leased again.
|
|
172
|
+
*/
|
|
173
|
+
export function releaseOwn(file) {
|
|
174
|
+
try {
|
|
175
|
+
const l = readLease(file);
|
|
176
|
+
if (l?.leaser?.pid === process.pid)
|
|
177
|
+
rewrite(file, `released\n${holderLines(l)}`);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
// Already gone, or unreadable: it holds nothing.
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** Names another process (pid and start time), and optionally its record, as holding a lease this process took. */
|
|
184
|
+
export function addHolder(file, pid, start, record) {
|
|
185
|
+
fs.appendFileSync(file, `${pid} ${norm(start)}\n${record && path.isAbsolute(record) && !/\n/.test(record) ? `record ${record}\n` : ""}`);
|
|
186
|
+
}
|
|
187
|
+
const leaseDir = (o) => o.dir ?? path.join(relayHome(), "ports");
|
|
188
|
+
/**
|
|
189
|
+
* Gives back the leases `holder` (an executor, by pid and start time) was named on (PortLease.hold)
|
|
190
|
+
* once nobody else holds them: for a relay process cleaning up after an executor whose own relay
|
|
191
|
+
* process died (core/stage2-executors.ts), once the holder has stopped: nothing is given back while
|
|
192
|
+
* it still runs, nor while its record is still there (remove the record first). A lease whose
|
|
193
|
+
* leasing process still runs is left for that process to release. Returns the ports given back.
|
|
194
|
+
*/
|
|
195
|
+
export function releaseLeasesOf(holder, o = {}) {
|
|
196
|
+
const dir = leaseDir(o);
|
|
197
|
+
const want = { pid: holder.pid, start: norm(holder.start) };
|
|
198
|
+
// Still running: not to be given back, whatever the caller thought.
|
|
199
|
+
if (sameProcess(want.pid, want.start, { fresh: true }))
|
|
200
|
+
return [];
|
|
201
|
+
const out = [];
|
|
202
|
+
for (const [port, g] of generations(dir)) {
|
|
203
|
+
const file = leaseFile(dir, port, g.gen);
|
|
204
|
+
const lease = readLease(file);
|
|
205
|
+
if (!lease?.leaser || !lease.holders.some((h) => h.pid === want.pid && h.start === want.start))
|
|
206
|
+
continue;
|
|
207
|
+
if (leaseHeld(lease, want))
|
|
208
|
+
continue;
|
|
209
|
+
rewrite(file, `released\n${holderLines(lease)}`);
|
|
210
|
+
out.push(port);
|
|
211
|
+
}
|
|
212
|
+
return out.sort((a, b) => a - b);
|
|
213
|
+
}
|
|
214
|
+
/** Whether a port's lease is held now (for tests and diagnostics). */
|
|
215
|
+
export function portHeld(port, o = {}) {
|
|
216
|
+
return lookLeases(leaseDir(o), [port]).held.has(port);
|
|
217
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether `child` is `parent` or lies inside it, by path alone: no filesystem call, so links are not
|
|
3
|
+
* followed (unlike `inside()` in core/config.ts). Every path the confinement code compares is
|
|
4
|
+
* resolved first (seatbelt.ts `canonical`), so lexical containment is what it means.
|
|
5
|
+
*/
|
|
6
|
+
export const within = (child, parent) => child === parent || child.startsWith(parent.endsWith("/") ? parent : `${parent}/`);
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { procStart } from "../core/procs.js";
|
|
3
|
+
import { redactor } from "../core/secrets.js";
|
|
4
|
+
function helperFailure(error, stderr, cut, reason) {
|
|
5
|
+
const failure = error;
|
|
6
|
+
const code = typeof failure.code === "number" ? String(failure.code)
|
|
7
|
+
: typeof failure.code === "string" && /^[A-Z0-9_]+$/.test(failure.code) ? failure.code : "none";
|
|
8
|
+
const signal = typeof failure.signal === "string" && /^SIG[A-Z0-9]+$/.test(failure.signal) ? failure.signal : "none";
|
|
9
|
+
const detail = reason ?? (failure.killed ? "timed out or killed" : typeof failure.code === "number" ? `exited ${code}` : "failed");
|
|
10
|
+
// Redact before truncating: cutting a token in half first could hide its shape/value.
|
|
11
|
+
const excerpt = cut(stderr).replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 256);
|
|
12
|
+
return { error: `TCP peer helper ${detail} (code=${code}, signal=${signal}, stderr=${JSON.stringify(excerpt)})` };
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The TCP client must belong to the pinned app server itself, not its process tree. Relay's
|
|
16
|
+
* accepted end is the positive control: a successful checker always sees that exact tuple.
|
|
17
|
+
* A nonzero exit, timeout or spawn failure is operational even if stdout contains both ends.
|
|
18
|
+
* Only an empty exit 1 for an already ended socket is a nonfatal drop.
|
|
19
|
+
*/
|
|
20
|
+
export const tcpPeerLookup = async (app, sock, o = {}) => {
|
|
21
|
+
if (![app.pid, sock.localPort, sock.remotePort].every((n) => Number.isSafeInteger(n) && n > 0))
|
|
22
|
+
return { error: "invalid TCP peer endpoints" };
|
|
23
|
+
const { localPort, remotePort } = sock;
|
|
24
|
+
const cut = redactor();
|
|
25
|
+
return new Promise((resolve) => {
|
|
26
|
+
try {
|
|
27
|
+
// Do not AND in -p app,relay: lsof can exit 1 when a requested PID has no matching
|
|
28
|
+
// file, even while printing relay's end. That is the normal foreign-peer case. The
|
|
29
|
+
// single socket selector must always match our own end; compare its owners below.
|
|
30
|
+
(o.exec ?? execFile)("/usr/sbin/lsof", ["-nP", `-iTCP@127.0.0.1:${remotePort}`, "-F", "pn"], {
|
|
31
|
+
env: { PATH: "/usr/bin:/bin:/usr/sbin", LC_ALL: "C" }, timeout: 2000, maxBuffer: 256 * 1024, encoding: "utf8",
|
|
32
|
+
}, (error, stdout, stderr = "") => {
|
|
33
|
+
// Do not rescue partial output: confirmation §14 obligation 2.
|
|
34
|
+
if (error !== null) {
|
|
35
|
+
const failure = error;
|
|
36
|
+
// lsof's empty exit 1 means no matching socket. A client that has already
|
|
37
|
+
// ended cannot be authenticated or dispatched, but has not broken the checker.
|
|
38
|
+
// Partial output, stderr, signals and timeouts NEVER take this exception.
|
|
39
|
+
if (failure.code === 1 && !failure.signal && !failure.killed && !stdout.trim() && !stderr.trim()
|
|
40
|
+
&& (sock.destroyed || sock.readableEnded || sock.writableEnded))
|
|
41
|
+
return resolve("foreign");
|
|
42
|
+
return resolve(helperFailure(error, stderr, cut));
|
|
43
|
+
}
|
|
44
|
+
let pid = 0;
|
|
45
|
+
let own = false, client = false;
|
|
46
|
+
const ownName = `127.0.0.1:${localPort}->127.0.0.1:${remotePort}`;
|
|
47
|
+
const clientName = `127.0.0.1:${remotePort}->127.0.0.1:${localPort}`;
|
|
48
|
+
for (const line of stdout.split("\n")) {
|
|
49
|
+
if (/^p\d+$/.test(line))
|
|
50
|
+
pid = Number(line.slice(1));
|
|
51
|
+
else if (line === `n${ownName}` && pid === process.pid)
|
|
52
|
+
own = true;
|
|
53
|
+
else if (line === `n${clientName}` && pid === app.pid)
|
|
54
|
+
client = true;
|
|
55
|
+
}
|
|
56
|
+
resolve(!own ? helperFailure(Object.assign(new Error(), { code: 0 }), stderr, cut, "did not list relay's own end") : client ? "ok" : "foreign");
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
resolve(helperFailure(error instanceof Error ? error : new Error("helper could not run"), "", cut));
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
// Darwin sys/un.h: SOL_LOCAL=0, LOCAL_PEERPID=2, LOCAL_PEERCRED=1. xucred (sys/ucred.h)
|
|
65
|
+
// begins with uint32 version, uid_t uid. These are socket credentials supplied by the kernel,
|
|
66
|
+
// never a pid/uid sent by the client. Perl only inspects fd 3; it never reads the JSON-RPC stream.
|
|
67
|
+
const PEER = String.raw `
|
|
68
|
+
open(my $s, "+<&=3") or die "inherited socket: $!";
|
|
69
|
+
my $p = getsockopt($s, 0, 2); defined($p) && length($p) == 4 or die "LOCAL_PEERPID: $!";
|
|
70
|
+
my $c = getsockopt($s, 0, 1); defined($c) && length($c) >= 8 or die "LOCAL_PEERCRED: $!";
|
|
71
|
+
unpack("I", $c) == 0 or die "unknown xucred version";
|
|
72
|
+
print unpack("i", $p), " ", unpack("I", substr($c, 4, 4)), "\n";
|
|
73
|
+
`;
|
|
74
|
+
/** Read macOS peer credentials on the accepted socket itself, with a bounded, fixed system helper. */
|
|
75
|
+
export async function socketPeer(sock) {
|
|
76
|
+
if (process.platform !== "darwin")
|
|
77
|
+
throw new Error("kernel broker peer identity is supported only on macOS");
|
|
78
|
+
const result = await new Promise((resolve, reject) => {
|
|
79
|
+
// A net.Socket in stdio duplicates its fd into the child. No private Node _handle is used.
|
|
80
|
+
// No inherited PERL5OPT, module paths, cwd modules or caller-supplied program text.
|
|
81
|
+
const child = spawn("/usr/bin/perl", ["-T", "-e", PEER], {
|
|
82
|
+
stdio: ["ignore", "pipe", "pipe", sock], env: { PATH: "/usr/bin:/bin", LC_ALL: "C" },
|
|
83
|
+
});
|
|
84
|
+
let out = "", err = "", failure;
|
|
85
|
+
const stop = (reason) => { failure ??= new Error(reason); child.kill("SIGKILL"); };
|
|
86
|
+
const onClose = () => stop("peer disconnected before its kernel identity could be read");
|
|
87
|
+
sock.once("close", onClose);
|
|
88
|
+
const timer = setTimeout(() => stop("kernel peer identity helper timed out"), 2000);
|
|
89
|
+
child.stdout.on("data", (chunk) => {
|
|
90
|
+
out += chunk.toString("utf8");
|
|
91
|
+
if (out.length > 128)
|
|
92
|
+
stop("invalid kernel peer identity output");
|
|
93
|
+
});
|
|
94
|
+
child.stderr.on("data", (chunk) => { err = (err + chunk.toString("utf8")).slice(0, 256); });
|
|
95
|
+
child.on("error", (error) => { failure = error; });
|
|
96
|
+
child.once("close", (code) => {
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
sock.off("close", onClose);
|
|
99
|
+
if (failure)
|
|
100
|
+
reject(failure);
|
|
101
|
+
else if (code !== 0)
|
|
102
|
+
reject(new Error(`kernel peer identity helper failed (${code}): ${err.trim()}`));
|
|
103
|
+
else
|
|
104
|
+
resolve(out);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
const m = /^(\d+) (\d+)\n$/.exec(result);
|
|
108
|
+
if (!m || !Number.isSafeInteger(Number(m[1])) || Number(m[1]) <= 1 || !Number.isSafeInteger(Number(m[2])))
|
|
109
|
+
throw new Error("invalid kernel peer pid/uid");
|
|
110
|
+
const pid = Number(m[1]), uid = Number(m[2]);
|
|
111
|
+
const start = procStart(pid, { fresh: true });
|
|
112
|
+
if (!start)
|
|
113
|
+
throw new Error(`could not determine start time of kernel peer pid ${pid}`);
|
|
114
|
+
return { pid, uid, start };
|
|
115
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* macOS's own services, whoever runs the Mac: ssh, screen sharing, Remote Management, Remote Apple
|
|
3
|
+
* Events, SMB and AFP file sharing, printing (decision D5, review R8). Nothing particular to one
|
|
4
|
+
* person's Mac belongs here: their own services go in never.ports, or are caught by the snapshot.
|
|
5
|
+
*/
|
|
6
|
+
export const STATIC_DENIED_TCP = [22, 5900, 3283, 3031, 445, 548, 631];
|
|
7
|
+
/** SSDP/UPnP and NAT-PMP/PCP mappings, denied to every host. */
|
|
8
|
+
export const STATIC_DENIED_UDP = [1900, 5351];
|