hmcp-web 0.2.1 → 0.2.3

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.
Files changed (63) hide show
  1. package/dist/api.d.ts +6 -0
  2. package/dist/api.js +36 -8
  3. package/dist/model/app-connect-note.d.ts +114 -0
  4. package/dist/model/app-connect-note.js +199 -0
  5. package/dist/model/app-servers.d.ts +24 -1
  6. package/dist/model/app-servers.js +54 -6
  7. package/dist/model/apps.d.ts +24 -0
  8. package/dist/model/apps.js +18 -0
  9. package/dist/model/bring-in.d.ts +185 -0
  10. package/dist/model/bring-in.js +755 -0
  11. package/dist/model/console-settings.d.ts +2 -2
  12. package/dist/model/import-record.d.ts +4 -0
  13. package/dist/model/import-record.js +22 -1
  14. package/dist/model/new-toolbox.d.ts +84 -0
  15. package/dist/model/new-toolbox.js +209 -0
  16. package/dist/model/protection.d.ts +21 -1
  17. package/dist/model/protection.js +68 -9
  18. package/dist/model/provisional-tools.d.ts +56 -0
  19. package/dist/model/provisional-tools.js +145 -0
  20. package/dist/model/server-names.d.ts +25 -0
  21. package/dist/model/server-names.js +158 -0
  22. package/dist/model/toolbox-label.d.ts +22 -0
  23. package/dist/model/toolbox-label.js +42 -0
  24. package/dist/model/tools.d.ts +20 -5
  25. package/dist/model/tools.js +22 -11
  26. package/dist/routes/connect-app.d.ts +54 -0
  27. package/dist/routes/connect-app.js +1018 -0
  28. package/dist/routes/connect-import.d.ts +21 -6
  29. package/dist/routes/connect-import.js +162 -546
  30. package/dist/routes/connect.d.ts +11 -0
  31. package/dist/routes/connect.js +28 -116
  32. package/dist/routes/github.js +2 -1
  33. package/dist/routes/guard.js +4 -0
  34. package/dist/routes/runtime.js +21 -22
  35. package/dist/routes/servers-add.d.ts +1 -0
  36. package/dist/routes/servers-add.js +6 -5
  37. package/dist-ui/assets/Activity-BSf4lBm-.js +1 -0
  38. package/dist-ui/assets/Approvals-CDz3zYpl.js +1 -0
  39. package/dist-ui/assets/AttachApp-COr1547c.js +5 -0
  40. package/dist-ui/assets/Connections-ClW5R6ea.js +2 -0
  41. package/dist-ui/assets/{Gallery-DB_OO7Vw.js → Gallery-0iiv1H9e.js} +3 -3
  42. package/dist-ui/assets/{PreApprovals-CXcU-_ug.js → PreApprovals-DYDKgSpr.js} +1 -1
  43. package/dist-ui/assets/Protection-DMtABpM7.js +1 -0
  44. package/dist-ui/assets/Safety-BLTF2fqV.js +1 -0
  45. package/dist-ui/assets/{Settings-XjNZ-wo-.js → Settings-DZ4P3Us6.js} +1 -1
  46. package/dist-ui/assets/StartPage-Bke6mrv5.js +1 -0
  47. package/dist-ui/assets/{Suggestions-HZyd0jDU.js → Suggestions-kAWUILyw.js} +1 -1
  48. package/dist-ui/assets/Tools-BdXSeKeL.js +4 -0
  49. package/dist-ui/assets/connect-app-words-CT8Fytzv.js +1 -0
  50. package/dist-ui/assets/index-Cm4wG2zz.js +16 -0
  51. package/dist-ui/assets/{kit-DRVm92_t.js → kit-BHB_ha4i.js} +1 -1
  52. package/dist-ui/assets/server-name-D9u6r07i.js +1 -0
  53. package/dist-ui/index.html +3 -2
  54. package/package.json +4 -4
  55. package/dist-ui/assets/Activity-Dgo5oK2r.js +0 -1
  56. package/dist-ui/assets/Approvals-C5_8rBkL.js +0 -1
  57. package/dist-ui/assets/AttachApp-BRW1mJ7X.js +0 -5
  58. package/dist-ui/assets/Connections-BHsXRdYI.js +0 -2
  59. package/dist-ui/assets/Protection-BF5OlzGC.js +0 -1
  60. package/dist-ui/assets/Safety-DVb8sdbt.js +0 -1
  61. package/dist-ui/assets/StartPage-D8WBBhDy.js +0 -1
  62. package/dist-ui/assets/Tools-GMaKxxIG.js +0 -4
  63. package/dist-ui/assets/index-DbHZ_SUd.js +0 -16
@@ -1,38 +1,20 @@
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";
1
+ import { parseDocument } from "yaml";
5
2
  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";
3
+ import { SecretStore } from "hmcp-core";
4
+ import { putBackInClient, restartHintFor } from "hmcp-gateway";
5
+ import { route, unprocessable } from "../http.js";
6
+ import { commitGatewayText, readGatewayFile, sameExcept } from "../model/gateway-config.js";
12
7
  import { deleteImportRecord, readLiveImportRecord, upstreamDigest, writeImportRecord } from "../model/import-record.js";
13
- import { targetFor } from "../model/app-servers.js";
8
+ import { adoptToolboxId, asHttp, bringIn, connectedToolbox } from "../model/bring-in.js";
14
9
  import { LABELS, ScopeSchema, gatewayAudit, parse, projectDirOf, record } from "./connect.js";
15
10
  import { removeServerRules } from "./runtime.js";
16
- import { secretUsage, upstreamYaml } from "./servers-add.js";
11
+ import { secretUsage } from "./servers-add.js";
12
+ export { rollBack } from "../model/bring-in.js";
17
13
  /**
18
14
  * "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.
15
+ * toolbox it is connected to, so every call they make is checked. The work
16
+ * is `bringIn`'s (model/bring-in.ts), which says how; this is its door from
17
+ * the console, and the door for its Undo.
36
18
  */
37
19
  const ImportBody = z
38
20
  .object({
@@ -53,403 +35,24 @@ const UndoBody = z
53
35
  confirm: z.literal(true)
54
36
  })
55
37
  .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
38
  export function connectImportRoutes(options) {
185
39
  return [
186
40
  route("POST", "/api/v1/connect/import", async (ctx) => {
187
41
  const body = parse(ImportBody, ctx.body);
188
42
  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
- }
43
+ const toolbox = connectedToolbox(options, body.scope, cwd);
44
+ adoptToolboxId(options.registryPath, toolbox);
45
+ const { toolbox: _toolbox, held: _held, probed: _probed, made: _made, ...result } = await bringIn({
46
+ options,
47
+ scope: body.scope,
48
+ cwd,
49
+ names: body.names,
50
+ extensions: body.extensions,
51
+ acknowledged: body.acknowledged,
52
+ toolbox,
53
+ actor: ctx.actor
449
54
  });
450
- if (audit)
451
- warnings.push(audit);
452
- return { imported, takenOut, failures, restartHint, extensionsToSwitchOff, otherApps, warning: warnings.length > 0 ? warnings.join(" ") : null };
55
+ return result;
453
56
  }),
454
57
  /**
455
58
  * Undo "Bring in servers": the app gets back the servers it gave up, and
@@ -463,132 +66,145 @@ export function connectImportRoutes(options) {
463
66
  */
464
67
  route("POST", "/api/v1/connect/import/undo", async (ctx) => {
465
68
  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
- };
69
+ return undoImport(options, body.scope, projectDirOf(body.projectDir), ctx.actor);
592
70
  })
593
71
  ];
594
72
  }
73
+ /** Undo "Bring in servers" for one app, as `/connect/import/undo` does it; also one-click connect's Undo. */
74
+ export async function undoImport(options, scope, cwd, actor,
75
+ /** Only these of the record's items (one-click Undo's own); the rest stay in the record. Default: all. */
76
+ only) {
77
+ const connected = connectedToolbox(options, scope, cwd);
78
+ adoptToolboxId(options.registryPath, connected);
79
+ const { target, entry, server, configPath, home } = connected;
80
+ /*
81
+ * As it still stands: a server the app's own undo record no longer
82
+ * holds was given back already (an Undo that then failed on the
83
+ * toolbox, or `adopt --revert` at a terminal), and isn't asked for twice.
84
+ */
85
+ const rec = readLiveImportRecord(options.registryPath, target);
86
+ const mine = rec && rec.gateway_id === entry.id ? (only ? rec.items.filter(only) : rec.items) : [];
87
+ if (!rec || mine.length === 0) {
88
+ throw unprocessable(`There is nothing to undo: no servers were brought in from ${LABELS[scope]} here.`);
89
+ }
90
+ // Back in the app already (an Undo that failed half-way): only the toolbox's copy and keys are left to remove.
91
+ const fromApp = mine.filter((i) => i.source === "config" && !i.back_in_app).map((i) => i.key);
92
+ const added = mine.filter((i) => i.added);
93
+ /*
94
+ * Checked before anything is written. A server is taken out only while
95
+ * it still runs what the import added: one set up again by hand under
96
+ * the same name is the person's now, and stays, with a word about it.
97
+ */
98
+ const file = readGatewayFile(configPath);
99
+ const removing = [];
100
+ const keptInToolbox = [];
101
+ for (const item of added) {
102
+ const u = file.config.upstreams.find((x) => x.name === item.upstream);
103
+ if (!u)
104
+ continue;
105
+ if (item.digest !== undefined && upstreamDigest(u) === item.digest)
106
+ removing.push(u.name);
107
+ else
108
+ keptInToolbox.push(u.name);
109
+ }
110
+ if (removing.length > 0 && removing.length >= file.config.upstreams.length) {
111
+ 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.");
112
+ }
113
+ let put;
114
+ try {
115
+ put = putBackInClient({ scope: scope, cwd, home }, fromApp, { where: rec.where ?? target.where });
116
+ }
117
+ catch (err) {
118
+ asHttp(err);
119
+ }
120
+ const notes = [];
121
+ if (keptInToolbox.length > 0) {
122
+ notes.push(`${keptInToolbox.map((n) => `“${n}”`).join(", ")} ${keptInToolbox.length === 1 ? "was" : "were"} changed in your toolbox since it was brought in, ` +
123
+ `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"}.`);
124
+ }
125
+ const removedRules = [];
126
+ if (removing.length > 0) {
127
+ const doc = parseDocument(file.text);
128
+ for (const name of removing) {
129
+ const at = doc.toJS().upstreams.findIndex((u) => u.name === name);
130
+ if (at >= 0)
131
+ doc.deleteIn(["upstreams", at]);
132
+ }
133
+ try {
134
+ commitGatewayText({
135
+ file,
136
+ text: doc.toString(),
137
+ expectedDigest: file.digest,
138
+ acknowledgedLoosens: false,
139
+ intended: (before, after) => sameExcept(before, after, ["upstreams"]) &&
140
+ JSON.stringify(before.upstreams.filter((u) => !removing.includes(u.name))) === JSON.stringify(after.upstreams)
141
+ ? null
142
+ : "taking the servers out would have changed something else too"
143
+ });
144
+ }
145
+ catch (err) {
146
+ const why = err instanceof Error ? err.message : String(err);
147
+ throw unprocessable(`${LABELS[scope]} has its servers back, but they could not be taken out of the toolbox (${why}), so they are in both for now. ` +
148
+ `Remove them from the toolbox's page, or try Undo again.`);
149
+ }
150
+ for (const name of removing) {
151
+ const cleanup = removeServerRules(server, name);
152
+ removedRules.push(...cleanup.removed);
153
+ if (cleanup.note)
154
+ notes.push(cleanup.note);
155
+ }
156
+ }
157
+ /* keys the import made, if nothing uses them now */
158
+ const usage = secretUsage(options);
159
+ const keysDeleted = [];
160
+ const keysKept = [];
161
+ const store = new SecretStore();
162
+ for (const name of mine.filter((i) => !keptInToolbox.includes(i.upstream)).flatMap((i) => i.keys_created)) {
163
+ if ((usage.get(name) ?? []).length > 0) {
164
+ keysKept.push(name);
165
+ continue;
166
+ }
167
+ try {
168
+ if (store.delete(name))
169
+ keysDeleted.push(name);
170
+ }
171
+ catch {
172
+ keysKept.push(name);
173
+ }
174
+ }
175
+ // Items this Undo was not asked about stay, so their own Undo still works.
176
+ const rest = rec.items.filter((i) => !mine.includes(i));
177
+ if (rest.length > 0)
178
+ writeImportRecord(options.registryPath, target, { ...rec, items: rest });
179
+ else
180
+ deleteImportRecord(options.registryPath, target);
181
+ const warning = record(gatewayAudit(configPath, actor), {
182
+ tool: "(connect)",
183
+ effect: null,
184
+ decision: "allow",
185
+ rule_id: "connect.import.undo",
186
+ reason: `bringing servers in from ${LABELS[scope]} undone via the console by ${actor}: ${put.restored.length} put back in ${target.path}, ${removing.length} removed from this gateway`,
187
+ outcome: "completed",
188
+ args_redacted: {
189
+ scope: scope,
190
+ client_config: target.path,
191
+ restored: put.restored,
192
+ removed: removing,
193
+ rules_removed: removedRules,
194
+ secrets_deleted: keysDeleted,
195
+ registry_id: entry.id
196
+ }
197
+ });
198
+ return {
199
+ restored: put.restored,
200
+ missing: put.missing,
201
+ removed: removing,
202
+ keptInToolbox,
203
+ extensions: mine.filter((i) => i.source === "extension").map((i) => ({ id: i.key, name: i.name })),
204
+ keysDeleted,
205
+ keysKept,
206
+ restartHint: restartHintFor(target, process.platform),
207
+ note: notes.length > 0 ? notes.join(" ") : null,
208
+ warning
209
+ };
210
+ }