@guren/plugin-cloudflare 0.6.0 → 0.7.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.
@@ -1,40 +1,12 @@
1
1
  /**
2
2
  * The OAuth consent screen for this application's own agent tools, scaffolded
3
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.
4
+ * `@cloudflare/workers-oauth-provider` owns the rest of the flow (discovery,
5
+ * registration, tokens, PKCE, refresh, `props` encryption) and hands back the one
6
+ * decision it cannot make: who is signed in and what they agreed to. Markup is in
7
+ * `app/View/` (RFC 0014). Tools come live from the router, never from a stale
8
+ * `.guren/agents.gen.ts`; the grant is intersected with the client's request, as
9
+ * the provider does not enforce that. Off Workers `getWorkersEnv` throws at request time.
38
10
  */
39
11
  import {
40
12
  CSRF_FORM_FIELD,
@@ -46,17 +18,15 @@ import {
46
18
  } from '@guren/core'
47
19
  import type { Application, DerivedAgentTool } from '@guren/core'
48
20
  // 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.
21
+ // `buildCloudflareOutput`, which would pull the deploy generator and its node
22
+ // builtins into this app's route graph and into the wrangler bundle.
52
23
  import { getWorkersEnv } from '@guren/plugin-cloudflare/env'
53
24
  import type { AuthRequest, OAuthHelpers } from '@cloudflare/workers-oauth-provider'
54
25
 
55
26
  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.
27
+ // Imported from the view rather than declared here: the page renders the form,
28
+ // so it owns its field names. Two spellings of one contract fail silently — a
29
+ // submitted field nothing looks for.
60
30
  import {
61
31
  McpOAuthConsentPage,
62
32
  QUERY_FIELD,
@@ -89,8 +59,6 @@ export default class McpOAuthController extends Controller {
89
59
  const client = await provider.lookupClient(parsed.clientId)
90
60
 
91
61
  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
62
  clientName: client?.clientName ?? parsed.clientId,
95
63
  query: new URL(this.ctx.req.url).searchParams.toString(),
96
64
  tools: this.offeredTools(parsed.scope),
@@ -110,29 +78,18 @@ export default class McpOAuthController extends Controller {
110
78
  throw new Error('The authenticated user id is neither a string nor a number.')
111
79
  }
112
80
 
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.
81
+ // `all: true` turns the repeated `scope` checkboxes into an array instead of
82
+ // the last one winning. The CSRF middleware already called `parseBody()` with
83
+ // no options, but Hono keys its body cache on those options rather than on the
84
+ // request alone, so this call still returns the array — measured, and kept
85
+ // standing by @guren/plugin-cloudflare's `tests/hono-parse-body.test.ts`.
125
86
  const form = await this.ctx.req.parseBody({ all: true })
126
87
 
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.
88
+ // Verified here as well as by the global CSRF middleware, because this form
89
+ // must not depend on that middleware being mounted: with `autoSession: false`
90
+ // or a custom chain it may be absent, and the rendered token looks convincing
91
+ // either way, so the screen would look protected while any site could POST a
92
+ // grant. Through the framework's own `verifyCsrfToken`, never a comparison here.
136
93
  if (!verifyCsrfToken(this.ctx, single(form[CSRF_FORM_FIELD]))) {
137
94
  return this.errorPage(
138
95
  419,
@@ -142,11 +99,9 @@ export default class McpOAuthController extends Controller {
142
99
  }
143
100
 
144
101
  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.
102
+ // Re-parsed from the original query rather than trusted from a hidden field
103
+ // holding the request itself: `parseAuthRequest` re-validates the client and
104
+ // its redirect URI, so a forged submission fails that validation.
150
105
  const parsed = await this.parseAuthRequest(
151
106
  provider,
152
107
  new Request(`${new URL(this.ctx.req.url).origin}/oauth/authorize?${single(form[QUERY_FIELD])}`),
@@ -157,9 +112,9 @@ export default class McpOAuthController extends Controller {
157
112
 
158
113
  const offered = this.offeredTools(parsed.scope)
159
114
  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.
115
+ // Intersection, not the submission: a box checked for anything the client
116
+ // did not ask for is dropped. `tool:<name>` is the wire form the scope
117
+ // grammar parses — a bare tool name grants nothing, silently.
163
118
  const granted = many(form[SCOPE_FIELD]).filter((scope) => offeredScopes.has(scope))
164
119
 
165
120
  const { redirectTo } = await provider.completeAuthorization({
@@ -176,19 +131,11 @@ export default class McpOAuthController extends Controller {
176
131
  }
177
132
 
178
133
  /**
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.
134
+ * Parse an authorize request, answering with a page instead of throwing: a
135
+ * malformed, truncated or tampered query is a routine arrival at this URL, not
136
+ * an application fault, and unhandled would surface as a 500 with a stack
137
+ * trace. The provider's own message is deliberately not echoed — it derives
138
+ * from attacker-controllable query parameters, and a browser reads this page.
192
139
  */
193
140
  private async parseAuthRequest(
194
141
  provider: OAuthHelpers,
@@ -207,20 +154,10 @@ export default class McpOAuthController extends Controller {
207
154
 
208
155
  /**
209
156
  * 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`.
157
+ * `getWorkersEnv()` is first-call-wins, safe here because `OAuthProvider`
158
+ * injects `OAUTH_PROVIDER` into `env` on *both* of its paths before either
159
+ * handler runs (read out of the published `oauth-provider.js`), so an absence
160
+ * is diagnostic, not a race: not on Workers, or built without `--mcp-oauth`.
224
161
  */
225
162
  private provider(): OAuthHelpers {
226
163
  let env: WorkerEnvWithProvider
@@ -244,10 +181,7 @@ export default class McpOAuthController extends Controller {
244
181
  return env.OAUTH_PROVIDER
245
182
  }
246
183
 
247
- /**
248
- * The tools this authorize request may grant: every MCP-exposed tool the
249
- * requested scopes expand to, in router order.
250
- */
184
+ /** Every MCP-exposed tool the requested scopes expand to, in router order. */
251
185
  private offeredTools(requested: string[]): DerivedAgentTool[] {
252
186
  const { tools } = deriveAgentTools(this.make<Application>('app').router.definitions())
253
187
  const exposed = tools.filter((tool) => tool.expose.mcp)
@@ -4,37 +4,17 @@ import { CSRF_FORM_FIELD, type DerivedAgentTool, type FC } from '@guren/core'
4
4
  /**
5
5
  * The OAuth consent screen for this application's own agent tools, scaffolded
6
6
  * once by `guren cloudflare:build --mcp-oauth` and yours to edit from here.
7
- *
8
7
  * 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.
8
+ * hydration, deliberately not Inertia: an API-only app has no client build, and
9
+ * the browser popup showing this may not carry the cookies an SPA boot needs.
10
+ * Keep the `@jsxImportSource` pragma on line 1, the only place TypeScript
11
+ * honours it: it is what lets this compile, with no tsconfig change, in an app
12
+ * pointing `jsx: "react-jsx"` at React.
23
13
  *
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.
14
+ * `hono/jsx` escapes text children and attribute values but does not validate
15
+ * URL schemes, so nothing user-supplied may be added as an `href` unsanitized.
16
+ * The screen lists *tools*, not scopes — nobody can look at `tools:*` and say
17
+ * what it reaches — expanded by the controller into one checkbox each.
38
18
  */
39
19
 
40
20
  /** The form field each granted scope is submitted under. */
@@ -68,12 +48,9 @@ const STYLES = `
68
48
  `
69
49
 
70
50
  /**
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.
51
+ * One tool, as a checkbox. The value is the `tool:<name>` wire form the scope
52
+ * grammar parses: `parseToolScope` ignores a bare tool name, so a screen
53
+ * submitting those would report success and grant nothing.
77
54
  */
78
55
  const ToolRow: FC<{ tool: DerivedAgentTool }> = ({ tool }) => (
79
56
  <li>
@@ -82,11 +59,9 @@ const ToolRow: FC<{ tool: DerivedAgentTool }> = ({ tool }) => (
82
59
  type="checkbox"
83
60
  name={SCOPE_FIELD}
84
61
  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.
62
+ // Read-only tools arrive ticked, anything that can write does not:
63
+ // granting a write has to be a decision somebody made, not one they
64
+ // failed to undo.
90
65
  checked={tool.annotations.readOnlyHint}
91
66
  />
92
67
  <span class="name">{tool.toolName}</span>
@@ -4,26 +4,14 @@ import type { FC } from '@guren/core'
4
4
  /**
5
5
  * The page a visitor gets when the authorize request itself is unusable —
6
6
  * scaffolded once by `guren cloudflare:build --mcp-oauth` and yours to edit.
7
+ * These arrivals are routine (a malformed, stale or tampered query, an expired
8
+ * CSRF token) and would otherwise surface as a 500 with a stack trace.
7
9
  *
8
- * These arrivals are routine, not application faults: a query that is
9
- * malformed, truncated, tampered with, or simply stale, and a consent form
10
- * submitted after its CSRF token expired. Left to the exception handler they
11
- * would surface as a 500 with a stack trace in it — alarming, and useless to
12
- * the person reading it, because the fix is never anything they can do on this
13
- * page. It is to start again from the client that sent them.
14
- *
15
- * **Nothing derived from the request is rendered here.** No provider message,
16
- * no query parameter, no exception text: all of it is attacker-controllable,
17
- * and this page is reached by a browser. `title` and `advice` are the
18
- * caller's own fixed strings.
19
- *
20
- * A file of its own rather than a second export beside the consent screen: it
21
- * is a different document with different styling and no form, and a developer
22
- * editing the consent screen should not have to scroll past it.
23
- *
24
- * See `McpOAuthConsentPage.tsx` for why the `@jsxImportSource` pragma on line
25
- * 1 is what lets this compile in an app whose `tsconfig` points
26
- * `jsx: "react-jsx"` at React. Keep it on the first line.
10
+ * **Nothing derived from the request is rendered here**: a provider message, a
11
+ * query parameter or an exception text is attacker-controllable and a browser
12
+ * reads this page, so `title` and `advice` are the caller's fixed strings. The
13
+ * `@jsxImportSource` pragma lets this compile in an app whose `tsconfig` points
14
+ * `jsx: "react-jsx"` at React — keep it on line 1, the only place it counts.
27
15
  */
28
16
  export interface McpOAuthErrorPageProps {
29
17
  /** What went wrong, in the visitor's terms. A fixed string, never echoed input. */
@@ -1,27 +1,12 @@
1
1
  /**
2
2
  * The OAuth authorize/consent routes for the App MCP endpoint, scaffolded once
3
3
  * by `guren cloudflare:build --mcp-oauth` and yours to edit from here.
4
- *
5
- * `@cloudflare/workers-oauth-provider` owns `/oauth/token` and
6
- * `/oauth/register` itself — it answers them before the request ever reaches
7
- * this application. `/oauth/authorize` is the one endpoint the provider hands
8
- * back, because only the application can say who is signed in and render a
9
- * consent screen that means anything.
10
- *
11
- * **Wire this into your routes entry**, or nothing mounts it:
12
- *
13
- * ```ts
14
- * // routes/web.ts
15
- * import { registerMcpOAuthRoutes } from './mcp-oauth'
16
- *
17
- * export function registerWebRoutes(router: Router): void {
18
- * registerMcpOAuthRoutes(router)
19
- * // …your own routes
20
- * }
21
- * ```
22
- *
23
- * These routes are deliberately **not** `.agent()`-exposed: they are the gate
24
- * an agent passes through, not something an agent may call.
4
+ * `@cloudflare/workers-oauth-provider` answers `/oauth/token` and
5
+ * `/oauth/register` itself; `/oauth/authorize` is the one endpoint it hands
6
+ * back, because only the application knows who is signed in.
7
+ * **Call `registerMcpOAuthRoutes(router)` from your routes entry**, or nothing
8
+ * mounts it. Not `.agent()`-exposed: these are the gate an agent passes through,
9
+ * not something an agent may call.
25
10
  */
26
11
  import type { Router } from '@guren/core'
27
12