@zieglar/pi-chat-exchange 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +137 -2
- package/dist/bin/ce-native.js +119 -0
- package/dist/bin/mcp-stdio.js +196 -0
- package/dist/control/debug-log.js +67 -0
- package/dist/control/mcp/debug-transport.js +48 -0
- package/dist/control/mcp/messaging-tools.js +278 -0
- package/dist/control/mcp/ping.js +43 -0
- package/dist/control/mcp/server.js +153 -0
- package/dist/core/authorization.js +32 -0
- package/dist/core/reference.js +32 -0
- package/dist/core/rules.js +468 -0
- package/dist/endpoints/pi/contract.js +2 -0
- package/dist/endpoints/pi/session-host.js +39 -0
- package/dist/host/bound-endpoint.js +176 -0
- package/dist/host/endpoint-host.js +839 -0
- package/dist/host/mcp-binding-config.js +209 -0
- package/dist/host/ownership-recovery.js +257 -0
- package/dist/index.js +11 -0
- package/dist/protocol/capabilities.js +46 -0
- package/dist/protocol/endpoint-capabilities.js +15 -0
- package/dist/protocol/entities.js +185 -0
- package/dist/protocol/formats.js +13 -0
- package/dist/protocol/idempotency.js +93 -0
- package/dist/protocol/identity.js +130 -0
- package/dist/protocol/index.js +8 -0
- package/dist/protocol/lifecycle.js +125 -0
- package/dist/protocol/outcomes.js +55 -0
- package/dist/runtime/desktop-manifest.js +65 -0
- package/dist/runtime/diagnostics.js +34 -0
- package/dist/runtime/executables.js +217 -0
- package/dist/runtime/native-readiness.js +131 -0
- package/dist/storage/capability.js +221 -0
- package/dist/storage/connection.js +95 -0
- package/dist/storage/creation-request.js +176 -0
- package/dist/storage/creation.js +553 -0
- package/dist/storage/current-schema.js +397 -0
- package/dist/storage/delivery-ack.js +177 -0
- package/dist/storage/errors.js +9 -0
- package/dist/storage/filesystem.js +171 -0
- package/dist/storage/inbox-discovery.js +135 -0
- package/dist/storage/messaging.js +156 -0
- package/dist/storage/migration.js +258 -0
- package/dist/storage/native-artifact.js +234 -0
- package/dist/storage/native-compat.js +65 -0
- package/dist/storage/ownership.js +789 -0
- package/dist/storage/participant-identity.js +127 -0
- package/dist/storage/participant.js +700 -0
- package/dist/storage/recovery.js +99 -0
- package/dist/storage/runtime.js +256 -0
- package/dist/storage/schema.js +556 -0
- package/dist/storage/session-state.js +75 -0
- package/dist/storage/sqlite-driver-node.js +66 -0
- package/dist/storage/sqlite-driver-rust.js +121 -0
- package/dist/storage/sqlite-driver-selection.js +86 -0
- package/dist/storage/sqlite-driver.js +4 -0
- package/dist/storage/store.js +450 -0
- package/dist/storage/transaction.js +196 -0
- package/dist/storage/trust-root.js +164 -0
- package/dist/tunnel/background-manager.js +1727 -0
- package/dist/tunnel/codes.js +79 -0
- package/dist/tunnel/health.js +75 -0
- package/dist/tunnel/keychain.js +526 -0
- package/dist/tunnel/managed-binding.js +454 -0
- package/dist/tunnel/manager-panel.js +249 -0
- package/dist/tunnel/manager-ui.js +341 -0
- package/dist/tunnel/manager.js +372 -0
- package/dist/tunnel/messaging-activation-ui.js +85 -0
- package/dist/tunnel/messaging-config.js +246 -0
- package/dist/tunnel/multi-session-admission.js +31 -0
- package/dist/tunnel/multi-session-policy.js +314 -0
- package/dist/tunnel/offline-client.js +104 -0
- package/dist/tunnel/profile.js +319 -0
- package/dist/tunnel/redact.js +9 -0
- package/dist/tunnel/secure-input.js +318 -0
- package/dist/tunnel/session-process-mutex.js +338 -0
- package/dist/tunnel/setup-ui.js +443 -0
- package/dist/tunnel/setup.js +734 -0
- package/dist/tunnel/state.js +127 -0
- package/native/tunnel-keychain.swift +432 -0
- package/package.json +65 -4
- package/pi-extension/allowlist.example.json +11 -0
- package/pi-extension/index.ts +2346 -0
- package/pi-extension/multi-session-commands.ts +93 -0
- package/pi-extension/multi-session-runtime.ts +75 -0
- package/pi-extension/tui-keys.ts +40 -0
- package/scripts/reconcile-session-process-mutex.mjs +262 -0
- package/scripts/recover-stale-ownership.mjs +91 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HANDOFF-CE-HOST-09 B1.1 Task 3 — bundled OFFLINE FAKE tunnel client.
|
|
3
|
+
*
|
|
4
|
+
* This process is a simulator, not a transport. It opens no socket, performs no
|
|
5
|
+
* network or control-plane call, reads no credential, and never receives one:
|
|
6
|
+
* the manager starts it without any secret at all. Every emitted record is
|
|
7
|
+
* explicitly labelled `simulated: true`, so no status derived from it may be
|
|
8
|
+
* read as a real connection, delivery, ACK, or completion.
|
|
9
|
+
*
|
|
10
|
+
* Protocol (fixed, newline-delimited JSON on stdout only):
|
|
11
|
+
* {"event":"ready", "runId":…,"pid":…,"simulated":true}
|
|
12
|
+
* {"event":"health", "runId":…,"pid":…,"sequence":n,"simulated":true,
|
|
13
|
+
* "payload":{ … the measured healthy health-probe shape, simulated … }}
|
|
14
|
+
* {"event":"activity","runId":…,"pid":…,"kind":"simulated-request",
|
|
15
|
+
* "simulated":true}
|
|
16
|
+
*
|
|
17
|
+
* `runId` and `pid` exist so the manager can correlate every record with the
|
|
18
|
+
* run it actually owns; records that do not match are discarded by the manager.
|
|
19
|
+
* SIGTERM/SIGINT stop the simulator with exit code 0.
|
|
20
|
+
*/
|
|
21
|
+
import { fileURLToPath } from "node:url";
|
|
22
|
+
const RUN_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
23
|
+
/** Fixed argv parsing: only the flags this simulator defines are accepted. */
|
|
24
|
+
export function parseOfflineClientArgs(argv) {
|
|
25
|
+
let runId;
|
|
26
|
+
let healthIntervalMs = 500;
|
|
27
|
+
let simulateActivity = false;
|
|
28
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
29
|
+
const flag = argv[index];
|
|
30
|
+
if (flag === "--run-id") {
|
|
31
|
+
runId = argv[index + 1];
|
|
32
|
+
index += 1;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (flag === "--health-interval-ms") {
|
|
36
|
+
healthIntervalMs = Number(argv[index + 1]);
|
|
37
|
+
index += 1;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (flag === "--simulate-activity") {
|
|
41
|
+
simulateActivity = true;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
if (runId === undefined || !RUN_ID_PATTERN.test(runId))
|
|
47
|
+
return undefined;
|
|
48
|
+
if (!Number.isSafeInteger(healthIntervalMs) || healthIntervalMs < 10 || healthIntervalMs > 60_000)
|
|
49
|
+
return undefined;
|
|
50
|
+
return Object.freeze({ runId, healthIntervalMs, simulateActivity });
|
|
51
|
+
}
|
|
52
|
+
/** The simulated health document. Mirrors the measured healthy shape. */
|
|
53
|
+
export function simulatedHealthPayload(sequence) {
|
|
54
|
+
return {
|
|
55
|
+
simulated: true,
|
|
56
|
+
result: "ok",
|
|
57
|
+
healthz: { ok: true, status: 200, body: "live" },
|
|
58
|
+
readyz: { ok: true, status: 200, body: "ready" },
|
|
59
|
+
process: { running: true },
|
|
60
|
+
request_count: sequence,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function emit(record) {
|
|
64
|
+
process.stdout.write(`${JSON.stringify(record)}\n`);
|
|
65
|
+
}
|
|
66
|
+
export function runOfflineClient(options) {
|
|
67
|
+
const pid = process.pid;
|
|
68
|
+
const base = { runId: options.runId, pid, simulated: true };
|
|
69
|
+
emit({ event: "ready", ...base });
|
|
70
|
+
let sequence = 0;
|
|
71
|
+
const timer = setInterval(() => {
|
|
72
|
+
sequence += 1;
|
|
73
|
+
emit({ event: "health", ...base, sequence, payload: simulatedHealthPayload(sequence) });
|
|
74
|
+
if (options.simulateActivity)
|
|
75
|
+
emit({ event: "activity", ...base, kind: "simulated-request" });
|
|
76
|
+
}, options.healthIntervalMs);
|
|
77
|
+
const stop = () => {
|
|
78
|
+
clearInterval(timer);
|
|
79
|
+
process.exit(0);
|
|
80
|
+
};
|
|
81
|
+
process.on("SIGTERM", stop);
|
|
82
|
+
process.on("SIGINT", stop);
|
|
83
|
+
}
|
|
84
|
+
function isEntryPoint() {
|
|
85
|
+
const entry = process.argv[1];
|
|
86
|
+
if (entry === undefined)
|
|
87
|
+
return false;
|
|
88
|
+
try {
|
|
89
|
+
return fileURLToPath(import.meta.url) === entry;
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (isEntryPoint()) {
|
|
96
|
+
const options = parseOfflineClientArgs(process.argv.slice(2));
|
|
97
|
+
if (options === undefined) {
|
|
98
|
+
// Fixed, content-free refusal: this simulator accepts only its own flags.
|
|
99
|
+
process.stdout.write(`${JSON.stringify({ event: "refused", simulated: true })}\n`);
|
|
100
|
+
process.exit(2);
|
|
101
|
+
}
|
|
102
|
+
runOfflineClient(options);
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=offline-client.js.map
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HANDOFF-CE-HOST-09 B1 — operator-owned tunnel profile construction,
|
|
3
|
+
* minimal child environment, and credential source gating.
|
|
4
|
+
*
|
|
5
|
+
* This module writes no file, reads no environment, and never touches a
|
|
6
|
+
* credential value: it returns structures a caller may serialize. The CE MCP
|
|
7
|
+
* binding is NOT produced here — the frozen 9-key binding validator rejects a
|
|
8
|
+
* top-level `tunnel` field, so the two configurations stay in separate files
|
|
9
|
+
* by construction.
|
|
10
|
+
*
|
|
11
|
+
* The admin UI section is emitted as the canonical minimal subset the real
|
|
12
|
+
* `tunnel-client` 0.0.16 accepts: `open_browser` only. The client rejects the
|
|
13
|
+
* nested `allow_remote_ui` key (it is a top-level flag, not an `admin_ui`
|
|
14
|
+
* member) and rejects `log_buffer_events: 0` (it must be > 0); both were
|
|
15
|
+
* removed to match the real schema. Remote UI stays disabled by default, and
|
|
16
|
+
* the profile carries an explicit acknowledgement flag for the operator
|
|
17
|
+
* documentation rather than an unfounded safety claim.
|
|
18
|
+
*/
|
|
19
|
+
import { isAbsolute, join, normalize } from "node:path";
|
|
20
|
+
import { TunnelRefusal } from "./codes.js";
|
|
21
|
+
import { APPROVED_NODE_VERSION } from "../storage/runtime.js";
|
|
22
|
+
/** Configuration-shaped refusal for profile construction. */
|
|
23
|
+
export class TunnelConfigError extends TunnelRefusal {
|
|
24
|
+
constructor(field) {
|
|
25
|
+
super("CE_TUNNEL_PROFILE_INVALID", field);
|
|
26
|
+
this.name = "TunnelConfigError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const TUNNEL_ID_PATTERN = /^tunnel_[A-Za-z0-9]{8,}$/;
|
|
30
|
+
const CREDENTIAL_SHAPED = /(sk-[A-Za-z0-9_-]{8,})|(cap_[0-9a-f]{16,})|(BEGIN [A-Z ]*PRIVATE KEY)/i;
|
|
31
|
+
// Exact CE stdio argv, single-space separators, narrow ASCII paths. Space-
|
|
32
|
+
// bearing paths use single quotes; expansions, metacharacters and escapes are
|
|
33
|
+
// never accepted. This encoding is safe for a shell and for quote-aware argv
|
|
34
|
+
// splitters. R5 Lane A F1: a space-bearing path may not contain a segment that
|
|
35
|
+
// starts with '-', so even a naive whitespace split cannot forge an option.
|
|
36
|
+
// `@` is admitted ONLY as an ordinary absolute-path character so a normally
|
|
37
|
+
// scoped npm install (node_modules/@scope/pkg) can express its real runtime
|
|
38
|
+
// paths; absolute-path, normalization, quoting and argv rules are unchanged.
|
|
39
|
+
const COMMAND_PATH = /^\/[A-Za-z0-9_./@ -]+$/;
|
|
40
|
+
function isCommandPath(path) {
|
|
41
|
+
if (!COMMAND_PATH.test(path))
|
|
42
|
+
return false;
|
|
43
|
+
return !path.includes(" ") || !path.split(" ").some((segment) => segment.startsWith("-"));
|
|
44
|
+
}
|
|
45
|
+
export function parseTunnelMcpCommand(command) {
|
|
46
|
+
const field = "mcp.commands.0.command";
|
|
47
|
+
if (typeof command !== "string" || CREDENTIAL_SHAPED.test(command))
|
|
48
|
+
throw new TunnelConfigError(field);
|
|
49
|
+
const tokens = command.match(/'[^']*'|[^ ']+/g) ?? [];
|
|
50
|
+
if (tokens.join(" ") !== command)
|
|
51
|
+
throw new TunnelConfigError(field);
|
|
52
|
+
// Quoting is permitted only where required to encode a space-bearing path.
|
|
53
|
+
// Keep the pre-existing canonical grammar for flags and ordinary paths.
|
|
54
|
+
if (tokens.some((token, index) => token.startsWith("'") &&
|
|
55
|
+
(![0, 1, 3].includes(index) || !token.includes(" "))))
|
|
56
|
+
throw new TunnelConfigError(field);
|
|
57
|
+
const argv = tokens.map((token) => token.startsWith("'") ? token.slice(1, -1) : token);
|
|
58
|
+
if (argv.length !== 4 && argv.length !== 6)
|
|
59
|
+
throw new TunnelConfigError(field);
|
|
60
|
+
const [executable, script, configFlag, configPath, channelFlag, channel] = argv;
|
|
61
|
+
for (const path of [executable, script, configPath]) {
|
|
62
|
+
if (path === undefined || !isCommandPath(path))
|
|
63
|
+
throw new TunnelConfigError(field);
|
|
64
|
+
absolutePath(path, field);
|
|
65
|
+
}
|
|
66
|
+
if (!executable?.endsWith("/node") || !script?.endsWith("/mcp-stdio.js") || configFlag !== "--config") {
|
|
67
|
+
throw new TunnelConfigError(field);
|
|
68
|
+
}
|
|
69
|
+
if (argv.length === 6 && (channelFlag !== "--channel" || channel !== "main"))
|
|
70
|
+
throw new TunnelConfigError(field);
|
|
71
|
+
return { nodePath: executable, scriptPath: script, bindingPath: configPath };
|
|
72
|
+
}
|
|
73
|
+
export function buildTunnelMcpCommand(input) {
|
|
74
|
+
const quote = (path) => {
|
|
75
|
+
if (!isCommandPath(path))
|
|
76
|
+
throw new TunnelConfigError("mcp.commands.0.command");
|
|
77
|
+
absolutePath(path, "mcp.commands.0.command");
|
|
78
|
+
return path.includes(" ") ? `'${path}'` : path;
|
|
79
|
+
};
|
|
80
|
+
const command = `${quote(input.nodePath)} ${quote(input.scriptPath)} --config ${quote(input.bindingPath)}`;
|
|
81
|
+
parseTunnelMcpCommand(command);
|
|
82
|
+
return command;
|
|
83
|
+
}
|
|
84
|
+
/** Change only argv's config-path token. Existing executable/script quoting,
|
|
85
|
+
* config flag and optional --channel main tokens remain byte-identical. */
|
|
86
|
+
export function replaceTunnelMcpBindingPath(command, bindingPath) {
|
|
87
|
+
const existing = parseTunnelMcpCommand(command);
|
|
88
|
+
const encoded = buildTunnelMcpCommand({ nodePath: existing.nodePath, scriptPath: existing.scriptPath, bindingPath });
|
|
89
|
+
const tokens = command.match(/'[^']*'|[^ ']+/g);
|
|
90
|
+
tokens[3] = encoded.match(/'[^']*'|[^ ']+/g)[3];
|
|
91
|
+
const next = tokens.join(" ");
|
|
92
|
+
parseTunnelMcpCommand(next);
|
|
93
|
+
return next;
|
|
94
|
+
}
|
|
95
|
+
/** Change only argv's node-executable token. Script path, binding path, and
|
|
96
|
+
* the optional --channel main token remain byte-identical. */
|
|
97
|
+
export function replaceTunnelMcpNodePath(command, nodePath) {
|
|
98
|
+
const existing = parseTunnelMcpCommand(command);
|
|
99
|
+
const rebuilt = buildTunnelMcpCommand({ nodePath, scriptPath: existing.scriptPath, bindingPath: existing.bindingPath });
|
|
100
|
+
const tokens = command.match(/'[^']*'|[^ ']+/g);
|
|
101
|
+
tokens[0] = rebuilt.match(/'[^']*'|[^ ']+/g)[0];
|
|
102
|
+
const next = tokens.join(" ");
|
|
103
|
+
parseTunnelMcpCommand(next);
|
|
104
|
+
return next;
|
|
105
|
+
}
|
|
106
|
+
/** Pure validation, shared by the wizard adapter and the persistence layer. */
|
|
107
|
+
export function validateTunnelIdentity(tunnelId, organizationId) {
|
|
108
|
+
if (typeof tunnelId !== "string" || !TUNNEL_ID_PATTERN.test(tunnelId))
|
|
109
|
+
throw new TunnelConfigError("control_plane.tunnel_id");
|
|
110
|
+
if (organizationId !== undefined && organizationId !== "" &&
|
|
111
|
+
(typeof organizationId !== "string" || !/^org-[A-Za-z0-9]{1,128}$/.test(organizationId))) {
|
|
112
|
+
throw new TunnelConfigError("control_plane.organization_id");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** Only canonical, credential-free HTTPS may be serialized into the profile. */
|
|
116
|
+
function validateControlPlaneUrl(value) {
|
|
117
|
+
const field = "control_plane.base_url";
|
|
118
|
+
let url;
|
|
119
|
+
try {
|
|
120
|
+
url = new URL(value);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
throw new TunnelConfigError(field);
|
|
124
|
+
}
|
|
125
|
+
if (url.protocol !== "https:" || url.hostname === "" || url.username !== "" || url.password !== "" ||
|
|
126
|
+
value.includes("?") || value.includes("#") ||
|
|
127
|
+
(value !== url.href && !(value === url.origin && url.href === `${url.origin}/`))) {
|
|
128
|
+
throw new TunnelConfigError(field);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function absolutePath(value, field) {
|
|
132
|
+
if (typeof value !== "string" || value.length === 0 || value.includes("\u0000"))
|
|
133
|
+
throw new TunnelConfigError(field);
|
|
134
|
+
if (CREDENTIAL_SHAPED.test(value))
|
|
135
|
+
throw new TunnelConfigError(field);
|
|
136
|
+
if (!isAbsolute(value) || normalize(value) !== value)
|
|
137
|
+
throw new TunnelConfigError(field);
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
/** Build the profile. Every exposure switch is explicit; the key stays a reference. */
|
|
141
|
+
export function buildTunnelProfile(input) {
|
|
142
|
+
validateTunnelIdentity(input.tunnelId, input.organizationId);
|
|
143
|
+
const keyFile = absolutePath(input.keyFile, "control_plane.api_key");
|
|
144
|
+
const healthUrlFile = absolutePath(input.healthUrlFile, "health.url_file");
|
|
145
|
+
const command = input.mcpCommand;
|
|
146
|
+
parseTunnelMcpCommand(command);
|
|
147
|
+
const baseUrl = input.controlPlaneBaseUrl ?? "https://api.openai.com";
|
|
148
|
+
validateControlPlaneUrl(baseUrl);
|
|
149
|
+
return Object.freeze({
|
|
150
|
+
config_version: 1,
|
|
151
|
+
control_plane: Object.freeze({ base_url: baseUrl, tunnel_id: input.tunnelId,
|
|
152
|
+
...(input.organizationId ? { organization_id: input.organizationId } : {}), api_key: `file:${keyFile}` }),
|
|
153
|
+
health: Object.freeze({ listen_addr: "127.0.0.1:0", url_file: healthUrlFile }),
|
|
154
|
+
admin_ui: Object.freeze({ open_browser: false }),
|
|
155
|
+
harpoon: Object.freeze({ capture_payloads: false }),
|
|
156
|
+
log: Object.freeze({ level: "info", format: "json", http_raw_unsafe: false }),
|
|
157
|
+
mcp: Object.freeze({ commands: Object.freeze([Object.freeze({ channel: "main", command })]) }),
|
|
158
|
+
localUiExposureAcknowledged: true,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** Serialize exactly the strict YAML subset accepted by the manager/client.
|
|
162
|
+
* The acknowledgement is CE metadata, not a tunnel-client configuration key. */
|
|
163
|
+
export function serializeTunnelProfile(profile) {
|
|
164
|
+
const scalar = (value) => {
|
|
165
|
+
if (!/^[\x20\x21\x23-\x5B\x5D-\x7E]*$/.test(value))
|
|
166
|
+
throw new TunnelConfigError("profile.scalar");
|
|
167
|
+
return `"${value}"`;
|
|
168
|
+
};
|
|
169
|
+
return [
|
|
170
|
+
"config_version: 1", "control_plane:",
|
|
171
|
+
` base_url: ${scalar(profile.control_plane.base_url)}`,
|
|
172
|
+
` tunnel_id: ${scalar(profile.control_plane.tunnel_id)}`,
|
|
173
|
+
...(profile.control_plane.organization_id ? [` organization_id: ${scalar(profile.control_plane.organization_id)}`] : []),
|
|
174
|
+
` api_key: ${scalar(profile.control_plane.api_key)}`,
|
|
175
|
+
"health:", ` listen_addr: ${scalar(profile.health.listen_addr)}`, ` url_file: ${scalar(profile.health.url_file)}`,
|
|
176
|
+
"admin_ui:", " open_browser: false",
|
|
177
|
+
"harpoon:", " capture_payloads: false", "log:", " level: info", " format: json", " http_raw_unsafe: false",
|
|
178
|
+
"mcp:", " commands:", " - channel: main", ` command: ${scalar(profile.mcp.commands[0].command)}`, "",
|
|
179
|
+
].join("\n");
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* r2 (Lane A finding 5 / Lane B NOTE 2): an explicit ALLOWLIST, not a denylist.
|
|
183
|
+
* Only variables the official client actually needs to locate its binaries
|
|
184
|
+
* and temp directory are passed through; every other inherited variable —
|
|
185
|
+
* including any `*_TOKEN`/`*_KEY` never enumerated here — is dropped.
|
|
186
|
+
* This function never adds a credential: the key reaches the client only via
|
|
187
|
+
* the profile's `file:` reference.
|
|
188
|
+
*/
|
|
189
|
+
const ALLOWED_ENV_PATTERN = /^(PATH|HOME|TMPDIR|LANG|LC_[A-Z_]+|TZ|TERM|SSL_CERT_FILE|SSL_CERT_DIR)$/;
|
|
190
|
+
export function childEnvironment(source) {
|
|
191
|
+
const env = {};
|
|
192
|
+
for (const [name, value] of Object.entries(source)) {
|
|
193
|
+
if (ALLOWED_ENV_PATTERN.test(name))
|
|
194
|
+
env[name] = value;
|
|
195
|
+
}
|
|
196
|
+
return env;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Decide where a credential comes from and whether it may legally reach the
|
|
200
|
+
* official client. The client accepts only `file:`/`env:` references, so a
|
|
201
|
+
* keychain-held secret requires a plaintext hand-off; that hand-off stays
|
|
202
|
+
* BLOCKED unless the operator explicitly authorizes it.
|
|
203
|
+
*/
|
|
204
|
+
export function resolveCredentialPlan(situation) {
|
|
205
|
+
if (situation.keychainAvailable) {
|
|
206
|
+
return Object.freeze({
|
|
207
|
+
source: "keychain",
|
|
208
|
+
clientHandoff: situation.allowPlaintextTempFile === true ? "temp-file" : "blocked",
|
|
209
|
+
blockedCode: situation.allowPlaintextTempFile === true ? undefined : "CE_TUNNEL_CREDENTIAL_HANDOFF_BLOCKED",
|
|
210
|
+
warning: situation.allowPlaintextTempFile === true
|
|
211
|
+
? "temporary 0600 plaintext file exists between write and client read; residue is possible after SIGKILL"
|
|
212
|
+
: undefined,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
if (situation.keyFileExists) {
|
|
216
|
+
return Object.freeze({
|
|
217
|
+
source: "file",
|
|
218
|
+
clientHandoff: "file",
|
|
219
|
+
blockedCode: undefined,
|
|
220
|
+
warning: "credential is plaintext at rest in an operator-owned 0600 file",
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
return Object.freeze({
|
|
224
|
+
source: "none",
|
|
225
|
+
clientHandoff: "blocked",
|
|
226
|
+
blockedCode: "CE_TUNNEL_KEY_MISSING",
|
|
227
|
+
warning: undefined,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* T14: a key file must be a NON-empty, REGULAR (non-symlink) file, owned by
|
|
232
|
+
* the current operator, with owner-only permissions (0600 exactly).
|
|
233
|
+
*/
|
|
234
|
+
export function checkKeyFileRequirements(stat) {
|
|
235
|
+
if (stat.isSymbolicLink)
|
|
236
|
+
return { ok: false, code: "CE_TUNNEL_KEY_PERMS_INVALID", reason: "symbolic-link" };
|
|
237
|
+
if (stat.uid !== stat.ownerUid)
|
|
238
|
+
return { ok: false, code: "CE_TUNNEL_KEY_PERMS_INVALID", reason: "foreign-owner" };
|
|
239
|
+
if (!Number.isSafeInteger(stat.mode) || stat.mode < 0 || (stat.mode & 0o170000) !== 0o100000) {
|
|
240
|
+
return { ok: false, code: "CE_TUNNEL_KEY_PERMS_INVALID", reason: "not-regular-file" };
|
|
241
|
+
}
|
|
242
|
+
if (stat.mode !== 0o100600)
|
|
243
|
+
return { ok: false, code: "CE_TUNNEL_KEY_PERMS_INVALID", reason: "not-exact-0600" };
|
|
244
|
+
if (!Number.isSafeInteger(stat.size) || stat.size <= 0)
|
|
245
|
+
return { ok: false, code: "CE_TUNNEL_KEY_PERMS_INVALID", reason: "empty-or-invalid-size" };
|
|
246
|
+
return { ok: true };
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* T17: the two configuration sources must agree. An absent env override is
|
|
250
|
+
* clean (the profile is the single source of truth); a disagreement is a hard
|
|
251
|
+
* refusal because the operator could be about to connect the WRONG tunnel.
|
|
252
|
+
*/
|
|
253
|
+
export function detectConfigDrift(input) {
|
|
254
|
+
if (input.envTunnelId !== undefined && input.envTunnelId !== input.profileTunnelId) {
|
|
255
|
+
return { ok: false, code: "CE_TUNNEL_CONFIG_CONFLICT", reason: "env-profile-tunnel-id-mismatch" };
|
|
256
|
+
}
|
|
257
|
+
return { ok: true };
|
|
258
|
+
}
|
|
259
|
+
// ---------------------------------------------------------------------------
|
|
260
|
+
// REAL-START-FIX-01 — MCP child Node resolution and profile migration.
|
|
261
|
+
// The durable Store refuses any Node whose exact version, bundled SQLite
|
|
262
|
+
// version, and SQLite source id do not match the approved runtime (see
|
|
263
|
+
// storage/runtime.ts), so the mcp child must resolve to the approved Node —
|
|
264
|
+
// never blindly to the Pi process's own runtime when that differs.
|
|
265
|
+
// ---------------------------------------------------------------------------
|
|
266
|
+
/** @deprecated Default version for the legacy pure location hint, not eligibility.
|
|
267
|
+
* Actual host/child qualification uses storage/runtime.ts exact tuple registry. */
|
|
268
|
+
export const REQUIRED_MCP_NODE_VERSION = APPROVED_NODE_VERSION.replace(/^v/, "");
|
|
269
|
+
/** @deprecated Legacy pure location hint only, NOT executable admission or runtime
|
|
270
|
+
* qualification. Retained for compatibility; production setup uses
|
|
271
|
+
* runtime/executables.resolveApprovedNode and fails closed after full checks. */
|
|
272
|
+
export function resolveMcpNodePath(input) {
|
|
273
|
+
if (input.execVersion === `v${input.requiredVersion}` && input.execPath.length > 0)
|
|
274
|
+
return input.execPath;
|
|
275
|
+
const dataDir = input.env.MISE_DATA_DIR !== undefined && input.env.MISE_DATA_DIR !== ""
|
|
276
|
+
? input.env.MISE_DATA_DIR
|
|
277
|
+
: join(input.homeDir, ".local", "share", "mise");
|
|
278
|
+
const candidate = join(dataDir, "installs", "node", input.requiredVersion, "bin", "node");
|
|
279
|
+
return input.exists(candidate) ? candidate : undefined;
|
|
280
|
+
}
|
|
281
|
+
// The two admin_ui keys the real tunnel-client 0.0.16 rejects: `allow_remote_ui`
|
|
282
|
+
// (a top-level flag, not an admin_ui member) and `log_buffer_events: 0` (must
|
|
283
|
+
// be > 0). They are emitted with a fixed two-space indent by our generator.
|
|
284
|
+
const ADMIN_UI_ALLOW_REMOTE_LINE = /^ allow_remote_ui:[^\n]*\n?/m;
|
|
285
|
+
const ADMIN_UI_LOG_BUFFER_LINE = /^ log_buffer_events:[^\n]*\n?/m;
|
|
286
|
+
const MCP_COMMAND_LINE = /^ command: "([^"]*)"$/m;
|
|
287
|
+
/** True when a saved profile still carries a key the real client rejects. */
|
|
288
|
+
export function needsTunnelProfileMigration(text) {
|
|
289
|
+
return ADMIN_UI_ALLOW_REMOTE_LINE.test(text) || ADMIN_UI_LOG_BUFFER_LINE.test(text);
|
|
290
|
+
}
|
|
291
|
+
/** Rewrite a saved profile in place: drop the two rejected admin_ui keys and,
|
|
292
|
+
* when a node path is supplied, repoint the mcp command's node executable
|
|
293
|
+
* while preserving the script path, binding path, and --channel main token
|
|
294
|
+
* byte-for-byte. Never touches tunnel_id, organization_id, api_key, or any
|
|
295
|
+
* other line. */
|
|
296
|
+
export function migrateTunnelProfileText(text, opts = {}) {
|
|
297
|
+
let next = text;
|
|
298
|
+
let changed = false;
|
|
299
|
+
if (ADMIN_UI_ALLOW_REMOTE_LINE.test(next)) {
|
|
300
|
+
next = next.replace(ADMIN_UI_ALLOW_REMOTE_LINE, "");
|
|
301
|
+
changed = true;
|
|
302
|
+
}
|
|
303
|
+
if (ADMIN_UI_LOG_BUFFER_LINE.test(next)) {
|
|
304
|
+
next = next.replace(ADMIN_UI_LOG_BUFFER_LINE, "");
|
|
305
|
+
changed = true;
|
|
306
|
+
}
|
|
307
|
+
if (opts.nodePath !== undefined) {
|
|
308
|
+
const match = MCP_COMMAND_LINE.exec(next);
|
|
309
|
+
if (match !== null) {
|
|
310
|
+
const rebuilt = replaceTunnelMcpNodePath(match[1], opts.nodePath);
|
|
311
|
+
if (rebuilt !== match[1]) {
|
|
312
|
+
next = next.replace(MCP_COMMAND_LINE, () => ` command: "${rebuilt}"`);
|
|
313
|
+
changed = true;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return { text: next, changed };
|
|
318
|
+
}
|
|
319
|
+
//# sourceMappingURL=profile.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function redactChildOutput(input) {
|
|
2
|
+
const nonempty = input !== "";
|
|
3
|
+
return Object.freeze({
|
|
4
|
+
text: nonempty ? "[child output suppressed]" : "",
|
|
5
|
+
truncated: false,
|
|
6
|
+
appliedRules: Object.freeze(nonempty ? ["raw-output-suppressed"] : []),
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=redact.js.map
|