hmcp-web 0.0.1 → 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 +49 -2
- package/THIRD-PARTY-NOTICES.md +110 -0
- package/bin/hmcp-web.js +20 -0
- package/dist/api.d.ts +22 -0
- package/dist/api.js +1458 -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/app-servers.d.ts +85 -0
- package/dist/model/app-servers.js +109 -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/import-record.d.ts +80 -0
- package/dist/model/import-record.js +179 -0
- package/dist/model/metrics.d.ts +65 -0
- package/dist/model/metrics.js +213 -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-import.d.ts +9 -0
- package/dist/routes/connect-import.js +594 -0
- package/dist/routes/connect.d.ts +50 -0
- package/dist/routes/connect.js +691 -0
- package/dist/routes/github.d.ts +97 -0
- package/dist/routes/github.js +587 -0
- package/dist/routes/guard.d.ts +3 -0
- package/dist/routes/guard.js +166 -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 +12 -0
- package/dist/routes/runtime.js +921 -0
- package/dist/routes/servers-add.d.ts +32 -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-CZ78RyRO.js +1 -0
- package/dist-ui/assets/Approvals-DPIlNZsv.js +1 -0
- package/dist-ui/assets/AttachApp-DjSeWCbS.js +5 -0
- package/dist-ui/assets/Connections-qcA96lXh.js +2 -0
- package/dist-ui/assets/Gallery-DB_OO7Vw.js +17 -0
- package/dist-ui/assets/PreApprovals-C4cKajcK.js +1 -0
- package/dist-ui/assets/Protection-B8h-5YAb.js +1 -0
- package/dist-ui/assets/Safety-BQqHyYdo.js +1 -0
- package/dist-ui/assets/Settings-Cx50zZSt.js +1 -0
- package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
- package/dist-ui/assets/Suggestions-CRo5UOTT.js +1 -0
- package/dist-ui/assets/Tools-xo39lPKB.js +4 -0
- package/dist-ui/assets/index-DttDjRpu.js +16 -0
- package/dist-ui/assets/index-QeJyD5z2.css +2 -0
- package/dist-ui/assets/kit-DRVm92_t.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,1091 @@
|
|
|
1
|
+
/** Test it, install, locked keys, live status, retry, move-to-locked. Workstream E. */
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { parseDocument, stringify } from "yaml";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { AuditLog, SECRET_NAME, SecretStore, expandPath, isSecretRef, parsePolicy, policyDigest, readRegistry, runtimeStateIsLive, writeAtomically, writeRegistry } from "hmcp-core";
|
|
8
|
+
import { UpstreamSchema, catalogCheck, catalogEntry, detectClients, emitPolicyYaml, loadGatewayConfig, materializeDraft } from "hmcp-gateway";
|
|
9
|
+
import { HttpError, conflict, notFound, respond, route, unprocessable } from "../http.js";
|
|
10
|
+
import { loadServer, storeFor } from "../model/server.js";
|
|
11
|
+
import { commandPathsFrom, doctor } from "../model/doctor.js";
|
|
12
|
+
import { applyPolicyChanges, applyStateFor, commitGatewayText, digestText, egressChangesFor, gatewayLoosens, liveRows, parseGatewayText, readGatewayFile, readGatewayFileOrBroken, isBroken, redactUpstream, refuseIfOverridesOff, requestRetry, KEPT_SECRET, sameExcept, unchangedBatch } from "../model/gateway-config.js";
|
|
13
|
+
import { forgetProbe, offersSignIn, packRulesFor, recallProbe, rememberProbe, runProbe, scratchPolicy, sweepTestLeftovers, scratchSecretStore, scrubSecrets, withProbeSlot } from "../model/probe.js";
|
|
14
|
+
import { processes } from "../model/process.js";
|
|
15
|
+
import { consoleOAuthFetch } from "./oauth.js";
|
|
16
|
+
/**
|
|
17
|
+
* Adding a server the way a person who knows nothing technical does it:
|
|
18
|
+
* fill in a form, press "Test it", see the tools, press "Save and turn on".
|
|
19
|
+
*
|
|
20
|
+
* The rules the rest of the console keeps hold here too, with two additions
|
|
21
|
+
* that come from keys now being typed into a page:
|
|
22
|
+
*
|
|
23
|
+
* - A key's value goes from the request into the locked-keys file and nowhere
|
|
24
|
+
* else. Before install it lives only in this process's memory and a scratch
|
|
25
|
+
* file deleted after the test; no response, audit record or error carries it.
|
|
26
|
+
* - Saving touches two files (policy.yaml for the address and rules, then
|
|
27
|
+
* gateway.yaml for the server). Policy is written first, so the server never
|
|
28
|
+
* runs without its rules; if gateway.yaml is refused, the policy and any new
|
|
29
|
+
* keys are put back.
|
|
30
|
+
*/
|
|
31
|
+
/** The toolbox made for someone who has none yet. */
|
|
32
|
+
export const DEFAULT_GATEWAY_ID = "main";
|
|
33
|
+
const DEFAULT_GATEWAY_LABEL = "My toolbox";
|
|
34
|
+
/* ------------------------------------------------------------------ helpers */
|
|
35
|
+
function entryById(options, id) {
|
|
36
|
+
return readRegistry(options.registryPath).servers.find((s) => s.id === id);
|
|
37
|
+
}
|
|
38
|
+
function serverFor(entry) {
|
|
39
|
+
try {
|
|
40
|
+
return loadServer(entry);
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
if (err instanceof HttpError)
|
|
44
|
+
throw err;
|
|
45
|
+
throw unprocessable(`toolbox "${entry.id}" could not be loaded: ${err.message}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function requireServer(options, id) {
|
|
49
|
+
const entry = entryById(options, id);
|
|
50
|
+
if (!entry)
|
|
51
|
+
throw notFound(`there is no toolbox called "${id}"`);
|
|
52
|
+
return serverFor(entry);
|
|
53
|
+
}
|
|
54
|
+
function parseBody(schema, body) {
|
|
55
|
+
const parsed = schema.safeParse(body === undefined ? {} : body);
|
|
56
|
+
if (!parsed.success) {
|
|
57
|
+
throw unprocessable(parsed.error.issues.map((i) => `${i.path.map(String).join(".") || "(body)"}: ${i.message}`).join("; "));
|
|
58
|
+
}
|
|
59
|
+
return parsed.data;
|
|
60
|
+
}
|
|
61
|
+
function secretStore() {
|
|
62
|
+
return new SecretStore();
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The new upstream with every env or header value the page could only send
|
|
66
|
+
* back as the kept-secret marker put back from the server it replaces. A
|
|
67
|
+
* marker with nothing to put back is dropped rather than written as text.
|
|
68
|
+
*/
|
|
69
|
+
function keepSavedValues(next, before) {
|
|
70
|
+
const restore = (now, was) => {
|
|
71
|
+
const out = {};
|
|
72
|
+
for (const [k, v] of Object.entries(now)) {
|
|
73
|
+
if (v !== KEPT_SECRET)
|
|
74
|
+
out[k] = v;
|
|
75
|
+
else if (was?.[k] !== undefined)
|
|
76
|
+
out[k] = was[k];
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
};
|
|
80
|
+
if (next.transport === "stdio")
|
|
81
|
+
return { ...next, env: restore(next.env, before.transport === "stdio" ? before.env : undefined) };
|
|
82
|
+
return { ...next, headers: restore(next.headers, before.transport === "http" ? before.headers : undefined) };
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Setting a server up again with a new value for a key it already had (the
|
|
86
|
+
* "Replace the key" fix): the new value goes into that same locked key, under
|
|
87
|
+
* the same name, so gateway.yaml keeps naming it and the turned-down value is
|
|
88
|
+
* not left behind under the old name (UT5 round 4). Only a typed key that
|
|
89
|
+
* another server doesn't also use: changing a shared key would change it for
|
|
90
|
+
* that server too, so a shared one keeps its value and the new one is saved
|
|
91
|
+
* beside it as before (the old one is still in use, so nothing is orphaned).
|
|
92
|
+
*/
|
|
93
|
+
function replaceKeysInPlace(m, before, gatewayId, usage, store) {
|
|
94
|
+
const next = m.upstream;
|
|
95
|
+
const now = next.transport === "stdio" ? next.env : next.headers;
|
|
96
|
+
const was = next.transport === before.transport ? (before.transport === "stdio" ? before.env : before.headers) : undefined;
|
|
97
|
+
const rename = new Map();
|
|
98
|
+
for (const [k, v] of Object.entries(now)) {
|
|
99
|
+
if (!isSecretRef(v) || !m.secretsToCreate.some((s) => s.name === v.secret))
|
|
100
|
+
continue;
|
|
101
|
+
const old = was?.[k];
|
|
102
|
+
if (!old || !isSecretRef(old) || rename.has(v.secret) || [...rename.values()].includes(old.secret))
|
|
103
|
+
continue;
|
|
104
|
+
const others = (usage.get(old.secret) ?? []).filter((u) => !(u.gatewayId === gatewayId && u.upstream === before.name));
|
|
105
|
+
if (others.length > 0)
|
|
106
|
+
continue;
|
|
107
|
+
let entry;
|
|
108
|
+
try {
|
|
109
|
+
entry = store.get(old.secret);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
entry = undefined;
|
|
113
|
+
}
|
|
114
|
+
if (!entry || entry.kind !== "value")
|
|
115
|
+
continue;
|
|
116
|
+
rename.set(v.secret, old.secret);
|
|
117
|
+
}
|
|
118
|
+
if (rename.size === 0)
|
|
119
|
+
return { materialized: m, replaces: [] };
|
|
120
|
+
const swap = (rec) => Object.fromEntries(Object.entries(rec).map(([k, v]) => [k, isSecretRef(v) && rename.has(v.secret) ? { ...v, secret: rename.get(v.secret) } : v]));
|
|
121
|
+
const upstream = next.transport === "stdio" ? { ...next, env: swap(next.env) } : { ...next, headers: swap(next.headers) };
|
|
122
|
+
return {
|
|
123
|
+
materialized: {
|
|
124
|
+
...m,
|
|
125
|
+
upstream,
|
|
126
|
+
secretsToCreate: m.secretsToCreate.map((s) => (rename.has(s.name) ? { ...s, name: rename.get(s.name) } : s))
|
|
127
|
+
},
|
|
128
|
+
replaces: [...rename.values()]
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/** The real store's names, with a broken or exposed file said in plain words. */
|
|
132
|
+
function secretNames(store) {
|
|
133
|
+
return secretSummaries(store).map((s) => s.name);
|
|
134
|
+
}
|
|
135
|
+
function secretSummaries(store) {
|
|
136
|
+
try {
|
|
137
|
+
return store.list();
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
throw unprocessable(err.message);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function auditTo(server, actor, entry, what) {
|
|
144
|
+
try {
|
|
145
|
+
new AuditLog({ config: server.policy.audit, actor, component: "hmcp-web", cwd: server.cwd }).appendStrict(entry);
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
return `${what}, but the audit record failed: ${err.message}`;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function auditEntry(rule, reason, args) {
|
|
153
|
+
return {
|
|
154
|
+
tool: "(gateway)",
|
|
155
|
+
effect: null,
|
|
156
|
+
decision: "allow",
|
|
157
|
+
rule_id: rule,
|
|
158
|
+
reason,
|
|
159
|
+
outcome: "completed",
|
|
160
|
+
args_redacted: { ...args, origin: "console" }
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
/** Drops the keys `UpstreamSchema` filled with nothing, so the file says only what was chosen. */
|
|
164
|
+
export function upstreamYaml(upstream) {
|
|
165
|
+
const out = {};
|
|
166
|
+
for (const [key, value] of Object.entries(upstream)) {
|
|
167
|
+
if (value === undefined)
|
|
168
|
+
continue;
|
|
169
|
+
if (Array.isArray(value) && value.length === 0)
|
|
170
|
+
continue;
|
|
171
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0)
|
|
172
|
+
continue;
|
|
173
|
+
if (key === "credential_passthrough" && value.enabled === false)
|
|
174
|
+
continue;
|
|
175
|
+
out[key] = value;
|
|
176
|
+
}
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
/** The policy a new toolbox starts with: watch-only, asking before writes. Same as POST /gateways. */
|
|
180
|
+
function newGatewayPolicyText(name) {
|
|
181
|
+
const plan = {
|
|
182
|
+
upstreams: [],
|
|
183
|
+
skipped: [],
|
|
184
|
+
gatewayEnv: {},
|
|
185
|
+
egressAllow: [],
|
|
186
|
+
egressNeedsLocalHttp: false,
|
|
187
|
+
secretsOnDisk: false,
|
|
188
|
+
nameMap: new Map(),
|
|
189
|
+
malformed: []
|
|
190
|
+
};
|
|
191
|
+
const text = emitPolicyYaml(plan, { name, posture: "approve-writes", enforcement: "observe", onUnclassified: "approve" })
|
|
192
|
+
.replace("# Generated by `hmcp-gateway adopt`.", "# Created in the hardened-mcp console.")
|
|
193
|
+
.replace(`\nname: ${name}-adopted\n`, `\nname: ${name}\n`);
|
|
194
|
+
/*
|
|
195
|
+
* A call that asks first is held open for up to 25 seconds while the person
|
|
196
|
+
* answers in the console, so the AI app gets the answer instead of an error
|
|
197
|
+
* telling it to retry.
|
|
198
|
+
*/
|
|
199
|
+
const doc = parseDocument(text);
|
|
200
|
+
doc.setIn(["approvals", "wait_seconds"], 25);
|
|
201
|
+
return doc.toString();
|
|
202
|
+
}
|
|
203
|
+
function newGatewayPolicy(name) {
|
|
204
|
+
return parsePolicy(parseDocument(newGatewayPolicyText(name)).toJS(), "policy.yaml");
|
|
205
|
+
}
|
|
206
|
+
/** Every `{ secret }` name an upstream refers to, including its sign-in. */
|
|
207
|
+
function secretRefsOf(upstream) {
|
|
208
|
+
const values = upstream.transport === "http" ? Object.values(upstream.headers) : Object.values(upstream.env);
|
|
209
|
+
const out = values.filter(isSecretRef).map((r) => r.secret);
|
|
210
|
+
if (upstream.transport === "http" && upstream.oauth)
|
|
211
|
+
out.push(upstream.oauth.secret);
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
/** Which registered toolboxes use which locked keys. Broken files are skipped. */
|
|
215
|
+
export function secretUsage(options) {
|
|
216
|
+
const usage = new Map();
|
|
217
|
+
for (const entry of readRegistry(options.registryPath).servers) {
|
|
218
|
+
let config;
|
|
219
|
+
try {
|
|
220
|
+
const file = readGatewayFileOrBroken(expandPath(entry.config_path));
|
|
221
|
+
if (isBroken(file))
|
|
222
|
+
continue;
|
|
223
|
+
config = file.config;
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
for (const upstream of config.upstreams) {
|
|
229
|
+
for (const name of secretRefsOf(upstream)) {
|
|
230
|
+
const list = usage.get(name) ?? [];
|
|
231
|
+
list.push({ gatewayId: entry.id, upstream: upstream.name });
|
|
232
|
+
usage.set(name, list);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return usage;
|
|
237
|
+
}
|
|
238
|
+
function now() {
|
|
239
|
+
return new Date().toISOString();
|
|
240
|
+
}
|
|
241
|
+
/** A key name from words: "GitHub key" -> "github_key", made unique. */
|
|
242
|
+
function secretNameFrom(words, taken) {
|
|
243
|
+
const base = words
|
|
244
|
+
.toLowerCase()
|
|
245
|
+
.replace(/[^a-z0-9]+/g, "_")
|
|
246
|
+
.replace(/^_+|_+$/g, "")
|
|
247
|
+
.slice(0, 56) || "key";
|
|
248
|
+
const start = /^[a-z0-9]/.test(base) ? base : `k${base}`;
|
|
249
|
+
let candidate = start;
|
|
250
|
+
for (let n = 2; taken.has(candidate); n++)
|
|
251
|
+
candidate = `${start}_${n}`;
|
|
252
|
+
return candidate;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* The hosts a signed-in (OAuth) server needs beyond its own URL: where tokens
|
|
256
|
+
* are refreshed. Not known until sign-in has happened, so read from the
|
|
257
|
+
* stored sign-in, never from the request.
|
|
258
|
+
*/
|
|
259
|
+
function oauthHosts(upstream, store) {
|
|
260
|
+
if (upstream.transport !== "http" || !upstream.oauth)
|
|
261
|
+
return [];
|
|
262
|
+
let entry;
|
|
263
|
+
try {
|
|
264
|
+
entry = store.get(upstream.oauth.secret);
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return [];
|
|
268
|
+
}
|
|
269
|
+
if (!entry || entry.kind !== "oauth")
|
|
270
|
+
return [];
|
|
271
|
+
const hosts = new Set();
|
|
272
|
+
for (const url of [entry.server_url, entry.metadata.token_endpoint]) {
|
|
273
|
+
try {
|
|
274
|
+
// With the port: a sign-in on :9443 does not need every port on that host.
|
|
275
|
+
hosts.add(new URL(url).host);
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
/* a malformed URL adds nothing; the connection will say what is wrong */
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return [...hosts];
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* What happened to a pack's rules, in plain words, from what core's batch
|
|
285
|
+
* actually did -- never from what was asked: a rule a person wrote for the
|
|
286
|
+
* same tool wins, and a policy the console may not write gets none.
|
|
287
|
+
*/
|
|
288
|
+
function packSummary(pack,
|
|
289
|
+
/** The server's own display name: the pack's label reads "Filesystem MCP server". */
|
|
290
|
+
name, batch, written, unwritable) {
|
|
291
|
+
if (unwritable) {
|
|
292
|
+
const why = unwritable.policyFile === null ? "its rules are written inside its gateway.yaml" : "it has policy_writes: false";
|
|
293
|
+
return [
|
|
294
|
+
`The ready-made rules for ${name} were not added, because this toolbox's rules can't be changed from the console ` +
|
|
295
|
+
`(${why}). Its tools are decided by the rules it already has.`
|
|
296
|
+
];
|
|
297
|
+
}
|
|
298
|
+
const out = [];
|
|
299
|
+
if (written.length > 0) {
|
|
300
|
+
out.push(`Added ${written.length === 1 ? "1 ready-made rule" : `${written.length} ready-made rules`} for ${name}.`);
|
|
301
|
+
}
|
|
302
|
+
const ids = new Set(pack.rules.map((r) => r.id));
|
|
303
|
+
const kept = batch.rulesSkipped.filter((r) => ids.has(r.id));
|
|
304
|
+
if (kept.length > 0) {
|
|
305
|
+
const tools = kept.map((k) => pack.rules.find((r) => r.id === k.id)?.match ?? k.id);
|
|
306
|
+
out.push(`Kept your own rule${kept.length === 1 ? "" : "s"} for ${tools.join(", ")} instead of the ready-made ` +
|
|
307
|
+
`one${kept.length === 1 ? "" : "s"}, so ${kept.length === 1 ? "that tool works" : "those tools work"} as you set ${kept.length === 1 ? "it" : "them"}.`);
|
|
308
|
+
}
|
|
309
|
+
if (written.length === 0 && kept.length === 0)
|
|
310
|
+
out.push(`The ready-made rules for ${name} were already in place.`);
|
|
311
|
+
return out;
|
|
312
|
+
}
|
|
313
|
+
/* ------------------------------------------------------------- live state */
|
|
314
|
+
function mergeUpstreams(rows) {
|
|
315
|
+
/*
|
|
316
|
+
* Several AI apps can each run the same toolbox. A server is shown as
|
|
317
|
+
* connected if any of them has it connected -- that is what the person can
|
|
318
|
+
* use -- and otherwise as the most recent report about it.
|
|
319
|
+
*/
|
|
320
|
+
const byName = new Map();
|
|
321
|
+
for (const row of rows) {
|
|
322
|
+
for (const u of row.upstreams) {
|
|
323
|
+
const seen = byName.get(u.name);
|
|
324
|
+
if (!seen)
|
|
325
|
+
byName.set(u.name, u);
|
|
326
|
+
else if (seen.state !== "connected" && (u.state === "connected" || Date.parse(u.since) > Date.parse(seen.since))) {
|
|
327
|
+
byName.set(u.name, u);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
332
|
+
}
|
|
333
|
+
function gatewayRunning(options, id, server) {
|
|
334
|
+
if (processes.isActive(id))
|
|
335
|
+
return true;
|
|
336
|
+
const announced = storeFor(server).runtimeState(server.component);
|
|
337
|
+
return announced !== undefined && runtimeStateIsLive(announced);
|
|
338
|
+
}
|
|
339
|
+
/* ------------------------------------------------------------- request bodies */
|
|
340
|
+
/** The draft is workstream D's shape; checked here only as far as this route relies on it. */
|
|
341
|
+
const DraftSchema = z
|
|
342
|
+
.object({
|
|
343
|
+
source: z.object({ kind: z.enum(["catalog", "registry", "paste", "manual"]) }).passthrough(),
|
|
344
|
+
name: z.string().min(1).max(64),
|
|
345
|
+
displayName: z.string().min(1).max(200),
|
|
346
|
+
launch: z.object({ transport: z.enum(["stdio", "http"]) }).passthrough(),
|
|
347
|
+
fields: z.array(z.object({ id: z.string(), kind: z.string() }).passthrough()).max(50),
|
|
348
|
+
guide: z.array(z.unknown()).max(50),
|
|
349
|
+
requires: z.array(z.string()).max(10),
|
|
350
|
+
pack: z.string().optional(),
|
|
351
|
+
pack_within_field: z.string().optional(),
|
|
352
|
+
warnings: z.array(z.string()).max(50)
|
|
353
|
+
})
|
|
354
|
+
.passthrough();
|
|
355
|
+
const TestServerBody = z
|
|
356
|
+
.object({
|
|
357
|
+
gatewayId: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
|
|
358
|
+
draft: DraftSchema,
|
|
359
|
+
values: z.record(z.string(), z.union([z.string().max(20_000), z.boolean(), z.array(z.string().max(4096)).max(50)])),
|
|
360
|
+
name: z.string().regex(/^[a-z0-9_]+$/, "a name is lower-case letters, digits and underscores").max(64).optional(),
|
|
361
|
+
/**
|
|
362
|
+
* The server this one takes the place of, by name: a fix such as
|
|
363
|
+
* "Choose the folder again" sets the same server up afresh, and saving
|
|
364
|
+
* puts it where the old one was rather than beside it.
|
|
365
|
+
*/
|
|
366
|
+
replacing: z.string().regex(/^[a-z0-9_]+$/).max(64).optional()
|
|
367
|
+
})
|
|
368
|
+
.strict();
|
|
369
|
+
const InstallBody = z
|
|
370
|
+
.object({
|
|
371
|
+
probeId: z.string().min(1).max(64),
|
|
372
|
+
expected: z.object({ gateway: z.string().min(1), policy: z.string().min(1) }).strict().optional(),
|
|
373
|
+
acknowledged: z.object({ loosens: z.literal(true) }).strict().optional(),
|
|
374
|
+
/**
|
|
375
|
+
* Only say what saving would loosen, and write nothing: the page asks
|
|
376
|
+
* this first, so the confirmation is not driven by a refused save (which
|
|
377
|
+
* every browser logs as an error).
|
|
378
|
+
*/
|
|
379
|
+
preview: z.literal(true).optional()
|
|
380
|
+
})
|
|
381
|
+
.strict();
|
|
382
|
+
const CreateSecretBody = z
|
|
383
|
+
.object({
|
|
384
|
+
name: z.string().regex(SECRET_NAME, "a key name is lower-case letters, digits, _ . or -").optional(),
|
|
385
|
+
label: z.string().min(1).max(200),
|
|
386
|
+
value: z.string().min(1).max(20_000)
|
|
387
|
+
})
|
|
388
|
+
.strict();
|
|
389
|
+
const PutSecretBody = z.object({ value: z.string().min(1).max(20_000) }).strict();
|
|
390
|
+
const MoveBody = z.object({ expectedDigest: z.string().min(1) }).strict();
|
|
391
|
+
export function serversAddRoutes(options) {
|
|
392
|
+
// A console killed during a test left a typed key in a scratch file and maybe the server running.
|
|
393
|
+
sweepTestLeftovers();
|
|
394
|
+
return [
|
|
395
|
+
/**
|
|
396
|
+
* "Test it". Runs the server with what was typed, against a scratch copy
|
|
397
|
+
* of everything, and keeps the result for install.
|
|
398
|
+
*/
|
|
399
|
+
route("POST", "/api/v1/test-server", async (ctx) => {
|
|
400
|
+
const body = parseBody(TestServerBody, ctx.body);
|
|
401
|
+
const draft = body.draft;
|
|
402
|
+
const values = body.values;
|
|
403
|
+
const gatewayId = body.gatewayId ?? DEFAULT_GATEWAY_ID;
|
|
404
|
+
const entry = entryById(options, gatewayId);
|
|
405
|
+
if (!entry && body.gatewayId && body.gatewayId !== DEFAULT_GATEWAY_ID) {
|
|
406
|
+
throw notFound(`there is no toolbox called "${body.gatewayId}"`);
|
|
407
|
+
}
|
|
408
|
+
const server = entry ? serverFor(entry) : null;
|
|
409
|
+
const real = secretStore();
|
|
410
|
+
const saved = secretSummaries(real);
|
|
411
|
+
const existingSecrets = saved.map((s) => s.name);
|
|
412
|
+
const existingSecretLabels = Object.fromEntries(saved.map((s) => [s.name, s.label]));
|
|
413
|
+
const machine = await doctor();
|
|
414
|
+
// Format checks come from our own catalog, never from the request (see validateFor).
|
|
415
|
+
const catalogFields = draft.source?.kind === "catalog" ? catalogEntry(draft.source.id)?.fields : undefined;
|
|
416
|
+
const check = draft.source?.kind === "catalog" ? catalogCheck(draft.source.id) : undefined;
|
|
417
|
+
let materialized;
|
|
418
|
+
try {
|
|
419
|
+
if (body.replacing && !server?.gateway.config.upstreams.some((u) => u.name === body.replacing)) {
|
|
420
|
+
throw notFound(`there is no server called "${body.replacing}" in this toolbox to set up again`);
|
|
421
|
+
}
|
|
422
|
+
materialized = materializeDraft(draft, values, {
|
|
423
|
+
takenNames: (server?.gateway.config.upstreams.map((u) => u.name) ?? []).filter((n) => n !== body.replacing),
|
|
424
|
+
...(body.replacing && !body.name ? { name: body.replacing } : {}),
|
|
425
|
+
existingSecrets,
|
|
426
|
+
existingSecretLabels,
|
|
427
|
+
validateFor: (id) => catalogFields?.find((f) => f.id === id)?.validate,
|
|
428
|
+
commandPaths: commandPathsFrom(machine),
|
|
429
|
+
...(body.name ? { name: body.name } : {})
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
catch (err) {
|
|
433
|
+
if (err instanceof HttpError)
|
|
434
|
+
throw err;
|
|
435
|
+
throw unprocessable(`this server could not be set up from what was filled in: ${err.message}`);
|
|
436
|
+
}
|
|
437
|
+
let replacesSecrets = [];
|
|
438
|
+
if (body.replacing && server) {
|
|
439
|
+
// Setting a server up again: a value the page only saw as the kept-secret marker is the one already saved.
|
|
440
|
+
const before = server.gateway.config.upstreams.find((u) => u.name === body.replacing);
|
|
441
|
+
materialized = { ...materialized, upstream: keepSavedValues(materialized.upstream, before) };
|
|
442
|
+
({ materialized, replaces: replacesSecrets } = replaceKeysInPlace(materialized, before, gatewayId, secretUsage(options), real));
|
|
443
|
+
}
|
|
444
|
+
const typed = materialized.secretsToCreate.map((s) => s.value);
|
|
445
|
+
const upstream = scrubSecrets(redactUpstream(materialized.upstream), typed);
|
|
446
|
+
if (Object.keys(materialized.problems).length > 0) {
|
|
447
|
+
return {
|
|
448
|
+
probeId: "",
|
|
449
|
+
outcome: { ok: false, tools: [], resources: 0, prompts: 0, findings: [], elapsedMs: 0 },
|
|
450
|
+
upstream,
|
|
451
|
+
egressHosts: materialized.egressHosts,
|
|
452
|
+
problems: scrubSecrets(materialized.problems, typed)
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
let outcome = await withProbeSlot(async () => {
|
|
456
|
+
/*
|
|
457
|
+
* A signed-in server is tested with the real locked-keys file: the
|
|
458
|
+
* sign-in already happened there, and a token refreshed during the
|
|
459
|
+
* test rotates the refresh token, so a copy would leave the real one
|
|
460
|
+
* stale. Only newly typed keys need the scratch file, and a sign-in
|
|
461
|
+
* server has none.
|
|
462
|
+
*/
|
|
463
|
+
const signedIn = materialized.upstream.transport === "http" && materialized.upstream.oauth !== undefined;
|
|
464
|
+
const scratch = signedIn && materialized.secretsToCreate.length === 0
|
|
465
|
+
? { store: real, dispose: () => { } }
|
|
466
|
+
: scratchSecretStore(materialized, real);
|
|
467
|
+
try {
|
|
468
|
+
const policy = scratchPolicy(server?.policy ?? newGatewayPolicy(DEFAULT_GATEWAY_ID), materialized.upstream, materialized.localNetwork, [...materialized.egressHosts, ...oauthHosts(materialized.upstream, real)]);
|
|
469
|
+
return await runProbe(materialized.upstream, {
|
|
470
|
+
policy,
|
|
471
|
+
secrets: scratch.store,
|
|
472
|
+
cwd: server?.cwd ?? homedir(),
|
|
473
|
+
...(materialized.packId ? { packId: materialized.packId } : {}),
|
|
474
|
+
...(materialized.within ? { within: materialized.within } : {}),
|
|
475
|
+
...(check ? { checkCall: check } : {})
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
finally {
|
|
479
|
+
scratch.dispose();
|
|
480
|
+
}
|
|
481
|
+
});
|
|
482
|
+
/*
|
|
483
|
+
* A 401 from an http server that was not set up to sign in: ask it
|
|
484
|
+
* whether it offers one. Without a key of our own in the request that is
|
|
485
|
+
* the whole answer ("sign in"); with one, the key was refused and stays
|
|
486
|
+
* the problem, but the page can still offer signing in instead.
|
|
487
|
+
*/
|
|
488
|
+
let signInAvailable = false;
|
|
489
|
+
const tried = materialized.upstream;
|
|
490
|
+
if (!outcome.ok &&
|
|
491
|
+
outcome.problem?.code === "auth-rejected" &&
|
|
492
|
+
(outcome.problem.detail?.status ?? 401) === 401 &&
|
|
493
|
+
tried.transport === "http" &&
|
|
494
|
+
!tried.oauth) {
|
|
495
|
+
signInAvailable = await offersSignIn(tried.url, consoleOAuthFetch(options.oauthAllowLoopbackForTests === true));
|
|
496
|
+
const sentKey = Object.keys(tried.headers).some((h) => h.toLowerCase() === "authorization");
|
|
497
|
+
if (signInAvailable && !sentKey) {
|
|
498
|
+
outcome = {
|
|
499
|
+
...outcome,
|
|
500
|
+
problem: { ...outcome.problem, code: "needs-sign-in", detail: { ...outcome.problem.detail, host: new URL(tried.url).host } }
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
const cached = rememberProbe({
|
|
505
|
+
gatewayId: entry ? gatewayId : null,
|
|
506
|
+
draft,
|
|
507
|
+
values,
|
|
508
|
+
materialized,
|
|
509
|
+
outcome,
|
|
510
|
+
...(body.replacing ? { replacing: body.replacing } : {}),
|
|
511
|
+
...(replacesSecrets.length > 0 ? { replacesSecrets } : {})
|
|
512
|
+
});
|
|
513
|
+
return {
|
|
514
|
+
probeId: cached.probeId,
|
|
515
|
+
outcome: scrubSecrets(outcome, typed),
|
|
516
|
+
upstream,
|
|
517
|
+
egressHosts: materialized.egressHosts,
|
|
518
|
+
problems: {},
|
|
519
|
+
...(signInAvailable ? { signInAvailable: true } : {})
|
|
520
|
+
};
|
|
521
|
+
}),
|
|
522
|
+
/**
|
|
523
|
+
* "Save and turn on". Creates the default toolbox when there is none.
|
|
524
|
+
* Policy first, then gateway.yaml; either both or neither.
|
|
525
|
+
*/
|
|
526
|
+
route("POST", "/api/v1/servers/:id/gateway/install", async (ctx) => {
|
|
527
|
+
const id = ctx.params["id"];
|
|
528
|
+
const body = parseBody(InstallBody, ctx.body);
|
|
529
|
+
const probe = recallProbe(body.probeId);
|
|
530
|
+
if (!probe) {
|
|
531
|
+
throw new HttpError(410, "probe-expired", "This test result is too old (they last 15 minutes). Press Test it again, then save.");
|
|
532
|
+
}
|
|
533
|
+
if (!probe.outcome.ok) {
|
|
534
|
+
throw unprocessable("The test did not pass, so the server was not saved. Fix what the test found and press Test it again.");
|
|
535
|
+
}
|
|
536
|
+
const { materialized } = probe;
|
|
537
|
+
const upstream = materialized.upstream;
|
|
538
|
+
const entry = entryById(options, id);
|
|
539
|
+
if (!entry && id !== DEFAULT_GATEWAY_ID)
|
|
540
|
+
throw notFound(`there is no toolbox called "${id}"`);
|
|
541
|
+
const creating = !entry;
|
|
542
|
+
const server = entry ? serverFor(entry) : null;
|
|
543
|
+
/* the files, and the digest checks */
|
|
544
|
+
let gatewayFile = null;
|
|
545
|
+
let policyPath;
|
|
546
|
+
let policyBefore;
|
|
547
|
+
if (server) {
|
|
548
|
+
if (!body.expected) {
|
|
549
|
+
throw conflict("The page did not say which version of this toolbox it saw, so nothing was saved in case it changed meanwhile. Reload, then save again.");
|
|
550
|
+
}
|
|
551
|
+
gatewayFile = readGatewayFile(expandPath(server.entry.config_path));
|
|
552
|
+
if (body.expected.gateway !== gatewayFile.digest || body.expected.policy !== policyDigest(server.policy)) {
|
|
553
|
+
throw conflict("This toolbox was changed since the page loaded it. Reload, then save again, so nothing changed meanwhile is lost.");
|
|
554
|
+
}
|
|
555
|
+
if (probe.replacing) {
|
|
556
|
+
if (!gatewayFile.config.upstreams.some((u) => u.name === probe.replacing)) {
|
|
557
|
+
throw conflict(`The server "${probe.replacing}" was removed from this toolbox since the test. Press Test it again.`);
|
|
558
|
+
}
|
|
559
|
+
if (upstream.name !== probe.replacing && gatewayFile.config.upstreams.some((u) => u.name === upstream.name)) {
|
|
560
|
+
throw conflict(`A server called "${upstream.name}" was added to this toolbox since the test. Press Test it again.`);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
else if (gatewayFile.config.upstreams.some((u) => u.name === upstream.name)) {
|
|
564
|
+
throw conflict(`A server called "${upstream.name}" was added to this toolbox since the test. Press Test it again.`);
|
|
565
|
+
}
|
|
566
|
+
if (server.policyFile === null || !server.gateway.config.policy_writes) {
|
|
567
|
+
policyPath = "";
|
|
568
|
+
policyBefore = "";
|
|
569
|
+
}
|
|
570
|
+
else {
|
|
571
|
+
policyPath = server.policyFile;
|
|
572
|
+
policyBefore = readFileSync(policyPath, "utf8");
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
else {
|
|
576
|
+
const dir = join(homedir(), ".hmcp", "gateways", DEFAULT_GATEWAY_ID);
|
|
577
|
+
for (const file of ["gateway.yaml", "policy.yaml"]) {
|
|
578
|
+
if (existsSync(join(dir, file))) {
|
|
579
|
+
throw conflict(`${join(dir, file)} already exists but is not in the console's list. Add it from Connections, or move it away.`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
policyPath = join(dir, "policy.yaml");
|
|
583
|
+
policyBefore = newGatewayPolicyText(DEFAULT_GATEWAY_ID);
|
|
584
|
+
}
|
|
585
|
+
/* what the policy needs: the address, POST, private addresses, and the pack's rules */
|
|
586
|
+
const namespace = gatewayFile?.config.namespace ?? true;
|
|
587
|
+
const pack = await packRulesFor({
|
|
588
|
+
packId: materialized.packId ?? probe.draft.pack,
|
|
589
|
+
upstreamName: upstream.name,
|
|
590
|
+
namespace,
|
|
591
|
+
toolNames: probe.outcome.tools.map((t) => t.name),
|
|
592
|
+
within: materialized.within
|
|
593
|
+
});
|
|
594
|
+
const changes = [
|
|
595
|
+
...egressChangesFor(upstream, { localNetwork: materialized.localNetwork }),
|
|
596
|
+
...[...materialized.egressHosts, ...oauthHosts(upstream, secretStore())].map((host) => ({ kind: "egress-allow", host })),
|
|
597
|
+
...(pack?.rules ?? []).map((rule) => ({ kind: "rule", rule: { ...rule } }))
|
|
598
|
+
];
|
|
599
|
+
let batch = unchangedBatch(policyBefore);
|
|
600
|
+
if (policyPath) {
|
|
601
|
+
batch = applyPolicyChanges(policyBefore, changes, policyPath);
|
|
602
|
+
if (server)
|
|
603
|
+
refuseIfOverridesOff(server.gateway.config, batch.loosens);
|
|
604
|
+
}
|
|
605
|
+
else if (changes.length > 0) {
|
|
606
|
+
const probeBatch = applyPolicyChanges(stringify(server.policy), changes.filter((c) => c.kind !== "rule"));
|
|
607
|
+
if (probeBatch.changed) {
|
|
608
|
+
throw unprocessable("This toolbox's rules can't be changed from the console " +
|
|
609
|
+
(server.policyFile === null ? "(they are written inside its gateway.yaml)" : "(it has policy_writes: false)") +
|
|
610
|
+
`, and this server needs its network rules changed: ${probeBatch.loosens.join("; ")}. Change them by hand, or add the server to another toolbox.`);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
/* gateway.yaml as it will be */
|
|
614
|
+
let gatewayText;
|
|
615
|
+
if (gatewayFile) {
|
|
616
|
+
const doc = parseDocument(gatewayFile.text);
|
|
617
|
+
const at = probe.replacing ? gatewayFile.config.upstreams.findIndex((u) => u.name === probe.replacing) : -1;
|
|
618
|
+
if (at >= 0)
|
|
619
|
+
doc.setIn(["upstreams", at], doc.createNode(upstreamYaml(upstream)));
|
|
620
|
+
else
|
|
621
|
+
doc.addIn(["upstreams"], doc.createNode(upstreamYaml(upstream)));
|
|
622
|
+
gatewayText = doc.toString();
|
|
623
|
+
}
|
|
624
|
+
else {
|
|
625
|
+
gatewayText = [
|
|
626
|
+
"# Created in the hardened-mcp console. policy.yaml beside this file decides",
|
|
627
|
+
"# what each tool may do. Keys are kept in the locked-keys file",
|
|
628
|
+
"# (~/.hmcp/secrets.json) and only named here.",
|
|
629
|
+
"",
|
|
630
|
+
stringify({ version: 1, name: DEFAULT_GATEWAY_ID, policy: "./policy.yaml", upstreams: [upstreamYaml(upstream)], on_injection: "strip", namespace: true }, { lineWidth: 0 })
|
|
631
|
+
].join("\n");
|
|
632
|
+
}
|
|
633
|
+
const parsed = UpstreamSchema.safeParse(upstream);
|
|
634
|
+
if (!parsed.success)
|
|
635
|
+
throw unprocessable(`the server is not valid: ${parsed.error.issues.map((i) => i.message).join("; ")}`);
|
|
636
|
+
/* everything this loosens, gated before anything is written */
|
|
637
|
+
const gatewayAfter = parseGatewayText(gatewayText);
|
|
638
|
+
const loosens = [...(gatewayFile ? gatewayLoosens(gatewayFile.config, gatewayAfter) : []), ...batch.loosens];
|
|
639
|
+
if (body.preview)
|
|
640
|
+
return { preview: true, loosens };
|
|
641
|
+
if (loosens.length > 0 && body.acknowledged?.loosens !== true) {
|
|
642
|
+
throw unprocessable(`saving this server lets more through and needs confirming: ${loosens.join("; ")}`, {
|
|
643
|
+
needs: "loosens",
|
|
644
|
+
loosens
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
/* keys first: the server refers to them */
|
|
648
|
+
const real = secretStore();
|
|
649
|
+
const createdSecrets = [];
|
|
650
|
+
// A key given a new value in place (Replace the key), with what it held, for a rollback.
|
|
651
|
+
const replacedSecrets = new Map();
|
|
652
|
+
const replacing = new Set(probe.replacesSecrets ?? []);
|
|
653
|
+
const rollbackSecrets = () => {
|
|
654
|
+
for (const name of createdSecrets) {
|
|
655
|
+
try {
|
|
656
|
+
real.delete(name);
|
|
657
|
+
}
|
|
658
|
+
catch {
|
|
659
|
+
/* best effort; the rollback must reach the files too */
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
for (const [name, was] of replacedSecrets) {
|
|
663
|
+
try {
|
|
664
|
+
real.set(name, was);
|
|
665
|
+
}
|
|
666
|
+
catch {
|
|
667
|
+
/* best effort */
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
try {
|
|
672
|
+
for (const s of materialized.secretsToCreate) {
|
|
673
|
+
if (replacing.has(s.name)) {
|
|
674
|
+
const was = real.get(s.name);
|
|
675
|
+
if (!was || was.kind !== "value")
|
|
676
|
+
throw conflict(`The locked key "${s.name}" was changed since the test. Press Test it again.`);
|
|
677
|
+
replacedSecrets.set(s.name, was);
|
|
678
|
+
real.set(s.name, { ...was, value: s.value, updated_at: now() });
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
if (real.has(s.name))
|
|
682
|
+
throw conflict(`A locked key called "${s.name}" was saved since the test. Press Test it again.`);
|
|
683
|
+
const stamp = now();
|
|
684
|
+
real.set(s.name, { kind: "value", value: s.value, label: s.label, created_at: stamp, updated_at: stamp });
|
|
685
|
+
createdSecrets.push(s.name);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
catch (err) {
|
|
689
|
+
// A key saved before the failure would otherwise stay behind, named by nothing.
|
|
690
|
+
rollbackSecrets();
|
|
691
|
+
if (err instanceof HttpError)
|
|
692
|
+
throw err;
|
|
693
|
+
throw unprocessable(`The keys couldn't be saved in the locked-keys file, so nothing was saved: ` +
|
|
694
|
+
scrubSecrets(err.message, materialized.secretsToCreate.map((x) => x.value)));
|
|
695
|
+
}
|
|
696
|
+
/* policy, then gateway.yaml, then (for a new toolbox) the list */
|
|
697
|
+
let newDigest;
|
|
698
|
+
const dir = dirname(policyPath || gatewayFile.path);
|
|
699
|
+
const createdDir = creating && !existsSync(dir);
|
|
700
|
+
try {
|
|
701
|
+
if (creating) {
|
|
702
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
703
|
+
writeFileSync(policyPath, batch.text, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
704
|
+
}
|
|
705
|
+
else if (batch.changed) {
|
|
706
|
+
writeAtomically(policyPath, batch.text);
|
|
707
|
+
}
|
|
708
|
+
try {
|
|
709
|
+
if (creating) {
|
|
710
|
+
const configPath = join(dir, "gateway.yaml");
|
|
711
|
+
writeFileSync(configPath, gatewayText, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
712
|
+
try {
|
|
713
|
+
loadGatewayConfig(configPath);
|
|
714
|
+
const reg = readRegistry(options.registryPath);
|
|
715
|
+
const added = {
|
|
716
|
+
id: DEFAULT_GATEWAY_ID,
|
|
717
|
+
kind: "gateway",
|
|
718
|
+
label: DEFAULT_GATEWAY_LABEL,
|
|
719
|
+
config_path: configPath,
|
|
720
|
+
added_at: now()
|
|
721
|
+
};
|
|
722
|
+
writeRegistry({ ...reg, servers: [...reg.servers, added] }, options.registryPath);
|
|
723
|
+
}
|
|
724
|
+
catch (err) {
|
|
725
|
+
if (existsSync(configPath))
|
|
726
|
+
unlinkSync(configPath);
|
|
727
|
+
throw err;
|
|
728
|
+
}
|
|
729
|
+
newDigest = digestText(gatewayText);
|
|
730
|
+
}
|
|
731
|
+
else {
|
|
732
|
+
const result = commitGatewayText({
|
|
733
|
+
file: gatewayFile,
|
|
734
|
+
text: gatewayText,
|
|
735
|
+
expectedDigest: body.expected.gateway,
|
|
736
|
+
acknowledgedLoosens: body.acknowledged?.loosens === true || loosens.length === 0,
|
|
737
|
+
intended: (before, after) => {
|
|
738
|
+
if (!sameExcept(before, after, ["upstreams"]))
|
|
739
|
+
return "adding the server would have changed something else too";
|
|
740
|
+
if (probe.replacing) {
|
|
741
|
+
const at = before.upstreams.findIndex((u) => u.name === probe.replacing);
|
|
742
|
+
return at >= 0 &&
|
|
743
|
+
after.upstreams.length === before.upstreams.length &&
|
|
744
|
+
before.upstreams.every((u, i) => i === at || JSON.stringify(u) === JSON.stringify(after.upstreams[i]))
|
|
745
|
+
? null
|
|
746
|
+
: "setting the server up again would have changed another server too";
|
|
747
|
+
}
|
|
748
|
+
return after.upstreams.length === before.upstreams.length + 1 &&
|
|
749
|
+
before.upstreams.every((u, i) => JSON.stringify(u) === JSON.stringify(after.upstreams[i]))
|
|
750
|
+
? null
|
|
751
|
+
: "adding the server would have changed something else too";
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
newDigest = result.digest;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
catch (err) {
|
|
758
|
+
// gateway.yaml was refused: the policy goes back to what it was.
|
|
759
|
+
if (creating) {
|
|
760
|
+
if (existsSync(policyPath))
|
|
761
|
+
unlinkSync(policyPath);
|
|
762
|
+
if (createdDir)
|
|
763
|
+
rmSync(dir, { recursive: true, force: true });
|
|
764
|
+
}
|
|
765
|
+
else if (batch.changed) {
|
|
766
|
+
writeAtomically(policyPath, policyBefore);
|
|
767
|
+
}
|
|
768
|
+
throw err;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
catch (err) {
|
|
772
|
+
rollbackSecrets();
|
|
773
|
+
if (err instanceof HttpError)
|
|
774
|
+
throw err;
|
|
775
|
+
if (err.code === "EEXIST")
|
|
776
|
+
throw conflict(`${err.message}; nothing was saved`);
|
|
777
|
+
throw unprocessable(`the server could not be saved, and nothing was changed: ${err.message}`);
|
|
778
|
+
}
|
|
779
|
+
forgetProbe(body.probeId);
|
|
780
|
+
/* audit both writes, never with a value -- and only what was really written */
|
|
781
|
+
const packIds = new Set((pack?.rules ?? []).map((r) => r.id));
|
|
782
|
+
const rulesWritten = [...batch.rulesAdded, ...batch.rulesReplaced].filter((r) => packIds.has(r));
|
|
783
|
+
const after = requireServer(options, id);
|
|
784
|
+
const warnings = [];
|
|
785
|
+
if (batch.changed || creating) {
|
|
786
|
+
const w = auditTo(after, ctx.actor, auditEntry("gateway.install.policy", `network rules and rules for "${upstream.name}" written to ${policyPath} via the console by ${ctx.actor}` +
|
|
787
|
+
(batch.loosens.length > 0 ? `, confirmed as loosening: ${batch.loosens.join("; ")}` : ""), {
|
|
788
|
+
upstream: upstream.name,
|
|
789
|
+
egress_hosts: changes.flatMap((c) => (c.kind === "egress-allow" ? [c.host] : [])),
|
|
790
|
+
rules: rulesWritten,
|
|
791
|
+
rules_skipped: batch.rulesSkipped.map((r) => r.id),
|
|
792
|
+
loosens: batch.loosens,
|
|
793
|
+
created: creating
|
|
794
|
+
}), "the policy was written");
|
|
795
|
+
if (w)
|
|
796
|
+
warnings.push(w);
|
|
797
|
+
}
|
|
798
|
+
const w = auditTo(after, ctx.actor, auditEntry("gateway.upstream.add", `connected server "${upstream.name}" added to ${after.entry.config_path} by ${ctx.actor}`, {
|
|
799
|
+
upstream: redactUpstream(upstream),
|
|
800
|
+
// The name a person knows it by, for Activity ("Added Files on this computer", UT6 N4).
|
|
801
|
+
display_name: probe.draft.displayName,
|
|
802
|
+
secrets_created: createdSecrets,
|
|
803
|
+
secrets_replaced: [...replacedSecrets.keys()],
|
|
804
|
+
loosens,
|
|
805
|
+
created: creating,
|
|
806
|
+
digest_after: newDigest
|
|
807
|
+
}), `"${upstream.name}" was added`);
|
|
808
|
+
if (w)
|
|
809
|
+
warnings.push(w);
|
|
810
|
+
/* what is running */
|
|
811
|
+
const rows = liveRows(storeFor(after), after.component);
|
|
812
|
+
const apply = applyStateFor({
|
|
813
|
+
rows,
|
|
814
|
+
running: gatewayRunning(options, id, after),
|
|
815
|
+
upstreamsOnly: true,
|
|
816
|
+
upstreamReload: after.gateway.config.upstream_reload,
|
|
817
|
+
digest: newDigest
|
|
818
|
+
});
|
|
819
|
+
const summary = [];
|
|
820
|
+
if (creating) {
|
|
821
|
+
// "Your toolbox is ready" is the result screen's own line for this.
|
|
822
|
+
summary.push("For now it only watches: everything runs and is written down. You choose whether to turn protection on in a later step, or under Protection settings.");
|
|
823
|
+
}
|
|
824
|
+
summary.push(probe.replacing ? `Saved the new settings for ${probe.draft.displayName}.` : `Added ${probe.draft.displayName} to your toolbox.`);
|
|
825
|
+
if (replacedSecrets.size > 0) {
|
|
826
|
+
summary.push(`Replaced ${replacedSecrets.size === 1 ? "the key" : `${replacedSecrets.size} keys`} in your locked keys (${[...replacedSecrets.keys()].join(", ")}). The old value is gone.`);
|
|
827
|
+
}
|
|
828
|
+
if (createdSecrets.length > 0)
|
|
829
|
+
summary.push(`Saved ${createdSecrets.length === 1 ? "1 key" : `${createdSecrets.length} keys`} in the locked-keys file.`);
|
|
830
|
+
// The same address can be both the server's own and one its setup names: said once.
|
|
831
|
+
const allowedSaid = new Set();
|
|
832
|
+
for (const c of changes) {
|
|
833
|
+
if (c.kind !== "egress-allow" || allowedSaid.has(c.host) || !batch.loosens.includes(`Your toolbox may connect to ${c.host}`))
|
|
834
|
+
continue;
|
|
835
|
+
allowedSaid.add(c.host);
|
|
836
|
+
summary.push(`Added ${c.host} to the allowed addresses.`);
|
|
837
|
+
}
|
|
838
|
+
if (pack && pack.rules.length > 0)
|
|
839
|
+
summary.push(...packSummary(pack, probe.draft.displayName, batch, rulesWritten, policyPath ? null : server));
|
|
840
|
+
if (pack && pack.skippedBounds.length > 0)
|
|
841
|
+
summary.push(`No folder limit was written for ${pack.skippedBounds.join(", ")}, because no folder was chosen.`);
|
|
842
|
+
// Whether it is on yet is the result screen's own title, so it is not repeated here.
|
|
843
|
+
summary.push(...warnings);
|
|
844
|
+
return {
|
|
845
|
+
gatewayId: id,
|
|
846
|
+
upstreamName: upstream.name,
|
|
847
|
+
displayName: probe.draft.displayName,
|
|
848
|
+
apply,
|
|
849
|
+
digests: { gateway: newDigest, policy: policyDigest(after.policy) },
|
|
850
|
+
created: creating,
|
|
851
|
+
summary
|
|
852
|
+
};
|
|
853
|
+
}),
|
|
854
|
+
route("GET", "/api/v1/servers/:id/live", (ctx) => {
|
|
855
|
+
const server = requireServer(options, ctx.params["id"]);
|
|
856
|
+
const rows = liveRows(storeFor(server), server.component);
|
|
857
|
+
let digest = "";
|
|
858
|
+
try {
|
|
859
|
+
digest = digestText(readFileSync(expandPath(server.entry.config_path), "utf8"));
|
|
860
|
+
}
|
|
861
|
+
catch {
|
|
862
|
+
/* no file, nothing applied */
|
|
863
|
+
}
|
|
864
|
+
return {
|
|
865
|
+
upstreams: mergeUpstreams(rows),
|
|
866
|
+
processes: rows.map((r) => ({
|
|
867
|
+
pid: r.pid,
|
|
868
|
+
config_digest: r.config_digest,
|
|
869
|
+
applied_at: r.applied_at,
|
|
870
|
+
refusal: r.refusal,
|
|
871
|
+
heartbeat_at: r.heartbeat_at
|
|
872
|
+
})),
|
|
873
|
+
applied: rows.some((r) => r.config_digest === digest),
|
|
874
|
+
running: rows.length > 0
|
|
875
|
+
};
|
|
876
|
+
}),
|
|
877
|
+
route("POST", "/api/v1/servers/:id/upstreams/:name/retry", (ctx) => {
|
|
878
|
+
parseBody(z.object({}).strict(), ctx.body);
|
|
879
|
+
const server = requireServer(options, ctx.params["id"]);
|
|
880
|
+
const name = ctx.params["name"];
|
|
881
|
+
if (!server.gateway.config.upstreams.some((u) => u.name === name))
|
|
882
|
+
throw notFound(`there is no server called "${name}" in this toolbox`);
|
|
883
|
+
if (liveRows(storeFor(server), server.component).length === 0) {
|
|
884
|
+
throw unprocessable("This toolbox is not running right now, so there is nothing to retry. It tries every server when your AI app starts it.");
|
|
885
|
+
}
|
|
886
|
+
if (!requestRetry(storeFor(server), server.component, name)) {
|
|
887
|
+
throw unprocessable("The running toolbox cannot take a retry request yet. Restart your AI app to try again.");
|
|
888
|
+
}
|
|
889
|
+
return respond(202, {});
|
|
890
|
+
}),
|
|
891
|
+
/* locked keys: names only, ever */
|
|
892
|
+
route("GET", "/api/v1/secrets", () => {
|
|
893
|
+
const store = secretStore();
|
|
894
|
+
let list;
|
|
895
|
+
try {
|
|
896
|
+
list = store.list();
|
|
897
|
+
}
|
|
898
|
+
catch (err) {
|
|
899
|
+
throw unprocessable(err.message);
|
|
900
|
+
}
|
|
901
|
+
const usage = secretUsage(options);
|
|
902
|
+
return { secrets: list.map((s) => ({ ...s, usedBy: usage.get(s.name) ?? [] })), path: store.path };
|
|
903
|
+
}),
|
|
904
|
+
route("POST", "/api/v1/secrets", (ctx) => {
|
|
905
|
+
const body = parseBody(CreateSecretBody, ctx.body);
|
|
906
|
+
const store = secretStore();
|
|
907
|
+
const taken = new Set(secretNames(store));
|
|
908
|
+
if (body.name && taken.has(body.name))
|
|
909
|
+
throw conflict(`A locked key called "${body.name}" already exists. Choose another name, or change that key instead.`);
|
|
910
|
+
const name = body.name ?? secretNameFrom(body.label, taken);
|
|
911
|
+
const stamp = now();
|
|
912
|
+
store.set(name, { kind: "value", value: body.value, label: body.label, created_at: stamp, updated_at: stamp });
|
|
913
|
+
return { name };
|
|
914
|
+
}),
|
|
915
|
+
route("PUT", "/api/v1/secrets/:name", (ctx) => {
|
|
916
|
+
const body = parseBody(PutSecretBody, ctx.body);
|
|
917
|
+
const name = ctx.params["name"];
|
|
918
|
+
const store = secretStore();
|
|
919
|
+
let current;
|
|
920
|
+
try {
|
|
921
|
+
current = store.get(name);
|
|
922
|
+
}
|
|
923
|
+
catch (err) {
|
|
924
|
+
throw unprocessable(err.message);
|
|
925
|
+
}
|
|
926
|
+
if (!current)
|
|
927
|
+
throw notFound(`There is no locked key called "${name}".`);
|
|
928
|
+
if (current.kind !== "value") {
|
|
929
|
+
throw unprocessable(`"${name}" is a sign-in, not a typed key. To change it, sign in again from the server's page.`);
|
|
930
|
+
}
|
|
931
|
+
store.update(name, (fresh) => fresh && fresh.kind === "value" ? { ...fresh, value: body.value, updated_at: now() } : fresh);
|
|
932
|
+
return { name };
|
|
933
|
+
}),
|
|
934
|
+
route("DELETE", "/api/v1/secrets/:name", (ctx) => {
|
|
935
|
+
const name = ctx.params["name"];
|
|
936
|
+
const store = secretStore();
|
|
937
|
+
const users = secretUsage(options).get(name) ?? [];
|
|
938
|
+
if (users.length > 0) {
|
|
939
|
+
throw new HttpError(409, "conflict", `"${name}" is still used by ${users.map((u) => `"${u.upstream}" in ${u.gatewayId}`).join(", ")}. ` +
|
|
940
|
+
`Remove ${users.length === 1 ? "that server" : "those servers"} first, or give ${users.length === 1 ? "it" : "them"} another key.`, { usedBy: users });
|
|
941
|
+
}
|
|
942
|
+
let deleted;
|
|
943
|
+
try {
|
|
944
|
+
deleted = store.delete(name);
|
|
945
|
+
}
|
|
946
|
+
catch (err) {
|
|
947
|
+
throw unprocessable(err.message);
|
|
948
|
+
}
|
|
949
|
+
if (!deleted)
|
|
950
|
+
throw notFound(`There is no locked key called "${name}".`);
|
|
951
|
+
return { deleted: name };
|
|
952
|
+
}),
|
|
953
|
+
/**
|
|
954
|
+
* "Move to locked file": every literal env or header value in this
|
|
955
|
+
* toolbox becomes a locked key and a `{ secret }` reference in its place.
|
|
956
|
+
*/
|
|
957
|
+
route("POST", "/api/v1/servers/:id/gateway/secrets/move", (ctx) => {
|
|
958
|
+
const id = ctx.params["id"];
|
|
959
|
+
const body = parseBody(MoveBody, ctx.body);
|
|
960
|
+
const server = requireServer(options, id);
|
|
961
|
+
const file = readGatewayFile(expandPath(server.entry.config_path));
|
|
962
|
+
if (body.expectedDigest !== file.digest) {
|
|
963
|
+
throw conflict("This toolbox was changed since the page loaded it. Reload, then try again.");
|
|
964
|
+
}
|
|
965
|
+
const store = secretStore();
|
|
966
|
+
const taken = new Set(secretNames(store));
|
|
967
|
+
const doc = parseDocument(file.text);
|
|
968
|
+
const moves = [];
|
|
969
|
+
file.config.upstreams.forEach((u, index) => {
|
|
970
|
+
const field = u.transport === "http" ? "headers" : "env";
|
|
971
|
+
const record = (u.transport === "http" ? u.headers : u.env);
|
|
972
|
+
for (const [key, value] of Object.entries(record)) {
|
|
973
|
+
if (typeof value !== "string" || value.length === 0)
|
|
974
|
+
continue;
|
|
975
|
+
const bearer = field === "headers" && key.toLowerCase() === "authorization" ? /^(Bearer |Token |Basic )(.+)$/.exec(value) : null;
|
|
976
|
+
const secret = secretNameFrom(`${u.name}_${key}`, taken);
|
|
977
|
+
taken.add(secret);
|
|
978
|
+
moves.push({
|
|
979
|
+
upstream: u.name,
|
|
980
|
+
key,
|
|
981
|
+
secret,
|
|
982
|
+
value: bearer ? bearer[2] : value,
|
|
983
|
+
...(bearer ? { prefix: bearer[1] } : {}),
|
|
984
|
+
index,
|
|
985
|
+
field
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
});
|
|
989
|
+
const stillIn = backupsHolding(server);
|
|
990
|
+
if (moves.length === 0)
|
|
991
|
+
return { moved: [], digest: file.digest, stillIn };
|
|
992
|
+
for (const m of moves) {
|
|
993
|
+
doc.setIn(["upstreams", m.index, m.field, m.key], doc.createNode({ secret: m.secret, ...(m.prefix ? { prefix: m.prefix } : {}) }));
|
|
994
|
+
}
|
|
995
|
+
const created = [];
|
|
996
|
+
try {
|
|
997
|
+
for (const m of moves) {
|
|
998
|
+
const stamp = now();
|
|
999
|
+
store.set(m.secret, { kind: "value", value: m.value, label: `${m.upstream}: ${m.key}`, created_at: stamp, updated_at: stamp });
|
|
1000
|
+
created.push(m.secret);
|
|
1001
|
+
}
|
|
1002
|
+
const result = commitGatewayText({
|
|
1003
|
+
file,
|
|
1004
|
+
text: doc.toString(),
|
|
1005
|
+
expectedDigest: body.expectedDigest,
|
|
1006
|
+
acknowledgedLoosens: false,
|
|
1007
|
+
intended: (before, after) => (onlyValuesBecameRefs(before, after) ? null : "moving keys would have changed something else too")
|
|
1008
|
+
});
|
|
1009
|
+
const warning = auditTo(server, ctx.actor, auditEntry("gateway.secrets.move", `${moves.length} value(s) in ${file.path} moved to the locked-keys file by ${ctx.actor}`, {
|
|
1010
|
+
moved: moves.map((m) => ({ upstream: m.upstream, key: m.key, secret: m.secret })),
|
|
1011
|
+
digest_before: result.previousDigest,
|
|
1012
|
+
digest_after: result.digest
|
|
1013
|
+
}), "the keys were moved");
|
|
1014
|
+
if (warning)
|
|
1015
|
+
process.stderr.write(`[hmcp-web] ${warning}\n`);
|
|
1016
|
+
return { moved: moves.map((m) => ({ upstream: m.upstream, key: m.key, secret: m.secret })), digest: result.digest, stillIn };
|
|
1017
|
+
}
|
|
1018
|
+
catch (err) {
|
|
1019
|
+
for (const name of created) {
|
|
1020
|
+
try {
|
|
1021
|
+
store.delete(name);
|
|
1022
|
+
}
|
|
1023
|
+
catch {
|
|
1024
|
+
/* best effort */
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
throw err;
|
|
1028
|
+
}
|
|
1029
|
+
})
|
|
1030
|
+
];
|
|
1031
|
+
}
|
|
1032
|
+
/** True when the only change is literal env/header values turned into references. */
|
|
1033
|
+
function onlyValuesBecameRefs(before, after) {
|
|
1034
|
+
if (!sameExcept(before, after, ["upstreams"]) || before.upstreams.length !== after.upstreams.length)
|
|
1035
|
+
return false;
|
|
1036
|
+
return before.upstreams.every((b, i) => {
|
|
1037
|
+
const a = after.upstreams[i];
|
|
1038
|
+
if (a.transport !== b.transport || a.name !== b.name)
|
|
1039
|
+
return false;
|
|
1040
|
+
const field = b.transport === "http" ? "headers" : "env";
|
|
1041
|
+
const strip = (u) => JSON.stringify({ ...u, [field]: undefined });
|
|
1042
|
+
if (strip(a) !== strip(b))
|
|
1043
|
+
return false;
|
|
1044
|
+
const bv = b[field];
|
|
1045
|
+
const av = a[field];
|
|
1046
|
+
const keys = Object.keys(bv);
|
|
1047
|
+
if (keys.length !== Object.keys(av).length)
|
|
1048
|
+
return false;
|
|
1049
|
+
return keys.every((k) => JSON.stringify(av[k]) === JSON.stringify(bv[k]) || (typeof bv[k] === "string" && isSecretRef(av[k])));
|
|
1050
|
+
});
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Backups the console knows of that may still hold the old values: the
|
|
1054
|
+
* `.hmcp-backup` an adopt left beside each AI app's config, and any in the
|
|
1055
|
+
* toolbox's own folder.
|
|
1056
|
+
*/
|
|
1057
|
+
function backupsHolding(server) {
|
|
1058
|
+
const out = new Set();
|
|
1059
|
+
try {
|
|
1060
|
+
for (const c of detectClients({})) {
|
|
1061
|
+
const backup = `${c.path}.hmcp-backup`;
|
|
1062
|
+
if (existsSync(backup))
|
|
1063
|
+
out.add(backup);
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
catch {
|
|
1067
|
+
/* the list is a courtesy */
|
|
1068
|
+
}
|
|
1069
|
+
try {
|
|
1070
|
+
for (const name of readdirSync(server.cwd))
|
|
1071
|
+
if (name.includes(".hmcp-backup"))
|
|
1072
|
+
out.add(join(server.cwd, name));
|
|
1073
|
+
}
|
|
1074
|
+
catch {
|
|
1075
|
+
/* as above */
|
|
1076
|
+
}
|
|
1077
|
+
try {
|
|
1078
|
+
// A project's backups sit in its .hmcp/backups (the toolbox's own folder, or the one above it).
|
|
1079
|
+
for (const dir of [join(server.cwd, "backups"), join(server.cwd, "..", "backups")]) {
|
|
1080
|
+
if (!existsSync(dir))
|
|
1081
|
+
continue;
|
|
1082
|
+
for (const name of readdirSync(dir))
|
|
1083
|
+
if (name.endsWith(".hmcp-backup"))
|
|
1084
|
+
out.add(resolve(dir, name));
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
catch {
|
|
1088
|
+
/* as above */
|
|
1089
|
+
}
|
|
1090
|
+
return [...out].sort();
|
|
1091
|
+
}
|