hmcp-web 0.0.1 → 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/LICENSE +77 -0
- package/README.md +49 -2
- package/THIRD-PARTY-NOTICES.md +110 -0
- package/bin/hmcp-web.js +20 -0
- package/dist/api.d.ts +22 -0
- package/dist/api.js +1458 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +40 -0
- package/dist/contracts/onboarding.d.ts +233 -0
- package/dist/contracts/onboarding.js +1 -0
- package/dist/http.d.ts +72 -0
- package/dist/http.js +319 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/model/app-servers.d.ts +85 -0
- package/dist/model/app-servers.js +109 -0
- package/dist/model/console-settings.d.ts +37 -0
- package/dist/model/console-settings.js +74 -0
- package/dist/model/doctor.d.ts +68 -0
- package/dist/model/doctor.js +254 -0
- package/dist/model/fs-browse.d.ts +9 -0
- package/dist/model/fs-browse.js +184 -0
- package/dist/model/gateway-config.d.ts +287 -0
- package/dist/model/gateway-config.js +760 -0
- package/dist/model/import-record.d.ts +80 -0
- package/dist/model/import-record.js +179 -0
- package/dist/model/metrics.d.ts +65 -0
- package/dist/model/metrics.js +213 -0
- package/dist/model/oauth-flows.d.ts +60 -0
- package/dist/model/oauth-flows.js +79 -0
- package/dist/model/pipeline.d.ts +58 -0
- package/dist/model/pipeline.js +84 -0
- package/dist/model/probe.d.ts +155 -0
- package/dist/model/probe.js +385 -0
- package/dist/model/process.d.ts +100 -0
- package/dist/model/process.js +278 -0
- package/dist/model/protection.d.ts +378 -0
- package/dist/model/protection.js +470 -0
- package/dist/model/registry-cache.d.ts +59 -0
- package/dist/model/registry-cache.js +238 -0
- package/dist/model/scan.d.ts +48 -0
- package/dist/model/scan.js +59 -0
- package/dist/model/server.d.ts +127 -0
- package/dist/model/server.js +243 -0
- package/dist/model/tools.d.ts +61 -0
- package/dist/model/tools.js +72 -0
- package/dist/routes/catalog.d.ts +8 -0
- package/dist/routes/catalog.js +47 -0
- package/dist/routes/connect-import.d.ts +9 -0
- package/dist/routes/connect-import.js +594 -0
- package/dist/routes/connect.d.ts +50 -0
- package/dist/routes/connect.js +691 -0
- 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/oauth.d.ts +55 -0
- package/dist/routes/oauth.js +406 -0
- package/dist/routes/policy.d.ts +34 -0
- package/dist/routes/policy.js +513 -0
- package/dist/routes/runtime.d.ts +12 -0
- package/dist/routes/runtime.js +921 -0
- package/dist/routes/servers-add.d.ts +32 -0
- package/dist/routes/servers-add.js +1091 -0
- package/dist/routes/system.d.ts +4 -0
- package/dist/routes/system.js +13 -0
- package/dist/start.d.ts +56 -0
- package/dist/start.js +164 -0
- package/dist-ui/assets/Activity-CZ78RyRO.js +1 -0
- 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-DB_OO7Vw.js +17 -0
- package/dist-ui/assets/PreApprovals-C4cKajcK.js +1 -0
- package/dist-ui/assets/Protection-B8h-5YAb.js +1 -0
- package/dist-ui/assets/Safety-BQqHyYdo.js +1 -0
- package/dist-ui/assets/Settings-Cx50zZSt.js +1 -0
- package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
- package/dist-ui/assets/Suggestions-CRo5UOTT.js +1 -0
- 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-DRVm92_t.js +4 -0
- package/dist-ui/brand/logo-256.png +0 -0
- package/dist-ui/brand/logo-512.png +0 -0
- package/dist-ui/brand/logo.svg +6 -0
- package/dist-ui/brand/mark.svg +5 -0
- package/dist-ui/fonts/OFL.txt +99 -0
- package/dist-ui/fonts/README.md +21 -0
- package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
- package/dist-ui/fonts/manrope-latin.woff2 +0 -0
- package/dist-ui/index.html +51 -0
- package/package.json +69 -6
- package/bin/notice.js +0 -7
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { dirname, isAbsolute, resolve } from "node:path";
|
|
3
|
+
import { existsSync, statSync } from "node:fs";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { AuditLog, expandPath, readRegistry } from "hmcp-core";
|
|
6
|
+
import { GuardInstallError, guardStatus, installGuard, loadGatewayConfig, uninstallGuard } from "hmcp-gateway";
|
|
7
|
+
import { badRequest, route, unprocessable } from "../http.js";
|
|
8
|
+
/**
|
|
9
|
+
* "Guard every Claude Code tool with hmcp": the guard's hooks in Claude
|
|
10
|
+
* Code's settings, added or taken out from the console.
|
|
11
|
+
*
|
|
12
|
+
* Like the connect routes, this writes another program's settings, so the
|
|
13
|
+
* browser names a scope and a toolbox and never a file: the settings path is
|
|
14
|
+
* the one `guardSettingsPath` resolves, and the config is the registered
|
|
15
|
+
* toolbox's own. The response names files and says what happened; it never
|
|
16
|
+
* echoes the settings file, which can hold a person's environment and keys.
|
|
17
|
+
*/
|
|
18
|
+
const Body = z
|
|
19
|
+
.object({
|
|
20
|
+
scope: z.enum(["user", "project"]),
|
|
21
|
+
projectDir: z.string().min(1).optional(),
|
|
22
|
+
/** Which toolbox's policy checks the calls. Optional when only one is registered. */
|
|
23
|
+
serverId: z.string().min(1).optional(),
|
|
24
|
+
install: z.boolean(),
|
|
25
|
+
confirm: z.literal(true)
|
|
26
|
+
})
|
|
27
|
+
.strict();
|
|
28
|
+
function projectDirOf(raw, scope) {
|
|
29
|
+
if (scope !== "project")
|
|
30
|
+
return undefined;
|
|
31
|
+
if (!raw)
|
|
32
|
+
throw unprocessable("a project install needs projectDir, the project folder");
|
|
33
|
+
if (raw.includes("\0") || !isAbsolute(raw) || raw.split(/[\\/]+/).some((p) => p === "." || p === "..")) {
|
|
34
|
+
throw unprocessable("projectDir must be an absolute path, written plainly");
|
|
35
|
+
}
|
|
36
|
+
const dir = resolve(raw);
|
|
37
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory())
|
|
38
|
+
throw unprocessable(`projectDir ${dir} is not a folder`);
|
|
39
|
+
return dir;
|
|
40
|
+
}
|
|
41
|
+
/** The toolbox whose gateway.yaml the guard checks calls against. */
|
|
42
|
+
function toolboxConfig(options, serverId) {
|
|
43
|
+
const gateways = readRegistry(options.registryPath).servers.filter((s) => s.kind === "gateway");
|
|
44
|
+
const entry = serverId ? gateways.find((s) => s.id === serverId) : gateways.length === 1 ? gateways[0] : undefined;
|
|
45
|
+
if (!entry) {
|
|
46
|
+
throw unprocessable(serverId
|
|
47
|
+
? `there is no toolbox called "${serverId}"`
|
|
48
|
+
: "say which toolbox should check Claude Code's calls (serverId): there is more than one, or none");
|
|
49
|
+
}
|
|
50
|
+
return { id: entry.id, configPath: expandPath(entry.config_path) };
|
|
51
|
+
}
|
|
52
|
+
/** The toolbox's own log, so turning the guard on or off is recorded beside what it then decides. */
|
|
53
|
+
function auditFor(configPath, actor) {
|
|
54
|
+
try {
|
|
55
|
+
const { policy } = loadGatewayConfig(configPath);
|
|
56
|
+
return policy.audit.enabled
|
|
57
|
+
? new AuditLog({ config: policy.audit, actor, component: "hmcp-web", cwd: dirname(configPath) })
|
|
58
|
+
: null;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export function guardRoutes(options) {
|
|
65
|
+
// The outermost layer, and the only place the real home folder is assumed.
|
|
66
|
+
const home = () => options.home ?? homedir();
|
|
67
|
+
return [
|
|
68
|
+
route("GET", "/api/v1/guard/claude-code", (ctx) => {
|
|
69
|
+
const scope = ctx.query.get("scope") ?? "user";
|
|
70
|
+
if (scope !== "user" && scope !== "project")
|
|
71
|
+
throw badRequest('scope must be "user" or "project"');
|
|
72
|
+
const projectDir = projectDirOf(ctx.query.get("projectDir"), scope);
|
|
73
|
+
try {
|
|
74
|
+
const status = guardStatus({ scope, home: home(), ...(projectDir ? { projectDir } : {}) });
|
|
75
|
+
const server = status.configPath
|
|
76
|
+
? readRegistry(options.registryPath).servers.find((s) => expandPath(s.config_path) === status.configPath)
|
|
77
|
+
: undefined;
|
|
78
|
+
return { ...status, serverId: server?.id ?? null };
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
if (err instanceof GuardInstallError)
|
|
82
|
+
throw unprocessable(err.message);
|
|
83
|
+
throw err;
|
|
84
|
+
}
|
|
85
|
+
}),
|
|
86
|
+
route("POST", "/api/v1/guard/claude-code", (ctx) => {
|
|
87
|
+
const parsed = Body.safeParse(ctx.body ?? {});
|
|
88
|
+
if (!parsed.success) {
|
|
89
|
+
throw badRequest("the request body is not valid", parsed.error.issues.map((i) => ({ path: i.path.join(".") || "(root)", message: i.message })));
|
|
90
|
+
}
|
|
91
|
+
const body = parsed.data;
|
|
92
|
+
const projectDir = projectDirOf(body.projectDir, body.scope);
|
|
93
|
+
const where = { scope: body.scope, home: home(), ...(projectDir ? { projectDir } : {}) };
|
|
94
|
+
try {
|
|
95
|
+
if (body.install) {
|
|
96
|
+
const { id, configPath } = toolboxConfig(options, body.serverId);
|
|
97
|
+
const result = installGuard({
|
|
98
|
+
...where,
|
|
99
|
+
configPath,
|
|
100
|
+
...(options.guardCliPath ? { local: true, cliPath: options.guardCliPath } : {})
|
|
101
|
+
});
|
|
102
|
+
const warning = result.changed
|
|
103
|
+
? note(auditFor(configPath, ctx.actor), {
|
|
104
|
+
tool: "(guard)",
|
|
105
|
+
effect: null,
|
|
106
|
+
decision: "allow",
|
|
107
|
+
rule_id: "guard.install",
|
|
108
|
+
reason: `the Claude Code guard was turned on by ${ctx.actor} in the console: hooks added to ${result.settingsPath}`,
|
|
109
|
+
outcome: "completed",
|
|
110
|
+
args_redacted: { scope: body.scope, settings: result.settingsPath, server_id: id }
|
|
111
|
+
})
|
|
112
|
+
: null;
|
|
113
|
+
return {
|
|
114
|
+
installed: true,
|
|
115
|
+
changed: result.changed,
|
|
116
|
+
settingsPath: result.settingsPath,
|
|
117
|
+
configPath: result.configPath,
|
|
118
|
+
serverId: id,
|
|
119
|
+
waitSeconds: result.waitSeconds,
|
|
120
|
+
observing: result.observing,
|
|
121
|
+
gitignoreWarning: result.gitignoreWarning,
|
|
122
|
+
restartHint: "Restart Claude Code after turning this on.",
|
|
123
|
+
warning
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const before = guardStatus(where);
|
|
127
|
+
const result = uninstallGuard(where);
|
|
128
|
+
const warning = result.removed > 0 && before.configPath
|
|
129
|
+
? note(auditFor(before.configPath, ctx.actor), {
|
|
130
|
+
tool: "(guard)",
|
|
131
|
+
effect: null,
|
|
132
|
+
decision: "allow",
|
|
133
|
+
rule_id: "guard.uninstall",
|
|
134
|
+
reason: `the Claude Code guard was turned off by ${ctx.actor} in the console: hooks removed from ${result.settingsPath}`,
|
|
135
|
+
outcome: "completed",
|
|
136
|
+
args_redacted: { scope: body.scope, settings: result.settingsPath }
|
|
137
|
+
})
|
|
138
|
+
: null;
|
|
139
|
+
return {
|
|
140
|
+
installed: false,
|
|
141
|
+
changed: result.removed > 0,
|
|
142
|
+
settingsPath: result.settingsPath,
|
|
143
|
+
restartHint: "Restart Claude Code after turning this off.",
|
|
144
|
+
warning
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
if (err instanceof GuardInstallError)
|
|
149
|
+
throw unprocessable(err.message);
|
|
150
|
+
throw err;
|
|
151
|
+
}
|
|
152
|
+
})
|
|
153
|
+
];
|
|
154
|
+
}
|
|
155
|
+
/** Appends one record; a failure is a warning, because the change itself already happened. */
|
|
156
|
+
function note(log, entry) {
|
|
157
|
+
if (!log)
|
|
158
|
+
return "this toolbox keeps no activity log, so the change was not recorded there";
|
|
159
|
+
try {
|
|
160
|
+
log.appendStrict(entry);
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
catch (err) {
|
|
164
|
+
return `the change was made but the activity log record failed: ${err.message}`;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { SecretStore } from "hmcp-core";
|
|
2
|
+
import { type FetchLike } from "hmcp-gateway";
|
|
3
|
+
import type { ApiOptions } from "../api.js";
|
|
4
|
+
import { type Route } from "../http.js";
|
|
5
|
+
import { OAuthFlows } from "../model/oauth-flows.js";
|
|
6
|
+
/**
|
|
7
|
+
* "Sign in with Notion", from the console.
|
|
8
|
+
*
|
|
9
|
+
* The browser half is a new tab on the provider's page, which comes back to
|
|
10
|
+
* `http://<the host the console is open at>:<console port>/oauth/callback`
|
|
11
|
+
* (127.0.0.1, localhost or [::1]: cookies are per host). Session cookies are
|
|
12
|
+
* SameSite=Strict, so that top-level navigation from the provider arrives
|
|
13
|
+
* without them: the callback is therefore a UI page that does nothing by
|
|
14
|
+
* itself, and only its `POST /complete` -- which carries the session and the
|
|
15
|
+
* CSRF header like every other mutating call -- finishes anything.
|
|
16
|
+
*
|
|
17
|
+
* Every request the console makes on the way goes through an egress guard
|
|
18
|
+
* built for that one request and allowing exactly the host being contacted,
|
|
19
|
+
* GET and POST only, https only, private addresses refused, redirects
|
|
20
|
+
* refused. The one exception is opt-in and narrow: see
|
|
21
|
+
* `HMCP_OAUTH_ALLOW_LOOPBACK` below. Nothing that leaves here carries a token, a client secret or the
|
|
22
|
+
* PKCE verifier: the browser gets the authorize URL and a state, and later a
|
|
23
|
+
* yes or a plain-words no.
|
|
24
|
+
*/
|
|
25
|
+
export interface OAuthRouteOptions {
|
|
26
|
+
/**
|
|
27
|
+
* The console's own port, for the redirect URI. CONTRACT REQUEST: belongs
|
|
28
|
+
* on ApiOptions; until then it is read here or from HMCP_WEB_PORT.
|
|
29
|
+
*/
|
|
30
|
+
readonly consolePort?: number;
|
|
31
|
+
/** The locked-keys file. Defaults to `new SecretStore()`. */
|
|
32
|
+
readonly secrets?: SecretStore;
|
|
33
|
+
/** Flows in progress; defaults to one table per route set. */
|
|
34
|
+
readonly oauthFlows?: OAuthFlows;
|
|
35
|
+
/**
|
|
36
|
+
* Tests only: let the console reach a provider on loopback over plain
|
|
37
|
+
* http. Never set by the CLI; nothing in production reads it.
|
|
38
|
+
*/
|
|
39
|
+
readonly oauthAllowLoopbackForTests?: boolean;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* `HMCP_OAUTH_ALLOW_LOOPBACK=1`, set in the console's environment, lets
|
|
43
|
+
* sign-in reach a provider on this computer -- 127.0.0.1, ::1 or localhost --
|
|
44
|
+
* over plain http. For testing, and for someone running their own MCP server
|
|
45
|
+
* and sign-in locally. It is read only by the console's routes, and it never
|
|
46
|
+
* opens anything beyond loopback: a provider on the local network
|
|
47
|
+
* (10.x, 192.168.x, 169.254.x, ...) is refused with or without it, because
|
|
48
|
+
* that is where a hostile address in a server's metadata would point.
|
|
49
|
+
*/
|
|
50
|
+
export declare const OAUTH_ALLOW_LOOPBACK_ENV = "HMCP_OAUTH_ALLOW_LOOPBACK";
|
|
51
|
+
/** A request-scoped fetch: a fresh guard per call that allows only the host it is about to contact. */
|
|
52
|
+
export declare function consoleOAuthFetch(allowLoopbackForTests?: boolean): FetchLike;
|
|
53
|
+
/** "mcp.notion.com" -> "Notion". Words for messages, not identity. */
|
|
54
|
+
export declare function providerName(serverUrl: string): string;
|
|
55
|
+
export declare function oauthRoutes(options: ApiOptions & OAuthRouteOptions): Route[];
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
/** Sign-in start/complete/flow status. Workstream C. */
|
|
2
|
+
import { lookup } from "node:dns/promises";
|
|
3
|
+
import { EgressConfigSchema, EgressDenied, EgressGuard, SECRET_NAME, SecretNameSchema, SecretStore, isIpLiteral } from "hmcp-core";
|
|
4
|
+
import { NoDynamicRegistration, SignInProblem, begin, complete, discover, egressFetchLike, oauthErrorCode, register } from "hmcp-gateway";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { conflict, HttpError, notFound, route, unprocessable } from "../http.js";
|
|
7
|
+
import { OAuthFlows } from "../model/oauth-flows.js";
|
|
8
|
+
const StartSchema = z
|
|
9
|
+
.object({
|
|
10
|
+
serverUrl: z.string().min(1).max(2048),
|
|
11
|
+
secretName: SecretNameSchema,
|
|
12
|
+
label: z.string().max(200).optional(),
|
|
13
|
+
clientId: z.string().min(1).max(512).optional(),
|
|
14
|
+
clientSecret: z.string().min(1).max(1024).optional()
|
|
15
|
+
})
|
|
16
|
+
.strict();
|
|
17
|
+
const CompleteSchema = z
|
|
18
|
+
.object({
|
|
19
|
+
state: z.string().min(1).max(256),
|
|
20
|
+
code: z.string().min(1).max(4096).optional(),
|
|
21
|
+
error: z.string().max(256).optional(),
|
|
22
|
+
error_description: z.string().max(2048).optional()
|
|
23
|
+
})
|
|
24
|
+
.strict();
|
|
25
|
+
/**
|
|
26
|
+
* `HMCP_OAUTH_ALLOW_LOOPBACK=1`, set in the console's environment, lets
|
|
27
|
+
* sign-in reach a provider on this computer -- 127.0.0.1, ::1 or localhost --
|
|
28
|
+
* over plain http. For testing, and for someone running their own MCP server
|
|
29
|
+
* and sign-in locally. It is read only by the console's routes, and it never
|
|
30
|
+
* opens anything beyond loopback: a provider on the local network
|
|
31
|
+
* (10.x, 192.168.x, 169.254.x, ...) is refused with or without it, because
|
|
32
|
+
* that is where a hostile address in a server's metadata would point.
|
|
33
|
+
*/
|
|
34
|
+
export const OAUTH_ALLOW_LOOPBACK_ENV = "HMCP_OAUTH_ALLOW_LOOPBACK";
|
|
35
|
+
function loopbackAllowedByEnv() {
|
|
36
|
+
return process.env[OAUTH_ALLOW_LOOPBACK_ENV] === "1";
|
|
37
|
+
}
|
|
38
|
+
const bare = (hostname) => hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
39
|
+
const isLoopbackLiteral = (address) => /^127\./.test(address) || address === "::1" || /^::ffff:127\./i.test(address);
|
|
40
|
+
/** Whether a URL's host is this computer: a loopback literal, or `localhost` resolving only to loopback. */
|
|
41
|
+
async function isLoopbackTarget(hostname) {
|
|
42
|
+
const host = bare(hostname);
|
|
43
|
+
if (isIpLiteral(host))
|
|
44
|
+
return isLoopbackLiteral(host);
|
|
45
|
+
if (host !== "localhost")
|
|
46
|
+
return false;
|
|
47
|
+
try {
|
|
48
|
+
const addresses = await lookup(host, { all: true, verbatim: true });
|
|
49
|
+
return addresses.length > 0 && addresses.every((a) => isLoopbackLiteral(a.address));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Why the console would not contact an address, in words a person can act
|
|
57
|
+
* on. The guard's own reasons name policy settings ("set egress.allow_http"),
|
|
58
|
+
* which mean nothing here: the console's sign-in guard is not configurable.
|
|
59
|
+
*/
|
|
60
|
+
function refusalWords(code, target, loopback) {
|
|
61
|
+
const host = target.host;
|
|
62
|
+
const optIn = ` To sign in to a server on this computer for testing, start the console with ${OAUTH_ALLOW_LOOPBACK_ENV}=1.`;
|
|
63
|
+
if (loopback) {
|
|
64
|
+
return (`${host} is on this computer${target.protocol === "http:" ? " and uses a plain http:// address" : ""}, and the ` +
|
|
65
|
+
`console only signs in to servers on the internet, over https://.${optIn}`);
|
|
66
|
+
}
|
|
67
|
+
switch (code) {
|
|
68
|
+
case "plaintext":
|
|
69
|
+
return (`${host} uses a plain http:// address, which isn't encrypted, so the console won't send a sign-in over it. ` +
|
|
70
|
+
`Check the server's instructions for its https:// address.`);
|
|
71
|
+
case "ip-literal":
|
|
72
|
+
case "private-address":
|
|
73
|
+
return (`${host} is an address on your own network or a bare IP address, and the console only signs in to servers ` +
|
|
74
|
+
`with a name on the internet (like https://mcp.example.com). Check the address.`);
|
|
75
|
+
case "scheme":
|
|
76
|
+
return `${host} isn't a web address the console can sign in to. Use the address starting with https://.`;
|
|
77
|
+
case "url-credentials":
|
|
78
|
+
return `The address has a name and password written into it. Remove them and use the plain https:// address.`;
|
|
79
|
+
default:
|
|
80
|
+
return `The console couldn't safely reach ${host}. Check the address.`;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** The guard a sign-in request to `target` goes through: that one host, and loopback only when opted into. */
|
|
84
|
+
async function guardFor(target, allowLoopbackForTests) {
|
|
85
|
+
const loopback = (allowLoopbackForTests || loopbackAllowedByEnv()) && (await isLoopbackTarget(target.hostname));
|
|
86
|
+
const guard = new EgressGuard(EgressConfigSchema.parse({
|
|
87
|
+
allow: [target.host],
|
|
88
|
+
methods: ["GET", "POST"],
|
|
89
|
+
...(loopback ? { allow_http: true, allow_ip_literals: true, block_private_ips: false } : {})
|
|
90
|
+
}));
|
|
91
|
+
return { guard, loopback };
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Refuses, before anything is sent, an address the sign-in guard would refuse
|
|
95
|
+
* -- so the person reads why in plain words, not wrapped in a discovery error.
|
|
96
|
+
*/
|
|
97
|
+
async function precheck(serverUrl, allowLoopbackForTests) {
|
|
98
|
+
let target;
|
|
99
|
+
try {
|
|
100
|
+
target = new URL(serverUrl);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
throw unprocessable("That isn't a full web address. Enter the server's address, starting with https://.", { problem: "address" });
|
|
104
|
+
}
|
|
105
|
+
const { guard, loopback } = await guardFor(target, allowLoopbackForTests);
|
|
106
|
+
try {
|
|
107
|
+
const check = guard.check(target.href, "GET");
|
|
108
|
+
if (!check.ok) {
|
|
109
|
+
const onThisComputer = !loopback && (await isLoopbackTarget(target.hostname));
|
|
110
|
+
throw unprocessable(refusalWords(check.code ?? "refused", target, onThisComputer), { problem: "egress", egress: check.code });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
await guard.close();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The check `discover()` runs on every address it finds (the sign-in page,
|
|
119
|
+
* the token and registration addresses, where the details are kept): the same
|
|
120
|
+
* guard every request goes through, so `HMCP_OAUTH_ALLOW_LOOPBACK` means
|
|
121
|
+
* exactly what it means for the server's own address -- loopback only, never
|
|
122
|
+
* the local network -- and the refusal comes at start, before the address is
|
|
123
|
+
* contacted or shown to anyone. A name is looked up too, so one that resolves
|
|
124
|
+
* into a private network is refused here rather than at the exchange.
|
|
125
|
+
*/
|
|
126
|
+
function discoveredAddressCheck(allowLoopbackForTests) {
|
|
127
|
+
return async (url, what) => {
|
|
128
|
+
const { guard } = await guardFor(url, allowLoopbackForTests);
|
|
129
|
+
try {
|
|
130
|
+
const check = guard.check(url.href, "POST");
|
|
131
|
+
let code = check.ok ? undefined : (check.code ?? "refused");
|
|
132
|
+
if (!code && !isIpLiteral(bare(url.hostname))) {
|
|
133
|
+
try {
|
|
134
|
+
await guard.resolveVerified(bare(url.hostname));
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
// A name that doesn't resolve fails on its own when it is used; only a private answer is refused here.
|
|
138
|
+
if (err instanceof EgressDenied && err.code === "private-address")
|
|
139
|
+
code = err.code;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (!code)
|
|
143
|
+
return;
|
|
144
|
+
const words = code === "private-address" || code === "ip-literal"
|
|
145
|
+
? `The server's ${what} points at an address on a private network, so the sign-in was stopped. Check the server's address, or ask its maker.`
|
|
146
|
+
: code === "plaintext"
|
|
147
|
+
? `The server's ${what} is not a secure (https) address, so the sign-in was stopped.`
|
|
148
|
+
: `The server's ${what} isn't one the console can safely use, so the sign-in was stopped.`;
|
|
149
|
+
throw new SignInProblem("unsafe", words, undefined, `${what}: ${url.host} refused (${code})`);
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
await guard.close();
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/** A request-scoped fetch: a fresh guard per call that allows only the host it is about to contact. */
|
|
157
|
+
export function consoleOAuthFetch(allowLoopbackForTests = false) {
|
|
158
|
+
return async (url, init) => {
|
|
159
|
+
const target = new URL(typeof url === "string" ? url : url.href);
|
|
160
|
+
const { guard, loopback } = await guardFor(target, allowLoopbackForTests);
|
|
161
|
+
try {
|
|
162
|
+
return await egressFetchLike(guard)(url, init);
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
if (err instanceof EgressDenied) {
|
|
166
|
+
const onThisComputer = !loopback && (await isLoopbackTarget(target.hostname));
|
|
167
|
+
throw new EgressDenied(refusalWords(err.code, target, onThisComputer), err.code);
|
|
168
|
+
}
|
|
169
|
+
throw err;
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
await guard.close();
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/** "mcp.notion.com" -> "Notion". Words for messages, not identity. */
|
|
177
|
+
export function providerName(serverUrl) {
|
|
178
|
+
let host;
|
|
179
|
+
try {
|
|
180
|
+
host = new URL(serverUrl).hostname;
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return "The provider";
|
|
184
|
+
}
|
|
185
|
+
if (/^[\d.]+$/.test(host) || host.includes(":") || host === "localhost")
|
|
186
|
+
return host;
|
|
187
|
+
const labels = host.split(".");
|
|
188
|
+
const name = labels.length >= 2 ? labels[labels.length - 2] : labels[0];
|
|
189
|
+
return name.charAt(0).toUpperCase() + name.slice(1);
|
|
190
|
+
}
|
|
191
|
+
const safeCode = (code) => (code && /^[a-z0-9_.-]{1,64}$/i.test(code) ? code : "unknown");
|
|
192
|
+
function startProblem(err, provider) {
|
|
193
|
+
if (err instanceof HttpError)
|
|
194
|
+
return err;
|
|
195
|
+
if (err instanceof NoDynamicRegistration) {
|
|
196
|
+
return new HttpError(422, "no-dynamic-registration", `${provider} doesn't let apps sign up by themselves. Create an app in ${provider}'s developer settings, ` +
|
|
197
|
+
`then enter its app ID under Advanced.`);
|
|
198
|
+
}
|
|
199
|
+
// The plain sentence is the message; the technical reason only ever travels as detail.
|
|
200
|
+
if (err instanceof SignInProblem)
|
|
201
|
+
return unprocessable(err.message, { problem: err.code, ...(err.detail ? { detail: err.detail } : {}) });
|
|
202
|
+
if (err instanceof EgressDenied) {
|
|
203
|
+
return unprocessable(`The console couldn't reach ${provider} safely: ${err.message}`, { problem: "egress", egress: err.code });
|
|
204
|
+
}
|
|
205
|
+
const code = oauthErrorCode(err);
|
|
206
|
+
if (code)
|
|
207
|
+
return unprocessable(`${provider} refused to let this console sign in (${safeCode(code)}).`, { problem: "rejected" });
|
|
208
|
+
return unprocessable(`Couldn't start the sign-in with ${provider}. Check the address and try again.`, { problem: "unknown" });
|
|
209
|
+
}
|
|
210
|
+
function finishProblem(err, provider) {
|
|
211
|
+
if (err instanceof EgressDenied)
|
|
212
|
+
return `The console couldn't reach ${provider} to finish signing in: ${err.message}`;
|
|
213
|
+
const code = oauthErrorCode(err);
|
|
214
|
+
if (code === "invalid_grant")
|
|
215
|
+
return `${provider} didn't accept the sign-in. Start again.`;
|
|
216
|
+
if (code)
|
|
217
|
+
return `${provider} couldn't finish the sign-in (${safeCode(code)}). Start again.`;
|
|
218
|
+
return `${provider} couldn't finish the sign-in. Start again.`;
|
|
219
|
+
}
|
|
220
|
+
/** The names the console answers to (http.ts's Host check), as they go in a URL. */
|
|
221
|
+
const CONSOLE_HOSTS = ["127.0.0.1", "localhost", "[::1]"];
|
|
222
|
+
/**
|
|
223
|
+
* Where the provider sends the browser back to: the console, at the host the
|
|
224
|
+
* browser has it open at. Cookies are per host, so a console opened at
|
|
225
|
+
* http://localhost:7777 that sent the sign-in back to 127.0.0.1 would arrive
|
|
226
|
+
* with no session. Only the console's own names on its own port are
|
|
227
|
+
* followed; anything else gets 127.0.0.1. Kept with the flow, so /complete
|
|
228
|
+
* sends exactly the same one.
|
|
229
|
+
*/
|
|
230
|
+
function redirectUriFor(options, requestHost) {
|
|
231
|
+
const port = options.consolePort ?? Number(process.env["HMCP_WEB_PORT"] ?? NaN);
|
|
232
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
233
|
+
throw unprocessable("The console doesn't know its own address, so it can't receive the sign-in. Restart the console.");
|
|
234
|
+
}
|
|
235
|
+
const name = CONSOLE_HOSTS.find((h) => requestHost?.toLowerCase() === `${h}:${port}`) ?? "127.0.0.1";
|
|
236
|
+
return `http://${name}:${port}/oauth/callback`;
|
|
237
|
+
}
|
|
238
|
+
/** Two server addresses as the same sign-in target, ignoring how they are spelled. */
|
|
239
|
+
function sameServer(a, b) {
|
|
240
|
+
try {
|
|
241
|
+
return new URL(a).href === new URL(b).href;
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return a === b;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/** "notion_signin" -> "notion_signin_2", the first that is free and valid. */
|
|
248
|
+
function freeName(store, name) {
|
|
249
|
+
for (let n = 2; n < 100; n++) {
|
|
250
|
+
const suffix = `_${n}`;
|
|
251
|
+
const candidate = `${name.slice(0, 64 - suffix.length)}${suffix}`;
|
|
252
|
+
if (SECRET_NAME.test(candidate) && !store.get(candidate))
|
|
253
|
+
return candidate;
|
|
254
|
+
}
|
|
255
|
+
return `${name.slice(0, 50)}_new`;
|
|
256
|
+
}
|
|
257
|
+
/** A registration this console already made with the same provider and redirect, if one is stored. */
|
|
258
|
+
function storedRegistration(store, d, redirectUri) {
|
|
259
|
+
const nowSec = Date.now() / 1000;
|
|
260
|
+
for (const summary of store.list()) {
|
|
261
|
+
if (summary.kind !== "oauth")
|
|
262
|
+
continue;
|
|
263
|
+
const entry = store.get(summary.name);
|
|
264
|
+
if (entry?.kind !== "oauth")
|
|
265
|
+
continue;
|
|
266
|
+
if (entry.authorization_server !== d.authorizationServer)
|
|
267
|
+
continue;
|
|
268
|
+
if (!entry.client.redirect_uris.includes(redirectUri))
|
|
269
|
+
continue;
|
|
270
|
+
const exp = entry.client.client_secret_expires_at;
|
|
271
|
+
if (exp && exp < nowSec)
|
|
272
|
+
continue;
|
|
273
|
+
return entry.client;
|
|
274
|
+
}
|
|
275
|
+
return undefined;
|
|
276
|
+
}
|
|
277
|
+
export function oauthRoutes(options) {
|
|
278
|
+
const flows = options.oauthFlows ?? new OAuthFlows();
|
|
279
|
+
const store = () => options.secrets ?? new SecretStore();
|
|
280
|
+
const fetchFn = consoleOAuthFetch(options.oauthAllowLoopbackForTests === true);
|
|
281
|
+
const checkAddress = discoveredAddressCheck(options.oauthAllowLoopbackForTests === true);
|
|
282
|
+
return [
|
|
283
|
+
route("POST", "/api/v1/oauth/start", async (ctx) => {
|
|
284
|
+
const parsed = StartSchema.safeParse(ctx.body ?? {});
|
|
285
|
+
if (!parsed.success) {
|
|
286
|
+
throw unprocessable("The sign-in request isn't complete. Check the server's address and the sign-in's name, then try again.", {
|
|
287
|
+
problem: "request",
|
|
288
|
+
detail: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
const body = parsed.data;
|
|
292
|
+
if (body.clientSecret && !body.clientId)
|
|
293
|
+
throw unprocessable("An app secret needs its app ID.");
|
|
294
|
+
const provider = providerName(body.serverUrl);
|
|
295
|
+
const redirectUri = redirectUriFor(options, ctx.host);
|
|
296
|
+
const secrets = store();
|
|
297
|
+
const existing = secrets.get(body.secretName);
|
|
298
|
+
if (existing && existing.kind !== "oauth") {
|
|
299
|
+
throw conflict(`A locked key called "${body.secretName}" already exists and isn't a sign-in. Choose another name.`);
|
|
300
|
+
}
|
|
301
|
+
/*
|
|
302
|
+
* Completing would overwrite it, and the server that sign-in is for
|
|
303
|
+
* would then be sent this one's tokens -- or none that work. Signing in
|
|
304
|
+
* again to the same server under its own name is a renewal, and fine.
|
|
305
|
+
*/
|
|
306
|
+
if (existing && !sameServer(existing.server_url, body.serverUrl)) {
|
|
307
|
+
throw conflict(`"${body.secretName}" is already the sign-in for ${existing.server_url}. Signing in to ${body.serverUrl} ` +
|
|
308
|
+
`under the same name would replace it, and that server would stop working. Choose another name, such as ` +
|
|
309
|
+
`"${freeName(secrets, body.secretName)}".`);
|
|
310
|
+
}
|
|
311
|
+
await precheck(body.serverUrl, options.oauthAllowLoopbackForTests === true);
|
|
312
|
+
let flow;
|
|
313
|
+
try {
|
|
314
|
+
const d = await discover(body.serverUrl, fetchFn, { checkAddress });
|
|
315
|
+
const client = body.clientId
|
|
316
|
+
? {
|
|
317
|
+
client_id: body.clientId,
|
|
318
|
+
...(body.clientSecret ? { client_secret: body.clientSecret } : {}),
|
|
319
|
+
redirect_uris: [redirectUri]
|
|
320
|
+
}
|
|
321
|
+
: (storedRegistration(secrets, d, redirectUri) ?? (await register(d, redirectUri, fetchFn)));
|
|
322
|
+
flow = flows.create({
|
|
323
|
+
secretName: body.secretName,
|
|
324
|
+
...(body.label ? { label: body.label } : {}),
|
|
325
|
+
codeVerifier: "",
|
|
326
|
+
redirectUri,
|
|
327
|
+
discovered: d,
|
|
328
|
+
client,
|
|
329
|
+
serverUrl: body.serverUrl,
|
|
330
|
+
provider
|
|
331
|
+
});
|
|
332
|
+
const begun = await begin(d, client, redirectUri, flow.state);
|
|
333
|
+
flow.codeVerifier = begun.codeVerifier;
|
|
334
|
+
const hosts = [...new Set([new URL(body.serverUrl).host, new URL(d.metadata.token_endpoint).host])];
|
|
335
|
+
return { authorizeUrl: begun.authorizeUrl, state: flow.state, hosts, provider };
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
const problem = startProblem(err, provider);
|
|
339
|
+
if (flow)
|
|
340
|
+
flows.finish(flow, problem.message);
|
|
341
|
+
throw problem;
|
|
342
|
+
}
|
|
343
|
+
}),
|
|
344
|
+
route("POST", "/api/v1/oauth/complete", async (ctx) => {
|
|
345
|
+
const parsed = CompleteSchema.safeParse(ctx.body ?? {});
|
|
346
|
+
if (!parsed.success)
|
|
347
|
+
throw unprocessable("The sign-in reply isn't complete.");
|
|
348
|
+
const body = parsed.data;
|
|
349
|
+
const taken = flows.take(body.state);
|
|
350
|
+
if (!taken.ok) {
|
|
351
|
+
if (taken.why === "unknown") {
|
|
352
|
+
throw notFound("This sign-in isn't one the console started, or the console restarted since. Start the sign-in again.");
|
|
353
|
+
}
|
|
354
|
+
if (taken.why === "expired") {
|
|
355
|
+
return { ok: false, secretName: taken.flow.secretName, problem: "The sign-in took too long and was stopped. Press Sign in again." };
|
|
356
|
+
}
|
|
357
|
+
throw conflict("This sign-in has already been finished. Start again if you need to sign in once more.");
|
|
358
|
+
}
|
|
359
|
+
const flow = taken.flow;
|
|
360
|
+
const verifier = flow.codeVerifier;
|
|
361
|
+
if (body.error || !body.code) {
|
|
362
|
+
const problem = body.error === "access_denied"
|
|
363
|
+
? `${flow.provider} said no — you may have pressed Cancel. Start again when you're ready.`
|
|
364
|
+
: body.error
|
|
365
|
+
? `${flow.provider} couldn't finish the sign-in (${safeCode(body.error)}). Start again.`
|
|
366
|
+
: `${flow.provider} didn't send back a sign-in code. Start again.`;
|
|
367
|
+
flows.finish(flow, problem);
|
|
368
|
+
return { ok: false, secretName: flow.secretName, problem };
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
await complete({
|
|
372
|
+
d: flow.discovered,
|
|
373
|
+
client: flow.client,
|
|
374
|
+
code: body.code,
|
|
375
|
+
codeVerifier: verifier,
|
|
376
|
+
redirectUri: flow.redirectUri,
|
|
377
|
+
serverUrl: flow.serverUrl,
|
|
378
|
+
secretName: flow.secretName,
|
|
379
|
+
...(flow.label ? { label: flow.label } : {})
|
|
380
|
+
}, store(), fetchFn);
|
|
381
|
+
}
|
|
382
|
+
catch (err) {
|
|
383
|
+
const problem = finishProblem(err, flow.provider);
|
|
384
|
+
flows.finish(flow, problem);
|
|
385
|
+
return { ok: false, secretName: flow.secretName, problem };
|
|
386
|
+
}
|
|
387
|
+
flows.finish(flow);
|
|
388
|
+
return { ok: true, secretName: flow.secretName };
|
|
389
|
+
}),
|
|
390
|
+
route("GET", "/api/v1/oauth/flows/:state", (ctx) => {
|
|
391
|
+
const flow = flows.get(ctx.params["state"] ?? "");
|
|
392
|
+
if (!flow)
|
|
393
|
+
throw notFound("No sign-in with that reference. Start the sign-in again.");
|
|
394
|
+
const status = flow.status === "completing" ? "waiting" : flow.status;
|
|
395
|
+
return {
|
|
396
|
+
status,
|
|
397
|
+
secretName: flow.secretName,
|
|
398
|
+
...(flow.status === "expired"
|
|
399
|
+
? { problem: "The sign-in took too long and was stopped. Press Sign in again." }
|
|
400
|
+
: flow.problem
|
|
401
|
+
? { problem: flow.problem }
|
|
402
|
+
: {})
|
|
403
|
+
};
|
|
404
|
+
})
|
|
405
|
+
];
|
|
406
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type Route } from "../http.js";
|
|
2
|
+
/**
|
|
3
|
+
* Policy as something the console edits, not only reads: any setting, any
|
|
4
|
+
* rule (hand-written globs included), the whole file as text, and the two
|
|
5
|
+
* read-only views that used to be CLI-only (`suggest`, `status`).
|
|
6
|
+
*
|
|
7
|
+
* The rules for what may be written live in core (`policy-write.ts`): the
|
|
8
|
+
* digest lock, the `policy_writes` refusal, `parsePolicy`, the canonical
|
|
9
|
+
* "only this changed" proof, the atomic write, and the one table that says
|
|
10
|
+
* which direction of each change is the loosening one. This module turns those
|
|
11
|
+
* outcomes into HTTP and writes the audit record. Every write here is
|
|
12
|
+
* process-wide -- policy applies to every tenant of a gateway -- so the
|
|
13
|
+
* tenant a request names is recorded but never narrows the write.
|
|
14
|
+
*/
|
|
15
|
+
export interface PolicyRouteOptions {
|
|
16
|
+
readonly registryPath: string;
|
|
17
|
+
}
|
|
18
|
+
export interface DiffHunk {
|
|
19
|
+
readonly oldStart: number;
|
|
20
|
+
readonly newStart: number;
|
|
21
|
+
/** Each line prefixed with " ", "-" or "+", as in a unified diff. */
|
|
22
|
+
readonly lines: readonly string[];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A line diff in unified hunks, for the file editor's preview. Plain LCS over
|
|
26
|
+
* whatever differs between the common head and tail; a change too large for
|
|
27
|
+
* that is shown as everything removed and everything added, which is still
|
|
28
|
+
* correct, only less helpful.
|
|
29
|
+
*
|
|
30
|
+
* The gateway.yaml editor has its own flat op/line diff (`lineDiff` in
|
|
31
|
+
* model/gateway-config.ts); the two UIs read different shapes, so both stay.
|
|
32
|
+
*/
|
|
33
|
+
export declare function lineDiff(before: string, after: string, context?: number): DiffHunk[];
|
|
34
|
+
export declare function policyRoutes(options: PolicyRouteOptions): Route[];
|