@zieglar/pi-chat-exchange 0.2.2 → 0.3.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/README.md +11 -7
- package/dist/bin/mcp-stdio.js +124 -56
- package/dist/control/mcp/endpoint-discovery.js +60 -0
- package/dist/control/mcp/messaging-tools.js +12 -2
- package/dist/control/mcp/server.js +10 -2
- package/dist/hooks/config.js +106 -0
- package/dist/hooks/events.js +19 -0
- package/dist/hooks/runner.js +187 -0
- package/dist/host/bound-endpoint.js +19 -6
- package/dist/host/endpoint-host.js +92 -4
- package/dist/host/mcp-binding-config.js +41 -5
- package/dist/runtime/native-readiness.js +8 -5
- package/dist/storage/creation.js +16 -0
- package/dist/storage/ownership.js +45 -1
- package/dist/tunnel/background-authorization.js +343 -0
- package/dist/tunnel/background-manager.js +104 -8
- package/dist/tunnel/background-scope.js +69 -0
- package/dist/tunnel/codes.js +1 -1
- package/dist/tunnel/hooks-management-ui.js +225 -0
- package/dist/tunnel/hooks-management.js +431 -0
- package/dist/tunnel/live-adoption-observation.js +136 -0
- package/dist/tunnel/live-adoption-probe.js +240 -0
- package/dist/tunnel/live-connection-status.js +136 -0
- package/dist/tunnel/live-mcp-composition.js +143 -0
- package/dist/tunnel/live-process-observation.js +98 -0
- package/dist/tunnel/live-session-migration.js +169 -0
- package/dist/tunnel/live-session-policy.js +578 -0
- package/dist/tunnel/manager-panel.js +4 -2
- package/dist/tunnel/manager-ui.js +71 -15
- package/dist/tunnel/multi-session-admission.js +1 -1
- package/dist/tunnel/multi-session-policy.js +45 -13
- package/dist/tunnel/setup-ui.js +2 -4
- package/dist/tunnel/status-ui.js +34 -0
- package/package.json +4 -1
- package/pi-extension/allowlist.example.json +12 -1
- package/pi-extension/desktop-target.ts +157 -0
- package/pi-extension/index.ts +1128 -132
- package/pi-extension/live-session-profile.ts +49 -0
- package/pi-extension/live-session-runtime.ts +59 -0
- package/pi-extension/multi-session-commands.ts +114 -3
- package/pi-extension/multi-session-runtime.ts +63 -11
- package/pi-extension/native-inbound.ts +235 -0
- package/pi-extension/ownership-feedback.ts +100 -0
- package/pi-extension/session-onboarding.ts +154 -0
- package/pi-extension/session-recovery.ts +214 -0
- package/skills/ce-hook-script/SKILL.md +62 -0
- package/skills/ce-hook-script/examples/file-notification.py +79 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/** Same-user local challenge: instantaneous observation, never a send reservation. */
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { isDeepStrictEqual as equal } from "node:util";
|
|
8
|
+
import { readLivePolicy } from "./live-session-policy.js";
|
|
9
|
+
const unknown = () => ({ kind: "UNVERIFIED" });
|
|
10
|
+
const hex = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
|
|
11
|
+
const integer = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
|
|
12
|
+
const text = (v) => typeof v === "string" && v.length > 0 && v.length <= 4096;
|
|
13
|
+
function row(v, keys) {
|
|
14
|
+
if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).length !== keys.length || Object.keys(v).some(k => !keys.includes(k)))
|
|
15
|
+
throw Error("invalid probe");
|
|
16
|
+
return v;
|
|
17
|
+
}
|
|
18
|
+
function checkDirectory(path, privateDirectory = false) {
|
|
19
|
+
if (fs.realpathSync(path) !== path)
|
|
20
|
+
throw Error("noncanonical probe directory");
|
|
21
|
+
const s = fs.lstatSync(path);
|
|
22
|
+
const uid = process.geteuid?.();
|
|
23
|
+
const sticky = s.uid === 0 && (s.mode & 0o1000) !== 0;
|
|
24
|
+
if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== 0 && s.uid !== uid || !sticky && (s.mode & 0o022) !== 0 || privateDirectory && (s.uid !== uid || (s.mode & 0o7777) !== 0o700))
|
|
25
|
+
throw Error("unsafe probe directory");
|
|
26
|
+
if (process.platform === "darwin") {
|
|
27
|
+
const output = execFileSync("/bin/ls", ["-lde", path], { encoding: "utf8", timeout: 5000, maxBuffer: 16384, env: { PATH: "/usr/bin:/bin", LC_ALL: "C" }, stdio: ["ignore", "pipe", "pipe"] });
|
|
28
|
+
const [header = "", ...entries] = output.trimEnd().split("\n");
|
|
29
|
+
if (!/^[bcdlps-][rwxStTs-]{9}[+@ ]/.test(header) || entries.some(entry => !/^\s*\d+: \S+ deny [a-z_,]+$/.test(entry)) || header[10] === "+" && !entries.length)
|
|
30
|
+
throw Error("unsafe probe ACL");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function pathFor(o, create = false) {
|
|
34
|
+
if (!hex(o.launchDigest) || !integer(o.identity.pid) || o.identity.pid < 1 || !text(o.identity.startedKey))
|
|
35
|
+
throw Error("invalid probe identity");
|
|
36
|
+
readLivePolicy(o.ref); // Canonical private directory and ancestor ACL checks.
|
|
37
|
+
// macOS per-user temporary roots exceed Unix socket limits. Use one short,
|
|
38
|
+
// canonical system temporary root, then require an owner-only per-UID directory.
|
|
39
|
+
const temporaryRoot = fs.realpathSync("/tmp");
|
|
40
|
+
for (let p = temporaryRoot;; p = dirname(p)) {
|
|
41
|
+
checkDirectory(p);
|
|
42
|
+
if (dirname(p) === p)
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
const directory = join(temporaryRoot, `ce-probe-${process.geteuid()}`);
|
|
46
|
+
if (create) {
|
|
47
|
+
try {
|
|
48
|
+
fs.mkdirSync(directory, { mode: 0o700 });
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error.code !== "EEXIST")
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
checkDirectory(directory, true);
|
|
56
|
+
const name = createHash("sha256").update(JSON.stringify([o.ref.root, o.ref.policyId, o.ref.genesisDigest, o.identity.pid, o.identity.startedKey, o.launchDigest])).digest("hex").slice(0, 40);
|
|
57
|
+
const path = join(directory, `${name}.sock`);
|
|
58
|
+
if (Buffer.byteLength(path) > 103)
|
|
59
|
+
throw Error("probe path too long");
|
|
60
|
+
return path;
|
|
61
|
+
}
|
|
62
|
+
const targets = (s) => s.manifest.registrations.filter(r => r.status === "active").map(({ endpointId, epoch, payloadReadGeneration, ackGeneration }) => ({ endpointId, epoch, payloadReadGeneration, ackGeneration }));
|
|
63
|
+
function socketStat(path) {
|
|
64
|
+
const s = fs.lstatSync(path);
|
|
65
|
+
if (!s.isSocket() || s.isSymbolicLink() || s.uid !== process.geteuid?.() || (s.mode & 0o7777) !== 0o600)
|
|
66
|
+
throw Error("unsafe probe socket");
|
|
67
|
+
return s;
|
|
68
|
+
}
|
|
69
|
+
const same = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
|
70
|
+
export async function startLiveAdoptionProbe(o) {
|
|
71
|
+
const path = pathFor(o, true);
|
|
72
|
+
try {
|
|
73
|
+
fs.lstatSync(path);
|
|
74
|
+
throw Error("probe exists");
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
if (e.code !== "ENOENT")
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
const clients = new Set();
|
|
81
|
+
const server = net.createServer(socket => {
|
|
82
|
+
if (clients.size >= 4) {
|
|
83
|
+
socket.destroy();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
clients.add(socket);
|
|
87
|
+
const deadline = setTimeout(() => socket.destroy(), 500);
|
|
88
|
+
socket.on("error", () => socket.destroy());
|
|
89
|
+
socket.on("close", () => { clearTimeout(deadline); clients.delete(socket); });
|
|
90
|
+
let bytes = Buffer.alloc(0);
|
|
91
|
+
let handled = false;
|
|
92
|
+
socket.on("data", chunk => {
|
|
93
|
+
if (handled) {
|
|
94
|
+
socket.destroy();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
bytes = Buffer.concat([bytes, chunk]);
|
|
98
|
+
if (bytes.length > 256) {
|
|
99
|
+
socket.destroy();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (!bytes.includes(10))
|
|
103
|
+
return;
|
|
104
|
+
handled = true;
|
|
105
|
+
try {
|
|
106
|
+
const request = row(JSON.parse(bytes.toString("utf8")), ["kind", "nonce"]);
|
|
107
|
+
if (request.kind !== "ce-live-probe-v1" || !hex(request.nonce))
|
|
108
|
+
throw Error("invalid challenge");
|
|
109
|
+
const { snapshot, owner, bound } = o.observe();
|
|
110
|
+
if (!equal(snapshot.ref, o.ref))
|
|
111
|
+
throw Error("foreign policy");
|
|
112
|
+
const response = { nonce: request.nonce, launchDigest: o.launchDigest, identity: o.identity, ref: o.ref, policy: { sequence: snapshot.sequence, digest: snapshot.digest, targets: targets(snapshot) },
|
|
113
|
+
owner: { endpointId: owner.endpointId, registered: owner.registered, participantId: owner.participantId ?? null, sessionId: owner.sessionId ?? null, exchangeId: owner.exchangeId ?? null, fencingToken: owner.fencingToken ?? null, lease: owner.lease, leaseExpiresAt: owner.leaseExpiresAt ?? null }, bound, observedAt: new Date().toISOString() };
|
|
114
|
+
const output = Buffer.from(`${JSON.stringify(response)}\n`);
|
|
115
|
+
if (output.length > 65536)
|
|
116
|
+
throw Error("oversized probe");
|
|
117
|
+
socket.end(output);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
socket.destroy();
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(path, () => { server.removeListener("error", reject); resolve(); }); });
|
|
125
|
+
fs.chmodSync(path, 0o600);
|
|
126
|
+
const owned = socketStat(path);
|
|
127
|
+
// Node unlinks a Unix socket path on close. Move only our inode away first,
|
|
128
|
+
// so Node's automatic cleanup cannot remove a substituted path.
|
|
129
|
+
let closed;
|
|
130
|
+
return { close() {
|
|
131
|
+
if (closed)
|
|
132
|
+
return closed;
|
|
133
|
+
for (const socket of clients)
|
|
134
|
+
socket.destroy();
|
|
135
|
+
let moved;
|
|
136
|
+
let substitute;
|
|
137
|
+
try {
|
|
138
|
+
const current = fs.lstatSync(path);
|
|
139
|
+
if (same(current, owned)) {
|
|
140
|
+
moved = `${path}.closing`;
|
|
141
|
+
fs.renameSync(path, moved);
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
substitute = `${path}.preserved-${randomBytes(8).toString("hex")}`;
|
|
145
|
+
fs.renameSync(path, substitute);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
catch { /* Missing socket is already unavailable. */ }
|
|
149
|
+
closed = new Promise(resolve => server.close(() => {
|
|
150
|
+
if (moved) {
|
|
151
|
+
try {
|
|
152
|
+
if (same(fs.lstatSync(moved), owned))
|
|
153
|
+
fs.unlinkSync(moved);
|
|
154
|
+
}
|
|
155
|
+
catch { }
|
|
156
|
+
}
|
|
157
|
+
if (substitute) {
|
|
158
|
+
try {
|
|
159
|
+
fs.linkSync(substitute, path);
|
|
160
|
+
fs.unlinkSync(substitute);
|
|
161
|
+
}
|
|
162
|
+
catch { }
|
|
163
|
+
}
|
|
164
|
+
resolve();
|
|
165
|
+
}));
|
|
166
|
+
return closed;
|
|
167
|
+
} };
|
|
168
|
+
}
|
|
169
|
+
export async function queryLiveAdoptionProbe(o) {
|
|
170
|
+
let path;
|
|
171
|
+
let before;
|
|
172
|
+
try {
|
|
173
|
+
path = pathFor(o);
|
|
174
|
+
before = socketStat(path);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return unknown();
|
|
178
|
+
}
|
|
179
|
+
const nonce = randomBytes(32).toString("hex");
|
|
180
|
+
return new Promise(resolve => {
|
|
181
|
+
const socket = net.connect(path);
|
|
182
|
+
let bytes = Buffer.alloc(0);
|
|
183
|
+
let done = false;
|
|
184
|
+
const finish = (result) => { if (done)
|
|
185
|
+
return; done = true; socket.destroy(); resolve(result); };
|
|
186
|
+
const deadline = setTimeout(() => finish(unknown()), 500);
|
|
187
|
+
socket.on("error", () => finish(unknown()));
|
|
188
|
+
socket.on("close", () => { clearTimeout(deadline); finish(unknown()); });
|
|
189
|
+
socket.on("connect", () => { try {
|
|
190
|
+
if (!same(before, socketStat(path)))
|
|
191
|
+
return finish(unknown());
|
|
192
|
+
socket.write(`${JSON.stringify({ kind: "ce-live-probe-v1", nonce })}\n`);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
finish(unknown());
|
|
196
|
+
} });
|
|
197
|
+
socket.on("data", chunk => {
|
|
198
|
+
bytes = Buffer.concat([bytes, chunk]);
|
|
199
|
+
if (bytes.length > 65536)
|
|
200
|
+
return finish(unknown());
|
|
201
|
+
if (!bytes.includes(10))
|
|
202
|
+
return;
|
|
203
|
+
try {
|
|
204
|
+
const r = row(JSON.parse(bytes.toString("utf8")), ["nonce", "launchDigest", "identity", "ref", "policy", "owner", "bound", "observedAt"]);
|
|
205
|
+
const id = row(r.identity, ["pid", "startedKey"]);
|
|
206
|
+
const ref = row(r.ref, ["kind", "root", "policyId", "genesisDigest", ...(o.ref.kind === "ce-live-session-v2" ? ["profilePath", "upgradeSequence"] : [])]);
|
|
207
|
+
const p = row(r.policy, ["sequence", "digest", "targets"]);
|
|
208
|
+
const owner = row(r.owner, ["endpointId", "registered", "participantId", "sessionId", "exchangeId", "fencingToken", "lease", "leaseExpiresAt"]);
|
|
209
|
+
const bound = row(r.bound, ["state", "renewal"]);
|
|
210
|
+
const now = Date.parse(o.now?.() ?? new Date().toISOString());
|
|
211
|
+
const observed = typeof r.observedAt === "string" ? Date.parse(r.observedAt) : NaN;
|
|
212
|
+
if (r.nonce !== nonce || r.launchDigest !== o.launchDigest || !equal(id, o.identity) || !equal(ref, o.ref) || !equal(o.current.ref, o.ref) || !integer(p.sequence) || !hex(p.digest) || p.sequence > o.current.sequence || p.sequence === o.current.sequence && p.digest !== o.current.digest || !Number.isFinite(now) || !Number.isFinite(observed) || observed > now || now - observed > 5000 || !Array.isArray(p.targets) || p.targets.length > 128)
|
|
213
|
+
return finish(unknown());
|
|
214
|
+
const labels = new Set();
|
|
215
|
+
for (const item of p.targets) {
|
|
216
|
+
const t = row(item, ["endpointId", "epoch", "payloadReadGeneration", "ackGeneration"]);
|
|
217
|
+
if (!text(t.endpointId) || labels.has(t.endpointId) || !integer(t.epoch) || !integer(t.payloadReadGeneration) || !integer(t.ackGeneration) || t.payloadReadGeneration > p.sequence || t.ackGeneration > p.sequence)
|
|
218
|
+
return finish(unknown());
|
|
219
|
+
labels.add(t.endpointId);
|
|
220
|
+
}
|
|
221
|
+
const target = p.targets.find(t => t.endpointId === o.targetEndpointId);
|
|
222
|
+
const current = targets(o.current).find(t => t.endpointId === o.targetEndpointId);
|
|
223
|
+
if (!target || !current || !equal(target, current) || !["ACTIVE", "WRITE_BLOCKED", "CLOSING", "CLOSED"].includes(String(bound.state)) || !["RUNNING", "STOPPED"].includes(String(bound.renewal)))
|
|
224
|
+
return finish(unknown());
|
|
225
|
+
if (bound.state !== "ACTIVE" || bound.renewal !== "RUNNING")
|
|
226
|
+
return finish({ kind: "BLOCKED" });
|
|
227
|
+
for (const key of ["endpointId", "participantId", "sessionId", "exchangeId", "fencingToken"])
|
|
228
|
+
if (owner[key] !== o.owner[key])
|
|
229
|
+
return finish(unknown());
|
|
230
|
+
if (owner.registered !== true || !o.owner.registered || owner.lease !== "ACTIVE" || o.owner.lease !== "ACTIVE" || typeof owner.leaseExpiresAt !== "string" || !o.owner.leaseExpiresAt || !Number.isFinite(Date.parse(owner.leaseExpiresAt)) || !Number.isFinite(Date.parse(o.owner.leaseExpiresAt)) || Date.parse(owner.leaseExpiresAt) <= now || Date.parse(o.owner.leaseExpiresAt) <= now)
|
|
231
|
+
return finish({ kind: "BLOCKED" });
|
|
232
|
+
finish({ kind: "OBSERVED" });
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
finish(unknown());
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
//# sourceMappingURL=live-adoption-probe.js.map
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/** Read-only composition of transport, exact child, policy and Owner evidence.
|
|
2
|
+
* No Store is opened here; the caller supplies a coherent current Owner view
|
|
3
|
+
* of the fixed MCP endpoint/Store/Exchange, never another Host or acquisition.
|
|
4
|
+
*
|
|
5
|
+
* R1: every awaited step can race a revocation, an Owner release or a child
|
|
6
|
+
* exit. The composition therefore re-validates the selected Profile, the
|
|
7
|
+
* immutable binding, the current policy generation, the coherent Owner and the
|
|
8
|
+
* exact child process tree AFTER each fresh nonce challenge, and it answers
|
|
9
|
+
* with the state observed at that instant only. It is never a promise of
|
|
10
|
+
* immediate future availability, and no stale fact is reused as readiness.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { isDeepStrictEqual } from "node:util";
|
|
14
|
+
import { parseTunnelProfile } from "./background-manager.js";
|
|
15
|
+
import { parseTunnelMcpCommand } from "./profile.js";
|
|
16
|
+
import { readMessagingGeneration, readPrivateMessagingFile } from "./messaging-config.js";
|
|
17
|
+
import { readLivePolicy } from "./live-session-policy.js";
|
|
18
|
+
import { queryLiveAdoptionProbe } from "./live-adoption-probe.js";
|
|
19
|
+
import { verifyManagedMcpChild } from "./live-process-observation.js";
|
|
20
|
+
const sameOwner = (a, b) => a.endpointId === b.endpointId && a.registered === b.registered && a.participantId === b.participantId &&
|
|
21
|
+
a.sessionId === b.sessionId && a.exchangeId === b.exchangeId && a.fencingToken === b.fencingToken &&
|
|
22
|
+
a.lease === b.lease && a.leaseExpiresAt !== undefined && b.leaseExpiresAt !== undefined &&
|
|
23
|
+
Number.isFinite(Date.parse(a.leaseExpiresAt)) && Number.isFinite(Date.parse(b.leaseExpiresAt)) &&
|
|
24
|
+
Date.parse(b.leaseExpiresAt) >= Date.parse(a.leaseExpiresAt);
|
|
25
|
+
const registrationOf = (snapshot, endpointId) => snapshot.manifest.registrations.find((r) => r.endpointId === endpointId);
|
|
26
|
+
export async function observeLiveConnection(options) {
|
|
27
|
+
let transport = "UNAVAILABLE";
|
|
28
|
+
try {
|
|
29
|
+
const observeRun = async () => {
|
|
30
|
+
const observed = await options.manager.observeLiveTransport();
|
|
31
|
+
transport = observed.kind === "CONNECTED" ? "CONNECTED" : "UNAVAILABLE";
|
|
32
|
+
return observed.kind === "CONNECTED" ? observed : undefined;
|
|
33
|
+
};
|
|
34
|
+
const run = await observeRun();
|
|
35
|
+
if (!run)
|
|
36
|
+
return { policy: "UNVERIFIED", transport };
|
|
37
|
+
const profile = readPrivateMessagingFile(options.profilePath);
|
|
38
|
+
if (!profile)
|
|
39
|
+
return { policy: "UNVERIFIED", transport };
|
|
40
|
+
const facts = parseTunnelProfile(profile.bytes.toString("utf8"));
|
|
41
|
+
if (!facts.mcpCommand)
|
|
42
|
+
return { policy: "UNVERIFIED", transport };
|
|
43
|
+
const command = parseTunnelMcpCommand(facts.mcpCommand);
|
|
44
|
+
const pair = readMessagingGeneration(options.profilePath, command.bindingPath, facts.keyFile);
|
|
45
|
+
if (!pair || (pair.config.admissionPolicy?.kind !== "ce-live-session-v1" && pair.config.admissionPolicy?.kind !== "ce-live-session-v2"))
|
|
46
|
+
return { policy: "UNVERIFIED", transport };
|
|
47
|
+
const ref = pair.config.admissionPolicy;
|
|
48
|
+
if (ref.kind === "ce-live-session-v2" && ref.profilePath !== options.profilePath)
|
|
49
|
+
return { policy: "UNVERIFIED", transport };
|
|
50
|
+
if (!isDeepStrictEqual(pair.document, { kind: ref.kind === "ce-live-session-v2" ? "ce-live-launch-v2" : "ce-live-launch-v1", version: 1, ref }))
|
|
51
|
+
return { policy: "UNVERIFIED", transport };
|
|
52
|
+
const watermark = options.watermark ?? {};
|
|
53
|
+
const current = readLivePolicy(ref, { credentialFile: facts.keyFile, watermark });
|
|
54
|
+
const m = current.manifest;
|
|
55
|
+
const c = pair.config;
|
|
56
|
+
if (m.identity.tunnelId !== facts.tunnelId || m.identity.organizationId !== (facts.organizationId ?? null) ||
|
|
57
|
+
!isDeepStrictEqual(m.store, c.store) || !isDeepStrictEqual(m.exchange, c.exchange) || !isDeepStrictEqual(m.chatgptEndpoint, c.endpoint) ||
|
|
58
|
+
m.mcp.payloadRead !== c.payloadRead.enabled || m.mcp.ack !== c.ack.enabled)
|
|
59
|
+
return { policy: "UNVERIFIED", transport };
|
|
60
|
+
const target = registrationOf(current, options.targetEndpointId);
|
|
61
|
+
if (!target)
|
|
62
|
+
return { policy: "UNVERIFIED", transport };
|
|
63
|
+
const child = await verifyManagedMcpChild({ run, ...command, recheckRun: observeRun, ...(options.inspect ? { inspect: options.inspect } : {}) });
|
|
64
|
+
if (!child)
|
|
65
|
+
return { policy: "UNVERIFIED", transport };
|
|
66
|
+
const binding = readPrivateMessagingFile(command.bindingPath, facts.keyFile);
|
|
67
|
+
const selected = readPrivateMessagingFile(options.profilePath, facts.keyFile);
|
|
68
|
+
if (!binding || !selected?.bytes.equals(profile.bytes))
|
|
69
|
+
return { policy: "UNVERIFIED", transport };
|
|
70
|
+
const launchDigest = createHash("sha256").update(binding.bytes).digest("hex");
|
|
71
|
+
const owner = options.readOwner(c);
|
|
72
|
+
if (!owner || owner.endpointId !== c.endpoint.endpointId)
|
|
73
|
+
return { policy: "UNVERIFIED", transport };
|
|
74
|
+
const challenge = async (snapshot, currentOwner) => await queryLiveAdoptionProbe({
|
|
75
|
+
ref, current: snapshot, identity: { pid: child.pid, startedKey: child.startedKey },
|
|
76
|
+
// Digest is over the exact immutable binding bytes, matching the launch
|
|
77
|
+
// identity. The recorder must use the same bytes, not reserialized config.
|
|
78
|
+
launchDigest, targetEndpointId: options.targetEndpointId, owner: currentOwner,
|
|
79
|
+
...(options.now ? { now: options.now } : {})
|
|
80
|
+
});
|
|
81
|
+
/** Re-prove every fact after an awaited challenge. Any change is unknown. */
|
|
82
|
+
const revalidate = async () => {
|
|
83
|
+
const profile2 = readPrivateMessagingFile(options.profilePath, facts.keyFile);
|
|
84
|
+
const binding2 = readPrivateMessagingFile(command.bindingPath, facts.keyFile);
|
|
85
|
+
if (!profile2?.bytes.equals(profile.bytes) || !binding2?.bytes.equals(binding.bytes))
|
|
86
|
+
return undefined;
|
|
87
|
+
let snapshot;
|
|
88
|
+
try {
|
|
89
|
+
snapshot = readLivePolicy(ref, { credentialFile: facts.keyFile, watermark });
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
const target2 = registrationOf(snapshot, options.targetEndpointId);
|
|
95
|
+
if (!target2 || !isDeepStrictEqual(target2, target))
|
|
96
|
+
return undefined;
|
|
97
|
+
const owner2 = options.readOwner(c);
|
|
98
|
+
if (!owner2 || owner2.endpointId !== c.endpoint.endpointId)
|
|
99
|
+
return undefined;
|
|
100
|
+
if (!sameOwner(owner, owner2))
|
|
101
|
+
return undefined;
|
|
102
|
+
const child2 = await verifyManagedMcpChild({ run, ...command, recheckRun: observeRun, ...(options.inspect ? { inspect: options.inspect } : {}) });
|
|
103
|
+
if (!child2 || !sameChild(child, child2))
|
|
104
|
+
return undefined;
|
|
105
|
+
const latest = await observeRun();
|
|
106
|
+
if (!latest || latest.runId !== run.runId || latest.managedPid !== run.managedPid)
|
|
107
|
+
return undefined;
|
|
108
|
+
return { snapshot, owner: owner2 };
|
|
109
|
+
};
|
|
110
|
+
const first = await challenge(current, owner);
|
|
111
|
+
const afterFirst = await revalidate();
|
|
112
|
+
if (!afterFirst)
|
|
113
|
+
return { policy: "UNVERIFIED", transport };
|
|
114
|
+
const second = await challenge(afterFirst.snapshot, afterFirst.owner);
|
|
115
|
+
const afterSecond = await revalidate();
|
|
116
|
+
if (!afterSecond)
|
|
117
|
+
return { policy: "UNVERIFIED", transport };
|
|
118
|
+
if (second.kind === "UNVERIFIED" || first.kind === "UNVERIFIED")
|
|
119
|
+
return { policy: "UNVERIFIED", transport };
|
|
120
|
+
if (second.kind === "BLOCKED" || first.kind === "BLOCKED")
|
|
121
|
+
return { policy: "BLOCKED", transport };
|
|
122
|
+
const now = options.now?.() ?? new Date().toISOString();
|
|
123
|
+
const lease = afterSecond.owner.lease;
|
|
124
|
+
if (lease !== "ACTIVE" || !afterSecond.owner.leaseExpiresAt || Date.parse(afterSecond.owner.leaseExpiresAt) <= Date.parse(now)) {
|
|
125
|
+
return { policy: "BLOCKED", transport };
|
|
126
|
+
}
|
|
127
|
+
return { policy: "OBSERVED", transport };
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return { policy: "UNVERIFIED", transport };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function sameChild(a, b) {
|
|
134
|
+
return a.pid === b.pid && a.startedKey === b.startedKey && a.command === b.command && a.runId === b.runId;
|
|
135
|
+
}
|
|
136
|
+
//# sourceMappingURL=live-connection-status.js.map
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import { basename } from "node:path";
|
|
4
|
+
import { readMessagingGeneration, readPrivateMessagingFile } from "./messaging-config.js";
|
|
5
|
+
import { parseTunnelProfile } from "./background-manager.js";
|
|
6
|
+
import { parseTunnelMcpCommand } from "./profile.js";
|
|
7
|
+
import { CeHostRefusal } from "../host/endpoint-host.js";
|
|
8
|
+
import { readLivePolicy } from "./live-session-policy.js";
|
|
9
|
+
import { readOwnershipObservation } from "../storage/ownership.js";
|
|
10
|
+
const denied = () => { throw new CeHostRefusal("CE_HOST_AUTHORITY_ABSENT", false, "ADMISSION_POLICY_DENIED"); };
|
|
11
|
+
/** Launch bytes fix Store/Exchange/ChatGPT and the global ceilings. Every
|
|
12
|
+
* operation consumes one typed snapshot, prepared by the Host/bound port. */
|
|
13
|
+
export function createLiveMcpComposition(config, reader, options = {}) {
|
|
14
|
+
if (config.admissionPolicy?.kind !== "ce-live-session-v1" && config.admissionPolicy?.kind !== "ce-live-session-v2")
|
|
15
|
+
return denied();
|
|
16
|
+
const ref = config.admissionPolicy;
|
|
17
|
+
const watermark = {};
|
|
18
|
+
const read = reader ?? (selected => readLivePolicy(selected, { watermark }));
|
|
19
|
+
const snapshot = () => {
|
|
20
|
+
let current;
|
|
21
|
+
try {
|
|
22
|
+
current = read(ref);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return denied();
|
|
26
|
+
}
|
|
27
|
+
const m = current.manifest;
|
|
28
|
+
if (!isDeepStrictEqual(m.store, config.store) || !isDeepStrictEqual(m.exchange, config.exchange) ||
|
|
29
|
+
!isDeepStrictEqual(m.chatgptEndpoint, config.endpoint) || !isDeepStrictEqual(current.ref, ref) ||
|
|
30
|
+
m.mcp.payloadRead !== config.payloadRead.enabled || m.mcp.ack !== config.ack.enabled ||
|
|
31
|
+
config.managed !== undefined && (config.managed.tunnelId !== m.identity.tunnelId || (config.managed.organizationId ?? null) !== m.identity.organizationId))
|
|
32
|
+
return denied();
|
|
33
|
+
return current;
|
|
34
|
+
};
|
|
35
|
+
const loaded = snapshot();
|
|
36
|
+
// The actual immutable launch pair and current Profile selection must agree.
|
|
37
|
+
// Selection failures deny only Hooks; business messaging keeps its own gate.
|
|
38
|
+
const selectedBindingGeneration = () => {
|
|
39
|
+
if (ref.kind !== "ce-live-session-v2" || options.bindingPath === undefined)
|
|
40
|
+
return undefined;
|
|
41
|
+
try {
|
|
42
|
+
const profile = readPrivateMessagingFile(ref.profilePath);
|
|
43
|
+
if (profile === undefined)
|
|
44
|
+
return undefined;
|
|
45
|
+
const facts = parseTunnelProfile(profile.bytes.toString("utf8"));
|
|
46
|
+
if (facts.mcpCommand === undefined || facts.tunnelId !== loaded.manifest.identity.tunnelId ||
|
|
47
|
+
(facts.organizationId ?? null) !== loaded.manifest.identity.organizationId)
|
|
48
|
+
return undefined;
|
|
49
|
+
readPrivateMessagingFile(ref.profilePath, facts.keyFile);
|
|
50
|
+
const selectedPath = parseTunnelMcpCommand(facts.mcpCommand).bindingPath;
|
|
51
|
+
if (selectedPath !== options.bindingPath)
|
|
52
|
+
return undefined;
|
|
53
|
+
const pair = readMessagingGeneration(ref.profilePath, options.bindingPath, facts.keyFile);
|
|
54
|
+
if (pair === undefined || !isDeepStrictEqual(pair.config, config) ||
|
|
55
|
+
!isDeepStrictEqual(pair.document, { kind: "ce-live-launch-v2", version: 1, ref }))
|
|
56
|
+
return undefined;
|
|
57
|
+
return /^messaging-([a-f0-9]{64})\.yaml$/.exec(basename(pair.bindingPath))?.[1];
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const loadedBindingGeneration = selectedBindingGeneration();
|
|
64
|
+
const consent = loaded.manifest.mcpHookConsent;
|
|
65
|
+
const enabledRules = (config.hooks ?? []).filter(rule => rule.enabled);
|
|
66
|
+
const capturedHookGeneration = ref.kind === "ce-live-session-v2" && loadedBindingGeneration !== undefined &&
|
|
67
|
+
consent?.bindingGeneration === loadedBindingGeneration && consent.targets.length === enabledRules.length &&
|
|
68
|
+
enabledRules.every(rule => consent.targets.some(target => target.ruleId === rule.id && target.endpointId === rule.recipient.endpointId && rule.recipient.adapter === "pi"))
|
|
69
|
+
? consent.generation : undefined;
|
|
70
|
+
const recipients = Object.freeze({ snapshot: () => {
|
|
71
|
+
const current = snapshot();
|
|
72
|
+
const active = current.manifest.registrations.filter(r => r.status === "active");
|
|
73
|
+
return Object.freeze({ recipients: Object.freeze(active.map(r => Object.freeze({ adapter: "pi", endpointId: r.endpointId }))),
|
|
74
|
+
viewDigest: current.digest, presence: Object.freeze(active.map(r => Object.freeze({ endpointId: r.endpointId, disclose: r.presenceDisclosure }))) });
|
|
75
|
+
} });
|
|
76
|
+
const admission = (operation, prepared) => {
|
|
77
|
+
// A caller without a prepared Host snapshot cannot silently reread a policy
|
|
78
|
+
// and authorize a different operation. Begin/renew also use this boundary.
|
|
79
|
+
if (prepared === undefined)
|
|
80
|
+
return denied();
|
|
81
|
+
// No surviving registration means no addressable recipient: every business
|
|
82
|
+
// operation fails closed. Cleanup never passes through this boundary.
|
|
83
|
+
if (prepared.recipients.length === 0)
|
|
84
|
+
return denied();
|
|
85
|
+
if (operation.kind === "send" && !prepared.recipients.some(r => r.endpointId === operation.to))
|
|
86
|
+
return denied();
|
|
87
|
+
if (operation.kind === "readPayload" && !config.payloadRead.enabled || operation.kind === "ack" && !config.ack.enabled)
|
|
88
|
+
return denied();
|
|
89
|
+
};
|
|
90
|
+
const hookAllowed = (rule) => {
|
|
91
|
+
const selectedGeneration = ref.kind === "ce-live-session-v2" ? selectedBindingGeneration() : undefined;
|
|
92
|
+
// This final synchronous policy read is the actual-start admission point.
|
|
93
|
+
const current = snapshot();
|
|
94
|
+
const original = loaded.manifest.registrations.find(r => r.endpointId === rule.recipient.endpointId);
|
|
95
|
+
if (ref.kind === "ce-live-session-v2") {
|
|
96
|
+
const approved = current.manifest.mcpHookConsent;
|
|
97
|
+
if (capturedHookGeneration === undefined || approved?.generation !== capturedHookGeneration ||
|
|
98
|
+
selectedGeneration !== loadedBindingGeneration || approved.bindingGeneration !== loadedBindingGeneration)
|
|
99
|
+
return false;
|
|
100
|
+
const target = approved.targets.find(target => target.ruleId === rule.id);
|
|
101
|
+
if (target === undefined || target.endpointId !== rule.recipient.endpointId || target.endpointId !== original?.endpointId ||
|
|
102
|
+
target.runtimeSessionId !== original.runtimeSessionId || target.epoch !== original.epoch)
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
return original !== undefined && original.status === "active" && current.manifest.registrations.some(r => r.endpointId === original.endpointId && r.runtimeSessionId === original.runtimeSessionId && r.status === "active" && r.epoch === original.epoch) &&
|
|
106
|
+
(config.hooks ?? []).some(candidate => candidate.enabled && isDeepStrictEqual(candidate, rule));
|
|
107
|
+
};
|
|
108
|
+
return Object.freeze({ ref, loaded, snapshot, recipients, admission, hookAllowed });
|
|
109
|
+
}
|
|
110
|
+
/** Synchronous observation only; never renews or changes bound admission. */
|
|
111
|
+
export function observeLiveMcpRuntime(live, host, bound, store, endpointId) {
|
|
112
|
+
const snapshot = live.snapshot();
|
|
113
|
+
const mapping = host.status(endpointId);
|
|
114
|
+
let owner = { ...mapping, lease: "ABSENT", leaseExpiresAt: undefined };
|
|
115
|
+
if (mapping.participantId !== undefined) {
|
|
116
|
+
const observed = readOwnershipObservation(store, mapping.participantId);
|
|
117
|
+
if (observed.ownership !== undefined && observed.ownership.sessionId === mapping.sessionId &&
|
|
118
|
+
observed.ownership.fencingToken === mapping.fencingToken) {
|
|
119
|
+
owner = { ...mapping, lease: observed.lease, leaseExpiresAt: observed.ownership.expiresAt };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return { snapshot, owner, bound: bound.operationalStatus() };
|
|
123
|
+
}
|
|
124
|
+
/** Only the visible projection is hashed. Internal sequence, IDs and policy
|
|
125
|
+
* digests never cross this adapter; real operational readiness remains advisory. */
|
|
126
|
+
export function projectEndpointDiscovery(discovery) {
|
|
127
|
+
const observedAt = discovery.observedAt;
|
|
128
|
+
if (!Number.isFinite(Date.parse(observedAt)))
|
|
129
|
+
return denied();
|
|
130
|
+
const state = (value) => value === "TRUE" ? "true" : value === "FALSE" ? "false" : "unknown";
|
|
131
|
+
const self = { adapter: discovery.self.adapter, endpointId: discovery.self.endpointId,
|
|
132
|
+
ownCapabilities: { send: discovery.self.effective.send, inbox: true, payloadRead: discovery.self.effective.readPayload, ack: discovery.self.effective.ack } };
|
|
133
|
+
const targets = discovery.targets.map(target => ({ adapter: target.adapter, endpointId: target.endpointId,
|
|
134
|
+
registered: true, authorized: { send: true }, active: state(target.active),
|
|
135
|
+
// Membership proves addressing only. Without exact child/run adoption and
|
|
136
|
+
// remote health evidence, composition cannot claim operational reachability.
|
|
137
|
+
reachable: target.reason === "PORT_BLOCKED" ? "false" : "unknown",
|
|
138
|
+
reason: target.reason === "PRESENCE_WITHHELD" ? "PRESENCE_WITHHELD"
|
|
139
|
+
: target.reason === "PORT_BLOCKED" ? "MCP_OPERATION_BLOCKED" : "OBSERVATION_UNKNOWN" }));
|
|
140
|
+
const projection = { self, targets };
|
|
141
|
+
return { ...projection, observedAt, viewDigest: createHash("sha256").update(JSON.stringify(projection)).digest("hex") };
|
|
142
|
+
}
|
|
143
|
+
//# sourceMappingURL=live-mcp-composition.js.map
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/** Read-only process evidence, not Owner/port readiness or future availability.
|
|
2
|
+
* ps exposes rendered argv, not lossless argv boundaries. Space-bearing paths
|
|
3
|
+
* and shell wrapper candidates therefore remain UNVERIFIED; never guess their
|
|
4
|
+
* quoting. macOS/Linux snapshots are bounded and errors disclose no diagnostics.
|
|
5
|
+
*/
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
7
|
+
import { buildTunnelMcpCommand } from "./profile.js";
|
|
8
|
+
function snapshot() {
|
|
9
|
+
if (process.platform !== "darwin" && process.platform !== "linux")
|
|
10
|
+
return Promise.resolve(undefined);
|
|
11
|
+
return new Promise(resolve => {
|
|
12
|
+
execFile("/bin/ps", ["-A", "-ww", "-o", "pid=,ppid=,uid=,lstart=,args="], {
|
|
13
|
+
env: { PATH: "/usr/bin:/bin", LC_ALL: "C" }, timeout: 5000, maxBuffer: 4 * 1024 * 1024,
|
|
14
|
+
}, (error, stdout) => {
|
|
15
|
+
if (error)
|
|
16
|
+
return resolve(undefined);
|
|
17
|
+
const rows = [];
|
|
18
|
+
for (const line of stdout.trimEnd().split("\n")) {
|
|
19
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+([A-Za-z]{3}\s+[A-Za-z]{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/.exec(line);
|
|
20
|
+
if (!match)
|
|
21
|
+
return resolve(undefined);
|
|
22
|
+
rows.push({ pid: Number(match[1]), ppid: Number(match[2]), uid: Number(match[3]), startedKey: match[4], command: match[5] });
|
|
23
|
+
}
|
|
24
|
+
resolve(rows);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Two stable same-user ancestry snapshots plus fresh manager revalidation.
|
|
29
|
+
* Wrappers may be intermediate ancestors, but only the exact Node invocation
|
|
30
|
+
* can be the candidate. No process is signalled, spawned, adopted or mutated.
|
|
31
|
+
*/
|
|
32
|
+
export async function verifyManagedMcpChild(options) {
|
|
33
|
+
try {
|
|
34
|
+
const { run } = options;
|
|
35
|
+
const uid = process.geteuid?.();
|
|
36
|
+
if (uid === undefined || run.identityConfirmed !== true || !run.runId.trim() || !Number.isSafeInteger(run.managedPid) || run.managedPid <= 0)
|
|
37
|
+
return undefined;
|
|
38
|
+
const anchor = { ...run };
|
|
39
|
+
const currentRun = async () => {
|
|
40
|
+
const current = await options.recheckRun();
|
|
41
|
+
return current?.identityConfirmed === true && current.runId === anchor.runId && current.managedPid === anchor.managedPid;
|
|
42
|
+
};
|
|
43
|
+
if ([options.nodePath, options.scriptPath, options.bindingPath].some(p => /\s/.test(p)))
|
|
44
|
+
return undefined;
|
|
45
|
+
const expected = buildTunnelMcpCommand(options);
|
|
46
|
+
if (!await currentRun())
|
|
47
|
+
return undefined;
|
|
48
|
+
const inspect = options.inspect ?? snapshot;
|
|
49
|
+
const capture = async () => {
|
|
50
|
+
const rows = await inspect();
|
|
51
|
+
if (!rows || rows.length > 65536)
|
|
52
|
+
return undefined;
|
|
53
|
+
const map = new Map();
|
|
54
|
+
for (const r of rows) {
|
|
55
|
+
if (!Number.isSafeInteger(r.pid) || r.pid < 0 || !Number.isSafeInteger(r.ppid) || r.ppid < 0 ||
|
|
56
|
+
!Number.isSafeInteger(r.uid) || !r.startedKey || !r.command || map.has(r.pid))
|
|
57
|
+
return undefined;
|
|
58
|
+
map.set(r.pid, { ...r });
|
|
59
|
+
}
|
|
60
|
+
const manager = map.get(anchor.managedPid);
|
|
61
|
+
if (!manager || manager.uid !== uid)
|
|
62
|
+
return undefined;
|
|
63
|
+
const candidates = [];
|
|
64
|
+
for (const candidate of map.values()) {
|
|
65
|
+
if (candidate.pid === manager.pid || candidate.command !== expected)
|
|
66
|
+
continue;
|
|
67
|
+
const path = [];
|
|
68
|
+
const seen = new Set();
|
|
69
|
+
let cursor = candidate;
|
|
70
|
+
while (cursor && !seen.has(cursor.pid) && cursor.uid === uid) {
|
|
71
|
+
seen.add(cursor.pid);
|
|
72
|
+
path.push(cursor);
|
|
73
|
+
if (cursor.pid === manager.pid) {
|
|
74
|
+
candidates.push(path);
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
cursor = map.get(cursor.ppid);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return candidates.length === 1 ? candidates[0] : undefined;
|
|
81
|
+
};
|
|
82
|
+
const first = await capture();
|
|
83
|
+
if (!first || !await currentRun())
|
|
84
|
+
return undefined;
|
|
85
|
+
const second = await capture();
|
|
86
|
+
if (!second || first.length !== second.length || first.some((r, i) => {
|
|
87
|
+
const other = second[i];
|
|
88
|
+
return r.pid !== other.pid || r.ppid !== other.ppid || r.uid !== other.uid || r.startedKey !== other.startedKey || r.command !== other.command;
|
|
89
|
+
}) || !await currentRun())
|
|
90
|
+
return undefined;
|
|
91
|
+
const child = second[0];
|
|
92
|
+
return Object.freeze({ pid: child.pid, startedKey: child.startedKey, command: child.command, runId: anchor.runId });
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=live-process-observation.js.map
|