hmcp-gateway 0.0.2 → 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.
Files changed (114) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +135 -9
  3. package/bin/hmcp-gateway.js +20 -0
  4. package/catalog/atlassian.yaml +41 -0
  5. package/catalog/brave-search.yaml +57 -0
  6. package/catalog/context7.yaml +42 -0
  7. package/catalog/fetch.yaml +37 -0
  8. package/catalog/figma.yaml +48 -0
  9. package/catalog/filesystem.yaml +48 -0
  10. package/catalog/git.yaml +48 -0
  11. package/catalog/github.yaml +103 -0
  12. package/catalog/huggingface.yaml +59 -0
  13. package/catalog/linear.yaml +47 -0
  14. package/catalog/memory.yaml +47 -0
  15. package/catalog/notion.yaml +41 -0
  16. package/catalog/playwright.yaml +38 -0
  17. package/catalog/postgres.yaml +66 -0
  18. package/catalog/sentry.yaml +39 -0
  19. package/catalog/sequential-thinking.yaml +29 -0
  20. package/catalog/stripe.yaml +41 -0
  21. package/catalog/supabase.yaml +45 -0
  22. package/catalog/time.yaml +49 -0
  23. package/dist/adopt-cli.d.ts +355 -0
  24. package/dist/adopt-cli.js +1885 -0
  25. package/dist/adopt-emit.d.ts +64 -0
  26. package/dist/adopt-emit.js +248 -0
  27. package/dist/adopt-plan.d.ts +108 -0
  28. package/dist/adopt-plan.js +501 -0
  29. package/dist/catalog.d.ts +140 -0
  30. package/dist/catalog.js +250 -0
  31. package/dist/classify.d.ts +23 -0
  32. package/dist/classify.js +47 -0
  33. package/dist/cli.d.ts +2 -0
  34. package/dist/cli.js +656 -0
  35. package/dist/client-allow.d.ts +42 -0
  36. package/dist/client-allow.js +95 -0
  37. package/dist/client-config.d.ts +263 -0
  38. package/dist/client-config.js +995 -0
  39. package/dist/config-source.d.ts +106 -0
  40. package/dist/config-source.js +156 -0
  41. package/dist/config.d.ts +159 -0
  42. package/dist/config.js +330 -0
  43. package/dist/connect-client.d.ts +51 -0
  44. package/dist/connect-client.js +299 -0
  45. package/dist/contracts.d.ts +251 -0
  46. package/dist/contracts.js +9 -0
  47. package/dist/credential.d.ts +63 -0
  48. package/dist/credential.js +136 -0
  49. package/dist/desktop-extensions.d.ts +53 -0
  50. package/dist/desktop-extensions.js +126 -0
  51. package/dist/draft.d.ts +71 -0
  52. package/dist/draft.js +596 -0
  53. package/dist/exposure-cli.d.ts +28 -0
  54. package/dist/exposure-cli.js +119 -0
  55. package/dist/gateway.d.ts +766 -0
  56. package/dist/gateway.js +2122 -0
  57. package/dist/github-doors.d.ts +162 -0
  58. package/dist/github-doors.js +780 -0
  59. package/dist/guard-install.d.ts +109 -0
  60. package/dist/guard-install.js +396 -0
  61. package/dist/guard.d.ts +265 -0
  62. package/dist/guard.js +975 -0
  63. package/dist/import-client.d.ts +184 -0
  64. package/dist/import-client.js +578 -0
  65. package/dist/index.d.ts +31 -0
  66. package/dist/index.js +31 -0
  67. package/dist/notify.d.ts +44 -0
  68. package/dist/notify.js +93 -0
  69. package/dist/oauth.d.ts +139 -0
  70. package/dist/oauth.js +641 -0
  71. package/dist/observe.d.ts +10 -0
  72. package/dist/observe.js +26 -0
  73. package/dist/open.d.ts +24 -0
  74. package/dist/open.js +31 -0
  75. package/dist/packs.d.ts +119 -0
  76. package/dist/packs.js +131 -0
  77. package/dist/pin-cli.d.ts +28 -0
  78. package/dist/pin-cli.js +103 -0
  79. package/dist/probe-upstream.d.ts +31 -0
  80. package/dist/probe-upstream.js +377 -0
  81. package/dist/registry-map.d.ts +39 -0
  82. package/dist/registry-map.js +390 -0
  83. package/dist/rule-cli.d.ts +51 -0
  84. package/dist/rule-cli.js +412 -0
  85. package/dist/serve-http.d.ts +67 -0
  86. package/dist/serve-http.js +478 -0
  87. package/dist/snippet.d.ts +20 -0
  88. package/dist/snippet.js +826 -0
  89. package/dist/status-cli.d.ts +61 -0
  90. package/dist/status-cli.js +195 -0
  91. package/dist/suggest-cli.d.ts +43 -0
  92. package/dist/suggest-cli.js +279 -0
  93. package/dist/toml-edit.d.ts +43 -0
  94. package/dist/toml-edit.js +363 -0
  95. package/dist/toolname.d.ts +47 -0
  96. package/dist/toolname.js +149 -0
  97. package/dist/upstream-errors.d.ts +54 -0
  98. package/dist/upstream-errors.js +330 -0
  99. package/dist/upstream.d.ts +128 -0
  100. package/dist/upstream.js +413 -0
  101. package/dist/version.d.ts +10 -0
  102. package/dist/version.js +11 -0
  103. package/package.json +51 -6
  104. package/packs/brave-search.yaml +20 -0
  105. package/packs/context7.yaml +13 -0
  106. package/packs/fetch.yaml +14 -0
  107. package/packs/filesystem.yaml +79 -0
  108. package/packs/git.yaml +29 -0
  109. package/packs/github.yaml +47 -0
  110. package/packs/huggingface.yaml +16 -0
  111. package/packs/memory.yaml +23 -0
  112. package/packs/playwright.yaml +41 -0
  113. package/packs/sequential-thinking.yaml +13 -0
  114. package/packs/time.yaml +14 -0
@@ -0,0 +1,780 @@
1
+ import { existsSync, readFileSync, readdirSync, unlinkSync } from "node:fs";
2
+ import { basename, join, resolve } from "node:path";
3
+ import { z } from "zod";
4
+ import { realPathDeepest } from "hmcp-core";
5
+ import { ClientConfigError, detectIndent, isRemote, parseServers, readClientConfig, scopeTargets, writePrivateText, writeTextPreservingMode } from "./client-config.js";
6
+ import { loadPacks } from "./packs.js";
7
+ /** The doors only a person, signed in, can close: hmcp can only open the page and remember their answer. */
8
+ export const MANUAL_GITHUB_DOORS = ["github-app-access", "claude-connector"];
9
+ /** Why those two can't be closed from here, in one line. */
10
+ export const MANUAL_DOOR_WHY = "GitHub and Anthropic only let you, signed in, remove an app's access — no program can do it for you, which is what keeps malware from doing it.";
11
+ /**
12
+ * The rules. `gh` and `git push` are the two commands that change GitHub with
13
+ * this computer's own sign-in; the WebFetch rule stops Claude Code's own web
14
+ * tool calling GitHub's API. Claude Code checks deny rules before it runs
15
+ * anything, and a deny wins over an allow in any settings file.
16
+ */
17
+ export const CLAUDE_CODE_GITHUB_RULES = ["Bash(gh:*)", "Bash(git push:*)", "WebFetch(domain:api.github.com)"];
18
+ /** The variables `gh`, git helpers and GitHub's own server read a key from. */
19
+ const TOKEN_VARIABLES = ["GITHUB_TOKEN", "GH_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN"];
20
+ /** A variable name that looks like it holds a GitHub key: GH_TOKEN, GITHUB_PAT, GH_ENTERPRISE_TOKEN... */
21
+ function looksLikeGithubKeyName(name) {
22
+ // Whole words only: GITHUB_PATH and GITHUB_EVENT_PATH, which every GitHub
23
+ // Actions runner sets, hold file paths, not keys.
24
+ return (TOKEN_VARIABLES.includes(name) ||
25
+ /^(GITHUB|GH)(_[A-Z0-9]+)*_(TOKEN|PAT|KEY|SECRET)(_[A-Z0-9]+)*$/i.test(name));
26
+ }
27
+ /**
28
+ * git's settings outside the home folder. Apple's git turns the macOS
29
+ * keychain on in its own file, so a Mac with nothing in `~/.gitconfig` can
30
+ * still have GitHub's password saved; Git for Windows does the same with Git
31
+ * Credential Manager. Read only, and only to see which password helper is
32
+ * named.
33
+ */
34
+ export function defaultSystemGitConfigs(env, platform) {
35
+ if (platform === "win32") {
36
+ return [
37
+ "C:\\Program Files\\Git\\etc\\gitconfig",
38
+ "C:\\Program Files (x86)\\Git\\etc\\gitconfig",
39
+ ...(env["ProgramData"] ? [join(env["ProgramData"], "Git", "config")] : [])
40
+ ];
41
+ }
42
+ return [
43
+ "/etc/gitconfig",
44
+ "/opt/homebrew/etc/gitconfig",
45
+ "/usr/local/etc/gitconfig",
46
+ "/Library/Developer/CommandLineTools/usr/share/git-core/gitconfig",
47
+ "/Applications/Xcode.app/Contents/Developer/usr/share/git-core/gitconfig"
48
+ ];
49
+ }
50
+ function readText(path) {
51
+ try {
52
+ return existsSync(path) ? readFileSync(path, "utf8") : undefined;
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ /** Claude Code's settings file for a scope. A project gets its local file, which Claude Code keeps out of git. */
59
+ export function claudeCodeSettingsPath(scope, options) {
60
+ return scope === "user"
61
+ ? join(resolve(options.home), ".claude", "settings.json")
62
+ : join(resolve(options.cwd), ".claude", "settings.local.json");
63
+ }
64
+ export function githubDoors(options) {
65
+ const read = options.readFile ?? readText;
66
+ return [
67
+ claudeCodeDoor(options),
68
+ ghDoor(options, read),
69
+ gitCredentialsDoor(options, read),
70
+ envDoor(options),
71
+ otherServersDoor(options),
72
+ ...manualDoors(readGithubDoorConfirmations(options.home))
73
+ ];
74
+ }
75
+ /* ------------------------------------------------------------- Claude Code */
76
+ const RULE_LIST = CLAUDE_CODE_GITHUB_RULES.join(", ");
77
+ function claudeCodeDoor(options) {
78
+ const userPath = claudeCodeSettingsPath("user", options);
79
+ const localPath = claudeCodeSettingsPath("project", options);
80
+ // Claude Code merges the rules of every file it reads; a deny in any one of them holds.
81
+ const files = [...new Set([userPath, join(resolve(options.cwd), ".claude", "settings.json"), localPath])];
82
+ const holding = [];
83
+ const unreadable = [];
84
+ const denied = new Set();
85
+ for (const path of files) {
86
+ if (!existsSync(path))
87
+ continue;
88
+ let deny;
89
+ try {
90
+ deny = denyRules(readSettings(path, "checked")).deny;
91
+ }
92
+ catch {
93
+ unreadable.push(path);
94
+ continue;
95
+ }
96
+ if (CLAUDE_CODE_GITHUB_RULES.some((r) => deny.includes(r)))
97
+ holding.push(path);
98
+ for (const rule of deny)
99
+ denied.add(rule);
100
+ }
101
+ const missing = CLAUDE_CODE_GITHUB_RULES.filter((r) => !denied.has(r));
102
+ const platform = options.platform ?? process.platform;
103
+ let record;
104
+ try {
105
+ record = readUndoRecord(options.home);
106
+ }
107
+ catch {
108
+ // A record that can't be read offers no undo; closing and undoing refuse with the reason.
109
+ record = { version: 1, files: {} };
110
+ }
111
+ const undoable = ["user", "project"].filter((s) => record.files[settingsKey(s === "user" ? userPath : localPath, platform)] !== undefined);
112
+ const base = { id: "claude-code-terminal", label: "Claude Code's terminal", ...(undoable.length > 0 ? { undoable } : {}) };
113
+ const fix = [
114
+ "Choose “Block GitHub in Claude Code” below.",
115
+ `Or add these to "permissions": { "deny": [...] } in ${userPath} yourself: ${RULE_LIST}.`,
116
+ "Restart Claude Code afterwards."
117
+ ];
118
+ if (missing.length === 0) {
119
+ /*
120
+ * Never "closed": a prefix rule stops the obvious commands, and Claude
121
+ * Code enforces it, but a command that reaches gh or git another way is
122
+ * not matched by it. Saying "closed" would be the overclaim this card
123
+ * exists to avoid.
124
+ */
125
+ return {
126
+ ...base,
127
+ state: "harder",
128
+ detail: "Claude Code is told not to run gh or git push or fetch GitHub's API; a determined workaround (another path to gh, sh -c, curl, a git alias) " +
129
+ `can still get through. The rules are in ${holding.join(" and ")}.`,
130
+ fix: ["For a guarantee, also log gh out and remove saved GitHub logins for git (below)."]
131
+ };
132
+ }
133
+ if (unreadable.length > 0) {
134
+ return {
135
+ ...base,
136
+ state: "unknown",
137
+ detail: `Claude Code's settings file ${unreadable.join(" and ")} can't be read, so it isn't clear whether gh and git push are blocked.`,
138
+ fix: [`Open ${unreadable[0]} in a text editor and fix the mistake in it, then check again.`]
139
+ };
140
+ }
141
+ return {
142
+ ...base,
143
+ state: "open",
144
+ detail: missing.length === CLAUDE_CODE_GITHUB_RULES.length
145
+ ? "Claude Code can run gh and git push in its terminal, which changes GitHub without asking hmcp."
146
+ : `Some of the rules are there, but not all. Still missing: ${missing.join(", ")}.`,
147
+ fix
148
+ };
149
+ }
150
+ /**
151
+ * Claude Code's settings file as an object, `{}` when there is none. Refuses
152
+ * a file it can't read rather than guess: writing over it would lose
153
+ * whatever the person had there.
154
+ */
155
+ function readSettings(path, doing, shown = path) {
156
+ if (!existsSync(path))
157
+ return {};
158
+ const refuse = (why) => {
159
+ throw new ClientConfigError(`Claude Code's settings file ${shown} ${why}, so it can't be ${doing} and nothing was changed. ` +
160
+ `Open it in a text editor, fix it, and try again.`);
161
+ };
162
+ const text = readFileSync(path, "utf8");
163
+ let parsed;
164
+ try {
165
+ parsed = JSON.parse(text);
166
+ }
167
+ catch (err) {
168
+ /*
169
+ * Only the line number. The parser's own message quotes the text around
170
+ * the mistake, and a settings file's `env` block can hold a key.
171
+ */
172
+ const line = jsonErrorLine(text, err.message);
173
+ throw new ClientConfigError(`${shown} isn't valid JSON${line === undefined ? "" : ` at line ${line}`}; fix it in a text editor. Nothing was changed.`);
174
+ }
175
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
176
+ return refuse("doesn't hold settings");
177
+ const permissions = parsed.permissions;
178
+ if (permissions !== undefined && (typeof permissions !== "object" || permissions === null || Array.isArray(permissions))) {
179
+ return refuse(`has a "permissions" that isn't a group of settings`);
180
+ }
181
+ if (permissions?.["deny"] !== undefined && !Array.isArray(permissions["deny"])) {
182
+ return refuse(`has a "permissions.deny" that isn't a list`);
183
+ }
184
+ return parsed;
185
+ }
186
+ /** The line a JSON.parse error points at, as a number and nothing else. */
187
+ function jsonErrorLine(text, message) {
188
+ const line = /\bline (\d+)/.exec(message)?.[1];
189
+ if (line)
190
+ return Number(line);
191
+ const position = /\bposition (\d+)/.exec(message)?.[1];
192
+ if (position)
193
+ return text.slice(0, Number(position)).split("\n").length;
194
+ // A file cut short: the mistake is at its end.
195
+ if (/end of JSON input/i.test(message))
196
+ return text.split("\n").length;
197
+ return undefined;
198
+ }
199
+ /**
200
+ * The file a settings path really is: through a symlink (a dotfiles repo
201
+ * often links `~/.claude/settings.json`), so the write lands in the file and
202
+ * the link stays a link. A file not made yet is spelled from its deepest
203
+ * folder that exists, so it reads the same before and after it is written.
204
+ */
205
+ function realTarget(path) {
206
+ return realPathDeepest(resolve(path));
207
+ }
208
+ /** One spelling per file for the undo record: real, and case-folded where the file system ignores case. */
209
+ function settingsKey(path, platform) {
210
+ const real = realTarget(path);
211
+ return platform === "darwin" || platform === "win32" ? real.toLowerCase() : real;
212
+ }
213
+ function denyRules(settings) {
214
+ const deny = settings.permissions?.["deny"];
215
+ return { deny: Array.isArray(deny) ? deny.filter((r) => typeof r === "string") : [] };
216
+ }
217
+ /* --------------------------------------------- closing Claude Code's door */
218
+ /**
219
+ * What hmcp added to each settings file, so undo removes exactly that. A rule
220
+ * the person already had is never recorded, so it is never taken away. Kept
221
+ * under `~/.hmcp` beside the other undo records, readable by its owner only.
222
+ */
223
+ const UndoRecordSchema = z
224
+ .object({
225
+ version: z.literal(1),
226
+ files: z.record(z.string(), z
227
+ .object({
228
+ added: z.array(z.string()),
229
+ /** The outermost thing hmcp created: the file, `permissions`, or `permissions.deny`. Undo tidies it away once empty. */
230
+ created: z.enum(["file", "permissions", "deny"]).nullable(),
231
+ at: z.string()
232
+ })
233
+ .strict())
234
+ })
235
+ .strict();
236
+ export function claudeCodeGithubUndoPath(home) {
237
+ return join(resolve(home), ".hmcp", "claude-code-github-block.json");
238
+ }
239
+ /**
240
+ * Throws when the record is there but can't be read. Writing a fresh one
241
+ * over it would forget which rules hmcp added, and undo would then leave them
242
+ * in for good; so nothing is changed until the person moves it aside.
243
+ */
244
+ function readUndoRecord(home) {
245
+ const path = claudeCodeGithubUndoPath(home);
246
+ const text = readText(path);
247
+ if (text === undefined)
248
+ return { version: 1, files: {} };
249
+ try {
250
+ return UndoRecordSchema.parse(JSON.parse(text));
251
+ }
252
+ catch {
253
+ throw new ClientConfigError(`hmcp's record of what it added to Claude Code's settings (${path}) can't be read, so nothing was changed. ` +
254
+ `Move that file aside and try again; any rules it listed may then need removing from Claude Code's settings by hand.`);
255
+ }
256
+ }
257
+ function writeUndoRecord(home, record) {
258
+ const path = claudeCodeGithubUndoPath(home);
259
+ if (Object.keys(record.files).length === 0) {
260
+ if (existsSync(path))
261
+ unlinkSync(path);
262
+ return;
263
+ }
264
+ writePrivateText(path, `${JSON.stringify(record, null, 2)}\n`);
265
+ }
266
+ /** The settings written back in the file's own indent and line ending, atomically, keeping its mode. */
267
+ function writeSettings(path, before, settings) {
268
+ const newline = before === null || before.endsWith("\n") ? "\n" : "";
269
+ writeTextPreservingMode(path, `${JSON.stringify(settings, null, detectIndent(before))}${newline}`);
270
+ }
271
+ /** Adds whichever of the three rules are missing. `added` is empty, and nothing written, when all were there. */
272
+ export function closeClaudeCodeGithub(options) {
273
+ const shown = resolve(options.settingsPath);
274
+ const path = realTarget(shown);
275
+ const key = settingsKey(shown, options.platform ?? process.platform);
276
+ // Read first, so a broken record stops everything before the settings are touched.
277
+ const record = readUndoRecord(options.home);
278
+ const before = readText(path) ?? null;
279
+ const settings = readSettings(path, "changed", shown);
280
+ const { deny } = denyRules(settings);
281
+ const rawDeny = settings.permissions?.["deny"] ?? [];
282
+ const missing = CLAUDE_CODE_GITHUB_RULES.filter((r) => !deny.includes(r));
283
+ if (missing.length === 0)
284
+ return { settingsPath: shown, added: [] };
285
+ const created = before === null ? "file" : settings.permissions === undefined ? "permissions" : settings.permissions["deny"] === undefined ? "deny" : null;
286
+ const previous = record.files[key];
287
+ const next = {
288
+ version: 1,
289
+ files: {
290
+ ...record.files,
291
+ [key]: {
292
+ added: [...new Set([...(previous?.added ?? []), ...missing])],
293
+ created: previous?.created ?? created,
294
+ at: new Date().toISOString()
295
+ }
296
+ }
297
+ };
298
+ // The record first: a block written without one could never be undone from here.
299
+ writeUndoRecord(options.home, next);
300
+ try {
301
+ writeSettings(path, before, { ...settings, permissions: { ...(settings.permissions ?? {}), deny: [...rawDeny, ...missing] } });
302
+ }
303
+ catch (err) {
304
+ writeUndoRecord(options.home, record);
305
+ throw err;
306
+ }
307
+ return { settingsPath: shown, added: [...missing] };
308
+ }
309
+ /** Removes only the rules hmcp added to this file. `removed` is empty when it added none. */
310
+ export function reopenClaudeCodeGithub(options) {
311
+ const shown = resolve(options.settingsPath);
312
+ const path = realTarget(shown);
313
+ const key = settingsKey(shown, options.platform ?? process.platform);
314
+ const record = readUndoRecord(options.home);
315
+ const entry = record.files[key];
316
+ if (!entry)
317
+ return { settingsPath: shown, removed: [] };
318
+ const { [key]: _done, ...rest } = record.files;
319
+ if (!existsSync(path)) {
320
+ writeUndoRecord(options.home, { version: 1, files: rest });
321
+ return { settingsPath: shown, removed: [] };
322
+ }
323
+ const before = readText(path) ?? null;
324
+ const settings = readSettings(path, "changed", shown);
325
+ const deny = [...(settings.permissions?.["deny"] ?? [])];
326
+ const removed = [];
327
+ // One copy each: a second, identical rule the person added by hand is theirs.
328
+ for (const rule of entry.added) {
329
+ const at = deny.lastIndexOf(rule);
330
+ if (at === -1)
331
+ continue;
332
+ deny.splice(at, 1);
333
+ removed.push(rule);
334
+ }
335
+ const permissions = { ...(settings.permissions ?? {}), deny };
336
+ if (deny.length === 0 && entry.created !== null)
337
+ delete permissions["deny"];
338
+ const next = { ...settings, permissions };
339
+ if (Object.keys(permissions).length === 0 && (entry.created === "permissions" || entry.created === "file"))
340
+ delete next.permissions;
341
+ if (entry.created === "file" && Object.keys(next).length === 0)
342
+ unlinkSync(path);
343
+ else if (removed.length > 0)
344
+ writeSettings(path, before, next);
345
+ writeUndoRecord(options.home, { version: 1, files: rest });
346
+ return { settingsPath: shown, removed };
347
+ }
348
+ /**
349
+ * Whether a project's `.claude/settings.local.json` is kept out of git, read
350
+ * from its `.gitignore` files only (never edited). Null when the folder isn't
351
+ * a git repository. A rule given in a global ignore file isn't seen, so
352
+ * `false` means "not that we can see".
353
+ */
354
+ export function projectSettingsIgnored(projectDir) {
355
+ const dir = resolve(projectDir);
356
+ if (!existsSync(join(dir, ".git")))
357
+ return null;
358
+ const lines = (path) => (readText(path) ?? "").split(/\r?\n/).map((l) => l.trim());
359
+ const top = new Set([
360
+ ".claude/settings.local.json",
361
+ "/.claude/settings.local.json",
362
+ "settings.local.json",
363
+ "**/settings.local.json",
364
+ "*.local.json",
365
+ ".claude",
366
+ ".claude/",
367
+ "/.claude",
368
+ "/.claude/",
369
+ ".claude/*",
370
+ "/.claude/*"
371
+ ]);
372
+ const inner = new Set(["settings.local.json", "/settings.local.json", "*", "*.local.json"]);
373
+ return lines(join(dir, ".gitignore")).some((l) => top.has(l)) || lines(join(dir, ".claude", ".gitignore")).some((l) => inner.has(l));
374
+ }
375
+ /* -------------------------------------------------------------------- gh */
376
+ /** Where `gh` keeps its sign-ins: GH_CONFIG_DIR, then XDG_CONFIG_HOME, then its default. */
377
+ function ghHostsPath(options) {
378
+ const env = options.env;
379
+ if (env["GH_CONFIG_DIR"])
380
+ return join(env["GH_CONFIG_DIR"], "hosts.yml");
381
+ if (env["XDG_CONFIG_HOME"])
382
+ return join(env["XDG_CONFIG_HOME"], "gh", "hosts.yml");
383
+ if ((options.platform ?? process.platform) === "win32" && env["AppData"])
384
+ return join(env["AppData"], "GitHub CLI", "hosts.yml");
385
+ return join(options.home, ".config", "gh", "hosts.yml");
386
+ }
387
+ function ghDoor(options, read) {
388
+ const base = { id: "gh-login", label: "GitHub's command-line tool (gh)" };
389
+ /*
390
+ * Whether the file names github.com as a host, and nothing more. `gh` itself
391
+ * is never run: `gh auth status` prints part of the key, and this answer
392
+ * reaches a browser.
393
+ */
394
+ const hosts = read(ghHostsPath(options));
395
+ if (hosts !== undefined && /^(["']?)github\.com\1[ \t]*:/m.test(hosts)) {
396
+ return {
397
+ ...base,
398
+ state: "open",
399
+ detail: "gh is signed in to github.com on this computer, so anything that runs gh can change GitHub without asking hmcp.",
400
+ fix: ["In a terminal, run `gh auth logout`.", "You can sign in again with `gh auth login` when you want to use gh yourself."]
401
+ };
402
+ }
403
+ return { ...base, state: "closed", detail: "gh isn't signed in to github.com on this computer.", fix: [] };
404
+ }
405
+ /* -------------------------------------------------------- git's passwords */
406
+ /**
407
+ * git's logins can't all be seen from here: a repository's own `.git/config`
408
+ * can name a helper or carry a key in a remote's address, and there is no
409
+ * list of every repository on the computer. So this door is "open" when a
410
+ * GitHub login is found and "can't check" otherwise -- never "closed".
411
+ */
412
+ function gitCredentialsDoor(options, read) {
413
+ const base = { id: "git-credentials", label: "Saved GitHub logins for git" };
414
+ const xdg = options.env["XDG_CONFIG_HOME"] || join(options.home, ".config");
415
+ const stores = [join(options.home, ".git-credentials"), join(xdg, "git", "credentials")];
416
+ // Only whether a line is for github.com. The line itself holds the password and is never kept.
417
+ const saved = stores.filter((path) => (read(path) ?? "").split(/\r?\n/).some(isGithubCredentialLine));
418
+ if (saved.length > 0) {
419
+ return {
420
+ ...base,
421
+ state: "open",
422
+ detail: `A saved GitHub password or key is in ${saved.map((p) => basename(p)).join(" and ")}, so git push can reach GitHub without asking hmcp.`,
423
+ fix: [
424
+ `Open ${saved[0]} in a text editor and delete the line that mentions github.com.`,
425
+ "git will ask you to sign in the next time you push from your own terminal."
426
+ ]
427
+ };
428
+ }
429
+ const configs = [
430
+ join(options.home, ".gitconfig"),
431
+ join(xdg, "git", "config"),
432
+ ...(options.systemGitConfigs ?? defaultSystemGitConfigs(options.env, options.platform ?? process.platform))
433
+ ];
434
+ const texts = configs.map((path) => read(path));
435
+ const keeper = texts.map(passwordKeeper).find((k) => k !== undefined);
436
+ const includes = texts.some((t) => t !== undefined && /^\s*\[\s*include(if)?\b/im.test(t));
437
+ const ssh = sshReachesGithub(options, read);
438
+ const found = [];
439
+ const fix = [];
440
+ if (keeper) {
441
+ found.push(`git is set to keep passwords in ${keeper}, which can't be checked from here without asking you.`);
442
+ fix.push("On a Mac: open Keychain Access, search for github.com, and delete the “internet password” entries for github.com.", "Anywhere: in a terminal, run printf 'protocol=https\\nhost=github.com\\n\\n' | git credential reject");
443
+ }
444
+ if (ssh) {
445
+ found.push("git can push over SSH with your keys; hmcp can't see which repositories they reach.");
446
+ fix.push("To stop pushes over SSH, remove this computer's key on github.com under Settings → SSH and GPG keys (https://github.com/settings/keys).");
447
+ }
448
+ if (includes)
449
+ found.push("Your git settings file includes other settings files, which weren't followed.");
450
+ if (found.length === 0)
451
+ found.push("No saved GitHub login was found in your settings.");
452
+ if (fix.length > 0)
453
+ fix.push("git will ask you to sign in the next time you push from your own terminal.");
454
+ return {
455
+ ...base,
456
+ state: "unknown",
457
+ detail: `${found.join(" ")} A repository's own settings can hold a login too, and those can't all be checked from here.`,
458
+ fix
459
+ };
460
+ }
461
+ /**
462
+ * Whether git could reach GitHub over SSH: a private key in `~/.ssh`, an ssh
463
+ * config or known_hosts entry for github.com, or a running ssh agent. Only
464
+ * names and yes/no; a key file is never opened.
465
+ */
466
+ function sshReachesGithub(options, read) {
467
+ if (options.env["SSH_AUTH_SOCK"])
468
+ return true;
469
+ const dir = join(options.home, ".ssh");
470
+ let names = [];
471
+ try {
472
+ names = readdirSync(dir);
473
+ }
474
+ catch {
475
+ names = [];
476
+ }
477
+ if (names.some((n) => /^id_[^.]+$/.test(n)))
478
+ return true;
479
+ return [join(dir, "config"), join(dir, "known_hosts")].some((p) => /github\.com/i.test(read(p) ?? ""));
480
+ }
481
+ function isGithubCredentialLine(line) {
482
+ try {
483
+ return new URL(line.trim()).hostname.toLowerCase() === "github.com";
484
+ }
485
+ catch {
486
+ return false;
487
+ }
488
+ }
489
+ /**
490
+ * The password keeper a git config names, in words, or undefined. A helper
491
+ * that saves to the file checked above, or one that asks `gh` (whose sign-in
492
+ * is its own door), isn't another place. The helper's own text is never
493
+ * repeated: it can be a script with a key written into it.
494
+ */
495
+ function passwordKeeper(text) {
496
+ if (text === undefined)
497
+ return undefined;
498
+ let inCredential = false;
499
+ let found;
500
+ for (const line of text.split(/\r?\n/)) {
501
+ const section = /^\s*\[\s*([^\]\s"]+)/.exec(line);
502
+ if (section) {
503
+ inCredential = section[1].toLowerCase() === "credential";
504
+ continue;
505
+ }
506
+ if (!inCredential)
507
+ continue;
508
+ const helper = /^\s*helper\s*=\s*(.*?)\s*$/i.exec(line)?.[1]?.replace(/^"|"$/g, "");
509
+ if (helper === undefined)
510
+ continue;
511
+ if (helper === "") {
512
+ found = undefined;
513
+ continue;
514
+ }
515
+ if (/^store(\s|$)/.test(helper) && !helper.includes("--file"))
516
+ continue;
517
+ if (/\bgh(\.exe)?\s+auth\s+git-credential\b/.test(helper))
518
+ continue;
519
+ found = /osxkeychain/.test(helper) ? "the macOS keychain" : /^manager/.test(helper) ? "Git Credential Manager" : "a password helper";
520
+ }
521
+ return found;
522
+ }
523
+ /* -------------------------------------------------------------- variables */
524
+ function envDoor(options) {
525
+ const base = { id: "env-token", label: "GitHub keys in the environment" };
526
+ const set = Object.keys(options.env)
527
+ .filter((name) => looksLikeGithubKeyName(name) && (options.env[name] ?? "") !== "")
528
+ .sort();
529
+ /*
530
+ * Claude Code's own settings can set variables for every command it runs
531
+ * (`"env": {...}`), which a shell startup file never shows. Names only.
532
+ */
533
+ const inSettings = [];
534
+ for (const path of claudeCodeSettingsFiles(options)) {
535
+ const env = settingsEnv(path);
536
+ const names = Object.keys(env)
537
+ .filter((n) => looksLikeGithubKeyName(n) && typeof env[n] === "string" && env[n] !== "")
538
+ .sort();
539
+ if (names.length > 0)
540
+ inSettings.push({ path, names });
541
+ }
542
+ const found = [];
543
+ const fix = [];
544
+ if (set.length > 0) {
545
+ found.push(`${set.join(", ")} ${set.length === 1 ? "is" : "are"} set where the console was started. A terminal with the same setting lets any command use that key to change GitHub.`);
546
+ fix.push(`Remove ${set.join(", ")} from your shell's startup file (such as ~/.zshrc or ~/.bash_profile).`);
547
+ }
548
+ for (const s of inSettings) {
549
+ found.push(`Claude Code's settings ${s.path} set ${s.names.join(", ")} for every command it runs.`);
550
+ fix.push(`Delete ${s.names.join(", ")} from the "env" part of ${s.path}.`);
551
+ }
552
+ if (found.length > 0) {
553
+ return { ...base, state: "open", detail: found.join(" "), fix: [...fix, "Open a new terminal, then restart Claude Code and the console."] };
554
+ }
555
+ return {
556
+ ...base,
557
+ state: "closed",
558
+ detail: `No GitHub key (such as ${TOKEN_VARIABLES.join(", ")}) is set where the console was started or in Claude Code's settings.`,
559
+ fix: []
560
+ };
561
+ }
562
+ /** Claude Code's settings files for this project and user, each once. */
563
+ function claudeCodeSettingsFiles(options) {
564
+ return [
565
+ ...new Set([
566
+ claudeCodeSettingsPath("user", options),
567
+ join(resolve(options.cwd), ".claude", "settings.json"),
568
+ claudeCodeSettingsPath("project", options)
569
+ ])
570
+ ];
571
+ }
572
+ /** A settings file's `env` block, or `{}` when it has none or can't be read. */
573
+ function settingsEnv(path) {
574
+ try {
575
+ const env = JSON.parse(readText(path) ?? "{}").env;
576
+ return typeof env === "object" && env !== null && !Array.isArray(env) ? env : {};
577
+ }
578
+ catch {
579
+ return {};
580
+ }
581
+ }
582
+ /* ------------------------------------------------- the apps' own servers */
583
+ /** Whether a client entry is a toolbox of ours, judged by what it runs. */
584
+ function isToolboxEntry(server) {
585
+ if (isRemote(server))
586
+ return false;
587
+ return [server.command, ...server.args].some((w) => w.includes("hmcp-gateway") || w.includes("hardened-mcp") || /gateway[\\/]dist[\\/]cli\.js$/.test(w));
588
+ }
589
+ function appServersFromConfigs(options) {
590
+ const scope = { home: options.home, cwd: options.cwd, ...(options.platform ? { platform: options.platform } : {}) };
591
+ const servers = [];
592
+ const unreadable = [];
593
+ // With the project folder at the home folder, a project file and an all-projects file are one file.
594
+ const seen = new Set();
595
+ for (const target of scopeTargets(scope)) {
596
+ try {
597
+ const file = readClientConfig(target.scope, scope);
598
+ for (const [name, server] of parseServers(file.servers).servers) {
599
+ const key = `${target.path}\0${target.where}\0${name}`;
600
+ if (seen.has(key))
601
+ continue;
602
+ seen.add(key);
603
+ servers.push({ client: target.client, name, server });
604
+ }
605
+ }
606
+ catch {
607
+ unreadable.push(target.client);
608
+ }
609
+ }
610
+ return { servers, unreadable };
611
+ }
612
+ function otherServersDoor(options) {
613
+ const base = { id: "other-servers", label: "Other GitHub servers in your AI apps" };
614
+ const { servers, unreadable } = (options.listAppServers ?? (() => appServersFromConfigs(options)))();
615
+ const github = servers.filter((s) => !isToolboxEntry(s.server) && mentionsGithub(s.name, s.server));
616
+ if (github.length > 0) {
617
+ return {
618
+ ...base,
619
+ state: "open",
620
+ detail: `${github.map((s) => `${s.client}: ${s.name}`).join("; ")}. ${github.length === 1 ? "It talks" : "They talk"} to GitHub directly, not through hmcp.`,
621
+ fix: [
622
+ "Connect that app with “Connect an app”, which moves its servers behind your toolbox.",
623
+ "Or remove the entry from the app's settings."
624
+ ]
625
+ };
626
+ }
627
+ if (unreadable.length > 0) {
628
+ return {
629
+ ...base,
630
+ state: "unknown",
631
+ detail: `The settings of ${[...new Set(unreadable)].join(", ")} can't be read, so they weren't checked.`,
632
+ fix: ["Fix the mistake in that app's settings file, then check again."]
633
+ };
634
+ }
635
+ return { ...base, state: "closed", detail: "No AI app on this computer runs its own GitHub server.", fix: [] };
636
+ }
637
+ function mentionsGithub(name, server) {
638
+ const words = isRemote(server) ? [name, server.url] : [name, server.command, ...server.args];
639
+ return words.some((w) => w.toLowerCase().includes("github"));
640
+ }
641
+ /* ------------------------------------------- the doors only a person can close */
642
+ const MANUAL = {
643
+ "github-app-access": {
644
+ label: "Claude's access on GitHub",
645
+ detail: "If you ever let Claude or Anthropic into your GitHub account, GitHub keeps that access on its side. It can't be checked from this computer.",
646
+ links: [
647
+ {
648
+ label: "Open GitHub's authorized apps",
649
+ url: "https://github.com/settings/applications",
650
+ press: "Under “Authorized OAuth Apps” and “Authorized GitHub Apps”, find Claude or Anthropic and press “Revoke”."
651
+ },
652
+ {
653
+ label: "Open GitHub's installed apps",
654
+ url: "https://github.com/settings/installations",
655
+ press: "Find Claude or Anthropic, press “Configure”, then at the bottom of that page press “Uninstall”."
656
+ }
657
+ ]
658
+ },
659
+ "claude-connector": {
660
+ label: "Claude's own GitHub connector",
661
+ detail: "Claude's own GitHub connection runs on Anthropic's servers and can't be checked from this computer.",
662
+ links: [
663
+ {
664
+ label: "Open Claude's connectors",
665
+ url: "https://claude.ai/settings/connectors",
666
+ press: "Find GitHub and press “Disconnect” (it may be under the “…” menu beside it)."
667
+ }
668
+ ]
669
+ }
670
+ };
671
+ function manualDoors(confirmed) {
672
+ return MANUAL_GITHUB_DOORS.map((id) => {
673
+ const door = MANUAL[id];
674
+ const done = confirmed.has(id);
675
+ return {
676
+ id,
677
+ label: door.label,
678
+ state: done ? "closed" : "unknown",
679
+ detail: done ? "You said you've done this. It can't be checked from this computer." : door.detail,
680
+ fix: door.links.map((l) => `${l.url}: ${l.press}`),
681
+ links: door.links,
682
+ why: MANUAL_DOOR_WHY,
683
+ confirmed: done
684
+ };
685
+ });
686
+ }
687
+ /**
688
+ * "I've done this", per door, kept beside hmcp's other files: door names and
689
+ * when, nothing else. Readable by its owner only.
690
+ */
691
+ const ConfirmationsSchema = z.object({ version: z.literal(1), confirmed: z.record(z.string(), z.string()) }).strict();
692
+ export function githubDoorConfirmationsPath(home) {
693
+ return join(resolve(home), ".hmcp", "github-doors-confirmed.json");
694
+ }
695
+ export function readGithubDoorConfirmations(home) {
696
+ const text = readText(githubDoorConfirmationsPath(home));
697
+ if (text === undefined)
698
+ return new Set();
699
+ try {
700
+ const parsed = ConfirmationsSchema.parse(JSON.parse(text));
701
+ return new Set(MANUAL_GITHUB_DOORS.filter((id) => parsed.confirmed[id] !== undefined));
702
+ }
703
+ catch {
704
+ // A broken file reads as nothing confirmed: the safe answer is "can't check".
705
+ return new Set();
706
+ }
707
+ }
708
+ export function isManualGithubDoor(id) {
709
+ return MANUAL_GITHUB_DOORS.includes(id);
710
+ }
711
+ export function confirmGithubDoor(options) {
712
+ if (!isManualGithubDoor(options.door)) {
713
+ throw new ClientConfigError(`"${options.door}" is checked from this computer, so it can't be marked as done by hand.`);
714
+ }
715
+ const current = readGithubDoorConfirmations(options.home);
716
+ if (options.done)
717
+ current.add(options.door);
718
+ else
719
+ current.delete(options.door);
720
+ const path = githubDoorConfirmationsPath(options.home);
721
+ if (current.size === 0) {
722
+ if (existsSync(path))
723
+ unlinkSync(path);
724
+ }
725
+ else {
726
+ const confirmed = Object.fromEntries([...current].map((id) => [id, new Date().toISOString()]));
727
+ writePrivateText(path, `${JSON.stringify({ version: 1, confirmed }, null, 2)}\n`);
728
+ }
729
+ return current;
730
+ }
731
+ /* ------------------------------------------------ the toolbox's own server */
732
+ /** Whether a toolbox's server is GitHub's: by its name, address or what it runs. */
733
+ export function isGithubUpstream(upstream) {
734
+ const words = upstream.transport === "http" ? [upstream.name, upstream.url] : [upstream.name, upstream.command, ...upstream.args];
735
+ return words.some((w) => w.toLowerCase().includes("github"));
736
+ }
737
+ /** GitHub's hosted server: the address that can make changes, and the one that can only look. */
738
+ export const GITHUB_HOSTED_URL = "https://api.githubcopilot.com/mcp/";
739
+ export const GITHUB_HOSTED_READONLY_URL = "https://api.githubcopilot.com/mcp/readonly";
740
+ /**
741
+ * Which of GitHub's two hosted addresses this is, or null for any other
742
+ * address. Only these two are switched by the console: any other address is
743
+ * the person's own, and changing it would be a guess.
744
+ */
745
+ export function githubHostedAccess(upstream) {
746
+ if (upstream.transport !== "http")
747
+ return null;
748
+ let url;
749
+ try {
750
+ url = new URL(upstream.url);
751
+ }
752
+ catch {
753
+ return null;
754
+ }
755
+ if (url.protocol !== "https:" || url.host !== "api.githubcopilot.com" || url.search !== "" || url.hash !== "")
756
+ return null;
757
+ if (/^\/mcp\/readonly\/?$/i.test(url.pathname))
758
+ return "readonly";
759
+ if (/^\/mcp\/?$/.test(url.pathname))
760
+ return githubReadonlyHeader(upstream) ? "readonly" : "changes";
761
+ return null;
762
+ }
763
+ /**
764
+ * GitHub's hosted server also goes read-only when asked with the
765
+ * `X-MCP-Readonly` header, whatever the address. A key kept as a locked-key
766
+ * reference isn't read: only a written value counts.
767
+ */
768
+ export function githubReadonlyHeader(upstream) {
769
+ if (upstream.transport !== "http")
770
+ return false;
771
+ return Object.entries(upstream.headers).some(([name, value]) => name.toLowerCase() === "x-mcp-readonly" && typeof value === "string" && /^(1|true|yes|on)$/i.test(value.trim()));
772
+ }
773
+ /**
774
+ * The GitHub pack's tools that change something, by their own names: what
775
+ * the self-check looks for once changes are switched on.
776
+ */
777
+ export function githubChangeTools() {
778
+ const pack = loadPacks().find((p) => p.name === "github");
779
+ return pack ? Object.entries(pack.tools).filter(([, r]) => r.effect !== "read").map(([name]) => name) : [];
780
+ }