hmcp-web 0.1.0 → 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/README.md +3 -2
- package/dist/api.d.ts +11 -0
- package/dist/api.js +64 -10
- package/dist/model/app-servers.d.ts +85 -0
- package/dist/model/app-servers.js +109 -0
- package/dist/model/import-record.d.ts +80 -0
- package/dist/model/import-record.js +179 -0
- package/dist/model/metrics.js +16 -1
- package/dist/routes/connect-import.d.ts +9 -0
- package/dist/routes/connect-import.js +594 -0
- package/dist/routes/connect.d.ts +36 -0
- package/dist/routes/connect.js +71 -13
- 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/runtime.d.ts +6 -0
- package/dist/routes/runtime.js +1 -1
- package/dist/routes/servers-add.d.ts +8 -0
- package/dist/routes/servers-add.js +2 -2
- package/dist-ui/assets/{Activity-BqKGpXMN.js → Activity-CZ78RyRO.js} +1 -1
- 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-B39L2Yma.js → Gallery-DB_OO7Vw.js} +1 -1
- package/dist-ui/assets/{PreApprovals-BsIhjMqb.js → PreApprovals-C4cKajcK.js} +1 -1
- package/dist-ui/assets/{Protection-DlB09ABa.js → Protection-B8h-5YAb.js} +1 -1
- package/dist-ui/assets/{Safety-CN-oHO2h.js → Safety-BQqHyYdo.js} +1 -1
- package/dist-ui/assets/{Settings-BLD7G1Ag.js → Settings-Cx50zZSt.js} +1 -1
- package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
- package/dist-ui/assets/{Suggestions-Dp7pofcs.js → Suggestions-CRo5UOTT.js} +1 -1
- 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-DQ7Oxf5n.js → kit-DRVm92_t.js} +1 -1
- package/dist-ui/index.html +3 -3
- package/package.json +4 -4
- package/dist-ui/assets/Approvals-Qo7bCcli.js +0 -1
- package/dist-ui/assets/AttachApp-0zRSPgSY.js +0 -5
- package/dist-ui/assets/Connections-CE0JGe8c.js +0 -2
- package/dist-ui/assets/StartPage-HuZSnmSr.js +0 -1
- package/dist-ui/assets/Tools-Bfot3bx5.js +0 -4
- package/dist-ui/assets/index-Khp0l1zp.js +0 -16
- package/dist-ui/assets/index-Ylyt4DEr.css +0 -2
package/dist/model/metrics.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { queryAuditLog } from "hmcp-core";
|
|
2
|
+
import { GUARD_LOOKALIKE_RULE, GUARD_OUTCOME_RULE } from "hmcp-gateway";
|
|
2
3
|
import { scopedFor, storeFor } from "./server.js";
|
|
3
4
|
/**
|
|
4
5
|
* Aggregates for the console's overview, read out of the audit log.
|
|
@@ -135,10 +136,24 @@ otherComponents = []) {
|
|
|
135
136
|
unknownTool++;
|
|
136
137
|
continue;
|
|
137
138
|
}
|
|
139
|
+
/*
|
|
140
|
+
* A call the Claude Code guard checked is written twice: the decision
|
|
141
|
+
* before it ran (outcome "relayed") and what became of it after ("guard.
|
|
142
|
+
* outcome"). Counted once: the decision, effect, tool and time from the
|
|
143
|
+
* first, and how it ended from the second. A name the guard declined to
|
|
144
|
+
* treat as the toolbox's own is a note beside the call, not a call.
|
|
145
|
+
*/
|
|
146
|
+
if (record.rule_id === GUARD_LOOKALIKE_RULE)
|
|
147
|
+
continue;
|
|
148
|
+
if (record.rule_id === GUARD_OUTCOME_RULE) {
|
|
149
|
+
outcomes[record.outcome] = (outcomes[record.outcome] ?? 0) + 1;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
138
152
|
const decision = record.decision;
|
|
139
153
|
if (decision === "allow" || decision === "approve" || decision === "deny")
|
|
140
154
|
decisions[decision]++;
|
|
141
|
-
|
|
155
|
+
if (record.outcome !== "relayed")
|
|
156
|
+
outcomes[record.outcome] = (outcomes[record.outcome] ?? 0) + 1;
|
|
142
157
|
// An unclassified call is its own fact, not a missing one — the whole
|
|
143
158
|
// reason `on_unclassified: deny` exists — so it is counted under its own
|
|
144
159
|
// key rather than dropped.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ApiOptions } from "../api.js";
|
|
2
|
+
import { type Route } from "../http.js";
|
|
3
|
+
/**
|
|
4
|
+
* Puts back what a refused import wrote, every step tried even when one
|
|
5
|
+
* before it fails: a gateway.yaml that can't be restored must not also leave
|
|
6
|
+
* the new keys behind. Returns what could not be put back, without keys.
|
|
7
|
+
*/
|
|
8
|
+
export declare function rollBack(steps: readonly (readonly [string, () => void])[], values: readonly string[]): string[];
|
|
9
|
+
export declare function connectImportRoutes(options: ApiOptions): Route[];
|
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, resolve } from "node:path";
|
|
4
|
+
import { parseDocument, stringify } from "yaml";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { SecretStore, expandPath, readRegistry, writeAtomically } from "hmcp-core";
|
|
7
|
+
import { ClientConfigError, ImportClientError, importCandidates, isRemote, keyWords, moveOutOfClient, parseServers, planImportSecrets, putBackInClient, readBackup, readClientConfig, restartHintFor, runsToolbox, scopeTargets } from "hmcp-gateway";
|
|
8
|
+
import { HttpError, conflict, unprocessable, route } from "../http.js";
|
|
9
|
+
import { loadServer } from "../model/server.js";
|
|
10
|
+
import { applyPolicyChanges, commitGatewayText, egressChangesFor, gatewayLoosens, parseGatewayText, readGatewayFile, refuseIfOverridesOff, sameExcept, unchangedBatch } from "../model/gateway-config.js";
|
|
11
|
+
import { runProbe, scratchPolicy, scratchSecretStore, scrubSecrets, withProbeSlot } from "../model/probe.js";
|
|
12
|
+
import { deleteImportRecord, readLiveImportRecord, upstreamDigest, writeImportRecord } from "../model/import-record.js";
|
|
13
|
+
import { targetFor } from "../model/app-servers.js";
|
|
14
|
+
import { LABELS, ScopeSchema, gatewayAudit, parse, projectDirOf, record } from "./connect.js";
|
|
15
|
+
import { removeServerRules } from "./runtime.js";
|
|
16
|
+
import { secretUsage, upstreamYaml } from "./servers-add.js";
|
|
17
|
+
/**
|
|
18
|
+
* "Bring in servers": moving the servers an AI app runs by itself into the
|
|
19
|
+
* toolbox it is connected to, so every call they make is checked.
|
|
20
|
+
*
|
|
21
|
+
* The same rules as adding a server by hand hold, with one more file in play:
|
|
22
|
+
*
|
|
23
|
+
* - Every server is tested first, the way "Test it" tests one, against a
|
|
24
|
+
* scratch copy of the keys and the policy. Only servers that connected are
|
|
25
|
+
* brought in; the rest stay in the app, untouched, and the reply says why.
|
|
26
|
+
* - Writes go keys, then policy, then gateway.yaml, then the app's settings
|
|
27
|
+
* -- each one put back if a later one is refused. The app's file is last so
|
|
28
|
+
* that at every moment a server is in the app, the toolbox, or both; never
|
|
29
|
+
* in neither.
|
|
30
|
+
* - A server leaves the app only after its entry is kept in the connection's
|
|
31
|
+
* undo record, so "Undo connection" gives it back too.
|
|
32
|
+
*
|
|
33
|
+
* Nothing about a server but its name goes back to the browser: no command
|
|
34
|
+
* line, address, setting value or key. A failure's message has every one of
|
|
35
|
+
* those taken out before it is sent.
|
|
36
|
+
*/
|
|
37
|
+
const ImportBody = z
|
|
38
|
+
.object({
|
|
39
|
+
scope: ScopeSchema,
|
|
40
|
+
projectDir: z.string().min(1).optional(),
|
|
41
|
+
/** Entry names in the app's settings. */
|
|
42
|
+
names: z.array(z.string().min(1).max(200)).max(100),
|
|
43
|
+
/** Claude Desktop extension ids. */
|
|
44
|
+
extensions: z.array(z.string().min(1).max(200)).max(100),
|
|
45
|
+
acknowledged: z.object({ loosens: z.literal(true) }).strict().optional(),
|
|
46
|
+
confirm: z.literal(true)
|
|
47
|
+
})
|
|
48
|
+
.strict();
|
|
49
|
+
const UndoBody = z
|
|
50
|
+
.object({
|
|
51
|
+
scope: ScopeSchema,
|
|
52
|
+
projectDir: z.string().min(1).optional(),
|
|
53
|
+
confirm: z.literal(true)
|
|
54
|
+
})
|
|
55
|
+
.strict();
|
|
56
|
+
/**
|
|
57
|
+
* The toolbox this app was connected to from the console. An app that is
|
|
58
|
+
* not connected, or was connected with adopt (which already moved its
|
|
59
|
+
* servers in, and owns its files), has nothing to bring servers into.
|
|
60
|
+
*/
|
|
61
|
+
function connectedToolbox(options, scope, cwd) {
|
|
62
|
+
const home = homedir();
|
|
63
|
+
const target = targetFor(scope, cwd, home);
|
|
64
|
+
let backup;
|
|
65
|
+
try {
|
|
66
|
+
backup = readBackup(target);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
throw unprocessable(err.message);
|
|
70
|
+
}
|
|
71
|
+
if (!backup || backup.scope !== scope) {
|
|
72
|
+
throw unprocessable(`Connect the app first: ${LABELS[scope]} isn't connected to a toolbox from this console, so there is nothing to bring its servers into.`);
|
|
73
|
+
}
|
|
74
|
+
if (backup.generated.length > 0 || !backup.registry_id) {
|
|
75
|
+
throw unprocessable(`${LABELS[scope]} was connected the older way, which already moved its servers into its toolbox. ` +
|
|
76
|
+
`Undo that connection and connect it again from here to bring servers in this way.`);
|
|
77
|
+
}
|
|
78
|
+
const entry = readRegistry(options.registryPath).servers.find((s) => s.id === backup.registry_id);
|
|
79
|
+
if (!entry || entry.kind !== "gateway") {
|
|
80
|
+
throw unprocessable(`Connect the app first: the toolbox ${LABELS[scope]} was connected to is no longer in this console.`);
|
|
81
|
+
}
|
|
82
|
+
const configPath = resolve(expandPath(entry.config_path));
|
|
83
|
+
/*
|
|
84
|
+
* The record is not enough: Claude Code's `local` record is shared by every
|
|
85
|
+
* project, and an entry deleted by hand leaves it behind. Taking servers out
|
|
86
|
+
* of a place that doesn't run the toolbox would leave them nowhere.
|
|
87
|
+
*/
|
|
88
|
+
if (!runsToolbox({ scope, cwd, home }, backup.gateway_entry_name, configPath)) {
|
|
89
|
+
throw unprocessable(`Connect the app first: ${LABELS[scope]} here doesn't run the toolbox (its "${backup.gateway_entry_name}" entry isn't in its settings), ` +
|
|
90
|
+
`so there is nothing to bring its servers into.`);
|
|
91
|
+
}
|
|
92
|
+
let server;
|
|
93
|
+
try {
|
|
94
|
+
server = loadServer(entry);
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
if (err instanceof HttpError)
|
|
98
|
+
throw err;
|
|
99
|
+
throw unprocessable(`toolbox "${entry.id}" could not be loaded: ${err.message}`);
|
|
100
|
+
}
|
|
101
|
+
return { target, entry, server, configPath, entryName: backup.gateway_entry_name, home };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The values of one server that must not reach the browser: every setting
|
|
105
|
+
* and header value as the app had it, and any part of its command line or
|
|
106
|
+
* address shaped like a key. The program's own name and its ordinary
|
|
107
|
+
* arguments are left alone, so a failure such as "node: not found" still
|
|
108
|
+
* reads as itself.
|
|
109
|
+
*/
|
|
110
|
+
function valuesOf(c) {
|
|
111
|
+
const out = [];
|
|
112
|
+
for (const planned of c.plan?.upstreams ?? []) {
|
|
113
|
+
const u = planned.upstream;
|
|
114
|
+
const literal = Object.values(u.transport === "stdio" ? u.env : u.headers).filter((v) => typeof v === "string");
|
|
115
|
+
// The same shapes that keep a server out (`keyWords`), in case a message quotes the command line or address.
|
|
116
|
+
out.push(...literal, ...keyWords(u.transport === "stdio" ? [u.command, ...u.args] : [u.url]));
|
|
117
|
+
}
|
|
118
|
+
out.push(...Object.values(c.plan?.gatewayEnv ?? {}));
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Puts back what a refused import wrote, every step tried even when one
|
|
123
|
+
* before it fails: a gateway.yaml that can't be restored must not also leave
|
|
124
|
+
* the new keys behind. Returns what could not be put back, without keys.
|
|
125
|
+
*/
|
|
126
|
+
export function rollBack(steps, values) {
|
|
127
|
+
const problems = [];
|
|
128
|
+
for (const [what, step] of steps) {
|
|
129
|
+
try {
|
|
130
|
+
step();
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
problems.push(scrubbed(`${what} could not be put back as it was (${err.message ?? String(err)})`, values));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return problems;
|
|
137
|
+
}
|
|
138
|
+
/** A refusal's message without any of those values in it. */
|
|
139
|
+
function scrubbed(message, values) {
|
|
140
|
+
return scrubSecrets(message, values);
|
|
141
|
+
}
|
|
142
|
+
/** `text` with these servers added at the end of `upstreams`, comments and layout kept. */
|
|
143
|
+
function withUpstreams(text, upstreams) {
|
|
144
|
+
const doc = parseDocument(text);
|
|
145
|
+
for (const u of upstreams)
|
|
146
|
+
doc.addIn(["upstreams"], doc.createNode(upstreamYaml(u)));
|
|
147
|
+
return doc.toString();
|
|
148
|
+
}
|
|
149
|
+
/** The other apps whose settings run this toolbox, so the person knows what else now runs these servers. */
|
|
150
|
+
function otherAppsUsing(configPath, except, cwd, home) {
|
|
151
|
+
const out = [];
|
|
152
|
+
for (const target of scopeTargets({ cwd, home })) {
|
|
153
|
+
if (target.scope === except.scope)
|
|
154
|
+
continue;
|
|
155
|
+
try {
|
|
156
|
+
const { servers } = parseServers(readClientConfig(target.scope, { cwd, home }).servers);
|
|
157
|
+
const uses = [...servers.values()].some((s) => {
|
|
158
|
+
if (isRemote(s))
|
|
159
|
+
return false;
|
|
160
|
+
const i = s.args.indexOf("-c");
|
|
161
|
+
const at = i >= 0 ? s.args[i + 1] : undefined;
|
|
162
|
+
return at !== undefined && resolve(dirname(target.path), at) === configPath;
|
|
163
|
+
});
|
|
164
|
+
if (uses && !out.includes(LABELS[target.scope]))
|
|
165
|
+
out.push(LABELS[target.scope]);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
/* an unreadable file is not evidence either way */
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
/** The gateway engine's refusals as the console's error shape. */
|
|
174
|
+
function asHttp(err, values = []) {
|
|
175
|
+
if (err instanceof HttpError)
|
|
176
|
+
throw err;
|
|
177
|
+
const message = scrubbed(err.message ?? String(err), values);
|
|
178
|
+
if (err instanceof ImportClientError && /changed/.test(message))
|
|
179
|
+
throw conflict(message);
|
|
180
|
+
if (err instanceof ClientConfigError)
|
|
181
|
+
throw unprocessable(message);
|
|
182
|
+
throw unprocessable(`nothing was changed: ${message}`);
|
|
183
|
+
}
|
|
184
|
+
export function connectImportRoutes(options) {
|
|
185
|
+
return [
|
|
186
|
+
route("POST", "/api/v1/connect/import", async (ctx) => {
|
|
187
|
+
const body = parse(ImportBody, ctx.body);
|
|
188
|
+
const cwd = projectDirOf(body.projectDir);
|
|
189
|
+
const { target, entry, server, configPath, entryName, home } = connectedToolbox(options, body.scope, cwd);
|
|
190
|
+
let candidates;
|
|
191
|
+
try {
|
|
192
|
+
({ candidates } = importCandidates({ scope: body.scope, cwd, home, gatewayConfigPath: configPath, entryName, secrets: new SecretStore() }));
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
asHttp(err);
|
|
196
|
+
}
|
|
197
|
+
/* what was asked for, each checked against what the app has now */
|
|
198
|
+
const picked = [];
|
|
199
|
+
const pick = (key, source) => {
|
|
200
|
+
const c = candidates.find((x) => x.source === source && x.key === key);
|
|
201
|
+
if (!c) {
|
|
202
|
+
throw unprocessable(`"${key}" isn't in ${LABELS[body.scope]} any more. Check again.`);
|
|
203
|
+
}
|
|
204
|
+
if (!c.importable)
|
|
205
|
+
throw unprocessable(`"${c.name}" can't be brought in: ${c.reason ?? "it isn't supported"}`);
|
|
206
|
+
if (!picked.includes(c))
|
|
207
|
+
picked.push(c);
|
|
208
|
+
};
|
|
209
|
+
for (const name of body.names)
|
|
210
|
+
pick(name, "config");
|
|
211
|
+
for (const id of body.extensions)
|
|
212
|
+
pick(id, "extension");
|
|
213
|
+
if (picked.length === 0)
|
|
214
|
+
throw unprocessable("Choose at least one server to bring in.");
|
|
215
|
+
const values = picked.flatMap(valuesOf);
|
|
216
|
+
// Already in the toolbox: nothing to add or test, only the app's copy to take out.
|
|
217
|
+
const toAdd = picked.filter((c) => c.inToolbox === undefined);
|
|
218
|
+
const real = new SecretStore();
|
|
219
|
+
let prepared;
|
|
220
|
+
try {
|
|
221
|
+
const taken = new Map();
|
|
222
|
+
prepared = toAdd.map((c) => {
|
|
223
|
+
const { plan, locks } = planImportSecrets(c.plan, real, taken);
|
|
224
|
+
return { c, upstream: plan.upstreams[0].upstream, locks };
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
asHttp(err, values);
|
|
229
|
+
}
|
|
230
|
+
const secrets = [...values, ...prepared.flatMap((p) => p.locks.map((l) => l.value))];
|
|
231
|
+
/* everything this would loosen, confirmed before anything starts */
|
|
232
|
+
const gatewayFile = readGatewayFile(configPath);
|
|
233
|
+
const policyPath = server.policyFile !== null && server.gateway.config.policy_writes ? server.policyFile : null;
|
|
234
|
+
const policyBefore = policyPath ? readFileSync(policyPath, "utf8") : "";
|
|
235
|
+
const changesFor = (list) => list.flatMap((p) => egressChangesFor(p.upstream, { localNetwork: p.c.needsLocalHttp }));
|
|
236
|
+
const all = changesFor(prepared);
|
|
237
|
+
let preview = unchangedBatch(policyBefore);
|
|
238
|
+
if (policyPath) {
|
|
239
|
+
preview = applyPolicyChanges(policyBefore, all, policyPath);
|
|
240
|
+
refuseIfOverridesOff(gatewayFile.config, preview.loosens);
|
|
241
|
+
}
|
|
242
|
+
else if (all.length > 0 && applyPolicyChanges(stringify(server.policy), all).changed) {
|
|
243
|
+
throw unprocessable("This toolbox's rules can't be changed from the console, and these servers need its network rules changed. " +
|
|
244
|
+
"Change them by hand, or bring the servers into another toolbox.");
|
|
245
|
+
}
|
|
246
|
+
const loosens = [
|
|
247
|
+
...gatewayLoosens(gatewayFile.config, parseGatewayText(withUpstreams(gatewayFile.text, prepared.map((p) => p.upstream)))),
|
|
248
|
+
...preview.loosens
|
|
249
|
+
];
|
|
250
|
+
if (loosens.length > 0 && body.acknowledged?.loosens !== true) {
|
|
251
|
+
throw unprocessable(`bringing these servers in lets more through and needs confirming: ${loosens.join("; ")}`, {
|
|
252
|
+
needs: "loosens",
|
|
253
|
+
loosens
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
/* test each one, as Test it does: scratch keys, scratch policy */
|
|
257
|
+
const passed = [];
|
|
258
|
+
const failures = [];
|
|
259
|
+
for (const p of prepared) {
|
|
260
|
+
const outcome = await withProbeSlot(async () => {
|
|
261
|
+
const materialized = {
|
|
262
|
+
upstream: p.upstream,
|
|
263
|
+
secretsToCreate: p.locks.map((l) => ({ ...l })),
|
|
264
|
+
secretsReferenced: [],
|
|
265
|
+
egressHosts: [],
|
|
266
|
+
localNetwork: p.c.needsLocalHttp,
|
|
267
|
+
problems: {}
|
|
268
|
+
};
|
|
269
|
+
const scratch = scratchSecretStore(materialized, real);
|
|
270
|
+
try {
|
|
271
|
+
return await runProbe(p.upstream, {
|
|
272
|
+
policy: scratchPolicy(server.policy, p.upstream, p.c.needsLocalHttp),
|
|
273
|
+
secrets: scratch.store,
|
|
274
|
+
cwd: server.cwd
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
finally {
|
|
278
|
+
scratch.dispose();
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
if (outcome.ok)
|
|
282
|
+
passed.push({ ...p, tools: outcome.tools.length });
|
|
283
|
+
else {
|
|
284
|
+
failures.push({
|
|
285
|
+
name: p.c.name,
|
|
286
|
+
source: p.c.source,
|
|
287
|
+
code: outcome.problem?.code ?? "unknown",
|
|
288
|
+
message: scrubbed(outcome.problem?.message ?? "It didn't answer.", secrets)
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const takeOut = picked.filter((c) => c.inToolbox !== undefined);
|
|
293
|
+
const extensionsToSwitchOff = [...passed.map((p) => p.c), ...takeOut]
|
|
294
|
+
.filter((c) => c.source === "extension")
|
|
295
|
+
.map((c) => ({ id: c.key, name: c.name, enabled: c.enabled ?? true }));
|
|
296
|
+
const restartHint = restartHintFor(target, process.platform);
|
|
297
|
+
const otherApps = otherAppsUsing(configPath, target, cwd, home);
|
|
298
|
+
const leaving = [...passed.map((p) => p.c), ...takeOut].filter((c) => c.source === "config");
|
|
299
|
+
if (passed.length === 0 && leaving.length === 0) {
|
|
300
|
+
return { imported: [], takenOut: [], failures, restartHint, extensionsToSwitchOff, otherApps, warning: null };
|
|
301
|
+
}
|
|
302
|
+
/* keys first: the servers refer to them */
|
|
303
|
+
const created = [];
|
|
304
|
+
const rollbackKeys = () => {
|
|
305
|
+
for (const name of created) {
|
|
306
|
+
try {
|
|
307
|
+
real.delete(name);
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
/* best effort; the rollback must reach the files too */
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
const createdFor = new Map();
|
|
315
|
+
let policyWritten = false;
|
|
316
|
+
let gatewayWritten = false;
|
|
317
|
+
try {
|
|
318
|
+
for (const p of passed) {
|
|
319
|
+
const mine = [];
|
|
320
|
+
for (const lock of p.locks) {
|
|
321
|
+
const saved = real.get(lock.name);
|
|
322
|
+
if (saved) {
|
|
323
|
+
if (saved.kind === "value" && saved.value === lock.value)
|
|
324
|
+
continue;
|
|
325
|
+
throw conflict(`A locked key called "${lock.name}" was saved meanwhile, so nothing was changed. Check again.`);
|
|
326
|
+
}
|
|
327
|
+
const stamp = new Date().toISOString();
|
|
328
|
+
real.set(lock.name, { kind: "value", value: lock.value, label: lock.label, created_at: stamp, updated_at: stamp });
|
|
329
|
+
created.push(lock.name);
|
|
330
|
+
mine.push(lock.name);
|
|
331
|
+
}
|
|
332
|
+
createdFor.set(p.c.key, mine);
|
|
333
|
+
}
|
|
334
|
+
/* then the policy, then gateway.yaml: the servers never run without their network rules */
|
|
335
|
+
const batch = policyPath && passed.length > 0 ? applyPolicyChanges(policyBefore, changesFor(passed), policyPath) : unchangedBatch(policyBefore);
|
|
336
|
+
if (batch.changed) {
|
|
337
|
+
if (readFileSync(policyPath, "utf8") !== policyBefore) {
|
|
338
|
+
throw conflict("This toolbox's protection settings changed while the servers were being tested, so nothing was changed. Check again.");
|
|
339
|
+
}
|
|
340
|
+
writeAtomically(policyPath, batch.text);
|
|
341
|
+
policyWritten = true;
|
|
342
|
+
}
|
|
343
|
+
if (passed.length > 0) {
|
|
344
|
+
// Read again: a gateway.yaml changed while the servers were tested is not written over.
|
|
345
|
+
const fresh = readGatewayFile(configPath);
|
|
346
|
+
const adding = passed.map((p) => p.upstream);
|
|
347
|
+
commitGatewayText({
|
|
348
|
+
file: fresh,
|
|
349
|
+
text: withUpstreams(fresh.text, adding),
|
|
350
|
+
expectedDigest: gatewayFile.digest,
|
|
351
|
+
acknowledgedLoosens: true,
|
|
352
|
+
intended: (before, after) => sameExcept(before, after, ["upstreams"]) &&
|
|
353
|
+
after.upstreams.length === before.upstreams.length + adding.length &&
|
|
354
|
+
before.upstreams.every((u, i) => JSON.stringify(u) === JSON.stringify(after.upstreams[i])) &&
|
|
355
|
+
adding.every((u, i) => after.upstreams[before.upstreams.length + i]?.name === u.name)
|
|
356
|
+
? null
|
|
357
|
+
: "bringing the servers in would have changed something else too"
|
|
358
|
+
});
|
|
359
|
+
gatewayWritten = true;
|
|
360
|
+
}
|
|
361
|
+
/* the app's settings last */
|
|
362
|
+
if (leaving.length > 0)
|
|
363
|
+
moveOutOfClient({ scope: body.scope, cwd, home }, Object.fromEntries(leaving.map((c) => [c.key, c.entry])));
|
|
364
|
+
}
|
|
365
|
+
catch (err) {
|
|
366
|
+
const problems = rollBack([
|
|
367
|
+
["gateway.yaml", () => gatewayWritten && writeAtomically(configPath, gatewayFile.text)],
|
|
368
|
+
["the protection settings", () => policyWritten && writeAtomically(policyPath, policyBefore)],
|
|
369
|
+
["the locked keys", rollbackKeys]
|
|
370
|
+
], secrets);
|
|
371
|
+
// The refusal itself is what is reported; anything that could not be undone is added to it.
|
|
372
|
+
if (problems.length === 0)
|
|
373
|
+
asHttp(err, secrets);
|
|
374
|
+
try {
|
|
375
|
+
asHttp(err, secrets);
|
|
376
|
+
}
|
|
377
|
+
catch (refusal) {
|
|
378
|
+
if (refusal instanceof HttpError) {
|
|
379
|
+
throw new HttpError(refusal.status, refusal.code, `${refusal.message} Also: ${problems.join("; ")}.`, refusal.detail);
|
|
380
|
+
}
|
|
381
|
+
throw refusal;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/* what Undo needs: names only */
|
|
385
|
+
const items = [
|
|
386
|
+
...passed.map((p) => ({
|
|
387
|
+
key: p.c.key,
|
|
388
|
+
name: p.c.name,
|
|
389
|
+
source: p.c.source,
|
|
390
|
+
upstream: p.upstream.name,
|
|
391
|
+
added: true,
|
|
392
|
+
keys_created: createdFor.get(p.c.key) ?? [],
|
|
393
|
+
digest: upstreamDigest(p.upstream)
|
|
394
|
+
})),
|
|
395
|
+
...takeOut.map((c) => ({ key: c.key, name: c.name, source: c.source, upstream: c.inToolbox, added: false, keys_created: [] }))
|
|
396
|
+
];
|
|
397
|
+
const warnings = [];
|
|
398
|
+
/*
|
|
399
|
+
* gateway.yaml is the person's own file and keeps the mode they gave it.
|
|
400
|
+
* Its keys are locked, so it holds none; but it names them and holds the
|
|
401
|
+
* servers' plain settings, so a copy others can read is pointed out.
|
|
402
|
+
*/
|
|
403
|
+
try {
|
|
404
|
+
if (passed.length > 0 && statSync(configPath).mode & 0o077) {
|
|
405
|
+
warnings.push(`Your toolbox's settings file can be read by other users of this computer; your keys are locked, but consider making it private: chmod 600 ${configPath}`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
catch {
|
|
409
|
+
/* no modes to speak of (Windows) */
|
|
410
|
+
}
|
|
411
|
+
try {
|
|
412
|
+
const before = readLiveImportRecord(options.registryPath, target);
|
|
413
|
+
const kept = before && before.gateway_id === entry.id ? before.items.filter((i) => !items.some((n) => n.key === i.key && n.source === i.source)) : [];
|
|
414
|
+
writeImportRecord(options.registryPath, target, {
|
|
415
|
+
version: 1,
|
|
416
|
+
scope: body.scope,
|
|
417
|
+
config_path: target.path,
|
|
418
|
+
where: target.where,
|
|
419
|
+
gateway_id: entry.id,
|
|
420
|
+
created_at: before?.created_at ?? new Date().toISOString(),
|
|
421
|
+
items: [...kept, ...items]
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
catch (err) {
|
|
425
|
+
warnings.push(`The servers were brought in, but the note Undo needs could not be saved (${err.message}). ` +
|
|
426
|
+
`Undo connection still gives the app its servers back.`);
|
|
427
|
+
}
|
|
428
|
+
const imported = passed.map((p) => ({ name: p.c.name, source: p.c.source, upstream: p.upstream.name, tools: p.tools, keysLocked: [...p.c.keySettings] }));
|
|
429
|
+
const takenOut = takeOut.map((c) => ({ name: c.name, source: c.source, upstream: c.inToolbox }));
|
|
430
|
+
const audit = record(gatewayAudit(configPath, ctx.actor), {
|
|
431
|
+
tool: "(connect)",
|
|
432
|
+
effect: null,
|
|
433
|
+
decision: "allow",
|
|
434
|
+
rule_id: "connect.import",
|
|
435
|
+
reason: `${imported.length} server(s) brought into this gateway from ${LABELS[body.scope]} via the console by ${ctx.actor}` +
|
|
436
|
+
(leaving.length > 0 ? `; ${leaving.length} taken out of ${target.path}` : "") +
|
|
437
|
+
(failures.length > 0 ? `; ${failures.length} left in the app because they did not connect` : ""),
|
|
438
|
+
outcome: "completed",
|
|
439
|
+
args_redacted: {
|
|
440
|
+
scope: body.scope,
|
|
441
|
+
client_config: target.path,
|
|
442
|
+
imported: imported.map((i) => ({ name: i.name, source: i.source, upstream: i.upstream })),
|
|
443
|
+
taken_out: leaving.map((c) => c.key),
|
|
444
|
+
secrets_created: created,
|
|
445
|
+
failed: failures.map((f) => f.name),
|
|
446
|
+
loosens,
|
|
447
|
+
registry_id: entry.id
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
if (audit)
|
|
451
|
+
warnings.push(audit);
|
|
452
|
+
return { imported, takenOut, failures, restartHint, extensionsToSwitchOff, otherApps, warning: warnings.length > 0 ? warnings.join(" ") : null };
|
|
453
|
+
}),
|
|
454
|
+
/**
|
|
455
|
+
* Undo "Bring in servers": the app gets back the servers it gave up, and
|
|
456
|
+
* the toolbox loses the ones the import added (with their ready-made
|
|
457
|
+
* rules, and keys the import made that nothing else uses). Servers the
|
|
458
|
+
* toolbox already had are left in it.
|
|
459
|
+
*
|
|
460
|
+
* The app's file is written first and the toolbox after, the reverse of
|
|
461
|
+
* the import, for the same reason: a failure half-way leaves a server in
|
|
462
|
+
* both, which is harmless, never in neither.
|
|
463
|
+
*/
|
|
464
|
+
route("POST", "/api/v1/connect/import/undo", async (ctx) => {
|
|
465
|
+
const body = parse(UndoBody, ctx.body);
|
|
466
|
+
const cwd = projectDirOf(body.projectDir);
|
|
467
|
+
const { target, entry, server, configPath, home } = connectedToolbox(options, body.scope, cwd);
|
|
468
|
+
/*
|
|
469
|
+
* As it still stands: a server the app's own undo record no longer
|
|
470
|
+
* holds was given back already (an Undo that then failed on the
|
|
471
|
+
* toolbox, or `adopt --revert` at a terminal), and isn't asked for twice.
|
|
472
|
+
*/
|
|
473
|
+
const rec = readLiveImportRecord(options.registryPath, target);
|
|
474
|
+
if (!rec || rec.items.length === 0 || rec.gateway_id !== entry.id) {
|
|
475
|
+
throw unprocessable(`There is nothing to undo: no servers were brought in from ${LABELS[body.scope]} here.`);
|
|
476
|
+
}
|
|
477
|
+
// Back in the app already (an Undo that failed half-way): only the toolbox's copy and keys are left to remove.
|
|
478
|
+
const fromApp = rec.items.filter((i) => i.source === "config" && !i.back_in_app).map((i) => i.key);
|
|
479
|
+
const added = rec.items.filter((i) => i.added);
|
|
480
|
+
/*
|
|
481
|
+
* Checked before anything is written. A server is taken out only while
|
|
482
|
+
* it still runs what the import added: one set up again by hand under
|
|
483
|
+
* the same name is the person's now, and stays, with a word about it.
|
|
484
|
+
*/
|
|
485
|
+
const file = readGatewayFile(configPath);
|
|
486
|
+
const removing = [];
|
|
487
|
+
const keptInToolbox = [];
|
|
488
|
+
for (const item of added) {
|
|
489
|
+
const u = file.config.upstreams.find((x) => x.name === item.upstream);
|
|
490
|
+
if (!u)
|
|
491
|
+
continue;
|
|
492
|
+
if (item.digest !== undefined && upstreamDigest(u) === item.digest)
|
|
493
|
+
removing.push(u.name);
|
|
494
|
+
else
|
|
495
|
+
keptInToolbox.push(u.name);
|
|
496
|
+
}
|
|
497
|
+
if (removing.length > 0 && removing.length >= file.config.upstreams.length) {
|
|
498
|
+
throw unprocessable("Taking these servers out would leave the toolbox with none, and a toolbox needs at least one. Add another server to it first, or undo the whole connection.");
|
|
499
|
+
}
|
|
500
|
+
let put;
|
|
501
|
+
try {
|
|
502
|
+
put = putBackInClient({ scope: body.scope, cwd, home }, fromApp, { where: rec.where ?? target.where });
|
|
503
|
+
}
|
|
504
|
+
catch (err) {
|
|
505
|
+
asHttp(err);
|
|
506
|
+
}
|
|
507
|
+
const notes = [];
|
|
508
|
+
if (keptInToolbox.length > 0) {
|
|
509
|
+
notes.push(`${keptInToolbox.map((n) => `“${n}”`).join(", ")} ${keptInToolbox.length === 1 ? "was" : "were"} changed in your toolbox since it was brought in, ` +
|
|
510
|
+
`so ${keptInToolbox.length === 1 ? "it stays" : "they stay"} there. Remove ${keptInToolbox.length === 1 ? "it" : "them"} from the toolbox's page if you don't want ${keptInToolbox.length === 1 ? "it" : "them"}.`);
|
|
511
|
+
}
|
|
512
|
+
const removedRules = [];
|
|
513
|
+
if (removing.length > 0) {
|
|
514
|
+
const doc = parseDocument(file.text);
|
|
515
|
+
for (const name of removing) {
|
|
516
|
+
const at = doc.toJS().upstreams.findIndex((u) => u.name === name);
|
|
517
|
+
if (at >= 0)
|
|
518
|
+
doc.deleteIn(["upstreams", at]);
|
|
519
|
+
}
|
|
520
|
+
try {
|
|
521
|
+
commitGatewayText({
|
|
522
|
+
file,
|
|
523
|
+
text: doc.toString(),
|
|
524
|
+
expectedDigest: file.digest,
|
|
525
|
+
acknowledgedLoosens: false,
|
|
526
|
+
intended: (before, after) => sameExcept(before, after, ["upstreams"]) &&
|
|
527
|
+
JSON.stringify(before.upstreams.filter((u) => !removing.includes(u.name))) === JSON.stringify(after.upstreams)
|
|
528
|
+
? null
|
|
529
|
+
: "taking the servers out would have changed something else too"
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
catch (err) {
|
|
533
|
+
const why = err instanceof Error ? err.message : String(err);
|
|
534
|
+
throw unprocessable(`${LABELS[body.scope]} has its servers back, but they could not be taken out of the toolbox (${why}), so they are in both for now. ` +
|
|
535
|
+
`Remove them from the toolbox's page, or try Undo again.`);
|
|
536
|
+
}
|
|
537
|
+
for (const name of removing) {
|
|
538
|
+
const cleanup = removeServerRules(server, name);
|
|
539
|
+
removedRules.push(...cleanup.removed);
|
|
540
|
+
if (cleanup.note)
|
|
541
|
+
notes.push(cleanup.note);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
/* keys the import made, if nothing uses them now */
|
|
545
|
+
const usage = secretUsage(options);
|
|
546
|
+
const keysDeleted = [];
|
|
547
|
+
const keysKept = [];
|
|
548
|
+
const store = new SecretStore();
|
|
549
|
+
for (const name of rec.items.filter((i) => !keptInToolbox.includes(i.upstream)).flatMap((i) => i.keys_created)) {
|
|
550
|
+
if ((usage.get(name) ?? []).length > 0) {
|
|
551
|
+
keysKept.push(name);
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
try {
|
|
555
|
+
if (store.delete(name))
|
|
556
|
+
keysDeleted.push(name);
|
|
557
|
+
}
|
|
558
|
+
catch {
|
|
559
|
+
keysKept.push(name);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
deleteImportRecord(options.registryPath, target);
|
|
563
|
+
const warning = record(gatewayAudit(configPath, ctx.actor), {
|
|
564
|
+
tool: "(connect)",
|
|
565
|
+
effect: null,
|
|
566
|
+
decision: "allow",
|
|
567
|
+
rule_id: "connect.import.undo",
|
|
568
|
+
reason: `bringing servers in from ${LABELS[body.scope]} undone via the console by ${ctx.actor}: ${put.restored.length} put back in ${target.path}, ${removing.length} removed from this gateway`,
|
|
569
|
+
outcome: "completed",
|
|
570
|
+
args_redacted: {
|
|
571
|
+
scope: body.scope,
|
|
572
|
+
client_config: target.path,
|
|
573
|
+
restored: put.restored,
|
|
574
|
+
removed: removing,
|
|
575
|
+
rules_removed: removedRules,
|
|
576
|
+
secrets_deleted: keysDeleted,
|
|
577
|
+
registry_id: entry.id
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
return {
|
|
581
|
+
restored: put.restored,
|
|
582
|
+
missing: put.missing,
|
|
583
|
+
removed: removing,
|
|
584
|
+
keptInToolbox,
|
|
585
|
+
extensions: rec.items.filter((i) => i.source === "extension").map((i) => ({ id: i.key, name: i.name })),
|
|
586
|
+
keysDeleted,
|
|
587
|
+
keysKept,
|
|
588
|
+
restartHint: restartHintFor(target, process.platform),
|
|
589
|
+
note: notes.length > 0 ? notes.join(" ") : null,
|
|
590
|
+
warning
|
|
591
|
+
};
|
|
592
|
+
})
|
|
593
|
+
];
|
|
594
|
+
}
|