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
@@ -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[];