hmcp-web 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/api.d.ts +11 -0
- package/dist/api.js +64 -10
- package/dist/model/app-servers.d.ts +85 -0
- package/dist/model/app-servers.js +109 -0
- package/dist/model/import-record.d.ts +80 -0
- package/dist/model/import-record.js +179 -0
- package/dist/model/metrics.js +16 -1
- package/dist/routes/connect-import.d.ts +9 -0
- package/dist/routes/connect-import.js +594 -0
- package/dist/routes/connect.d.ts +36 -0
- package/dist/routes/connect.js +71 -13
- package/dist/routes/github.d.ts +97 -0
- package/dist/routes/github.js +587 -0
- package/dist/routes/guard.d.ts +3 -0
- package/dist/routes/guard.js +166 -0
- package/dist/routes/runtime.d.ts +6 -0
- package/dist/routes/runtime.js +1 -1
- package/dist/routes/servers-add.d.ts +8 -0
- package/dist/routes/servers-add.js +2 -2
- package/dist-ui/assets/{Activity-BqKGpXMN.js → Activity-CZ78RyRO.js} +1 -1
- package/dist-ui/assets/Approvals-DPIlNZsv.js +1 -0
- package/dist-ui/assets/AttachApp-DjSeWCbS.js +5 -0
- package/dist-ui/assets/Connections-qcA96lXh.js +2 -0
- package/dist-ui/assets/{Gallery-B39L2Yma.js → Gallery-DB_OO7Vw.js} +1 -1
- package/dist-ui/assets/{PreApprovals-BsIhjMqb.js → PreApprovals-C4cKajcK.js} +1 -1
- package/dist-ui/assets/{Protection-DlB09ABa.js → Protection-B8h-5YAb.js} +1 -1
- package/dist-ui/assets/{Safety-CN-oHO2h.js → Safety-BQqHyYdo.js} +1 -1
- package/dist-ui/assets/{Settings-BLD7G1Ag.js → Settings-Cx50zZSt.js} +1 -1
- package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
- package/dist-ui/assets/{Suggestions-Dp7pofcs.js → Suggestions-CRo5UOTT.js} +1 -1
- package/dist-ui/assets/Tools-xo39lPKB.js +4 -0
- package/dist-ui/assets/index-DttDjRpu.js +16 -0
- package/dist-ui/assets/index-QeJyD5z2.css +2 -0
- package/dist-ui/assets/{kit-DQ7Oxf5n.js → kit-DRVm92_t.js} +1 -1
- package/dist-ui/index.html +3 -3
- package/package.json +4 -4
- package/dist-ui/assets/Approvals-Qo7bCcli.js +0 -1
- package/dist-ui/assets/AttachApp-0zRSPgSY.js +0 -5
- package/dist-ui/assets/Connections-CE0JGe8c.js +0 -2
- package/dist-ui/assets/StartPage-HuZSnmSr.js +0 -1
- package/dist-ui/assets/Tools-Bfot3bx5.js +0 -4
- package/dist-ui/assets/index-Khp0l1zp.js +0 -16
- package/dist-ui/assets/index-Ylyt4DEr.css +0 -2
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { parse as parseYaml, parseDocument } from "yaml";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { SecretStore, decide, expandPath, globMatch, parsePolicy, readRegistry, resolveEffect, writeAtomically } from "hmcp-core";
|
|
6
|
+
import { ClientConfigError, GITHUB_HOSTED_READONLY_URL, GITHUB_HOSTED_URL, claudeCodeSettingsPath, closeClaudeCodeGithub, confirmGithubDoor, githubChangeTools, githubDoors, githubHostedAccess, githubReadonlyHeader, isGithubUpstream, loadPacks, projectSettingsIgnored, reopenClaudeCodeGithub } from "hmcp-gateway";
|
|
7
|
+
import { HttpError, badRequest, conflict, notFound, route, unprocessable } from "../http.js";
|
|
8
|
+
import { applyPolicyChanges, commitGatewayText, readGatewayFile, sameExcept } from "../model/gateway-config.js";
|
|
9
|
+
import { packRulesFor, runProbe, scratchPolicy, withProbeSlot } from "../model/probe.js";
|
|
10
|
+
import { loadServer, scopedFor, storeFor } from "../model/server.js";
|
|
11
|
+
import { gatewayAudit, projectDirOf, record } from "./connect.js";
|
|
12
|
+
/** The same test "Test it" runs: this toolbox's policy with the server's address allowed, the real locked keys. */
|
|
13
|
+
const defaultProbe = (spec, server) => withProbeSlot(() => runProbe(spec, { policy: scratchPolicy(server.policy, spec, false), secrets: new SecretStore(), cwd: server.cwd }));
|
|
14
|
+
const ClaudeCodeBody = z
|
|
15
|
+
.object({
|
|
16
|
+
scope: z.enum(["user", "project"]),
|
|
17
|
+
projectDir: z.string().min(1).optional(),
|
|
18
|
+
close: z.boolean(),
|
|
19
|
+
confirm: z.literal(true)
|
|
20
|
+
})
|
|
21
|
+
.strict();
|
|
22
|
+
const ConfirmBody = z.object({ door: z.string().min(1).max(64), done: z.boolean() }).strict();
|
|
23
|
+
const ChangesBody = z.object({ allow: z.boolean(), expectedDigest: z.string().min(1), confirm: z.literal(true) }).strict();
|
|
24
|
+
function parse(schema, body) {
|
|
25
|
+
const result = schema.safeParse(body ?? {});
|
|
26
|
+
if (!result.success) {
|
|
27
|
+
throw badRequest("the request body is not valid", result.error.issues.map((i) => ({ path: i.path.join(".") || "(root)", message: i.message })));
|
|
28
|
+
}
|
|
29
|
+
return result.data;
|
|
30
|
+
}
|
|
31
|
+
const exposedName = (server, upstream, tool) => server.gateway.config.namespace ? `${upstream}__${tool}` : tool;
|
|
32
|
+
/**
|
|
33
|
+
* A stand-in tenant for grading. A toolbox that requires a tenant refuses
|
|
34
|
+
* every call that names none, so `decide()` without one answers "deny" for
|
|
35
|
+
* every tool and hides what the rules and the posture say. Rules carry no
|
|
36
|
+
* tenant of their own, so one stand-in value reaches the same answer the
|
|
37
|
+
* gateway gives every tenant it serves.
|
|
38
|
+
*/
|
|
39
|
+
const STAND_IN_TENANT = "hmcp-console-grading";
|
|
40
|
+
/** How a tool is decided under a policy, past its tenant check. */
|
|
41
|
+
function judge(policy, tool, effect) {
|
|
42
|
+
return decide({ tool, effect, policy, argsUnknown: true, ...(policy.tenant ? { tenant: { expected: STAND_IN_TENANT } } : {}) }).kind;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The last tool list this console got from a toolbox's GitHub server: from
|
|
46
|
+
* "Check it works", or from the switch. `tools: null` means "the address
|
|
47
|
+
* changed and the list isn't known since". In memory only: after a restart,
|
|
48
|
+
* the toolbox's own published list is the source.
|
|
49
|
+
*/
|
|
50
|
+
const lastListed = new Map();
|
|
51
|
+
const listedKey = (gatewayId, upstream) => `${gatewayId}\0${upstream}`;
|
|
52
|
+
export function rememberListed(gatewayId, upstream, outcome) {
|
|
53
|
+
lastListed.set(listedKey(gatewayId, upstream), {
|
|
54
|
+
at: Date.now(),
|
|
55
|
+
tools: outcome?.ok
|
|
56
|
+
? outcome.tools.map((t) => ({ name: t.name, exposedName: t.exposedName, effect: t.effect === "unknown" ? undefined : t.effect }))
|
|
57
|
+
: null
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/** The approvals store, only when its file already exists: reading the doors must never create one. */
|
|
61
|
+
function existingStore(server) {
|
|
62
|
+
return existsSync(server.storePath) ? storeFor(server) : null;
|
|
63
|
+
}
|
|
64
|
+
/** The newest tool list known for one upstream: the console's own, or what the running toolbox published. */
|
|
65
|
+
function knownTools(server, gatewayId, upstream) {
|
|
66
|
+
const mine = lastListed.get(listedKey(gatewayId, upstream));
|
|
67
|
+
let published = null;
|
|
68
|
+
try {
|
|
69
|
+
const rows = (existingStore(server)?.inventory(server.component) ?? []).filter((r) => r.upstream === upstream);
|
|
70
|
+
if (rows.length > 0) {
|
|
71
|
+
const prefix = server.gateway.config.namespace ? `${upstream}__` : "";
|
|
72
|
+
published = {
|
|
73
|
+
at: Math.max(...rows.map((r) => r.discovered_at)),
|
|
74
|
+
tools: rows.map((r) => ({
|
|
75
|
+
name: r.tool.startsWith(prefix) ? r.tool.slice(prefix.length) : r.tool,
|
|
76
|
+
exposedName: r.tool,
|
|
77
|
+
effect: r.effect ?? undefined
|
|
78
|
+
}))
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
published = null;
|
|
84
|
+
}
|
|
85
|
+
if (mine && (!published || mine.at >= published.at))
|
|
86
|
+
return mine.tools;
|
|
87
|
+
return published?.tools ?? null;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* What a change would meet, graded over the tools the server really lists:
|
|
91
|
+
* every one that isn't a read is a change tool. With no list yet, it says
|
|
92
|
+
* so ("unchecked") rather than guess from the pack's names, most of which
|
|
93
|
+
* a given release of GitHub's server doesn't use.
|
|
94
|
+
*/
|
|
95
|
+
export function changeState(server, gatewayId, upstream) {
|
|
96
|
+
const policy = server.policy;
|
|
97
|
+
const posture = policy.defaults.mode;
|
|
98
|
+
const known = knownTools(server, gatewayId, upstream);
|
|
99
|
+
const changes = (known ?? []).filter((t) => (resolveEffect({ tool: t.exposedName, effect: t.effect, policy }) ?? null) !== "read");
|
|
100
|
+
let preApproved = false;
|
|
101
|
+
try {
|
|
102
|
+
// The toolbox's own pre-approvals (the default tenant's).
|
|
103
|
+
preApproved = (existingStore(server) ? scopedFor(server, "").listGrants({ activeOnly: true }) : []).some((g) => changes.some((t) => globMatch(g.tool_match, t.exposedName)));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
preApproved = false;
|
|
107
|
+
}
|
|
108
|
+
if (policy.enforcement === "observe")
|
|
109
|
+
return { kind: "observe", posture, preApproved };
|
|
110
|
+
if (known === null)
|
|
111
|
+
return { kind: "unchecked", posture, preApproved };
|
|
112
|
+
if (changes.length === 0)
|
|
113
|
+
return { kind: "no-changes", posture, preApproved };
|
|
114
|
+
const kinds = changes.map((t) => ({ name: t.name, kind: judge(policy, t.exposedName, t.effect) }));
|
|
115
|
+
const runs = kinds.filter((k) => k.kind === "allow").map((k) => k.name);
|
|
116
|
+
const refused = kinds.filter((k) => k.kind === "deny").map((k) => k.name);
|
|
117
|
+
if (runs.length > 0)
|
|
118
|
+
return { kind: "runs", posture, preApproved, tools: runs };
|
|
119
|
+
if (refused.length === kinds.length)
|
|
120
|
+
return { kind: "refused", posture, preApproved };
|
|
121
|
+
if (refused.length > 0)
|
|
122
|
+
return { kind: "partly-refused", posture, preApproved, tools: refused };
|
|
123
|
+
return { kind: "waits", posture, preApproved };
|
|
124
|
+
}
|
|
125
|
+
function githubServers(options) {
|
|
126
|
+
const out = [];
|
|
127
|
+
for (const entry of readRegistry(options.registryPath).servers) {
|
|
128
|
+
if (entry.kind !== "gateway")
|
|
129
|
+
continue;
|
|
130
|
+
const configPath = expandPath(entry.config_path);
|
|
131
|
+
try {
|
|
132
|
+
const file = readGatewayFile(configPath);
|
|
133
|
+
// Only a toolbox with a GitHub server is loaded at all.
|
|
134
|
+
if (!file.config.upstreams.some(isGithubUpstream))
|
|
135
|
+
continue;
|
|
136
|
+
let server = null;
|
|
137
|
+
try {
|
|
138
|
+
server = loadServer(entry);
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
server = null;
|
|
142
|
+
}
|
|
143
|
+
for (const u of file.config.upstreams) {
|
|
144
|
+
if (!isGithubUpstream(u))
|
|
145
|
+
continue;
|
|
146
|
+
out.push({
|
|
147
|
+
gatewayId: entry.id,
|
|
148
|
+
gatewayLabel: entry.label,
|
|
149
|
+
configPath,
|
|
150
|
+
upstream: u.name,
|
|
151
|
+
access: githubHostedAccess(u),
|
|
152
|
+
digest: file.digest,
|
|
153
|
+
changes: server ? changeState(server, entry.id, u.name) : null
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
// A toolbox that can't be read is shown as broken on its own card.
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
/* ------------------------------------------------- the switch's loosening check */
|
|
164
|
+
const STRICT = { allow: 0, approve: 1, deny: 2 };
|
|
165
|
+
/**
|
|
166
|
+
* The tools whose decision is less strict under `after` than under `before`
|
|
167
|
+
* (deny → approve or allow, approve → allow). The same posture, enforcement
|
|
168
|
+
* and tenant hold in both, since only rules are added, so any difference is
|
|
169
|
+
* the rules'. A pack rule placed above a rule the person wrote would show
|
|
170
|
+
* here, which is the case this exists for.
|
|
171
|
+
*/
|
|
172
|
+
export function loosenedTools(before, after, tools) {
|
|
173
|
+
const out = [];
|
|
174
|
+
for (const t of tools) {
|
|
175
|
+
const { name, effect } = typeof t === "string" ? { name: t, effect: undefined } : t;
|
|
176
|
+
const was = judge(before, name, effect);
|
|
177
|
+
const now = judge(after, name, effect);
|
|
178
|
+
if (STRICT[now] < STRICT[was])
|
|
179
|
+
out.push(name);
|
|
180
|
+
}
|
|
181
|
+
return [...new Set(out)];
|
|
182
|
+
}
|
|
183
|
+
function doorsView(options, projectDir) {
|
|
184
|
+
return {
|
|
185
|
+
projectDir,
|
|
186
|
+
doors: githubDoors({ home: homedir(), cwd: projectDir, env: process.env }),
|
|
187
|
+
servers: githubServers(options)
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function entryById(options, id) {
|
|
191
|
+
const found = readRegistry(options.registryPath).servers.find((s) => s.id === id);
|
|
192
|
+
if (!found)
|
|
193
|
+
throw notFound(`no registered server with id "${id}"`);
|
|
194
|
+
return found;
|
|
195
|
+
}
|
|
196
|
+
function serverById(options, id) {
|
|
197
|
+
try {
|
|
198
|
+
return loadServer(entryById(options, id));
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
if (err instanceof HttpError)
|
|
202
|
+
throw err;
|
|
203
|
+
throw unprocessable(`server "${id}" could not be loaded: ${err.message}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
export const KEY_NOTE = "If GitHub refuses a change, your key needs Read and write on Contents, Issues and Pull requests. " +
|
|
207
|
+
"You can change that at https://github.com/settings/personal-access-tokens.";
|
|
208
|
+
/** A probe's failure in words a person can act on. The message never holds a secret (see UpstreamProblem). */
|
|
209
|
+
function connectFailure(outcome) {
|
|
210
|
+
const problem = outcome.problem;
|
|
211
|
+
if (problem?.code === "auth-rejected")
|
|
212
|
+
return "GitHub didn't accept the key. Replace the key in this server's settings and check again.";
|
|
213
|
+
return `It didn't connect${problem?.message ? `: ${problem.message}` : "."}`;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The first word of a tool's name is a verb that changes something. GitHub's
|
|
217
|
+
* tools are named verb first (`star_repository`, `request_copilot_review`), so
|
|
218
|
+
* only the first word is read: `get_pull_request` is a read.
|
|
219
|
+
*/
|
|
220
|
+
const CHANGE_VERBS = new Set(("create update delete remove write push merge star unstar request assign unassign add edit set close reopen fork " +
|
|
221
|
+
"dismiss submit approve lock unlock transfer rename archive unarchive enable disable run rerun cancel trigger upload " +
|
|
222
|
+
"move resolve comment label mark publish revert post send invite accept reject").split(" "));
|
|
223
|
+
const firstWord = (name) => (name.split(/[_.-]|(?=[A-Z])/)[0] ?? "").toLowerCase();
|
|
224
|
+
/**
|
|
225
|
+
* Whether the toolbox side works: the server connects, it offers tools that
|
|
226
|
+
* make changes, and how every tool it lists is decided under the policy as it
|
|
227
|
+
* is now. Green only when every tool that isn't a read waits for the person
|
|
228
|
+
* (or is refused, which is said in so many words). Whether the key itself may
|
|
229
|
+
* write can only be known from a call.
|
|
230
|
+
*/
|
|
231
|
+
export function checkLines(outcome, upstream, policy) {
|
|
232
|
+
if (!outcome.ok)
|
|
233
|
+
return [{ ok: false, text: connectFailure(outcome) }];
|
|
234
|
+
const lines = [{ ok: true, text: "The GitHub server connects." }];
|
|
235
|
+
if (githubHostedAccess(upstream) === "readonly") {
|
|
236
|
+
lines.push({ ok: false, text: "It can only look: it is set to GitHub's read-only access. Switch on “Let Claude change GitHub through hmcp” first." });
|
|
237
|
+
return lines;
|
|
238
|
+
}
|
|
239
|
+
const ruleReads = [];
|
|
240
|
+
const guessedReads = [];
|
|
241
|
+
const misread = [];
|
|
242
|
+
const waits = [];
|
|
243
|
+
const refused = [];
|
|
244
|
+
const runs = [];
|
|
245
|
+
const unclassified = [];
|
|
246
|
+
for (const tool of outcome.tools) {
|
|
247
|
+
const given = tool.effect === "unknown" ? undefined : tool.effect;
|
|
248
|
+
const fromRule = resolveEffect({ tool: tool.exposedName, policy });
|
|
249
|
+
const effect = fromRule ?? given ?? null;
|
|
250
|
+
if (effect === "read") {
|
|
251
|
+
if (CHANGE_VERBS.has(firstWord(tool.name)))
|
|
252
|
+
misread.push(tool.name);
|
|
253
|
+
else if (fromRule === "read")
|
|
254
|
+
ruleReads.push(tool.name);
|
|
255
|
+
else
|
|
256
|
+
guessedReads.push(tool.name);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const kind = judge(policy, tool.exposedName, given);
|
|
260
|
+
if (effect === null)
|
|
261
|
+
unclassified.push({ name: tool.name, kind });
|
|
262
|
+
if (kind === "allow")
|
|
263
|
+
runs.push(tool.name);
|
|
264
|
+
else if (kind === "deny")
|
|
265
|
+
refused.push(tool.name);
|
|
266
|
+
else
|
|
267
|
+
waits.push(tool.name);
|
|
268
|
+
}
|
|
269
|
+
const changes = [...waits, ...refused, ...runs];
|
|
270
|
+
if (changes.length === 0 && misread.length === 0) {
|
|
271
|
+
lines.push({ ok: false, text: "It offers no tools that make changes, so Claude can't change GitHub through hmcp." });
|
|
272
|
+
return lines;
|
|
273
|
+
}
|
|
274
|
+
if (changes.length > 0) {
|
|
275
|
+
lines.push({
|
|
276
|
+
ok: true,
|
|
277
|
+
text: `It offers ${changes.length} tool${changes.length === 1 ? "" : "s"} that make changes, such as ${changes.slice(0, 3).join(", ")}.`
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
if (policy.enforcement === "observe") {
|
|
281
|
+
lines.push({ ok: false, text: "Your toolbox is only watching, so changes would run without asking you. Turn protection on in its settings." });
|
|
282
|
+
}
|
|
283
|
+
if (runs.length > 0) {
|
|
284
|
+
lines.push({ ok: false, text: `These run without asking you: ${runs.join(", ")}. Change them to “Ask me first” on the Tools page.` });
|
|
285
|
+
}
|
|
286
|
+
if (misread.length > 0) {
|
|
287
|
+
lines.push({
|
|
288
|
+
ok: false,
|
|
289
|
+
text: `These are treated as only looking, but the name says it changes something: ${misread.join(", ")}. Set them to “Ask me first” on the Tools page.`
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
if (unclassified.length > 0) {
|
|
293
|
+
const how = (k) => (k === "allow" ? "runs without asking" : k === "deny" ? "is refused" : "asks you first");
|
|
294
|
+
lines.push({
|
|
295
|
+
ok: unclassified.every((u) => u.kind !== "allow"),
|
|
296
|
+
text: `These aren't classified, so your toolbox's settings decide them: ${unclassified.map((u) => `${u.name} (${how(u.kind)})`).join(", ")}.`
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
if (refused.length > 0) {
|
|
300
|
+
lines.push({ ok: true, text: `These changes are refused under your toolbox's settings, so Claude can't make them: ${refused.join(", ")}.` });
|
|
301
|
+
}
|
|
302
|
+
if (guessedReads.length > 0) {
|
|
303
|
+
lines.push({
|
|
304
|
+
ok: true,
|
|
305
|
+
text: `Treated as only looking because of the name or the server's own label, so they run without asking: ${guessedReads.join(", ")}.`
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
if (waits.length > 0 && runs.length === 0 && misread.length === 0 && policy.enforcement !== "observe") {
|
|
309
|
+
lines.push({ ok: true, text: refused.length > 0 ? "Every other change waits for you to say yes before it runs." : "Each change waits for you to say yes before it runs." });
|
|
310
|
+
}
|
|
311
|
+
return lines;
|
|
312
|
+
}
|
|
313
|
+
/* ------------------------------------------------------------------ routes */
|
|
314
|
+
export function githubRoutes(options, deps = {}) {
|
|
315
|
+
const probe = deps.probe ?? defaultProbe;
|
|
316
|
+
return [
|
|
317
|
+
route("GET", "/api/v1/github-doors", (ctx) => doorsView(options, projectDirOf(ctx.query.get("projectDir")))),
|
|
318
|
+
/** Blocks (or unblocks) gh, git push and GitHub's API in Claude Code's own settings. */
|
|
319
|
+
route("POST", "/api/v1/github-doors/claude-code", (ctx) => {
|
|
320
|
+
const body = parse(ClaudeCodeBody, ctx.body);
|
|
321
|
+
const projectDir = projectDirOf(body.projectDir);
|
|
322
|
+
const home = homedir();
|
|
323
|
+
const settingsPath = claudeCodeSettingsPath(body.scope, { home, cwd: projectDir });
|
|
324
|
+
let changed;
|
|
325
|
+
try {
|
|
326
|
+
changed = body.close
|
|
327
|
+
? closeClaudeCodeGithub({ settingsPath, home }).added
|
|
328
|
+
: reopenClaudeCodeGithub({ settingsPath, home }).removed;
|
|
329
|
+
}
|
|
330
|
+
catch (err) {
|
|
331
|
+
if (err instanceof ClientConfigError)
|
|
332
|
+
throw unprocessable(err.message);
|
|
333
|
+
throw err;
|
|
334
|
+
}
|
|
335
|
+
/*
|
|
336
|
+
* Recorded in the activity log of each toolbox with a GitHub server:
|
|
337
|
+
* that is where someone looks for why its changes stopped (or started)
|
|
338
|
+
* reaching GitHub another way. Rule names only.
|
|
339
|
+
*/
|
|
340
|
+
let warning = null;
|
|
341
|
+
if (changed.length > 0) {
|
|
342
|
+
const servers = githubServers(options);
|
|
343
|
+
const configs = [...new Set(servers.map((s) => s.configPath))];
|
|
344
|
+
if (configs.length === 0)
|
|
345
|
+
warning = "no toolbox has a GitHub server, so this wasn't written to an activity log";
|
|
346
|
+
for (const configPath of configs) {
|
|
347
|
+
warning ??= record(gatewayAudit(configPath, ctx.actor), {
|
|
348
|
+
tool: "(github)",
|
|
349
|
+
effect: null,
|
|
350
|
+
decision: "allow",
|
|
351
|
+
rule_id: body.close ? "github.claude-code.block" : "github.claude-code.unblock",
|
|
352
|
+
reason: `GitHub ${body.close ? "blocked" : "unblocked"} in Claude Code's terminal via the console by ${ctx.actor}: ` +
|
|
353
|
+
`${changed.join(", ")} ${body.close ? "added to" : "removed from"} permissions.deny in ${settingsPath}`,
|
|
354
|
+
outcome: "completed",
|
|
355
|
+
args_redacted: { scope: body.scope, settings_file: settingsPath, rules: changed }
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/*
|
|
360
|
+
* The project file is Claude Code's "local" one, meant to stay out of
|
|
361
|
+
* git. When the project's .gitignore doesn't say so, it is reported,
|
|
362
|
+
* not fixed: .gitignore is the project's file, not ours to edit.
|
|
363
|
+
*/
|
|
364
|
+
const projectNote = body.scope === "project" && projectSettingsIgnored(projectDir) === false
|
|
365
|
+
? `${settingsPath} isn't kept out of git in this project, so the block could be committed and shared with everyone who uses it. ` +
|
|
366
|
+
`Add .claude/settings.local.json to the project's .gitignore if that isn't what you want.`
|
|
367
|
+
: null;
|
|
368
|
+
return { ...doorsView(options, projectDir), settingsPath, changed, warning, projectNote };
|
|
369
|
+
}),
|
|
370
|
+
/** "I've done this", for the two doors only a person can close. Names and yes/no only. */
|
|
371
|
+
route("POST", "/api/v1/github-doors/confirm", (ctx) => {
|
|
372
|
+
const body = parse(ConfirmBody, ctx.body);
|
|
373
|
+
try {
|
|
374
|
+
confirmGithubDoor({ home: homedir(), door: body.door, done: body.done });
|
|
375
|
+
}
|
|
376
|
+
catch (err) {
|
|
377
|
+
if (err instanceof ClientConfigError)
|
|
378
|
+
throw unprocessable(err.message);
|
|
379
|
+
throw err;
|
|
380
|
+
}
|
|
381
|
+
return doorsView(options, projectDirOf(null));
|
|
382
|
+
}),
|
|
383
|
+
/**
|
|
384
|
+
* Switches a toolbox's GitHub server between GitHub's read-only address
|
|
385
|
+
* and the one that can make changes.
|
|
386
|
+
*
|
|
387
|
+
* Turning changes on writes the GitHub pack's rules to the policy first,
|
|
388
|
+
* so every change waits for the person even where the posture would let
|
|
389
|
+
* it run; then gateway.yaml, through the same lost-update check as any
|
|
390
|
+
* console edit. A pack rule never loosens the posture or overrides a rule
|
|
391
|
+
* the person wrote, and if the batch would loosen anything at all it is
|
|
392
|
+
* refused with nothing written. Turning changes off puts the read-only
|
|
393
|
+
* address back and leaves the rules, which then match nothing.
|
|
394
|
+
*/
|
|
395
|
+
route("POST", "/api/v1/servers/:id/github/:name/changes", async (ctx) => {
|
|
396
|
+
const id = ctx.params["id"];
|
|
397
|
+
const name = ctx.params["name"];
|
|
398
|
+
const body = parse(ChangesBody, ctx.body);
|
|
399
|
+
const server = serverById(options, id);
|
|
400
|
+
const configPath = expandPath(entryById(options, id).config_path);
|
|
401
|
+
const stale = () => conflict("gateway.yaml changed since it was read. Reload it and try again, so nothing written in the meantime is overwritten.");
|
|
402
|
+
if (readGatewayFile(configPath).digest !== body.expectedDigest)
|
|
403
|
+
throw stale();
|
|
404
|
+
const current = server.gateway.config.upstreams.find((u) => u.name === name);
|
|
405
|
+
if (!current)
|
|
406
|
+
throw notFound(`no connected server called "${name}"`);
|
|
407
|
+
if (body.allow && githubReadonlyHeader(current)) {
|
|
408
|
+
throw unprocessable(`"${name}" asks GitHub for read-only access with the X-MCP-Readonly header, so changing its address wouldn't let it make changes. ` +
|
|
409
|
+
`Remove that header in the server's settings instead. Nothing was changed.`);
|
|
410
|
+
}
|
|
411
|
+
const access = githubHostedAccess(current);
|
|
412
|
+
if (access === null) {
|
|
413
|
+
throw unprocessable(`"${name}" doesn't use GitHub's hosted address (api.githubcopilot.com/mcp), so it can't be switched here. Change it in the server's settings instead.`);
|
|
414
|
+
}
|
|
415
|
+
const want = body.allow ? "changes" : "readonly";
|
|
416
|
+
if (access === want)
|
|
417
|
+
return { changed: false, rulesWritten: [], note: null, warning: null, servers: githubServers(options) };
|
|
418
|
+
const nextUrl = body.allow ? GITHUB_HOSTED_URL : GITHUB_HOSTED_READONLY_URL;
|
|
419
|
+
const next = { ...current, url: nextUrl };
|
|
420
|
+
/* the pack's rules, for the tools the server offers at its new address */
|
|
421
|
+
let policyBefore = null;
|
|
422
|
+
let policyAfter = null;
|
|
423
|
+
let rulesWritten = [];
|
|
424
|
+
let note = null;
|
|
425
|
+
let listed = null;
|
|
426
|
+
if (body.allow) {
|
|
427
|
+
if (server.policyFile === null || !server.gateway.config.policy_writes) {
|
|
428
|
+
throw unprocessable("This toolbox's rules can't be changed from the console " +
|
|
429
|
+
(server.policyFile === null ? "(they are written inside its gateway.yaml)" : "(it has policy_writes: false)") +
|
|
430
|
+
", so changes weren't switched on: they might run without asking you. Nothing was changed.");
|
|
431
|
+
}
|
|
432
|
+
/*
|
|
433
|
+
* Read before the server is asked for its tools, which can take a
|
|
434
|
+
* while: an edit to policy.yaml made meanwhile is then caught by the
|
|
435
|
+
* check just before writing, as gateway.yaml's is.
|
|
436
|
+
*/
|
|
437
|
+
policyBefore = readFileSync(server.policyFile, "utf8");
|
|
438
|
+
const outcome = await probe(next, server);
|
|
439
|
+
listed = outcome;
|
|
440
|
+
/*
|
|
441
|
+
* Without a list from GitHub, only the pack's rules for changes are
|
|
442
|
+
* written: each only makes a tool ask first, so one that matches
|
|
443
|
+
* nothing does no harm. A read is never allowed on a guess.
|
|
444
|
+
*/
|
|
445
|
+
const toolNames = outcome.ok ? outcome.tools.map((t) => t.name) : githubChangeTools();
|
|
446
|
+
if (!outcome.ok)
|
|
447
|
+
note = "GitHub couldn't be reached to list its tools, so only the rules that make changes ask first were written. Use “Check it works” once it connects.";
|
|
448
|
+
const pack = await packRulesFor({
|
|
449
|
+
packId: "github",
|
|
450
|
+
upstreamName: name,
|
|
451
|
+
namespace: server.gateway.config.namespace,
|
|
452
|
+
toolNames,
|
|
453
|
+
within: undefined
|
|
454
|
+
});
|
|
455
|
+
const beforePolicy = parsePolicy(parseYaml(policyBefore) ?? { version: 1 }, server.policyFile);
|
|
456
|
+
/*
|
|
457
|
+
* A rule the person wrote keeps deciding every tool it matches. Core
|
|
458
|
+
* puts a new rule above the first rule whose pattern matches its tool,
|
|
459
|
+
* so it takes effect; for a pattern the person wrote (`github__*`)
|
|
460
|
+
* that would put the pack's "allow" for a read in front of their
|
|
461
|
+
* "ask" or "block". So a pack rule is written only for a tool no rule
|
|
462
|
+
* of theirs matches -- which is the same as adding it after theirs,
|
|
463
|
+
* since the first matching rule wins.
|
|
464
|
+
*/
|
|
465
|
+
const own = beforePolicy.rules.filter((r) => !r.id.startsWith("pack-"));
|
|
466
|
+
const rules = (pack?.rules ?? [])
|
|
467
|
+
.filter((r) => outcome.ok || r.decision !== "allow")
|
|
468
|
+
.filter((r) => !own.some((o) => globMatch(o.match, r.match)));
|
|
469
|
+
const batch = applyPolicyChanges(policyBefore, rules.map((rule) => ({ kind: "rule", rule: { ...rule } })), server.policyFile);
|
|
470
|
+
if (batch.loosens.length > 0) {
|
|
471
|
+
throw unprocessable(`Switching changes on would let more through than asked (${batch.loosens.join("; ")}), so nothing was changed.`);
|
|
472
|
+
}
|
|
473
|
+
/*
|
|
474
|
+
* And the hard check, whatever the rules above did: every tool the
|
|
475
|
+
* server listed and every tool the pack names is decided under the
|
|
476
|
+
* old policy and the new one. Any that would be less strict refuses
|
|
477
|
+
* the whole switch.
|
|
478
|
+
*/
|
|
479
|
+
if (batch.changed) {
|
|
480
|
+
const afterPolicy = parsePolicy(parseYaml(batch.text) ?? { version: 1 }, server.policyFile);
|
|
481
|
+
const listed = outcome.ok
|
|
482
|
+
? outcome.tools.map((t) => ({ name: t.exposedName, effect: t.effect === "unknown" ? undefined : t.effect }))
|
|
483
|
+
: [];
|
|
484
|
+
// A listed tool is judged with the gateway's own reading of it; a pack name the server didn't list, as unclassified.
|
|
485
|
+
const seen = new Set(listed.map((t) => t.name));
|
|
486
|
+
const named = Object.keys(loadPacks().find((p) => p.name === "github")?.tools ?? {})
|
|
487
|
+
.map((t) => exposedName(server, name, t))
|
|
488
|
+
.filter((t) => !seen.has(t));
|
|
489
|
+
const looser = loosenedTools(beforePolicy, afterPolicy, [...listed, ...named]);
|
|
490
|
+
if (looser.length > 0) {
|
|
491
|
+
throw unprocessable(`Switching changes on would let these run with less asking than now: ${looser.join(", ")}. Nothing was changed. ` +
|
|
492
|
+
`Check your own rules for GitHub on the Protection page, then try again.`);
|
|
493
|
+
}
|
|
494
|
+
policyAfter = batch.text;
|
|
495
|
+
}
|
|
496
|
+
rulesWritten = [...batch.rulesAdded, ...batch.rulesReplaced];
|
|
497
|
+
}
|
|
498
|
+
/* gateway.yaml, read again: the test above can take a while, and an edit made meanwhile wins */
|
|
499
|
+
const file = readGatewayFile(configPath);
|
|
500
|
+
if (file.digest !== body.expectedDigest)
|
|
501
|
+
throw stale();
|
|
502
|
+
const doc = parseDocument(file.text);
|
|
503
|
+
const seq = doc.get("upstreams", true);
|
|
504
|
+
const index = (seq?.items ?? []).findIndex((item) => item.get?.("name") === name);
|
|
505
|
+
if (index < 0)
|
|
506
|
+
throw notFound(`no connected server called "${name}"`);
|
|
507
|
+
doc.setIn(["upstreams", index, "url"], nextUrl);
|
|
508
|
+
if (policyAfter !== null) {
|
|
509
|
+
// policy.yaml too may have been edited while the tools were listed; that edit wins.
|
|
510
|
+
if (readFileSync(server.policyFile, "utf8") !== policyBefore) {
|
|
511
|
+
throw conflict("policy.yaml changed while GitHub's tools were being listed. Nothing was changed; try again.");
|
|
512
|
+
}
|
|
513
|
+
writeAtomically(server.policyFile, policyAfter);
|
|
514
|
+
}
|
|
515
|
+
let result;
|
|
516
|
+
try {
|
|
517
|
+
result = commitGatewayText({
|
|
518
|
+
file,
|
|
519
|
+
text: doc.toString(),
|
|
520
|
+
expectedDigest: body.expectedDigest,
|
|
521
|
+
acknowledgedLoosens: false,
|
|
522
|
+
intended: (before, after) => sameExcept(before, after, ["upstreams"]) &&
|
|
523
|
+
after.upstreams.length === before.upstreams.length &&
|
|
524
|
+
before.upstreams.every((u, i) => JSON.stringify(u.name === name ? { ...u, url: nextUrl } : u) === JSON.stringify(after.upstreams[i]))
|
|
525
|
+
? null
|
|
526
|
+
: `switching "${name}" would have changed something else too`
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
catch (err) {
|
|
530
|
+
if (policyAfter !== null) {
|
|
531
|
+
/*
|
|
532
|
+
* Put the policy back only if it is still exactly what was written
|
|
533
|
+
* here. Someone else's edit since then is theirs: it is left, and
|
|
534
|
+
* said, rather than overwritten by an undo.
|
|
535
|
+
*/
|
|
536
|
+
let now = null;
|
|
537
|
+
try {
|
|
538
|
+
now = readFileSync(server.policyFile, "utf8");
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
now = null;
|
|
542
|
+
}
|
|
543
|
+
if (now !== policyAfter) {
|
|
544
|
+
throw conflict(`gateway.yaml couldn't be saved (${err.message}), and policy.yaml was changed by someone else after hmcp wrote ` +
|
|
545
|
+
`its GitHub rules, so it was left as it is. Look for the rules starting "pack-github-" in it.`);
|
|
546
|
+
}
|
|
547
|
+
writeAtomically(server.policyFile, policyBefore);
|
|
548
|
+
}
|
|
549
|
+
throw err;
|
|
550
|
+
}
|
|
551
|
+
const warning = record(gatewayAudit(configPath, ctx.actor), {
|
|
552
|
+
tool: "(github)",
|
|
553
|
+
effect: null,
|
|
554
|
+
decision: "allow",
|
|
555
|
+
rule_id: body.allow ? "github.changes.on" : "github.changes.off",
|
|
556
|
+
reason: `"${name}" switched to GitHub's ${body.allow ? "address that can make changes" : "read-only address"} via the console by ${ctx.actor}` +
|
|
557
|
+
(rulesWritten.length > 0 ? `; ${rulesWritten.length} ready-made rule(s) written so changes ask first` : ""),
|
|
558
|
+
outcome: "completed",
|
|
559
|
+
args_redacted: {
|
|
560
|
+
upstream: name,
|
|
561
|
+
access: want,
|
|
562
|
+
rules_written: rulesWritten,
|
|
563
|
+
digest_before: result.previousDigest,
|
|
564
|
+
digest_after: result.digest
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
// The address changed: the list just taken is the one to grade, or none is known.
|
|
568
|
+
rememberListed(id, name, listed);
|
|
569
|
+
return { changed: true, rulesWritten, note, warning, servers: githubServers(options) };
|
|
570
|
+
}),
|
|
571
|
+
/** "Check it works": connects the server once, lists its tools, and grades each change tool under the policy as it is now. */
|
|
572
|
+
route("POST", "/api/v1/servers/:id/github/:name/check", async (ctx) => {
|
|
573
|
+
const id = ctx.params["id"];
|
|
574
|
+
const name = ctx.params["name"];
|
|
575
|
+
const server = serverById(options, id);
|
|
576
|
+
const upstream = server.gateway.config.upstreams.find((u) => u.name === name);
|
|
577
|
+
if (!upstream)
|
|
578
|
+
throw notFound(`no connected server called "${name}"`);
|
|
579
|
+
if (!isGithubUpstream(upstream))
|
|
580
|
+
throw unprocessable(`"${name}" isn't a GitHub server.`);
|
|
581
|
+
const outcome = await probe(upstream, server);
|
|
582
|
+
// The card grades what this list really holds from now on.
|
|
583
|
+
rememberListed(id, name, outcome);
|
|
584
|
+
return { lines: checkLines(outcome, upstream, server.policy), note: KEY_NOTE };
|
|
585
|
+
})
|
|
586
|
+
];
|
|
587
|
+
}
|