hmcp-web 0.0.1 → 0.1.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 +48 -2
- package/THIRD-PARTY-NOTICES.md +110 -0
- package/bin/hmcp-web.js +20 -0
- package/dist/api.d.ts +11 -0
- package/dist/api.js +1404 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +40 -0
- package/dist/contracts/onboarding.d.ts +233 -0
- package/dist/contracts/onboarding.js +1 -0
- package/dist/http.d.ts +72 -0
- package/dist/http.js +319 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/model/console-settings.d.ts +37 -0
- package/dist/model/console-settings.js +74 -0
- package/dist/model/doctor.d.ts +68 -0
- package/dist/model/doctor.js +254 -0
- package/dist/model/fs-browse.d.ts +9 -0
- package/dist/model/fs-browse.js +184 -0
- package/dist/model/gateway-config.d.ts +287 -0
- package/dist/model/gateway-config.js +760 -0
- package/dist/model/metrics.d.ts +65 -0
- package/dist/model/metrics.js +198 -0
- package/dist/model/oauth-flows.d.ts +60 -0
- package/dist/model/oauth-flows.js +79 -0
- package/dist/model/pipeline.d.ts +58 -0
- package/dist/model/pipeline.js +84 -0
- package/dist/model/probe.d.ts +155 -0
- package/dist/model/probe.js +385 -0
- package/dist/model/process.d.ts +100 -0
- package/dist/model/process.js +278 -0
- package/dist/model/protection.d.ts +378 -0
- package/dist/model/protection.js +470 -0
- package/dist/model/registry-cache.d.ts +59 -0
- package/dist/model/registry-cache.js +238 -0
- package/dist/model/scan.d.ts +48 -0
- package/dist/model/scan.js +59 -0
- package/dist/model/server.d.ts +127 -0
- package/dist/model/server.js +243 -0
- package/dist/model/tools.d.ts +61 -0
- package/dist/model/tools.js +72 -0
- package/dist/routes/catalog.d.ts +8 -0
- package/dist/routes/catalog.js +47 -0
- package/dist/routes/connect.d.ts +14 -0
- package/dist/routes/connect.js +633 -0
- package/dist/routes/oauth.d.ts +55 -0
- package/dist/routes/oauth.js +406 -0
- package/dist/routes/policy.d.ts +34 -0
- package/dist/routes/policy.js +513 -0
- package/dist/routes/runtime.d.ts +6 -0
- package/dist/routes/runtime.js +921 -0
- package/dist/routes/servers-add.d.ts +24 -0
- package/dist/routes/servers-add.js +1091 -0
- package/dist/routes/system.d.ts +4 -0
- package/dist/routes/system.js +13 -0
- package/dist/start.d.ts +56 -0
- package/dist/start.js +164 -0
- package/dist-ui/assets/Activity-BqKGpXMN.js +1 -0
- package/dist-ui/assets/Approvals-Qo7bCcli.js +1 -0
- package/dist-ui/assets/AttachApp-0zRSPgSY.js +5 -0
- package/dist-ui/assets/Connections-CE0JGe8c.js +2 -0
- package/dist-ui/assets/Gallery-B39L2Yma.js +17 -0
- package/dist-ui/assets/PreApprovals-BsIhjMqb.js +1 -0
- package/dist-ui/assets/Protection-DlB09ABa.js +1 -0
- package/dist-ui/assets/Safety-CN-oHO2h.js +1 -0
- package/dist-ui/assets/Settings-BLD7G1Ag.js +1 -0
- package/dist-ui/assets/StartPage-HuZSnmSr.js +1 -0
- package/dist-ui/assets/Suggestions-Dp7pofcs.js +1 -0
- package/dist-ui/assets/Tools-Bfot3bx5.js +4 -0
- package/dist-ui/assets/index-Khp0l1zp.js +16 -0
- package/dist-ui/assets/index-Ylyt4DEr.css +2 -0
- package/dist-ui/assets/kit-DQ7Oxf5n.js +4 -0
- package/dist-ui/brand/logo-256.png +0 -0
- package/dist-ui/brand/logo-512.png +0 -0
- package/dist-ui/brand/logo.svg +6 -0
- package/dist-ui/brand/mark.svg +5 -0
- package/dist-ui/fonts/OFL.txt +99 -0
- package/dist-ui/fonts/README.md +21 -0
- package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
- package/dist-ui/fonts/manrope-latin.woff2 +0 -0
- package/dist-ui/index.html +51 -0
- package/package.json +69 -6
- package/bin/notice.js +0 -7
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { stringify } from "yaml";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { AuditLog, readRegistry, writeRegistry } from "hmcp-core";
|
|
7
|
+
import { AdoptCommandError, AdoptRefusedError, ClientConfigError, UpstreamSchema, adoptApply, adoptPlan, adoptRevert, connectClient, detectClients, emitPolicyYaml, isLocalTarget, loadGatewayConfig, readBackup, resolveScope } from "hmcp-gateway";
|
|
8
|
+
import { badRequest, conflict, HttpError, route, unprocessable } from "../http.js";
|
|
9
|
+
/**
|
|
10
|
+
* Connecting the AI apps a person already uses: `hmcp-gateway adopt`, from
|
|
11
|
+
* the console.
|
|
12
|
+
*
|
|
13
|
+
* These are the only console routes that write outside `~/.hmcp`: they edit
|
|
14
|
+
* another program's config. So every path written is one the gateway's own
|
|
15
|
+
* `scopeTargets` resolves for a named scope, plus the generated pair in a
|
|
16
|
+
* validated directory. Nothing here takes a file path to write from the
|
|
17
|
+
* browser beyond `projectDir` and `outDir`, and both are checked to be
|
|
18
|
+
* absolute, plain, existing directories first.
|
|
19
|
+
*
|
|
20
|
+
* The engine is the CLI's own, so a plan here and `adopt` at a terminal can
|
|
21
|
+
* never disagree about what would happen.
|
|
22
|
+
*/
|
|
23
|
+
const SCOPES = [
|
|
24
|
+
"project",
|
|
25
|
+
"local",
|
|
26
|
+
"user",
|
|
27
|
+
"claude-desktop",
|
|
28
|
+
"cursor-project",
|
|
29
|
+
"cursor-user",
|
|
30
|
+
"vscode-project",
|
|
31
|
+
"vscode-user",
|
|
32
|
+
"windsurf"
|
|
33
|
+
];
|
|
34
|
+
const ScopeSchema = z.enum(SCOPES);
|
|
35
|
+
/** The scopes whose file lives in a project, so need a project folder to find it. */
|
|
36
|
+
const PROJECT_SCOPES = new Set(["project", "local", "cursor-project", "vscode-project"]);
|
|
37
|
+
/** The client allow rule is a Claude Code permission; the other apps never read it. */
|
|
38
|
+
const CLAUDE_CODE_SCOPES = new Set(["project", "local", "user"]);
|
|
39
|
+
const LABELS = {
|
|
40
|
+
project: "Claude Code — this project",
|
|
41
|
+
local: "Claude Code — this project, only you",
|
|
42
|
+
user: "Claude Code — all projects",
|
|
43
|
+
"claude-desktop": "Claude Desktop",
|
|
44
|
+
"cursor-project": "Cursor — this project",
|
|
45
|
+
"cursor-user": "Cursor — all projects",
|
|
46
|
+
"vscode-project": "VS Code — this project",
|
|
47
|
+
"vscode-user": "VS Code — all projects",
|
|
48
|
+
windsurf: "Windsurf"
|
|
49
|
+
};
|
|
50
|
+
const REGISTRY_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
51
|
+
const AdoptBody = z
|
|
52
|
+
.object({
|
|
53
|
+
scope: ScopeSchema,
|
|
54
|
+
projectDir: z.string().min(1).optional(),
|
|
55
|
+
/** Original name in the client config -> upstream name in the gateway. */
|
|
56
|
+
rename: z.record(z.string().min(1), z.string().min(1)).optional(),
|
|
57
|
+
gatewayName: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/).optional(),
|
|
58
|
+
entryName: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/).optional(),
|
|
59
|
+
posture: z.enum(["read-only", "approve-writes", "locked"]).optional(),
|
|
60
|
+
mode: z.enum(["observe", "enforce"]).optional(),
|
|
61
|
+
onUnclassified: z.enum(["deny", "approve"]).optional(),
|
|
62
|
+
packs: z.boolean().optional(),
|
|
63
|
+
clientAllow: z.boolean().optional(),
|
|
64
|
+
copyEnv: z.boolean().optional(),
|
|
65
|
+
allowLocalHttp: z.boolean().optional(),
|
|
66
|
+
strictEgress: z.boolean().optional(),
|
|
67
|
+
relativeConfig: z.boolean().optional(),
|
|
68
|
+
outDir: z.string().min(1).optional(),
|
|
69
|
+
register: z.boolean().optional(),
|
|
70
|
+
id: z.string().regex(REGISTRY_ID).optional()
|
|
71
|
+
})
|
|
72
|
+
.strict();
|
|
73
|
+
const ApplyBody = AdoptBody.extend({ confirm: z.literal(true) }).strict();
|
|
74
|
+
const RevertBody = z
|
|
75
|
+
.object({
|
|
76
|
+
scope: ScopeSchema,
|
|
77
|
+
projectDir: z.string().min(1).optional(),
|
|
78
|
+
purge: z.boolean(),
|
|
79
|
+
confirm: z.literal(true)
|
|
80
|
+
})
|
|
81
|
+
.strict();
|
|
82
|
+
const CreateBody = z
|
|
83
|
+
.object({
|
|
84
|
+
// Also the folder name under ~/.hmcp/gateways, so nothing that could climb out of it.
|
|
85
|
+
name: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/, "a name is lower-case letters, digits, dashes and underscores"),
|
|
86
|
+
upstreams: z.array(z.unknown()).min(1).max(50),
|
|
87
|
+
posture: z.enum(["read-only", "approve-writes", "locked"]).default("approve-writes"),
|
|
88
|
+
mode: z.enum(["observe", "enforce"]).default("observe"),
|
|
89
|
+
onUnclassified: z.enum(["deny", "approve"]).default("approve"),
|
|
90
|
+
outDir: z.string().min(1).optional(),
|
|
91
|
+
id: z.string().regex(REGISTRY_ID).optional(),
|
|
92
|
+
label: z.string().min(1).max(200).optional(),
|
|
93
|
+
acknowledged: z.object({ loosens: z.literal(true) }).strict().optional()
|
|
94
|
+
})
|
|
95
|
+
.strict();
|
|
96
|
+
const AttachBody = z
|
|
97
|
+
.object({
|
|
98
|
+
gatewayId: z.string().regex(REGISTRY_ID),
|
|
99
|
+
scope: ScopeSchema,
|
|
100
|
+
projectDir: z.string().min(1).optional()
|
|
101
|
+
})
|
|
102
|
+
.strict();
|
|
103
|
+
export function pathDirsFromEnv(path = process.env["PATH"]) {
|
|
104
|
+
return [
|
|
105
|
+
...new Set((path ?? "")
|
|
106
|
+
.split(delimiter)
|
|
107
|
+
.filter((d) => d.length > 0 && isAbsolute(d) && !/[\\/](node_modules|_npx)([\\/]|$)/.test(d) && existsSync(d)))
|
|
108
|
+
];
|
|
109
|
+
}
|
|
110
|
+
function parse(schema, body) {
|
|
111
|
+
const result = schema.safeParse(body ?? {});
|
|
112
|
+
if (!result.success) {
|
|
113
|
+
throw badRequest("the request body is not valid", result.error.issues.map((i) => ({ path: i.path.join(".") || "(root)", message: i.message })));
|
|
114
|
+
}
|
|
115
|
+
return result.data;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* A directory named by the browser: absolute, written plainly, and real.
|
|
119
|
+
*
|
|
120
|
+
* "Plainly" because `/a/b/../c` resolves somewhere its text does not say,
|
|
121
|
+
* and a path a person reviews should be the path that is used.
|
|
122
|
+
*/
|
|
123
|
+
function plainDirectory(raw, field, mustExist) {
|
|
124
|
+
if (raw.includes("\0") || !isAbsolute(raw))
|
|
125
|
+
throw unprocessable(`${field} must be an absolute path`);
|
|
126
|
+
if (raw.split(/[\\/]+/).some((part) => part === ".." || part === ".")) {
|
|
127
|
+
throw unprocessable(`${field} must not contain "." or ".." segments`);
|
|
128
|
+
}
|
|
129
|
+
const path = resolve(raw);
|
|
130
|
+
if (!existsSync(path)) {
|
|
131
|
+
if (mustExist)
|
|
132
|
+
throw unprocessable(`${field} ${path} does not exist`);
|
|
133
|
+
return path;
|
|
134
|
+
}
|
|
135
|
+
if (!statSync(path).isDirectory())
|
|
136
|
+
throw unprocessable(`${field} ${path} is not a folder`);
|
|
137
|
+
return path;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The project folder, defaulting to the console's own working directory --
|
|
141
|
+
* which is what the CLI does with its own, and the folder the console was
|
|
142
|
+
* started from is the likeliest project.
|
|
143
|
+
*/
|
|
144
|
+
function projectDirOf(raw) {
|
|
145
|
+
return raw ? plainDirectory(raw, "projectDir", true) : process.cwd();
|
|
146
|
+
}
|
|
147
|
+
function libraryOptions(body, options) {
|
|
148
|
+
if (body.clientAllow && !CLAUDE_CODE_SCOPES.has(body.scope)) {
|
|
149
|
+
throw unprocessable(`the client allow rule is a Claude Code setting, and ${LABELS[body.scope]} does not read it`);
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
scope: body.scope,
|
|
153
|
+
cwd: projectDirOf(body.projectDir),
|
|
154
|
+
registry: options.registryPath,
|
|
155
|
+
...(body.rename ? { rename: body.rename } : {}),
|
|
156
|
+
...(body.gatewayName ? { name: body.gatewayName } : {}),
|
|
157
|
+
...(body.entryName ? { entryName: body.entryName } : {}),
|
|
158
|
+
...(body.posture ? { posture: body.posture } : {}),
|
|
159
|
+
...(body.mode ? { mode: body.mode } : {}),
|
|
160
|
+
...(body.onUnclassified ? { onUnclassified: body.onUnclassified } : {}),
|
|
161
|
+
...(body.packs === false ? { noPacks: true } : {}),
|
|
162
|
+
...(body.clientAllow !== undefined ? { clientAllow: body.clientAllow } : {}),
|
|
163
|
+
...(body.copyEnv !== undefined ? { copyEnv: body.copyEnv } : {}),
|
|
164
|
+
...(body.allowLocalHttp !== undefined ? { allowLocalHttp: body.allowLocalHttp } : {}),
|
|
165
|
+
...(body.strictEgress !== undefined ? { strictEgress: body.strictEgress } : {}),
|
|
166
|
+
...(body.relativeConfig !== undefined ? { relativeConfig: body.relativeConfig } : {}),
|
|
167
|
+
...(body.outDir ? { outDir: plainDirectory(body.outDir, "outDir", false) } : {}),
|
|
168
|
+
...(body.register !== undefined ? { register: body.register } : {}),
|
|
169
|
+
...(body.id ? { id: body.id } : {})
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/* ------------------------------------------------- the report, for a browser */
|
|
173
|
+
const KEPT = "[kept secret]";
|
|
174
|
+
/** A flag whose next argument (or `=value`) is a credential. */
|
|
175
|
+
const SECRET_FLAG = /^--?(api[-_]?key|token|access[-_]?token|password|passwd|secret|client[-_]?secret|auth|authorization|bearer|cookie|credential)s?$/i;
|
|
176
|
+
/** An argument that is a credential on its face: a known token prefix, a JWT, or a NAME=value whose name says so. */
|
|
177
|
+
const SECRET_VALUE = /^(sk|pk|rk)[-_]|^gh[pousr]_|^github_pat_|^xox[abpr]-|^glpat-|^AKIA[0-9A-Z]{12}|^eyJ[\w-]+\.[\w-]+\.|^Bearer\s|^[A-Z0-9_]*(TOKEN|SECRET|KEY|PASSWORD|AUTH)[A-Z0-9_]*=/i;
|
|
178
|
+
/**
|
|
179
|
+
* A URL with its userinfo removed and each query value replaced, keeping the
|
|
180
|
+
* parameter names a person needs to recognise it. The fragment goes too: it is
|
|
181
|
+
* where an OAuth redirect leaves a token.
|
|
182
|
+
*/
|
|
183
|
+
function sanitizeUrl(raw, found) {
|
|
184
|
+
let url;
|
|
185
|
+
try {
|
|
186
|
+
url = new URL(raw);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return raw;
|
|
190
|
+
}
|
|
191
|
+
if (url.username)
|
|
192
|
+
found.add(decodeURIComponent(url.username));
|
|
193
|
+
if (url.password)
|
|
194
|
+
found.add(decodeURIComponent(url.password));
|
|
195
|
+
const names = [];
|
|
196
|
+
for (const [name, value] of url.searchParams) {
|
|
197
|
+
names.push(name);
|
|
198
|
+
if (value)
|
|
199
|
+
found.add(value);
|
|
200
|
+
}
|
|
201
|
+
if (url.hash.length > 1)
|
|
202
|
+
found.add(url.hash.slice(1));
|
|
203
|
+
if (!url.username && !url.password && names.length === 0 && url.hash.length <= 1)
|
|
204
|
+
return raw;
|
|
205
|
+
const query = names.length > 0 ? `?${names.map((n) => `${encodeURIComponent(n)}=${KEPT}`).join("&")}` : "";
|
|
206
|
+
return `${url.protocol}//${url.host}${url.pathname}${query}`;
|
|
207
|
+
}
|
|
208
|
+
function sanitizeArgs(args, found) {
|
|
209
|
+
return args.map((arg, i) => {
|
|
210
|
+
const eq = /^(--?[^=\s]+)=(.*)$/s.exec(arg);
|
|
211
|
+
if (eq && SECRET_FLAG.test(eq[1])) {
|
|
212
|
+
found.add(eq[2]);
|
|
213
|
+
return `${eq[1]}=${KEPT}`;
|
|
214
|
+
}
|
|
215
|
+
const previous = i > 0 ? args[i - 1] : "";
|
|
216
|
+
if (SECRET_FLAG.test(previous) || previous === "-k" || SECRET_VALUE.test(arg)) {
|
|
217
|
+
found.add(arg);
|
|
218
|
+
return KEPT;
|
|
219
|
+
}
|
|
220
|
+
return /^[a-z][a-z0-9+.-]*:\/\//i.test(arg) ? sanitizeUrl(arg, found) : arg;
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* The adopt report as the console serves it.
|
|
225
|
+
*
|
|
226
|
+
* The CLI prints each server's full command line and address, which is right
|
|
227
|
+
* at a terminal the person owns. A browser is another matter: an API key on a
|
|
228
|
+
* command line, or a token in a query string, would travel in this response.
|
|
229
|
+
* So args and URLs are sanitized here, in the web layer, leaving the CLI's
|
|
230
|
+
* output exactly as it is; and every value taken out is also taken out of any
|
|
231
|
+
* other string in the report -- a probe failure, say, that quotes the address.
|
|
232
|
+
*/
|
|
233
|
+
function sanitizeReport(report) {
|
|
234
|
+
if (report === null || typeof report !== "object")
|
|
235
|
+
return report;
|
|
236
|
+
const r = report;
|
|
237
|
+
if (!Array.isArray(r.upstreams))
|
|
238
|
+
return report;
|
|
239
|
+
const found = new Set();
|
|
240
|
+
const upstreams = r.upstreams.map((u) => ({
|
|
241
|
+
...u,
|
|
242
|
+
...(Array.isArray(u.args) ? { args: sanitizeArgs(u.args, found) } : {}),
|
|
243
|
+
...(typeof u.url === "string" ? { url: sanitizeUrl(u.url, found) } : {})
|
|
244
|
+
}));
|
|
245
|
+
const secrets = [...found].filter((v) => v.length >= 4 && v !== KEPT).sort((a, b) => b.length - a.length);
|
|
246
|
+
const scrub = (value) => {
|
|
247
|
+
if (typeof value === "string")
|
|
248
|
+
return secrets.reduce((text, secret) => text.split(secret).join(KEPT), value);
|
|
249
|
+
if (Array.isArray(value))
|
|
250
|
+
return value.map(scrub);
|
|
251
|
+
if (value !== null && typeof value === "object") {
|
|
252
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, scrub(v)]));
|
|
253
|
+
}
|
|
254
|
+
return value;
|
|
255
|
+
};
|
|
256
|
+
return scrub({ ...report, upstreams });
|
|
257
|
+
}
|
|
258
|
+
/** The engine's refusals, as the console's error shape. */
|
|
259
|
+
function asHttp(err) {
|
|
260
|
+
if (err instanceof HttpError)
|
|
261
|
+
throw err;
|
|
262
|
+
if (err instanceof AdoptRefusedError) {
|
|
263
|
+
// The message is scrubbed with the report, since it quotes the report's blocking reasons.
|
|
264
|
+
const { message, ...report } = sanitizeReport({ ...err.report, message: err.message });
|
|
265
|
+
throw unprocessable(message, { blocking: report.blocking, report });
|
|
266
|
+
}
|
|
267
|
+
if (err instanceof AdoptCommandError || err instanceof ClientConfigError)
|
|
268
|
+
throw unprocessable(err.message);
|
|
269
|
+
throw err;
|
|
270
|
+
}
|
|
271
|
+
/** The gateway's own audit log, or null when its config does not load or keeps none. */
|
|
272
|
+
function gatewayAudit(configPath, actor) {
|
|
273
|
+
try {
|
|
274
|
+
const { policy } = loadGatewayConfig(configPath);
|
|
275
|
+
if (!policy.audit.enabled)
|
|
276
|
+
return null;
|
|
277
|
+
return new AuditLog({ config: policy.audit, actor, component: "hmcp-web", cwd: dirname(configPath) });
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/** Appends one record, and turns a failure into a warning: the change itself already happened. */
|
|
284
|
+
function record(log, entry) {
|
|
285
|
+
if (!log)
|
|
286
|
+
return "this gateway keeps no activity log, so the change was not recorded there";
|
|
287
|
+
try {
|
|
288
|
+
log.appendStrict(entry);
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
catch (err) {
|
|
292
|
+
return `the change was made but the activity log record failed: ${err.message}`;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
function uniqueId(base, taken) {
|
|
296
|
+
let candidate = base;
|
|
297
|
+
for (let n = 2; taken.has(candidate); n++)
|
|
298
|
+
candidate = `${base}-${n}`.slice(0, 64);
|
|
299
|
+
return candidate;
|
|
300
|
+
}
|
|
301
|
+
/** Drops the keys `UpstreamSchema` filled with nothing, so the file says only what was chosen. */
|
|
302
|
+
function prune(upstream) {
|
|
303
|
+
const out = {};
|
|
304
|
+
for (const [key, value] of Object.entries(upstream)) {
|
|
305
|
+
if (Array.isArray(value) && value.length === 0)
|
|
306
|
+
continue;
|
|
307
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0)
|
|
308
|
+
continue;
|
|
309
|
+
if (key === "credential_passthrough" && value.enabled === false)
|
|
310
|
+
continue;
|
|
311
|
+
out[key] = value;
|
|
312
|
+
}
|
|
313
|
+
return out;
|
|
314
|
+
}
|
|
315
|
+
/** Whether a value in env or headers is written as itself rather than as a locked-key reference. */
|
|
316
|
+
function hasLiteral(upstream) {
|
|
317
|
+
const values = Object.values(upstream.transport === "stdio" ? upstream.env : upstream.headers);
|
|
318
|
+
return values.some((v) => typeof v === "string");
|
|
319
|
+
}
|
|
320
|
+
/** A path with every existing folder on it resolved, so one file is always spelled one way. */
|
|
321
|
+
function realPath(path) {
|
|
322
|
+
try {
|
|
323
|
+
return realpathSync(path);
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
try {
|
|
327
|
+
return join(realpathSync(dirname(path)), path.slice(dirname(path).length + 1));
|
|
328
|
+
}
|
|
329
|
+
catch {
|
|
330
|
+
return path;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Drops a project scope that is the very file of an all-projects scope: with
|
|
336
|
+
* the project folder at the home folder, "Cursor — this project" and "Cursor —
|
|
337
|
+
* all projects" are both `~/.cursor/mcp.json`, and offering both would act
|
|
338
|
+
* twice on one file. Claude Code's "local" lives inside `~/.claude.json` by
|
|
339
|
+
* design and is not a duplicate.
|
|
340
|
+
*/
|
|
341
|
+
function withoutSameFile(clients) {
|
|
342
|
+
const shared = new Set(clients.filter((c) => !PROJECT_SCOPES.has(c.scope)).map((c) => realPath(c.path)));
|
|
343
|
+
return clients.filter((c) => c.scope === "local" || !PROJECT_SCOPES.has(c.scope) || !shared.has(realPath(c.path)));
|
|
344
|
+
}
|
|
345
|
+
export function connectRoutes(options, deps = {}) {
|
|
346
|
+
return [
|
|
347
|
+
route("GET", "/api/v1/connect/clients", (ctx) => {
|
|
348
|
+
const projectDir = projectDirOf(ctx.query.get("projectDir"));
|
|
349
|
+
return {
|
|
350
|
+
projectDir,
|
|
351
|
+
clients: withoutSameFile(detectClients({ cwd: projectDir })).map((c) => ({
|
|
352
|
+
...c,
|
|
353
|
+
label: LABELS[c.scope],
|
|
354
|
+
projectScoped: PROJECT_SCOPES.has(c.scope),
|
|
355
|
+
/*
|
|
356
|
+
* An app with no servers yet can still be connected to a toolbox
|
|
357
|
+
* made here: that is the whole of `attach`. Only a config file that
|
|
358
|
+
* cannot be read stops it, and then `error` says why.
|
|
359
|
+
*/
|
|
360
|
+
canAttach: c.error === null
|
|
361
|
+
}))
|
|
362
|
+
};
|
|
363
|
+
}),
|
|
364
|
+
/** A dry run. Starts each server once to ask what it offers, and writes nothing to any config. */
|
|
365
|
+
route("POST", "/api/v1/connect/plan", async (ctx) => {
|
|
366
|
+
const body = parse(AdoptBody, ctx.body);
|
|
367
|
+
try {
|
|
368
|
+
return sanitizeReport(await adoptPlan(libraryOptions(body, options)));
|
|
369
|
+
}
|
|
370
|
+
catch (err) {
|
|
371
|
+
asHttp(err);
|
|
372
|
+
}
|
|
373
|
+
}),
|
|
374
|
+
route("POST", "/api/v1/connect/apply", async (ctx) => {
|
|
375
|
+
const body = parse(ApplyBody, ctx.body);
|
|
376
|
+
const { confirm: _confirm, ...adopt } = body;
|
|
377
|
+
const lib = libraryOptions(adopt, options);
|
|
378
|
+
// Checked first so a taken id costs nothing; the engine would refuse it
|
|
379
|
+
// only after writing the gateway's files.
|
|
380
|
+
if (adopt.id && adopt.register !== false && readRegistry(options.registryPath).servers.some((s) => s.id === adopt.id)) {
|
|
381
|
+
throw conflict(`a server with id "${adopt.id}" is already registered`);
|
|
382
|
+
}
|
|
383
|
+
let result;
|
|
384
|
+
try {
|
|
385
|
+
result = await adoptApply(lib);
|
|
386
|
+
}
|
|
387
|
+
catch (err) {
|
|
388
|
+
asHttp(err);
|
|
389
|
+
}
|
|
390
|
+
const applied = result.applied;
|
|
391
|
+
const configPath = applied.configPath;
|
|
392
|
+
const warning = configPath
|
|
393
|
+
? record(gatewayAudit(configPath, ctx.actor), {
|
|
394
|
+
tool: "(connect)",
|
|
395
|
+
effect: null,
|
|
396
|
+
decision: "allow",
|
|
397
|
+
rule_id: "connect.apply",
|
|
398
|
+
reason: `${result.client} (${result.scope}) connected through this gateway via the console by ${ctx.actor}: ` +
|
|
399
|
+
`${applied.replaced.length} server(s) replaced in ${applied.clientConfigPath}` +
|
|
400
|
+
(applied.clientAllowAdded ? `; client allow rule ${applied.clientAllowAdded.rule} added` : ""),
|
|
401
|
+
outcome: "completed",
|
|
402
|
+
args_redacted: {
|
|
403
|
+
scope: result.scope,
|
|
404
|
+
client_config: applied.clientConfigPath,
|
|
405
|
+
replaced: [...applied.replaced],
|
|
406
|
+
registry_id: applied.registryId,
|
|
407
|
+
mode: result.starting?.mode ?? null,
|
|
408
|
+
client_allow: applied.clientAllowAdded?.rule ?? null
|
|
409
|
+
}
|
|
410
|
+
})
|
|
411
|
+
: null;
|
|
412
|
+
return { ...sanitizeReport(result), registryId: applied.registryId, warning };
|
|
413
|
+
}),
|
|
414
|
+
route("POST", "/api/v1/connect/revert", async (ctx) => {
|
|
415
|
+
const body = parse(RevertBody, ctx.body);
|
|
416
|
+
const cwd = projectDirOf(body.projectDir);
|
|
417
|
+
const found = detectClients({ cwd }).find((c) => c.scope === body.scope);
|
|
418
|
+
if (!found.canRevert) {
|
|
419
|
+
throw unprocessable(found.error ?? `There is nothing to undo for ${LABELS[body.scope]}: it was not connected from here.`);
|
|
420
|
+
}
|
|
421
|
+
// Opened before reverting, because purging deletes the config that names the log.
|
|
422
|
+
const backup = readBackup(resolveScope(body.scope, { cwd }));
|
|
423
|
+
// A connection made with attach generated nothing; its gateway is found by its console row.
|
|
424
|
+
const generatedConfig = backup?.generated.find((p) => p.endsWith("gateway.yaml")) ??
|
|
425
|
+
(backup?.registry_id
|
|
426
|
+
? readRegistry(options.registryPath).servers.find((s) => s.id === backup.registry_id)?.config_path
|
|
427
|
+
: undefined);
|
|
428
|
+
const log = generatedConfig ? gatewayAudit(generatedConfig, ctx.actor) : null;
|
|
429
|
+
let result;
|
|
430
|
+
try {
|
|
431
|
+
result = await adoptRevert({ scope: body.scope, cwd, purge: body.purge, registry: options.registryPath });
|
|
432
|
+
}
|
|
433
|
+
catch (err) {
|
|
434
|
+
asHttp(err);
|
|
435
|
+
}
|
|
436
|
+
const warning = record(log, {
|
|
437
|
+
tool: "(connect)",
|
|
438
|
+
effect: null,
|
|
439
|
+
decision: "allow",
|
|
440
|
+
rule_id: "connect.revert",
|
|
441
|
+
reason: `${result.client} (${result.scope}) disconnected from this gateway via the console by ${ctx.actor}: ` +
|
|
442
|
+
`${result.restored.length} server(s) restored to ${result.clientConfigPath}` +
|
|
443
|
+
(body.purge ? `; ${result.deleted.length} generated file(s) deleted` : ""),
|
|
444
|
+
outcome: "completed",
|
|
445
|
+
args_redacted: {
|
|
446
|
+
scope: result.scope,
|
|
447
|
+
client_config: result.clientConfigPath,
|
|
448
|
+
restored: [...result.restored],
|
|
449
|
+
deleted: [...result.deleted],
|
|
450
|
+
registry_removed: result.registryRemoved
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
return { ...result, warning };
|
|
454
|
+
}),
|
|
455
|
+
/**
|
|
456
|
+
* Put a toolbox made here into an AI app: one entry added beside the
|
|
457
|
+
* app's own servers. Undo (`/connect/revert`) takes the entry away again
|
|
458
|
+
* and leaves the toolbox alone.
|
|
459
|
+
*/
|
|
460
|
+
route("POST", "/api/v1/connect/attach", async (ctx) => {
|
|
461
|
+
const body = parse(AttachBody, ctx.body);
|
|
462
|
+
const entry = readRegistry(options.registryPath).servers.find((s) => s.id === body.gatewayId);
|
|
463
|
+
if (!entry)
|
|
464
|
+
throw unprocessable(`there is no toolbox called "${body.gatewayId}"`);
|
|
465
|
+
if (entry.kind !== "gateway")
|
|
466
|
+
throw unprocessable(`"${body.gatewayId}" is not a toolbox, so an app cannot be connected to it`);
|
|
467
|
+
const configPath = resolve(entry.config_path);
|
|
468
|
+
const cwd = projectDirOf(body.projectDir);
|
|
469
|
+
let pathDirs = [];
|
|
470
|
+
try {
|
|
471
|
+
pathDirs = (await deps.pathDirs?.()) ?? [];
|
|
472
|
+
}
|
|
473
|
+
catch {
|
|
474
|
+
// The machine check failing is no reason to refuse; the defaults below still apply.
|
|
475
|
+
}
|
|
476
|
+
if (pathDirs.length === 0)
|
|
477
|
+
pathDirs = pathDirsFromEnv();
|
|
478
|
+
let result;
|
|
479
|
+
try {
|
|
480
|
+
result = await connectClient({
|
|
481
|
+
scope: body.scope,
|
|
482
|
+
cwd,
|
|
483
|
+
home: homedir(),
|
|
484
|
+
gatewayConfigPath: configPath,
|
|
485
|
+
pathDirs,
|
|
486
|
+
registryId: entry.id
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
catch (err) {
|
|
490
|
+
asHttp(err);
|
|
491
|
+
}
|
|
492
|
+
const warning = result.alreadyConnected
|
|
493
|
+
? null
|
|
494
|
+
: record(gatewayAudit(configPath, ctx.actor), {
|
|
495
|
+
tool: "(connect)",
|
|
496
|
+
effect: null,
|
|
497
|
+
decision: "allow",
|
|
498
|
+
rule_id: "connect.attach",
|
|
499
|
+
reason: `${LABELS[body.scope]} connected to this gateway via the console by ${ctx.actor}, as "${result.entryName}" in ${result.configPath}`,
|
|
500
|
+
outcome: "completed",
|
|
501
|
+
args_redacted: { scope: body.scope, client_config: result.configPath, entry: result.entryName, registry_id: entry.id }
|
|
502
|
+
});
|
|
503
|
+
return {
|
|
504
|
+
configPath: result.configPath,
|
|
505
|
+
entryName: result.entryName,
|
|
506
|
+
backupPath: result.backupPath,
|
|
507
|
+
alreadyConnected: result.alreadyConnected,
|
|
508
|
+
restartHint: result.restartHint,
|
|
509
|
+
...(warning ? { warning } : {})
|
|
510
|
+
};
|
|
511
|
+
}),
|
|
512
|
+
/** A gateway from nothing: a name and the servers it fronts. */
|
|
513
|
+
route("POST", "/api/v1/gateways", (ctx) => {
|
|
514
|
+
const body = parse(CreateBody, ctx.body);
|
|
515
|
+
const upstreams = [];
|
|
516
|
+
const problems = [];
|
|
517
|
+
body.upstreams.forEach((raw, index) => {
|
|
518
|
+
const result = UpstreamSchema.safeParse(raw);
|
|
519
|
+
if (result.success)
|
|
520
|
+
upstreams.push(result.data);
|
|
521
|
+
else
|
|
522
|
+
for (const i of result.error.issues)
|
|
523
|
+
problems.push({ path: `upstreams.${index}.${i.path.join(".")}`, message: i.message });
|
|
524
|
+
});
|
|
525
|
+
if (problems.length > 0)
|
|
526
|
+
throw unprocessable("a connected server is not valid", problems);
|
|
527
|
+
const names = upstreams.map((u) => u.name);
|
|
528
|
+
const twice = names.find((n, i) => names.indexOf(n) !== i);
|
|
529
|
+
if (twice)
|
|
530
|
+
throw unprocessable(`two connected servers are both called "${twice}"`);
|
|
531
|
+
const dir = body.outDir ? plainDirectory(body.outDir, "outDir", false) : join(homedir(), ".hmcp", "gateways", body.name);
|
|
532
|
+
const configPath = join(dir, "gateway.yaml");
|
|
533
|
+
const policyPath = join(dir, "policy.yaml");
|
|
534
|
+
for (const path of [configPath, policyPath]) {
|
|
535
|
+
if (existsSync(path))
|
|
536
|
+
throw conflict(`${path} already exists; choose another name or folder`);
|
|
537
|
+
}
|
|
538
|
+
const reg = readRegistry(options.registryPath);
|
|
539
|
+
const taken = new Set(reg.servers.map((s) => s.id));
|
|
540
|
+
if (body.id && taken.has(body.id))
|
|
541
|
+
throw conflict(`a server with id "${body.id}" is already registered`);
|
|
542
|
+
const id = body.id ?? uniqueId(body.name, taken);
|
|
543
|
+
// A `{ secret }` reference is a name, not a value, so only literals earn the warning.
|
|
544
|
+
const literals = upstreams.some(hasLiteral);
|
|
545
|
+
const hosts = upstreams.flatMap((u) => (u.transport === "http" ? [new URL(u.url).hostname] : []));
|
|
546
|
+
/*
|
|
547
|
+
* A server on this computer or the local network is reachable only with
|
|
548
|
+
* the private-address protections off, for every HTTP server of this
|
|
549
|
+
* gateway. That is a loosening, so it is confirmed like any other.
|
|
550
|
+
*/
|
|
551
|
+
const local = hosts.filter((h) => isLocalTarget(h));
|
|
552
|
+
if (local.length > 0 && !body.acknowledged?.loosens) {
|
|
553
|
+
throw unprocessable(`a server is on this computer or the local network (${[...new Set(local)].join(", ")}), which needs the ` +
|
|
554
|
+
`protection against reaching private addresses switched off for this toolbox`, {
|
|
555
|
+
needs: "loosens",
|
|
556
|
+
loosens: [
|
|
557
|
+
`allow connections to this computer and the local network (${[...new Set(local)].join(", ")})`,
|
|
558
|
+
"allow plain http:// and bare IP addresses"
|
|
559
|
+
]
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
const plan = {
|
|
563
|
+
upstreams: upstreams.map((upstream) => ({ upstream, originalName: upstream.name, warnings: [] })),
|
|
564
|
+
skipped: [],
|
|
565
|
+
gatewayEnv: {},
|
|
566
|
+
egressAllow: [...new Set(hosts)].sort(),
|
|
567
|
+
egressNeedsLocalHttp: local.length > 0,
|
|
568
|
+
secretsOnDisk: literals,
|
|
569
|
+
nameMap: new Map(),
|
|
570
|
+
malformed: []
|
|
571
|
+
};
|
|
572
|
+
const gatewayYaml = [
|
|
573
|
+
"# Created in the hardened-mcp console. policy.yaml beside this file decides",
|
|
574
|
+
"# what each tool may do.",
|
|
575
|
+
...(literals
|
|
576
|
+
? ["#", "# A value set in env or headers below is stored here as written. If it is a", "# credential, do not share or commit this file."]
|
|
577
|
+
: []),
|
|
578
|
+
"",
|
|
579
|
+
stringify({ version: 1, name: body.name, policy: "./policy.yaml", upstreams: upstreams.map(prune), on_injection: "strip", namespace: true }, { lineWidth: 0 })
|
|
580
|
+
].join("\n");
|
|
581
|
+
const policyYaml = emitPolicyYaml(plan, {
|
|
582
|
+
name: body.name,
|
|
583
|
+
posture: body.posture,
|
|
584
|
+
enforcement: body.mode,
|
|
585
|
+
onUnclassified: body.onUnclassified
|
|
586
|
+
})
|
|
587
|
+
.replace("# Generated by `hmcp-gateway adopt`.", "# Created in the hardened-mcp console.")
|
|
588
|
+
.replace(`\nname: ${body.name}-adopted\n`, `\nname: ${body.name}\n`);
|
|
589
|
+
const createdDir = !existsSync(dir);
|
|
590
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
591
|
+
try {
|
|
592
|
+
// `wx`: a file that appeared since the check above is still not overwritten.
|
|
593
|
+
writeFileSync(configPath, gatewayYaml, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
594
|
+
writeFileSync(policyPath, policyYaml, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
595
|
+
loadGatewayConfig(configPath);
|
|
596
|
+
}
|
|
597
|
+
catch (err) {
|
|
598
|
+
for (const path of [configPath, policyPath])
|
|
599
|
+
if (existsSync(path))
|
|
600
|
+
unlinkSync(path);
|
|
601
|
+
if (createdDir)
|
|
602
|
+
rmSync(dir, { recursive: true, force: true });
|
|
603
|
+
if (err.code === "EEXIST")
|
|
604
|
+
throw conflict(`${err.message}; nothing was written`);
|
|
605
|
+
throw unprocessable(`the gateway could not be written: ${err.message}`);
|
|
606
|
+
}
|
|
607
|
+
const entry = {
|
|
608
|
+
id,
|
|
609
|
+
kind: "gateway",
|
|
610
|
+
label: body.label ?? body.name,
|
|
611
|
+
config_path: configPath,
|
|
612
|
+
added_at: new Date().toISOString()
|
|
613
|
+
};
|
|
614
|
+
writeRegistry({ ...reg, servers: [...reg.servers, entry] }, options.registryPath);
|
|
615
|
+
const warning = record(gatewayAudit(configPath, ctx.actor), {
|
|
616
|
+
tool: "(connect)",
|
|
617
|
+
effect: null,
|
|
618
|
+
decision: "allow",
|
|
619
|
+
rule_id: "connect.create",
|
|
620
|
+
reason: `gateway "${body.name}" created via the console by ${ctx.actor}, fronting ${names.join(", ")}`,
|
|
621
|
+
outcome: "completed",
|
|
622
|
+
args_redacted: { name: body.name, upstreams: names, mode: body.mode, posture: body.posture, registry_id: id }
|
|
623
|
+
});
|
|
624
|
+
return {
|
|
625
|
+
id,
|
|
626
|
+
configPath,
|
|
627
|
+
policyPath,
|
|
628
|
+
warnings: literals ? ["A value set in env or headers is stored in gateway.yaml as written."] : [],
|
|
629
|
+
warning
|
|
630
|
+
};
|
|
631
|
+
})
|
|
632
|
+
];
|
|
633
|
+
}
|