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.
Files changed (84) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +48 -2
  3. package/THIRD-PARTY-NOTICES.md +110 -0
  4. package/bin/hmcp-web.js +20 -0
  5. package/dist/api.d.ts +11 -0
  6. package/dist/api.js +1404 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +40 -0
  9. package/dist/contracts/onboarding.d.ts +233 -0
  10. package/dist/contracts/onboarding.js +1 -0
  11. package/dist/http.d.ts +72 -0
  12. package/dist/http.js +319 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.js +7 -0
  15. package/dist/model/console-settings.d.ts +37 -0
  16. package/dist/model/console-settings.js +74 -0
  17. package/dist/model/doctor.d.ts +68 -0
  18. package/dist/model/doctor.js +254 -0
  19. package/dist/model/fs-browse.d.ts +9 -0
  20. package/dist/model/fs-browse.js +184 -0
  21. package/dist/model/gateway-config.d.ts +287 -0
  22. package/dist/model/gateway-config.js +760 -0
  23. package/dist/model/metrics.d.ts +65 -0
  24. package/dist/model/metrics.js +198 -0
  25. package/dist/model/oauth-flows.d.ts +60 -0
  26. package/dist/model/oauth-flows.js +79 -0
  27. package/dist/model/pipeline.d.ts +58 -0
  28. package/dist/model/pipeline.js +84 -0
  29. package/dist/model/probe.d.ts +155 -0
  30. package/dist/model/probe.js +385 -0
  31. package/dist/model/process.d.ts +100 -0
  32. package/dist/model/process.js +278 -0
  33. package/dist/model/protection.d.ts +378 -0
  34. package/dist/model/protection.js +470 -0
  35. package/dist/model/registry-cache.d.ts +59 -0
  36. package/dist/model/registry-cache.js +238 -0
  37. package/dist/model/scan.d.ts +48 -0
  38. package/dist/model/scan.js +59 -0
  39. package/dist/model/server.d.ts +127 -0
  40. package/dist/model/server.js +243 -0
  41. package/dist/model/tools.d.ts +61 -0
  42. package/dist/model/tools.js +72 -0
  43. package/dist/routes/catalog.d.ts +8 -0
  44. package/dist/routes/catalog.js +47 -0
  45. package/dist/routes/connect.d.ts +14 -0
  46. package/dist/routes/connect.js +633 -0
  47. package/dist/routes/oauth.d.ts +55 -0
  48. package/dist/routes/oauth.js +406 -0
  49. package/dist/routes/policy.d.ts +34 -0
  50. package/dist/routes/policy.js +513 -0
  51. package/dist/routes/runtime.d.ts +6 -0
  52. package/dist/routes/runtime.js +921 -0
  53. package/dist/routes/servers-add.d.ts +24 -0
  54. package/dist/routes/servers-add.js +1091 -0
  55. package/dist/routes/system.d.ts +4 -0
  56. package/dist/routes/system.js +13 -0
  57. package/dist/start.d.ts +56 -0
  58. package/dist/start.js +164 -0
  59. package/dist-ui/assets/Activity-BqKGpXMN.js +1 -0
  60. package/dist-ui/assets/Approvals-Qo7bCcli.js +1 -0
  61. package/dist-ui/assets/AttachApp-0zRSPgSY.js +5 -0
  62. package/dist-ui/assets/Connections-CE0JGe8c.js +2 -0
  63. package/dist-ui/assets/Gallery-B39L2Yma.js +17 -0
  64. package/dist-ui/assets/PreApprovals-BsIhjMqb.js +1 -0
  65. package/dist-ui/assets/Protection-DlB09ABa.js +1 -0
  66. package/dist-ui/assets/Safety-CN-oHO2h.js +1 -0
  67. package/dist-ui/assets/Settings-BLD7G1Ag.js +1 -0
  68. package/dist-ui/assets/StartPage-HuZSnmSr.js +1 -0
  69. package/dist-ui/assets/Suggestions-Dp7pofcs.js +1 -0
  70. package/dist-ui/assets/Tools-Bfot3bx5.js +4 -0
  71. package/dist-ui/assets/index-Khp0l1zp.js +16 -0
  72. package/dist-ui/assets/index-Ylyt4DEr.css +2 -0
  73. package/dist-ui/assets/kit-DQ7Oxf5n.js +4 -0
  74. package/dist-ui/brand/logo-256.png +0 -0
  75. package/dist-ui/brand/logo-512.png +0 -0
  76. package/dist-ui/brand/logo.svg +6 -0
  77. package/dist-ui/brand/mark.svg +5 -0
  78. package/dist-ui/fonts/OFL.txt +99 -0
  79. package/dist-ui/fonts/README.md +21 -0
  80. package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
  81. package/dist-ui/fonts/manrope-latin.woff2 +0 -0
  82. package/dist-ui/index.html +51 -0
  83. package/package.json +69 -6
  84. package/bin/notice.js +0 -7
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./api.js";
2
+ export * from "./http.js";
3
+ export * from "./model/server.js";
4
+ export * from "./model/protection.js";
5
+ export * from "./model/pipeline.js";
6
+ export * from "./model/tools.js";
7
+ export * from "./start.js";
@@ -0,0 +1,37 @@
1
+ import { z } from "zod";
2
+ import type { ConsoleSettings } from "../contracts/onboarding.js";
3
+ /** What PUT accepts: any part of the settings; the rest stays as it is. */
4
+ export declare const SettingsPatchSchema: z.ZodObject<{
5
+ version: z.ZodOptional<z.ZodLiteral<1>>;
6
+ onboarding: z.ZodOptional<z.ZodObject<{
7
+ step: z.ZodOptional<z.ZodEnum<{
8
+ server: "server";
9
+ done: "done";
10
+ welcome: "welcome";
11
+ computer: "computer";
12
+ app: "app";
13
+ try: "try";
14
+ protect: "protect";
15
+ }>>;
16
+ done: z.ZodOptional<z.ZodArray<z.ZodEnum<{
17
+ server: "server";
18
+ done: "done";
19
+ welcome: "welcome";
20
+ computer: "computer";
21
+ app: "app";
22
+ try: "try";
23
+ protect: "protect";
24
+ }>>>;
25
+ dismissed: z.ZodOptional<z.ZodBoolean>;
26
+ }, z.core.$strict>>;
27
+ registry: z.ZodOptional<z.ZodObject<{
28
+ enabled: z.ZodOptional<z.ZodBoolean>;
29
+ }, z.core.$strict>>;
30
+ }, z.core.$strict>;
31
+ export type SettingsPatch = z.infer<typeof SettingsPatchSchema>;
32
+ export declare function defaultConsoleSettings(): ConsoleSettings;
33
+ export declare function consoleSettingsPath(): string;
34
+ export declare function readConsoleSettings(path?: string): ConsoleSettings;
35
+ export declare function writeConsoleSettings(patch: unknown, path?: string): ConsoleSettings;
36
+ /** For the registry routes (workstream D): is the public server list switched on? */
37
+ export declare function registryEnabled(): boolean;
@@ -0,0 +1,74 @@
1
+ import { mkdirSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { z } from "zod";
5
+ import { writeAtomically } from "hmcp-core";
6
+ import { unprocessable } from "../http.js";
7
+ /**
8
+ * The console's own settings, `~/.hmcp/console.json`: where the start page
9
+ * got to, and whether the public server list is used.
10
+ *
11
+ * Separate from every gateway's files on purpose: none of this changes what
12
+ * a gateway lets through, so none of it needs a digest, an acknowledgement or
13
+ * an audit record. A file that is missing or broken reads as the defaults
14
+ * rather than failing the page -- losing your place in the welcome steps is
15
+ * not worth an error screen.
16
+ */
17
+ const STEPS = ["welcome", "computer", "server", "app", "try", "protect", "done"];
18
+ const Step = z.enum(STEPS);
19
+ const SettingsSchema = z
20
+ .object({
21
+ version: z.literal(1),
22
+ onboarding: z.object({ step: Step, done: z.array(Step), dismissed: z.boolean() }).strict(),
23
+ registry: z.object({ enabled: z.boolean() }).strict()
24
+ })
25
+ .strict();
26
+ /** What PUT accepts: any part of the settings; the rest stays as it is. */
27
+ export const SettingsPatchSchema = z
28
+ .object({
29
+ version: z.literal(1).optional(),
30
+ onboarding: z
31
+ .object({ step: Step.optional(), done: z.array(Step).optional(), dismissed: z.boolean().optional() })
32
+ .strict()
33
+ .optional(),
34
+ registry: z.object({ enabled: z.boolean().optional() }).strict().optional()
35
+ })
36
+ .strict();
37
+ export function defaultConsoleSettings() {
38
+ return { version: 1, onboarding: { step: "welcome", done: [], dismissed: false }, registry: { enabled: true } };
39
+ }
40
+ export function consoleSettingsPath() {
41
+ return process.env["HMCP_CONSOLE_SETTINGS"] || join(homedir(), ".hmcp", "console.json");
42
+ }
43
+ export function readConsoleSettings(path = consoleSettingsPath()) {
44
+ try {
45
+ const parsed = SettingsSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
46
+ return parsed.success ? parsed.data : defaultConsoleSettings();
47
+ }
48
+ catch {
49
+ return defaultConsoleSettings();
50
+ }
51
+ }
52
+ export function writeConsoleSettings(patch, path = consoleSettingsPath()) {
53
+ const parsed = SettingsPatchSchema.safeParse(patch ?? {});
54
+ if (!parsed.success) {
55
+ throw unprocessable(`these settings are not valid: ${parsed.error.issues.map((i) => `${i.path.join(".") || "(body)"}: ${i.message}`).join("; ")}`);
56
+ }
57
+ const current = readConsoleSettings(path);
58
+ const next = {
59
+ version: 1,
60
+ onboarding: {
61
+ step: parsed.data.onboarding?.step ?? current.onboarding.step,
62
+ done: [...new Set(parsed.data.onboarding?.done ?? current.onboarding.done)],
63
+ dismissed: parsed.data.onboarding?.dismissed ?? current.onboarding.dismissed
64
+ },
65
+ registry: { enabled: parsed.data.registry?.enabled ?? current.registry.enabled }
66
+ };
67
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
68
+ writeAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
69
+ return next;
70
+ }
71
+ /** For the registry routes (workstream D): is the public server list switched on? */
72
+ export function registryEnabled() {
73
+ return readConsoleSettings().registry.enabled;
74
+ }
@@ -0,0 +1,68 @@
1
+ import type { DoctorResponse, RuntimeCheck } from "../contracts/onboarding.js";
2
+ /**
3
+ * The machine check: which of the programs MCP servers are started with are
4
+ * installed here, where, and which version.
5
+ *
6
+ * Two reasons it is more than `which`:
7
+ *
8
+ * - An AI app started from the Dock or the Start menu does not get the PATH a
9
+ * terminal has. Claude Desktop on macOS sees roughly /usr/bin:/bin, so `npx`
10
+ * from Homebrew or nvm is "not found" there even though it works in a
11
+ * terminal. So this also looks in the places installers put things, and the
12
+ * answer carries absolute paths -- saved commands use them, and the app's
13
+ * entry is given `pathDirs` as its PATH.
14
+ * - "Docker is installed" and "Docker is running" are different problems with
15
+ * different fixes, so `docker info` is asked as well as `--version`.
16
+ *
17
+ * Nothing here runs through a shell: lookups are done in JS and programs are
18
+ * started with execFile.
19
+ */
20
+ export type CheckId = RuntimeCheck["id"];
21
+ export interface DoctorEnvironment {
22
+ readonly platform: NodeJS.Platform;
23
+ readonly arch: string;
24
+ readonly env: NodeJS.ProcessEnv;
25
+ readonly home: string;
26
+ /** Runs a program and gives its stdout; rejects on failure or timeout. Swapped in tests. */
27
+ readonly run: (file: string, args: string[], timeoutMs: number) => Promise<string>;
28
+ /** Replaces the folders searched. Tests only, so the answer does not depend on this computer. */
29
+ readonly dirs?: readonly string[];
30
+ }
31
+ export declare function hostEnvironment(): DoctorEnvironment;
32
+ /** The folders a system puts on every program's PATH. */
33
+ export declare function systemDefaultDirs(platform: NodeJS.Platform, env?: NodeJS.ProcessEnv): string[];
34
+ /**
35
+ * Places installers put programs that a GUI app's PATH does not include.
36
+ * Searched after PATH, so what a terminal would run still wins.
37
+ */
38
+ export declare function extraDirs(platform: NodeJS.Platform, home: string, env: NodeJS.ProcessEnv): string[];
39
+ /** PATH first, then the extra places, then the system defaults, without repeats. */
40
+ export declare function searchDirs(environment: Pick<DoctorEnvironment, "platform" | "env" | "home">): string[];
41
+ /**
42
+ * A pure-JS `which`. On Windows each PATHEXT extension is tried, because
43
+ * `npx` there is `npx.cmd`.
44
+ */
45
+ export declare function findOnPath(name: string, dirs: readonly string[], platform: NodeJS.Platform, env?: NodeJS.ProcessEnv): string | null;
46
+ /** "v22.19.0", "uv 0.5.1 (abc 2024-..)", "Docker version 27.3.1, build ..." -> the number. */
47
+ export declare function parseVersion(output: string): string | null;
48
+ /** Runs the whole check. Use `doctor()` from a route; this is uncached. */
49
+ export declare function runDoctor(environment?: DoctorEnvironment): Promise<DoctorResponse>;
50
+ /**
51
+ * The check, cached for a minute: the start page, Test it and install all ask,
52
+ * and a `docker info` against a stopped daemon takes the whole timeout.
53
+ * `fresh` is the "Check again" button, after someone installed something.
54
+ */
55
+ export declare function doctor(options?: {
56
+ fresh?: boolean;
57
+ now?: number;
58
+ }): Promise<DoctorResponse>;
59
+ /** For tests. */
60
+ export declare function clearDoctorCache(): void;
61
+ /**
62
+ * Absolute paths keyed by program name, for `materializeDraft`'s
63
+ * `commandPaths` ("npx" -> "/opt/homebrew/bin/npx"). `python3` and `python`
64
+ * both map to whichever was found.
65
+ */
66
+ export declare function commandPathsFrom(result: DoctorResponse): Record<string, string>;
67
+ /** The folders an AI app's entry should have on PATH (for connectRoutes' `deps.pathDirs`). */
68
+ export declare function doctorPathDirs(): Promise<string[]>;
@@ -0,0 +1,254 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readdirSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter as hostDelimiter, join, dirname } from "node:path";
5
+ /** What is looked for, in order. `python` tries python3 first. */
6
+ const PROGRAMS = [
7
+ { id: "node", names: ["node"] },
8
+ { id: "npx", names: ["npx"] },
9
+ { id: "uv", names: ["uv"] },
10
+ { id: "uvx", names: ["uvx"] },
11
+ { id: "docker", names: ["docker"] },
12
+ { id: "python", names: ["python3", "python"] },
13
+ { id: "git", names: ["git"] }
14
+ ];
15
+ const VERSION_TIMEOUT_MS = 3_000;
16
+ const CACHE_MS = 60_000;
17
+ function defaultRun(platform) {
18
+ return (file, args, timeoutMs) => new Promise((resolvePromise, reject) => {
19
+ /*
20
+ * On Windows a .cmd or .bat (npx.cmd) cannot be started by execFile
21
+ * without a shell any more (Node refuses since the 2024 fix for
22
+ * argument injection). cmd.exe is named explicitly with the path as one
23
+ * argument instead of turning the shell on for everything.
24
+ */
25
+ const viaCmd = platform === "win32" && /\.(cmd|bat)$/i.test(file);
26
+ const [exe, argv] = viaCmd ? ["cmd.exe", ["/d", "/s", "/c", file, ...args]] : [file, args];
27
+ execFile(exe, argv, { timeout: timeoutMs, windowsHide: true, encoding: "utf8" }, (err, stdout, stderr) => {
28
+ if (err)
29
+ reject(err);
30
+ else
31
+ resolvePromise(`${stdout}${stdout ? "" : stderr}`);
32
+ });
33
+ });
34
+ }
35
+ export function hostEnvironment() {
36
+ return {
37
+ platform: process.platform,
38
+ arch: process.arch,
39
+ env: process.env,
40
+ home: homedir(),
41
+ run: defaultRun(process.platform)
42
+ };
43
+ }
44
+ function pathDelimiter(platform) {
45
+ return platform === "win32" ? ";" : platform === process.platform ? hostDelimiter : ":";
46
+ }
47
+ function joinFor(platform, ...parts) {
48
+ return platform === "win32" ? parts.join("\\").replace(/\\+/g, "\\") : join(...parts);
49
+ }
50
+ /** The folders a system puts on every program's PATH. */
51
+ export function systemDefaultDirs(platform, env = {}) {
52
+ if (platform === "win32") {
53
+ const root = env["SystemRoot"] ?? env["windir"] ?? "C:\\Windows";
54
+ return [`${root}\\System32`, root];
55
+ }
56
+ return ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
57
+ }
58
+ /** The newest nvm-installed node's bin folder, or the one nvm says is current. */
59
+ function nvmBin(home, env) {
60
+ if (env["NVM_BIN"])
61
+ return [env["NVM_BIN"]];
62
+ const versions = join(env["NVM_DIR"] ?? join(home, ".nvm"), "versions", "node");
63
+ try {
64
+ const found = readdirSync(versions)
65
+ .filter((v) => /^v\d+\.\d+\.\d+$/.test(v))
66
+ .sort((a, b) => {
67
+ const pa = a.slice(1).split(".").map(Number);
68
+ const pb = b.slice(1).split(".").map(Number);
69
+ for (let i = 0; i < 3; i++)
70
+ if (pa[i] !== pb[i])
71
+ return pb[i] - pa[i];
72
+ return 0;
73
+ });
74
+ return found.length > 0 ? [join(versions, found[0], "bin")] : [];
75
+ }
76
+ catch {
77
+ return [];
78
+ }
79
+ }
80
+ /**
81
+ * Places installers put programs that a GUI app's PATH does not include.
82
+ * Searched after PATH, so what a terminal would run still wins.
83
+ */
84
+ export function extraDirs(platform, home, env) {
85
+ if (platform === "win32") {
86
+ const pf = env["ProgramFiles"] ?? "C:\\Program Files";
87
+ const appData = env["APPDATA"] ?? joinFor(platform, home, "AppData", "Roaming");
88
+ const local = env["LOCALAPPDATA"] ?? joinFor(platform, home, "AppData", "Local");
89
+ return [
90
+ joinFor(platform, pf, "nodejs"),
91
+ joinFor(platform, appData, "npm"),
92
+ joinFor(platform, home, ".local", "bin"),
93
+ joinFor(platform, home, ".cargo", "bin"),
94
+ joinFor(platform, local, "Volta", "bin"),
95
+ joinFor(platform, pf, "Docker", "Docker", "resources", "bin"),
96
+ joinFor(platform, pf, "Git", "cmd")
97
+ ];
98
+ }
99
+ return [
100
+ "/opt/homebrew/bin",
101
+ "/usr/local/bin",
102
+ join(home, ".local", "bin"),
103
+ join(home, ".cargo", "bin"),
104
+ ...nvmBin(home, env),
105
+ join(env["VOLTA_HOME"] ?? join(home, ".volta"), "bin"),
106
+ ...(platform === "darwin" ? ["/Applications/Docker.app/Contents/Resources/bin"] : [])
107
+ ];
108
+ }
109
+ /** PATH first, then the extra places, then the system defaults, without repeats. */
110
+ export function searchDirs(environment) {
111
+ const { platform, env, home } = environment;
112
+ const pathVar = env["PATH"] ?? env["Path"] ?? "";
113
+ const fromPath = pathVar.split(pathDelimiter(platform)).filter((d) => d.length > 0);
114
+ const seen = new Set();
115
+ const out = [];
116
+ for (const dir of [...fromPath, ...extraDirs(platform, home, env), ...systemDefaultDirs(platform, env)]) {
117
+ const key = platform === "win32" ? dir.toLowerCase() : dir;
118
+ if (seen.has(key))
119
+ continue;
120
+ seen.add(key);
121
+ out.push(dir);
122
+ }
123
+ return out;
124
+ }
125
+ function isExecutableFile(path, platform) {
126
+ try {
127
+ const st = statSync(path);
128
+ if (!st.isFile())
129
+ return false;
130
+ return platform === "win32" ? true : (st.mode & 0o111) !== 0;
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }
136
+ /**
137
+ * A pure-JS `which`. On Windows each PATHEXT extension is tried, because
138
+ * `npx` there is `npx.cmd`.
139
+ */
140
+ export function findOnPath(name, dirs, platform, env = {}) {
141
+ const exts = platform === "win32"
142
+ ? (env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((e) => e.toLowerCase())
143
+ : [""];
144
+ for (const dir of dirs) {
145
+ for (const ext of exts) {
146
+ const candidate = join(dir, name + ext);
147
+ if (isExecutableFile(candidate, platform))
148
+ return candidate;
149
+ }
150
+ }
151
+ return null;
152
+ }
153
+ /** "v22.19.0", "uv 0.5.1 (abc 2024-..)", "Docker version 27.3.1, build ..." -> the number. */
154
+ export function parseVersion(output) {
155
+ const line = output.split(/\r?\n/).find((l) => l.trim().length > 0) ?? "";
156
+ const match = /(\d+\.\d+(?:\.\d+)?)/.exec(line);
157
+ return match ? match[1] : null;
158
+ }
159
+ async function check(environment, id, names, dirs) {
160
+ let path = null;
161
+ for (const name of names) {
162
+ path = findOnPath(name, dirs, environment.platform, environment.env);
163
+ if (path)
164
+ break;
165
+ }
166
+ if (!path)
167
+ return { id, found: false, path: null, version: null };
168
+ let version = null;
169
+ let problem;
170
+ try {
171
+ version = parseVersion(await environment.run(path, ["--version"], VERSION_TIMEOUT_MS));
172
+ }
173
+ catch (err) {
174
+ problem = `found at ${path}, but it did not answer when asked its version (${err.message.split("\n")[0]})`;
175
+ }
176
+ const out = { id, found: true, path, version, ...(problem ? { problem } : {}) };
177
+ if (id === "docker") {
178
+ try {
179
+ await environment.run(path, ["info", "--format", "{{.ServerVersion}}"], VERSION_TIMEOUT_MS);
180
+ out.running = true;
181
+ }
182
+ catch {
183
+ out.running = false;
184
+ out.problem ??= "Docker is installed but not running. Open Docker Desktop and wait until it says it is running.";
185
+ }
186
+ }
187
+ return out;
188
+ }
189
+ /** Runs the whole check. Use `doctor()` from a route; this is uncached. */
190
+ export async function runDoctor(environment = hostEnvironment()) {
191
+ const dirs = environment.dirs ?? searchDirs(environment);
192
+ const checks = await Promise.all(PROGRAMS.map((p) => check(environment, p.id, p.names, dirs)));
193
+ const found = checks.filter((c) => c.found && c.path).map((c) => dirnameFor(environment.platform, c.path));
194
+ const seen = new Set();
195
+ const pathDirs = [];
196
+ for (const dir of [...found, ...systemDefaultDirs(environment.platform, environment.env)]) {
197
+ const key = environment.platform === "win32" ? dir.toLowerCase() : dir;
198
+ if (seen.has(key))
199
+ continue;
200
+ seen.add(key);
201
+ pathDirs.push(dir);
202
+ }
203
+ return { platform: environment.platform, arch: environment.arch, checks, pathDirs };
204
+ }
205
+ function dirnameFor(platform, path) {
206
+ if (platform !== "win32")
207
+ return dirname(path);
208
+ const i = path.lastIndexOf("\\");
209
+ return i > 0 ? path.slice(0, i) : path;
210
+ }
211
+ let cached = null;
212
+ /**
213
+ * The check, cached for a minute: the start page, Test it and install all ask,
214
+ * and a `docker info` against a stopped daemon takes the whole timeout.
215
+ * `fresh` is the "Check again" button, after someone installed something.
216
+ */
217
+ export function doctor(options = {}) {
218
+ const now = options.now ?? Date.now();
219
+ if (!options.fresh && cached && now - cached.at < CACHE_MS)
220
+ return cached.result;
221
+ const result = runDoctor();
222
+ cached = { at: now, result };
223
+ // A failed run is not kept, so the next ask tries again.
224
+ result.catch(() => {
225
+ if (cached?.result === result)
226
+ cached = null;
227
+ });
228
+ return result;
229
+ }
230
+ /** For tests. */
231
+ export function clearDoctorCache() {
232
+ cached = null;
233
+ }
234
+ /**
235
+ * Absolute paths keyed by program name, for `materializeDraft`'s
236
+ * `commandPaths` ("npx" -> "/opt/homebrew/bin/npx"). `python3` and `python`
237
+ * both map to whichever was found.
238
+ */
239
+ export function commandPathsFrom(result) {
240
+ const out = {};
241
+ for (const c of result.checks) {
242
+ if (!c.found || !c.path)
243
+ continue;
244
+ out[c.id] = c.path;
245
+ if (c.id === "python") {
246
+ out["python3"] = c.path;
247
+ }
248
+ }
249
+ return out;
250
+ }
251
+ /** The folders an AI app's entry should have on PATH (for connectRoutes' `deps.pathDirs`). */
252
+ export async function doctorPathDirs() {
253
+ return (await doctor()).pathDirs;
254
+ }
@@ -0,0 +1,9 @@
1
+ import type { DirListing } from "../contracts/onboarding.js";
2
+ /** Plain words when choosing this folder gives a server more than anyone means to. */
3
+ export declare function folderWarning(path: string, home: string, platform?: NodeJS.Platform): string | undefined;
4
+ export declare function shortcuts(home: string, platform?: NodeJS.Platform): DirListing["shortcuts"];
5
+ /** One folder's sub-folders. `raw` empty means the home folder. */
6
+ export declare function listDirs(raw: string | null, options?: {
7
+ home?: string;
8
+ platform?: NodeJS.Platform;
9
+ }): DirListing;
@@ -0,0 +1,184 @@
1
+ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
4
+ import { HttpError, notFound, unprocessable } from "../http.js";
5
+ /**
6
+ * The folder picker's view of the disk: folder names, and nothing else.
7
+ *
8
+ * A server like Filesystem is given folders, and typing a path is where a
9
+ * non-technical person gets stuck. This lets the browser walk folders without
10
+ * the console ever sending a file name or a byte of content -- the picker
11
+ * does not need them, and the console is not a file browser.
12
+ *
13
+ * Hidden folders (".git", ".ssh") are left out: nobody choosing "my
14
+ * documents" means them, and `.ssh` is the last thing to hand a server.
15
+ */
16
+ const MAX_ENTRIES = 500;
17
+ /** Windows folders that are not really anyone's. */
18
+ const WINDOWS_SYSTEM = new Set(["$recycle.bin", "system volume information", "$windows.~bt", "$windows.~ws", "config.msi"]);
19
+ function samePath(a, b, platform) {
20
+ return platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
21
+ }
22
+ function within(child, parent, platform) {
23
+ const c = platform === "win32" ? child.toLowerCase() : child;
24
+ const p = platform === "win32" ? parent.toLowerCase() : parent;
25
+ return c === p || c.startsWith(p.endsWith(sep) ? p : p + sep);
26
+ }
27
+ /** Hidden folders in a home folder that hold sign-in keys, by name. */
28
+ const KEY_FOLDERS = {
29
+ ".ssh": "the keys this computer uses to sign in to other computers (SSH)",
30
+ ".aws": "your Amazon Web Services keys",
31
+ ".gnupg": "your encryption keys",
32
+ ".kube": "the keys to your Kubernetes clusters",
33
+ ".docker": "your Docker sign-ins",
34
+ ".azure": "your Microsoft Azure sign-ins",
35
+ ".config": "many programs' settings, often with their sign-ins",
36
+ ".gcloud": "your Google Cloud keys",
37
+ ".npmrc": "your npm sign-in"
38
+ };
39
+ /** Folders that belong to the computer itself, not to any one person. */
40
+ const SYSTEM_POSIX = ["/etc", "/private/etc", "/System", "/usr", "/bin", "/sbin", "/var", "/private/var", "/Library", "/opt", "/boot", "/proc", "/sys", "/root"];
41
+ /** Plain words when choosing this folder gives a server more than anyone means to. */
42
+ export function folderWarning(path, home, platform = process.platform) {
43
+ const candidates = [path];
44
+ try {
45
+ // A link ("Documents/ssh-link" -> ~/.ssh) is judged by where it really goes, too.
46
+ const real = realpathSync(path);
47
+ if (!samePath(real, path, platform))
48
+ candidates.push(real);
49
+ }
50
+ catch {
51
+ /* a folder that cannot be resolved is judged by its name */
52
+ }
53
+ const homes = [home];
54
+ try {
55
+ homes.push(realpathSync(home));
56
+ }
57
+ catch {
58
+ /* judged by its name */
59
+ }
60
+ for (const p of candidates) {
61
+ if (parse(p).root === p) {
62
+ return "This is the top of your computer's disk: a server given it can reach every file on this computer.";
63
+ }
64
+ for (const h of homes) {
65
+ if (samePath(p, h, platform)) {
66
+ return "This is your whole home folder: every file you have, including private ones. Choose a folder inside it instead.";
67
+ }
68
+ if (within(p, join(h, ".hmcp"), platform)) {
69
+ return "This is hardened-mcp's own folder, where your locked keys and settings live. A server given it could read or change them.";
70
+ }
71
+ if (within(p, h, platform)) {
72
+ const first = p.slice(h.length).split(/[\\/]+/).filter(Boolean)[0] ?? "";
73
+ const keys = KEY_FOLDERS[platform === "win32" ? first.toLowerCase() : first];
74
+ if (keys)
75
+ return `This folder holds ${keys}. A server given it could use them to act as you. Choose another folder.`;
76
+ if (first.startsWith(".")) {
77
+ return "This is a hidden folder, where programs keep their own settings and sometimes their keys. Choose one of your own folders instead.";
78
+ }
79
+ if (platform === "darwin" && first === "Library") {
80
+ return "This is where your apps keep their own data, including saved sign-ins and browser data. Choose one of your own folders instead.";
81
+ }
82
+ if (platform === "win32" && first.toLowerCase() === "appdata") {
83
+ return "This is where your apps keep their own data, including saved sign-ins and browser data. Choose one of your own folders instead.";
84
+ }
85
+ }
86
+ }
87
+ // Inside your own home folder, the checks above are the ones that matter.
88
+ if (homes.some((h) => within(p, h, platform)))
89
+ continue;
90
+ const homesRoot = dirname(home);
91
+ const isHomesRoot = /^(\/Users|\/home|[A-Za-z]:\\Users)$/i.test(homesRoot);
92
+ if (isHomesRoot && samePath(p, homesRoot, platform)) {
93
+ return "This folder holds the home folder of everyone who uses this computer. Choose one of your own folders instead.";
94
+ }
95
+ if (isHomesRoot && within(p, homesRoot, platform) && !within(p, join(homesRoot, "Shared"), platform)) {
96
+ return "This is another person's home folder on this computer. Choose one of your own folders instead.";
97
+ }
98
+ if (platform === "win32") {
99
+ if (/^[A-Za-z]:\\(windows|program files( \(x86\))?|programdata)(\\|$)/i.test(p)) {
100
+ return "This is one of the computer's own system folders. A server given it could change how this computer works. Choose one of your own folders instead.";
101
+ }
102
+ }
103
+ else if (SYSTEM_POSIX.some((s) => within(p, s, platform))) {
104
+ return "This is one of the computer's own system folders. A server given it could read its settings or change how it works. Choose one of your own folders instead.";
105
+ }
106
+ }
107
+ return undefined;
108
+ }
109
+ export function shortcuts(home, platform = process.platform) {
110
+ const out = [{ label: "Home", path: home }];
111
+ for (const name of ["Desktop", "Documents", "Downloads"]) {
112
+ const path = join(home, name);
113
+ if (existsSync(path))
114
+ out.push({ label: name, path });
115
+ }
116
+ if (platform === "win32") {
117
+ for (const letter of "CDEFGHIJKLMNOPQRSTUVWXYZ") {
118
+ const drive = `${letter}:\\`;
119
+ if (existsSync(drive))
120
+ out.push({ label: `${letter}: drive`, path: drive });
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ /** One folder's sub-folders. `raw` empty means the home folder. */
126
+ export function listDirs(raw, options = {}) {
127
+ const home = options.home ?? homedir();
128
+ const platform = options.platform ?? process.platform;
129
+ const requested = raw && raw.trim() ? raw.trim() : home;
130
+ if (requested.includes("\0") || !isAbsolute(requested)) {
131
+ throw unprocessable("A folder has to be given as a full path, starting from the top of the disk.");
132
+ }
133
+ const path = resolve(requested);
134
+ let entries;
135
+ try {
136
+ if (!statSync(path).isDirectory())
137
+ throw unprocessable(`${path} is a file, not a folder.`);
138
+ entries = readdirSync(path, { withFileTypes: true });
139
+ }
140
+ catch (err) {
141
+ if (err instanceof HttpError)
142
+ throw err;
143
+ const code = err.code;
144
+ if (code === "ENOENT")
145
+ throw notFound(`There is no folder at ${path}.`);
146
+ if (code === "EACCES" || code === "EPERM") {
147
+ throw new HttpError(403, "forbidden", `This computer does not let the console look inside ${path}. Choose another folder.`);
148
+ }
149
+ throw unprocessable(`${path} could not be opened: ${err.message}`);
150
+ }
151
+ const dirs = [];
152
+ for (const entry of entries) {
153
+ if (entry.name.startsWith("."))
154
+ continue;
155
+ if (platform === "win32" && WINDOWS_SYSTEM.has(entry.name.toLowerCase()))
156
+ continue;
157
+ const full = join(path, entry.name);
158
+ if (entry.isDirectory()) {
159
+ dirs.push({ name: entry.name, path: full });
160
+ }
161
+ else if (entry.isSymbolicLink()) {
162
+ // Shown with where it really goes, so "Documents" pointing at a cloud drive is not a surprise.
163
+ try {
164
+ if (!statSync(full).isDirectory())
165
+ continue;
166
+ dirs.push({ name: entry.name, path: full, symlinkTo: realpathSync(full) });
167
+ }
168
+ catch {
169
+ /* a broken link is not a folder anyone can pick */
170
+ }
171
+ }
172
+ }
173
+ dirs.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
174
+ const parent = dirname(path);
175
+ const warning = folderWarning(path, home, platform);
176
+ return {
177
+ path,
178
+ parent: parent === path ? null : parent,
179
+ dirs: dirs.slice(0, MAX_ENTRIES),
180
+ truncated: dirs.length > MAX_ENTRIES,
181
+ shortcuts: shortcuts(home, platform),
182
+ ...(warning ? { warning } : {})
183
+ };
184
+ }