@guren/plugin-cloudflare 0.5.0 → 0.6.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/dist/build-B2fIb1lu.js +867 -0
- package/dist/commands.d.ts +8 -0
- package/dist/commands.js +12 -2
- package/dist/env.d.ts +26 -0
- package/dist/env.js +34 -0
- package/dist/index.d.ts +25 -8
- package/dist/index.js +2 -17
- package/package.json +10 -3
- package/templates/mcp-oauth/app/Http/Controllers/McpOAuthController.ts +286 -0
- package/templates/mcp-oauth/app/View/McpOAuthConsentPage.tsx +142 -0
- package/templates/mcp-oauth/app/View/McpOAuthErrorPage.tsx +57 -0
- package/templates/mcp-oauth/routes/mcp-oauth.ts +35 -0
- package/dist/build-B7zQ13ai.js +0 -321
package/dist/commands.d.ts
CHANGED
package/dist/commands.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as buildCloudflareOutput } from "./build-
|
|
1
|
+
import { t as buildCloudflareOutput } from "./build-B2fIb1lu.js";
|
|
2
2
|
import { defineCommand } from "citty";
|
|
3
3
|
var commands_default = { "cloudflare:build": defineCommand({
|
|
4
4
|
meta: {
|
|
@@ -13,12 +13,22 @@ var commands_default = { "cloudflare:build": defineCommand({
|
|
|
13
13
|
"skip-app-build": {
|
|
14
14
|
type: "boolean",
|
|
15
15
|
description: "Skip running the app's build script before assembling output"
|
|
16
|
+
},
|
|
17
|
+
"mcp-oauth": {
|
|
18
|
+
type: "boolean",
|
|
19
|
+
description: "Front the App MCP endpoint with @cloudflare/workers-oauth-provider, scaffold the consent flow, and make the OAUTH_KV binding build-owned (requires @guren/plugin-mcp)"
|
|
20
|
+
},
|
|
21
|
+
"mcp-path": {
|
|
22
|
+
type: "string",
|
|
23
|
+
description: "Path the App MCP endpoint is mounted at, protected as the OAuth apiRoute (default /mcp; must match mcpPlugin({ path }))"
|
|
16
24
|
}
|
|
17
25
|
},
|
|
18
26
|
async run({ args }) {
|
|
19
27
|
await buildCloudflareOutput({
|
|
20
28
|
rootDir: args.root || process.cwd(),
|
|
21
|
-
skipAppBuild: Boolean(args["skip-app-build"])
|
|
29
|
+
skipAppBuild: Boolean(args["skip-app-build"]),
|
|
30
|
+
mcpOAuth: Boolean(args["mcp-oauth"]),
|
|
31
|
+
...args["mcp-path"] ? { mcpPath: args["mcp-path"] } : {}
|
|
22
32
|
});
|
|
23
33
|
}
|
|
24
34
|
}) };
|
package/dist/env.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/env.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The Workers env holder, published as `@guren/plugin-cloudflare/env`.
|
|
4
|
+
*
|
|
5
|
+
* **This module must stay import-free.** It is the one thing *application*
|
|
6
|
+
* code reaches for at runtime — a scaffolded controller resolving a binding,
|
|
7
|
+
* the OAuth consent screen reading `env.OAUTH_PROVIDER` — and the package's
|
|
8
|
+
* root entry re-exports `buildCloudflareOutput`, which pulls `node:fs`,
|
|
9
|
+
* `node:path` and the whole deploy generator behind it. An app importing
|
|
10
|
+
* `getWorkersEnv` from the root therefore drags the build tooling into its
|
|
11
|
+
* route graph on every `bun run dev` boot and into the wrangler bundle on
|
|
12
|
+
* every deploy, for three functions that need nothing at all.
|
|
13
|
+
*
|
|
14
|
+
* The root keeps re-exporting these names, so nothing that already imports
|
|
15
|
+
* them from there breaks. New application code should import from this
|
|
16
|
+
* subpath; `tests/lean-env-subpath.test.ts` holds that boundary, and the
|
|
17
|
+
* scaffolded consent controller is checked against it by name.
|
|
18
|
+
*/
|
|
19
|
+
/** First call wins; later calls are ignored (never overwrite a live env). */
|
|
20
|
+
declare function captureWorkersEnv(env: unknown): void;
|
|
21
|
+
/** Throws with a clear message if called before the first request captured env. */
|
|
22
|
+
declare function getWorkersEnv<E = unknown>(): E;
|
|
23
|
+
/** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
|
|
24
|
+
declare function resetWorkersEnv(): void;
|
|
25
|
+
//#endregion
|
|
26
|
+
export { captureWorkersEnv, getWorkersEnv, resetWorkersEnv };
|
package/dist/env.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//#region src/env.ts
|
|
2
|
+
/**
|
|
3
|
+
* The Workers env holder, published as `@guren/plugin-cloudflare/env`.
|
|
4
|
+
*
|
|
5
|
+
* **This module must stay import-free.** It is the one thing *application*
|
|
6
|
+
* code reaches for at runtime — a scaffolded controller resolving a binding,
|
|
7
|
+
* the OAuth consent screen reading `env.OAUTH_PROVIDER` — and the package's
|
|
8
|
+
* root entry re-exports `buildCloudflareOutput`, which pulls `node:fs`,
|
|
9
|
+
* `node:path` and the whole deploy generator behind it. An app importing
|
|
10
|
+
* `getWorkersEnv` from the root therefore drags the build tooling into its
|
|
11
|
+
* route graph on every `bun run dev` boot and into the wrangler bundle on
|
|
12
|
+
* every deploy, for three functions that need nothing at all.
|
|
13
|
+
*
|
|
14
|
+
* The root keeps re-exporting these names, so nothing that already imports
|
|
15
|
+
* them from there breaks. New application code should import from this
|
|
16
|
+
* subpath; `tests/lean-env-subpath.test.ts` holds that boundary, and the
|
|
17
|
+
* scaffolded consent controller is checked against it by name.
|
|
18
|
+
*/
|
|
19
|
+
let holder;
|
|
20
|
+
/** First call wins; later calls are ignored (never overwrite a live env). */
|
|
21
|
+
function captureWorkersEnv(env) {
|
|
22
|
+
holder ??= { env };
|
|
23
|
+
}
|
|
24
|
+
/** Throws with a clear message if called before the first request captured env. */
|
|
25
|
+
function getWorkersEnv() {
|
|
26
|
+
if (!holder) throw new Error("getWorkersEnv() was called before the first request captured the Workers env. Defer access behind a closure instead of reading it at module scope, e.g. binding: () => getWorkersEnv<Env>().DB");
|
|
27
|
+
return holder.env;
|
|
28
|
+
}
|
|
29
|
+
/** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
|
|
30
|
+
function resetWorkersEnv() {
|
|
31
|
+
holder = void 0;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { captureWorkersEnv, getWorkersEnv, resetWorkersEnv };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,6 @@
|
|
|
1
|
+
import { captureWorkersEnv, getWorkersEnv, resetWorkersEnv } from "./env.js";
|
|
1
2
|
import { FileMetadata, GetStreamOptions, PutOptions, ServiceProviderConstructor, StorageDriver, StorageDriverCapabilities, TemporaryUrlOptions } from "@guren/core";
|
|
2
3
|
import { PathLike } from "@guren/core/internal/deploy-build";
|
|
3
|
-
//#region src/env.d.ts
|
|
4
|
-
/** First call wins; later calls are ignored (never overwrite a live env). */
|
|
5
|
-
declare function captureWorkersEnv(env: unknown): void;
|
|
6
|
-
/** Throws with a clear message if called before the first request captured env. */
|
|
7
|
-
declare function getWorkersEnv<E = unknown>(): E;
|
|
8
|
-
/** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
|
|
9
|
-
declare function resetWorkersEnv(): void;
|
|
10
|
-
//#endregion
|
|
11
4
|
//#region src/handler.d.ts
|
|
12
5
|
interface WorkersExecutionContext {
|
|
13
6
|
waitUntil(promise: Promise<unknown>): void;
|
|
@@ -45,6 +38,30 @@ interface BuildCloudflareOutputOptions {
|
|
|
45
38
|
ssrEntryKey?: string;
|
|
46
39
|
/** Skip running the app's `build` script before assembling output. */
|
|
47
40
|
skipAppBuild?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Front the worker with `@cloudflare/workers-oauth-provider`, so the App MCP
|
|
43
|
+
* endpoint is reached by OAuth-authorized clients instead of bearer tokens
|
|
44
|
+
* (RFC 0016 §7).
|
|
45
|
+
*
|
|
46
|
+
* A **build** option and not plugin configuration, because the generator
|
|
47
|
+
* runs in a separate process from the application and cannot read what
|
|
48
|
+
* `mcpPlugin()` was passed. Nothing records the choice: pass it on every
|
|
49
|
+
* build that wants it. A committed config carrying the OAuth binding while
|
|
50
|
+
* a build omits the flag is warned about, which is the drift this leaves
|
|
51
|
+
* detectable.
|
|
52
|
+
*/
|
|
53
|
+
mcpOAuth?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Path the App MCP endpoint is mounted at, used as the OAuth provider's
|
|
56
|
+
* protected `apiRoute`. Only read when `mcpOAuth` is on.
|
|
57
|
+
*
|
|
58
|
+
* Defaults to `mcpPlugin()`'s own default. An app that passed
|
|
59
|
+
* `mcpPlugin({ path })` must pass the same value here: the generator cannot
|
|
60
|
+
* see runtime configuration, and a provider protecting a path the endpoint
|
|
61
|
+
* does not serve leaves the endpoint outside the OAuth boundary entirely —
|
|
62
|
+
* silently, because the request still reaches the app.
|
|
63
|
+
*/
|
|
64
|
+
mcpPath?: string;
|
|
48
65
|
}
|
|
49
66
|
/**
|
|
50
67
|
* Assemble a deployable Cloudflare Workers directory (`.cloudflare/`) from a
|
package/dist/index.js
CHANGED
|
@@ -1,21 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { captureWorkersEnv, getWorkersEnv, resetWorkersEnv } from "./env.js";
|
|
2
|
+
import { n as flattenD1Migrations, t as buildCloudflareOutput } from "./build-B2fIb1lu.js";
|
|
2
3
|
import { definePlugin } from "@guren/core";
|
|
3
|
-
//#region src/env.ts
|
|
4
|
-
let holder;
|
|
5
|
-
/** First call wins; later calls are ignored (never overwrite a live env). */
|
|
6
|
-
function captureWorkersEnv(env) {
|
|
7
|
-
holder ??= { env };
|
|
8
|
-
}
|
|
9
|
-
/** Throws with a clear message if called before the first request captured env. */
|
|
10
|
-
function getWorkersEnv() {
|
|
11
|
-
if (!holder) throw new Error("getWorkersEnv() was called before the first request captured the Workers env. Defer access behind a closure instead of reading it at module scope, e.g. binding: () => getWorkersEnv<Env>().DB");
|
|
12
|
-
return holder.env;
|
|
13
|
-
}
|
|
14
|
-
/** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
|
|
15
|
-
function resetWorkersEnv() {
|
|
16
|
-
holder = void 0;
|
|
17
|
-
}
|
|
18
|
-
//#endregion
|
|
19
4
|
//#region src/handler.ts
|
|
20
5
|
function createWorkersHandler(app) {
|
|
21
6
|
let bootPromise;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@guren/plugin-cloudflare",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
}
|
|
26
26
|
},
|
|
27
27
|
"files": [
|
|
28
|
-
"dist"
|
|
28
|
+
"dist",
|
|
29
|
+
"templates"
|
|
29
30
|
],
|
|
30
31
|
"main": "dist/index.js",
|
|
31
32
|
"types": "dist/index.d.ts",
|
|
@@ -33,6 +34,10 @@
|
|
|
33
34
|
".": {
|
|
34
35
|
"types": "./dist/index.d.ts",
|
|
35
36
|
"default": "./dist/index.js"
|
|
37
|
+
},
|
|
38
|
+
"./env": {
|
|
39
|
+
"types": "./dist/env.d.ts",
|
|
40
|
+
"default": "./dist/env.js"
|
|
36
41
|
}
|
|
37
42
|
},
|
|
38
43
|
"scripts": {
|
|
@@ -41,12 +46,14 @@
|
|
|
41
46
|
"typecheck": "tsc --noEmit"
|
|
42
47
|
},
|
|
43
48
|
"dependencies": {
|
|
44
|
-
"@guren/core": "^1.
|
|
49
|
+
"@guren/core": "^1.13.0",
|
|
45
50
|
"citty": "^0.1.6"
|
|
46
51
|
},
|
|
47
52
|
"devDependencies": {
|
|
53
|
+
"@cloudflare/workers-oauth-provider": "^0.10.3",
|
|
48
54
|
"@cloudflare/workers-types": "^4.20260702.1",
|
|
49
55
|
"@types/node": "^20.14.10",
|
|
56
|
+
"hono": "^4.11.7",
|
|
50
57
|
"miniflare": "5.20260801.1-alpha",
|
|
51
58
|
"tsdown": "^0.22.14",
|
|
52
59
|
"typescript": "^7.0.2"
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OAuth consent screen for this application's own agent tools, scaffolded
|
|
3
|
+
* once by `guren cloudflare:build --mcp-oauth` and yours to edit from here.
|
|
4
|
+
*
|
|
5
|
+
* **What this file owns and what it does not.**
|
|
6
|
+
* `@cloudflare/workers-oauth-provider` runs in front of the worker and owns
|
|
7
|
+
* every other part of the flow: discovery metadata, dynamic client
|
|
8
|
+
* registration, the token endpoint, PKCE, refresh, and the encryption of the
|
|
9
|
+
* `props` a grant carries. It hands back exactly one decision, because it is
|
|
10
|
+
* the only one the provider cannot make — *who is signed in, and what did they
|
|
11
|
+
* agree to*. That is this controller.
|
|
12
|
+
*
|
|
13
|
+
* **The markup lives in `app/View/`, not here.** `McpOAuthConsentPage.tsx` and
|
|
14
|
+
* `McpOAuthErrorPage.tsx` are `hono/jsx` components rendered by
|
|
15
|
+
* `Controller.view()` (RFC 0014) — server-rendered, no hydration, no client
|
|
16
|
+
* bundle, and deliberately not Inertia (see the consent page's own header for
|
|
17
|
+
* why). This file decides *what* to show; those decide how it looks.
|
|
18
|
+
*
|
|
19
|
+
* Escaping comes with the renderer: `hono/jsx` escapes text children and
|
|
20
|
+
* attribute values, so nothing here hand-escapes anything. What it does not do
|
|
21
|
+
* is validate URL schemes — see `Controller.view()`'s contract before adding a
|
|
22
|
+
* user-supplied `href`.
|
|
23
|
+
*
|
|
24
|
+
* **Derived live, never read from a manifest.** `.guren/agents.gen.ts` is a
|
|
25
|
+
* build artifact that can be stale; the router is what actually serves. A
|
|
26
|
+
* consent screen listing a tool the dispatcher would deny — or, far worse,
|
|
27
|
+
* omitting one it would allow — is the one bug this screen cannot have.
|
|
28
|
+
*
|
|
29
|
+
* **The grant is a subset of the request, by construction.** Only a checkbox
|
|
30
|
+
* that appeared in the expansion of what the client asked for is honoured, so
|
|
31
|
+
* a submitted value naming anything else is dropped rather than granted. The
|
|
32
|
+
* provider does not enforce this; a form is user input.
|
|
33
|
+
*
|
|
34
|
+
* **Off Workers this fails at request time, not import time.** `getWorkersEnv`
|
|
35
|
+
* throws when no worker request has captured an env — which is exactly right
|
|
36
|
+
* for a file that also has to be importable by `guren codegen`, `guren check`
|
|
37
|
+
* and your test suite, none of which run on workerd.
|
|
38
|
+
*/
|
|
39
|
+
import {
|
|
40
|
+
CSRF_FORM_FIELD,
|
|
41
|
+
Controller,
|
|
42
|
+
deriveAgentTools,
|
|
43
|
+
expandToolScopes,
|
|
44
|
+
getCsrfToken,
|
|
45
|
+
verifyCsrfToken,
|
|
46
|
+
} from '@guren/core'
|
|
47
|
+
import type { Application, DerivedAgentTool } from '@guren/core'
|
|
48
|
+
// The lean subpath, deliberately not the root entry: the root also exports
|
|
49
|
+
// `buildCloudflareOutput`, so importing from it would pull the deploy
|
|
50
|
+
// generator and its node builtins into this app's route graph on every boot
|
|
51
|
+
// and into the wrangler bundle on every deploy.
|
|
52
|
+
import { getWorkersEnv } from '@guren/plugin-cloudflare/env'
|
|
53
|
+
import type { AuthRequest, OAuthHelpers } from '@cloudflare/workers-oauth-provider'
|
|
54
|
+
|
|
55
|
+
import { McpOAuthErrorPage } from '../../View/McpOAuthErrorPage.js'
|
|
56
|
+
// `SCOPE_FIELD` and `QUERY_FIELD` are imported from the view rather than
|
|
57
|
+
// declared here: the page renders the form, so it owns its field names, and
|
|
58
|
+
// this file reads them back. Two declarations would be two spellings of one
|
|
59
|
+
// contract, and the failure — a submitted field nothing looks for — is silent.
|
|
60
|
+
import {
|
|
61
|
+
McpOAuthConsentPage,
|
|
62
|
+
QUERY_FIELD,
|
|
63
|
+
SCOPE_FIELD,
|
|
64
|
+
} from '../../View/McpOAuthConsentPage.js'
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Where an unauthenticated visitor is sent. The consent decision is only
|
|
68
|
+
* meaningful for a signed-in user — change this to your own login path.
|
|
69
|
+
*/
|
|
70
|
+
const LOGIN_PATH = '/login'
|
|
71
|
+
|
|
72
|
+
interface WorkerEnvWithProvider {
|
|
73
|
+
OAUTH_PROVIDER: OAuthHelpers
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export default class McpOAuthController extends Controller {
|
|
77
|
+
/** GET /oauth/authorize — render the consent screen. */
|
|
78
|
+
async show(): Promise<Response> {
|
|
79
|
+
const userId = await this.auth.id()
|
|
80
|
+
if (userId === null || userId === undefined) {
|
|
81
|
+
return this.redirect(this.loginUrl())
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const provider = this.provider()
|
|
85
|
+
const parsed = await this.parseAuthRequest(provider, this.ctx.req.raw)
|
|
86
|
+
if (parsed instanceof Response) {
|
|
87
|
+
return parsed
|
|
88
|
+
}
|
|
89
|
+
const client = await provider.lookupClient(parsed.clientId)
|
|
90
|
+
|
|
91
|
+
return this.view(McpOAuthConsentPage, {
|
|
92
|
+
// The client's registered name when it has one; its id otherwise, which
|
|
93
|
+
// is at least something the person can recognize in the client's own UI.
|
|
94
|
+
clientName: client?.clientName ?? parsed.clientId,
|
|
95
|
+
query: new URL(this.ctx.req.url).searchParams.toString(),
|
|
96
|
+
tools: this.offeredTools(parsed.scope),
|
|
97
|
+
csrfToken: getCsrfToken(this.ctx),
|
|
98
|
+
})
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** POST /oauth/authorize — record the decision and hand back to the provider. */
|
|
102
|
+
async approve(): Promise<Response> {
|
|
103
|
+
const userId = await this.auth.id()
|
|
104
|
+
if (userId === null || userId === undefined) {
|
|
105
|
+
return this.redirect(this.loginUrl())
|
|
106
|
+
}
|
|
107
|
+
if (typeof userId !== 'string' && typeof userId !== 'number') {
|
|
108
|
+
// The grant carries this id in its props and the endpoint maps it to an
|
|
109
|
+
// AgentPrincipal, which admits a string or a number and nothing else.
|
|
110
|
+
throw new Error('The authenticated user id is neither a string nor a number.')
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// `all: true` is what turns the repeated `scope` checkboxes into an array
|
|
114
|
+
// instead of the last one winning — without it this screen would grant
|
|
115
|
+
// exactly one tool however many boxes were ticked, silently.
|
|
116
|
+
//
|
|
117
|
+
// The CSRF middleware has already called `parseBody()` on this request,
|
|
118
|
+
// with no options, to read the `_token` field. Hono's body cache is keyed
|
|
119
|
+
// on those options rather than on the request alone, so this second call
|
|
120
|
+
// still returns the array. Measured rather than assumed: a cache keyed on
|
|
121
|
+
// the request alone would hand back the middleware's `all: false` result,
|
|
122
|
+
// and the failure would be invisible — no error, no log line, one tool
|
|
123
|
+
// granted. `tests/hono-parse-body.test.ts` in @guren/plugin-cloudflare
|
|
124
|
+
// keeps that measurement standing across Hono upgrades.
|
|
125
|
+
const form = await this.ctx.req.parseBody({ all: true })
|
|
126
|
+
|
|
127
|
+
// Verified here as well as by the global CSRF middleware, because *this*
|
|
128
|
+
// form must not depend on that middleware being mounted. An app with
|
|
129
|
+
// `autoSession: false`, or one composing its own middleware chain, can
|
|
130
|
+
// easily not have it — and `csrfField()` below renders an entirely
|
|
131
|
+
// convincing token either way, so the screen would look protected while
|
|
132
|
+
// any site could POST a grant on a signed-in user's behalf. The token is
|
|
133
|
+
// read through the framework's own `verifyCsrfToken`, never a comparison
|
|
134
|
+
// written here: a second implementation of that check is how one of them
|
|
135
|
+
// comes to accept a token the other rejects.
|
|
136
|
+
if (!verifyCsrfToken(this.ctx, single(form[CSRF_FORM_FIELD]))) {
|
|
137
|
+
return this.errorPage(
|
|
138
|
+
419,
|
|
139
|
+
'This consent form has expired',
|
|
140
|
+
'Start the authorization again from the application that sent you here.',
|
|
141
|
+
)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const provider = this.provider()
|
|
145
|
+
// Re-parsed from the original query rather than trusted from a hidden
|
|
146
|
+
// field holding the request itself: `parseAuthRequest` re-validates the
|
|
147
|
+
// client and its redirect URI, and a form is user input however it got
|
|
148
|
+
// here. The submitted value only decides *which* authorize request this
|
|
149
|
+
// is, and a forged one fails that validation.
|
|
150
|
+
const parsed = await this.parseAuthRequest(
|
|
151
|
+
provider,
|
|
152
|
+
new Request(`${new URL(this.ctx.req.url).origin}/oauth/authorize?${single(form[QUERY_FIELD])}`),
|
|
153
|
+
)
|
|
154
|
+
if (parsed instanceof Response) {
|
|
155
|
+
return parsed
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const offered = this.offeredTools(parsed.scope)
|
|
159
|
+
const offeredScopes = new Set(offered.map((tool) => `tool:${tool.toolName}`))
|
|
160
|
+
// Intersection, not the submission: a checked box for anything the client
|
|
161
|
+
// did not ask for is dropped. `tool:<name>` is the wire form the endpoint's
|
|
162
|
+
// scope grammar parses — the bare tool name grants nothing, silently.
|
|
163
|
+
const granted = many(form[SCOPE_FIELD]).filter((scope) => offeredScopes.has(scope))
|
|
164
|
+
|
|
165
|
+
const { redirectTo } = await provider.completeAuthorization({
|
|
166
|
+
request: parsed,
|
|
167
|
+
// The provider's own identifier type is a string; `props.userId` keeps
|
|
168
|
+
// the application's, which is what its policies look up by.
|
|
169
|
+
userId: String(userId),
|
|
170
|
+
scope: granted,
|
|
171
|
+
props: { userId, scopes: granted },
|
|
172
|
+
metadata: { grantedAt: new Date().toISOString() },
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
return this.redirect(redirectTo)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Parse an authorize request, answering with a page instead of throwing.
|
|
180
|
+
*
|
|
181
|
+
* `parseAuthRequest` rejects on a query that is malformed, truncated, or
|
|
182
|
+
* tampered with — a missing `client_id`, an unregistered `redirect_uri` — and
|
|
183
|
+
* every one of those is a *routine* arrival at this URL, not an application
|
|
184
|
+
* fault. Left unhandled they surface as a 500 whose body is a stack trace,
|
|
185
|
+
* which is both alarming and useless to the person reading it: the fix is
|
|
186
|
+
* never anything they can do on this page, it is to start again from the
|
|
187
|
+
* client.
|
|
188
|
+
*
|
|
189
|
+
* Deliberately does not echo the provider's message. It is derived from
|
|
190
|
+
* attacker-controllable query parameters, and this page is reached by a
|
|
191
|
+
* browser.
|
|
192
|
+
*/
|
|
193
|
+
private async parseAuthRequest(
|
|
194
|
+
provider: OAuthHelpers,
|
|
195
|
+
request: Request,
|
|
196
|
+
): Promise<AuthRequest | Response> {
|
|
197
|
+
try {
|
|
198
|
+
return await provider.parseAuthRequest(request)
|
|
199
|
+
} catch {
|
|
200
|
+
return this.errorPage(
|
|
201
|
+
400,
|
|
202
|
+
'This authorization link is not valid',
|
|
203
|
+
'Start the authorization again from the application that sent you here.',
|
|
204
|
+
)
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The provider helpers, from the Workers env this request captured.
|
|
210
|
+
*
|
|
211
|
+
* `getWorkersEnv()` is first-call-wins, so it hands back the env of
|
|
212
|
+
* whichever request booted the worker — which is safe here because
|
|
213
|
+
* `OAuthProvider` injects `OAUTH_PROVIDER` into `env` on *both* of its
|
|
214
|
+
* paths, before either handler runs (read directly out of the published
|
|
215
|
+
* `oauth-provider.js`: the same `if (!env.OAUTH_PROVIDER) env.OAUTH_PROVIDER
|
|
216
|
+
* = …` guard sits ahead of the default handler and ahead of the API
|
|
217
|
+
* handler). So a worker whose first request was a tool call captures an env
|
|
218
|
+
* carrying the helpers just as one whose first request was this screen does,
|
|
219
|
+
* and the absence below is genuinely diagnostic rather than a race.
|
|
220
|
+
*
|
|
221
|
+
* Wrapped so the failure names the cause a developer actually has: either
|
|
222
|
+
* this is not running on Workers, or the worker was built without
|
|
223
|
+
* `--mcp-oauth` and so was never wrapped in an `OAuthProvider`.
|
|
224
|
+
*/
|
|
225
|
+
private provider(): OAuthHelpers {
|
|
226
|
+
let env: WorkerEnvWithProvider
|
|
227
|
+
try {
|
|
228
|
+
env = getWorkersEnv<WorkerEnvWithProvider>()
|
|
229
|
+
} catch (error) {
|
|
230
|
+
throw new Error(
|
|
231
|
+
'The OAuth consent routes require the Cloudflare Workers env. '
|
|
232
|
+
+ 'They run only in a worker built with `guren cloudflare:build --mcp-oauth`. '
|
|
233
|
+
+ `(${String(error)})`,
|
|
234
|
+
)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (!env.OAUTH_PROVIDER) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
'env.OAUTH_PROVIDER is missing. This worker was not wrapped in an OAuthProvider — '
|
|
240
|
+
+ 'rebuild with `guren cloudflare:build --mcp-oauth`.',
|
|
241
|
+
)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return env.OAUTH_PROVIDER
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The tools this authorize request may grant: every MCP-exposed tool the
|
|
249
|
+
* requested scopes expand to, in router order.
|
|
250
|
+
*/
|
|
251
|
+
private offeredTools(requested: string[]): DerivedAgentTool[] {
|
|
252
|
+
const { tools } = deriveAgentTools(this.make<Application>('app').router.definitions())
|
|
253
|
+
const exposed = tools.filter((tool) => tool.expose.mcp)
|
|
254
|
+
|
|
255
|
+
const allowed = new Set(
|
|
256
|
+
expandToolScopes(
|
|
257
|
+
requested,
|
|
258
|
+
exposed.map((tool) => ({ name: tool.toolName, readOnly: tool.annotations.readOnlyHint })),
|
|
259
|
+
),
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
return exposed.filter((tool) => allowed.has(tool.toolName))
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private loginUrl(): string {
|
|
266
|
+
const target = new URL(this.ctx.req.url)
|
|
267
|
+
return `${LOGIN_PATH}?redirectTo=${encodeURIComponent(`${target.pathname}${target.search}`)}`
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** A plain, stack-free page for the arrivals that are nobody's bug. */
|
|
271
|
+
private errorPage(status: number, title: string, advice: string): Promise<Response> {
|
|
272
|
+
return this.view(McpOAuthErrorPage, { title, advice }, { status })
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** One value from a parsed body field that may legally hold several. */
|
|
277
|
+
function single(value: unknown): string {
|
|
278
|
+
return typeof value === 'string' ? value : ''
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Every string value of a parsed body field, whether it held one or many. */
|
|
282
|
+
function many(value: unknown): string[] {
|
|
283
|
+
if (typeof value === 'string') return [value]
|
|
284
|
+
if (Array.isArray(value)) return value.filter((entry): entry is string => typeof entry === 'string')
|
|
285
|
+
return []
|
|
286
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/** @jsxImportSource @guren/core */
|
|
2
|
+
import { CSRF_FORM_FIELD, type DerivedAgentTool, type FC } from '@guren/core'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The OAuth consent screen for this application's own agent tools, scaffolded
|
|
6
|
+
* once by `guren cloudflare:build --mcp-oauth` and yours to edit from here.
|
|
7
|
+
*
|
|
8
|
+
* Server-rendered through `Controller.view()` (RFC 0014) — `hono/jsx`, no
|
|
9
|
+
* hydration, no client bundle. **Not** an Inertia page, for three reasons in
|
|
10
|
+
* order: an API-only app has no client build to render one into; a consent
|
|
11
|
+
* screen that depends on the asset pipeline is one that breaks when the
|
|
12
|
+
* pipeline does; and the OAuth client showing this is a browser popup that may
|
|
13
|
+
* not carry the session cookies an SPA boot needs.
|
|
14
|
+
*
|
|
15
|
+
* The `@jsxImportSource` pragma on line 1 is what lets this file compile in an
|
|
16
|
+
* app whose `tsconfig` points `jsx: "react-jsx"` at React for `resources/js`.
|
|
17
|
+
* It is per-file and overrides `jsxImportSource` for this module only, so
|
|
18
|
+
* **your app needs no tsconfig change** — the same way `web/app/View/*.tsx`
|
|
19
|
+
* does it. Verified by dropping both components into a stock fullstack app
|
|
20
|
+
* (`jsx: "react-jsx"`, React types installed) and running its own `tsc`: clean
|
|
21
|
+
* with the pragma, eleven errors without it. Keep it on the first line, where
|
|
22
|
+
* it is the only place TypeScript honours it.
|
|
23
|
+
*
|
|
24
|
+
* **Escaping is the renderer's job, not this file's.** Text children and
|
|
25
|
+
* attribute values are escaped by `hono/jsx`, so a client name containing
|
|
26
|
+
* markup cannot break out of either. What it does *not* do is validate URL
|
|
27
|
+
* schemes: a `javascript:` href built from untrusted data would be emitted
|
|
28
|
+
* verbatim. Nothing here renders a user-supplied URL, and nothing added here
|
|
29
|
+
* should without sanitizing it first.
|
|
30
|
+
*
|
|
31
|
+
* **What the screen shows, and why it shows tools rather than scopes.** The
|
|
32
|
+
* endpoint's scope grammar (`tool:<name>`, `tools:read`, `tools:*`,
|
|
33
|
+
* `tools:<prefix>.*`) is compact enough for a client to request and far too
|
|
34
|
+
* compact for a human to consent to: nobody can look at `tools:*` and say what
|
|
35
|
+
* it reaches. The controller expands the requested scopes against the
|
|
36
|
+
* application's live tool derivation and hands the result here, one checkbox
|
|
37
|
+
* per tool, carrying the read-only and approval-required facts each one has.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/** The form field each granted scope is submitted under. */
|
|
41
|
+
export const SCOPE_FIELD = 'scope'
|
|
42
|
+
|
|
43
|
+
/** The form field carrying the original authorize query, re-parsed on POST. */
|
|
44
|
+
export const QUERY_FIELD = 'authorize_query'
|
|
45
|
+
|
|
46
|
+
export interface McpOAuthConsentPageProps {
|
|
47
|
+
/** The client's own registered name, or its id when it registered none. */
|
|
48
|
+
clientName: string
|
|
49
|
+
/** The authorize request's query string, handed back on submit. */
|
|
50
|
+
query: string
|
|
51
|
+
/** The tools this request may grant — already intersected with what it asked for. */
|
|
52
|
+
tools: DerivedAgentTool[]
|
|
53
|
+
/** This request's CSRF token, from `getCsrfToken(ctx)`. */
|
|
54
|
+
csrfToken: string
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const STYLES = `
|
|
58
|
+
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }
|
|
59
|
+
body { margin: 0 auto; max-width: 42rem; padding: 2rem 1rem; line-height: 1.5; }
|
|
60
|
+
h1 { font-size: 1.25rem; }
|
|
61
|
+
.tools { list-style: none; margin: 1.5rem 0; padding: 0; }
|
|
62
|
+
.tools li { border-top: 1px solid rgba(128,128,128,.35); padding: .75rem 0; }
|
|
63
|
+
.name { font-family: ui-monospace, monospace; font-weight: 600; }
|
|
64
|
+
.desc { display: block; margin: .25rem 0 0 1.75rem; opacity: .8; }
|
|
65
|
+
.badge { border: 1px solid currentColor; border-radius: .5rem; font-size: .75rem; margin-left: .5rem; padding: 0 .4rem; }
|
|
66
|
+
.empty { opacity: .8; }
|
|
67
|
+
button { font: inherit; padding: .5rem 1rem; }
|
|
68
|
+
`
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One tool, as a checkbox.
|
|
72
|
+
*
|
|
73
|
+
* The value is the `tool:<name>` wire form the scope grammar parses. A bare
|
|
74
|
+
* tool name is not a scope: `parseToolScope` ignores every entry outside
|
|
75
|
+
* `tool:` / `tools:`, so a screen submitting bare names would report success
|
|
76
|
+
* and produce a grant that reaches nothing.
|
|
77
|
+
*/
|
|
78
|
+
const ToolRow: FC<{ tool: DerivedAgentTool }> = ({ tool }) => (
|
|
79
|
+
<li>
|
|
80
|
+
<label>
|
|
81
|
+
<input
|
|
82
|
+
type="checkbox"
|
|
83
|
+
name={SCOPE_FIELD}
|
|
84
|
+
value={`tool:${tool.toolName}`}
|
|
85
|
+
// Read-only tools arrive ticked; anything that can write does not.
|
|
86
|
+
// The default is what most people accept unread, so it is the
|
|
87
|
+
// framework's fail-closed posture rendered as a checkbox: granting a
|
|
88
|
+
// write has to be a decision somebody made, not one they failed to
|
|
89
|
+
// undo.
|
|
90
|
+
checked={tool.annotations.readOnlyHint}
|
|
91
|
+
/>
|
|
92
|
+
<span class="name">{tool.toolName}</span>
|
|
93
|
+
{tool.annotations.readOnlyHint ? <span class="badge">read only</span> : null}
|
|
94
|
+
{tool.approval === 'required' ? <span class="badge">approval required</span> : null}
|
|
95
|
+
</label>
|
|
96
|
+
{tool.description ? <span class="desc">{tool.description}</span> : null}
|
|
97
|
+
</li>
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
export const McpOAuthConsentPage: FC<McpOAuthConsentPageProps> = ({
|
|
101
|
+
clientName,
|
|
102
|
+
query,
|
|
103
|
+
tools,
|
|
104
|
+
csrfToken,
|
|
105
|
+
}) => (
|
|
106
|
+
<html lang="en">
|
|
107
|
+
<head>
|
|
108
|
+
<meta charset="utf-8" />
|
|
109
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
110
|
+
<title>Authorize {clientName}</title>
|
|
111
|
+
<style>{STYLES}</style>
|
|
112
|
+
</head>
|
|
113
|
+
<body>
|
|
114
|
+
<h1>
|
|
115
|
+
<strong>{clientName}</strong> is asking to use this application's tools
|
|
116
|
+
</h1>
|
|
117
|
+
<p>
|
|
118
|
+
Approving lets it act as you, through the tools you select. Uncheck anything you would
|
|
119
|
+
rather it could not do.
|
|
120
|
+
</p>
|
|
121
|
+
<form method="post" action="/oauth/authorize">
|
|
122
|
+
<input type="hidden" name={CSRF_FORM_FIELD} value={csrfToken} />
|
|
123
|
+
<input type="hidden" name={QUERY_FIELD} value={query} />
|
|
124
|
+
{tools.length === 0 ? (
|
|
125
|
+
<p class="empty">
|
|
126
|
+
This application requested no tools it can be granted. Nothing here would give it
|
|
127
|
+
access, so there is nothing to approve.
|
|
128
|
+
</p>
|
|
129
|
+
) : (
|
|
130
|
+
<ul class="tools">
|
|
131
|
+
{tools.map((tool) => (
|
|
132
|
+
<ToolRow key={tool.toolName} tool={tool} />
|
|
133
|
+
))}
|
|
134
|
+
</ul>
|
|
135
|
+
)}
|
|
136
|
+
{tools.length === 0 ? null : <button type="submit">Approve selected</button>}
|
|
137
|
+
</form>
|
|
138
|
+
</body>
|
|
139
|
+
</html>
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
export default McpOAuthConsentPage
|