hmcp-web 0.2.2 → 0.2.4

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 +15 -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 +756 -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 +4 -1
  17. package/dist/model/protection.js +12 -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 +1049 -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 +30 -0
  31. package/dist/routes/connect.js +74 -126
  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-CQw7bFh4.js +1 -0
  38. package/dist-ui/assets/Approvals-_rFRWRyy.js +1 -0
  39. package/dist-ui/assets/AttachApp-eNBD48eb.js +5 -0
  40. package/dist-ui/assets/Connections-_AV8r8_W.js +2 -0
  41. package/dist-ui/assets/{Gallery-DB_OO7Vw.js → Gallery-0iiv1H9e.js} +3 -3
  42. package/dist-ui/assets/{PreApprovals-C-2ZGYfc.js → PreApprovals-Bwrhm8hr.js} +1 -1
  43. package/dist-ui/assets/Protection-CM1fEDmQ.js +1 -0
  44. package/dist-ui/assets/Safety-BbtS6-Sw.js +1 -0
  45. package/dist-ui/assets/{Settings-CSyTOe8X.js → Settings-BjarVZaa.js} +1 -1
  46. package/dist-ui/assets/StartPage-CUFNfiyY.js +1 -0
  47. package/dist-ui/assets/{Suggestions-CaQ_ifWR.js → Suggestions-CfqM3_Ik.js} +1 -1
  48. package/dist-ui/assets/Tools-jM5XlNbn.js +4 -0
  49. package/dist-ui/assets/connect-app-words-Dy16Vpfd.js +1 -0
  50. package/dist-ui/assets/index-DywhXnhV.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-CoVSFaRd.js +0 -1
  56. package/dist-ui/assets/Approvals-BSEDgiNu.js +0 -1
  57. package/dist-ui/assets/AttachApp-Cpm6DOaX.js +0 -5
  58. package/dist-ui/assets/Connections-D5Xd9vH8.js +0 -2
  59. package/dist-ui/assets/Protection-B4Ltb5iP.js +0 -1
  60. package/dist-ui/assets/Safety-CSQhoL9D.js +0 -1
  61. package/dist-ui/assets/StartPage-JBVzYXce.js +0 -1
  62. package/dist-ui/assets/Tools-CDl6irG1.js +0 -4
  63. package/dist-ui/assets/index-CTvq_isK.js +0 -16
@@ -0,0 +1,756 @@
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 { SecretStore, expandPath, parsePolicy, writeAtomically } from "hmcp-core";
6
+ import { ClientConfigError, ImportClientError, adoptRevert, connectClient, importCandidates, isRemote, keyWords, moveOutOfClient, parseServers, planImportSecrets, readBackup, readClientConfig, restartHintFor, runsToolbox, scopeTargets, writeBackup } from "hmcp-gateway";
7
+ import { HttpError, conflict, unprocessable } from "../http.js";
8
+ import { loadServer } from "./server.js";
9
+ import { applyPolicyChanges, commitGatewayText, egressChangesFor, gatewayLoosens, parseGatewayText, readGatewayFile, refuseIfOverridesOff, sameExcept, unchangedBatch } from "./gateway-config.js";
10
+ import { runProbe, scratchPolicy, scratchSecretStore, scrubSecrets, withProbeSlot } from "./probe.js";
11
+ import { readImportRecord, readLiveImportRecord, upstreamDigest, writeImportRecord } from "./import-record.js";
12
+ import { recordedToolbox, targetFor } from "./app-servers.js";
13
+ import { toolboxLabel } from "./toolbox-label.js";
14
+ import { localLoosens, planNewToolbox, removeNewToolbox, writeNewToolbox } from "./new-toolbox.js";
15
+ import { LABELS, gatewayAudit, launchOf, pathDirsFromEnv, record } from "../routes/connect.js";
16
+ import { upstreamYaml } from "../routes/servers-add.js";
17
+ /**
18
+ * The toolbox this app was connected to from the console. An app that is
19
+ * not connected, or was connected with adopt (which already moved its
20
+ * servers in, and owns its files), has nothing to bring servers into.
21
+ */
22
+ export function connectedToolbox(options, scope, cwd) {
23
+ const home = homedir();
24
+ const target = targetFor(scope, cwd, home);
25
+ let backup;
26
+ try {
27
+ backup = readBackup(target);
28
+ }
29
+ catch (err) {
30
+ throw unprocessable(err.message);
31
+ }
32
+ if (!backup || backup.scope !== scope) {
33
+ 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.`);
34
+ }
35
+ if (backup.generated.length > 0 || !backup.registry_id) {
36
+ throw unprocessable(`${LABELS[scope]} was connected the older way, which already moved its servers into its toolbox. ` +
37
+ `Undo that connection and connect it again from here to bring servers in this way.`);
38
+ }
39
+ const entry = recordedToolbox(backup, options.registryPath, { scope, cwd, home });
40
+ if (!entry || entry.kind !== "gateway") {
41
+ throw unprocessable(`Connect the app first: the toolbox ${LABELS[scope]} was connected to is no longer in this console.`);
42
+ }
43
+ const configPath = resolve(expandPath(entry.config_path));
44
+ /*
45
+ * The record is not enough: Claude Code's `local` record is shared by every
46
+ * project, and an entry deleted by hand leaves it behind. Taking servers out
47
+ * of a place that doesn't run the toolbox would leave them nowhere.
48
+ */
49
+ if (!runsToolbox({ scope, cwd, home }, backup.gateway_entry_name, configPath)) {
50
+ 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), ` +
51
+ `so there is nothing to bring its servers into.`);
52
+ }
53
+ let server;
54
+ try {
55
+ server = loadServer(entry);
56
+ }
57
+ catch (err) {
58
+ if (err instanceof HttpError)
59
+ throw err;
60
+ throw unprocessable(`toolbox "${entry.id}" could not be loaded: ${err.message}`);
61
+ }
62
+ return {
63
+ target,
64
+ entry,
65
+ server,
66
+ configPath,
67
+ entryName: backup.gateway_entry_name,
68
+ home,
69
+ ...(entry.id !== backup.registry_id ? { staleId: { id: backup.registry_id, createdAt: backup.created_at } } : {})
70
+ };
71
+ }
72
+ /**
73
+ * Points the app's records at its toolbox's id now, when `connectedToolbox`
74
+ * found the toolbox by what the app runs because the id it was connected
75
+ * under is gone. Called once a request has passed its own checks, so a
76
+ * refused request writes nothing.
77
+ *
78
+ * The import record goes first, then the app's undo record. A step that
79
+ * fails part-way loses nothing: `readLiveImportRecord` keeps a record while
80
+ * either id is one the console doesn't have, and the next call finds the
81
+ * undo record still naming the old id and finishes the job. The undo record
82
+ * is read again just before: one undone, or made again (a new `created_at`),
83
+ * since `connectedToolbox` read it is left alone.
84
+ */
85
+ export function adoptToolboxId(registryPath, connected) {
86
+ const stale = connected.staleId;
87
+ if (!stale)
88
+ return;
89
+ const { target, entry } = connected;
90
+ let now;
91
+ try {
92
+ now = readBackup(target);
93
+ }
94
+ catch {
95
+ return;
96
+ }
97
+ if (!now || now.scope !== target.scope || now.created_at !== stale.createdAt || now.registry_id !== stale.id)
98
+ return;
99
+ try {
100
+ const rec = readImportRecord(registryPath, target);
101
+ if (rec && rec.gateway_id === stale.id)
102
+ writeImportRecord(registryPath, target, { ...rec, gateway_id: entry.id });
103
+ writeBackup(target, { ...now, registry_id: entry.id });
104
+ }
105
+ catch (err) {
106
+ throw unprocessable(`${LABELS[target.scope]}'s records could not be updated to its toolbox's new id, so nothing else was changed: ${err.message}`);
107
+ }
108
+ }
109
+ /**
110
+ * The values of one server that must not reach the browser: every setting
111
+ * and header value as the app had it, and any part of its command line or
112
+ * address shaped like a key. The program's own name and its ordinary
113
+ * arguments are left alone, so a failure such as "node: not found" still
114
+ * reads as itself.
115
+ */
116
+ function valuesOf(c) {
117
+ const out = [];
118
+ for (const planned of c.plan?.upstreams ?? []) {
119
+ const u = planned.upstream;
120
+ const literal = Object.values(u.transport === "stdio" ? u.env : u.headers).filter((v) => typeof v === "string");
121
+ // The same shapes that keep a server out (`keyWords`), in case a message quotes the command line or address.
122
+ out.push(...literal, ...keyWords(u.transport === "stdio" ? [u.command, ...u.args] : [u.url]));
123
+ }
124
+ out.push(...Object.values(c.plan?.gatewayEnv ?? {}));
125
+ return out;
126
+ }
127
+ /**
128
+ * Puts back what a refused import wrote, every step tried even when one
129
+ * before it fails: a gateway.yaml that can't be restored must not also leave
130
+ * the new keys behind. Returns what could not be put back, without keys.
131
+ */
132
+ export function rollBack(steps, values) {
133
+ const problems = [];
134
+ for (const [what, step] of steps) {
135
+ try {
136
+ step();
137
+ }
138
+ catch (err) {
139
+ problems.push(scrubbed(`${what} could not be put back as it was (${err.message ?? String(err)})`, values));
140
+ }
141
+ }
142
+ return problems;
143
+ }
144
+ /** A refusal's message without any of those values in it. */
145
+ function scrubbed(message, values) {
146
+ return scrubSecrets(message, values);
147
+ }
148
+ /** `text` with these servers added at the end of `upstreams`, comments and layout kept. */
149
+ function withUpstreams(text, upstreams) {
150
+ const doc = parseDocument(text);
151
+ for (const u of upstreams)
152
+ doc.addIn(["upstreams"], doc.createNode(upstreamYaml(u)));
153
+ return doc.toString();
154
+ }
155
+ /** The other apps whose settings run this toolbox, so the person knows what else now runs these servers. */
156
+ export function otherAppsUsing(configPath, except, cwd, home) {
157
+ const out = [];
158
+ for (const target of scopeTargets({ cwd, home })) {
159
+ if (target.scope === except.scope)
160
+ continue;
161
+ try {
162
+ const { servers } = parseServers(readClientConfig(target.scope, { cwd, home }).servers);
163
+ const uses = [...servers.values()].some((s) => {
164
+ if (isRemote(s))
165
+ return false;
166
+ const i = s.args.indexOf("-c");
167
+ const at = i >= 0 ? s.args[i + 1] : undefined;
168
+ return at !== undefined && resolve(dirname(target.path), at) === configPath;
169
+ });
170
+ if (uses && !out.includes(LABELS[target.scope]))
171
+ out.push(LABELS[target.scope]);
172
+ }
173
+ catch {
174
+ /* an unreadable file is not evidence either way */
175
+ }
176
+ }
177
+ return out;
178
+ }
179
+ /** The gateway engine's refusals as the console's error shape. */
180
+ export function asHttp(err, values = []) {
181
+ if (err instanceof HttpError)
182
+ throw err;
183
+ const message = scrubbed(err.message ?? String(err), values);
184
+ if (err instanceof ImportClientError && /changed/.test(message))
185
+ throw conflict(message);
186
+ if (err instanceof ClientConfigError)
187
+ throw unprocessable(message);
188
+ throw unprocessable(`nothing was changed: ${message}`);
189
+ }
190
+ const TOOLBOX_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
191
+ /**
192
+ * An app with no toolbox yet: refused before anything is tested when it
193
+ * already has a connection, since connecting would then be refused only
194
+ * after the servers had been started.
195
+ */
196
+ function refuseIfConnected(target, scope) {
197
+ let backup;
198
+ try {
199
+ backup = readBackup(target);
200
+ }
201
+ catch (err) {
202
+ throw unprocessable(err.message);
203
+ }
204
+ if (backup) {
205
+ throw unprocessable(`${LABELS[scope]} is already connected to a toolbox by hardened-mcp ("${backup.gateway_entry_name}"). ` +
206
+ `Bring its servers into that toolbox, or undo that connection first.`);
207
+ }
208
+ }
209
+ /**
210
+ * Whether the app may still run a toolbox this made: an undo record naming
211
+ * it, or an entry in the app's settings started with its gateway.yaml. A file
212
+ * that can't be read is taken as yes, so nothing it may need is deleted.
213
+ */
214
+ function appMayRun(scope, cwd, home, target, made) {
215
+ try {
216
+ if (readBackup(target)?.registry_id === made.id)
217
+ return true;
218
+ const { servers } = parseServers(readClientConfig(scope, { cwd, home }).servers);
219
+ return [...servers.values()].some((s) => {
220
+ if (isRemote(s))
221
+ return false;
222
+ const i = s.args.indexOf("-c");
223
+ const at = i >= 0 ? s.args[i + 1] : undefined;
224
+ return at !== undefined && resolve(dirname(target.path), at) === resolve(made.configPath);
225
+ });
226
+ }
227
+ catch {
228
+ return true;
229
+ }
230
+ }
231
+ /**
232
+ * Brings the chosen servers of one app into a toolbox. Throws the console's
233
+ * refusals (`HttpError`); a refusal after anything was written puts every
234
+ * write back first, newest first.
235
+ */
236
+ export async function bringIn(args) {
237
+ const { options, scope, cwd } = args;
238
+ const isNew = "new" in args.toolbox;
239
+ const connected = isNew ? null : args.toolbox;
240
+ const newChoice = isNew ? args.toolbox.new : null;
241
+ const home = connected ? connected.home : homedir();
242
+ const target = connected ? connected.target : targetFor(scope, cwd, home);
243
+ if (newChoice) {
244
+ // Also the folder name under ~/.hmcp/gateways, so nothing that could climb out of it: the rule POST /gateways holds.
245
+ if (!TOOLBOX_NAME.test(newChoice.name))
246
+ throw unprocessable("a name is lower-case letters, digits, dashes and underscores");
247
+ refuseIfConnected(target, scope);
248
+ }
249
+ let candidates;
250
+ try {
251
+ ({ candidates } = importCandidates({
252
+ scope,
253
+ cwd,
254
+ home,
255
+ ...(connected ? { gatewayConfigPath: connected.configPath, entryName: connected.entryName } : {}),
256
+ secrets: new SecretStore()
257
+ }));
258
+ }
259
+ catch (err) {
260
+ asHttp(err);
261
+ }
262
+ /* what was asked for, each checked against what the app has now */
263
+ const picked = [];
264
+ const pick = (key, source) => {
265
+ const c = candidates.find((x) => x.source === source && x.key === key);
266
+ if (!c) {
267
+ throw unprocessable(`"${key}" isn't in ${LABELS[scope]} any more. Check again.`);
268
+ }
269
+ if (!c.importable)
270
+ throw unprocessable(`"${c.name}" can't be brought in: ${c.reason ?? "it isn't supported"}`);
271
+ if (!picked.includes(c))
272
+ picked.push(c);
273
+ };
274
+ for (const name of args.names)
275
+ pick(name, "config");
276
+ for (const id of args.extensions)
277
+ pick(id, "extension");
278
+ if (picked.length === 0)
279
+ throw unprocessable("Choose at least one server to bring in.");
280
+ const values = picked.flatMap(valuesOf);
281
+ // Already in the toolbox: nothing to add or test, only the app's copy to take out.
282
+ const toAdd = picked.filter((c) => c.inToolbox === undefined);
283
+ const real = new SecretStore();
284
+ let prepared;
285
+ try {
286
+ const taken = new Map();
287
+ prepared = toAdd.map((c) => {
288
+ const { plan, locks } = planImportSecrets(c.plan, real, taken);
289
+ return { c, upstream: plan.upstreams[0].upstream, locks };
290
+ });
291
+ }
292
+ catch (err) {
293
+ asHttp(err, values);
294
+ }
295
+ const secrets = [...values, ...prepared.flatMap((p) => p.locks.map((l) => l.value))];
296
+ /* everything this would loosen, confirmed before anything starts */
297
+ const changesFor = (list) => list.flatMap((p) => egressChangesFor(p.upstream, { localNetwork: p.c.needsLocalHttp }));
298
+ const newToolboxFor = (list, id) => planNewToolbox({ name: newChoice.name, upstreams: list.map((p) => p.upstream), policyChanges: changesFor(list), ...(id ? { id } : {}), ...(newChoice.label ? { label: newChoice.label } : {}) }, options.registryPath);
299
+ // Connected toolbox only: as it was before anything was written, for the checks and the rollback.
300
+ let gatewayFile = null;
301
+ let policyPath = null;
302
+ let policyBefore = "";
303
+ if (connected) {
304
+ gatewayFile = readGatewayFile(connected.configPath);
305
+ policyPath = connected.server.policyFile !== null && connected.server.gateway.config.policy_writes ? connected.server.policyFile : null;
306
+ policyBefore = policyPath ? readFileSync(policyPath, "utf8") : "";
307
+ }
308
+ /** Everything bringing these servers in would loosen; throws the refusals that no OK can get past. */
309
+ const loosensOf = (list) => {
310
+ const all = changesFor(list);
311
+ if (connected) {
312
+ let preview = unchangedBatch(policyBefore);
313
+ if (policyPath) {
314
+ preview = applyPolicyChanges(policyBefore, all, policyPath);
315
+ refuseIfOverridesOff(gatewayFile.config, preview.loosens);
316
+ }
317
+ else if (all.length > 0 && applyPolicyChanges(stringify(connected.server.policy), all).changed) {
318
+ throw unprocessable("This toolbox's rules can't be changed from the console, and these servers need its network rules changed. " +
319
+ "Change them by hand, or bring the servers into another toolbox.");
320
+ }
321
+ return [
322
+ ...gatewayLoosens(gatewayFile.config, parseGatewayText(withUpstreams(gatewayFile.text, list.map((p) => p.upstream)))),
323
+ ...preview.loosens
324
+ ];
325
+ }
326
+ // Also refuses a name or folder already taken, before anything starts.
327
+ const planned = newToolboxFor(list);
328
+ /*
329
+ * A new toolbox's policy is written with each server's address already
330
+ * allowed, so no loosening line names it. Weighed one by one (`hold`),
331
+ * each address is said as a line of its own, the way adding it to a
332
+ * toolbox that exists says it, so a wildcard or odd address can't slip
333
+ * onto the allow-list unseen.
334
+ */
335
+ const hosts = args.hold
336
+ ? list.flatMap((p) => egressChangesFor(p.upstream, { localNetwork: p.c.needsLocalHttp }).flatMap((c) => (c.kind === "egress-allow" ? [`Your toolbox may connect to ${c.host}`] : [])))
337
+ : [];
338
+ return [...new Set([...localLoosens(planned.local), ...planned.loosens, ...hosts])];
339
+ };
340
+ /* one-click: each server weighed alone, and one that needs an OK left in the app */
341
+ const held = [];
342
+ if (args.hold) {
343
+ const accept = args.hold.accept;
344
+ const kept = [];
345
+ for (const p of prepared) {
346
+ let lines;
347
+ let why = null;
348
+ try {
349
+ lines = loosensOf([p]);
350
+ }
351
+ catch (err) {
352
+ // A name already taken (409) is about the toolbox, not this server: refused for all.
353
+ if (!(err instanceof HttpError) || err.status !== 422)
354
+ throw err;
355
+ lines = [];
356
+ // The overrides-off refusal quotes the lines, which can name an address: said in its own words instead.
357
+ why =
358
+ err.detail?.problem === "overrides-off"
359
+ ? "It would need this toolbox's protection loosened, which this toolbox doesn't allow from the console."
360
+ : scrubbed(err.message, secrets);
361
+ }
362
+ const extra = lines.filter((line) => !accept(line, p.upstream, p.c));
363
+ if (why === null && extra.length === 0) {
364
+ kept.push(p);
365
+ continue;
366
+ }
367
+ held.push({
368
+ name: p.c.name,
369
+ source: p.c.source,
370
+ key: p.c.key,
371
+ loosens: extra.map((line) => scrubbed(line, secrets)),
372
+ // Said without the lines themselves, which can name its address: only names go back from one click.
373
+ why: why ??
374
+ args.hold.why ??
375
+ (p.c.needsLocalHttp || extra.some((line) => /local network|plain http/.test(line))
376
+ ? "It needs your OK first: it is on this computer or the local network, or uses an unencrypted web address, and the toolbox would have to allow that."
377
+ : "It needs your OK first: bringing it in would let more through than the toolbox allows now.")
378
+ });
379
+ }
380
+ prepared = kept;
381
+ }
382
+ const loosens = loosensOf(prepared);
383
+ // Under `hold`, every line left is one `accept` took for one of these servers.
384
+ const acceptedAll = args.hold !== undefined && loosens.every((line) => prepared.some((p) => args.hold.accept(line, p.upstream, p.c)));
385
+ if (args.dryRun) {
386
+ return {
387
+ imported: [],
388
+ takenOut: [],
389
+ failures: [],
390
+ held,
391
+ probed: [],
392
+ made: null,
393
+ restartHint: restartHintFor(target, process.platform),
394
+ extensionsToSwitchOff: [],
395
+ otherApps: [],
396
+ warning: loosens.length > 0 && !acceptedAll ? "These servers together would need an OK." : null,
397
+ toolbox: null
398
+ };
399
+ }
400
+ // What each server is tested against: the toolbox's policy, or the one a new toolbox would start with.
401
+ let basePolicy;
402
+ let probeCwd;
403
+ if (connected) {
404
+ basePolicy = connected.server.policy;
405
+ probeCwd = connected.server.cwd;
406
+ }
407
+ else {
408
+ basePolicy = parsePolicy(parseDocument(newToolboxFor(prepared).policyYaml).toJS(), "policy.yaml");
409
+ /*
410
+ * The toolbox's folder doesn't exist yet, so a server is tested from the
411
+ * home folder, as Test it tests one for a toolbox not made yet. Once made,
412
+ * the toolbox runs it from its own folder; a server set from a project
413
+ * has that folder written into it, and runs from there either way.
414
+ */
415
+ probeCwd = home;
416
+ }
417
+ if (loosens.length > 0 && args.acknowledged?.loosens !== true && !acceptedAll) {
418
+ throw unprocessable(`bringing these servers in lets more through and needs confirming: ${loosens.join("; ")}`, {
419
+ needs: "loosens",
420
+ loosens
421
+ });
422
+ }
423
+ /* test each one, as Test it does: scratch keys, scratch policy */
424
+ const passed = [];
425
+ const failures = [];
426
+ for (const p of prepared) {
427
+ const outcome = await withProbeSlot(async () => {
428
+ const materialized = {
429
+ upstream: p.upstream,
430
+ secretsToCreate: p.locks.map((l) => ({ ...l })),
431
+ secretsReferenced: [],
432
+ egressHosts: [],
433
+ localNetwork: p.c.needsLocalHttp,
434
+ problems: {}
435
+ };
436
+ const scratch = scratchSecretStore(materialized, real);
437
+ try {
438
+ return await runProbe(p.upstream, {
439
+ policy: scratchPolicy(basePolicy, p.upstream, p.c.needsLocalHttp),
440
+ secrets: scratch.store,
441
+ cwd: probeCwd
442
+ });
443
+ }
444
+ finally {
445
+ scratch.dispose();
446
+ }
447
+ });
448
+ if (outcome.ok)
449
+ passed.push({ ...p, tools: outcome.tools.length, probeTools: outcome.tools });
450
+ else {
451
+ failures.push({
452
+ name: p.c.name,
453
+ source: p.c.source,
454
+ code: outcome.problem?.code ?? "unknown",
455
+ message: scrubbed(outcome.problem?.message ?? "It didn't answer.", secrets)
456
+ });
457
+ }
458
+ }
459
+ const takeOut = picked.filter((c) => c.inToolbox !== undefined);
460
+ const extensionsToSwitchOff = [...passed.map((p) => p.c), ...takeOut]
461
+ .filter((c) => c.source === "extension")
462
+ .map((c) => ({ id: c.key, name: c.name, enabled: c.enabled ?? true }));
463
+ let restartHint = restartHintFor(target, process.platform);
464
+ const otherApps = connected ? otherAppsUsing(connected.configPath, target, cwd, home) : [];
465
+ const leaving = [...passed.map((p) => p.c), ...takeOut].filter((c) => c.source === "config");
466
+ // A new toolbox is never made with no servers in it, whatever else is chosen.
467
+ if (passed.length === 0 && (leaving.length === 0 || !connected)) {
468
+ return {
469
+ imported: [],
470
+ takenOut: [],
471
+ failures,
472
+ held,
473
+ probed: [],
474
+ made: null,
475
+ restartHint,
476
+ extensionsToSwitchOff,
477
+ otherApps,
478
+ warning: connected ? null : "None of the servers connected, so no toolbox was made and nothing was changed.",
479
+ toolbox: connected
480
+ ? { id: connected.entry.id, label: toolboxLabel(connected.entry), configPath: connected.configPath, created: false, entryName: connected.entryName }
481
+ : null
482
+ };
483
+ }
484
+ // The new toolbox as it will be written: the servers that connected, and nothing else.
485
+ const finalPlan = connected ? null : newToolboxFor(passed);
486
+ /* keys first: the servers refer to them */
487
+ const created = [];
488
+ const rollbackKeys = () => {
489
+ for (const name of created) {
490
+ try {
491
+ real.delete(name);
492
+ }
493
+ catch {
494
+ /* best effort; the rollback must reach the files too */
495
+ }
496
+ }
497
+ };
498
+ const createdFor = new Map();
499
+ let policyWritten = false;
500
+ let gatewayWritten = false;
501
+ let made = null;
502
+ let attached = null;
503
+ try {
504
+ for (const p of passed) {
505
+ const mine = [];
506
+ for (const lock of p.locks) {
507
+ const saved = real.get(lock.name);
508
+ if (saved) {
509
+ if (saved.kind === "value" && saved.value === lock.value)
510
+ continue;
511
+ throw conflict(`A locked key called "${lock.name}" was saved meanwhile, so nothing was changed. Check again.`);
512
+ }
513
+ const stamp = new Date().toISOString();
514
+ real.set(lock.name, { kind: "value", value: lock.value, label: lock.label, created_at: stamp, updated_at: stamp });
515
+ created.push(lock.name);
516
+ mine.push(lock.name);
517
+ }
518
+ createdFor.set(p.c.key, mine);
519
+ }
520
+ if (connected) {
521
+ /* then the policy, then gateway.yaml: the servers never run without their network rules */
522
+ const batch = policyPath && passed.length > 0 ? applyPolicyChanges(policyBefore, changesFor(passed), policyPath) : unchangedBatch(policyBefore);
523
+ if (batch.changed) {
524
+ if (readFileSync(policyPath, "utf8") !== policyBefore) {
525
+ throw conflict("This toolbox's protection settings changed while the servers were being tested, so nothing was changed. Check again.");
526
+ }
527
+ writeAtomically(policyPath, batch.text);
528
+ policyWritten = true;
529
+ }
530
+ if (passed.length > 0) {
531
+ // Read again: a gateway.yaml changed while the servers were tested is not written over.
532
+ const fresh = readGatewayFile(connected.configPath);
533
+ const adding = passed.map((p) => p.upstream);
534
+ commitGatewayText({
535
+ file: fresh,
536
+ text: withUpstreams(fresh.text, adding),
537
+ expectedDigest: gatewayFile.digest,
538
+ acknowledgedLoosens: true,
539
+ intended: (before, after) => sameExcept(before, after, ["upstreams"]) &&
540
+ after.upstreams.length === before.upstreams.length + adding.length &&
541
+ before.upstreams.every((u, i) => JSON.stringify(u) === JSON.stringify(after.upstreams[i])) &&
542
+ adding.every((u, i) => after.upstreams[before.upstreams.length + i]?.name === u.name)
543
+ ? null
544
+ : "bringing the servers in would have changed something else too"
545
+ });
546
+ gatewayWritten = true;
547
+ }
548
+ }
549
+ else {
550
+ /* then the toolbox, with its row in the console, then the app connected to it */
551
+ made = writeNewToolbox(finalPlan, options.registryPath);
552
+ attached = await connectClient({
553
+ scope,
554
+ cwd,
555
+ home,
556
+ gatewayConfigPath: made.configPath,
557
+ pathDirs: [...(args.pathDirs ?? pathDirsFromEnv())],
558
+ registryId: made.id,
559
+ ...launchOf(options)
560
+ });
561
+ // An entry that already ran this file was there before the toolbox was: not a connection this made.
562
+ if (attached.alreadyConnected) {
563
+ throw unprocessable(`${LABELS[scope]} already had an entry ("${attached.entryName}") pointing at ${made.configPath}, so it was not connected to the new toolbox. ` +
564
+ `Remove that entry from its settings, then try again.`);
565
+ }
566
+ restartHint = attached.restartHint;
567
+ }
568
+ /* the app's settings last */
569
+ if (leaving.length > 0)
570
+ moveOutOfClient({ scope, cwd, home }, Object.fromEntries(leaving.map((c) => [c.key, c.entry])));
571
+ }
572
+ catch (err) {
573
+ const problems = [];
574
+ /*
575
+ * A new toolbox, and the keys made for it, go only once the app is known
576
+ * not to run it: taking away a toolbox the app's settings still start
577
+ * would leave the app's servers in neither place.
578
+ */
579
+ let keepToolbox = false;
580
+ if (made) {
581
+ let revertFailed = false;
582
+ if (attached && !attached.alreadyConnected) {
583
+ // The connection's own Undo: the app's file back as it was, and its undo record gone.
584
+ try {
585
+ await adoptRevert({ scope, cwd, home, registry: options.registryPath });
586
+ }
587
+ catch (revertErr) {
588
+ revertFailed = true;
589
+ problems.push(scrubbed(`${LABELS[scope]}'s settings could not be put back as they were (${revertErr.message ?? String(revertErr)})`, secrets));
590
+ }
591
+ }
592
+ // Also when connecting itself failed part-way: the app's file may name the toolbox with no undo record yet.
593
+ keepToolbox = revertFailed || appMayRun(scope, cwd, home, target, made);
594
+ if (keepToolbox) {
595
+ problems.push(`the new toolbox "${made.id}" was kept, with its locked keys, because ${LABELS[scope]}'s settings may still run it (${made.configPath}); ` +
596
+ `undo that connection from the console, then remove the toolbox`);
597
+ }
598
+ }
599
+ problems.push(...rollBack(connected
600
+ ? [
601
+ ["gateway.yaml", () => gatewayWritten && writeAtomically(connected.configPath, gatewayFile.text)],
602
+ ["the protection settings", () => policyWritten && writeAtomically(policyPath, policyBefore)],
603
+ ["the locked keys", rollbackKeys]
604
+ ]
605
+ : keepToolbox
606
+ ? []
607
+ : [
608
+ ["the new toolbox", () => made && removeNewToolbox(made, options.registryPath)],
609
+ ["the locked keys", rollbackKeys]
610
+ ], secrets));
611
+ // The refusal itself is what is reported; anything that could not be undone is added to it.
612
+ if (problems.length === 0)
613
+ asHttp(err, secrets);
614
+ try {
615
+ asHttp(err, secrets);
616
+ }
617
+ catch (refusal) {
618
+ if (refusal instanceof HttpError) {
619
+ // Something stayed behind, so the usual "nothing was changed" opening would not be true.
620
+ const opening = refusal.message.replace(/^nothing was changed: /, "this stopped part-way and was not fully undone: ");
621
+ throw new HttpError(refusal.status, refusal.code, `${opening} Also: ${problems.join("; ")}.`, refusal.detail);
622
+ }
623
+ throw refusal;
624
+ }
625
+ }
626
+ const entry = connected ? connected.entry : made.entry;
627
+ const configPath = connected ? connected.configPath : made.configPath;
628
+ /* what Undo needs: names only */
629
+ const items = [
630
+ ...passed.map((p) => ({
631
+ key: p.c.key,
632
+ name: p.c.name,
633
+ source: p.c.source,
634
+ upstream: p.upstream.name,
635
+ added: true,
636
+ keys_created: createdFor.get(p.c.key) ?? [],
637
+ digest: upstreamDigest(p.upstream)
638
+ })),
639
+ ...takeOut.map((c) => ({ key: c.key, name: c.name, source: c.source, upstream: c.inToolbox, added: false, keys_created: [] }))
640
+ ];
641
+ const warnings = [];
642
+ /*
643
+ * gateway.yaml is the person's own file and keeps the mode they gave it.
644
+ * Its keys are locked, so it holds none; but it names them and holds the
645
+ * servers' plain settings, so a copy others can read is pointed out.
646
+ */
647
+ try {
648
+ if (passed.length > 0 && statSync(configPath).mode & 0o077) {
649
+ 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}`);
650
+ }
651
+ }
652
+ catch {
653
+ /* no modes to speak of (Windows) */
654
+ }
655
+ try {
656
+ const before = readLiveImportRecord(options.registryPath, target);
657
+ const earlier = before && before.gateway_id === entry.id ? before.items : [];
658
+ /*
659
+ * A copy the app wrote back and this only took out again is the same
660
+ * server an earlier import added: that item stays, with its keys and
661
+ * digest, so Undo still takes it out of the toolbox.
662
+ */
663
+ const same = (a, b) => a.key === b.key && a.source === b.source;
664
+ const fresh = items.filter((n) => !(n.added === false && earlier.some((i) => same(i, n) && i.added && i.upstream === n.upstream)));
665
+ // Taken out of the app again just now, so not "back in the app" any more: its Undo must put it back there.
666
+ const retaken = (i) => items.some((n) => same(i, n) && n.added === false && i.added && i.upstream === n.upstream);
667
+ const kept = earlier
668
+ .filter((i) => !fresh.some((n) => same(i, n)))
669
+ .map((i) => {
670
+ if (!retaken(i))
671
+ return i;
672
+ const { back_in_app: _back, ...rest } = i;
673
+ return rest;
674
+ });
675
+ writeImportRecord(options.registryPath, target, {
676
+ version: 1,
677
+ scope,
678
+ config_path: target.path,
679
+ where: target.where,
680
+ gateway_id: entry.id,
681
+ created_at: before?.created_at ?? new Date().toISOString(),
682
+ items: [...kept, ...fresh]
683
+ });
684
+ }
685
+ catch (err) {
686
+ warnings.push(`The servers were brought in, but the note Undo needs could not be saved (${err.message}). ` +
687
+ `Undo connection still gives the app its servers back.`);
688
+ }
689
+ const imported = passed.map((p) => ({ name: p.c.name, source: p.c.source, upstream: p.upstream.name, tools: p.tools, keysLocked: [...p.c.keySettings] }));
690
+ const takenOut = takeOut.map((c) => ({ name: c.name, source: c.source, upstream: c.inToolbox }));
691
+ const log = gatewayAudit(configPath, args.actor);
692
+ const audits = [];
693
+ if (made && attached) {
694
+ // The same records making the toolbox and connecting the app leave when done one at a time.
695
+ const plan = finalPlan;
696
+ audits.push(record(log, {
697
+ tool: "(connect)",
698
+ effect: null,
699
+ decision: "allow",
700
+ rule_id: "connect.create",
701
+ reason: `gateway "${plan.name}" created via the console by ${args.actor}, fronting ${plan.upstreamNames.join(", ")}`,
702
+ outcome: "completed",
703
+ args_redacted: { name: plan.name, upstreams: [...plan.upstreamNames], mode: plan.mode, posture: plan.posture, registry_id: made.id }
704
+ }), record(log, {
705
+ tool: "(connect)",
706
+ effect: null,
707
+ decision: "allow",
708
+ rule_id: "connect.attach",
709
+ reason: `${LABELS[scope]} connected to this gateway via the console by ${args.actor}, as "${attached.entryName}" in ${attached.configPath}`,
710
+ outcome: "completed",
711
+ args_redacted: { scope, client_config: attached.configPath, entry: attached.entryName, registry_id: made.id }
712
+ }));
713
+ }
714
+ audits.push(record(log, {
715
+ tool: "(connect)",
716
+ effect: null,
717
+ decision: "allow",
718
+ rule_id: "connect.import",
719
+ reason: `${imported.length} server(s) brought into this gateway from ${LABELS[scope]} via the console by ${args.actor}` +
720
+ (leaving.length > 0 ? `; ${leaving.length} taken out of ${target.path}` : "") +
721
+ (failures.length > 0 ? `; ${failures.length} left in the app because they did not connect` : ""),
722
+ outcome: "completed",
723
+ args_redacted: {
724
+ scope,
725
+ client_config: target.path,
726
+ imported: imported.map((i) => ({ name: i.name, source: i.source, upstream: i.upstream })),
727
+ taken_out: leaving.map((c) => c.key),
728
+ secrets_created: created,
729
+ failed: failures.map((f) => f.name),
730
+ loosens,
731
+ registry_id: entry.id
732
+ }
733
+ }));
734
+ for (const audit of new Set(audits))
735
+ if (audit)
736
+ warnings.push(audit);
737
+ return {
738
+ imported,
739
+ takenOut,
740
+ failures,
741
+ held,
742
+ probed: passed.map((p) => ({ upstream: p.upstream.name, digest: upstreamDigest(p.upstream), tools: p.probeTools })),
743
+ made: made ? { id: made.id, configPath: made.configPath, policyPath: made.policyPath, dir: made.dir, createdDir: made.createdDir, files: [...made.files] } : null,
744
+ restartHint,
745
+ extensionsToSwitchOff,
746
+ otherApps,
747
+ warning: warnings.length > 0 ? warnings.join(" ") : null,
748
+ toolbox: {
749
+ id: entry.id,
750
+ label: toolboxLabel(entry),
751
+ configPath,
752
+ created: made !== null,
753
+ entryName: connected ? connected.entryName : attached.entryName
754
+ }
755
+ };
756
+ }