hmcp-gateway 0.0.2 → 0.2.0
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 +77 -0
- package/README.md +135 -9
- package/bin/hmcp-gateway.js +20 -0
- package/catalog/atlassian.yaml +41 -0
- package/catalog/brave-search.yaml +57 -0
- package/catalog/context7.yaml +42 -0
- package/catalog/fetch.yaml +37 -0
- package/catalog/figma.yaml +48 -0
- package/catalog/filesystem.yaml +48 -0
- package/catalog/git.yaml +48 -0
- package/catalog/github.yaml +103 -0
- package/catalog/huggingface.yaml +59 -0
- package/catalog/linear.yaml +47 -0
- package/catalog/memory.yaml +47 -0
- package/catalog/notion.yaml +41 -0
- package/catalog/playwright.yaml +38 -0
- package/catalog/postgres.yaml +66 -0
- package/catalog/sentry.yaml +39 -0
- package/catalog/sequential-thinking.yaml +29 -0
- package/catalog/stripe.yaml +41 -0
- package/catalog/supabase.yaml +45 -0
- package/catalog/time.yaml +49 -0
- package/dist/adopt-cli.d.ts +355 -0
- package/dist/adopt-cli.js +1885 -0
- package/dist/adopt-emit.d.ts +64 -0
- package/dist/adopt-emit.js +248 -0
- package/dist/adopt-plan.d.ts +108 -0
- package/dist/adopt-plan.js +501 -0
- package/dist/catalog.d.ts +140 -0
- package/dist/catalog.js +250 -0
- package/dist/classify.d.ts +23 -0
- package/dist/classify.js +47 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +656 -0
- package/dist/client-allow.d.ts +42 -0
- package/dist/client-allow.js +95 -0
- package/dist/client-config.d.ts +263 -0
- package/dist/client-config.js +995 -0
- package/dist/config-source.d.ts +106 -0
- package/dist/config-source.js +156 -0
- package/dist/config.d.ts +159 -0
- package/dist/config.js +330 -0
- package/dist/connect-client.d.ts +51 -0
- package/dist/connect-client.js +299 -0
- package/dist/contracts.d.ts +251 -0
- package/dist/contracts.js +9 -0
- package/dist/credential.d.ts +63 -0
- package/dist/credential.js +136 -0
- package/dist/desktop-extensions.d.ts +53 -0
- package/dist/desktop-extensions.js +126 -0
- package/dist/draft.d.ts +71 -0
- package/dist/draft.js +596 -0
- package/dist/exposure-cli.d.ts +28 -0
- package/dist/exposure-cli.js +119 -0
- package/dist/gateway.d.ts +766 -0
- package/dist/gateway.js +2122 -0
- package/dist/github-doors.d.ts +162 -0
- package/dist/github-doors.js +780 -0
- package/dist/guard-install.d.ts +109 -0
- package/dist/guard-install.js +396 -0
- package/dist/guard.d.ts +265 -0
- package/dist/guard.js +975 -0
- package/dist/import-client.d.ts +184 -0
- package/dist/import-client.js +578 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +31 -0
- package/dist/notify.d.ts +44 -0
- package/dist/notify.js +93 -0
- package/dist/oauth.d.ts +139 -0
- package/dist/oauth.js +641 -0
- package/dist/observe.d.ts +10 -0
- package/dist/observe.js +26 -0
- package/dist/open.d.ts +24 -0
- package/dist/open.js +31 -0
- package/dist/packs.d.ts +119 -0
- package/dist/packs.js +131 -0
- package/dist/pin-cli.d.ts +28 -0
- package/dist/pin-cli.js +103 -0
- package/dist/probe-upstream.d.ts +31 -0
- package/dist/probe-upstream.js +377 -0
- package/dist/registry-map.d.ts +39 -0
- package/dist/registry-map.js +390 -0
- package/dist/rule-cli.d.ts +51 -0
- package/dist/rule-cli.js +412 -0
- package/dist/serve-http.d.ts +67 -0
- package/dist/serve-http.js +478 -0
- package/dist/snippet.d.ts +20 -0
- package/dist/snippet.js +826 -0
- package/dist/status-cli.d.ts +61 -0
- package/dist/status-cli.js +195 -0
- package/dist/suggest-cli.d.ts +43 -0
- package/dist/suggest-cli.js +279 -0
- package/dist/toml-edit.d.ts +43 -0
- package/dist/toml-edit.js +363 -0
- package/dist/toolname.d.ts +47 -0
- package/dist/toolname.js +149 -0
- package/dist/upstream-errors.d.ts +54 -0
- package/dist/upstream-errors.js +330 -0
- package/dist/upstream.d.ts +128 -0
- package/dist/upstream.js +413 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.js +11 -0
- package/package.json +51 -6
- package/packs/brave-search.yaml +20 -0
- package/packs/context7.yaml +13 -0
- package/packs/fetch.yaml +14 -0
- package/packs/filesystem.yaml +79 -0
- package/packs/git.yaml +29 -0
- package/packs/github.yaml +47 -0
- package/packs/huggingface.yaml +16 -0
- package/packs/memory.yaml +23 -0
- package/packs/playwright.yaml +41 -0
- package/packs/sequential-thinking.yaml +13 -0
- package/packs/time.yaml +14 -0
|
@@ -0,0 +1,1885 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir, tmpdir } from "node:os";
|
|
3
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { parse as parseYaml } from "yaml";
|
|
6
|
+
import { defaultRegistryPath, defaultSecretsPath, SECRET_VALUE_PATTERNS, SecretStore, readRegistry, writeRegistry } from "hmcp-core";
|
|
7
|
+
import { toText } from "hmcp-scanner";
|
|
8
|
+
import { loadGatewayConfig } from "./config.js";
|
|
9
|
+
import { Gateway } from "./gateway.js";
|
|
10
|
+
import { backupPath, clientEditProblem, ClientConfigError, codexHomeNote, isRemote, parseServers, readBackup, readClientConfig, resolveScope, scopeTargets, tidyProjectBackups, wholeFileBackupPath, writeBackup, writeClientConfig, restoreClientConfig, sameJson, writeWholeFileBackup } from "./client-config.js";
|
|
11
|
+
import { planAdoption } from "./adopt-plan.js";
|
|
12
|
+
import { emitClientEntry, emitGatewayYaml, emitPolicyYaml } from "./adopt-emit.js";
|
|
13
|
+
import { applyPack, packFor } from "./packs.js";
|
|
14
|
+
import { VERSION } from "./version.js";
|
|
15
|
+
import { stableNodePath } from "./connect-client.js";
|
|
16
|
+
import { addAllowRule, allowRuleFor, clientSettingsPath, readClientSettings, removeAllowRule } from "./client-allow.js";
|
|
17
|
+
import { CLIENT_TOOL_NAME_LIMIT, clientToolName, toolNameBudget } from "./toolname.js";
|
|
18
|
+
/**
|
|
19
|
+
* Putting the gateway in front of the MCP servers a client already has.
|
|
20
|
+
*
|
|
21
|
+
* The gateway has always been able to do this; what it could not do was be
|
|
22
|
+
* installed. Doing it by hand means writing an upstream block per server with
|
|
23
|
+
* its exact command and environment, writing a policy, editing the client's
|
|
24
|
+
* own config to point at the gateway instead, and adding a row to the registry
|
|
25
|
+
* so the console can see it. Four files, and every one of them a chance to
|
|
26
|
+
* produce something that looks protected and is not.
|
|
27
|
+
*
|
|
28
|
+
* So the shape of this command is: say what it would do, then do it on
|
|
29
|
+
* `--apply`, and keep enough to undo it. The report is the important half. A
|
|
30
|
+
* gateway that refuses a tool the agent needed is a bad afternoon; a gateway
|
|
31
|
+
* that silently stopped passing a tool on, and nobody noticed, is the failure
|
|
32
|
+
* worth designing against.
|
|
33
|
+
*
|
|
34
|
+
* Factored out of `cli.ts` with an injected `write` so tests call it rather
|
|
35
|
+
* than shelling out, as `exposure-cli.ts` does.
|
|
36
|
+
*/
|
|
37
|
+
export class AdoptCommandError extends Error {
|
|
38
|
+
}
|
|
39
|
+
const DEFAULT_ENTRY_NAME = "hmcp";
|
|
40
|
+
const DEFAULT_GATEWAY_NAME = "claude-code";
|
|
41
|
+
function out(options) {
|
|
42
|
+
return options.write ?? ((line) => process.stdout.write(`${line}\n`));
|
|
43
|
+
}
|
|
44
|
+
/** The toolbox's default name for the app it is made for. */
|
|
45
|
+
function defaultNameFor(scope) {
|
|
46
|
+
if (scope === "project" || scope === "local" || scope === "user")
|
|
47
|
+
return DEFAULT_GATEWAY_NAME;
|
|
48
|
+
// "cursor-project" and "cursor-user" are both "cursor"; "copilot-cli" stays as it is.
|
|
49
|
+
return scope.replace(/-(project|user)$/, "");
|
|
50
|
+
}
|
|
51
|
+
/** Scopes that belong to the person rather than to one project folder. */
|
|
52
|
+
const USER_WIDE = new Set([
|
|
53
|
+
"user",
|
|
54
|
+
"claude-desktop",
|
|
55
|
+
"cursor-user",
|
|
56
|
+
"vscode-user",
|
|
57
|
+
"windsurf",
|
|
58
|
+
"copilot-cli",
|
|
59
|
+
"antigravity",
|
|
60
|
+
"devin",
|
|
61
|
+
"junie",
|
|
62
|
+
"codex"
|
|
63
|
+
]);
|
|
64
|
+
/** Where the generated pair lives for this scope. */
|
|
65
|
+
function generatedDir(target, options) {
|
|
66
|
+
if (options.outDir)
|
|
67
|
+
return resolve(options.outDir);
|
|
68
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
69
|
+
// A relative `policy:` resolves against the config's own directory, so a
|
|
70
|
+
// directory holding both is self-contained and can be moved as a unit.
|
|
71
|
+
if (target.scope === "user")
|
|
72
|
+
return join(dirname(target.path), ".hmcp", "claude-code");
|
|
73
|
+
/*
|
|
74
|
+
* An app's all-projects settings get a folder of their own under ~/.hmcp,
|
|
75
|
+
* not `<wherever the console runs>/.hmcp`: from the home folder that was
|
|
76
|
+
* ~/.hmcp itself, beside the console's own files.
|
|
77
|
+
*/
|
|
78
|
+
if (USER_WIDE.has(target.scope))
|
|
79
|
+
return join(options.home ?? homedir(), ".hmcp", options.name ?? defaultNameFor(target.scope));
|
|
80
|
+
/*
|
|
81
|
+
* A project's first toolbox is `<project>/.hmcp`. A second app connected
|
|
82
|
+
* for the same folder gets a folder of its own beside it, instead of
|
|
83
|
+
* replacing the toolbox the first app is still using (UT5): VS Code's
|
|
84
|
+
* servers vanished when Claude Code was connected for the same project.
|
|
85
|
+
*/
|
|
86
|
+
const shared = join(cwd, ".hmcp");
|
|
87
|
+
if (!toolboxInUse(join(shared, "gateway.yaml"), target, options))
|
|
88
|
+
return shared;
|
|
89
|
+
const name = options.name ?? defaultNameFor(target.scope);
|
|
90
|
+
for (const candidate of [name, `${name}-${target.scope}`]) {
|
|
91
|
+
const dir = join(shared, candidate);
|
|
92
|
+
if (!toolboxInUse(join(dir, "gateway.yaml"), target, options))
|
|
93
|
+
return dir;
|
|
94
|
+
}
|
|
95
|
+
return join(shared, `${name}-${target.scope}-${Date.now().toString(36)}`);
|
|
96
|
+
}
|
|
97
|
+
function readBackupQuietly(target) {
|
|
98
|
+
try {
|
|
99
|
+
return readBackup(target);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Whether another app is connected to the toolbox at `configPath`: an entry of
|
|
107
|
+
* ours in any other app's settings runs it with `-c <configPath>`, or the
|
|
108
|
+
* console has it registered for another app. An undo's "files kept" leftover
|
|
109
|
+
* is neither, and may be replaced; a toolbox in use never is.
|
|
110
|
+
*/
|
|
111
|
+
function toolboxInUse(configPath, target, options) {
|
|
112
|
+
if (!existsSync(configPath))
|
|
113
|
+
return false;
|
|
114
|
+
const scopeOptions = {
|
|
115
|
+
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
|
|
116
|
+
...(options.home !== undefined ? { home: options.home } : {})
|
|
117
|
+
};
|
|
118
|
+
const base = resolve(options.cwd ?? process.cwd());
|
|
119
|
+
for (const other of scopeTargets(scopeOptions)) {
|
|
120
|
+
if (other.scope === target.scope)
|
|
121
|
+
continue;
|
|
122
|
+
let servers;
|
|
123
|
+
try {
|
|
124
|
+
servers = readClientConfig(other.scope, scopeOptions).servers;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
for (const entry of Object.values(servers)) {
|
|
130
|
+
const args = entry?.args;
|
|
131
|
+
if (!Array.isArray(args))
|
|
132
|
+
continue;
|
|
133
|
+
const at = args.indexOf("-c");
|
|
134
|
+
const value = at >= 0 ? args[at + 1] : undefined;
|
|
135
|
+
if (typeof value === "string" && resolve(dirname(other.path), value) === configPath)
|
|
136
|
+
return true;
|
|
137
|
+
if (typeof value === "string" && resolve(base, value) === configPath)
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (options.register === false)
|
|
142
|
+
return false;
|
|
143
|
+
try {
|
|
144
|
+
const registry = readRegistry(options.registry ?? defaultRegistryPath());
|
|
145
|
+
const own = readBackupQuietly(target)?.registry_id;
|
|
146
|
+
return registry.servers.some((e) => e.config_path === configPath && e.id !== own);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function parseNameOverrides(pairs) {
|
|
153
|
+
const map = new Map();
|
|
154
|
+
for (const pair of pairs) {
|
|
155
|
+
const at = pair.indexOf("=");
|
|
156
|
+
if (at <= 0 || at === pair.length - 1) {
|
|
157
|
+
throw new AdoptCommandError(`--name expects <original>=<upstream>, not ${JSON.stringify(pair)}`);
|
|
158
|
+
}
|
|
159
|
+
map.set(pair.slice(0, at), pair.slice(at + 1));
|
|
160
|
+
}
|
|
161
|
+
return map;
|
|
162
|
+
}
|
|
163
|
+
/** This build's own `cli.js`, for the `--local` entry. */
|
|
164
|
+
function localCliPath() {
|
|
165
|
+
return fileURLToPath(new URL("./cli.js", import.meta.url));
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Whether this code is running from a source checkout rather than from an
|
|
169
|
+
* installed package. An installed copy always has `node_modules` on its path,
|
|
170
|
+
* including the one npx unpacks into its cache; a checkout's own files do not.
|
|
171
|
+
*/
|
|
172
|
+
function runningFromCheckout() {
|
|
173
|
+
return !localCliPath().split(/[\\/]/).includes("node_modules");
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* What the client is told to run.
|
|
177
|
+
*
|
|
178
|
+
* `--local` and `--pin` each say so outright. With neither, the answer
|
|
179
|
+
* follows where this command itself came from: an installed package pins its
|
|
180
|
+
* own version, so the client runs what the operator just ran; a checkout
|
|
181
|
+
* points at itself, because the alternative is an entry naming a package on
|
|
182
|
+
* the registry that is not this build -- and, before a release exists, is not
|
|
183
|
+
* there at all, so the client's gateway entry would simply fail to start.
|
|
184
|
+
*/
|
|
185
|
+
export function clientCommand(options) {
|
|
186
|
+
const local = options.local ?? (options.pinVersion === undefined && runningFromCheckout());
|
|
187
|
+
/*
|
|
188
|
+
* The stable spelling of this node (`/opt/homebrew/bin/node`), not the
|
|
189
|
+
* versioned Cellar folder it resolves to, which the next `brew upgrade node`
|
|
190
|
+
* deletes -- and with it the app's toolbox. The console's connect does the
|
|
191
|
+
* same.
|
|
192
|
+
*/
|
|
193
|
+
if (local)
|
|
194
|
+
return { command: stableNodePath(), args: [localCliPath()], local };
|
|
195
|
+
return { command: "npx", args: ["-y", `hmcp-gateway@${options.pinVersion ?? VERSION}`], local };
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Whether this client entry is a gateway of ours.
|
|
199
|
+
*
|
|
200
|
+
* By name and by what it runs, because the two can disagree: a user may rename
|
|
201
|
+
* the entry, and a stale entry from an older adoption may not use the name
|
|
202
|
+
* this run would pick.
|
|
203
|
+
*/
|
|
204
|
+
function isOurGateway(name, server, entryName) {
|
|
205
|
+
if (name === entryName)
|
|
206
|
+
return true;
|
|
207
|
+
if (isRemote(server))
|
|
208
|
+
return false;
|
|
209
|
+
return [server.command, ...server.args].some((w) => w.includes("hmcp-gateway") || w.endsWith("gateway/dist/cli.js"));
|
|
210
|
+
}
|
|
211
|
+
/** The `-c` path an existing gateway entry was pointed at. */
|
|
212
|
+
function configPathOf(server) {
|
|
213
|
+
if (isRemote(server))
|
|
214
|
+
return undefined;
|
|
215
|
+
const at = server.args.indexOf("-c");
|
|
216
|
+
const value = at >= 0 ? server.args[at + 1] : undefined;
|
|
217
|
+
return value === undefined ? undefined : resolve(value);
|
|
218
|
+
}
|
|
219
|
+
const REGISTRY_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
220
|
+
/**
|
|
221
|
+
* An id legal for a registry row.
|
|
222
|
+
*
|
|
223
|
+
* Deliberately not the upstream-name normalizer: a registry id may contain
|
|
224
|
+
* dashes and an upstream name may not, and sharing one function would quietly
|
|
225
|
+
* hold both to the stricter rule.
|
|
226
|
+
*/
|
|
227
|
+
function registryId(label, taken) {
|
|
228
|
+
let base = label
|
|
229
|
+
.normalize("NFC")
|
|
230
|
+
.toLowerCase()
|
|
231
|
+
.replace(/[^a-z0-9_-]+/g, "-")
|
|
232
|
+
.replace(/^-+|-+$/g, "");
|
|
233
|
+
if (!REGISTRY_ID.test(base))
|
|
234
|
+
base = `gateway-${base}`.slice(0, 64);
|
|
235
|
+
if (!REGISTRY_ID.test(base))
|
|
236
|
+
base = "gateway";
|
|
237
|
+
let candidate = base;
|
|
238
|
+
for (let n = 2; taken.has(candidate); n++)
|
|
239
|
+
candidate = `${base}-${n}`;
|
|
240
|
+
return candidate;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Starts every upstream once to ask what it offers, then throws it away.
|
|
244
|
+
*
|
|
245
|
+
* This is the only part of a dry run that is not free: it spawns each stdio
|
|
246
|
+
* server as a child process and dials each HTTP one. It also builds the audit
|
|
247
|
+
* log and approvals store, because a `Gateway` does that in its constructor,
|
|
248
|
+
* and a tool withheld for its name is audited during connect. Those records
|
|
249
|
+
* are genuinely this gateway's and are left where they belong rather than
|
|
250
|
+
* redirected somewhere temporary.
|
|
251
|
+
*
|
|
252
|
+
* `announceServing()` is deliberately not called. It publishes an inventory
|
|
253
|
+
* and claims a live pid, and a command that is about to exit must not leave a
|
|
254
|
+
* console believing a gateway is running.
|
|
255
|
+
*/
|
|
256
|
+
async function probe(configPath) {
|
|
257
|
+
const { config, policy: loaded } = loadGatewayConfig(configPath);
|
|
258
|
+
/*
|
|
259
|
+
* The look adopt takes keeps nothing. It used the real approvals store, so
|
|
260
|
+
* it pinned every tool as classified *before* the ready-made rules were
|
|
261
|
+
* written, and the first real run then saw "effect changed" on each tool a
|
|
262
|
+
* pack classifies: `status` reported tools changed since pinned on a
|
|
263
|
+
* brand-new install, while `pin list` (asking the running gateway) said
|
|
264
|
+
* nothing had. Its store and log live in the scratch folder, which is
|
|
265
|
+
* removed afterwards, and the gateway itself pins on its first real start.
|
|
266
|
+
*/
|
|
267
|
+
const scratch = dirname(configPath);
|
|
268
|
+
const policy = {
|
|
269
|
+
...loaded,
|
|
270
|
+
approvals: { ...loaded.approvals, store_path: join(scratch, "probe-approvals.sqlite") },
|
|
271
|
+
audit: { ...loaded.audit, path: join(scratch, "probe-audit.jsonl") }
|
|
272
|
+
};
|
|
273
|
+
const gateway = new Gateway({ config, policy, cwd: scratch });
|
|
274
|
+
try {
|
|
275
|
+
await gateway.connectUpstreams();
|
|
276
|
+
const tools = gateway.inventory().map((entry) => ({
|
|
277
|
+
localName: entry.localName,
|
|
278
|
+
upstream: entry.upstream.spec.name,
|
|
279
|
+
effect: entry.effect ?? null,
|
|
280
|
+
effectSource: entry.effectSource,
|
|
281
|
+
hidden: entry.hidden,
|
|
282
|
+
injection: entry.injection
|
|
283
|
+
}));
|
|
284
|
+
const scan = gateway.scanUpstreams();
|
|
285
|
+
return {
|
|
286
|
+
tools,
|
|
287
|
+
withheld: gateway.withheld(),
|
|
288
|
+
scanText: toText(scan, "upstream MCP servers"),
|
|
289
|
+
scan
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
finally {
|
|
293
|
+
await gateway.close().catch(() => undefined);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
function describePlan(plan, write, scope) {
|
|
297
|
+
if (plan.malformed.length > 0) {
|
|
298
|
+
write("");
|
|
299
|
+
write("Entries that did not parse, and were left alone:");
|
|
300
|
+
for (const bad of plan.malformed)
|
|
301
|
+
write(` ${bad.name}: ${bad.message}`);
|
|
302
|
+
}
|
|
303
|
+
write("");
|
|
304
|
+
write(`Will wrap ${plan.upstreams.length} server(s):`);
|
|
305
|
+
for (const planned of plan.upstreams) {
|
|
306
|
+
const renamed = planned.originalName === planned.upstream.name ? "" : ` (was "${planned.originalName}")`;
|
|
307
|
+
const how = planned.upstream.transport === "stdio"
|
|
308
|
+
? `stdio: ${planned.upstream.command} ${planned.upstream.args.join(" ")}`.trimEnd()
|
|
309
|
+
: `http: ${planned.upstream.url}`;
|
|
310
|
+
write(` ${planned.upstream.name}${renamed}`);
|
|
311
|
+
write(` ${how}`);
|
|
312
|
+
for (const warning of planned.warnings)
|
|
313
|
+
write(` note: ${warning}`);
|
|
314
|
+
}
|
|
315
|
+
if (plan.skipped.length > 0) {
|
|
316
|
+
write("");
|
|
317
|
+
write(`Will NOT wrap ${plan.skipped.length} server(s). These stay configured directly in the client:`);
|
|
318
|
+
for (const skip of plan.skipped) {
|
|
319
|
+
write(` ${skip.name}`);
|
|
320
|
+
write(` why: ${skip.reason}`);
|
|
321
|
+
write(` fix: ${skip.remedy}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (Object.keys(plan.gatewayEnv).length > 0) {
|
|
325
|
+
write("");
|
|
326
|
+
write("Environment moved onto the toolbox's own entry in your app, and passed on by name:");
|
|
327
|
+
for (const key of Object.keys(plan.gatewayEnv).sort())
|
|
328
|
+
write(` ${key}`);
|
|
329
|
+
if (scope !== undefined && !USER_WIDE.has(scope) && scope !== "local") {
|
|
330
|
+
write(" (in a project, whose settings file is often committed, a key among them goes into your locked keys instead)");
|
|
331
|
+
}
|
|
332
|
+
else {
|
|
333
|
+
write(" (the values stay in the client config they were already in; gateway.yaml holds none)");
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (plan.secretsOnDisk) {
|
|
337
|
+
write("");
|
|
338
|
+
write("--copy-env: a literal credential will be written into gateway.yaml. Do not commit it.");
|
|
339
|
+
}
|
|
340
|
+
if (plan.egressNeedsLocalHttp) {
|
|
341
|
+
write("");
|
|
342
|
+
write("--allow-local-http: egress.block_private_ips, allow_ip_literals and allow_http are");
|
|
343
|
+
write("set to permit loopback. That applies to every HTTP upstream of this gateway, not");
|
|
344
|
+
write("only the one that needed it.");
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
const WHY_ALLOW = "Without it you are asked twice about one call: the client asks whether it may call the gateway's tool, " +
|
|
348
|
+
"and then the gateway holds the call for approval. The gateway already decides every call to these " +
|
|
349
|
+
"tools, so the client's question adds a prompt and no protection.";
|
|
350
|
+
/**
|
|
351
|
+
* Decides whether the client allow rule is added, and refuses the one case
|
|
352
|
+
* where it must not be. Runs before anything is written, so a refusal or an
|
|
353
|
+
* unreadable settings file stops with nothing changed.
|
|
354
|
+
*/
|
|
355
|
+
async function clientAllowChoice(options, target, mode) {
|
|
356
|
+
const entryName = options.entryName ?? DEFAULT_ENTRY_NAME;
|
|
357
|
+
const path = clientSettingsPath(target, {
|
|
358
|
+
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
|
|
359
|
+
...(options.home !== undefined ? { home: options.home } : {})
|
|
360
|
+
});
|
|
361
|
+
const rule = allowRuleFor(entryName);
|
|
362
|
+
if (mode === "observe") {
|
|
363
|
+
if (options.clientAllow) {
|
|
364
|
+
throw new AdoptCommandError(`--client-allow cannot be used while the gateway is in observe mode. Observing enforces nothing, so ` +
|
|
365
|
+
`the client's own permission prompts are the only thing asking before a tool runs; allowing the ` +
|
|
366
|
+
`gateway's tools in the client would leave nothing asking at all. Use --mode enforce, or add the ` +
|
|
367
|
+
`rule after you switch enforcement on. Nothing was changed.`);
|
|
368
|
+
}
|
|
369
|
+
return { path, rule, add: false };
|
|
370
|
+
}
|
|
371
|
+
let add = options.clientAllow ?? false;
|
|
372
|
+
// Not asked again once it has been answered yes: a merge into a gateway that
|
|
373
|
+
// already has the rule has nothing to decide.
|
|
374
|
+
const already = readClientSettingsQuietly(path).includes(rule);
|
|
375
|
+
if (options.clientAllow === undefined && options.apply && options.ask && !already) {
|
|
376
|
+
const answer = (await options.ask(`Allow the gateway's tools in the client, so you are not asked twice?\n` +
|
|
377
|
+
` ${WHY_ALLOW}\n` +
|
|
378
|
+
` This adds ${JSON.stringify(rule)} to permissions.allow in ${path}.\n` +
|
|
379
|
+
`[yes] / no: `))
|
|
380
|
+
.trim()
|
|
381
|
+
.toLowerCase();
|
|
382
|
+
if (answer === "" || answer === "y" || answer === "yes")
|
|
383
|
+
add = true;
|
|
384
|
+
else if (answer === "n" || answer === "no")
|
|
385
|
+
add = false;
|
|
386
|
+
else
|
|
387
|
+
throw new AdoptCommandError(`expected yes or no, not ${JSON.stringify(answer)}. Nothing was changed.`);
|
|
388
|
+
}
|
|
389
|
+
if (add) {
|
|
390
|
+
try {
|
|
391
|
+
// Read now, so a file that cannot be edited stops before anything else is written.
|
|
392
|
+
readClientSettings(path);
|
|
393
|
+
}
|
|
394
|
+
catch (err) {
|
|
395
|
+
throw err instanceof ClientConfigError ? new AdoptCommandError(`${err.message} Nothing was changed.`) : err;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return { path, rule, add };
|
|
399
|
+
}
|
|
400
|
+
/** The rules already allowed in a settings file, or none if it cannot be read (which is reported later). */
|
|
401
|
+
function readClientSettingsQuietly(path) {
|
|
402
|
+
try {
|
|
403
|
+
return readClientSettings(path).permissions?.["allow"] ?? [];
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
return [];
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
/** Adds the rule if it was chosen, and says what happened either way. Returns what revert must undo. */
|
|
410
|
+
function applyClientAllow(choice, mode, write) {
|
|
411
|
+
write("");
|
|
412
|
+
if (mode === "observe") {
|
|
413
|
+
write("Your client's own permission prompts are untouched. While the gateway is only observing");
|
|
414
|
+
write("they are the only thing that asks before a tool runs, so they are left on. Once you");
|
|
415
|
+
write("switch enforcement on, `hmcp-gateway adopt --client-allow` stops you being asked twice.");
|
|
416
|
+
return undefined;
|
|
417
|
+
}
|
|
418
|
+
if (!choice.add && readClientSettingsQuietly(choice.path).includes(choice.rule)) {
|
|
419
|
+
write(`${JSON.stringify(choice.rule)} is already allowed in ${choice.path}, so the client does not ask about the gateway's tools.`);
|
|
420
|
+
return undefined;
|
|
421
|
+
}
|
|
422
|
+
if (!choice.add) {
|
|
423
|
+
write("Your client will still ask before calling the gateway's tools, and the gateway will then");
|
|
424
|
+
write("hold writes for approval, so you are asked twice about one call. To stop that, add");
|
|
425
|
+
write(` ${JSON.stringify(choice.rule)}`);
|
|
426
|
+
write(`to permissions.allow in ${choice.path}, or re-run with --client-allow.`);
|
|
427
|
+
return undefined;
|
|
428
|
+
}
|
|
429
|
+
const added = addAllowRule(choice.path, choice.rule);
|
|
430
|
+
if (!added) {
|
|
431
|
+
write(`${JSON.stringify(choice.rule)} is already allowed in ${choice.path}; nothing to add.`);
|
|
432
|
+
return undefined;
|
|
433
|
+
}
|
|
434
|
+
write(`Added ${JSON.stringify(choice.rule)} to permissions.allow in ${choice.path}`);
|
|
435
|
+
write(` ${WHY_ALLOW}`);
|
|
436
|
+
write(" From here the gateway is where calls to these tools are decided. `adopt --revert` removes the rule.");
|
|
437
|
+
return { path: choice.path, rule: choice.rule };
|
|
438
|
+
}
|
|
439
|
+
function describeProbe(result, starting, write) {
|
|
440
|
+
const { posture, mode, onUnclassified } = starting;
|
|
441
|
+
const byUpstream = new Map();
|
|
442
|
+
for (const tool of result.tools) {
|
|
443
|
+
const list = byUpstream.get(tool.upstream) ?? [];
|
|
444
|
+
list.push(tool);
|
|
445
|
+
byUpstream.set(tool.upstream, list);
|
|
446
|
+
}
|
|
447
|
+
write("");
|
|
448
|
+
write(`${result.tools.length} tool(s) across ${byUpstream.size} server(s):`);
|
|
449
|
+
for (const upstream of [...byUpstream.keys()].sort()) {
|
|
450
|
+
write("");
|
|
451
|
+
write(` ${upstream}`);
|
|
452
|
+
for (const tool of byUpstream.get(upstream)) {
|
|
453
|
+
const flags = [
|
|
454
|
+
tool.hidden ? "hidden" : null,
|
|
455
|
+
tool.injection ? `injection:${tool.injection.action}` : null
|
|
456
|
+
].filter(Boolean);
|
|
457
|
+
write(` ${tool.localName.padEnd(44)} ${(tool.effect ?? "unclassified").padEnd(13)} ` +
|
|
458
|
+
`(${tool.effectSource})${flags.length > 0 ? ` [${flags.join(", ")}]` : ""}`);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const unclassified = result.tools.filter((t) => t.effect === null && !t.hidden);
|
|
462
|
+
const held = result.tools.filter((t) => t.effect !== null && t.effect !== "read" && !t.hidden);
|
|
463
|
+
const injected = result.tools.filter((t) => t.injection !== null);
|
|
464
|
+
// Withheld by the gateway itself, which is given the limit in the config
|
|
465
|
+
// this probe ran with; picked out here because the remedy is specific.
|
|
466
|
+
const budget = toolNameBudget(starting.entryName);
|
|
467
|
+
const tooLong = result.withheld.filter((t) => t.localName.length > budget);
|
|
468
|
+
/*
|
|
469
|
+
* In observe mode nothing below happens yet, and saying "WILL BE REFUSED"
|
|
470
|
+
* about a gateway that will refuse nothing is the wrong thing to print in
|
|
471
|
+
* capitals. The mode is stated first, and each heading then says what
|
|
472
|
+
* enforcement *would* do.
|
|
473
|
+
*/
|
|
474
|
+
const when = mode === "observe" ? "ONCE ENFORCED, " : "";
|
|
475
|
+
if (mode === "observe") {
|
|
476
|
+
write("");
|
|
477
|
+
write("STARTING IN OBSERVE MODE -- nothing will be refused or held.");
|
|
478
|
+
write(" Every call runs, and is recorded with what the policy would have decided.");
|
|
479
|
+
write(" That lets you put the gateway in front of real work without breaking it.");
|
|
480
|
+
write(" It also means the policy protects nothing until you switch enforcement on;");
|
|
481
|
+
write(" the one thing still enforced is a tool you switch off.");
|
|
482
|
+
write(" To enforce from the first call instead, re-run with --mode enforce.");
|
|
483
|
+
}
|
|
484
|
+
if (unclassified.length > 0) {
|
|
485
|
+
write("");
|
|
486
|
+
if (onUnclassified === "deny") {
|
|
487
|
+
write(`${when}WILL BE REFUSED -- ${unclassified.length} tool(s) nothing could classify:`);
|
|
488
|
+
for (const tool of unclassified)
|
|
489
|
+
write(` ${tool.localName}`);
|
|
490
|
+
write(" `on_unclassified: deny` refuses these. policy.yaml carries a commented stub for");
|
|
491
|
+
write(" each one; uncomment it to classify that tool deliberately.");
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
write(`${when}WILL ASK FOR APPROVAL -- ${unclassified.length} tool(s) nothing could classify:`);
|
|
495
|
+
for (const tool of unclassified)
|
|
496
|
+
write(` ${tool.localName}`);
|
|
497
|
+
write(" Nothing says what these do, so each call asks. Say it once and the asking");
|
|
498
|
+
write(" stops: `hmcp approve <id> --classify read|write|destructive` when one is");
|
|
499
|
+
write(" waiting, or `hmcp-gateway rule <tool>` at any time.");
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if (held.length > 0) {
|
|
503
|
+
write("");
|
|
504
|
+
const verb = posture === "read-only" || posture === "locked" ? "WILL BE REFUSED" : "WILL ASK FOR APPROVAL";
|
|
505
|
+
write(`${when}${verb} -- ${held.length} tool(s) that mutate state:`);
|
|
506
|
+
for (const tool of held)
|
|
507
|
+
write(` ${tool.localName.padEnd(44)} ${tool.effect}`);
|
|
508
|
+
if (posture === "approve-writes") {
|
|
509
|
+
write(" Each call waits for a human: the client's own prompt where it supports one,");
|
|
510
|
+
write(" otherwise `hmcp pending` and `hmcp approve <id>`, or the console.");
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (injected.length > 0) {
|
|
514
|
+
write("");
|
|
515
|
+
write(`INJECTION FOUND in ${injected.length} upstream description(s):`);
|
|
516
|
+
for (const tool of injected) {
|
|
517
|
+
write(` ${tool.localName}: ${tool.injection.patternIds.join(", ")} -> ${tool.injection.action}`);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const unreadable = result.withheld.filter((t) => !tooLong.includes(t));
|
|
521
|
+
if (unreadable.length > 0) {
|
|
522
|
+
write("");
|
|
523
|
+
write(`WITHHELD -- ${unreadable.length} tool(s) the gateway will not pass on at all:`);
|
|
524
|
+
for (const tool of unreadable)
|
|
525
|
+
write(` ${tool.localName}: ${tool.reason}`);
|
|
526
|
+
write(" These never reach the agent, and a call to one is refused as though it did not");
|
|
527
|
+
write(" exist. The upstream still advertises them.");
|
|
528
|
+
}
|
|
529
|
+
if (tooLong.length > 0) {
|
|
530
|
+
write("");
|
|
531
|
+
write(`NAME TOO LONG -- ${tooLong.length} tool(s) will be withheld because the client could not send their names:`);
|
|
532
|
+
for (const tool of tooLong) {
|
|
533
|
+
const full = clientToolName(starting.entryName, tool.localName);
|
|
534
|
+
write(` ${full}`);
|
|
535
|
+
write(` ${full.length} characters; the model API accepts ${CLIENT_TOOL_NAME_LIMIT}.`);
|
|
536
|
+
}
|
|
537
|
+
write(" One name over the limit fails the whole request, not the one tool, so these are");
|
|
538
|
+
write(" withheld rather than served. Wrapping a server makes its names longer than they");
|
|
539
|
+
write(" were when it was used directly. To make room, shorten the prefix:");
|
|
540
|
+
for (const upstream of [...new Set(tooLong.map((t) => t.upstream))]) {
|
|
541
|
+
write(` --name ${upstream}=<shorter>`);
|
|
542
|
+
}
|
|
543
|
+
write(` --entry-name <shorter than "${starting.entryName}">`);
|
|
544
|
+
}
|
|
545
|
+
write("");
|
|
546
|
+
write(result.scanText.trimEnd());
|
|
547
|
+
if (result.scanText.includes("against a budget of")) {
|
|
548
|
+
// Said only when there is a budget finding to say it about: nothing in the
|
|
549
|
+
// gateway enforces the budget, so a reader should not take that finding
|
|
550
|
+
// for a thing that will refuse a call.
|
|
551
|
+
write("");
|
|
552
|
+
write("The tool_budget finding above is advisory. Nothing in the gateway enforces the");
|
|
553
|
+
write("budget; it reports that a tool set this size is hard for a human to review.");
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* The ready-made classification for each adopted server this build
|
|
558
|
+
* recognises, checked against what the server actually advertised.
|
|
559
|
+
*
|
|
560
|
+
* A filesystem write is bounded to the project directory: that is where the
|
|
561
|
+
* person is working, it is never wider than what the server itself allows,
|
|
562
|
+
* and it is a real absolute path in the written policy rather than something
|
|
563
|
+
* resolved later against a directory the reader cannot see.
|
|
564
|
+
*/
|
|
565
|
+
function packsFor(plan, probed, options) {
|
|
566
|
+
if (options.noPacks)
|
|
567
|
+
return [];
|
|
568
|
+
const advertised = probed.tools.map((t) => t.localName);
|
|
569
|
+
const out = [];
|
|
570
|
+
for (const planned of plan.upstreams) {
|
|
571
|
+
const upstream = planned.upstream;
|
|
572
|
+
if (upstream.transport !== "stdio")
|
|
573
|
+
continue;
|
|
574
|
+
const pack = packFor({ command: upstream.command, args: upstream.args });
|
|
575
|
+
if (!pack)
|
|
576
|
+
continue;
|
|
577
|
+
const applied = applyPack(pack, {
|
|
578
|
+
upstreamName: upstream.name,
|
|
579
|
+
namespace: true,
|
|
580
|
+
advertised,
|
|
581
|
+
within: folderGivenTo(upstream.args, options)
|
|
582
|
+
});
|
|
583
|
+
if (applied.rules.length === 0)
|
|
584
|
+
continue;
|
|
585
|
+
out.push({ ...applied, packName: pack.name, packLabel: pack.label, upstreamName: upstream.name });
|
|
586
|
+
}
|
|
587
|
+
return out;
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* A project's `.hmcp/` holds files written for this computer (its paths, its
|
|
591
|
+
* node, the backups of the app's settings), so it starts out ignored by git
|
|
592
|
+
* (UT5). Written once; a person who wants to share it edits or removes it.
|
|
593
|
+
*/
|
|
594
|
+
function keepOutOfGit(options) {
|
|
595
|
+
const path = join(resolve(options.cwd ?? process.cwd()), ".hmcp", ".gitignore");
|
|
596
|
+
if (existsSync(path))
|
|
597
|
+
return;
|
|
598
|
+
try {
|
|
599
|
+
writeFileSync(path, "# Written by hardened-mcp. These files are made for this computer (its folders and programs),\n" +
|
|
600
|
+
"# so they are kept out of git. Remove this file if you want to share the toolbox's settings.\n" +
|
|
601
|
+
"*\n", { encoding: "utf8" });
|
|
602
|
+
}
|
|
603
|
+
catch {
|
|
604
|
+
/* best effort: the toolbox works without it */
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
/** Where adopt keeps locked keys: the same file the console and the gateway read. */
|
|
608
|
+
function secretsPathFor(options) {
|
|
609
|
+
if (process.env.HMCP_SECRETS_FILE)
|
|
610
|
+
return process.env.HMCP_SECRETS_FILE;
|
|
611
|
+
return options.home !== undefined ? join(options.home, ".hmcp", "secrets.json") : defaultSecretsPath();
|
|
612
|
+
}
|
|
613
|
+
/** A locked-key name for one header or env setting of one server, unused or already holding this value. */
|
|
614
|
+
export function headerSecretName(store, upstream, header, value) {
|
|
615
|
+
const base = `${upstream}.${header.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "")}`.slice(0, 60);
|
|
616
|
+
for (let n = 1;; n++) {
|
|
617
|
+
const name = n === 1 ? base : `${base}-${n}`;
|
|
618
|
+
const entry = store.get(name);
|
|
619
|
+
if (entry === undefined || (entry.kind === "value" && entry.value === value))
|
|
620
|
+
return name;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
/** True when an env value is a key written out: a literal (not `${VAR}`) whose name or shape says so. */
|
|
624
|
+
export function isLiteralKey(name, value) {
|
|
625
|
+
if (typeof value !== "string" || value === "" || /\$\{[^}]*\}/.test(value))
|
|
626
|
+
return false;
|
|
627
|
+
return KEYISH_NAME.test(name) || SECRET_VALUE_PATTERNS.some((p) => p.regex.test(value));
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Moves every header value the plan marked as a key into the locked keys,
|
|
631
|
+
* and has gateway.yaml name it instead (`{secret: ..., prefix: "Bearer "}`).
|
|
632
|
+
* gateway.yaml is then free of secrets, as its header says, which matters
|
|
633
|
+
* most for a project scope, where it sits in the repository.
|
|
634
|
+
*
|
|
635
|
+
* In a project scope the same is done for a stdio server's env keys (R2
|
|
636
|
+
* round 4, R4-3). Elsewhere they move onto the toolbox's own entry in the
|
|
637
|
+
* app's settings and are passed on by name, which keeps them in the file
|
|
638
|
+
* they were already in; but a project's `.mcp.json` (or `.vscode/mcp.json`,
|
|
639
|
+
* `.cursor/mcp.json`) is a file people commit, so a key left there is a key
|
|
640
|
+
* in the repository. There, a literal env value that looks like a key goes
|
|
641
|
+
* into the locked keys and gateway.yaml names it as `{secret: ...}`; a `${VAR}`
|
|
642
|
+
* and a setting that is not a key (a folder, a log level) stay as they were.
|
|
643
|
+
*
|
|
644
|
+
* The client entry is told where the locked keys are, so the gateway the app
|
|
645
|
+
* starts reads the same file whatever HOME the app gives it.
|
|
646
|
+
*/
|
|
647
|
+
function lockHeaderSecrets(plan, options, write, target) {
|
|
648
|
+
const project = !USER_WIDE.has(target.scope) && target.scope !== "local";
|
|
649
|
+
const marked = plan.upstreams.filter((u) => (u.lockHeaders?.length ?? 0) > 0 && u.upstream.transport === "http");
|
|
650
|
+
const envKeys = project
|
|
651
|
+
? plan.upstreams.filter((u) => u.upstream.transport === "stdio" && u.upstream.pass_env.some((name) => isLiteralKey(name, plan.gatewayEnv[name])))
|
|
652
|
+
: [];
|
|
653
|
+
if (marked.length === 0 && envKeys.length === 0)
|
|
654
|
+
return plan;
|
|
655
|
+
const path = secretsPathFor(options);
|
|
656
|
+
const store = new SecretStore(path);
|
|
657
|
+
const now = new Date().toISOString();
|
|
658
|
+
const lockedEnv = new Set();
|
|
659
|
+
const lock = (upstream, setting, secret, label) => {
|
|
660
|
+
const name = headerSecretName(store, upstream, setting, secret);
|
|
661
|
+
const existing = store.get(name);
|
|
662
|
+
store.set(name, {
|
|
663
|
+
kind: "value",
|
|
664
|
+
value: secret,
|
|
665
|
+
label,
|
|
666
|
+
created_at: existing?.created_at ?? now,
|
|
667
|
+
updated_at: now
|
|
668
|
+
});
|
|
669
|
+
return name;
|
|
670
|
+
};
|
|
671
|
+
const upstreams = plan.upstreams.map((planned) => {
|
|
672
|
+
const upstream = planned.upstream;
|
|
673
|
+
if (upstream.transport === "stdio") {
|
|
674
|
+
if (!envKeys.includes(planned))
|
|
675
|
+
return planned;
|
|
676
|
+
const env = { ...upstream.env };
|
|
677
|
+
const passEnv = [];
|
|
678
|
+
for (const key of upstream.pass_env) {
|
|
679
|
+
const value = plan.gatewayEnv[key];
|
|
680
|
+
if (!isLiteralKey(key, value)) {
|
|
681
|
+
passEnv.push(key);
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
const name = lock(upstream.name, key, value, `${key} for ${planned.originalName}`);
|
|
685
|
+
env[key] = { secret: name };
|
|
686
|
+
lockedEnv.add(key);
|
|
687
|
+
write(`Kept ${key} of "${planned.originalName}" in your locked keys as "${name}" (${path}), not in ${target.path}`);
|
|
688
|
+
}
|
|
689
|
+
return { ...planned, upstream: { ...upstream, env, pass_env: passEnv } };
|
|
690
|
+
}
|
|
691
|
+
if (!planned.lockHeaders)
|
|
692
|
+
return planned;
|
|
693
|
+
const headers = { ...upstream.headers };
|
|
694
|
+
for (const header of planned.lockHeaders) {
|
|
695
|
+
const value = headers[header];
|
|
696
|
+
if (typeof value !== "string")
|
|
697
|
+
continue;
|
|
698
|
+
const prefix = /^(Bearer|Basic|Token) /i.exec(value)?.[0];
|
|
699
|
+
const secret = prefix ? value.slice(prefix.length) : value;
|
|
700
|
+
const name = lock(upstream.name, header, secret, `${header} for ${planned.originalName}`);
|
|
701
|
+
headers[header] = prefix ? { secret: name, prefix } : { secret: name };
|
|
702
|
+
write(`Kept the ${header} header of "${planned.originalName}" in your locked keys as "${name}" (${path})`);
|
|
703
|
+
}
|
|
704
|
+
return { ...planned, upstream: { ...upstream, headers } };
|
|
705
|
+
});
|
|
706
|
+
// A key now locked leaves the toolbox's entry, unless some server still passes it on by name.
|
|
707
|
+
const stillPassed = new Set(upstreams.flatMap((u) => (u.upstream.transport === "stdio" ? u.upstream.pass_env : [])));
|
|
708
|
+
const gatewayEnv = Object.fromEntries(Object.entries(plan.gatewayEnv).filter(([key]) => !lockedEnv.has(key) || stillPassed.has(key)));
|
|
709
|
+
/*
|
|
710
|
+
* A project's settings file is shared with whoever uses the project, so it
|
|
711
|
+
* doesn't name this computer's locked-keys file when that is the usual one:
|
|
712
|
+
* the toolbox finds it in the home folder anyway (UT5).
|
|
713
|
+
*/
|
|
714
|
+
// The app starts the toolbox with the person's own home folder, so "usual" is the file under that one.
|
|
715
|
+
const usual = path === defaultSecretsPath();
|
|
716
|
+
if (usual && !USER_WIDE.has(target.scope))
|
|
717
|
+
return { ...plan, upstreams, gatewayEnv };
|
|
718
|
+
return { ...plan, upstreams, gatewayEnv: { ...gatewayEnv, HMCP_SECRETS_FILE: path } };
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* The one folder a server was given on its command line, as the bound for
|
|
722
|
+
* its ready-made rules. Not the folder adopt was run from: that was often the
|
|
723
|
+
* home folder, which made a bound wider than the server itself and protected
|
|
724
|
+
* nothing. Several folders, or none, and no bound is written (and that is
|
|
725
|
+
* said), rather than a guess.
|
|
726
|
+
*/
|
|
727
|
+
function folderGivenTo(args, options) {
|
|
728
|
+
const home = options.home ?? homedir();
|
|
729
|
+
const dirs = new Set();
|
|
730
|
+
for (const arg of args) {
|
|
731
|
+
if (arg.startsWith("-"))
|
|
732
|
+
continue;
|
|
733
|
+
const expanded = arg === "~" ? home : arg.startsWith("~/") ? join(home, arg.slice(2)) : arg;
|
|
734
|
+
if (!expanded.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(expanded))
|
|
735
|
+
continue;
|
|
736
|
+
try {
|
|
737
|
+
if (statSync(expanded).isDirectory())
|
|
738
|
+
dirs.add(resolve(expanded));
|
|
739
|
+
}
|
|
740
|
+
catch {
|
|
741
|
+
/* not a folder on this computer */
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return dirs.size === 1 ? [...dirs][0] : undefined;
|
|
745
|
+
}
|
|
746
|
+
function emitInto(dir, plan, options, starting, probed,
|
|
747
|
+
/** Leave an existing policy file alone. Set when merging into a gateway already in place. */
|
|
748
|
+
keepPolicy = false) {
|
|
749
|
+
const name = options.name ?? DEFAULT_GATEWAY_NAME;
|
|
750
|
+
const { posture } = starting;
|
|
751
|
+
mkdirSync(dir, { recursive: true });
|
|
752
|
+
const configPath = join(dir, "gateway.yaml");
|
|
753
|
+
const policyPath = join(dir, "policy.yaml");
|
|
754
|
+
writeFileSync(configPath, emitGatewayYaml(plan, { name, posture, entryName: options.entryName ?? DEFAULT_ENTRY_NAME }), { encoding: "utf8", mode: 0o600 });
|
|
755
|
+
/*
|
|
756
|
+
* `gateway.yaml` is generated and is regenerated. `policy.yaml` is the file
|
|
757
|
+
* a person edits: rules they wrote, rules `suggest` proposed and they
|
|
758
|
+
* pasted, the mode they chose. Once it exists it is theirs, so a later
|
|
759
|
+
* adopt -- merging a server that appeared since -- leaves it byte for byte
|
|
760
|
+
* as it is. Regenerating it threw all of that away without a word.
|
|
761
|
+
*/
|
|
762
|
+
if (keepPolicy && existsSync(policyPath))
|
|
763
|
+
return { dir, configPath, policyPath, policyKept: true };
|
|
764
|
+
const packs = probed ? packsFor(plan, probed, options) : [];
|
|
765
|
+
writeFileSync(policyPath, emitPolicyYaml(plan, {
|
|
766
|
+
name,
|
|
767
|
+
posture,
|
|
768
|
+
enforcement: starting.mode,
|
|
769
|
+
onUnclassified: starting.onUnclassified,
|
|
770
|
+
...(probed ? { unclassified: probed.tools.filter((t) => t.effect === null && !t.hidden) } : {}),
|
|
771
|
+
...(probed ? { toolCount: probed.tools.length } : {}),
|
|
772
|
+
packs
|
|
773
|
+
}), { encoding: "utf8", mode: 0o600 });
|
|
774
|
+
return { dir, configPath, policyPath, policyKept: false, packs };
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Which mode the gateway starts in, and what happens to an unclassified tool.
|
|
778
|
+
*
|
|
779
|
+
* Asked out loud when there is someone to ask, because the default protects
|
|
780
|
+
* nothing: observe mode is the right way to *start* and the wrong thing to
|
|
781
|
+
* find out about afterwards. Not asked on a dry run, which changes nothing,
|
|
782
|
+
* and not asked when a gateway is already in place: adding a server to one
|
|
783
|
+
* that is enforcing must not quietly switch enforcement off, so the mode it
|
|
784
|
+
* is already in is kept unless `--mode` says otherwise.
|
|
785
|
+
*/
|
|
786
|
+
async function startingChoices(options, existingConfigPath, write) {
|
|
787
|
+
let mode = options.mode;
|
|
788
|
+
let onUnclassified = options.onUnclassified;
|
|
789
|
+
let posture = options.posture;
|
|
790
|
+
if (existingConfigPath) {
|
|
791
|
+
try {
|
|
792
|
+
const { policy } = loadGatewayConfig(existingConfigPath);
|
|
793
|
+
mode ??= policy.enforcement;
|
|
794
|
+
onUnclassified ??= policy.defaults.on_unclassified;
|
|
795
|
+
posture ??= policy.defaults.mode;
|
|
796
|
+
}
|
|
797
|
+
catch {
|
|
798
|
+
/* An existing config that no longer loads is reported by the merge itself. */
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
if (mode === undefined && options.apply && options.ask) {
|
|
802
|
+
const answer = (await options.ask("Start in observe mode, or enforce from the first call?\n" +
|
|
803
|
+
" observe every call runs and is recorded with what the policy would have decided.\n" +
|
|
804
|
+
" Nothing breaks, and nothing is protected until you switch enforcement on.\n" +
|
|
805
|
+
" enforce the policy applies at once: writes wait for approval, unknown tools ask.\n" +
|
|
806
|
+
"[observe] / enforce: "))
|
|
807
|
+
.trim()
|
|
808
|
+
.toLowerCase();
|
|
809
|
+
if (answer === "" || answer === "observe" || answer === "o")
|
|
810
|
+
mode = "observe";
|
|
811
|
+
else if (answer === "enforce" || answer === "e")
|
|
812
|
+
mode = "enforce";
|
|
813
|
+
else
|
|
814
|
+
throw new AdoptCommandError(`expected observe or enforce, not ${JSON.stringify(answer)}. Nothing was changed.`);
|
|
815
|
+
}
|
|
816
|
+
const starting = {
|
|
817
|
+
posture: posture ?? "approve-writes",
|
|
818
|
+
mode: mode ?? "observe",
|
|
819
|
+
onUnclassified: onUnclassified ?? "approve",
|
|
820
|
+
entryName: options.entryName ?? DEFAULT_ENTRY_NAME
|
|
821
|
+
};
|
|
822
|
+
if (options.mode === undefined && !existingConfigPath && !(options.apply && options.ask)) {
|
|
823
|
+
write("");
|
|
824
|
+
write(`Mode: ${starting.mode} (the default; choose with --mode observe or --mode enforce)`);
|
|
825
|
+
}
|
|
826
|
+
return starting;
|
|
827
|
+
}
|
|
828
|
+
/** Refused before anything was written; carries the report that says why. */
|
|
829
|
+
export class AdoptRefusedError extends AdoptCommandError {
|
|
830
|
+
report;
|
|
831
|
+
constructor(report) {
|
|
832
|
+
super(`Nothing was changed. ${report.blocking.join(" ")}`);
|
|
833
|
+
this.report = report;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
const ADOPT_HEADER = "# Generated by `hmcp-gateway adopt`.";
|
|
837
|
+
/** A file adopt may overwrite: absent, or one adopt itself wrote. */
|
|
838
|
+
function isAdoptFile(path) {
|
|
839
|
+
if (!existsSync(path))
|
|
840
|
+
return true;
|
|
841
|
+
try {
|
|
842
|
+
return readFileSync(path, "utf8").startsWith(ADOPT_HEADER);
|
|
843
|
+
}
|
|
844
|
+
catch {
|
|
845
|
+
return false;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
export function verdictFor(tool, starting, packRules) {
|
|
849
|
+
if (tool.hidden)
|
|
850
|
+
return ["hidden", "on_injection"];
|
|
851
|
+
/*
|
|
852
|
+
* A ready-made rule first: it classifies the tool, so a tool the probe saw
|
|
853
|
+
* as unlabelled (it ran before the rules existed) is decided by the rule
|
|
854
|
+
* that will be written, exactly as the gateway will decide it.
|
|
855
|
+
*/
|
|
856
|
+
const pack = packRules.get(tool.localName);
|
|
857
|
+
if (pack)
|
|
858
|
+
return [pack[1] === "allow" ? "run" : pack[1] === "approve" ? "ask" : "blocked", pack[0]];
|
|
859
|
+
if (tool.effect === null)
|
|
860
|
+
return [starting.onUnclassified === "deny" ? "blocked" : "ask", "defaults.on_unclassified"];
|
|
861
|
+
if (starting.posture === "locked")
|
|
862
|
+
return ["blocked", "defaults.mode"];
|
|
863
|
+
if (tool.effect === "read")
|
|
864
|
+
return ["run", "defaults.mode"];
|
|
865
|
+
return [starting.posture === "read-only" ? "blocked" : "ask", "defaults.mode"];
|
|
866
|
+
}
|
|
867
|
+
function upstreamReport(planned, alreadyFronted) {
|
|
868
|
+
const u = planned.upstream;
|
|
869
|
+
return {
|
|
870
|
+
name: u.name,
|
|
871
|
+
originalName: planned.originalName,
|
|
872
|
+
transport: u.transport,
|
|
873
|
+
command: u.transport === "stdio" ? u.command : null,
|
|
874
|
+
args: u.transport === "stdio" ? u.args : [],
|
|
875
|
+
url: u.transport === "http" ? u.url : null,
|
|
876
|
+
envNames: u.transport === "stdio" ? Object.keys(u.env).sort() : [],
|
|
877
|
+
passEnv: u.transport === "stdio" ? u.pass_env : [],
|
|
878
|
+
headerNames: u.transport === "http" ? Object.keys(u.headers).sort() : [],
|
|
879
|
+
warnings: planned.warnings,
|
|
880
|
+
alreadyFronted
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Probes each upstream on its own, for a caller that wants every failure
|
|
885
|
+
* rather than the first.
|
|
886
|
+
*
|
|
887
|
+
* Only reached after the ordinary probe has failed. Connecting is
|
|
888
|
+
* all-or-nothing and stops at the first upstream that will not connect, so
|
|
889
|
+
* the servers after it were never tried; each is tried here on its own,
|
|
890
|
+
* concurrently, under the same `connect_timeout_ms`.
|
|
891
|
+
*/
|
|
892
|
+
async function probeEach(merged, options, starting, firstError) {
|
|
893
|
+
const named = /upstream "([^"]+)"/.exec(firstError.message)?.[1];
|
|
894
|
+
const failures = [];
|
|
895
|
+
if (named !== undefined)
|
|
896
|
+
failures.push({ upstream: named, message: firstError.message });
|
|
897
|
+
const rest = merged.upstreams.filter((u) => u.upstream.name !== named);
|
|
898
|
+
const results = await Promise.allSettled(rest.map(async (planned) => {
|
|
899
|
+
const scratch = mkdtempSync(join(tmpdir(), "hmcp-adopt-"));
|
|
900
|
+
try {
|
|
901
|
+
const staged = emitInto(scratch, { ...merged, upstreams: [planned] }, options, starting);
|
|
902
|
+
return await probe(staged.configPath);
|
|
903
|
+
}
|
|
904
|
+
finally {
|
|
905
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
906
|
+
}
|
|
907
|
+
}));
|
|
908
|
+
const tools = [];
|
|
909
|
+
results.forEach((result, i) => {
|
|
910
|
+
if (result.status === "fulfilled")
|
|
911
|
+
tools.push(...result.value.tools);
|
|
912
|
+
else
|
|
913
|
+
failures.push({ upstream: rest[i].upstream.name, message: result.reason.message });
|
|
914
|
+
});
|
|
915
|
+
// Nothing named and every one connected alone: the failure is in the set.
|
|
916
|
+
if (failures.length === 0)
|
|
917
|
+
failures.push({ upstream: "(all)", message: firstError.message });
|
|
918
|
+
return { tools, failures };
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* The whole of adoption, once.
|
|
922
|
+
*
|
|
923
|
+
* Returns what it found and did as data, and narrates as it goes through
|
|
924
|
+
* `write`. The CLI prints the narration and ignores the data; the library
|
|
925
|
+
* functions below do the opposite. One engine rather than two keeps the
|
|
926
|
+
* report and the printed output from ever disagreeing about what happened,
|
|
927
|
+
* and keeps the CLI's output byte for byte what it was.
|
|
928
|
+
*
|
|
929
|
+
* `library` changes three things, none of them visible on a terminal: a
|
|
930
|
+
* refusal the CLI would throw before probing is collected into `blocking`
|
|
931
|
+
* instead, a failed probe is attributed per upstream rather than thrown, and
|
|
932
|
+
* applying refuses while anything is blocking, before writing anything.
|
|
933
|
+
*/
|
|
934
|
+
async function adoptEngine(options, write, library) {
|
|
935
|
+
const entryName = options.entryName ?? DEFAULT_ENTRY_NAME;
|
|
936
|
+
const scopeOptions = {
|
|
937
|
+
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
|
|
938
|
+
...(options.home !== undefined ? { home: options.home } : {})
|
|
939
|
+
};
|
|
940
|
+
let target;
|
|
941
|
+
try {
|
|
942
|
+
target = resolveScope(options.scope, scopeOptions);
|
|
943
|
+
}
|
|
944
|
+
catch (err) {
|
|
945
|
+
throw err instanceof ClientConfigError ? new AdoptCommandError(err.message) : err;
|
|
946
|
+
}
|
|
947
|
+
const file = readClientConfig(target.scope, scopeOptions);
|
|
948
|
+
const parsed = parseServers(file.servers, { httpOnly: target.httpOnly });
|
|
949
|
+
const { malformed } = parsed;
|
|
950
|
+
// Copied because an already-adopted scope has its gateway entry removed from
|
|
951
|
+
// the set before planning.
|
|
952
|
+
const servers = new Map(parsed.servers);
|
|
953
|
+
write(`Client config: ${target.path}`);
|
|
954
|
+
write(`Scope: ${target.scope} (${target.where})`);
|
|
955
|
+
const codexNote = codexHomeNote(target, options.home ?? homedir());
|
|
956
|
+
if (codexNote)
|
|
957
|
+
write(`Note: Codex is ${codexNote}.`);
|
|
958
|
+
// A file whose servers are in a form that cannot be changed safely: listed, never edited.
|
|
959
|
+
const editProblem = clientEditProblem(file);
|
|
960
|
+
if (editProblem) {
|
|
961
|
+
if (options.apply)
|
|
962
|
+
throw new AdoptCommandError(editProblem);
|
|
963
|
+
write(`Note: ${editProblem}`);
|
|
964
|
+
}
|
|
965
|
+
/*
|
|
966
|
+
* An existing gateway entry means this scope has been adopted before, and
|
|
967
|
+
* the right behaviour depends on whether anything new has appeared beside
|
|
968
|
+
* it. Without the backup there is no safe move at all: replacing an entry we
|
|
969
|
+
* cannot restore is not an operation with an undo.
|
|
970
|
+
*/
|
|
971
|
+
const existing = [...servers.entries()].find(([name, server]) => isOurGateway(name, server, entryName));
|
|
972
|
+
const backup = readBackup(target);
|
|
973
|
+
let reservedNames = [];
|
|
974
|
+
let existingConfigPath;
|
|
975
|
+
const report = {
|
|
976
|
+
scope: target.scope,
|
|
977
|
+
client: target.client,
|
|
978
|
+
clientConfigPath: target.path,
|
|
979
|
+
where: target.where,
|
|
980
|
+
status: "ready",
|
|
981
|
+
existingGateway: null,
|
|
982
|
+
serversFound: [...servers.keys()].filter((name) => name !== existing?.[0]),
|
|
983
|
+
upstreams: [],
|
|
984
|
+
skipped: [],
|
|
985
|
+
malformed,
|
|
986
|
+
gatewayEnvNames: [],
|
|
987
|
+
egressAllow: [],
|
|
988
|
+
starting: null,
|
|
989
|
+
tools: [],
|
|
990
|
+
withheld: [],
|
|
991
|
+
namesTooLong: [],
|
|
992
|
+
probeFailures: [],
|
|
993
|
+
findings: [],
|
|
994
|
+
packs: [],
|
|
995
|
+
clientAllow: null,
|
|
996
|
+
files: null,
|
|
997
|
+
warnings: [],
|
|
998
|
+
blocking: [],
|
|
999
|
+
applied: null
|
|
1000
|
+
};
|
|
1001
|
+
const blocking = [];
|
|
1002
|
+
const warnings = [];
|
|
1003
|
+
report.blocking = blocking;
|
|
1004
|
+
report.warnings = warnings;
|
|
1005
|
+
const allowState = (add) => {
|
|
1006
|
+
const path = clientSettingsPath(target, scopeOptions);
|
|
1007
|
+
const rule = allowRuleFor(entryName);
|
|
1008
|
+
const alreadyAllowed = readClientSettingsQuietly(path).includes(rule);
|
|
1009
|
+
return { path, rule, alreadyAllowed, willAdd: add && !alreadyAllowed };
|
|
1010
|
+
};
|
|
1011
|
+
if (existing) {
|
|
1012
|
+
if (!backup) {
|
|
1013
|
+
throw new AdoptCommandError(`"${existing[0]}" in ${target.path} is already an hmcp gateway, but there is no adoption backup ` +
|
|
1014
|
+
`beside it. Replacing it would leave nothing to restore the original servers from. Move that ` +
|
|
1015
|
+
`entry aside by hand, or run adopt in a scope that has not been adopted.`);
|
|
1016
|
+
}
|
|
1017
|
+
/*
|
|
1018
|
+
* Connected from the console rather than adopted: the gateway's files are
|
|
1019
|
+
* the console's, written in its own format, and regenerating them here
|
|
1020
|
+
* would rewrite a toolbox the person built by hand. Its servers are added
|
|
1021
|
+
* in the console instead.
|
|
1022
|
+
*/
|
|
1023
|
+
if (backup.generated.length === 0 && servers.size > 1) {
|
|
1024
|
+
throw new AdoptCommandError(`"${existing[0]}" in ${target.path} is a toolbox connected from the console, not one adopt wrote, so ` +
|
|
1025
|
+
`adopt will not rewrite it. To move the app's other servers into that toolbox, open the console, go to ` +
|
|
1026
|
+
`Connections and press "Bring in servers" for this app; or undo the connection first and adopt then.`);
|
|
1027
|
+
}
|
|
1028
|
+
existingConfigPath = configPathOf(existing[1]);
|
|
1029
|
+
if (existingConfigPath && existsSync(existingConfigPath)) {
|
|
1030
|
+
reservedNames = loadGatewayConfig(existingConfigPath).config.upstreams.map((u) => u.name);
|
|
1031
|
+
}
|
|
1032
|
+
report.existingGateway = { entryName: existing[0], configPath: existingConfigPath ?? null, upstreams: reservedNames };
|
|
1033
|
+
servers.delete(existing[0]);
|
|
1034
|
+
if (servers.size === 0) {
|
|
1035
|
+
report.status = "already-adopted";
|
|
1036
|
+
write("");
|
|
1037
|
+
write(`Already adopted: "${existing[0]}" fronts ${reservedNames.length} upstream(s) and nothing new`);
|
|
1038
|
+
const mode = existingConfigPath && existsSync(existingConfigPath)
|
|
1039
|
+
? loadGatewayConfig(existingConfigPath).policy.enforcement
|
|
1040
|
+
: "observe";
|
|
1041
|
+
if (library) {
|
|
1042
|
+
// The one thing left to do to a gateway already in place is the allow
|
|
1043
|
+
// rule, so the report says whether that is what applying would do.
|
|
1044
|
+
report.clientAllow = allowState(options.clientAllow === true && mode === "enforce");
|
|
1045
|
+
if (options.clientAllow && mode === "observe") {
|
|
1046
|
+
blocking.push("The client allow rule cannot be added while the gateway is in watch-only mode.");
|
|
1047
|
+
}
|
|
1048
|
+
else if (!report.clientAllow.willAdd) {
|
|
1049
|
+
blocking.push("This app is already connected through the gateway, and no new server has appeared. Nothing to do.");
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
if (!(options.apply && options.clientAllow)) {
|
|
1053
|
+
write("has appeared beside it. Nothing to do.");
|
|
1054
|
+
if (library && options.apply)
|
|
1055
|
+
throw new AdoptRefusedError(report);
|
|
1056
|
+
return report;
|
|
1057
|
+
}
|
|
1058
|
+
/*
|
|
1059
|
+
* The one thing left to do to a gateway that is already in place: the
|
|
1060
|
+
* allow rule, asked for now that it is enforcing. The mode is read from
|
|
1061
|
+
* the policy it is actually running, not from a flag.
|
|
1062
|
+
*/
|
|
1063
|
+
write("has appeared beside it.");
|
|
1064
|
+
const choice = await clientAllowChoice(options, target, mode);
|
|
1065
|
+
const added = applyClientAllow(choice, mode, write);
|
|
1066
|
+
if (added)
|
|
1067
|
+
writeBackup(target, { ...backup, client_allow: added });
|
|
1068
|
+
report.applied = {
|
|
1069
|
+
configPath: existingConfigPath ?? null,
|
|
1070
|
+
policyPath: null,
|
|
1071
|
+
policyKept: true,
|
|
1072
|
+
clientConfigPath: target.path,
|
|
1073
|
+
replaced: [],
|
|
1074
|
+
wholeFileBackup: null,
|
|
1075
|
+
backupRecord: backupPath(target),
|
|
1076
|
+
registryId: backup.registry_id ?? null,
|
|
1077
|
+
clientAllowAdded: added ?? null,
|
|
1078
|
+
literalSecretsInBackup: false
|
|
1079
|
+
};
|
|
1080
|
+
return report;
|
|
1081
|
+
}
|
|
1082
|
+
write("");
|
|
1083
|
+
write(`Already adopted. ${servers.size} new server(s) appeared beside "${existing[0]}" and will be`);
|
|
1084
|
+
write(`merged into ${existingConfigPath ?? "its config"}.`);
|
|
1085
|
+
}
|
|
1086
|
+
/*
|
|
1087
|
+
* The toolbox is named for the app it was made for ("cursor", not
|
|
1088
|
+
* "claude-code" for every app), and keeps its name when servers are added
|
|
1089
|
+
* to it later: the name is half of every storage key, so a rename would
|
|
1090
|
+
* orphan its approvals and pins.
|
|
1091
|
+
*/
|
|
1092
|
+
if (options.name === undefined) {
|
|
1093
|
+
let kept;
|
|
1094
|
+
if (existingConfigPath && existsSync(existingConfigPath)) {
|
|
1095
|
+
try {
|
|
1096
|
+
kept = loadGatewayConfig(existingConfigPath).config.name;
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
kept = undefined;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
options = { ...options, name: kept ?? defaultNameFor(target.scope) };
|
|
1103
|
+
}
|
|
1104
|
+
const gatewayDir = generatedDir(target, options);
|
|
1105
|
+
const gatewayConfigPath = existingConfigPath ?? join(gatewayDir, "gateway.yaml");
|
|
1106
|
+
const plan = planAdoption(servers, {
|
|
1107
|
+
gatewayEntryName: entryName,
|
|
1108
|
+
gatewayConfigPath,
|
|
1109
|
+
...(options.copyEnv !== undefined ? { copyEnv: options.copyEnv } : {}),
|
|
1110
|
+
...(options.allowLocalHttp !== undefined ? { allowLocalHttp: options.allowLocalHttp } : {}),
|
|
1111
|
+
...(options.strictEgress !== undefined ? { strictEgress: options.strictEgress } : {}),
|
|
1112
|
+
names: options.rename ? new Map(Object.entries(options.rename)) : parseNameOverrides(options.names ?? []),
|
|
1113
|
+
reservedNames,
|
|
1114
|
+
malformed
|
|
1115
|
+
});
|
|
1116
|
+
describePlan(plan, write, target.scope);
|
|
1117
|
+
report.skipped = plan.skipped;
|
|
1118
|
+
report.gatewayEnvNames = Object.keys(plan.gatewayEnv).sort();
|
|
1119
|
+
report.egressAllow = plan.egressAllow;
|
|
1120
|
+
if (plan.secretsOnDisk) {
|
|
1121
|
+
warnings.push("Copying environment values is on, so a secret value is written into gateway.yaml in plain text. " +
|
|
1122
|
+
"Do not share or commit that file.");
|
|
1123
|
+
}
|
|
1124
|
+
if (plan.egressNeedsLocalHttp) {
|
|
1125
|
+
warnings.push("A server on this machine or the local network is reached over HTTP, so the network limits that " +
|
|
1126
|
+
"block private addresses are switched off for every HTTP server in this toolbox, not only that one.");
|
|
1127
|
+
}
|
|
1128
|
+
const adopted = plan.upstreams.map((u) => u.originalName);
|
|
1129
|
+
const replacedEntries = Object.fromEntries(adopted.map((name) => [name, file.servers[name]]));
|
|
1130
|
+
const literalSecretsInBackup = hasLiteralSecret(replacedEntries);
|
|
1131
|
+
if (literalSecretsInBackup) {
|
|
1132
|
+
const names = literalSecretNames(replacedEntries);
|
|
1133
|
+
warnings.push(`A server being moved has a password or key written out in the app's settings (${names.join(", ")}). ` +
|
|
1134
|
+
`The two backups of those settings will hold it too: ${wholeFileBackupPath(target)} and ${backupPath(target)}. ` +
|
|
1135
|
+
`Keep them as private as the original.`);
|
|
1136
|
+
}
|
|
1137
|
+
if (plan.upstreams.length === 0) {
|
|
1138
|
+
report.status = "nothing-to-wrap";
|
|
1139
|
+
blocking.push("Every server was left out, so there is no gateway to write.");
|
|
1140
|
+
write("");
|
|
1141
|
+
write("Nothing left to wrap, so there is no gateway to write. Nothing was changed.");
|
|
1142
|
+
if (library && options.apply)
|
|
1143
|
+
throw new AdoptRefusedError(report);
|
|
1144
|
+
return report;
|
|
1145
|
+
}
|
|
1146
|
+
/*
|
|
1147
|
+
* Merging means the generated files describe the union, so the plan is
|
|
1148
|
+
* widened with what the existing gateway already fronts before anything is
|
|
1149
|
+
* emitted or probed.
|
|
1150
|
+
*/
|
|
1151
|
+
const merged = existingConfigPath ? mergeWithExisting(plan, existingConfigPath) : plan;
|
|
1152
|
+
const fresh = new Set(plan.upstreams.map((u) => u.upstream.name));
|
|
1153
|
+
report.upstreams = merged.upstreams.map((u) => upstreamReport(u, !fresh.has(u.upstream.name)));
|
|
1154
|
+
const starting = await startingChoices(options, existingConfigPath, write);
|
|
1155
|
+
report.starting = { ...starting, gatewayName: options.name ?? DEFAULT_GATEWAY_NAME };
|
|
1156
|
+
let clientAllow;
|
|
1157
|
+
try {
|
|
1158
|
+
clientAllow = await clientAllowChoice(options, target, starting.mode);
|
|
1159
|
+
}
|
|
1160
|
+
catch (err) {
|
|
1161
|
+
if (!library || !(err instanceof AdoptCommandError))
|
|
1162
|
+
throw err;
|
|
1163
|
+
blocking.push(err.message.replace(/ Nothing was changed\.$/, ""));
|
|
1164
|
+
clientAllow = { path: clientSettingsPath(target, scopeOptions), rule: allowRuleFor(entryName), add: false };
|
|
1165
|
+
}
|
|
1166
|
+
report.clientAllow = allowState(starting.mode === "enforce" && clientAllow.add);
|
|
1167
|
+
const policyPath = join(gatewayDir, "policy.yaml");
|
|
1168
|
+
const policyKept = existingConfigPath !== undefined && existsSync(policyPath);
|
|
1169
|
+
report.files = {
|
|
1170
|
+
gatewayConfig: join(gatewayDir, "gateway.yaml"),
|
|
1171
|
+
policy: policyPath,
|
|
1172
|
+
policyKept,
|
|
1173
|
+
clientConfig: target.path,
|
|
1174
|
+
wholeFileBackup: file.exists ? wholeFileBackupPath(target) : null,
|
|
1175
|
+
backupRecord: backupPath(target),
|
|
1176
|
+
clientSettings: clientAllow.add && starting.mode === "enforce" ? clientAllow.path : null,
|
|
1177
|
+
registry: options.register === false ? null : (options.registry ?? defaultRegistryPath())
|
|
1178
|
+
};
|
|
1179
|
+
if (library) {
|
|
1180
|
+
// Never written over: a gateway.yaml or policy.yaml someone wrote by hand
|
|
1181
|
+
// in the directory adopt would use. The merge case writes into its own.
|
|
1182
|
+
for (const path of [join(gatewayDir, "gateway.yaml"), ...(policyKept ? [] : [policyPath])]) {
|
|
1183
|
+
if (path !== existingConfigPath && !isAdoptFile(path)) {
|
|
1184
|
+
blocking.push(`${path} already exists and was not written by adopt, so it would be overwritten. Choose another folder.`);
|
|
1185
|
+
}
|
|
1186
|
+
else if (path !== existingConfigPath && existsSync(path)) {
|
|
1187
|
+
// Kept by an earlier undo ("Files kept"): said, so edited rules are not lost without a word.
|
|
1188
|
+
warnings.push(`This replaces ${path}, left from an earlier connection. Any changes made to it since are lost.`);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
if (options.apply && blocking.length > 0)
|
|
1192
|
+
throw new AdoptRefusedError(report);
|
|
1193
|
+
}
|
|
1194
|
+
write("");
|
|
1195
|
+
write("Starting each server once to ask what it offers. This spawns the stdio servers");
|
|
1196
|
+
write("and dials the HTTP ones; nothing is written to the client config yet.");
|
|
1197
|
+
const scratch = mkdtempSync(join(tmpdir(), "hmcp-adopt-"));
|
|
1198
|
+
let probed;
|
|
1199
|
+
let probeError;
|
|
1200
|
+
try {
|
|
1201
|
+
const staged = emitInto(scratch, merged, options, starting);
|
|
1202
|
+
probed = await probe(staged.configPath);
|
|
1203
|
+
}
|
|
1204
|
+
catch (err) {
|
|
1205
|
+
if (!library) {
|
|
1206
|
+
throw new AdoptCommandError(`could not connect the upstreams as configured: ${err.message}\n` +
|
|
1207
|
+
`Nothing was changed. Fix the server that failed, or drop it with --name, and try again.`);
|
|
1208
|
+
}
|
|
1209
|
+
probeError = err;
|
|
1210
|
+
}
|
|
1211
|
+
finally {
|
|
1212
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
1213
|
+
}
|
|
1214
|
+
if (probed === undefined) {
|
|
1215
|
+
const each = await probeEach(merged, options, starting, probeError);
|
|
1216
|
+
report.status = "probe-failed";
|
|
1217
|
+
report.probeFailures = each.failures;
|
|
1218
|
+
report.tools = each.tools.map((tool) => toolReport(tool, starting, new Map()));
|
|
1219
|
+
blocking.push(`${each.failures.length} server(s) did not start or answer: ${each.failures.map((f) => f.upstream).join(", ")}. ` +
|
|
1220
|
+
`Fix them, or leave them out by giving them no place in this gateway.`);
|
|
1221
|
+
if (options.apply)
|
|
1222
|
+
throw new AdoptRefusedError(report);
|
|
1223
|
+
return report;
|
|
1224
|
+
}
|
|
1225
|
+
describeProbe(probed, starting, write);
|
|
1226
|
+
const packs = policyKept ? [] : packsFor(merged, probed, options);
|
|
1227
|
+
const packRules = new Map(packs.flatMap((p) => p.rules.map((r) => [r.match, [r.id, r.decision]])));
|
|
1228
|
+
const budget = toolNameBudget(starting.entryName);
|
|
1229
|
+
report.packs = packs;
|
|
1230
|
+
report.tools = probed.tools.map((tool) => toolReport(tool, starting, packRules));
|
|
1231
|
+
report.withheld = probed.withheld
|
|
1232
|
+
.filter((t) => t.localName.length <= budget)
|
|
1233
|
+
.map((t) => ({ name: t.localName, upstream: t.upstream, reason: t.reason }));
|
|
1234
|
+
report.namesTooLong = probed.withheld
|
|
1235
|
+
.filter((t) => t.localName.length > budget)
|
|
1236
|
+
.map((t) => {
|
|
1237
|
+
const clientName = clientToolName(starting.entryName, t.localName);
|
|
1238
|
+
return { name: t.localName, clientName, length: clientName.length, limit: CLIENT_TOOL_NAME_LIMIT, upstream: t.upstream };
|
|
1239
|
+
});
|
|
1240
|
+
report.findings = probed.scan.findings.map((f) => ({
|
|
1241
|
+
ruleId: f.ruleId,
|
|
1242
|
+
severity: f.severity,
|
|
1243
|
+
title: f.title,
|
|
1244
|
+
message: f.message,
|
|
1245
|
+
fix: f.fix
|
|
1246
|
+
}));
|
|
1247
|
+
if (!options.apply) {
|
|
1248
|
+
write("");
|
|
1249
|
+
write("Nothing has been written. Re-run with --apply to:");
|
|
1250
|
+
write(` write ${join(gatewayDir, "gateway.yaml")} and policy.yaml`);
|
|
1251
|
+
write(` replace ${merged.upstreams.length} entr(ies) in ${target.path} with one "${entryName}" entry`);
|
|
1252
|
+
write(` back the originals up to ${wholeFileBackupPath(target)}`);
|
|
1253
|
+
if (options.register !== false)
|
|
1254
|
+
write(" register the gateway with the console");
|
|
1255
|
+
return report;
|
|
1256
|
+
}
|
|
1257
|
+
const locked = lockHeaderSecrets(merged, options, write, target);
|
|
1258
|
+
const generated = emitInto(gatewayDir, locked, options, starting, probed, existingConfigPath !== undefined);
|
|
1259
|
+
if (!USER_WIDE.has(target.scope))
|
|
1260
|
+
keepOutOfGit(options);
|
|
1261
|
+
write("");
|
|
1262
|
+
write(`Wrote ${generated.configPath}`);
|
|
1263
|
+
if (generated.policyKept) {
|
|
1264
|
+
write(`Kept ${generated.policyPath} exactly as it is: policy.yaml is yours once it exists.`);
|
|
1265
|
+
const unclassified = probed.tools.filter((t) => t.effect === null && !t.hidden);
|
|
1266
|
+
if (unclassified.length > 0) {
|
|
1267
|
+
write(` ${unclassified.length} tool(s) are unclassified under it; classify one with: hmcp-gateway rule <tool>`);
|
|
1268
|
+
}
|
|
1269
|
+
if (merged.egressAllow.length > 0) {
|
|
1270
|
+
write(` If a new server is reached over HTTP, check egress.allow there includes: ${merged.egressAllow.join(", ")}`);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
else {
|
|
1274
|
+
write(`Wrote ${generated.policyPath}`);
|
|
1275
|
+
/*
|
|
1276
|
+
* Said out loud rather than left in the file, because a rule written for
|
|
1277
|
+
* you is a rule you did not choose. Each line names what was classified
|
|
1278
|
+
* and what was not, so the first thing a reader does with the generated
|
|
1279
|
+
* policy is check it rather than trust it.
|
|
1280
|
+
*/
|
|
1281
|
+
for (const pack of generated.packs ?? []) {
|
|
1282
|
+
write(` ${pack.rules.length} rule(s) from the ready-made ${pack.packLabel} classification, ` +
|
|
1283
|
+
`for tools "${pack.upstreamName}" advertised just now`);
|
|
1284
|
+
if (pack.skippedBounds.length > 0) {
|
|
1285
|
+
write(` no path bound was written for ${pack.skippedBounds.join(", ")}; add one by hand`);
|
|
1286
|
+
}
|
|
1287
|
+
if (pack.unmatched.length > 0) {
|
|
1288
|
+
write(` ${pack.unmatched.length} tool(s) the pack knows were not advertised, so nothing was written ` +
|
|
1289
|
+
`for them: ${pack.unmatched.slice(0, 6).join(", ")}${pack.unmatched.length > 6 ? ", …" : ""}`);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
const id = installEntry({ file, target, plan, merged: locked, generated, options, backup, existing, write });
|
|
1294
|
+
const allowed = applyClientAllow(clientAllow, starting.mode, write);
|
|
1295
|
+
if (allowed) {
|
|
1296
|
+
const written = readBackup(target);
|
|
1297
|
+
if (written)
|
|
1298
|
+
writeBackup(target, { ...written, client_allow: allowed });
|
|
1299
|
+
}
|
|
1300
|
+
printChecklist({ target, generated, entryName, id, options, starting, write });
|
|
1301
|
+
report.applied = {
|
|
1302
|
+
configPath: generated.configPath,
|
|
1303
|
+
policyPath: generated.policyPath,
|
|
1304
|
+
policyKept: generated.policyKept,
|
|
1305
|
+
clientConfigPath: target.path,
|
|
1306
|
+
replaced: adopted,
|
|
1307
|
+
wholeFileBackup: file.exists ? wholeFileBackupPath(target) : null,
|
|
1308
|
+
backupRecord: backupPath(target),
|
|
1309
|
+
registryId: id ?? null,
|
|
1310
|
+
clientAllowAdded: allowed ?? null,
|
|
1311
|
+
literalSecretsInBackup
|
|
1312
|
+
};
|
|
1313
|
+
return report;
|
|
1314
|
+
}
|
|
1315
|
+
function toolReport(tool, starting, packRules) {
|
|
1316
|
+
const [verdict, decidedBy] = verdictFor(tool, starting, packRules);
|
|
1317
|
+
return {
|
|
1318
|
+
name: tool.localName,
|
|
1319
|
+
upstream: tool.upstream,
|
|
1320
|
+
effect: tool.effect,
|
|
1321
|
+
effectSource: tool.effectSource,
|
|
1322
|
+
hidden: tool.hidden,
|
|
1323
|
+
injection: tool.injection,
|
|
1324
|
+
verdict,
|
|
1325
|
+
decidedBy
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
export async function runAdoptCommand(options) {
|
|
1329
|
+
await adoptEngine(options, out(options), false);
|
|
1330
|
+
}
|
|
1331
|
+
const quiet = () => undefined;
|
|
1332
|
+
/** What adopting would do, with nothing written. Upstreams are started once to ask what they offer. */
|
|
1333
|
+
export async function adoptPlan(options) {
|
|
1334
|
+
return adoptEngine({ ...options, apply: false }, quiet, true);
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* Adopts. Throws `AdoptRefusedError`, with nothing written, when the plan
|
|
1338
|
+
* has anything blocking; `AdoptCommandError` for a refusal the CLI also makes.
|
|
1339
|
+
*/
|
|
1340
|
+
export async function adoptApply(options) {
|
|
1341
|
+
return adoptEngine({ ...options, apply: true }, quiet, true);
|
|
1342
|
+
}
|
|
1343
|
+
/** Widens a plan with the upstreams a gateway being merged into already has. */
|
|
1344
|
+
function mergeWithExisting(plan, existingConfigPath) {
|
|
1345
|
+
const { config } = loadGatewayConfig(existingConfigPath);
|
|
1346
|
+
const already = config.upstreams.map((upstream) => ({
|
|
1347
|
+
upstream,
|
|
1348
|
+
originalName: upstream.name,
|
|
1349
|
+
warnings: []
|
|
1350
|
+
}));
|
|
1351
|
+
return { ...plan, upstreams: [...already, ...plan.upstreams] };
|
|
1352
|
+
}
|
|
1353
|
+
function installEntry(args) {
|
|
1354
|
+
const { file, target, plan, merged, generated, options, write } = args;
|
|
1355
|
+
const entryName = options.entryName ?? DEFAULT_ENTRY_NAME;
|
|
1356
|
+
const adopted = plan.upstreams.map((u) => u.originalName);
|
|
1357
|
+
/*
|
|
1358
|
+
* Everything that can refuse happens before anything is written.
|
|
1359
|
+
*
|
|
1360
|
+
* Registration used to run after the client config had been rewritten,
|
|
1361
|
+
* which meant a taken registry id left the gateway entry in place with no
|
|
1362
|
+
* backup beside it -- the one state `adopt` itself then refuses to touch,
|
|
1363
|
+
* reachable by a name clash in an unrelated file.
|
|
1364
|
+
*/
|
|
1365
|
+
const registration = options.register === false ? undefined : prepareRegistration(args);
|
|
1366
|
+
// Then the verbatim copy: whatever goes wrong after this, the original file
|
|
1367
|
+
// is sitting beside it.
|
|
1368
|
+
writeWholeFileBackup(file);
|
|
1369
|
+
const servers = { ...file.servers };
|
|
1370
|
+
for (const name of adopted)
|
|
1371
|
+
delete servers[name];
|
|
1372
|
+
if (args.existing)
|
|
1373
|
+
delete servers[args.existing[0]];
|
|
1374
|
+
const { command, args: commandArgs, local } = clientCommand(options);
|
|
1375
|
+
if (local && options.local === undefined) {
|
|
1376
|
+
write(` The client entry runs this checkout (${commandArgs[0]}), because that is where adopt was run from.`);
|
|
1377
|
+
write(` Pass --pin <version> to have the client run the published package instead.`);
|
|
1378
|
+
}
|
|
1379
|
+
const configPath = options.relativeConfig
|
|
1380
|
+
? relative(dirname(target.path), generated.configPath)
|
|
1381
|
+
: generated.configPath;
|
|
1382
|
+
// The app's own fields first (VS Code's `type: "stdio"`), as connecting from the console writes them.
|
|
1383
|
+
servers[entryName] = { ...target.stdioFields, ...emitClientEntry(merged, { configPath, command, args: commandArgs }) };
|
|
1384
|
+
writeClientConfig(file, servers);
|
|
1385
|
+
write(`Rewrote ${target.path}: ${adopted.length} entr(ies) replaced by "${entryName}"`);
|
|
1386
|
+
const registryIdUsed = registration ? commitRegistration(registration, write) : undefined;
|
|
1387
|
+
const replaced = { ...(args.backup?.replaced ?? {}) };
|
|
1388
|
+
for (const name of adopted)
|
|
1389
|
+
replaced[name] = file.servers[name];
|
|
1390
|
+
writeBackup(target, {
|
|
1391
|
+
version: 1,
|
|
1392
|
+
created_at: new Date().toISOString(),
|
|
1393
|
+
scope: target.scope,
|
|
1394
|
+
config_path: target.path,
|
|
1395
|
+
gateway_entry_name: entryName,
|
|
1396
|
+
replaced,
|
|
1397
|
+
generated: [generated.configPath, generated.policyPath],
|
|
1398
|
+
...(registryIdUsed !== undefined ? { registry_id: registryIdUsed } : {}),
|
|
1399
|
+
...(args.backup?.client_allow ? { client_allow: args.backup.client_allow } : {})
|
|
1400
|
+
});
|
|
1401
|
+
/*
|
|
1402
|
+
* Both backups hold the original entries verbatim, so if one of those
|
|
1403
|
+
* carried a literal credential rather than a `${VAR}`, adoption has just
|
|
1404
|
+
* written that credential into two new files. Said out loud, because the
|
|
1405
|
+
* files are new and whatever protected the original -- a gitignore rule, a
|
|
1406
|
+
* mode -- does not cover them.
|
|
1407
|
+
*/
|
|
1408
|
+
if (hasLiteralSecret(replaced)) {
|
|
1409
|
+
write("");
|
|
1410
|
+
write("One of the replaced entries held a literal value in `env` or `headers`, which both");
|
|
1411
|
+
write("backups now contain. If the original config was kept out of version control, keep");
|
|
1412
|
+
write(`these out too: ${wholeFileBackupPath(target)} and ${backupPath(target)}.`);
|
|
1413
|
+
}
|
|
1414
|
+
return registryIdUsed;
|
|
1415
|
+
}
|
|
1416
|
+
/**
|
|
1417
|
+
* Whether any replaced entry carried a value that is a secret rather than a
|
|
1418
|
+
* reference to one.
|
|
1419
|
+
*
|
|
1420
|
+
* A `${VAR}` is a pointer and costs nothing to copy; anything else might be
|
|
1421
|
+
* the credential itself. Deliberately not trying to tell a token from a
|
|
1422
|
+
* setting: the point is to say "look at this", not to classify it.
|
|
1423
|
+
*/
|
|
1424
|
+
function hasLiteralSecret(replaced) {
|
|
1425
|
+
return literalSecretNames(replaced).length > 0;
|
|
1426
|
+
}
|
|
1427
|
+
/** A setting's name that says it carries a key. `PAT` only as a word, so `MEMORY_FILE_PATH` is not one. */
|
|
1428
|
+
const KEYISH_NAME = /(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION|(^|[_-])PAT($|[_-]))/i;
|
|
1429
|
+
/**
|
|
1430
|
+
* The env and header names whose literal value looks like a key: by its name,
|
|
1431
|
+
* or by the value's own shape (a GitHub token, a Stripe key...). A file path
|
|
1432
|
+
* in `MEMORY_FILE_PATH` is not a secret, and warning about every setting
|
|
1433
|
+
* trains people to skip the warning that matters.
|
|
1434
|
+
*/
|
|
1435
|
+
function literalSecretNames(replaced) {
|
|
1436
|
+
const out = [];
|
|
1437
|
+
for (const entry of Object.values(replaced)) {
|
|
1438
|
+
if (typeof entry !== "object" || entry === null)
|
|
1439
|
+
continue;
|
|
1440
|
+
for (const field of ["env", "headers"]) {
|
|
1441
|
+
const block = entry[field];
|
|
1442
|
+
if (typeof block !== "object" || block === null)
|
|
1443
|
+
continue;
|
|
1444
|
+
for (const [name, value] of Object.entries(block)) {
|
|
1445
|
+
if (typeof value !== "string" || value === "" || /\$\{[^}]*\}/.test(value))
|
|
1446
|
+
continue;
|
|
1447
|
+
if (KEYISH_NAME.test(name) || SECRET_VALUE_PATTERNS.some((p) => p.regex.test(value)))
|
|
1448
|
+
out.push(name);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
return [...new Set(out)];
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* What the console calls the toolbox: the app, and for a project the folder
|
|
1456
|
+
* -- "webapp, VS Code", "Cursor, all projects" -- not the folder the files
|
|
1457
|
+
* sit in (".hmcp (user)", UT5).
|
|
1458
|
+
*/
|
|
1459
|
+
function registryLabel(target, options) {
|
|
1460
|
+
const app = target.client.replace(/ \((this|all) projects?\)$/, "");
|
|
1461
|
+
if (USER_WIDE.has(target.scope)) {
|
|
1462
|
+
const label = target.scope === "user" || target.client.endsWith("(all projects)") ? `${app}, all projects` : app;
|
|
1463
|
+
return { label, idHint: defaultNameFor(target.scope) };
|
|
1464
|
+
}
|
|
1465
|
+
const folder = basename(resolve(options.cwd ?? process.cwd())) || "project";
|
|
1466
|
+
return { label: `${folder}, ${app}${target.scope === "local" ? " (only you)" : ""}`, idHint: folder };
|
|
1467
|
+
}
|
|
1468
|
+
/** Decides the registry row and proves it can be written, without writing it. */
|
|
1469
|
+
function prepareRegistration(args) {
|
|
1470
|
+
const { generated, options, target } = args;
|
|
1471
|
+
const registryPath = options.registry ?? defaultRegistryPath();
|
|
1472
|
+
// Validate the config before persisting a path the console will later open.
|
|
1473
|
+
// This is the same check `loadServer` makes, done here rather than by
|
|
1474
|
+
// importing it: the console package depends on this one, so reaching back
|
|
1475
|
+
// into it would turn the dependency into a cycle.
|
|
1476
|
+
loadGatewayConfig(generated.configPath);
|
|
1477
|
+
const registry = readRegistry(registryPath);
|
|
1478
|
+
if (args.backup?.registry_id) {
|
|
1479
|
+
const already = registry.servers.find((s) => s.id === args.backup.registry_id);
|
|
1480
|
+
if (already)
|
|
1481
|
+
return { registryPath, entry: undefined, existingId: already.id };
|
|
1482
|
+
}
|
|
1483
|
+
// One row per toolbox: a toolbox already registered (an earlier connection, or another app's) is not listed twice.
|
|
1484
|
+
const sameFile = registry.servers.find((s) => s.config_path === generated.configPath);
|
|
1485
|
+
if (sameFile)
|
|
1486
|
+
return { registryPath, entry: undefined, existingId: sameFile.id };
|
|
1487
|
+
const taken = new Set(registry.servers.map((s) => s.id));
|
|
1488
|
+
if (options.id !== undefined && taken.has(options.id)) {
|
|
1489
|
+
throw new AdoptCommandError(`the registry at ${registryPath} already has a server with id "${options.id}". ` +
|
|
1490
|
+
`Pass a different --id, or --no-register.`);
|
|
1491
|
+
}
|
|
1492
|
+
const { label, idHint } = registryLabel(target, options);
|
|
1493
|
+
return {
|
|
1494
|
+
registryPath,
|
|
1495
|
+
entry: {
|
|
1496
|
+
id: options.id ?? registryId(idHint, taken),
|
|
1497
|
+
kind: "gateway",
|
|
1498
|
+
label,
|
|
1499
|
+
// Absolute, always: the console expands this against its own working
|
|
1500
|
+
// directory, which is not this one.
|
|
1501
|
+
config_path: generated.configPath,
|
|
1502
|
+
added_at: new Date().toISOString()
|
|
1503
|
+
},
|
|
1504
|
+
existingId: undefined
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
function commitRegistration(registration, write) {
|
|
1508
|
+
if (registration.entry === undefined)
|
|
1509
|
+
return registration.existingId;
|
|
1510
|
+
const registry = readRegistry(registration.registryPath);
|
|
1511
|
+
writeRegistry({ ...registry, servers: [...registry.servers, registration.entry] }, registration.registryPath);
|
|
1512
|
+
write(`Registered with the console as "${registration.entry.id}" in ${registration.registryPath}`);
|
|
1513
|
+
return registration.entry.id;
|
|
1514
|
+
}
|
|
1515
|
+
function printChecklist(args) {
|
|
1516
|
+
const { generated, entryName, starting, write } = args;
|
|
1517
|
+
if (starting.mode === "observe") {
|
|
1518
|
+
write("");
|
|
1519
|
+
write("Done. The gateway is in OBSERVE MODE: it records, and enforces nothing yet.");
|
|
1520
|
+
write("");
|
|
1521
|
+
write(` 1. hmcp-gateway status -c ${generated.configPath}`);
|
|
1522
|
+
write(" Says which mode it is in, in capitals when it is this one.");
|
|
1523
|
+
write(" 2. Restart the client. It reads its MCP config at startup, and a new");
|
|
1524
|
+
write(" project-scope server may need approving there first.");
|
|
1525
|
+
write(` 3. Use your agent as you normally would. "${entryName}" carries the tools,`);
|
|
1526
|
+
write(" namespaced, and every call goes through exactly as it did before.");
|
|
1527
|
+
write(" 4. hmcp audit tail");
|
|
1528
|
+
write(" Each call, with what the policy would have done to it.");
|
|
1529
|
+
write(` 5. hmcp-gateway suggest -c ${generated.configPath}`);
|
|
1530
|
+
write(" What enforcing would have refused or held, which tools nothing");
|
|
1531
|
+
write(" classified, and rules that fit what your agent actually did.");
|
|
1532
|
+
write(` 6. When the policy says what you want, set "enforcement: enforce" in`);
|
|
1533
|
+
write(` ${generated.policyPath}`);
|
|
1534
|
+
write(" A running gateway picks that up without a restart.");
|
|
1535
|
+
write("");
|
|
1536
|
+
write(" Until step 6 nothing is refused or held, except a tool you switch off:");
|
|
1537
|
+
write(" hmcp-gateway exposure off <tool>");
|
|
1538
|
+
write("");
|
|
1539
|
+
printConsoleNote(write);
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
write("");
|
|
1543
|
+
write("Done. To confirm it is actually enforcing, in this order:");
|
|
1544
|
+
write("");
|
|
1545
|
+
write(` 1. hmcp-gateway tools -c ${generated.configPath}`);
|
|
1546
|
+
write(" The gateway's own view, with the client not involved yet.");
|
|
1547
|
+
write(" 2. Restart the client. It reads its MCP config at startup, and a new");
|
|
1548
|
+
write(" project-scope server may need approving there first.");
|
|
1549
|
+
write(` 3. Ask it to list its tools. "${entryName}" should carry the namespaced ones.`);
|
|
1550
|
+
write(" 4. Call a read tool. It should simply work.");
|
|
1551
|
+
write(" 5. Call a write tool. It should wait -- either the client prompts, or");
|
|
1552
|
+
write(" `hmcp pending` shows it and `hmcp approve <id>` releases it.");
|
|
1553
|
+
if (starting.onUnclassified === "deny") {
|
|
1554
|
+
write(" 6. Call one of the unclassified tools listed above. It should be refused,");
|
|
1555
|
+
write(" naming defaults.on_unclassified. This is the step that proves the");
|
|
1556
|
+
write(" gateway is in the path rather than merely installed.");
|
|
1557
|
+
}
|
|
1558
|
+
else {
|
|
1559
|
+
write(" 6. Call one of the unclassified tools listed above. It should wait like a");
|
|
1560
|
+
write(" write does, naming defaults.on_unclassified, and");
|
|
1561
|
+
write(" `hmcp approve <id> --classify read` (or write, or destructive) both");
|
|
1562
|
+
write(" releases it and stops it asking. This is the step that proves the");
|
|
1563
|
+
write(" gateway is in the path rather than merely installed.");
|
|
1564
|
+
}
|
|
1565
|
+
write(" 7. hmcp audit tail -- every one of those calls, allowed or not.");
|
|
1566
|
+
write("");
|
|
1567
|
+
printConsoleNote(write);
|
|
1568
|
+
}
|
|
1569
|
+
function printConsoleNote(write) {
|
|
1570
|
+
write(" The console (hmcp-web) will show this gateway registered but with NO tools");
|
|
1571
|
+
write(" until it has served at least once, and will mark them stale whenever no");
|
|
1572
|
+
write(" gateway process is alive: the tool list it shows is what a running gateway");
|
|
1573
|
+
write(" published, not something the console goes and asks for. Over stdio the");
|
|
1574
|
+
write(" gateway lives only while the client holds the session, so the console is");
|
|
1575
|
+
write(" live only while the client is running. That is expected, not a failed");
|
|
1576
|
+
write(" adoption.");
|
|
1577
|
+
write("");
|
|
1578
|
+
write(" hmcp-gateway adopt --revert puts the original entries back.");
|
|
1579
|
+
}
|
|
1580
|
+
/** The locked-key names a gateway.yaml's servers refer to; none when it can't be read. */
|
|
1581
|
+
function lockedKeysNamedIn(configPath) {
|
|
1582
|
+
try {
|
|
1583
|
+
// Read as written, not loaded: loading also needs its policy file, which a purge may have taken already.
|
|
1584
|
+
const doc = parseYaml(readFileSync(configPath, "utf8"));
|
|
1585
|
+
const names = (doc?.upstreams ?? []).flatMap((u) => {
|
|
1586
|
+
const record = { ...(u["env"] ?? {}), ...(u["headers"] ?? {}) };
|
|
1587
|
+
const refs = Object.values(record).flatMap((v) => (v && typeof v === "object" && "secret" in v ? [String(v.secret)] : []));
|
|
1588
|
+
const oauth = u["oauth"]?.secret;
|
|
1589
|
+
return typeof oauth === "string" ? [...refs, oauth] : refs;
|
|
1590
|
+
});
|
|
1591
|
+
return [...new Set(names)].sort();
|
|
1592
|
+
}
|
|
1593
|
+
catch {
|
|
1594
|
+
return [];
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
/**
|
|
1598
|
+
* The apps (other than the one being undone) whose settings still have an
|
|
1599
|
+
* entry running this toolbox: one whose `-c` names its gateway.yaml.
|
|
1600
|
+
*/
|
|
1601
|
+
function appsStillUsing(backup, undoing, scopeOptions, registryPath) {
|
|
1602
|
+
const configs = new Set();
|
|
1603
|
+
for (const path of backup.generated)
|
|
1604
|
+
if (basename(path) === "gateway.yaml")
|
|
1605
|
+
configs.add(resolve(path));
|
|
1606
|
+
if (backup.registry_id) {
|
|
1607
|
+
try {
|
|
1608
|
+
const row = readRegistry(registryPath).servers.find((s) => s.id === backup.registry_id);
|
|
1609
|
+
if (row)
|
|
1610
|
+
configs.add(resolve(row.config_path));
|
|
1611
|
+
}
|
|
1612
|
+
catch {
|
|
1613
|
+
/* no registry: only the generated files say which toolbox this is */
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
if (configs.size === 0)
|
|
1617
|
+
return [];
|
|
1618
|
+
const out = [];
|
|
1619
|
+
for (const target of scopeTargets(scopeOptions)) {
|
|
1620
|
+
if (target.scope === undoing.scope)
|
|
1621
|
+
continue;
|
|
1622
|
+
try {
|
|
1623
|
+
const { servers } = parseServers(readClientConfig(target.scope, scopeOptions).servers, { httpOnly: target.httpOnly });
|
|
1624
|
+
const uses = [...servers.values()].some((server) => {
|
|
1625
|
+
if (isRemote(server))
|
|
1626
|
+
return false;
|
|
1627
|
+
const i = server.args.indexOf("-c");
|
|
1628
|
+
const at = i >= 0 ? server.args[i + 1] : undefined;
|
|
1629
|
+
return at !== undefined && configs.has(resolve(dirname(target.path), at));
|
|
1630
|
+
});
|
|
1631
|
+
if (uses && !out.includes(target.client))
|
|
1632
|
+
out.push(target.client);
|
|
1633
|
+
}
|
|
1634
|
+
catch {
|
|
1635
|
+
/* an unreadable file is not evidence either way */
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
return out;
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* Undoing one adoption.
|
|
1642
|
+
*
|
|
1643
|
+
* `guarded` is for a caller that did not write the backup it is reading and
|
|
1644
|
+
* cannot see it: a backup sits beside the client config, which for a project
|
|
1645
|
+
* scope is inside a checkout someone else may have written. Guarded, purge
|
|
1646
|
+
* deletes only a gateway.yaml or policy.yaml that still carries adopt's own
|
|
1647
|
+
* header, and the registry row goes only if it points at a file this backup
|
|
1648
|
+
* generated. The CLI is not guarded, and prints what it did exactly as before.
|
|
1649
|
+
*/
|
|
1650
|
+
async function revertEngine(options, write, guarded) {
|
|
1651
|
+
const scopeOptions = {
|
|
1652
|
+
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
|
|
1653
|
+
...(options.home !== undefined ? { home: options.home } : {})
|
|
1654
|
+
};
|
|
1655
|
+
/*
|
|
1656
|
+
* Revert reads the backup, so it cannot use the populated-scope heuristic:
|
|
1657
|
+
* after adoption the scope holds one entry, and the scope that was adopted
|
|
1658
|
+
* is the one with a backup beside it.
|
|
1659
|
+
*/
|
|
1660
|
+
const targets = options.scope
|
|
1661
|
+
? [resolveScope(options.scope, scopeOptions)]
|
|
1662
|
+
: scopeTargets(scopeOptions);
|
|
1663
|
+
const found = targets.map((target) => ({ target, backup: readBackup(target) })).filter((t) => t.backup);
|
|
1664
|
+
if (found.length === 0) {
|
|
1665
|
+
throw new AdoptCommandError("found no adoption backup, so there is nothing to revert. Looked beside:\n" +
|
|
1666
|
+
targets.map((t) => ` ${t.path}`).join("\n"));
|
|
1667
|
+
}
|
|
1668
|
+
if (found.length > 1) {
|
|
1669
|
+
throw new AdoptCommandError("more than one scope has an adoption backup. Pass --scope to say which to revert:\n" +
|
|
1670
|
+
found.map((f) => ` --scope ${f.target.scope.padEnd(15)} ${f.target.path} (${f.target.client})`).join("\n"));
|
|
1671
|
+
}
|
|
1672
|
+
const { target, backup } = found[0];
|
|
1673
|
+
const file = readClientConfig(target.scope, scopeOptions);
|
|
1674
|
+
const servers = { ...file.servers };
|
|
1675
|
+
const entry = servers[backup.gateway_entry_name];
|
|
1676
|
+
if (entry === undefined) {
|
|
1677
|
+
write(`"${backup.gateway_entry_name}" is not in ${target.path} any more; restoring the originals anyway.`);
|
|
1678
|
+
}
|
|
1679
|
+
/*
|
|
1680
|
+
* A name taken since adoption is reported rather than clobbered. Whatever is
|
|
1681
|
+
* sitting there now is something the user added on purpose, and it is not
|
|
1682
|
+
* this command's to overwrite on the way to undoing its own work.
|
|
1683
|
+
*/
|
|
1684
|
+
// The very entry being restored (the app wrote its old list back) needs nothing, and is no collision.
|
|
1685
|
+
const collisions = Object.keys(backup.replaced).filter((name) => servers[name] !== undefined && name !== backup.gateway_entry_name && !sameJson(servers[name], backup.replaced[name]));
|
|
1686
|
+
if (collisions.length > 0) {
|
|
1687
|
+
throw new AdoptCommandError(`these names were adopted, and ${target.path} now has a different server under each:\n` +
|
|
1688
|
+
collisions.map((n) => ` ${n}`).join("\n") +
|
|
1689
|
+
`\nRename or remove them first; restoring over them would discard what is there now.`);
|
|
1690
|
+
}
|
|
1691
|
+
delete servers[backup.gateway_entry_name];
|
|
1692
|
+
for (const [name, original] of Object.entries(backup.replaced))
|
|
1693
|
+
servers[name] = original;
|
|
1694
|
+
const restoredFile = restoreClientConfig(file, servers);
|
|
1695
|
+
write(`Restored ${Object.keys(backup.replaced).length} entr(ies) to ${target.path}`);
|
|
1696
|
+
if (restoredFile.how === "bytes")
|
|
1697
|
+
write(`${target.path} is back exactly as it was; its copy was removed.`);
|
|
1698
|
+
if (restoredFile.how === "removed")
|
|
1699
|
+
write(`${target.path} did not exist before, so it was removed again.`);
|
|
1700
|
+
if (restoredFile.backupLeft) {
|
|
1701
|
+
write(`${target.path} changed since, so a copy of it as it was is kept at ${restoredFile.backupLeft}. It holds the old values.`);
|
|
1702
|
+
}
|
|
1703
|
+
let clientAllowRemoved = null;
|
|
1704
|
+
let clientAllowError = null;
|
|
1705
|
+
if (backup.client_allow) {
|
|
1706
|
+
const { path, rule } = backup.client_allow;
|
|
1707
|
+
try {
|
|
1708
|
+
if (removeAllowRule(path, rule)) {
|
|
1709
|
+
write(`Removed ${JSON.stringify(rule)} from permissions.allow in ${path}`);
|
|
1710
|
+
clientAllowRemoved = { path, rule };
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
catch (err) {
|
|
1714
|
+
// The servers are already back. A settings file that can no longer be
|
|
1715
|
+
// read is reported, not allowed to fail the undo half-way.
|
|
1716
|
+
write(`Could not remove ${JSON.stringify(rule)} from ${path}: ${err.message}`);
|
|
1717
|
+
clientAllowError = err.message;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
let registryRemoved = null;
|
|
1721
|
+
/*
|
|
1722
|
+
* Another app may still run this toolbox: it was adopted from Claude Code
|
|
1723
|
+
* and then connected to Claude Desktop from the console, say. Undoing one
|
|
1724
|
+
* app's connection takes away that app's entry and nothing else; the
|
|
1725
|
+
* toolbox, its files and its console row stay while anything points at it.
|
|
1726
|
+
*/
|
|
1727
|
+
const stillUsedBy = appsStillUsing(backup, target, scopeOptions, options.registry ?? defaultRegistryPath());
|
|
1728
|
+
if (stillUsedBy.length > 0) {
|
|
1729
|
+
write(`Kept the toolbox: ${stillUsedBy.join(", ")} still ${stillUsedBy.length === 1 ? "uses" : "use"} it.`);
|
|
1730
|
+
}
|
|
1731
|
+
/*
|
|
1732
|
+
* A backup that generated nothing is a connection made from the console:
|
|
1733
|
+
* the gateway existed before it and goes on existing after it, with its own
|
|
1734
|
+
* row in the console. Undo takes the app's entry away and nothing else.
|
|
1735
|
+
*/
|
|
1736
|
+
if (backup.registry_id && backup.generated.length > 0 && stillUsedBy.length === 0) {
|
|
1737
|
+
const registryPath = options.registry ?? defaultRegistryPath();
|
|
1738
|
+
const registry = readRegistry(registryPath);
|
|
1739
|
+
const generated = new Set(backup.generated.map((p) => resolve(p)));
|
|
1740
|
+
const kept = registry.servers.filter((s) => s.id !== backup.registry_id || (guarded && !generated.has(resolve(s.config_path))));
|
|
1741
|
+
if (kept.length !== registry.servers.length) {
|
|
1742
|
+
writeRegistry({ ...registry, servers: kept }, registryPath);
|
|
1743
|
+
write(`Removed "${backup.registry_id}" from ${registryPath}`);
|
|
1744
|
+
registryRemoved = backup.registry_id;
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
/*
|
|
1748
|
+
* The keys this toolbox kept locked (moved there when it was connected, or
|
|
1749
|
+
* typed in since). Undo puts the app's file back as it was and leaves the
|
|
1750
|
+
* locked keys alone: another toolbox may use them too. Said, so a copy isn't
|
|
1751
|
+
* left behind without a word.
|
|
1752
|
+
*/
|
|
1753
|
+
const keysKept = lockedKeysNamedIn(backup.generated.find((p) => basename(p) === "gateway.yaml") ?? backup.config_path);
|
|
1754
|
+
const deleted = [];
|
|
1755
|
+
const refusedToDelete = [];
|
|
1756
|
+
let leftInPlace = [];
|
|
1757
|
+
if (options.purge && stillUsedBy.length > 0) {
|
|
1758
|
+
leftInPlace = [...backup.generated.filter((p) => existsSync(p))];
|
|
1759
|
+
for (const path of leftInPlace)
|
|
1760
|
+
refusedToDelete.push({ path, why: `${stillUsedBy.join(", ")} still uses this toolbox` });
|
|
1761
|
+
leftInPlace = [];
|
|
1762
|
+
}
|
|
1763
|
+
else if (options.purge) {
|
|
1764
|
+
for (const path of backup.generated) {
|
|
1765
|
+
if (!existsSync(path))
|
|
1766
|
+
continue;
|
|
1767
|
+
if (guarded) {
|
|
1768
|
+
const name = basename(path);
|
|
1769
|
+
if (name !== "gateway.yaml" && name !== "policy.yaml") {
|
|
1770
|
+
refusedToDelete.push({ path, why: "it is not a gateway.yaml or policy.yaml" });
|
|
1771
|
+
continue;
|
|
1772
|
+
}
|
|
1773
|
+
if (!isAdoptFile(path)) {
|
|
1774
|
+
refusedToDelete.push({ path, why: "it no longer starts with the header adopt writes" });
|
|
1775
|
+
continue;
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
unlinkSync(path);
|
|
1779
|
+
write(`Deleted ${path}`);
|
|
1780
|
+
deleted.push(path);
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
else if (backup.generated.length > 0) {
|
|
1784
|
+
write(`Left in place: ${backup.generated.join(", ")} (--purge deletes them)`);
|
|
1785
|
+
leftInPlace = [...backup.generated];
|
|
1786
|
+
}
|
|
1787
|
+
const record = backupPath(target);
|
|
1788
|
+
if (existsSync(record))
|
|
1789
|
+
unlinkSync(record);
|
|
1790
|
+
tidyProjectBackups(target);
|
|
1791
|
+
if (keysKept.length > 0) {
|
|
1792
|
+
write(`These keys stay in your locked keys: ${keysKept.join(", ")}. Remove them under Settings & help, Locked keys, if nothing else uses them.`);
|
|
1793
|
+
}
|
|
1794
|
+
write("Restart the client to pick up the restored servers.");
|
|
1795
|
+
return {
|
|
1796
|
+
keysKept,
|
|
1797
|
+
scope: target.scope,
|
|
1798
|
+
client: target.client,
|
|
1799
|
+
clientConfigPath: target.path,
|
|
1800
|
+
restored: Object.keys(backup.replaced),
|
|
1801
|
+
entryMissing: entry === undefined,
|
|
1802
|
+
clientAllowRemoved,
|
|
1803
|
+
clientAllowError,
|
|
1804
|
+
registryRemoved,
|
|
1805
|
+
deleted,
|
|
1806
|
+
leftInPlace,
|
|
1807
|
+
refusedToDelete,
|
|
1808
|
+
backupRemoved: record,
|
|
1809
|
+
stillUsedBy,
|
|
1810
|
+
fileRestored: restoredFile.how,
|
|
1811
|
+
copyLeft: restoredFile.backupLeft
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
export async function runRevertCommand(options) {
|
|
1815
|
+
await revertEngine(options, out(options), false);
|
|
1816
|
+
}
|
|
1817
|
+
/** Puts one scope back as it was before adoption. Purge deletes only files adopt wrote. */
|
|
1818
|
+
export async function adoptRevert(options) {
|
|
1819
|
+
return revertEngine(options, quiet, true);
|
|
1820
|
+
}
|
|
1821
|
+
/** Whether the app owning this scope looks installed on this computer. */
|
|
1822
|
+
function looksInstalled(target, home) {
|
|
1823
|
+
if (existsSync(target.path))
|
|
1824
|
+
return true;
|
|
1825
|
+
switch (target.scope) {
|
|
1826
|
+
case "user":
|
|
1827
|
+
case "local":
|
|
1828
|
+
return existsSync(join(home, ".claude"));
|
|
1829
|
+
case "junie":
|
|
1830
|
+
case "junie-project":
|
|
1831
|
+
// Junie's file is in an `mcp` folder of its own, made only when a server is added.
|
|
1832
|
+
return existsSync(dirname(dirname(target.path)));
|
|
1833
|
+
case "project":
|
|
1834
|
+
case "cursor-project":
|
|
1835
|
+
case "vscode-project":
|
|
1836
|
+
case "antigravity-project":
|
|
1837
|
+
case "devin-project":
|
|
1838
|
+
case "roo-project":
|
|
1839
|
+
case "codex-project":
|
|
1840
|
+
// A project file is about the folder, not an installed app.
|
|
1841
|
+
return existsSync(dirname(target.path));
|
|
1842
|
+
default:
|
|
1843
|
+
return existsSync(dirname(target.path));
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* Every scope this build knows, and what is in each, without writing.
|
|
1848
|
+
*
|
|
1849
|
+
* `canRevert` checks the backup's own scope: `local` and `user` share
|
|
1850
|
+
* `~/.claude.json`, and so share the one backup file beside it.
|
|
1851
|
+
*/
|
|
1852
|
+
export function detectClients(options = {}) {
|
|
1853
|
+
const scopeOptions = {
|
|
1854
|
+
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
|
|
1855
|
+
...(options.home !== undefined ? { home: options.home } : {}),
|
|
1856
|
+
...(options.platform !== undefined ? { platform: options.platform } : {})
|
|
1857
|
+
};
|
|
1858
|
+
const entryName = options.entryName ?? DEFAULT_ENTRY_NAME;
|
|
1859
|
+
const home = options.home ?? homedir();
|
|
1860
|
+
return scopeTargets(scopeOptions).map((target) => {
|
|
1861
|
+
const base = {
|
|
1862
|
+
scope: target.scope,
|
|
1863
|
+
client: target.client,
|
|
1864
|
+
path: target.path,
|
|
1865
|
+
where: target.where,
|
|
1866
|
+
installed: looksInstalled(target, home)
|
|
1867
|
+
};
|
|
1868
|
+
try {
|
|
1869
|
+
const file = readClientConfig(target.scope, scopeOptions);
|
|
1870
|
+
const { servers } = parseServers(file.servers, { httpOnly: target.httpOnly });
|
|
1871
|
+
const backup = readBackup(target);
|
|
1872
|
+
return {
|
|
1873
|
+
...base,
|
|
1874
|
+
exists: file.exists,
|
|
1875
|
+
serverCount: Object.keys(file.servers).length,
|
|
1876
|
+
alreadyAdopted: [...servers.entries()].some(([name, server]) => isOurGateway(name, server, entryName)),
|
|
1877
|
+
canRevert: backup !== undefined && backup.scope === target.scope,
|
|
1878
|
+
error: null
|
|
1879
|
+
};
|
|
1880
|
+
}
|
|
1881
|
+
catch (err) {
|
|
1882
|
+
return { ...base, exists: existsSync(target.path), serverCount: 0, alreadyAdopted: false, canRevert: false, error: err.message };
|
|
1883
|
+
}
|
|
1884
|
+
});
|
|
1885
|
+
}
|