localmcp-cli 0.0.0-stage → 0.0.11

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.
@@ -0,0 +1,326 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { sendJson } from "./protocol.js";
3
+
4
+ function safeEqual(a, b) {
5
+ const left = Buffer.from(String(a ?? ""), "utf8");
6
+ const right = Buffer.from(String(b ?? ""), "utf8");
7
+ if (left.length !== right.length) return false;
8
+ return timingSafeEqual(left, right);
9
+ }
10
+
11
+ function htmlEscape(value) {
12
+ return String(value ?? "")
13
+ .replaceAll("&", "&")
14
+ .replaceAll("<", "&lt;")
15
+ .replaceAll(">", "&gt;")
16
+ .replaceAll('"', "&quot;")
17
+ .replaceAll("'", "&#39;");
18
+ }
19
+
20
+ function randomToken(bytes = 32) {
21
+ return randomBytes(bytes).toString("base64url");
22
+ }
23
+
24
+ function pkceChallenge(verifier) {
25
+ return createHash("sha256").update(verifier).digest("base64url");
26
+ }
27
+
28
+ async function readRequestBody(req, maxBytes = 65536) {
29
+ const chunks = [];
30
+ let total = 0;
31
+ for await (const chunk of req) {
32
+ total += chunk.length;
33
+ if (total > maxBytes) {
34
+ throw new Error("Request body too large.");
35
+ }
36
+ chunks.push(chunk);
37
+ }
38
+ return Buffer.concat(chunks).toString("utf8");
39
+ }
40
+
41
+ export function createAuthService({ config }) {
42
+ const oauthClients = new Map();
43
+ const oauthCodes = new Map();
44
+ const oauthTokens = new Map();
45
+
46
+ function isDirectLoopback(req) {
47
+ if (
48
+ req.headers["x-forwarded-for"] ||
49
+ req.headers["cf-connecting-ip"] ||
50
+ req.headers["x-real-ip"] ||
51
+ req.headers["forwarded"]
52
+ ) {
53
+ return false;
54
+ }
55
+ const addr = String(req.socket?.remoteAddress || "");
56
+ return addr === "127.0.0.1" || addr === "::1" || addr === "::ffff:127.0.0.1";
57
+ }
58
+
59
+ function extractSecretKey(req, url) {
60
+ const headerKey = req.headers["x-secret-key"];
61
+ if (typeof headerKey === "string" && headerKey.trim()) {
62
+ return headerKey.trim();
63
+ }
64
+ return String(url.searchParams.get("secret-key") || "").trim();
65
+ }
66
+
67
+ function hasValidSecretKey(req, url) {
68
+ const provided = extractSecretKey(req, url);
69
+ if (!provided || !config.state.secretKey) return false;
70
+ return safeEqual(provided, config.state.secretKey);
71
+ }
72
+
73
+ function extractBearerToken(req) {
74
+ const header = req.headers.authorization;
75
+ if (typeof header !== "string") return "";
76
+ const match = header.match(/^Bearer\s+(.+)$/i);
77
+ return match ? match[1].trim() : "";
78
+ }
79
+
80
+ function authenticateRequest(req, url) {
81
+ if (config.state.connectionMode === "local" && isDirectLoopback(req)) return { kind: "local", scope: "local.control" };
82
+ if (hasValidSecretKey(req, url)) {
83
+ return { kind: "secret-key", scope: "local.control" };
84
+ }
85
+ const token = extractBearerToken(req);
86
+ if (token) {
87
+ const record = oauthTokens.get(token);
88
+ if (record && record.expiresAt > Date.now()) {
89
+ return { kind: "oauth", scope: record.scope, clientId: record.clientId };
90
+ }
91
+ }
92
+ return { kind: "anonymous", scope: "" };
93
+ }
94
+
95
+ function requireReadAuth(authContext) {
96
+ if (authContext.kind === "anonymous" || (config.state.quickTunnel && authContext.kind !== "secret-key")) {
97
+ throw new Error("Read authorization required.");
98
+ }
99
+ }
100
+
101
+ function requireControlAuth(controlPin, authContext) {
102
+ if (authContext.kind === "secret-key" || authContext.kind === "local") return;
103
+ if (authContext.kind === "oauth" && String(authContext.scope || "").split(/\s+/).includes("local.control")) {
104
+ return;
105
+ }
106
+ if (config.hasConfiguredControlPin() && controlPin && safeEqual(controlPin, config.state.controlPin)) {
107
+ return;
108
+ }
109
+ throw new Error("Control authorization required (valid secret-key, OAuth local.control token, or control_pin).");
110
+ }
111
+
112
+ function requireCapability(flagName, enabled, controlPin, authContext) {
113
+ if (!enabled) {
114
+ throw new Error(`${flagName} is disabled in LocalMCP settings.`);
115
+ }
116
+ requireControlAuth(controlPin, authContext);
117
+ }
118
+
119
+ function publicOrigin(req) {
120
+ if (config.state.publicMcpUrl) {
121
+ try {
122
+ return new URL(config.state.publicMcpUrl).origin;
123
+ } catch {
124
+ // Fallback to request headers
125
+ }
126
+ }
127
+ const proto = String(req.headers["x-forwarded-proto"] || "http").split(",")[0].trim();
128
+ const host = String(req.headers["x-forwarded-host"] || req.headers.host || `127.0.0.1:${config.state.port}`)
129
+ .split(",")[0]
130
+ .trim();
131
+ return `${proto}://${host}`;
132
+ }
133
+
134
+ function protectedResourceMetadata(req) {
135
+ const origin = publicOrigin(req);
136
+ return {
137
+ resource: `${origin}${config.state.mcpPath}`,
138
+ authorization_servers: [origin],
139
+ scopes_supported: ["local.read", "local.control"],
140
+ bearer_methods_supported: ["header"],
141
+ };
142
+ }
143
+
144
+ function oauthMetadata(req) {
145
+ const origin = publicOrigin(req);
146
+ return {
147
+ issuer: origin,
148
+ authorization_response_iss_parameter_supported: true,
149
+ authorization_endpoint: `${origin}/oauth/authorize`,
150
+ token_endpoint: `${origin}/oauth/token`,
151
+ registration_endpoint: `${origin}/oauth/register`,
152
+ response_types_supported: ["code"],
153
+ grant_types_supported: ["authorization_code"],
154
+ code_challenge_methods_supported: ["S256"],
155
+ token_endpoint_auth_methods_supported: ["none"],
156
+ scopes_supported: ["local.read", "local.control"],
157
+ };
158
+ }
159
+
160
+ async function handleRegister(req, res) {
161
+ try {
162
+ const body = JSON.parse((await readRequestBody(req)) || "{}");
163
+ const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris.map(String) : [];
164
+ if (redirectUris.length === 0) {
165
+ sendJson(res, 400, { error: "invalid_client_metadata", error_description: "redirect_uris is required." });
166
+ return;
167
+ }
168
+ if (redirectUris.some(uri => {
169
+ try {
170
+ const url = new URL(uri);
171
+ return url.hash || url.username || url.password || !(url.protocol === "https:" ||
172
+ (url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)));
173
+ } catch { return true; }
174
+ })) {
175
+ sendJson(res, 400, { error: "invalid_redirect_uri" });
176
+ return;
177
+ }
178
+ const clientId = `lmcp_${randomToken(12)}`;
179
+ oauthClients.set(clientId, {
180
+ clientId,
181
+ clientName: String(body.client_name || "MCP Client"),
182
+ redirectUris,
183
+ });
184
+ sendJson(res, 201, {
185
+ client_id: clientId,
186
+ client_name: String(body.client_name || "MCP Client"),
187
+ redirect_uris: redirectUris,
188
+ token_endpoint_auth_method: "none",
189
+ });
190
+ } catch (error) {
191
+ sendJson(res, 400, { error: "invalid_request", error_description: error.message });
192
+ }
193
+ }
194
+
195
+ async function handleAuthorize(req, res, url) {
196
+ const submitted = req.method === "POST" ? new URLSearchParams(await readRequestBody(req)) : url.searchParams;
197
+ const clientId = String(submitted.get("client_id") || "");
198
+ const redirectUri = String(submitted.get("redirect_uri") || "");
199
+ const state = String(submitted.get("state") || "");
200
+ const codeChallenge = String(submitted.get("code_challenge") || "");
201
+ const codeChallengeMethod = String(submitted.get("code_challenge_method") || "S256");
202
+ const scope = String(submitted.get("scope") || "local.read local.control");
203
+ const approve = req.method === "POST" && submitted.get("approve") === "1";
204
+ const providedPin = String(submitted.get("pin") || "");
205
+
206
+ const client = oauthClients.get(clientId);
207
+ if (!client || !client.redirectUris.includes(redirectUri)) {
208
+ sendJson(res, 400, { error: "invalid_client", error_description: "Unknown client_id or redirect_uri." });
209
+ return;
210
+ }
211
+
212
+ if (!/^[A-Za-z0-9_-]{43}$/.test(codeChallenge) || codeChallengeMethod !== "S256") {
213
+ sendJson(res, 400, { error: "invalid_request" });
214
+ return;
215
+ }
216
+ if (approve) {
217
+ const approvalKey = config.hasConfiguredControlPin() ? config.state.controlPin : config.state.secretKey;
218
+ if (!safeEqual(providedPin, approvalKey)) {
219
+ sendJson(res, 403, { error: "access_denied" });
220
+ return;
221
+ }
222
+ const code = randomToken(24);
223
+ oauthCodes.set(code, {
224
+ clientId,
225
+ redirectUri,
226
+ codeChallenge,
227
+ codeChallengeMethod,
228
+ scope,
229
+ expiresAt: Date.now() + 5 * 60 * 1000,
230
+ });
231
+ const dest = new URL(redirectUri);
232
+ dest.searchParams.set("code", code);
233
+ dest.searchParams.set("iss", publicOrigin(req));
234
+ if (state) dest.searchParams.set("state", state);
235
+ res.writeHead(302, { Location: dest.toString() }).end();
236
+ return;
237
+ }
238
+
239
+ const pinInput = `<label>Local approval credential: <input type="password" name="pin" required /></label><br/>`;
240
+
241
+ const html = `<!doctype html><html><head><meta charset="utf-8"><title>LocalMCP Authorization</title></head>
242
+ <body style="font-family:system-ui,sans-serif;max-width:460px;margin:48px auto;padding:24px;">
243
+ <h2>Authorize ${htmlEscape(client.clientName)}</h2>
244
+ <p>Grant access to <strong>${htmlEscape(config.state.serverName)}</strong> (${htmlEscape(scope)}).</p>
245
+ <form method="POST" action="/oauth/authorize">
246
+ <input type="hidden" name="client_id" value="${htmlEscape(clientId)}" />
247
+ <input type="hidden" name="redirect_uri" value="${htmlEscape(redirectUri)}" />
248
+ <input type="hidden" name="state" value="${htmlEscape(state)}" />
249
+ <input type="hidden" name="code_challenge" value="${htmlEscape(codeChallenge)}" />
250
+ <input type="hidden" name="code_challenge_method" value="${htmlEscape(codeChallengeMethod)}" />
251
+ <input type="hidden" name="scope" value="${htmlEscape(scope)}" />
252
+ <input type="hidden" name="approve" value="1" />
253
+ ${pinInput}
254
+ <button type="submit" style="margin-top:12px;padding:8px 16px;">Approve</button>
255
+ </form></body></html>`;
256
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(html);
257
+ }
258
+
259
+ async function handleToken(req, res) {
260
+ try {
261
+ const raw = await readRequestBody(req);
262
+ const contentType = String(req.headers["content-type"] || "");
263
+ const params = contentType.includes("application/json")
264
+ ? new URLSearchParams(Object.entries(JSON.parse(raw || "{}")))
265
+ : new URLSearchParams(raw);
266
+
267
+ const grantType = params.get("grant_type");
268
+ const code = String(params.get("code") || "");
269
+ const clientId = String(params.get("client_id") || "");
270
+ const redirectUri = String(params.get("redirect_uri") || "");
271
+ const codeVerifier = String(params.get("code_verifier") || "");
272
+
273
+ if (grantType !== "authorization_code") {
274
+ sendJson(res, 400, { error: "unsupported_grant_type" });
275
+ return;
276
+ }
277
+
278
+ const record = oauthCodes.get(code);
279
+ oauthCodes.delete(code);
280
+ if (!record || record.expiresAt <= Date.now()) {
281
+ sendJson(res, 400, { error: "invalid_grant", error_description: "Code expired or invalid." });
282
+ return;
283
+ }
284
+ if (record.clientId !== clientId || record.redirectUri !== redirectUri) {
285
+ sendJson(res, 400, { error: "invalid_grant", error_description: "Client or redirect_uri mismatch." });
286
+ return;
287
+ }
288
+ if (record.codeChallenge && pkceChallenge(codeVerifier) !== record.codeChallenge) {
289
+ sendJson(res, 400, { error: "invalid_grant", error_description: "PKCE verification failed." });
290
+ return;
291
+ }
292
+
293
+ const accessToken = randomToken(32);
294
+ const ttl = Math.max(60, Number(config.state.oauthTokenTtlSeconds) || 86400);
295
+ oauthTokens.set(accessToken, {
296
+ clientId,
297
+ scope: record.scope,
298
+ expiresAt: Date.now() + ttl * 1000,
299
+ });
300
+
301
+ sendJson(res, 200, {
302
+ access_token: accessToken,
303
+ token_type: "Bearer",
304
+ expires_in: ttl,
305
+ scope: record.scope,
306
+ });
307
+ } catch (error) {
308
+ sendJson(res, 400, { error: "invalid_request", error_description: error.message });
309
+ }
310
+ }
311
+
312
+ return {
313
+ isDirectLoopback,
314
+ extractSecretKey,
315
+ hasValidSecretKey,
316
+ authenticateRequest,
317
+ requireReadAuth,
318
+ requireControlAuth,
319
+ requireCapability,
320
+ protectedResourceMetadata,
321
+ oauthMetadata,
322
+ handleRegister,
323
+ handleAuthorize,
324
+ handleToken,
325
+ };
326
+ }
@@ -0,0 +1,39 @@
1
+ import fs from "node:fs";
2
+
3
+ export const logLimit = 5 * 1024 * 1024;
4
+
5
+ function size(file) {
6
+ return fs.statSync(file, { throwIfNoEntry: false })?.size ?? 0;
7
+ }
8
+
9
+ export function boundExistingLog(file) {
10
+ if (size(file) > logLimit) {
11
+ fs.truncateSync(file, logLimit);
12
+ fs.renameSync(file, file + ".1");
13
+ } else if (size(file + ".1") > logLimit) {
14
+ fs.truncateSync(file + ".1", logLimit);
15
+ }
16
+ }
17
+
18
+ export function appendLog(file, data, { wholeRecord = false } = {}) {
19
+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data);
20
+ boundExistingLog(file);
21
+ if (wholeRecord && bytes.length > logLimit) return;
22
+ for (let offset = 0; offset < bytes.length; offset += logLimit) {
23
+ const chunk = bytes.subarray(offset, offset + logLimit);
24
+ if (size(file) + chunk.length > logLimit) fs.renameSync(file, file + ".1");
25
+ fs.appendFileSync(file, chunk, { mode: 0o600 });
26
+ }
27
+ }
28
+
29
+ export function redirectDaemonLog(file) {
30
+ boundExistingLog(file);
31
+ for (const stream of [process.stdout, process.stderr]) {
32
+ stream.write = (chunk, encoding, callback) => {
33
+ if (typeof encoding === "function") callback = encoding;
34
+ appendLog(file, typeof chunk === "string" ? Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8") : chunk);
35
+ if (callback) process.nextTick(callback);
36
+ return true;
37
+ };
38
+ }
39
+ }
@@ -0,0 +1,319 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { lstat, realpath } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import dotenv from "dotenv";
8
+ import { getStandardSkillCandidates } from "./context-discovery.js";
9
+
10
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
11
+ const PROJECT_ROOT = path.resolve(MODULE_DIR, "..", "..");
12
+
13
+ const DEFAULT_SAFE_EXECUTABLES = [
14
+ "pwd",
15
+ "ls",
16
+ "find",
17
+ "cat",
18
+ "head",
19
+ "tail",
20
+ "wc",
21
+ "du",
22
+ "df",
23
+ "ps",
24
+ "whoami",
25
+ "hostname",
26
+ "git",
27
+ "git.exe",
28
+ "node",
29
+ "node.exe",
30
+ "npm",
31
+ "npm.cmd",
32
+ "npx",
33
+ "npx.cmd",
34
+ "python",
35
+ "python.exe",
36
+ "python3",
37
+ "python3.exe",
38
+ "rg",
39
+ "rg.exe",
40
+ "sed",
41
+ "where",
42
+ "where.exe",
43
+ "ipconfig",
44
+ "tasklist",
45
+ ];
46
+
47
+ export function childEnvironment() {
48
+ const env = { ...process.env };
49
+ for (const key of Object.keys(env)) {
50
+ if (/^(SECRET_KEY|LOCAL_CONTROL_PIN|MCP_GUIDE_FILE|DOTENV_CONFIG_PATH|ELECTRON_RUN_AS_NODE|NODE_CHANNEL_FD|NODE_CHANNEL_SERIALIZATION_MODE)$/i.test(key)) delete env[key];
51
+ }
52
+ return env;
53
+ }
54
+
55
+ export function platformLabel(platform = process.platform) {
56
+ if (platform === "darwin") return "macOS";
57
+ if (platform === "win32") return "Windows";
58
+ return platform;
59
+ }
60
+
61
+ export function expandHome(inputPath) {
62
+ if (!inputPath) return inputPath;
63
+ if (inputPath === "~") return os.homedir();
64
+ if (inputPath.startsWith("~/") || inputPath.startsWith("~\\")) {
65
+ return path.join(os.homedir(), inputPath.slice(2));
66
+ }
67
+ return inputPath;
68
+ }
69
+
70
+ export function readPackageVersion() {
71
+ try {
72
+ const pkg = JSON.parse(readFileSync(path.join(PROJECT_ROOT, "package.json"), "utf8"));
73
+ return String(pkg.version || "0.0.10").trim() || "0.0.10";
74
+ } catch {
75
+ return "0.0.10";
76
+ }
77
+ }
78
+
79
+ export function resolveDefaultServerName(platform = process.platform) {
80
+ const host = String(os.hostname() || "").trim();
81
+ if (host) return `LocalMCP (${host})`;
82
+ return `LocalMCP (${platformLabel(platform)})`;
83
+ }
84
+
85
+ export function resolveServerName(rawValue, platform = process.platform) {
86
+ const custom = String(rawValue || "").trim();
87
+ return custom ? custom.slice(0, 80) : resolveDefaultServerName(platform);
88
+ }
89
+
90
+ export function isPathInside(root, target) {
91
+ const rel = path.relative(root, target);
92
+ return rel === "" || (rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel));
93
+ }
94
+
95
+ export function createRuntimeConfig({ cwd = process.cwd(), env = process.env } = {}) {
96
+ const platform = process.platform;
97
+ const envFilePath = env.DOTENV_CONFIG_PATH
98
+ ? path.resolve(cwd, env.DOTENV_CONFIG_PATH)
99
+ : path.join(cwd, ".env");
100
+
101
+ if (existsSync(envFilePath)) {
102
+ env = { ...dotenv.parse(readFileSync(envFilePath)), ...env };
103
+ }
104
+
105
+ const runtimeDir = env.LOCALMCP_RUNTIME_DIR || cwd;
106
+ const artifactDir = path.join(runtimeDir, ".mcp-artifacts");
107
+ const auditDir = path.join(runtimeDir, ".mcp-audit");
108
+ const guideFilePath = String(env.MCP_GUIDE_FILE || "").trim() || path.join(cwd, "GUIDE.md");
109
+ const version = readPackageVersion();
110
+
111
+ const resolveOrCreateSecretKey = () => {
112
+ const fromEnv = String(env.SECRET_KEY || "").trim();
113
+ if (fromEnv) return fromEnv;
114
+ const keyFile = path.join(artifactDir, "secret-key.txt");
115
+ if (existsSync(keyFile)) {
116
+ const stored = readFileSync(keyFile, "utf8").trim();
117
+ if (stored) return stored;
118
+ }
119
+ const generated = randomBytes(24).toString("hex");
120
+ mkdirSync(artifactDir, { recursive: true });
121
+ writeFileSync(keyFile, generated, { mode: 0o600 });
122
+ return generated;
123
+ };
124
+
125
+ const parseRoots = (rawValue) => {
126
+ const raw = String(rawValue ?? cwd);
127
+ const items = raw
128
+ .split(path.delimiter)
129
+ .map((entry) => entry.trim())
130
+ .filter(Boolean)
131
+ .map((entry) => path.resolve(cwd, expandHome(entry)));
132
+ return Array.from(new Set(items));
133
+ };
134
+
135
+ const parseSafeExecutables = (rawValue) => {
136
+ const source = rawValue ? String(rawValue).split(",") : DEFAULT_SAFE_EXECUTABLES;
137
+ return new Set(source.map((item) => item.trim()).filter(Boolean));
138
+ };
139
+
140
+ const state = {
141
+ cwd,
142
+ platform,
143
+ version,
144
+ startedAt: new Date(),
145
+ envFilePath,
146
+ artifactDir,
147
+ auditDir,
148
+ guideFilePath,
149
+ port: Number(env.PORT ?? 8787),
150
+ connectionMode: env.CONNECTION_MODE === "local" ? "local" : "tunnel",
151
+ primarySkillDir: expandHome(env.PRIMARY_SKILL_DIR || ""),
152
+ host: env.CONNECTION_MODE === "local" ? "127.0.0.1" : String(env.HOST ?? "127.0.0.1").trim() || "127.0.0.1",
153
+ mcpPath: String(env.MCP_PATH ?? "/mcp").trim() || "/mcp",
154
+ secretKey: resolveOrCreateSecretKey(),
155
+ publicMcpUrl: String(env.PUBLIC_MCP_URL ?? "").trim(),
156
+ quickTunnel: env.CONNECTION_MODE !== "local" && env.TUNNEL_MODE === "cloudflare",
157
+ serverName: resolveServerName(env.MCP_SERVER_NAME, platform),
158
+ allowedRoots: parseRoots(env.LOCAL_CONTROL_ROOTS),
159
+ allowWrites: env.ALLOW_WRITES === "1",
160
+ allowShell: env.ALLOW_SHELL === "1",
161
+ allowUnsafeShell: env.ALLOW_UNSAFE_SHELL === "1",
162
+ allowScreenshot: env.ALLOW_SCREENSHOT === "1",
163
+ allowOpen: env.ALLOW_OPEN === "1",
164
+ allowAppleScript: (env.ALLOW_APPLESCRIPT ?? (platform === "darwin" ? "1" : "0")) === "1",
165
+ allowGui: env.ALLOW_GUI === "1",
166
+ allowAgents: (env.ALLOW_AGENTS ?? "1") === "1",
167
+ controlPin: String(env.LOCAL_CONTROL_PIN ?? ""),
168
+ requireOAuthApprovalPin: env.OAUTH_REQUIRE_APPROVAL_PIN === "1",
169
+ oauthTokenTtlSeconds: Number(env.OAUTH_TOKEN_TTL_SECONDS ?? 86400),
170
+ maxCommandOutputChars: Number(env.MAX_COMMAND_OUTPUT_CHARS ?? 20000),
171
+ maxReadBytes: Number(env.MAX_READ_BYTES ?? 262144),
172
+ maxDirectoryEntries: Number(env.MAX_DIRECTORY_ENTRIES ?? 300),
173
+ commandTimeoutMs: Number(env.COMMAND_TIMEOUT_MS ?? 15000),
174
+ safeExecutables: parseSafeExecutables(env.SAFE_EXECUTABLES),
175
+ };
176
+
177
+ let lastEnvMtimeMs = -1;
178
+
179
+ function reload({ force = false } = {}) {
180
+ try {
181
+ if (!existsSync(state.envFilePath)) return false;
182
+ const mtimeMs = statSync(state.envFilePath).mtimeMs;
183
+ if (!force && mtimeMs === lastEnvMtimeMs) return false;
184
+ const parsed = dotenv.parse(readFileSync(state.envFilePath, "utf8"));
185
+ lastEnvMtimeMs = mtimeMs;
186
+
187
+ const pick = (key) => (Object.prototype.hasOwnProperty.call(parsed, key) ? parsed[key] : env[key]);
188
+ state.allowWrites = pick("ALLOW_WRITES") === "1";
189
+ state.allowShell = pick("ALLOW_SHELL") === "1";
190
+ state.allowUnsafeShell = pick("ALLOW_UNSAFE_SHELL") === "1";
191
+ state.allowScreenshot = pick("ALLOW_SCREENSHOT") === "1";
192
+ state.allowOpen = pick("ALLOW_OPEN") === "1";
193
+ state.allowAppleScript = (pick("ALLOW_APPLESCRIPT") ?? (platform === "darwin" ? "1" : "0")) === "1";
194
+ state.allowGui = pick("ALLOW_GUI") === "1";
195
+ state.allowAgents = (pick("ALLOW_AGENTS") ?? "1") === "1";
196
+ state.controlPin = String(pick("LOCAL_CONTROL_PIN") ?? "");
197
+ state.requireOAuthApprovalPin = pick("OAUTH_REQUIRE_APPROVAL_PIN") === "1";
198
+ state.publicMcpUrl = String(pick("PUBLIC_MCP_URL") ?? "").trim();
199
+ state.primarySkillDir = expandHome(pick("PRIMARY_SKILL_DIR") || "");
200
+ if (parsed.DESKTOP_PRIMARY_SKILL_DIR !== undefined) state.primarySkillDir = Buffer.from(parsed.DESKTOP_PRIMARY_SKILL_DIR, "base64").toString("utf8");
201
+ state.secretKey = pick("SECRET_KEY") || state.secretKey;
202
+ state.quickTunnel = state.connectionMode !== "local" && pick("TUNNEL_MODE") === "cloudflare";
203
+ state.serverName = resolveServerName(pick("MCP_SERVER_NAME"), platform);
204
+
205
+ if (pick("LOCAL_CONTROL_ROOTS") !== undefined) {
206
+ state.allowedRoots = parseRoots(pick("LOCAL_CONTROL_ROOTS"));
207
+ }
208
+ if (pick("SAFE_EXECUTABLES")) {
209
+ state.safeExecutables = parseSafeExecutables(pick("SAFE_EXECUTABLES"));
210
+ }
211
+ return true;
212
+ } catch {
213
+ return false;
214
+ }
215
+ }
216
+
217
+ function hasConfiguredControlPin() {
218
+ return Boolean(state.controlPin && state.controlPin !== "change-me-to-a-long-random-secret");
219
+ }
220
+
221
+ function getCapabilities() {
222
+ return {
223
+ writes: state.allowWrites,
224
+ shell: state.allowShell,
225
+ unsafeShell: state.allowUnsafeShell,
226
+ screenshot: state.allowScreenshot,
227
+ open: state.allowOpen,
228
+ appleScript: state.allowAppleScript,
229
+ gui: state.allowGui,
230
+ agents: state.allowAgents,
231
+ powerShell: platform === "win32",
232
+ readToolsRequireAuth: state.connectionMode !== "local",
233
+ oauth: state.connectionMode !== "local" && !state.quickTunnel,
234
+ pinFallbackForControl: hasConfiguredControlPin(),
235
+ };
236
+ }
237
+
238
+ async function canonicalizeGuidePath() {
239
+ if (!state.guideFilePath) return "";
240
+ try {
241
+ const parentReal = await realpath(path.dirname(state.guideFilePath));
242
+ return path.join(parentReal, path.basename(state.guideFilePath));
243
+ } catch {
244
+ return path.resolve(state.guideFilePath);
245
+ }
246
+ }
247
+
248
+ async function assertAllowedRealPath(candidateRealPath, { accessMode = "write" } = {}) {
249
+ const guideReal = await canonicalizeGuidePath();
250
+ if (guideReal && path.relative(guideReal, candidateRealPath) === "") {
251
+ return;
252
+ }
253
+
254
+ const extraReadRoots =
255
+ accessMode === "read"
256
+ ? [...getStandardSkillCandidates(), { dir: state.primarySkillDir }]
257
+ .map((item) => item.dir)
258
+ .filter((dir) => dir && existsSync(dir))
259
+ : [];
260
+
261
+ const resolvedRoots = await Promise.all(
262
+ [...state.allowedRoots, ...extraReadRoots].map(async (root) => {
263
+ try {
264
+ return await realpath(root);
265
+ } catch {
266
+ return root;
267
+ }
268
+ })
269
+ );
270
+ if (!resolvedRoots.some((root) => isPathInside(root, candidateRealPath))) {
271
+ throw new Error(`Path "${candidateRealPath}" is outside LOCAL_CONTROL_ROOTS.`);
272
+ }
273
+ }
274
+
275
+ function assertPublicPath(candidate) {
276
+ const parts = candidate.split(path.sep);
277
+ if (parts.some(part => /^(?:\.env(?:\..*)?|\.mcp-(?:audit|artifacts|logs))$/i.test(part)) ||
278
+ path.relative(state.envFilePath, candidate) === "") {
279
+ throw new Error("Private runtime path.");
280
+ }
281
+ }
282
+
283
+ async function resolveAllowedPath(inputPath, { mustExist = true, accessMode = "write" } = {}) {
284
+ const candidate = path.resolve(cwd, expandHome(inputPath || "."));
285
+ assertPublicPath(candidate);
286
+ if (mustExist) {
287
+ const real = await realpath(candidate);
288
+ assertPublicPath(real);
289
+ await assertAllowedRealPath(real, { accessMode });
290
+ return real;
291
+ }
292
+
293
+ let probe = candidate;
294
+ while (!(await lstat(probe).catch(error => {
295
+ if (error.code === "ENOENT") return null;
296
+ throw error;
297
+ }))) {
298
+ const parent = path.dirname(probe);
299
+ if (parent === probe) break;
300
+ probe = parent;
301
+ }
302
+ const realBase = await realpath(probe);
303
+ const finalPath = path.join(realBase, path.relative(probe, candidate));
304
+ assertPublicPath(finalPath);
305
+ await assertAllowedRealPath(finalPath, { accessMode });
306
+ return finalPath;
307
+ }
308
+
309
+ reload({ force: true });
310
+
311
+ return {
312
+ state,
313
+ reload,
314
+ hasConfiguredControlPin,
315
+ getCapabilities,
316
+ resolveAllowedPath,
317
+ assertPublicPath,
318
+ };
319
+ }