@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,343 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { closeSync, constants, fsyncSync, fstatSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
|
4
|
+
import { userInfo } from "node:os";
|
|
5
|
+
import { dirname, isAbsolute, join, normalize } from "node:path";
|
|
6
|
+
import { TunnelRefusal } from "./codes.js";
|
|
7
|
+
const refusal = () => new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED");
|
|
8
|
+
const digestPattern = /^[a-f0-9]{64}$/;
|
|
9
|
+
const SELECTION_FILE = "selection.json";
|
|
10
|
+
function checkedPath(value) {
|
|
11
|
+
if (typeof value !== "string" || !isAbsolute(value) || normalize(value) !== value || /[\x00-\x1f\x7f]/.test(value) || value.split("/").includes(".."))
|
|
12
|
+
throw refusal();
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
function owner() {
|
|
16
|
+
if (typeof process.geteuid !== "function" || constants.O_NOFOLLOW === undefined)
|
|
17
|
+
throw refusal();
|
|
18
|
+
return process.geteuid();
|
|
19
|
+
}
|
|
20
|
+
function missing(error) {
|
|
21
|
+
return error?.code === "ENOENT";
|
|
22
|
+
}
|
|
23
|
+
function privateRecord(stat, uid) {
|
|
24
|
+
return stat.isFile() && stat.nlink === 1 && stat.uid === uid && (stat.mode & 0o7777) === 0o600 && stat.size <= 8192;
|
|
25
|
+
}
|
|
26
|
+
/** macOS ACL grants are independent of POSIX mode. Only absent ACLs or
|
|
27
|
+
* deny-only ACLs are admitted; unknown output or probe failure is fail-closed.
|
|
28
|
+
* The OS utility is fixed and never discovered through PATH. */
|
|
29
|
+
function darwinAclOutput(path) {
|
|
30
|
+
if (process.platform !== "darwin")
|
|
31
|
+
return undefined;
|
|
32
|
+
try {
|
|
33
|
+
return execFileSync("/bin/ls", ["-lde", path], {
|
|
34
|
+
cwd: "/", env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" },
|
|
35
|
+
shell: false, timeout: 5_000, killSignal: "SIGKILL", maxBuffer: 16_384,
|
|
36
|
+
encoding: "utf8", stdio: ["ignore", "pipe", "pipe"],
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw refusal();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Directory injection is solely for isolated tests; production uses the OS account home. */
|
|
44
|
+
export function createBackgroundAuthorizationStore(options = {}) {
|
|
45
|
+
const home = userInfo().homedir;
|
|
46
|
+
const directory = options.directory ?? join(home, ".config/pi-chat-exchange/background-authorization");
|
|
47
|
+
const now = options.now ?? Date.now;
|
|
48
|
+
const seam = options.filesystem ?? {};
|
|
49
|
+
const writeBytes = seam.writeSync ?? writeSync;
|
|
50
|
+
const syncFile = seam.fsyncSync ?? fsyncSync;
|
|
51
|
+
const moveFile = seam.renameSync ?? renameSync;
|
|
52
|
+
function path(profilePath) {
|
|
53
|
+
checkedPath(directory);
|
|
54
|
+
return join(directory, `${createHash("sha256").update(checkedPath(profilePath)).digest("hex")}.json`);
|
|
55
|
+
}
|
|
56
|
+
function selectionPath() {
|
|
57
|
+
checkedPath(directory);
|
|
58
|
+
return join(directory, SELECTION_FILE);
|
|
59
|
+
}
|
|
60
|
+
/** Rejects allow ACLs and unrecognised ACL output. Never mutates the path. */
|
|
61
|
+
function assertAclSafe(target) {
|
|
62
|
+
const output = options.readAcl ? options.readAcl(target) : darwinAclOutput(target);
|
|
63
|
+
if (output === undefined)
|
|
64
|
+
return;
|
|
65
|
+
const lines = output.trimEnd().split("\n");
|
|
66
|
+
const header = lines.shift() ?? "";
|
|
67
|
+
if (!/^[bcdlps-][rwxStTs-]{9}[+@ ]/.test(header))
|
|
68
|
+
throw refusal();
|
|
69
|
+
for (const entry of lines) {
|
|
70
|
+
if (!/^\s*\d+: \S+ deny [a-z_,]+$/.test(entry))
|
|
71
|
+
throw refusal();
|
|
72
|
+
}
|
|
73
|
+
if (header[10] === "+" && lines.length === 0)
|
|
74
|
+
throw refusal();
|
|
75
|
+
}
|
|
76
|
+
function trustedDirectory(uid, create) {
|
|
77
|
+
checkedPath(directory);
|
|
78
|
+
const chain = [];
|
|
79
|
+
for (let cursor = directory;; cursor = dirname(cursor)) {
|
|
80
|
+
chain.unshift(cursor);
|
|
81
|
+
if (dirname(cursor) === cursor)
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
let absent = false;
|
|
85
|
+
for (const entry of chain) {
|
|
86
|
+
let stat;
|
|
87
|
+
try {
|
|
88
|
+
stat = lstatSync(entry);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (!missing(error))
|
|
92
|
+
throw error;
|
|
93
|
+
if (!create) {
|
|
94
|
+
absent = true;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
mkdirSync(entry, { mode: 0o700 });
|
|
98
|
+
stat = lstatSync(entry);
|
|
99
|
+
}
|
|
100
|
+
const inHome = entry === home || entry.startsWith(`${home}/`);
|
|
101
|
+
const stickyRoot = stat.uid === 0 && (stat.mode & 0o1000) !== 0;
|
|
102
|
+
if (!stat.isDirectory() || (stat.uid !== uid && stat.uid !== 0) ||
|
|
103
|
+
((stat.mode & 0o022) !== 0 && !stickyRoot) ||
|
|
104
|
+
(inHome && entry !== home && stat.uid !== uid) ||
|
|
105
|
+
(entry === directory && (stat.uid !== uid || (stat.mode & 0o7777) !== 0o700)))
|
|
106
|
+
throw refusal();
|
|
107
|
+
assertAclSafe(entry);
|
|
108
|
+
}
|
|
109
|
+
return !absent;
|
|
110
|
+
}
|
|
111
|
+
/** Reads a private record file without healing or repairing it. */
|
|
112
|
+
function readPrivateRecord(file, uid) {
|
|
113
|
+
let fd;
|
|
114
|
+
try {
|
|
115
|
+
let before;
|
|
116
|
+
try {
|
|
117
|
+
before = lstatSync(file);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (missing(error))
|
|
121
|
+
return { kind: "absent" };
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
if (!privateRecord(before, uid))
|
|
125
|
+
return { kind: "invalid" };
|
|
126
|
+
assertAclSafe(file);
|
|
127
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
128
|
+
const opened = fstatSync(fd);
|
|
129
|
+
if (!privateRecord(opened, uid) || opened.dev !== before.dev || opened.ino !== before.ino)
|
|
130
|
+
return { kind: "invalid" };
|
|
131
|
+
const buffer = Buffer.alloc(8193);
|
|
132
|
+
let length = 0;
|
|
133
|
+
while (length < buffer.length) {
|
|
134
|
+
const count = readSync(fd, buffer, length, buffer.length - length, null);
|
|
135
|
+
if (count === 0)
|
|
136
|
+
break;
|
|
137
|
+
length += count;
|
|
138
|
+
}
|
|
139
|
+
if (length > 8192)
|
|
140
|
+
return { kind: "invalid" };
|
|
141
|
+
const data = JSON.parse(buffer.subarray(0, length).toString("utf8"));
|
|
142
|
+
if (!data || typeof data !== "object" || Array.isArray(data))
|
|
143
|
+
return { kind: "invalid" };
|
|
144
|
+
return { kind: "valid", record: data };
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return { kind: "invalid" };
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
if (fd !== undefined) {
|
|
151
|
+
try {
|
|
152
|
+
closeSync(fd);
|
|
153
|
+
}
|
|
154
|
+
catch { /* No raw filesystem errors escape inspection. */ }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** Durable commit of one private record: write, file sync, rename, directory sync.
|
|
159
|
+
* Failures before the rename are refusals; the previous record still stands.
|
|
160
|
+
* A failure after the rename returns `uncertain` and never claims rollback. */
|
|
161
|
+
function commitRecord(file, bytes) {
|
|
162
|
+
let fd;
|
|
163
|
+
let temp;
|
|
164
|
+
let renamed = false;
|
|
165
|
+
try {
|
|
166
|
+
temp = join(directory, `.${randomUUID()}.tmp`);
|
|
167
|
+
fd = openSync(temp, constants.O_EXCL | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_WRONLY, 0o600);
|
|
168
|
+
const uid = owner();
|
|
169
|
+
if (!privateRecord(fstatSync(fd), uid))
|
|
170
|
+
throw refusal();
|
|
171
|
+
let offset = 0;
|
|
172
|
+
while (offset < bytes.length) {
|
|
173
|
+
const count = writeBytes(fd, bytes, offset, bytes.length - offset);
|
|
174
|
+
if (count === 0)
|
|
175
|
+
throw refusal();
|
|
176
|
+
offset += count;
|
|
177
|
+
}
|
|
178
|
+
syncFile(fd);
|
|
179
|
+
closeSync(fd);
|
|
180
|
+
fd = undefined;
|
|
181
|
+
trustedDirectory(uid, false);
|
|
182
|
+
assertAclSafe(temp);
|
|
183
|
+
moveFile(temp, file);
|
|
184
|
+
renamed = true;
|
|
185
|
+
temp = undefined;
|
|
186
|
+
try {
|
|
187
|
+
fd = openSync(directory, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
|
|
188
|
+
syncFile(fd);
|
|
189
|
+
closeSync(fd);
|
|
190
|
+
fd = undefined;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return { committed: true, durability: "uncertain" };
|
|
194
|
+
}
|
|
195
|
+
return { committed: true, durability: "synced" };
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
if (renamed)
|
|
199
|
+
return { committed: true, durability: "uncertain" };
|
|
200
|
+
throw refusal();
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
if (fd !== undefined) {
|
|
204
|
+
try {
|
|
205
|
+
closeSync(fd);
|
|
206
|
+
}
|
|
207
|
+
catch { /* Best effort cleanup. */ }
|
|
208
|
+
}
|
|
209
|
+
if (temp !== undefined) {
|
|
210
|
+
try {
|
|
211
|
+
unlinkSync(temp);
|
|
212
|
+
}
|
|
213
|
+
catch { /* Only remove this write's exclusive temporary file. */ }
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function inspect(profilePath) {
|
|
218
|
+
try {
|
|
219
|
+
const file = path(profilePath);
|
|
220
|
+
const uid = owner();
|
|
221
|
+
if (!trustedDirectory(uid, false))
|
|
222
|
+
return { kind: "absent" };
|
|
223
|
+
const found = readPrivateRecord(file, uid);
|
|
224
|
+
if (found.kind !== "valid" || !found.record)
|
|
225
|
+
return found.kind === "absent" ? { kind: "absent" } : { kind: "invalid" };
|
|
226
|
+
const record = found.record;
|
|
227
|
+
const keys = ["version", "uid", "profilePath", "state", "scopeDigest", "updatedAt"];
|
|
228
|
+
if (Object.keys(record).length !== keys.length || !keys.every(key => Object.hasOwn(record, key)) ||
|
|
229
|
+
record.version !== 1 || record.uid !== uid || record.profilePath !== profilePath ||
|
|
230
|
+
(record.state !== "granted" && record.state !== "revoked") ||
|
|
231
|
+
typeof record.scopeDigest !== "string" || !digestPattern.test(record.scopeDigest) ||
|
|
232
|
+
!Number.isSafeInteger(record.updatedAt) || record.updatedAt < 0)
|
|
233
|
+
return { kind: "invalid" };
|
|
234
|
+
// A prior writer may have observed rename but not directory-sync success.
|
|
235
|
+
// Re-establish durability before a visible grant can authorize a fresh process.
|
|
236
|
+
if (record.state === "granted") {
|
|
237
|
+
const directoryFd = openSync(directory, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
|
|
238
|
+
try {
|
|
239
|
+
syncFile(directoryFd);
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
closeSync(directoryFd);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return { kind: "valid", state: record.state, scopeDigest: record.scopeDigest };
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return { kind: "invalid" };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function write(profilePath, state, scopeDigest) {
|
|
252
|
+
try {
|
|
253
|
+
const file = path(profilePath);
|
|
254
|
+
const uid = owner();
|
|
255
|
+
const updatedAt = now();
|
|
256
|
+
if ((state !== "granted" && state !== "revoked") || typeof scopeDigest !== "string" || !digestPattern.test(scopeDigest) || !Number.isSafeInteger(updatedAt) || updatedAt < 0)
|
|
257
|
+
throw refusal();
|
|
258
|
+
trustedDirectory(uid, true);
|
|
259
|
+
const existing = lstatSync(file, { throwIfNoEntry: false });
|
|
260
|
+
if (existing) {
|
|
261
|
+
if (existing.nlink !== 1)
|
|
262
|
+
throw refusal();
|
|
263
|
+
assertAclSafe(file);
|
|
264
|
+
}
|
|
265
|
+
const bytes = Buffer.from(JSON.stringify({ version: 1, uid, profilePath, state, scopeDigest, updatedAt }));
|
|
266
|
+
if (bytes.length > 8192)
|
|
267
|
+
throw refusal();
|
|
268
|
+
return commitRecord(file, bytes);
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
if (error?.code === "CE_TUNNEL_BACKGROUND_UNAUTHORIZED")
|
|
272
|
+
throw error;
|
|
273
|
+
throw refusal();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/** Non-authoritative launch selection. The per-profile grant stays separate. */
|
|
277
|
+
function readSelection() {
|
|
278
|
+
try {
|
|
279
|
+
const uid = owner();
|
|
280
|
+
if (!trustedDirectory(uid, false))
|
|
281
|
+
return { kind: "absent" };
|
|
282
|
+
const found = readPrivateRecord(selectionPath(), uid);
|
|
283
|
+
if (found.kind === "absent")
|
|
284
|
+
return { kind: "absent" };
|
|
285
|
+
if (found.kind !== "valid" || !found.record)
|
|
286
|
+
return { kind: "invalid" };
|
|
287
|
+
const record = found.record;
|
|
288
|
+
const keys = ["version", "uid", "profilePath", "clientPath", "updatedAt"];
|
|
289
|
+
if (Object.keys(record).length !== keys.length || !keys.every(key => Object.hasOwn(record, key)) ||
|
|
290
|
+
record.version !== 1 || record.uid !== uid ||
|
|
291
|
+
typeof record.profilePath !== "string" || typeof record.clientPath !== "string" ||
|
|
292
|
+
!Number.isSafeInteger(record.updatedAt) || record.updatedAt < 0)
|
|
293
|
+
return { kind: "invalid" };
|
|
294
|
+
try {
|
|
295
|
+
checkedPath(record.profilePath);
|
|
296
|
+
checkedPath(record.clientPath);
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return { kind: "invalid" };
|
|
300
|
+
}
|
|
301
|
+
const directoryFd = openSync(directory, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
|
|
302
|
+
try {
|
|
303
|
+
syncFile(directoryFd);
|
|
304
|
+
}
|
|
305
|
+
finally {
|
|
306
|
+
closeSync(directoryFd);
|
|
307
|
+
}
|
|
308
|
+
return { kind: "valid", profilePath: record.profilePath, clientPath: record.clientPath };
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return { kind: "invalid" };
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function writeSelection(profilePath, clientPath) {
|
|
315
|
+
try {
|
|
316
|
+
const uid = owner();
|
|
317
|
+
const updatedAt = now();
|
|
318
|
+
const normalizedProfile = checkedPath(profilePath);
|
|
319
|
+
const normalizedClient = checkedPath(clientPath);
|
|
320
|
+
if (!Number.isSafeInteger(updatedAt) || updatedAt < 0)
|
|
321
|
+
throw refusal();
|
|
322
|
+
trustedDirectory(uid, true);
|
|
323
|
+
const file = selectionPath();
|
|
324
|
+
const existing = lstatSync(file, { throwIfNoEntry: false });
|
|
325
|
+
if (existing) {
|
|
326
|
+
if (existing.nlink !== 1)
|
|
327
|
+
throw refusal();
|
|
328
|
+
assertAclSafe(file);
|
|
329
|
+
}
|
|
330
|
+
const bytes = Buffer.from(JSON.stringify({ version: 1, uid, profilePath: normalizedProfile, clientPath: normalizedClient, updatedAt }));
|
|
331
|
+
if (bytes.length > 8192)
|
|
332
|
+
throw refusal();
|
|
333
|
+
return commitRecord(file, bytes);
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (error?.code === "CE_TUNNEL_BACKGROUND_UNAUTHORIZED")
|
|
337
|
+
throw error;
|
|
338
|
+
throw refusal();
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return { inspect, write, path, selectionPath, readSelection, writeSelection };
|
|
342
|
+
}
|
|
343
|
+
//# sourceMappingURL=background-authorization.js.map
|
|
@@ -168,6 +168,8 @@ import { TunnelRefusal } from "./codes.js";
|
|
|
168
168
|
import { TUNNEL_ID_PATTERN } from "./tunnel-id.js";
|
|
169
169
|
import { resolveTunnelClient } from "../runtime/executables.js";
|
|
170
170
|
import { resolveWrapperIdentityEvidence } from "../runtime/wrapper-identity.js";
|
|
171
|
+
import { createBackgroundAuthorizationStore } from "./background-authorization.js";
|
|
172
|
+
import { captureBackgroundAuthorizationScope } from "./background-scope.js";
|
|
171
173
|
import { createHealthCompletionRecorder } from "./health.js";
|
|
172
174
|
import { checkKeyFileRequirements, childEnvironment } from "./profile.js";
|
|
173
175
|
import { DEFAULT_TUNNEL_TIMING, initialTunnelState, nextTunnelState, } from "./state.js";
|
|
@@ -564,9 +566,12 @@ function mapStateName(name) {
|
|
|
564
566
|
/** Single path-selection authority for manager, setup and configuration status.
|
|
565
567
|
* Reject control bytes before a path can reach any visible TUI/status surface. */
|
|
566
568
|
export function resolveTunnelProfilePath(options) {
|
|
569
|
+
const selection = createBackgroundAuthorizationStore(options.authorizationDirectory === undefined ? {} : { directory: options.authorizationDirectory }).readSelection();
|
|
570
|
+
if (options.profilePath === undefined && !options.env.CE_TUNNEL_PROFILE && selection.kind === "invalid")
|
|
571
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.selection");
|
|
567
572
|
const path = options.profilePath ??
|
|
568
573
|
(typeof options.env.CE_TUNNEL_PROFILE === "string" && options.env.CE_TUNNEL_PROFILE.length > 0
|
|
569
|
-
? options.env.CE_TUNNEL_PROFILE : defaultProfilePath());
|
|
574
|
+
? options.env.CE_TUNNEL_PROFILE : selection.kind === "valid" ? selection.profilePath : defaultProfilePath());
|
|
570
575
|
if (!isAbsolute(path) || normalize(path) !== path || !/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/.test(path)) {
|
|
571
576
|
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile.path");
|
|
572
577
|
}
|
|
@@ -578,8 +583,13 @@ export function createBackgroundTunnelManager(options) {
|
|
|
578
583
|
const timing = options.timing ?? DEFAULT_BACKGROUND_TUNNEL_TIMING;
|
|
579
584
|
// Constructor overrides remain domain-test dependencies. Operator settings
|
|
580
585
|
// and discovered production executables always cross the trust boundary.
|
|
586
|
+
const selection = options.authorizationDirectory === undefined ? createBackgroundAuthorizationStore().readSelection() : createBackgroundAuthorizationStore({ directory: options.authorizationDirectory }).readSelection();
|
|
581
587
|
const clientPath = options.clientPath ?? (() => {
|
|
582
588
|
try {
|
|
589
|
+
if (env.CE_TUNNEL_CLIENT_PATH !== undefined)
|
|
590
|
+
return resolveTunnelClient({ env });
|
|
591
|
+
if (selection.kind === "valid")
|
|
592
|
+
return resolveTunnelClient({ env: { CE_TUNNEL_CLIENT_PATH: selection.clientPath } });
|
|
583
593
|
return resolveTunnelClient({ env });
|
|
584
594
|
}
|
|
585
595
|
catch {
|
|
@@ -588,6 +598,56 @@ export function createBackgroundTunnelManager(options) {
|
|
|
588
598
|
})();
|
|
589
599
|
const profilePath = resolveTunnelProfilePath(options);
|
|
590
600
|
const stateFilePath = options.stateFilePath ?? `${dirname(profilePath)}/background-state.json`;
|
|
601
|
+
const authorizationStore = createBackgroundAuthorizationStore(options.authorizationDirectory === undefined ? {} : { directory: options.authorizationDirectory });
|
|
602
|
+
const authorizationScope = () => {
|
|
603
|
+
const entry = lstatSync(profilePath);
|
|
604
|
+
if (!entry.isFile() || entry.nlink !== 1)
|
|
605
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
|
|
606
|
+
const profileText = readFileSync(profilePath, "utf8");
|
|
607
|
+
const facts = parseTunnelProfile(profileText);
|
|
608
|
+
checkKeyFileMetadata(facts.keyFile);
|
|
609
|
+
return captureBackgroundAuthorizationScope({ profilePath, profileText, credentialPath: facts.keyFile, mcpCommand: facts.mcpCommand, clientPath });
|
|
610
|
+
};
|
|
611
|
+
const authorizationStatus = () => {
|
|
612
|
+
const selected = authorizationStore.readSelection();
|
|
613
|
+
if (selected.kind === "invalid")
|
|
614
|
+
return "invalid";
|
|
615
|
+
const record = authorizationStore.inspect(profilePath);
|
|
616
|
+
if (record.kind === "invalid")
|
|
617
|
+
return "invalid";
|
|
618
|
+
if (record.kind === "absent")
|
|
619
|
+
return env[BACKGROUND_OPT_IN] === "1" ? "environment" : "absent";
|
|
620
|
+
if (record.state === "revoked")
|
|
621
|
+
return "revoked";
|
|
622
|
+
return record.scopeDigest === authorizationScope().digest ? "granted" : "changed";
|
|
623
|
+
};
|
|
624
|
+
const assertAuthorization = () => {
|
|
625
|
+
const status = authorizationStatus();
|
|
626
|
+
if (status !== "granted" && status !== "environment")
|
|
627
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", `authorization.${status}`);
|
|
628
|
+
};
|
|
629
|
+
const grantAuthorization = (expectedDigest) => {
|
|
630
|
+
if (authorizationStore.inspect(profilePath).kind === "invalid")
|
|
631
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.invalid");
|
|
632
|
+
const scope = authorizationScope();
|
|
633
|
+
if (scope.digest !== expectedDigest)
|
|
634
|
+
throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "authorization.scope");
|
|
635
|
+
const saved = authorizationStore.write(profilePath, "granted", scope.digest);
|
|
636
|
+
if (saved.durability !== "synced")
|
|
637
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.durability-uncertain");
|
|
638
|
+
if (clientPath === undefined)
|
|
639
|
+
throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
|
|
640
|
+
const selection = authorizationStore.writeSelection(profilePath, clientPath);
|
|
641
|
+
if (selection.durability !== "synced")
|
|
642
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.selection-uncertain");
|
|
643
|
+
};
|
|
644
|
+
const revokeAuthorization = () => {
|
|
645
|
+
if (authorizationStore.inspect(profilePath).kind === "invalid")
|
|
646
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.invalid");
|
|
647
|
+
const saved = authorizationStore.write(profilePath, "revoked", "0".repeat(64));
|
|
648
|
+
if (saved.durability !== "synced")
|
|
649
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.revocation-uncertain");
|
|
650
|
+
};
|
|
591
651
|
const logPath = `${dirname(stateFilePath)}/background-tunnel.log`;
|
|
592
652
|
const spawnSeam = options.spawn ?? defaultSpawnDaemon(logPath);
|
|
593
653
|
/** Exact command lines this manager's own spawn may show in ps (F2): the
|
|
@@ -1059,7 +1119,7 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1059
1119
|
await sleep(EXIT_POLL_MS);
|
|
1060
1120
|
}
|
|
1061
1121
|
};
|
|
1062
|
-
const refresh = async () => {
|
|
1122
|
+
const refresh = async (observation) => {
|
|
1063
1123
|
reloadRecord();
|
|
1064
1124
|
if (recordCorrupt) {
|
|
1065
1125
|
note = "ownership record unreadable; refusing to guess";
|
|
@@ -1068,6 +1128,10 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1068
1128
|
let current = record;
|
|
1069
1129
|
if (current === undefined || current.state === "stopped")
|
|
1070
1130
|
return status();
|
|
1131
|
+
// Observation must not enter refresh's ledger reconciliation paths.
|
|
1132
|
+
if (observation !== undefined && (current.state !== "running" || current.identityPending === true ||
|
|
1133
|
+
current.termRequestedAt !== undefined))
|
|
1134
|
+
return status();
|
|
1071
1135
|
// C-v2-5: establish the run baseline BEFORE any async measurement so a
|
|
1072
1136
|
// health completion can never predate it.
|
|
1073
1137
|
const baseline = machineStartedAt(current);
|
|
@@ -1079,6 +1143,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1079
1143
|
// must never be adopted or signalled).
|
|
1080
1144
|
if (presence.kind === "absent" || (current.identityPending === true && exitedPendingRuns.has(current.runId))) {
|
|
1081
1145
|
observeAbsence(current, runTiming, baseline);
|
|
1146
|
+
if (observation !== undefined)
|
|
1147
|
+
return status();
|
|
1082
1148
|
// R4/C-v2-3: persist ONLY under the lock, re-checking the run inside.
|
|
1083
1149
|
let release;
|
|
1084
1150
|
try {
|
|
@@ -1113,6 +1179,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1113
1179
|
note = "process inspection unavailable; ownership retained";
|
|
1114
1180
|
return status();
|
|
1115
1181
|
}
|
|
1182
|
+
if (observation !== undefined && presence.identity.pid !== current.pid)
|
|
1183
|
+
return status();
|
|
1116
1184
|
if (current.identityPending === true) {
|
|
1117
1185
|
// Same re-acquisition rule as terminateOwned (S3-2 + F2: exact membership
|
|
1118
1186
|
// in the evidence-derived spawn-identity set, never substring).
|
|
@@ -1171,18 +1239,39 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1171
1239
|
if (latest.kind !== "ok" || latest.record.runId !== current.runId || latest.record.state === "stopped") {
|
|
1172
1240
|
return status();
|
|
1173
1241
|
}
|
|
1242
|
+
if (observation !== undefined && (latest.record.state !== "running" || latest.record.termRequestedAt !== undefined ||
|
|
1243
|
+
latest.record.pid !== current.pid || latest.record.processStartedKey !== current.processStartedKey ||
|
|
1244
|
+
latest.record.commandIdentity !== current.commandIdentity || latest.record.commandIdentityExec !== current.commandIdentityExec))
|
|
1245
|
+
return status();
|
|
1174
1246
|
state = nextTunnelState(state, {
|
|
1175
1247
|
now: now(), runId: current.runId, managedPid: current.pid, processAlive: true,
|
|
1176
1248
|
userStopped: current.termRequestedAt !== undefined, startedAt: baseline,
|
|
1177
1249
|
exit: undefined, probe, startupLogSeen: false, externalInstance: false,
|
|
1178
1250
|
}, runTiming);
|
|
1251
|
+
observation?.onVerifiedProbe(probe);
|
|
1179
1252
|
return status();
|
|
1180
1253
|
};
|
|
1181
|
-
const
|
|
1254
|
+
const observeLiveTransport = async () => {
|
|
1255
|
+
let health;
|
|
1256
|
+
try {
|
|
1257
|
+
const current = await refresh({ onVerifiedProbe: (probe) => { health = probe; } });
|
|
1258
|
+
// This manager supervises remote `run` only (never dev proxy). Require
|
|
1259
|
+
// explicit current polling evidence; CONNECTED alone does not imply it.
|
|
1260
|
+
if (!disposed && current.state === "CONNECTED" && current.running && health?.connectedEligible === true &&
|
|
1261
|
+
health.controlPlanePollObserved === true && typeof current.runId === "string" && current.runId.trim().length > 0 &&
|
|
1262
|
+
current.pid !== undefined && Number.isSafeInteger(current.pid) && current.pid > 0 &&
|
|
1263
|
+
health.completion?.runId === current.runId && health.completion.managedPid === current.pid) {
|
|
1264
|
+
return { kind: "CONNECTED", runId: current.runId, managedPid: current.pid, identityConfirmed: true };
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
catch { /* Inspection/probe failure exposes no raw diagnostics or identity. */ }
|
|
1268
|
+
return { kind: "UNAVAILABLE" };
|
|
1269
|
+
};
|
|
1270
|
+
const start = (expectedProfileSha256) => {
|
|
1182
1271
|
// R5/C-v2-2: the lifecycle generation is captured AT CALL TIME, so a stop
|
|
1183
1272
|
// submitted before this start executes still invalidates it.
|
|
1184
1273
|
const fenceAtCall = startFence;
|
|
1185
|
-
const op = enqueue(() => startImpl(fenceAtCall));
|
|
1274
|
+
const op = enqueue(() => startImpl(fenceAtCall, undefined, expectedProfileSha256));
|
|
1186
1275
|
activeStart = op;
|
|
1187
1276
|
const settled = op.then((result) => { if (activeStart === op)
|
|
1188
1277
|
activeStart = undefined; return result; }, (error) => { if (activeStart === op)
|
|
@@ -1204,14 +1293,13 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1204
1293
|
activeStart = undefined; rejectAck?.(error); throw error; });
|
|
1205
1294
|
return { ack, settled };
|
|
1206
1295
|
};
|
|
1207
|
-
const startImpl = async (fenceAtCall, onSpawned) => {
|
|
1296
|
+
const startImpl = async (fenceAtCall, onSpawned, expectedProfileSha256) => {
|
|
1208
1297
|
if (fenceAtCall !== startFence)
|
|
1209
1298
|
throw new TunnelRefusal("CE_TUNNEL_READY_TIMEOUT");
|
|
1210
1299
|
if (disposed)
|
|
1211
1300
|
throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
|
|
1212
|
-
//
|
|
1213
|
-
|
|
1214
|
-
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED");
|
|
1301
|
+
// Durable revocation and invalid records override legacy process permission.
|
|
1302
|
+
assertAuthorization();
|
|
1215
1303
|
if (!isAbsolute(profilePath) || normalize(profilePath) !== profilePath) {
|
|
1216
1304
|
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
|
|
1217
1305
|
}
|
|
@@ -1225,6 +1313,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1225
1313
|
const facts = parseTunnelProfile(profileText);
|
|
1226
1314
|
checkKeyFileMetadata(facts.keyFile);
|
|
1227
1315
|
const profileSha256 = createHash("sha256").update(profileText, "utf8").digest("hex");
|
|
1316
|
+
if (expectedProfileSha256 !== undefined && expectedProfileSha256 !== profileSha256)
|
|
1317
|
+
throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "profile");
|
|
1228
1318
|
// S6/C4: prove the record location is writable BEFORE spawning.
|
|
1229
1319
|
ensureStateDir(dirname(stateFilePath));
|
|
1230
1320
|
const writabilityProbe = `${stateFilePath}.${randomUUID()}.probe`;
|
|
@@ -1290,6 +1380,9 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1290
1380
|
if (currentProfileText !== profileText)
|
|
1291
1381
|
throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "profile");
|
|
1292
1382
|
checkKeyFileMetadata(facts.keyFile);
|
|
1383
|
+
// Admission uses this final grant snapshot. A concurrent revoke cannot
|
|
1384
|
+
// retract an admitted start; Stop is the explicit process cleanup barrier.
|
|
1385
|
+
assertAuthorization();
|
|
1293
1386
|
if (clientPath === undefined)
|
|
1294
1387
|
throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED", "client");
|
|
1295
1388
|
const runId = `bg-${randomUUID()}`;
|
|
@@ -1619,6 +1712,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1619
1712
|
};
|
|
1620
1713
|
return {
|
|
1621
1714
|
kind: "real-background",
|
|
1715
|
+
profilePath: () => profilePath,
|
|
1716
|
+
authorizationScope, authorizationStatus, grantAuthorization, revokeAuthorization,
|
|
1622
1717
|
start,
|
|
1623
1718
|
startDeferred,
|
|
1624
1719
|
withProfileConfigurationLock: (operation) => enqueue(async () => {
|
|
@@ -1653,6 +1748,7 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1653
1748
|
}),
|
|
1654
1749
|
stop,
|
|
1655
1750
|
refresh,
|
|
1751
|
+
observeLiveTransport,
|
|
1656
1752
|
status,
|
|
1657
1753
|
runId: () => (record !== undefined && record.state !== "stopped" ? record.runId : undefined),
|
|
1658
1754
|
async dispose() {
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { admitExecutable, qualifyNodeExecutable } from "../runtime/executables.js";
|
|
5
|
+
import { resolveWrapperIdentityEvidence } from "../runtime/wrapper-identity.js";
|
|
6
|
+
import { parseMcpBindingConfig } from "../host/mcp-binding-config.js";
|
|
7
|
+
import { parseTunnelMcpCommand } from "./profile.js";
|
|
8
|
+
import { TunnelRefusal } from "./codes.js";
|
|
9
|
+
const sha = (text) => createHash("sha256").update(text).digest("hex");
|
|
10
|
+
const identity = (stat) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.mode, stat.uid];
|
|
11
|
+
function safeDocument(path, key) {
|
|
12
|
+
let fd;
|
|
13
|
+
try {
|
|
14
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
15
|
+
const stat = fstatSync(fd);
|
|
16
|
+
// Exclude credential aliases before reading even a single byte.
|
|
17
|
+
if (!stat.isFile() || (stat.uid !== process.geteuid?.() && stat.uid !== 0) ||
|
|
18
|
+
(stat.mode & 0o022) !== 0 || stat.size > 1_048_576 || (stat.dev === key.dev && stat.ino === key.ino))
|
|
19
|
+
throw new Error("unsafe");
|
|
20
|
+
const text = readFileSync(fd, "utf8");
|
|
21
|
+
if (Buffer.byteLength(text) > 1_048_576)
|
|
22
|
+
throw new Error("oversized");
|
|
23
|
+
return text;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "authorization.scope");
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
if (fd !== undefined)
|
|
30
|
+
closeSync(fd);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Exact launch scope, never credential contents or messaging authority. The caller
|
|
34
|
+
* admits the selected client; grant validation rechecks these file identities before spawn. */
|
|
35
|
+
export function captureBackgroundAuthorizationScope(input) {
|
|
36
|
+
try {
|
|
37
|
+
if (input.clientPath === undefined || input.mcpCommand === undefined)
|
|
38
|
+
throw new Error("missing");
|
|
39
|
+
const key = lstatSync(input.credentialPath);
|
|
40
|
+
if (safeDocument(input.profilePath, key) !== input.profileText)
|
|
41
|
+
throw new Error("drift");
|
|
42
|
+
const client = lstatSync(input.clientPath);
|
|
43
|
+
if (!client.isFile() || (client.uid !== process.geteuid?.() && client.uid !== 0) || (client.mode & 0o022) !== 0)
|
|
44
|
+
throw new Error("client");
|
|
45
|
+
const wrapper = resolveWrapperIdentityEvidence(input.clientPath);
|
|
46
|
+
const parsed = parseTunnelMcpCommand(input.mcpCommand);
|
|
47
|
+
const scriptPath = fileURLToPath(new URL("../../dist/bin/mcp-stdio.js", import.meta.url));
|
|
48
|
+
// Persistent permission never authorizes an arbitrary script with a familiar basename.
|
|
49
|
+
if (parsed.scriptPath !== scriptPath)
|
|
50
|
+
throw new Error("script");
|
|
51
|
+
admitExecutable(parsed.nodePath);
|
|
52
|
+
qualifyNodeExecutable(parsed.nodePath);
|
|
53
|
+
const binding = safeDocument(parsed.bindingPath, key);
|
|
54
|
+
parseMcpBindingConfig(JSON.parse(binding));
|
|
55
|
+
const profileSha256 = sha(input.profileText);
|
|
56
|
+
const scope = { version: 1, profilePath: input.profilePath, profileSha256,
|
|
57
|
+
credential: [input.credentialPath, ...identity(key)], client: [input.clientPath, ...identity(client)],
|
|
58
|
+
wrapper: wrapper?.execTarget === undefined ? null : [wrapper.execTarget, ...identity(lstatSync(wrapper.execTarget))],
|
|
59
|
+
node: [parsed.nodePath, ...identity(lstatSync(parsed.nodePath))],
|
|
60
|
+
script: [scriptPath, sha(safeDocument(scriptPath, key))], binding: [parsed.bindingPath, sha(binding)] };
|
|
61
|
+
return { digest: sha(JSON.stringify(scope)), profileSha256, clientPath: input.clientPath, credentialPath: input.credentialPath };
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error instanceof TunnelRefusal)
|
|
65
|
+
throw error;
|
|
66
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "authorization.scope");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=background-scope.js.map
|
package/dist/tunnel/codes.js
CHANGED
|
@@ -58,7 +58,7 @@ const MESSAGES = Object.freeze({
|
|
|
58
58
|
CE_TUNNEL_CONFIG_CONFLICT: "two configuration sources disagree",
|
|
59
59
|
CE_TUNNEL_KEYCHAIN_AUTH_REQUIRED: "reading the credential needs a one-time macOS keychain authorization for this helper build",
|
|
60
60
|
CE_TUNNEL_KEYCHAIN_USER_CANCELED: "the macOS keychain authorization prompt was dismissed",
|
|
61
|
-
CE_TUNNEL_BACKGROUND_UNAUTHORIZED: "real background
|
|
61
|
+
CE_TUNNEL_BACKGROUND_UNAUTHORIZED: "real background startup permission is absent, revoked, changed, or unsafe; inspect /ce-tunnel permission status",
|
|
62
62
|
CE_TUNNEL_MANAGER_BUSY: "another manager holds this tunnel's ownership lock",
|
|
63
63
|
CE_TUNNEL_STATE_CORRUPT: "the ownership record exists but is unreadable; refusing to guess",
|
|
64
64
|
});
|