hmcp-web 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +77 -0
- package/README.md +48 -2
- package/THIRD-PARTY-NOTICES.md +110 -0
- package/bin/hmcp-web.js +20 -0
- package/dist/api.d.ts +11 -0
- package/dist/api.js +1404 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +40 -0
- package/dist/contracts/onboarding.d.ts +233 -0
- package/dist/contracts/onboarding.js +1 -0
- package/dist/http.d.ts +72 -0
- package/dist/http.js +319 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/model/console-settings.d.ts +37 -0
- package/dist/model/console-settings.js +74 -0
- package/dist/model/doctor.d.ts +68 -0
- package/dist/model/doctor.js +254 -0
- package/dist/model/fs-browse.d.ts +9 -0
- package/dist/model/fs-browse.js +184 -0
- package/dist/model/gateway-config.d.ts +287 -0
- package/dist/model/gateway-config.js +760 -0
- package/dist/model/metrics.d.ts +65 -0
- package/dist/model/metrics.js +198 -0
- package/dist/model/oauth-flows.d.ts +60 -0
- package/dist/model/oauth-flows.js +79 -0
- package/dist/model/pipeline.d.ts +58 -0
- package/dist/model/pipeline.js +84 -0
- package/dist/model/probe.d.ts +155 -0
- package/dist/model/probe.js +385 -0
- package/dist/model/process.d.ts +100 -0
- package/dist/model/process.js +278 -0
- package/dist/model/protection.d.ts +378 -0
- package/dist/model/protection.js +470 -0
- package/dist/model/registry-cache.d.ts +59 -0
- package/dist/model/registry-cache.js +238 -0
- package/dist/model/scan.d.ts +48 -0
- package/dist/model/scan.js +59 -0
- package/dist/model/server.d.ts +127 -0
- package/dist/model/server.js +243 -0
- package/dist/model/tools.d.ts +61 -0
- package/dist/model/tools.js +72 -0
- package/dist/routes/catalog.d.ts +8 -0
- package/dist/routes/catalog.js +47 -0
- package/dist/routes/connect.d.ts +14 -0
- package/dist/routes/connect.js +633 -0
- package/dist/routes/oauth.d.ts +55 -0
- package/dist/routes/oauth.js +406 -0
- package/dist/routes/policy.d.ts +34 -0
- package/dist/routes/policy.js +513 -0
- package/dist/routes/runtime.d.ts +6 -0
- package/dist/routes/runtime.js +921 -0
- package/dist/routes/servers-add.d.ts +24 -0
- package/dist/routes/servers-add.js +1091 -0
- package/dist/routes/system.d.ts +4 -0
- package/dist/routes/system.js +13 -0
- package/dist/start.d.ts +56 -0
- package/dist/start.js +164 -0
- package/dist-ui/assets/Activity-BqKGpXMN.js +1 -0
- package/dist-ui/assets/Approvals-Qo7bCcli.js +1 -0
- package/dist-ui/assets/AttachApp-0zRSPgSY.js +5 -0
- package/dist-ui/assets/Connections-CE0JGe8c.js +2 -0
- package/dist-ui/assets/Gallery-B39L2Yma.js +17 -0
- package/dist-ui/assets/PreApprovals-BsIhjMqb.js +1 -0
- package/dist-ui/assets/Protection-DlB09ABa.js +1 -0
- package/dist-ui/assets/Safety-CN-oHO2h.js +1 -0
- package/dist-ui/assets/Settings-BLD7G1Ag.js +1 -0
- package/dist-ui/assets/StartPage-HuZSnmSr.js +1 -0
- package/dist-ui/assets/Suggestions-Dp7pofcs.js +1 -0
- package/dist-ui/assets/Tools-Bfot3bx5.js +4 -0
- package/dist-ui/assets/index-Khp0l1zp.js +16 -0
- package/dist-ui/assets/index-Ylyt4DEr.css +2 -0
- package/dist-ui/assets/kit-DQ7Oxf5n.js +4 -0
- package/dist-ui/brand/logo-256.png +0 -0
- package/dist-ui/brand/logo-512.png +0 -0
- package/dist-ui/brand/logo.svg +6 -0
- package/dist-ui/brand/mark.svg +5 -0
- package/dist-ui/fonts/OFL.txt +99 -0
- package/dist-ui/fonts/README.md +21 -0
- package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
- package/dist-ui/fonts/manrope-latin.woff2 +0 -0
- package/dist-ui/index.html +51 -0
- package/package.json +69 -6
- package/bin/notice.js +0 -7
|
@@ -0,0 +1,760 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { isMap, isScalar, isSeq, parseDocument } from "yaml";
|
|
3
|
+
import { applyPolicyBatch, LIVE_STATE_STALE_MS, canonicalJson, classifyAddress, isIpLiteral, isSecretRef, parsePolicy, sha256, writeAtomically } from "hmcp-core";
|
|
4
|
+
import { GatewayConfigSchema } from "hmcp-gateway";
|
|
5
|
+
import { HttpError, conflict, unprocessable } from "../http.js";
|
|
6
|
+
/**
|
|
7
|
+
* Editing `gateway.yaml` from the console.
|
|
8
|
+
*
|
|
9
|
+
* Every write here goes through `commitGatewayText`, which is the whole of the
|
|
10
|
+
* boundary: a digest lock, YAML that parses, a config the gateway's own schema
|
|
11
|
+
* accepts, the two settings that decide whether the console may write policy
|
|
12
|
+
* at all left exactly as they were, the policy itself left alone, and an
|
|
13
|
+
* acknowledgement for any change that widens what reaches the model. Edits are
|
|
14
|
+
* made through the `yaml` Document API, so comments and layout around the
|
|
15
|
+
* edited node survive.
|
|
16
|
+
*
|
|
17
|
+
* A running gateway with `upstream_reload` (the default) applies a change to
|
|
18
|
+
* `upstreams` live; any other change still waits for its next start. Which of
|
|
19
|
+
* the two happened is read from what the running processes report -- see
|
|
20
|
+
* `applyState` in routes/runtime.ts.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* What the console shows in place of an upstream header or env value.
|
|
24
|
+
*
|
|
25
|
+
* Those two maps are where credentials live in this file, and the console does
|
|
26
|
+
* not echo a credential back over its API. A value left as this marker on a
|
|
27
|
+
* save keeps whatever is on disk for the same upstream and key.
|
|
28
|
+
*/
|
|
29
|
+
export const KEPT_SECRET = "[kept secret]";
|
|
30
|
+
/** The two settings no console write may change. See `assertGuardsUnchanged`. */
|
|
31
|
+
export const GUARDED_SETTINGS = ["policy_writes", "policy_overrides"];
|
|
32
|
+
export function digestText(text) {
|
|
33
|
+
return sha256(text);
|
|
34
|
+
}
|
|
35
|
+
export function readGatewayFile(path) {
|
|
36
|
+
const text = readFileSync(path, "utf8");
|
|
37
|
+
const parsed = GatewayConfigSchema.safeParse(parseDocument(text).toJS());
|
|
38
|
+
if (!parsed.success)
|
|
39
|
+
throw unprocessable(`${path} is not a valid gateway config: ${issues(parsed.error)}`);
|
|
40
|
+
return { path, text, digest: digestText(text), config: parsed.data };
|
|
41
|
+
}
|
|
42
|
+
/** The file when it is valid, or what is wrong with it when it is not. */
|
|
43
|
+
export function readGatewayFileOrBroken(path) {
|
|
44
|
+
const text = readFileSync(path, "utf8");
|
|
45
|
+
const doc = parseDocument(text);
|
|
46
|
+
if (doc.errors.length > 0) {
|
|
47
|
+
return { path, text: null, digest: digestText(text), error: `not valid YAML: ${doc.errors[0].message}` };
|
|
48
|
+
}
|
|
49
|
+
const parsed = GatewayConfigSchema.safeParse(doc.toJS());
|
|
50
|
+
if (!parsed.success) {
|
|
51
|
+
return {
|
|
52
|
+
path,
|
|
53
|
+
text: redactBrokenText(text),
|
|
54
|
+
digest: digestText(text),
|
|
55
|
+
error: `not a valid gateway config: ${issues(parsed.error)}`
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return { path, text, digest: digestText(text), config: parsed.data };
|
|
59
|
+
}
|
|
60
|
+
export function isBroken(file) {
|
|
61
|
+
return "error" in file;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Repairs a gateway.yaml the schema rejects.
|
|
65
|
+
*
|
|
66
|
+
* The usual checks compare against the parsed config before the edit, and a
|
|
67
|
+
* broken file has none, so this path holds the line differently:
|
|
68
|
+
* - the broken text must still be YAML, so the guards' values on disk can be
|
|
69
|
+
* read from it (a file that is not even YAML is refused: there is nothing
|
|
70
|
+
* to compare the guards against);
|
|
71
|
+
* - `policy_writes`, `policy_overrides` and `policy:` must come out exactly as
|
|
72
|
+
* the broken file has them, reading an absent guard as its schema default;
|
|
73
|
+
* - the save always counts as loosening, because what it widens cannot be
|
|
74
|
+
* computed against a file the gateway could not load.
|
|
75
|
+
*/
|
|
76
|
+
export function repairGatewayText(args) {
|
|
77
|
+
const { file } = args;
|
|
78
|
+
if (args.expectedDigest !== file.digest) {
|
|
79
|
+
throw conflict("gateway.yaml changed since it was read. Reload it and make the change again, so nothing written in " +
|
|
80
|
+
"the meantime is overwritten.");
|
|
81
|
+
}
|
|
82
|
+
const current = readFileSync(file.path, "utf8");
|
|
83
|
+
const doc = parseDocument(current);
|
|
84
|
+
if (doc.errors.length > 0) {
|
|
85
|
+
throw unprocessable("gateway.yaml is not valid YAML, so the console cannot tell what its write permissions were. Fix the " +
|
|
86
|
+
"file in a text editor.");
|
|
87
|
+
}
|
|
88
|
+
const raw = (doc.toJS() ?? {});
|
|
89
|
+
const after = parseGatewayText(args.text);
|
|
90
|
+
for (const key of GUARDED_SETTINGS) {
|
|
91
|
+
const before = raw[key] === undefined ? GatewayConfigSchema.shape[key].parse(undefined) : raw[key];
|
|
92
|
+
if (before !== after[key]) {
|
|
93
|
+
throw new HttpError(403, "forbidden", `${key} cannot be changed from the console. It decides whether the console may change policy at ` +
|
|
94
|
+
`all, so a console that could change it would be giving itself permission. Edit gateway.yaml directly.`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (canonicalJson(raw["policy"] ?? null) !== canonicalJson(after.policy)) {
|
|
98
|
+
throw unprocessable(`this repair would change the policy (the "policy:" entry), which is not edited here. Change rules and ` +
|
|
99
|
+
`settings on the Protection settings page, where each change is checked.`);
|
|
100
|
+
}
|
|
101
|
+
if (!args.acknowledgedLoosens) {
|
|
102
|
+
throw unprocessable("this file could not be loaded, so what a repair lets through cannot be compared with what was there. " +
|
|
103
|
+
"Confirm the repair to save it.", { needs: "loosens", loosens: ["repairing a gateway.yaml that could not be loaded"] });
|
|
104
|
+
}
|
|
105
|
+
writeAtomically(file.path, args.text);
|
|
106
|
+
return { after, previousDigest: file.digest, digest: digestText(args.text) };
|
|
107
|
+
}
|
|
108
|
+
/** Every header value of an HTTP upstream and env value of a stdio one. */
|
|
109
|
+
function secretSites(doc) {
|
|
110
|
+
const out = [];
|
|
111
|
+
const upstreams = doc.get("upstreams", true);
|
|
112
|
+
if (!isSeq(upstreams))
|
|
113
|
+
return out;
|
|
114
|
+
for (const item of upstreams.items) {
|
|
115
|
+
if (!isMap(item))
|
|
116
|
+
continue;
|
|
117
|
+
const name = String(item.get("name") ?? "");
|
|
118
|
+
for (const field of ["headers", "env"]) {
|
|
119
|
+
const map = item.get(field, true);
|
|
120
|
+
if (!isMap(map))
|
|
121
|
+
continue;
|
|
122
|
+
for (const pair of map.items) {
|
|
123
|
+
if (isScalar(pair.key) && isScalar(pair.value)) {
|
|
124
|
+
out.push({ upstream: name, field, key: String(pair.key.value), node: pair.value });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
/** Replaces source ranges back to front, so earlier offsets stay valid. */
|
|
132
|
+
function spliceRanges(text, edits) {
|
|
133
|
+
let out = text;
|
|
134
|
+
for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
|
|
135
|
+
out = out.slice(0, edit.start) + edit.with + out.slice(edit.end);
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The file as the console shows it: byte for byte, except that each credential
|
|
141
|
+
* value is replaced in place by the marker. Done on source ranges rather than
|
|
142
|
+
* by re-serialising, so what the editor shows is the file's own layout.
|
|
143
|
+
*/
|
|
144
|
+
export function redactText(text) {
|
|
145
|
+
const doc = parseDocument(text);
|
|
146
|
+
const edits = secretSites(doc)
|
|
147
|
+
.filter((s) => s.node.range)
|
|
148
|
+
.map((s) => ({ start: s.node.range[0], end: s.node.range[1], with: JSON.stringify(KEPT_SECRET) }));
|
|
149
|
+
return spliceRanges(text, edits);
|
|
150
|
+
}
|
|
151
|
+
/** A key whose value is treated as a credential in a file whose shape cannot be trusted. */
|
|
152
|
+
const CREDENTIAL_KEY = /(token|secret|key|password|passw|auth|authorization|bearer|cookie|credential|api[-_]?key)/i;
|
|
153
|
+
/** Maps whose every value is treated as a credential, at any depth. `header` is the likely typo. */
|
|
154
|
+
const CREDENTIAL_MAPS = new Set(["headers", "header", "env"]);
|
|
155
|
+
/**
|
|
156
|
+
* Every scalar a broken file might hold a credential in, keyed by its document
|
|
157
|
+
* path.
|
|
158
|
+
*
|
|
159
|
+
* `secretSites` knows where credentials live only when the file has the shape
|
|
160
|
+
* the schema expects; a file the schema rejects may have upstreams as a map,
|
|
161
|
+
* a `header:` typo, or a token at the top level. So this walks the whole
|
|
162
|
+
* document and takes everything under a credential-looking key, and
|
|
163
|
+
* everything under a `headers`, `header` or `env` map, however deep.
|
|
164
|
+
*/
|
|
165
|
+
function conservativeSites(doc) {
|
|
166
|
+
const out = [];
|
|
167
|
+
const walk = (node, path, secret) => {
|
|
168
|
+
if (isScalar(node)) {
|
|
169
|
+
if (secret)
|
|
170
|
+
out.push({ path: JSON.stringify(path), node });
|
|
171
|
+
}
|
|
172
|
+
else if (isMap(node)) {
|
|
173
|
+
for (const pair of node.items) {
|
|
174
|
+
const key = isScalar(pair.key) ? String(pair.key.value) : "";
|
|
175
|
+
walk(pair.value, [...path, key], secret || CREDENTIAL_KEY.test(key) || CREDENTIAL_MAPS.has(key));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else if (isSeq(node)) {
|
|
179
|
+
node.items.forEach((item, i) => walk(item, [...path, i], secret));
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
walk(doc.contents, [], false);
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The redaction for a file the schema rejects: everything `conservativeSites`
|
|
187
|
+
* finds, as well as everything `redactText` would.
|
|
188
|
+
*/
|
|
189
|
+
export function redactBrokenText(text) {
|
|
190
|
+
const doc = parseDocument(text);
|
|
191
|
+
const nodes = new Set([...secretSites(doc).map((s) => s.node), ...conservativeSites(doc).map((s) => s.node)]);
|
|
192
|
+
const edits = [...nodes]
|
|
193
|
+
.filter((n) => n.range)
|
|
194
|
+
.map((n) => ({ start: n.range[0], end: n.range[1], with: JSON.stringify(KEPT_SECRET) }));
|
|
195
|
+
return spliceRanges(text, edits);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* A value as the browser may see it. A `{ secret: name }` reference is shown
|
|
199
|
+
* as itself -- it names a locked key, it does not contain one, and the page
|
|
200
|
+
* needs it to say "uses your GitHub key". A literal is a credential as far as
|
|
201
|
+
* anyone can tell, and is replaced by the marker.
|
|
202
|
+
*/
|
|
203
|
+
function redactValue(value) {
|
|
204
|
+
return isSecretRef(value) ? value : KEPT_SECRET;
|
|
205
|
+
}
|
|
206
|
+
export function redactUpstream(upstream) {
|
|
207
|
+
if (upstream.transport === "http") {
|
|
208
|
+
return { ...upstream, headers: Object.fromEntries(Object.entries(upstream.headers).map(([k, v]) => [k, redactValue(v)])) };
|
|
209
|
+
}
|
|
210
|
+
return { ...upstream, env: Object.fromEntries(Object.entries(upstream.env).map(([k, v]) => [k, redactValue(v)])) };
|
|
211
|
+
}
|
|
212
|
+
export function redactConfig(config) {
|
|
213
|
+
return { ...config, upstreams: config.upstreams.map(redactUpstream) };
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Puts the real values back wherever the marker was left in a submitted text.
|
|
217
|
+
*
|
|
218
|
+
* Copied from the current file's own source, so a credential never passes
|
|
219
|
+
* through the browser in either direction. A marker with nothing to keep -- an
|
|
220
|
+
* upstream or key that does not exist on disk -- is refused, rather than
|
|
221
|
+
* written as the literal word.
|
|
222
|
+
*/
|
|
223
|
+
export function restoreSecretsInText(submitted, current) {
|
|
224
|
+
const currentDoc = parseDocument(current);
|
|
225
|
+
const submittedDoc = parseDocument(submitted);
|
|
226
|
+
const now = secretSites(currentDoc);
|
|
227
|
+
const edits = [];
|
|
228
|
+
const handled = new Set();
|
|
229
|
+
for (const site of secretSites(submittedDoc)) {
|
|
230
|
+
if (site.node.value !== KEPT_SECRET || !site.node.range)
|
|
231
|
+
continue;
|
|
232
|
+
handled.add(site.node);
|
|
233
|
+
const original = now.find((s) => s.upstream === site.upstream && s.field === site.field && s.key === site.key);
|
|
234
|
+
if (!original?.node.range) {
|
|
235
|
+
throw unprocessable(`${site.field}.${site.key} on "${site.upstream}" is marked ${KEPT_SECRET}, but there is no saved value ` +
|
|
236
|
+
`to keep. Type the value.`);
|
|
237
|
+
}
|
|
238
|
+
edits.push({
|
|
239
|
+
start: site.node.range[0],
|
|
240
|
+
end: site.node.range[1],
|
|
241
|
+
with: current.slice(original.node.range[0], original.node.range[1])
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
/*
|
|
245
|
+
* Any other marker is one a broken file's redaction left (`redactBrokenText`).
|
|
246
|
+
* It is restored from the same document path, and only from a value that
|
|
247
|
+
* redaction would itself have hidden; anything else is refused rather than
|
|
248
|
+
* written as the literal word.
|
|
249
|
+
*/
|
|
250
|
+
const byPath = new Map(conservativeSites(currentDoc).map((s) => [s.path, s.node]));
|
|
251
|
+
for (const site of conservativeSites(submittedDoc)) {
|
|
252
|
+
if (site.node.value !== KEPT_SECRET || !site.node.range || handled.has(site.node))
|
|
253
|
+
continue;
|
|
254
|
+
handled.add(site.node);
|
|
255
|
+
const original = byPath.get(site.path);
|
|
256
|
+
if (!original?.range) {
|
|
257
|
+
throw unprocessable(`${site.path} is marked ${KEPT_SECRET}, but there is no saved value there to keep. Type the value.`);
|
|
258
|
+
}
|
|
259
|
+
edits.push({ start: site.node.range[0], end: site.node.range[1], with: current.slice(original.range[0], original.range[1]) });
|
|
260
|
+
}
|
|
261
|
+
let stray = null;
|
|
262
|
+
const find = (node, path) => {
|
|
263
|
+
if (stray)
|
|
264
|
+
return;
|
|
265
|
+
if (isScalar(node) && node.value === KEPT_SECRET && !handled.has(node))
|
|
266
|
+
stray = JSON.stringify(path);
|
|
267
|
+
else if (isMap(node))
|
|
268
|
+
for (const pair of node.items)
|
|
269
|
+
find(pair.value, [...path, isScalar(pair.key) ? String(pair.key.value) : ""]);
|
|
270
|
+
else if (isSeq(node))
|
|
271
|
+
node.items.forEach((item, i) => find(item, [...path, i]));
|
|
272
|
+
};
|
|
273
|
+
find(submittedDoc.contents, []);
|
|
274
|
+
if (stray) {
|
|
275
|
+
throw unprocessable(`${stray} is marked ${KEPT_SECRET}, but nothing saved there is kept secret. Type the value.`);
|
|
276
|
+
}
|
|
277
|
+
return spliceRanges(submitted, edits);
|
|
278
|
+
}
|
|
279
|
+
/** The same, for an upstream submitted as an object. */
|
|
280
|
+
export function restoreSecretsInUpstream(submitted, current) {
|
|
281
|
+
const field = submitted.transport === "http" ? "headers" : "env";
|
|
282
|
+
// A `{ secret }` reference is not the marker, so it passes through as written.
|
|
283
|
+
const values = submitted[field];
|
|
284
|
+
const kept = current && current.transport === submitted.transport
|
|
285
|
+
? current[field]
|
|
286
|
+
: {};
|
|
287
|
+
const out = {};
|
|
288
|
+
for (const [key, value] of Object.entries(values)) {
|
|
289
|
+
if (value !== KEPT_SECRET) {
|
|
290
|
+
out[key] = value;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (!Object.prototype.hasOwnProperty.call(kept, key)) {
|
|
294
|
+
throw unprocessable(`${field}.${key} is marked ${KEPT_SECRET}, but there is no saved value to keep. Type the value.`);
|
|
295
|
+
}
|
|
296
|
+
out[key] = kept[key];
|
|
297
|
+
}
|
|
298
|
+
return { ...submitted, [field]: out };
|
|
299
|
+
}
|
|
300
|
+
/* ------------------------------------------------------------ loosening */
|
|
301
|
+
const STRENGTH = { deny: 3, strip: 2, annotate: 1, accept: 0 };
|
|
302
|
+
/** Which way a tool-level override falls back, when it is removed. */
|
|
303
|
+
function fallbackFor(config, tool) {
|
|
304
|
+
if (config.namespace) {
|
|
305
|
+
const upstream = config.upstreams.find((u) => tool.startsWith(`${u.name}__`));
|
|
306
|
+
if (upstream?.on_injection)
|
|
307
|
+
return upstream.on_injection;
|
|
308
|
+
}
|
|
309
|
+
return config.on_injection;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Every way a change widens what this gateway lets through, in plain words.
|
|
313
|
+
*
|
|
314
|
+
* Each one needs `acknowledged.loosens`. They are the changes where a person
|
|
315
|
+
* clicking through a form could make the gateway quietly protect less: a
|
|
316
|
+
* weaker answer to a poisoned description, a renamed gateway or tool set that
|
|
317
|
+
* strands every switch and pin stored under the old names, and credentials or
|
|
318
|
+
* environment handed to a server that did not have them.
|
|
319
|
+
*/
|
|
320
|
+
export function gatewayLoosens(before, after) {
|
|
321
|
+
const out = [];
|
|
322
|
+
const weaker = (a, b) => (STRENGTH[b] ?? 0) < (STRENGTH[a] ?? 0);
|
|
323
|
+
if (weaker(before.on_injection, after.on_injection)) {
|
|
324
|
+
out.push(`hidden instructions in a tool description are handled with "${after.on_injection}" instead of "${before.on_injection}"`);
|
|
325
|
+
}
|
|
326
|
+
for (const u of after.upstreams) {
|
|
327
|
+
const was = before.upstreams.find((b) => b.name === u.name);
|
|
328
|
+
if (!was) {
|
|
329
|
+
// A new server is graded against the gateway-wide setting it would otherwise have had.
|
|
330
|
+
const b = u.on_injection ?? after.on_injection;
|
|
331
|
+
if (weaker(after.on_injection, b)) {
|
|
332
|
+
out.push(`new server "${u.name}" handles hidden instructions with "${b}" instead of "${after.on_injection}"`);
|
|
333
|
+
}
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const a = was.on_injection ?? before.on_injection;
|
|
337
|
+
const b = u.on_injection ?? after.on_injection;
|
|
338
|
+
if (weaker(a, b) && (was.on_injection !== undefined || u.on_injection !== undefined)) {
|
|
339
|
+
out.push(`"${u.name}" handles hidden instructions with "${b}" instead of "${a}"`);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
const tools = new Set([...Object.keys(before.injection_overrides), ...Object.keys(after.injection_overrides)]);
|
|
343
|
+
for (const tool of tools) {
|
|
344
|
+
const a = before.injection_overrides[tool] ?? fallbackFor(before, tool);
|
|
345
|
+
const b = after.injection_overrides[tool] ?? fallbackFor(after, tool);
|
|
346
|
+
if (weaker(a, b)) {
|
|
347
|
+
out.push(b === "accept"
|
|
348
|
+
? `"${tool}" keeps its description exactly as written, even where it looks like hidden instructions`
|
|
349
|
+
: `"${tool}" handles hidden instructions with "${b}" instead of "${a}"`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (before.name !== after.name) {
|
|
353
|
+
out.push(`renaming the gateway moves it to a new identity: tools switched off, pre-approvals and reviewed tool ` +
|
|
354
|
+
`changes are stored under the old name and stop applying`);
|
|
355
|
+
}
|
|
356
|
+
if (before.namespace !== after.namespace) {
|
|
357
|
+
out.push(`every tool is renamed, so tools switched off, rules naming a tool and reviewed tool changes stop applying`);
|
|
358
|
+
}
|
|
359
|
+
for (const u of after.upstreams) {
|
|
360
|
+
const was = before.upstreams.find((b) => b.name === u.name);
|
|
361
|
+
/*
|
|
362
|
+
* Compared by name, so a raw edit that reuses a server's name for a new
|
|
363
|
+
* destination lands here too: its kept-secret values are restored by name,
|
|
364
|
+
* and would otherwise follow it there unremarked.
|
|
365
|
+
*/
|
|
366
|
+
const destination = (x) => canonicalJson(x.transport === "http" ? { t: x.transport, url: x.url } : { t: x.transport, command: x.command, args: x.args });
|
|
367
|
+
const carries = u.transport === "http" ? Object.keys(u.headers).length > 0 : Object.keys(u.env).length > 0 || u.pass_env.length > 0;
|
|
368
|
+
if (was && carries && destination(was) !== destination(u)) {
|
|
369
|
+
out.push(`server "${u.name}" now points somewhere else and keeps its saved credentials`);
|
|
370
|
+
}
|
|
371
|
+
if (u.transport === "http" && u.credential_passthrough.enabled) {
|
|
372
|
+
const had = was?.transport === "http" && was.credential_passthrough.enabled;
|
|
373
|
+
if (!had)
|
|
374
|
+
out.push(`"${u.name}" is sent each caller's own credential (${u.credential_passthrough.header})`);
|
|
375
|
+
}
|
|
376
|
+
if (u.transport === "stdio") {
|
|
377
|
+
const had = new Set(was?.transport === "stdio" ? was.pass_env : []);
|
|
378
|
+
const added = u.pass_env.filter((n) => !had.has(n));
|
|
379
|
+
if (added.length > 0)
|
|
380
|
+
out.push(`"${u.name}" is given ${added.join(", ")} from the gateway's environment`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
function issues(error) {
|
|
386
|
+
return error.issues.map((i) => `${i.path.map(String).join(".") || "(root)"}: ${i.message}`).join("; ");
|
|
387
|
+
}
|
|
388
|
+
/** Parses and validates text as a gateway config, or says why it is not one. */
|
|
389
|
+
export function parseGatewayText(text) {
|
|
390
|
+
const doc = parseDocument(text);
|
|
391
|
+
if (doc.errors.length > 0)
|
|
392
|
+
throw unprocessable(`not valid YAML: ${doc.errors[0].message}`);
|
|
393
|
+
const parsed = GatewayConfigSchema.safeParse(doc.toJS());
|
|
394
|
+
if (!parsed.success)
|
|
395
|
+
throw unprocessable(`not a valid gateway config: ${issues(parsed.error)}`);
|
|
396
|
+
return parsed.data;
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* The guard on the guard.
|
|
400
|
+
*
|
|
401
|
+
* `policy_writes` and `policy_overrides` decide whether this console may write
|
|
402
|
+
* policy at all. A console that could change them would be granting itself
|
|
403
|
+
* permission, so no write from here may, in either direction -- tightening
|
|
404
|
+
* them is a reviewed edit to the file too.
|
|
405
|
+
*/
|
|
406
|
+
export function assertGuardsUnchanged(before, after) {
|
|
407
|
+
for (const key of GUARDED_SETTINGS) {
|
|
408
|
+
if (before[key] !== after[key]) {
|
|
409
|
+
throw new HttpError(403, "forbidden", `${key} cannot be changed from the console. It decides whether the console may change policy at ` +
|
|
410
|
+
`all, so a console that could change it would be giving itself permission. Edit gateway.yaml directly.`);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (canonicalJson(before.policy) !== canonicalJson(after.policy)) {
|
|
414
|
+
throw unprocessable(`this edit would change the policy (the "policy:" entry), which is not edited here. Change rules and ` +
|
|
415
|
+
`settings on the Protection settings page, where each change is checked.`);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* The one place a gateway.yaml is written from the console.
|
|
420
|
+
*
|
|
421
|
+
* `intended` is the caller's own assertion that nothing outside the part it
|
|
422
|
+
* meant to change has changed: a check on the parsed result rather than on the
|
|
423
|
+
* edit, so a Document API surprise cannot widen a write.
|
|
424
|
+
*/
|
|
425
|
+
export function commitGatewayText(args) {
|
|
426
|
+
const { file } = args;
|
|
427
|
+
if (args.expectedDigest !== file.digest) {
|
|
428
|
+
throw conflict("gateway.yaml changed since it was read. Reload it and make the change again, so nothing written in " +
|
|
429
|
+
"the meantime is overwritten.");
|
|
430
|
+
}
|
|
431
|
+
const after = parseGatewayText(args.text);
|
|
432
|
+
assertGuardsUnchanged(file.config, after);
|
|
433
|
+
const stray = args.intended?.(file.config, after) ?? null;
|
|
434
|
+
if (stray)
|
|
435
|
+
throw unprocessable(`refused: ${stray}`);
|
|
436
|
+
const loosens = gatewayLoosens(file.config, after);
|
|
437
|
+
if (loosens.length > 0 && !args.acknowledgedLoosens) {
|
|
438
|
+
throw unprocessable(`this change lets more through and needs confirming: ${loosens.join("; ")}`, { needs: "loosens", loosens });
|
|
439
|
+
}
|
|
440
|
+
writeAtomically(file.path, args.text);
|
|
441
|
+
return { before: file.config, after, previousDigest: file.digest, digest: digestText(args.text), loosens };
|
|
442
|
+
}
|
|
443
|
+
/** Every top-level key but these, canonicalised, for an "only this changed" check. */
|
|
444
|
+
export function sameExcept(before, after, keys) {
|
|
445
|
+
const strip = (c) => canonicalJson(Object.fromEntries(Object.entries(c).filter(([k]) => !keys.includes(k))));
|
|
446
|
+
return strip(before) === strip(after);
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* A line diff, for a preview, as a flat op/line list: the gateway editor's
|
|
450
|
+
* shape. The policy editor's diff is hunked instead -- see `lineDiff` in
|
|
451
|
+
* routes/policy.ts. Longest common subsequence, which is quadratic,
|
|
452
|
+
* so a pair of files too large for it falls back to "all removed, all added" --
|
|
453
|
+
* still correct, just less helpful.
|
|
454
|
+
*/
|
|
455
|
+
export function lineDiff(a, b) {
|
|
456
|
+
const x = a.split("\n");
|
|
457
|
+
const y = b.split("\n");
|
|
458
|
+
if (x.length * y.length > 4_000_000) {
|
|
459
|
+
return [...x.map((line) => ({ op: "-", line })), ...y.map((line) => ({ op: "+", line }))];
|
|
460
|
+
}
|
|
461
|
+
const n = x.length;
|
|
462
|
+
const m = y.length;
|
|
463
|
+
const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
|
464
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
465
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
466
|
+
lcs[i][j] = x[i] === y[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
const out = [];
|
|
470
|
+
let i = 0;
|
|
471
|
+
let j = 0;
|
|
472
|
+
while (i < n && j < m) {
|
|
473
|
+
if (x[i] === y[j]) {
|
|
474
|
+
out.push({ op: " ", line: x[i] });
|
|
475
|
+
i++;
|
|
476
|
+
j++;
|
|
477
|
+
}
|
|
478
|
+
else if (lcs[i + 1][j] >= lcs[i][j + 1])
|
|
479
|
+
out.push({ op: "-", line: x[i++] });
|
|
480
|
+
else
|
|
481
|
+
out.push({ op: "+", line: y[j++] });
|
|
482
|
+
}
|
|
483
|
+
while (i < n)
|
|
484
|
+
out.push({ op: "-", line: x[i++] });
|
|
485
|
+
while (j < m)
|
|
486
|
+
out.push({ op: "+", line: y[j++] });
|
|
487
|
+
return out;
|
|
488
|
+
}
|
|
489
|
+
/** A batch that changed nothing, for a policy that was not edited at all. */
|
|
490
|
+
export function unchangedBatch(text) {
|
|
491
|
+
return { text, loosens: [], changed: false, rulesAdded: [], rulesReplaced: [], rulesSkipped: [] };
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* ADAPTER for core's `applyPolicyBatch(policyText, changes)` (workstream A,
|
|
495
|
+
* core/src/policy-batch.ts). Until that lands this applies the changes itself
|
|
496
|
+
* through the yaml Document API, so comments and layout around them survive;
|
|
497
|
+
* at merge this body becomes a one-line call (translating `PolicyChange` if
|
|
498
|
+
* A's shape differs).
|
|
499
|
+
*/
|
|
500
|
+
export function applyPolicyChanges(policyText, changes, source = "policy.yaml") {
|
|
501
|
+
/*
|
|
502
|
+
* Core's batch edit does the work (comments survive; each rule is checked
|
|
503
|
+
* like any other console write; a rule a person wrote for the same tool
|
|
504
|
+
* wins over a pack's, and a new rule goes above the first rule that would
|
|
505
|
+
* otherwise catch its tool). This only maps the console's change list onto it.
|
|
506
|
+
*/
|
|
507
|
+
const egressAllowAdd = [];
|
|
508
|
+
const egressMethodsAdd = [];
|
|
509
|
+
const rules = [];
|
|
510
|
+
let localNetwork = false;
|
|
511
|
+
let plainHttp = false;
|
|
512
|
+
for (const change of changes) {
|
|
513
|
+
if (change.kind === "egress-allow")
|
|
514
|
+
egressAllowAdd.push(change.host);
|
|
515
|
+
else if (change.kind === "egress-method")
|
|
516
|
+
egressMethodsAdd.push(change.method.toUpperCase());
|
|
517
|
+
else if (change.kind === "egress-local-network")
|
|
518
|
+
localNetwork = true;
|
|
519
|
+
else if (change.kind === "egress-plain-http")
|
|
520
|
+
plainHttp = true;
|
|
521
|
+
else
|
|
522
|
+
rules.push(change.rule);
|
|
523
|
+
}
|
|
524
|
+
try {
|
|
525
|
+
const result = applyPolicyBatch(policyText, {
|
|
526
|
+
egressAllowAdd,
|
|
527
|
+
egressMethodsAdd,
|
|
528
|
+
...(localNetwork
|
|
529
|
+
? { egress: { block_private_ips: false, allow_http: true, allow_ip_literals: true } }
|
|
530
|
+
: plainHttp
|
|
531
|
+
? { egress: { allow_http: true } }
|
|
532
|
+
: {}),
|
|
533
|
+
rules
|
|
534
|
+
});
|
|
535
|
+
/*
|
|
536
|
+
* Core names a rule by its id ("pack-filesystem-write_file"), twice; a
|
|
537
|
+
* person deciding whether to confirm needs the tool it lets through. Keep
|
|
538
|
+
* core's sentences for the network, and say the rule ones by tool.
|
|
539
|
+
*/
|
|
540
|
+
const added = new Set([...result.rulesAdded, ...result.rulesReplaced]);
|
|
541
|
+
const loosens = result.loosens.filter((line) => !/^(new )?rule "/.test(line));
|
|
542
|
+
for (const rule of rules) {
|
|
543
|
+
if (added.has(rule.id) && rule.decision === "allow" && rule.effect !== "read") {
|
|
544
|
+
// The match is "<server>__<tool>"; the person knows the tool by its own name.
|
|
545
|
+
const sep = rule.match.indexOf("__");
|
|
546
|
+
const tool = sep >= 0 ? rule.match.slice(sep + 2) : rule.match;
|
|
547
|
+
loosens.push(`“${tool}” runs without asking you, even when protection is on`);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if ((localNetwork || plainHttp) && result.changed) {
|
|
551
|
+
loosens.push("This applies to every server your toolbox reaches over the network, not only this one");
|
|
552
|
+
}
|
|
553
|
+
return {
|
|
554
|
+
text: result.text,
|
|
555
|
+
loosens,
|
|
556
|
+
changed: result.changed,
|
|
557
|
+
rulesAdded: result.rulesAdded,
|
|
558
|
+
rulesReplaced: result.rulesReplaced,
|
|
559
|
+
rulesSkipped: result.rulesSkipped
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
catch (err) {
|
|
563
|
+
throw unprocessable(`the policy changes for this server could not be made to ${source}: ${err.message}`);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* The refusal for a toolbox with `policy_overrides: false`, which lets the
|
|
568
|
+
* console tighten its policy but never loosen it -- the same line core's
|
|
569
|
+
* `writePolicyBatch` holds. Acknowledging would not change the answer, so
|
|
570
|
+
* this carries no `needs: "loosens"`: the page must not offer a confirm
|
|
571
|
+
* button that can only fail. Throws when `loosens` is not empty.
|
|
572
|
+
*/
|
|
573
|
+
export function refuseIfOverridesOff(config, loosens) {
|
|
574
|
+
if (config.policy_overrides !== false || loosens.length === 0)
|
|
575
|
+
return;
|
|
576
|
+
throw unprocessable("This toolbox is set so the console can't loosen its protection, and this would: " +
|
|
577
|
+
`${loosens.join("; ")}. Nothing was saved. Whoever looks after this toolbox can make the change in its ` +
|
|
578
|
+
"policy.yaml (it has policy_overrides: false in its gateway.yaml), or you can add the server to another toolbox.", { problem: "overrides-off", loosens: [...loosens] });
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* policy.yaml without the rules the console or a pack wrote for one server:
|
|
582
|
+
* ids starting `pack-` or `console-` whose `match` names a tool of that
|
|
583
|
+
* server (`<upstream>__...`). Removing a server otherwise leaves them behind,
|
|
584
|
+
* deciding tools that no longer exist -- and deciding them again, unseen, for
|
|
585
|
+
* a different server later added under the same name.
|
|
586
|
+
*
|
|
587
|
+
* A rule a person wrote is never touched, and neither is `egress`: another
|
|
588
|
+
* server may share an address. Edited through the Document API so comments
|
|
589
|
+
* survive, and checked to have removed exactly those rules.
|
|
590
|
+
*/
|
|
591
|
+
export function removeRulesWrittenFor(policyText, upstream) {
|
|
592
|
+
const doc = parseDocument(policyText);
|
|
593
|
+
if (doc.errors.length > 0)
|
|
594
|
+
throw new Error(`the policy is not valid YAML: ${doc.errors[0].message}`);
|
|
595
|
+
const seq = doc.get("rules", true);
|
|
596
|
+
if (!isSeq(seq))
|
|
597
|
+
return { text: policyText, removed: [] };
|
|
598
|
+
const removed = [];
|
|
599
|
+
for (let i = seq.items.length - 1; i >= 0; i--) {
|
|
600
|
+
const item = seq.items[i];
|
|
601
|
+
if (!isMap(item))
|
|
602
|
+
continue;
|
|
603
|
+
const id = item.get("id");
|
|
604
|
+
const match = item.get("match");
|
|
605
|
+
if (typeof id !== "string" || typeof match !== "string")
|
|
606
|
+
continue;
|
|
607
|
+
if (!(id.startsWith("pack-") || id.startsWith("console-")) || !match.startsWith(`${upstream}__`))
|
|
608
|
+
continue;
|
|
609
|
+
/*
|
|
610
|
+
* The note written above a console rule ("Set from the console by ...:
|
|
611
|
+
* run it without asking") goes with it. Left behind, it reads as a live
|
|
612
|
+
* allow rule with nothing under it. The first item's note is parsed onto
|
|
613
|
+
* the list itself; anything there not written by the console stays.
|
|
614
|
+
*/
|
|
615
|
+
if (i === 0 && seq.commentBefore && /Set from the console|ready-made/i.test(seq.commentBefore))
|
|
616
|
+
seq.commentBefore = undefined;
|
|
617
|
+
seq.items.splice(i, 1);
|
|
618
|
+
removed.unshift(id);
|
|
619
|
+
}
|
|
620
|
+
if (removed.length === 0)
|
|
621
|
+
return { text: policyText, removed };
|
|
622
|
+
const text = doc.toString({ lineWidth: 0 });
|
|
623
|
+
const before = parsePolicy(parseDocument(policyText).toJS(), "policy.yaml");
|
|
624
|
+
const after = parsePolicy(parseDocument(text).toJS(), "the edited policy");
|
|
625
|
+
const gone = new Set(removed);
|
|
626
|
+
if (canonicalJson({ ...before, rules: before.rules.filter((r) => !gone.has(r.id)) }) !== canonicalJson(after)) {
|
|
627
|
+
throw new Error("the edit changed something other than those rules");
|
|
628
|
+
}
|
|
629
|
+
return { text, removed };
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Whether the egress guard refuses this host unless private addresses are
|
|
633
|
+
* allowed: `localhost`, and any literal in loopback, link-local or private
|
|
634
|
+
* space. The same test adopt-plan.ts makes.
|
|
635
|
+
*/
|
|
636
|
+
export function isLocalHost(hostname) {
|
|
637
|
+
const bare = hostname.replace(/^\[|\]$/g, "");
|
|
638
|
+
if (bare === "localhost" || bare.endsWith(".localhost"))
|
|
639
|
+
return true;
|
|
640
|
+
if (!isIpLiteral(bare))
|
|
641
|
+
return false;
|
|
642
|
+
return classifyAddress(bare).blocked;
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* The allow-list entry for one server: its host, with its port when the
|
|
646
|
+
* address names one, so allowing a server on :3845 does not open every other
|
|
647
|
+
* port on that host. An IPv6 literal stays bare -- `::1:3845` cannot be told
|
|
648
|
+
* apart from an address -- which is the old, wider behaviour for that case only.
|
|
649
|
+
*/
|
|
650
|
+
function allowEntryFor(url) {
|
|
651
|
+
const bare = url.hostname.replace(/^\[|\]$/g, "");
|
|
652
|
+
return url.port && !bare.includes(":") ? `${bare}:${url.port}` : bare;
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* The changes an upstream needs for its own address, before any rule pack.
|
|
656
|
+
*
|
|
657
|
+
* The one place this is worked out: Test it's scratch policy and install both
|
|
658
|
+
* call it, so what is saved is what was tested. A server on this computer or
|
|
659
|
+
* the local network needs the guard's private-address, bare-IP and plain-http
|
|
660
|
+
* protections off; one on a public host reached over plain http needs only
|
|
661
|
+
* plain http. `localNetwork` is what the draft found (a private address);
|
|
662
|
+
* it can only add to what the address itself says, never take it away.
|
|
663
|
+
*/
|
|
664
|
+
export function egressChangesFor(upstream, options = {}) {
|
|
665
|
+
if (upstream.transport !== "http")
|
|
666
|
+
return [];
|
|
667
|
+
const url = new URL(upstream.url);
|
|
668
|
+
const out = [
|
|
669
|
+
{ kind: "egress-allow", host: allowEntryFor(url) },
|
|
670
|
+
{ kind: "egress-method", method: "POST" }
|
|
671
|
+
];
|
|
672
|
+
if (options.localNetwork === true || isLocalHost(url.hostname))
|
|
673
|
+
out.push({ kind: "egress-local-network" });
|
|
674
|
+
else if (url.protocol === "http:")
|
|
675
|
+
out.push({ kind: "egress-plain-http" });
|
|
676
|
+
return out;
|
|
677
|
+
}
|
|
678
|
+
/** The rows of gateway processes still beating, newest heartbeat first. */
|
|
679
|
+
export function liveRows(store, component, now = Date.now()) {
|
|
680
|
+
const read = store.readLiveState;
|
|
681
|
+
if (typeof read !== "function")
|
|
682
|
+
return [];
|
|
683
|
+
return read
|
|
684
|
+
.call(store, component)
|
|
685
|
+
.filter((r) => now - Date.parse(r.heartbeat_at) <= LIVE_STATE_STALE_MS)
|
|
686
|
+
.sort((a, b) => Date.parse(b.heartbeat_at) - Date.parse(a.heartbeat_at));
|
|
687
|
+
}
|
|
688
|
+
/** Asks running gateways to retry one server now. False when the store cannot take requests. */
|
|
689
|
+
export function requestRetry(store, component, upstream) {
|
|
690
|
+
const request = store.requestLive;
|
|
691
|
+
if (typeof request !== "function")
|
|
692
|
+
return false;
|
|
693
|
+
request.call(store, component, upstream, "retry");
|
|
694
|
+
return true;
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* A gateway's refusal in words a person can act on. The gateway writes for a
|
|
698
|
+
* log ("gateway.yaml changed connect_timeout_ms, which a running gateway cannot
|
|
699
|
+
* pick up..."); the console shows this instead, with the setting's own name
|
|
700
|
+
* kept in brackets for whoever wants to look it up.
|
|
701
|
+
*/
|
|
702
|
+
export function plainRefusal(refusal) {
|
|
703
|
+
const changed = /^gateway\.yaml changed (.+?), which a running gateway cannot pick up/.exec(refusal);
|
|
704
|
+
if (changed) {
|
|
705
|
+
const serversMove = /The servers were updated|Server changes are still applied/.test(refusal);
|
|
706
|
+
return (`Your AI app is still using the toolbox as it was before a setting changed (${changed[1]}). ` +
|
|
707
|
+
`That setting only takes effect when the app starts` +
|
|
708
|
+
(serversMove ? `. Servers you add or change still reach the app straight away. ` : `, and nothing else you change reaches the app until then. `) +
|
|
709
|
+
`Quit the app completely and open it again.`);
|
|
710
|
+
}
|
|
711
|
+
const broken = /^gateway\.yaml could not be used[^:]*: (.*)$/s.exec(refusal);
|
|
712
|
+
if (broken) {
|
|
713
|
+
return `The toolbox's settings file has a mistake in it, so your AI app kept using the settings from before. Fix the file and save it again. (${broken[1]})`;
|
|
714
|
+
}
|
|
715
|
+
return refusal;
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Whether a gateway's published refusal can only be cleared by a restart.
|
|
719
|
+
* A file that did not parse ("could not be used") is cleared by the next good
|
|
720
|
+
* write, so it does not count; a change outside `upstreams` does.
|
|
721
|
+
*/
|
|
722
|
+
export function refusalNeedsRestart(refusal) {
|
|
723
|
+
if (!refusal)
|
|
724
|
+
return false;
|
|
725
|
+
return !/^gateway\.yaml could not be used/.test(refusal);
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Whether that refusal also holds back changes to the servers. A gateway that
|
|
729
|
+
* carries server changes past a standing refusal says so ("The servers were
|
|
730
|
+
* updated"); one that does not refuses the whole file.
|
|
731
|
+
*/
|
|
732
|
+
export function refusalBlocksServers(refusal) {
|
|
733
|
+
return refusalNeedsRestart(refusal) && !/The servers were updated|Server changes are still applied/.test(refusal);
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* What a write to gateway.yaml means for what is running.
|
|
737
|
+
*
|
|
738
|
+
* Only `upstreams` changes are applied live, and only by a gateway with
|
|
739
|
+
* `upstream_reload` on; anything else waits for its next start. `running`
|
|
740
|
+
* covers a gateway from before live state existed, which announces itself but
|
|
741
|
+
* writes no live rows: it can only pick the change up by restarting.
|
|
742
|
+
*/
|
|
743
|
+
export function applyStateFor(args) {
|
|
744
|
+
if (args.rows.length === 0)
|
|
745
|
+
return args.running ? "needs-restart" : "not-running";
|
|
746
|
+
if (!args.upstreamsOnly || !args.upstreamReload)
|
|
747
|
+
return "needs-restart";
|
|
748
|
+
/*
|
|
749
|
+
* A running gateway already refused an earlier change it can only take at
|
|
750
|
+
* start (a timeout, the namespace...). Until it restarts, the file it is
|
|
751
|
+
* handed still differs from what it runs outside `upstreams`, so this
|
|
752
|
+
* write, however small, is refused with it: answering "pending" would
|
|
753
|
+
* leave the person waiting for a server that never appears.
|
|
754
|
+
*/
|
|
755
|
+
if (args.rows.some((r) => r.config_digest !== args.digest && refusalBlocksServers(r.refusal)))
|
|
756
|
+
return "needs-restart";
|
|
757
|
+
if (args.rows.every((r) => r.config_digest === args.digest))
|
|
758
|
+
return "live";
|
|
759
|
+
return "pending";
|
|
760
|
+
}
|