@guren/plugin-cloudflare 0.4.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.
@@ -9,6 +9,14 @@ declare const _default: {
9
9
  type: "boolean";
10
10
  description: string;
11
11
  };
12
+ 'mcp-oauth': {
13
+ type: "boolean";
14
+ description: string;
15
+ };
16
+ 'mcp-path': {
17
+ type: "string";
18
+ description: string;
19
+ };
12
20
  }>;
13
21
  };
14
22
  //#endregion
package/dist/commands.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as buildCloudflareOutput } from "./build-B7zQ13ai.js";
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 { FileMetadata, PutOptions, ServiceProviderConstructor, StorageDriver } from "@guren/core";
1
+ import { captureWorkersEnv, getWorkersEnv, resetWorkersEnv } from "./env.js";
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
@@ -125,9 +142,16 @@ interface R2PutOptionsLike {
125
142
  customMetadata?: Record<string, string>;
126
143
  }
127
144
  type R2PutValue = R2StreamLike | R2BlobLike | ArrayBuffer | ArrayBufferView | string | null;
145
+ interface R2GetOptionsLike {
146
+ /** R2's offset/length range form (the driver never sends `suffix`). */
147
+ range?: {
148
+ offset: number;
149
+ length?: number;
150
+ };
151
+ }
128
152
  interface R2BucketLike {
129
153
  head(key: string): Promise<R2ObjectLike | null>;
130
- get(key: string): Promise<R2ObjectBodyLike | null>;
154
+ get(key: string, options?: R2GetOptionsLike): Promise<R2ObjectBodyLike | null>;
131
155
  put(key: string, value: R2PutValue, options?: R2PutOptionsLike): Promise<R2ObjectLike | null>;
132
156
  delete(keys: string | string[]): Promise<void>;
133
157
  list(options?: R2ListOptionsLike): Promise<R2ObjectsLike>;
@@ -186,6 +210,12 @@ interface R2DriverOptions {
186
210
  * ```
187
211
  */
188
212
  declare class R2Driver implements StorageDriver {
213
+ /**
214
+ * Declared iff `presign` credentials were configured — a config fact,
215
+ * never a probe (RFC 0015 §3): without them `temporaryUrl()` throws, and
216
+ * the delivery route must know that *before* handing out a redirect.
217
+ */
218
+ readonly capabilities?: StorageDriverCapabilities;
189
219
  private readonly resolveBinding;
190
220
  private readonly publicUrl?;
191
221
  private readonly prefix;
@@ -202,6 +232,7 @@ declare class R2Driver implements StorageDriver {
202
232
  putFile(_path: string, _localPath: string, _options?: PutOptions): Promise<string>;
203
233
  get(path: string): Promise<Buffer | null>;
204
234
  getAsString(path: string): Promise<string | null>;
235
+ getStream(path: string, options?: GetStreamOptions): Promise<ReadableStream<Uint8Array> | null>;
205
236
  exists(path: string): Promise<boolean>;
206
237
  delete(path: string): Promise<boolean>;
207
238
  deleteMany(paths: string[]): Promise<number>;
@@ -209,7 +240,7 @@ declare class R2Driver implements StorageDriver {
209
240
  copy(from: string, to: string): Promise<string>;
210
241
  move(from: string, to: string): Promise<string>;
211
242
  url(path: string): string;
212
- temporaryUrl(path: string, expiration: Date): Promise<string>;
243
+ temporaryUrl(path: string, expiration: Date, options?: TemporaryUrlOptions): Promise<string>;
213
244
  size(path: string): Promise<number>;
214
245
  lastModified(path: string): Promise<Date>;
215
246
  private metadataOrFail;
package/dist/index.js CHANGED
@@ -1,21 +1,6 @@
1
- import { n as flattenD1Migrations, t as buildCloudflareOutput } from "./build-B7zQ13ai.js";
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;
@@ -81,9 +66,27 @@ async function hmac(key, value) {
81
66
  }, false, ["sign"]);
82
67
  return crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(value));
83
68
  }
84
- /** `AWS4<secret>` → date → region → service → terminator. */
85
- async function signingKey(secretAccessKey, dateStamp, region, service) {
86
- return hmac(await hmac(await hmac(await hmac(new TextEncoder().encode(`AWS4${secretAccessKey}`), dateStamp), region), service), TERMINATOR);
69
+ /**
70
+ * `AWS4<secret>` → date → region → service → terminator, cached per
71
+ * credential and day: the delivery route presigns once per request on
72
+ * redirect-mode disks, and the four-step HMAC chain (eight `crypto.subtle`
73
+ * host calls) only changes when the date stamp rolls over. Keyed by access
74
+ * key id — never the secret — plus scope; self-bounding, but capped anyway
75
+ * so a pathological key rotation cannot grow it.
76
+ */
77
+ const signingKeyCache = /* @__PURE__ */ new Map();
78
+ const SIGNING_KEY_CACHE_MAX = 8;
79
+ function signingKey(accessKeyId, secretAccessKey, dateStamp, region, service) {
80
+ const cacheKey = `${accessKeyId}/${dateStamp}/${region}/${service}`;
81
+ const cached = signingKeyCache.get(cacheKey);
82
+ if (cached) return cached;
83
+ const derived = (async () => {
84
+ return hmac(await hmac(await hmac(await hmac(new TextEncoder().encode(`AWS4${secretAccessKey}`), dateStamp), region), service), TERMINATOR);
85
+ })();
86
+ if (signingKeyCache.size >= SIGNING_KEY_CACHE_MAX) signingKeyCache.clear();
87
+ signingKeyCache.set(cacheKey, derived);
88
+ derived.catch(() => signingKeyCache.delete(cacheKey));
89
+ return derived;
87
90
  }
88
91
  /**
89
92
  * Presign a GET so the URL alone authorizes the read until it expires.
@@ -115,7 +118,7 @@ async function presignGetUrl(options) {
115
118
  scope,
116
119
  await sha256Hex(canonicalRequest)
117
120
  ].join("\n");
118
- const key = await signingKey(secretAccessKey, dateStamp, region, service);
121
+ const key = await signingKey(accessKeyId, secretAccessKey, dateStamp, region, service);
119
122
  url.searchParams.set("X-Amz-Signature", toHex(await hmac(key, stringToSign)));
120
123
  return url.toString();
121
124
  }
@@ -140,6 +143,12 @@ const DELETE_CONCURRENCY = 6;
140
143
  * ```
141
144
  */
142
145
  var R2Driver = class {
146
+ /**
147
+ * Declared iff `presign` credentials were configured — a config fact,
148
+ * never a probe (RFC 0015 §3): without them `temporaryUrl()` throws, and
149
+ * the delivery route must know that *before* handing out a redirect.
150
+ */
151
+ capabilities;
143
152
  resolveBinding;
144
153
  publicUrl;
145
154
  prefix;
@@ -151,6 +160,7 @@ var R2Driver = class {
151
160
  this.prefix = trimSlashes(options.prefix ?? "");
152
161
  this.diskVisibility = options.visibility ?? (options.publicUrl ? "public" : "private");
153
162
  this.presign = options.presign;
163
+ if (options.presign) this.capabilities = { presignedGet: true };
154
164
  }
155
165
  bucket() {
156
166
  const binding = this.resolveBinding();
@@ -193,6 +203,15 @@ var R2Driver = class {
193
203
  const object = await this.bucket().get(this.key(path));
194
204
  return object ? object.text() : null;
195
205
  }
206
+ async getStream(path, options) {
207
+ const range = options?.range;
208
+ const object = await this.bucket().get(this.key(path), range ? { range: {
209
+ offset: range.start,
210
+ ...range.end !== void 0 ? { length: range.end - range.start + 1 } : {}
211
+ } } : void 0);
212
+ if (!object) return null;
213
+ return object.body;
214
+ }
196
215
  async exists(path) {
197
216
  return await this.bucket().head(this.key(path)) !== null;
198
217
  }
@@ -234,7 +253,7 @@ var R2Driver = class {
234
253
  if (!this.publicUrl) throw new Error("R2Driver.url() requires the \"publicUrl\" option (the bucket’s custom domain or r2.dev subdomain). R2 has no derivable public URL.");
235
254
  return `${this.publicUrl}/${encodeKey(this.key(path))}`;
236
255
  }
237
- async temporaryUrl(path, expiration) {
256
+ async temporaryUrl(path, expiration, options) {
238
257
  if (!this.presign) throw new Error("R2Driver.temporaryUrl() cannot sign URLs through the R2 binding. Either configure \"presign: { accountId, bucket, accessKeyId, secretAccessKey }\" (an R2 API token, used with the S3-compatible endpoint) or serve private files through a signed app route.");
239
258
  const expiresIn = Math.floor((expiration.getTime() - Date.now()) / 1e3);
240
259
  if (expiresIn > MAX_PRESIGN_SECONDS) throw new Error(`R2Driver.temporaryUrl(): R2 presigned URLs may be valid for at most 7 days (requested ${expiresIn}s).`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-cloudflare",
3
- "version": "0.4.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.10.0",
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
+ }