@guren/plugin-cloudflare 0.5.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.
@@ -0,0 +1,220 @@
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
+ * `@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.
10
+ */
11
+ import {
12
+ CSRF_FORM_FIELD,
13
+ Controller,
14
+ deriveAgentTools,
15
+ expandToolScopes,
16
+ getCsrfToken,
17
+ verifyCsrfToken,
18
+ } from '@guren/core'
19
+ import type { Application, DerivedAgentTool } from '@guren/core'
20
+ // The lean subpath, deliberately not the root entry: the root also exports
21
+ // `buildCloudflareOutput`, which would pull the deploy generator and its node
22
+ // builtins into this app's route graph and into the wrangler bundle.
23
+ import { getWorkersEnv } from '@guren/plugin-cloudflare/env'
24
+ import type { AuthRequest, OAuthHelpers } from '@cloudflare/workers-oauth-provider'
25
+
26
+ import { McpOAuthErrorPage } from '../../View/McpOAuthErrorPage.js'
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.
30
+ import {
31
+ McpOAuthConsentPage,
32
+ QUERY_FIELD,
33
+ SCOPE_FIELD,
34
+ } from '../../View/McpOAuthConsentPage.js'
35
+
36
+ /**
37
+ * Where an unauthenticated visitor is sent. The consent decision is only
38
+ * meaningful for a signed-in user — change this to your own login path.
39
+ */
40
+ const LOGIN_PATH = '/login'
41
+
42
+ interface WorkerEnvWithProvider {
43
+ OAUTH_PROVIDER: OAuthHelpers
44
+ }
45
+
46
+ export default class McpOAuthController extends Controller {
47
+ /** GET /oauth/authorize — render the consent screen. */
48
+ async show(): Promise<Response> {
49
+ const userId = await this.auth.id()
50
+ if (userId === null || userId === undefined) {
51
+ return this.redirect(this.loginUrl())
52
+ }
53
+
54
+ const provider = this.provider()
55
+ const parsed = await this.parseAuthRequest(provider, this.ctx.req.raw)
56
+ if (parsed instanceof Response) {
57
+ return parsed
58
+ }
59
+ const client = await provider.lookupClient(parsed.clientId)
60
+
61
+ return this.view(McpOAuthConsentPage, {
62
+ clientName: client?.clientName ?? parsed.clientId,
63
+ query: new URL(this.ctx.req.url).searchParams.toString(),
64
+ tools: this.offeredTools(parsed.scope),
65
+ csrfToken: getCsrfToken(this.ctx),
66
+ })
67
+ }
68
+
69
+ /** POST /oauth/authorize — record the decision and hand back to the provider. */
70
+ async approve(): Promise<Response> {
71
+ const userId = await this.auth.id()
72
+ if (userId === null || userId === undefined) {
73
+ return this.redirect(this.loginUrl())
74
+ }
75
+ if (typeof userId !== 'string' && typeof userId !== 'number') {
76
+ // The grant carries this id in its props and the endpoint maps it to an
77
+ // AgentPrincipal, which admits a string or a number and nothing else.
78
+ throw new Error('The authenticated user id is neither a string nor a number.')
79
+ }
80
+
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`.
86
+ const form = await this.ctx.req.parseBody({ all: true })
87
+
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.
93
+ if (!verifyCsrfToken(this.ctx, single(form[CSRF_FORM_FIELD]))) {
94
+ return this.errorPage(
95
+ 419,
96
+ 'This consent form has expired',
97
+ 'Start the authorization again from the application that sent you here.',
98
+ )
99
+ }
100
+
101
+ const provider = this.provider()
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.
105
+ const parsed = await this.parseAuthRequest(
106
+ provider,
107
+ new Request(`${new URL(this.ctx.req.url).origin}/oauth/authorize?${single(form[QUERY_FIELD])}`),
108
+ )
109
+ if (parsed instanceof Response) {
110
+ return parsed
111
+ }
112
+
113
+ const offered = this.offeredTools(parsed.scope)
114
+ const offeredScopes = new Set(offered.map((tool) => `tool:${tool.toolName}`))
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.
118
+ const granted = many(form[SCOPE_FIELD]).filter((scope) => offeredScopes.has(scope))
119
+
120
+ const { redirectTo } = await provider.completeAuthorization({
121
+ request: parsed,
122
+ // The provider's own identifier type is a string; `props.userId` keeps
123
+ // the application's, which is what its policies look up by.
124
+ userId: String(userId),
125
+ scope: granted,
126
+ props: { userId, scopes: granted },
127
+ metadata: { grantedAt: new Date().toISOString() },
128
+ })
129
+
130
+ return this.redirect(redirectTo)
131
+ }
132
+
133
+ /**
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.
139
+ */
140
+ private async parseAuthRequest(
141
+ provider: OAuthHelpers,
142
+ request: Request,
143
+ ): Promise<AuthRequest | Response> {
144
+ try {
145
+ return await provider.parseAuthRequest(request)
146
+ } catch {
147
+ return this.errorPage(
148
+ 400,
149
+ 'This authorization link is not valid',
150
+ 'Start the authorization again from the application that sent you here.',
151
+ )
152
+ }
153
+ }
154
+
155
+ /**
156
+ * The provider helpers, from the Workers env this request captured.
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`.
161
+ */
162
+ private provider(): OAuthHelpers {
163
+ let env: WorkerEnvWithProvider
164
+ try {
165
+ env = getWorkersEnv<WorkerEnvWithProvider>()
166
+ } catch (error) {
167
+ throw new Error(
168
+ 'The OAuth consent routes require the Cloudflare Workers env. '
169
+ + 'They run only in a worker built with `guren cloudflare:build --mcp-oauth`. '
170
+ + `(${String(error)})`,
171
+ )
172
+ }
173
+
174
+ if (!env.OAUTH_PROVIDER) {
175
+ throw new Error(
176
+ 'env.OAUTH_PROVIDER is missing. This worker was not wrapped in an OAuthProvider — '
177
+ + 'rebuild with `guren cloudflare:build --mcp-oauth`.',
178
+ )
179
+ }
180
+
181
+ return env.OAUTH_PROVIDER
182
+ }
183
+
184
+ /** Every MCP-exposed tool the requested scopes expand to, in router order. */
185
+ private offeredTools(requested: string[]): DerivedAgentTool[] {
186
+ const { tools } = deriveAgentTools(this.make<Application>('app').router.definitions())
187
+ const exposed = tools.filter((tool) => tool.expose.mcp)
188
+
189
+ const allowed = new Set(
190
+ expandToolScopes(
191
+ requested,
192
+ exposed.map((tool) => ({ name: tool.toolName, readOnly: tool.annotations.readOnlyHint })),
193
+ ),
194
+ )
195
+
196
+ return exposed.filter((tool) => allowed.has(tool.toolName))
197
+ }
198
+
199
+ private loginUrl(): string {
200
+ const target = new URL(this.ctx.req.url)
201
+ return `${LOGIN_PATH}?redirectTo=${encodeURIComponent(`${target.pathname}${target.search}`)}`
202
+ }
203
+
204
+ /** A plain, stack-free page for the arrivals that are nobody's bug. */
205
+ private errorPage(status: number, title: string, advice: string): Promise<Response> {
206
+ return this.view(McpOAuthErrorPage, { title, advice }, { status })
207
+ }
208
+ }
209
+
210
+ /** One value from a parsed body field that may legally hold several. */
211
+ function single(value: unknown): string {
212
+ return typeof value === 'string' ? value : ''
213
+ }
214
+
215
+ /** Every string value of a parsed body field, whether it held one or many. */
216
+ function many(value: unknown): string[] {
217
+ if (typeof value === 'string') return [value]
218
+ if (Array.isArray(value)) return value.filter((entry): entry is string => typeof entry === 'string')
219
+ return []
220
+ }
@@ -0,0 +1,117 @@
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
+ * Server-rendered through `Controller.view()` (RFC 0014) — `hono/jsx`, no
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.
13
+ *
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.
18
+ */
19
+
20
+ /** The form field each granted scope is submitted under. */
21
+ export const SCOPE_FIELD = 'scope'
22
+
23
+ /** The form field carrying the original authorize query, re-parsed on POST. */
24
+ export const QUERY_FIELD = 'authorize_query'
25
+
26
+ export interface McpOAuthConsentPageProps {
27
+ /** The client's own registered name, or its id when it registered none. */
28
+ clientName: string
29
+ /** The authorize request's query string, handed back on submit. */
30
+ query: string
31
+ /** The tools this request may grant — already intersected with what it asked for. */
32
+ tools: DerivedAgentTool[]
33
+ /** This request's CSRF token, from `getCsrfToken(ctx)`. */
34
+ csrfToken: string
35
+ }
36
+
37
+ const STYLES = `
38
+ :root { color-scheme: light dark; font-family: system-ui, sans-serif; }
39
+ body { margin: 0 auto; max-width: 42rem; padding: 2rem 1rem; line-height: 1.5; }
40
+ h1 { font-size: 1.25rem; }
41
+ .tools { list-style: none; margin: 1.5rem 0; padding: 0; }
42
+ .tools li { border-top: 1px solid rgba(128,128,128,.35); padding: .75rem 0; }
43
+ .name { font-family: ui-monospace, monospace; font-weight: 600; }
44
+ .desc { display: block; margin: .25rem 0 0 1.75rem; opacity: .8; }
45
+ .badge { border: 1px solid currentColor; border-radius: .5rem; font-size: .75rem; margin-left: .5rem; padding: 0 .4rem; }
46
+ .empty { opacity: .8; }
47
+ button { font: inherit; padding: .5rem 1rem; }
48
+ `
49
+
50
+ /**
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.
54
+ */
55
+ const ToolRow: FC<{ tool: DerivedAgentTool }> = ({ tool }) => (
56
+ <li>
57
+ <label>
58
+ <input
59
+ type="checkbox"
60
+ name={SCOPE_FIELD}
61
+ value={`tool:${tool.toolName}`}
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.
65
+ checked={tool.annotations.readOnlyHint}
66
+ />
67
+ <span class="name">{tool.toolName}</span>
68
+ {tool.annotations.readOnlyHint ? <span class="badge">read only</span> : null}
69
+ {tool.approval === 'required' ? <span class="badge">approval required</span> : null}
70
+ </label>
71
+ {tool.description ? <span class="desc">{tool.description}</span> : null}
72
+ </li>
73
+ )
74
+
75
+ export const McpOAuthConsentPage: FC<McpOAuthConsentPageProps> = ({
76
+ clientName,
77
+ query,
78
+ tools,
79
+ csrfToken,
80
+ }) => (
81
+ <html lang="en">
82
+ <head>
83
+ <meta charset="utf-8" />
84
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
85
+ <title>Authorize {clientName}</title>
86
+ <style>{STYLES}</style>
87
+ </head>
88
+ <body>
89
+ <h1>
90
+ <strong>{clientName}</strong> is asking to use this application's tools
91
+ </h1>
92
+ <p>
93
+ Approving lets it act as you, through the tools you select. Uncheck anything you would
94
+ rather it could not do.
95
+ </p>
96
+ <form method="post" action="/oauth/authorize">
97
+ <input type="hidden" name={CSRF_FORM_FIELD} value={csrfToken} />
98
+ <input type="hidden" name={QUERY_FIELD} value={query} />
99
+ {tools.length === 0 ? (
100
+ <p class="empty">
101
+ This application requested no tools it can be granted. Nothing here would give it
102
+ access, so there is nothing to approve.
103
+ </p>
104
+ ) : (
105
+ <ul class="tools">
106
+ {tools.map((tool) => (
107
+ <ToolRow key={tool.toolName} tool={tool} />
108
+ ))}
109
+ </ul>
110
+ )}
111
+ {tools.length === 0 ? null : <button type="submit">Approve selected</button>}
112
+ </form>
113
+ </body>
114
+ </html>
115
+ )
116
+
117
+ export default McpOAuthConsentPage
@@ -0,0 +1,45 @@
1
+ /** @jsxImportSource @guren/core */
2
+ import type { FC } from '@guren/core'
3
+
4
+ /**
5
+ * The page a visitor gets when the authorize request itself is unusable —
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.
9
+ *
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.
15
+ */
16
+ export interface McpOAuthErrorPageProps {
17
+ /** What went wrong, in the visitor's terms. A fixed string, never echoed input. */
18
+ title: string
19
+ /** What to do about it. Also fixed. */
20
+ advice: string
21
+ }
22
+
23
+ const STYLES = `
24
+ :root { color-scheme: light dark; font-family: system-ui, sans-serif; }
25
+ body { margin: 0 auto; max-width: 32rem; padding: 3rem 1rem; line-height: 1.5; }
26
+ h1 { font-size: 1.25rem; }
27
+ p { opacity: .8; }
28
+ `
29
+
30
+ export const McpOAuthErrorPage: FC<McpOAuthErrorPageProps> = ({ title, advice }) => (
31
+ <html lang="en">
32
+ <head>
33
+ <meta charset="utf-8" />
34
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
35
+ <title>{title}</title>
36
+ <style>{STYLES}</style>
37
+ </head>
38
+ <body>
39
+ <h1>{title}</h1>
40
+ <p>{advice}</p>
41
+ </body>
42
+ </html>
43
+ )
44
+
45
+ export default McpOAuthErrorPage
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The OAuth authorize/consent routes for the App MCP endpoint, scaffolded once
3
+ * by `guren cloudflare:build --mcp-oauth` and yours to edit from here.
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.
10
+ */
11
+ import type { Router } from '@guren/core'
12
+
13
+ import McpOAuthController from '../app/Http/Controllers/McpOAuthController.js'
14
+
15
+ export function registerMcpOAuthRoutes(router: Router): void {
16
+ router.get('/oauth/authorize', [McpOAuthController, 'show']).name('mcp-oauth.authorize')
17
+ router.post('/oauth/authorize', [McpOAuthController, 'approve']).name('mcp-oauth.approve')
18
+ }
19
+
20
+ export default registerMcpOAuthRoutes