@guren/plugin-cloudflare 0.12.3 → 0.13.1
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/README.md +21 -12
- package/dist/{bundle-size-CUn3w_nY.js → bundle-size-CcXTKLKq.js} +420 -114
- package/dist/commands.d.ts +64 -0
- package/dist/commands.js +1933 -42
- package/dist/config.d.ts +117 -0
- package/dist/config.js +102 -0
- package/dist/env.d.ts +16 -4
- package/dist/env.js +28 -8
- package/dist/index.d.ts +23 -10
- package/dist/index.js +25 -5
- package/dist/worker-manifest-16SJawlX.js +31 -0
- package/package.json +10 -3
- package/templates/mcp-oauth/app/Http/Controllers/McpOAuthController.ts +27 -2
- package/templates/mcp-oauth/app/View/McpOAuthConsentPage.tsx +21 -1
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
//#region src/worker-manifest.d.ts
|
|
2
|
+
declare const WORKER_MANIFEST_VERSION = 2;
|
|
3
|
+
/** One binding's resource identity, settled by a deploy and carried over by every build. */
|
|
4
|
+
interface ResolvedResource {
|
|
5
|
+
id?: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
}
|
|
8
|
+
interface WorkerManifest {
|
|
9
|
+
version: typeof WORKER_MANIFEST_VERSION;
|
|
10
|
+
/** Paths are relative to the app root, POSIX, each starting with `./`. */
|
|
11
|
+
entrypoint: string;
|
|
12
|
+
assetsDirectory: string;
|
|
13
|
+
compatibilityFlags: string[];
|
|
14
|
+
htmlHandling: 'none';
|
|
15
|
+
alias: Record<string, string>;
|
|
16
|
+
define: Record<string, string>;
|
|
17
|
+
/** Plain-text bindings; `define` cannot reach a runtime `process.env[key]` read. */
|
|
18
|
+
vars: Record<string, string>;
|
|
19
|
+
d1: {
|
|
20
|
+
binding: string;
|
|
21
|
+
databaseName: string;
|
|
22
|
+
};
|
|
23
|
+
/** KV namespace bindings the build owns (`OAUTH_KV` under `--mcp-oauth`). */
|
|
24
|
+
kvNamespaces: string[];
|
|
25
|
+
/** Cron schedules for a `scheduled` trigger; empty when the worker schedules nothing. */
|
|
26
|
+
crons: string[];
|
|
27
|
+
/** `config/cloudflare.ts` names by binding, which the plan resolves and creates under. */
|
|
28
|
+
resourceNames: Record<string, string>;
|
|
29
|
+
/** Why the schedule kernel could not be read; the plan blocks unless the config sets its own triggers. */
|
|
30
|
+
scheduleUnreadable?: string;
|
|
31
|
+
/** Agent classes hosted as SQLite-backed Durable Objects, with the binding each gets. */
|
|
32
|
+
agents: Array<{
|
|
33
|
+
exportName: string;
|
|
34
|
+
binding: string;
|
|
35
|
+
}>;
|
|
36
|
+
/** R2 bucket bindings the introspected app's disks name (RFC 0035 §2); absent from a manifest older than that. */
|
|
37
|
+
r2Buckets?: string[];
|
|
38
|
+
/** Keyed by binding name. The build never writes an entry, only carries them over. */
|
|
39
|
+
resolved: Record<string, ResolvedResource>;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/config.d.ts
|
|
43
|
+
/**
|
|
44
|
+
* Guren's deploy settings, read by `cloudflare:build` and `cloudflare:deploy` and never by
|
|
45
|
+
* the running app (RFC 0035 §3). Default-exported from `config/cloudflare.ts`.
|
|
46
|
+
*/
|
|
47
|
+
interface CloudflareDeployConfig {
|
|
48
|
+
/** Front the App MCP endpoint with the OAuth provider, which binds `OAUTH_KV`. Replaces `--mcp-oauth`. */
|
|
49
|
+
mcpOAuth?: boolean;
|
|
50
|
+
/** Where the App MCP endpoint is mounted, as `mcpPlugin({ path })` has it. Defaults to `/mcp`. */
|
|
51
|
+
mcpPath?: string;
|
|
52
|
+
/** Resource names by binding (`DB`, `OAUTH_KV`), for one the default name does not fit or collides with. */
|
|
53
|
+
resourceNames?: Record<string, string>;
|
|
54
|
+
}
|
|
55
|
+
declare function defineCloudflareConfig(config: CloudflareDeployConfig): CloudflareDeployConfig;
|
|
56
|
+
interface GurenWorkerOptions {
|
|
57
|
+
/** The Worker's name, the same one `cf deploy` deploys under. */
|
|
58
|
+
name: string;
|
|
59
|
+
/** The `cloudflare:build` output directory, relative to the app root. Defaults to `.guren/cloudflare`. */
|
|
60
|
+
outputDir?: string;
|
|
61
|
+
}
|
|
62
|
+
/** The bindings and exports below are the plain objects `bindings.*()` and `exports.*()` from `cf/config` return. */
|
|
63
|
+
type GurenBinding = {
|
|
64
|
+
type: 'd1';
|
|
65
|
+
name?: string;
|
|
66
|
+
id?: string;
|
|
67
|
+
} | {
|
|
68
|
+
type: 'kv';
|
|
69
|
+
id?: string;
|
|
70
|
+
} | {
|
|
71
|
+
type: 'r2';
|
|
72
|
+
name?: string;
|
|
73
|
+
} | {
|
|
74
|
+
type: 'durable-object';
|
|
75
|
+
worker: string;
|
|
76
|
+
exportName: string;
|
|
77
|
+
} | {
|
|
78
|
+
type: 'text';
|
|
79
|
+
value: string;
|
|
80
|
+
};
|
|
81
|
+
interface GurenWorker {
|
|
82
|
+
name: string;
|
|
83
|
+
entrypoint: string;
|
|
84
|
+
compatibilityFlags: string[];
|
|
85
|
+
assets: {
|
|
86
|
+
htmlHandling: WorkerManifest['htmlHandling'];
|
|
87
|
+
};
|
|
88
|
+
env: Record<string, GurenBinding>;
|
|
89
|
+
exports: Record<string, {
|
|
90
|
+
type: 'durable-object';
|
|
91
|
+
storage: 'sqlite';
|
|
92
|
+
}>;
|
|
93
|
+
/** Absent when nothing is scheduled; a `triggers` key after the spread replaces it. */
|
|
94
|
+
triggers?: Array<{
|
|
95
|
+
type: 'scheduled';
|
|
96
|
+
schedule: string;
|
|
97
|
+
}>;
|
|
98
|
+
}
|
|
99
|
+
interface GurenWranglerBundle {
|
|
100
|
+
keepNames: true;
|
|
101
|
+
alias: Record<string, string>;
|
|
102
|
+
define: Record<string, string>;
|
|
103
|
+
assetsDirectory: string;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The Worker as `cloudflare:build` assembled it, to spread into `defineConfig({ worker })`.
|
|
107
|
+
* `compatibilityDate` is left to the config file: a date that moved with each
|
|
108
|
+
* build would change the runtime's behaviour on every deploy.
|
|
109
|
+
*/
|
|
110
|
+
declare function gurenWorker(options: GurenWorkerOptions): Promise<GurenWorker>;
|
|
111
|
+
/**
|
|
112
|
+
* The bundler options for `defineWranglerConfig()`. `keepNames` is pinned on:
|
|
113
|
+
* queued jobs, events, notifications and durable agents are stored by class name.
|
|
114
|
+
*/
|
|
115
|
+
declare function gurenWranglerBundle(options?: Pick<GurenWorkerOptions, 'outputDir'>): Promise<GurenWranglerBundle>;
|
|
116
|
+
//#endregion
|
|
117
|
+
export { CloudflareDeployConfig, GurenBinding, GurenWorker, GurenWorkerOptions, GurenWranglerBundle, defineCloudflareConfig, gurenWorker, gurenWranglerBundle };
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { r as WORKER_MANIFEST_FILE, s as resourceName, t as CF_OUTPUT_DIR } from "./worker-manifest-16SJawlX.js";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
//#region src/config.ts
|
|
5
|
+
/**
|
|
6
|
+
* `@guren/plugin-cloudflare/config`: Guren's part of `cloudflare.config.ts` and
|
|
7
|
+
* `wrangler.config.ts` for the `cf` CLI (RFC 0035 §3). `cf` evaluates those files
|
|
8
|
+
* under Node, in another process from the Bun build that knows the app, so this
|
|
9
|
+
* module computes nothing about the app: it reads the manifest `cloudflare:build`
|
|
10
|
+
* wrote, and imports only Node builtins and the manifest's types.
|
|
11
|
+
*/
|
|
12
|
+
function defineCloudflareConfig(config) {
|
|
13
|
+
return config;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The Worker as `cloudflare:build` assembled it, to spread into `defineConfig({ worker })`.
|
|
17
|
+
* `compatibilityDate` is left to the config file: a date that moved with each
|
|
18
|
+
* build would change the runtime's behaviour on every deploy.
|
|
19
|
+
*/
|
|
20
|
+
async function gurenWorker(options) {
|
|
21
|
+
const manifest = await readWorkerManifest(options.outputDir);
|
|
22
|
+
const resolved = manifest.resolved;
|
|
23
|
+
const env = {};
|
|
24
|
+
const d1 = resolved[manifest.d1.binding];
|
|
25
|
+
env[manifest.d1.binding] = {
|
|
26
|
+
type: "d1",
|
|
27
|
+
name: d1?.name ?? manifest.d1.databaseName,
|
|
28
|
+
...d1?.id ? { id: d1.id } : {}
|
|
29
|
+
};
|
|
30
|
+
for (const binding of manifest.kvNamespaces) {
|
|
31
|
+
const id = resolved[binding]?.id;
|
|
32
|
+
env[binding] = {
|
|
33
|
+
type: "kv",
|
|
34
|
+
...id ? { id } : {}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
for (const binding of manifest.r2Buckets ?? []) env[binding] = {
|
|
38
|
+
type: "r2",
|
|
39
|
+
name: resourceName(options.name, binding, manifest.resourceNames, resolved[binding]?.name)
|
|
40
|
+
};
|
|
41
|
+
for (const [key, value] of Object.entries(manifest.vars)) env[key] = {
|
|
42
|
+
type: "text",
|
|
43
|
+
value
|
|
44
|
+
};
|
|
45
|
+
const exports = {};
|
|
46
|
+
for (const agent of manifest.agents) {
|
|
47
|
+
env[agent.binding] = {
|
|
48
|
+
type: "durable-object",
|
|
49
|
+
worker: options.name,
|
|
50
|
+
exportName: agent.exportName
|
|
51
|
+
};
|
|
52
|
+
exports[agent.exportName] = {
|
|
53
|
+
type: "durable-object",
|
|
54
|
+
storage: "sqlite"
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
name: options.name,
|
|
59
|
+
entrypoint: manifest.entrypoint,
|
|
60
|
+
compatibilityFlags: manifest.compatibilityFlags,
|
|
61
|
+
assets: { htmlHandling: manifest.htmlHandling },
|
|
62
|
+
env,
|
|
63
|
+
exports,
|
|
64
|
+
...manifest.crons.length > 0 ? { triggers: manifest.crons.map((schedule) => ({
|
|
65
|
+
type: "scheduled",
|
|
66
|
+
schedule
|
|
67
|
+
})) } : {}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The bundler options for `defineWranglerConfig()`. `keepNames` is pinned on:
|
|
72
|
+
* queued jobs, events, notifications and durable agents are stored by class name.
|
|
73
|
+
*/
|
|
74
|
+
async function gurenWranglerBundle(options = {}) {
|
|
75
|
+
const manifest = await readWorkerManifest(options.outputDir);
|
|
76
|
+
return {
|
|
77
|
+
keepNames: true,
|
|
78
|
+
alias: manifest.alias,
|
|
79
|
+
define: manifest.define,
|
|
80
|
+
assetsDirectory: manifest.assetsDirectory
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** `cf` runs from the app root (it refuses a directory without the project's manifest), so paths resolve from the cwd. */
|
|
84
|
+
async function readWorkerManifest(outputDir = CF_OUTPUT_DIR) {
|
|
85
|
+
const path = resolve(process.cwd(), outputDir, WORKER_MANIFEST_FILE);
|
|
86
|
+
let text;
|
|
87
|
+
try {
|
|
88
|
+
text = await readFile(path, "utf8");
|
|
89
|
+
} catch {
|
|
90
|
+
throw new Error(`@guren/plugin-cloudflare/config: ${path} not found. Run \`bunx guren cloudflare:build\` first (\`bunx guren cloudflare:deploy\` runs it for you); it writes this manifest. A build given another outputDir needs the same outputDir here.`);
|
|
91
|
+
}
|
|
92
|
+
let manifest;
|
|
93
|
+
try {
|
|
94
|
+
manifest = JSON.parse(text);
|
|
95
|
+
} catch {
|
|
96
|
+
manifest = null;
|
|
97
|
+
}
|
|
98
|
+
if (manifest?.version !== 2) throw new Error(`@guren/plugin-cloudflare/config: ${path} is not a version 2 manifest (it reads ${manifest === null ? "as no JSON object" : `version ${String(manifest.version)}`}). Run \`bunx guren cloudflare:build\` again with the installed plugin.`);
|
|
99
|
+
return manifest;
|
|
100
|
+
}
|
|
101
|
+
//#endregion
|
|
102
|
+
export { defineCloudflareConfig, gurenWorker, gurenWranglerBundle };
|
package/dist/env.d.ts
CHANGED
|
@@ -9,6 +9,12 @@
|
|
|
9
9
|
* bundle. The root keeps re-exporting them for compatibility;
|
|
10
10
|
* `tests/lean-env-subpath.test.ts` holds the boundary.
|
|
11
11
|
*/
|
|
12
|
+
/**
|
|
13
|
+
* Where the captured env lives: a registry symbol on `globalThis`, so `@guren/orm`
|
|
14
|
+
* resolves `createD1Database({ binding: 'DB' })` without importing this package, and two
|
|
15
|
+
* installed copies of it share one env. `@guren/orm`'s d1.ts spells the same key.
|
|
16
|
+
*/
|
|
17
|
+
declare const WORKERS_ENV_SLOT: unique symbol;
|
|
12
18
|
/**
|
|
13
19
|
* First call wins; later calls are ignored (never overwrite a live env). Not the
|
|
14
20
|
* hard error RFC 0017 §6 asks for: under the Workers Vitest integration a Worker
|
|
@@ -23,13 +29,19 @@ declare function captureWorkersEnv(env: unknown): void;
|
|
|
23
29
|
* entrypoint booted first, which may be the Worker's rather than the object's.
|
|
24
30
|
*/
|
|
25
31
|
declare function getWorkersEnv<E = unknown>(): E;
|
|
32
|
+
/**
|
|
33
|
+
* The binding a driver was given by name, read when it is first used. `owner` prefixes the
|
|
34
|
+
* errors; `@guren/orm`'s `createD1Database` words its own the same way.
|
|
35
|
+
*/
|
|
36
|
+
declare function readWorkersBinding(name: string, owner: string): unknown;
|
|
26
37
|
/** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
|
|
27
38
|
declare function resetWorkersEnv(): void;
|
|
28
39
|
/**
|
|
29
|
-
* Whether this code
|
|
30
|
-
*
|
|
31
|
-
*
|
|
40
|
+
* Whether this code runs on workerd (its navigator user agent): the switch an app's
|
|
41
|
+
* `config/database.ts` takes to pick D1 and keep filesystem work out of the Worker.
|
|
42
|
+
* Also true in the Cloudflare build's introspection (RFC 0035 §2.1); both variables
|
|
43
|
+
* are required, so an exported target alone never changes `bun run dev`.
|
|
32
44
|
*/
|
|
33
45
|
declare function isWorkersRuntime(): boolean;
|
|
34
46
|
//#endregion
|
|
35
|
-
export { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv };
|
|
47
|
+
export { WORKERS_ENV_SLOT, captureWorkersEnv, getWorkersEnv, isWorkersRuntime, readWorkersBinding, resetWorkersEnv };
|
package/dist/env.js
CHANGED
|
@@ -9,7 +9,13 @@
|
|
|
9
9
|
* bundle. The root keeps re-exporting them for compatibility;
|
|
10
10
|
* `tests/lean-env-subpath.test.ts` holds the boundary.
|
|
11
11
|
*/
|
|
12
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Where the captured env lives: a registry symbol on `globalThis`, so `@guren/orm`
|
|
14
|
+
* resolves `createD1Database({ binding: 'DB' })` without importing this package, and two
|
|
15
|
+
* installed copies of it share one env. `@guren/orm`'s d1.ts spells the same key.
|
|
16
|
+
*/
|
|
17
|
+
const WORKERS_ENV_SLOT = Symbol.for("guren.workersEnv");
|
|
18
|
+
const slots = globalThis;
|
|
13
19
|
/**
|
|
14
20
|
* First call wins; later calls are ignored (never overwrite a live env). Not the
|
|
15
21
|
* hard error RFC 0017 §6 asks for: under the Workers Vitest integration a Worker
|
|
@@ -18,7 +24,7 @@ let holder;
|
|
|
18
24
|
* latch in `boot.ts` is what keeps one isolate on one application.
|
|
19
25
|
*/
|
|
20
26
|
function captureWorkersEnv(env) {
|
|
21
|
-
|
|
27
|
+
slots[WORKERS_ENV_SLOT] ??= { env };
|
|
22
28
|
}
|
|
23
29
|
/**
|
|
24
30
|
* Throws with a clear message if called before the first request captured env.
|
|
@@ -26,20 +32,34 @@ function captureWorkersEnv(env) {
|
|
|
26
32
|
* entrypoint booted first, which may be the Worker's rather than the object's.
|
|
27
33
|
*/
|
|
28
34
|
function getWorkersEnv() {
|
|
35
|
+
const holder = slots[WORKERS_ENV_SLOT];
|
|
29
36
|
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");
|
|
30
37
|
return holder.env;
|
|
31
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* The binding a driver was given by name, read when it is first used. `owner` prefixes the
|
|
41
|
+
* errors; `@guren/orm`'s `createD1Database` words its own the same way.
|
|
42
|
+
*/
|
|
43
|
+
function readWorkersBinding(name, owner) {
|
|
44
|
+
const holder = slots[WORKERS_ENV_SLOT];
|
|
45
|
+
if (!holder) throw new Error(`${owner}: the "${name}" binding was read before the first request captured the Workers env. Use it inside a request.`);
|
|
46
|
+
const value = holder.env?.[name];
|
|
47
|
+
if (value == null) throw new Error(`${owner}: the Workers env has no "${name}" binding. Check wrangler.jsonc, or the binding in cloudflare.config.ts.`);
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
32
50
|
/** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
|
|
33
51
|
function resetWorkersEnv() {
|
|
34
|
-
|
|
52
|
+
slots[WORKERS_ENV_SLOT] = void 0;
|
|
35
53
|
}
|
|
36
54
|
/**
|
|
37
|
-
* Whether this code
|
|
38
|
-
*
|
|
39
|
-
*
|
|
55
|
+
* Whether this code runs on workerd (its navigator user agent): the switch an app's
|
|
56
|
+
* `config/database.ts` takes to pick D1 and keep filesystem work out of the Worker.
|
|
57
|
+
* Also true in the Cloudflare build's introspection (RFC 0035 §2.1); both variables
|
|
58
|
+
* are required, so an exported target alone never changes `bun run dev`.
|
|
40
59
|
*/
|
|
41
60
|
function isWorkersRuntime() {
|
|
42
|
-
|
|
61
|
+
if (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") return true;
|
|
62
|
+
return typeof process !== "undefined" && process.env?.GUREN_INTROSPECT === "1" && process.env?.GUREN_INTROSPECT_TARGET === "cloudflare";
|
|
43
63
|
}
|
|
44
64
|
//#endregion
|
|
45
|
-
export { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv };
|
|
65
|
+
export { WORKERS_ENV_SLOT, captureWorkersEnv, getWorkersEnv, isWorkersRuntime, readWorkersBinding, resetWorkersEnv };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv } from "./env.js";
|
|
2
2
|
import { FileMetadata, GetStreamOptions, PutOptions, ServiceProviderConstructor, StorageDriver, StorageDriverCapabilities, TemporaryUrlOptions } from "@guren/core";
|
|
3
3
|
import { PathLike } from "@guren/core/internal/deploy-build";
|
|
4
|
+
import "@guren/core/internal/deploy-check";
|
|
4
5
|
//#region src/boot.d.ts
|
|
5
6
|
interface WorkersExecutionContext {
|
|
6
7
|
waitUntil(promise: Promise<unknown>): void;
|
|
@@ -157,12 +158,15 @@ interface BuildCloudflareOutputOptions {
|
|
|
157
158
|
* leaves the endpoint outside the OAuth boundary silently.
|
|
158
159
|
*/
|
|
159
160
|
mcpPath?: string;
|
|
161
|
+
/** Send the app build's own output to stderr, so stdout carries only a caller's JSON. */
|
|
162
|
+
appBuildToStderr?: boolean;
|
|
160
163
|
}
|
|
161
164
|
/**
|
|
162
|
-
* Assemble a deployable Cloudflare Workers directory
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
* `wrangler.jsonc` scaffold
|
|
165
|
+
* Assemble a deployable Cloudflare Workers directory from a built Guren app: a
|
|
166
|
+
* generated worker entry that statically wires the SSR bundle, and static assets
|
|
167
|
+
* for Workers Static Assets. On the Wrangler backend it goes to `.cloudflare/` with
|
|
168
|
+
* a one-time `wrangler.jsonc` scaffold; on the cf backend to `.guren/cloudflare/`
|
|
169
|
+
* with the `guren-worker.json` manifest `gurenWorker()` reads (RFC 0035 §3).
|
|
166
170
|
*/
|
|
167
171
|
declare function buildCloudflareOutput(options?: BuildCloudflareOutputOptions): Promise<void>;
|
|
168
172
|
/**
|
|
@@ -326,12 +330,11 @@ interface R2PresignOptions {
|
|
|
326
330
|
}
|
|
327
331
|
interface R2DriverOptions {
|
|
328
332
|
/**
|
|
329
|
-
*
|
|
330
|
-
* request
|
|
331
|
-
*
|
|
332
|
-
* `createD1Database({ binding })`.
|
|
333
|
+
* The R2 bucket binding: its name (`'MEDIA'`), read from the Workers env the first
|
|
334
|
+
* request captured, or a deferred closure such as `() => getWorkersEnv<Env>().MEDIA`.
|
|
335
|
+
* The same contract as `createD1Database({ binding })`.
|
|
333
336
|
*/
|
|
334
|
-
binding: () => unknown;
|
|
337
|
+
binding: string | (() => unknown);
|
|
335
338
|
/**
|
|
336
339
|
* Base URL for `url()`: the bucket's custom domain (recommended) or its r2.dev
|
|
337
340
|
* subdomain. R2 has no derivable default, so `url()` throws when this is unset.
|
|
@@ -414,6 +417,16 @@ declare class R2Driver implements StorageDriver {
|
|
|
414
417
|
/** The key prefix (for tests and diagnostics). */
|
|
415
418
|
getPrefix(): string;
|
|
416
419
|
}
|
|
420
|
+
/**
|
|
421
|
+
* The arguments `StorageManager.registerDisk()` takes for an R2 disk: its factory, and the
|
|
422
|
+
* description introspection reports without building it (RFC 0035 §2.1). One options object
|
|
423
|
+
* feeds both, so the binding the deploy sees is the one the driver reads.
|
|
424
|
+
* @example storage.registerDisk('media', ...r2Disk({ binding: 'MEDIA', publicUrl }))
|
|
425
|
+
*/
|
|
426
|
+
declare function r2Disk(options: R2DriverOptions): [() => R2Driver, {
|
|
427
|
+
driver: 'r2';
|
|
428
|
+
binding?: string;
|
|
429
|
+
}];
|
|
417
430
|
//#endregion
|
|
418
431
|
//#region src/index.d.ts
|
|
419
432
|
/**
|
|
@@ -424,4 +437,4 @@ interface CloudflarePluginConfig {}
|
|
|
424
437
|
/** Register the Cloudflare plugin: `createApp({ providers: [cloudflarePlugin()] })`. */
|
|
425
438
|
declare function cloudflarePlugin(config?: CloudflarePluginConfig): ServiceProviderConstructor;
|
|
426
439
|
//#endregion
|
|
427
|
-
export { type BuildCloudflareOutputOptions, type BundleAttribution, type BundleReport, type BundleSize, CloudflarePluginConfig, type EsbuildMetafile, OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, type OAuthPurgeOptions, type OAuthPurgeResult, type OAuthPurgerLike, type OAuthSweepEnv, type OAuthSweepKvLike, type R2BucketLike, R2Driver, type R2DriverOptions, type R2PresignOptions, type ReportBundleSizeOptions, WORKER_SIZE_LIMIT, WORKER_SIZE_WARN_SHARE, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, type WorkersScheduledEvent, attributeBundle, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, parseWranglerSize, printBundleReport, renderBundleReport, reportBundleSize, resetWorkersEnv, sweepOAuthStorage };
|
|
440
|
+
export { type BuildCloudflareOutputOptions, type BundleAttribution, type BundleReport, type BundleSize, CloudflarePluginConfig, type EsbuildMetafile, OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, type OAuthPurgeOptions, type OAuthPurgeResult, type OAuthPurgerLike, type OAuthSweepEnv, type OAuthSweepKvLike, type R2BucketLike, R2Driver, type R2DriverOptions, type R2PresignOptions, type ReportBundleSizeOptions, WORKER_SIZE_LIMIT, WORKER_SIZE_WARN_SHARE, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, type WorkersScheduledEvent, attributeBundle, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, parseWranglerSize, printBundleReport, r2Disk, renderBundleReport, reportBundleSize, resetWorkersEnv, sweepOAuthStorage };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv } from "./env.js";
|
|
2
|
-
import {
|
|
1
|
+
import { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, readWorkersBinding, resetWorkersEnv } from "./env.js";
|
|
2
|
+
import { _ as flattenD1Migrations, a as parseWranglerSize, c as reportBundleSize, i as attributeBundle, n as WORKER_SIZE_WARN_SHARE, o as printBundleReport, p as buildCloudflareOutput, s as renderBundleReport, t as WORKER_SIZE_LIMIT } from "./bundle-size-CcXTKLKq.js";
|
|
3
3
|
import { definePlugin } from "@guren/core";
|
|
4
4
|
//#region src/boot.ts
|
|
5
5
|
const latches = /* @__PURE__ */ new WeakMap();
|
|
@@ -237,7 +237,9 @@ var R2Driver = class {
|
|
|
237
237
|
diskVisibility;
|
|
238
238
|
presign;
|
|
239
239
|
constructor(options) {
|
|
240
|
-
|
|
240
|
+
const { binding } = options;
|
|
241
|
+
if (binding === "") throw new Error("R2Driver: `binding` names no binding; pass its name, such as 'MEDIA'.");
|
|
242
|
+
this.resolveBinding = typeof binding === "string" ? () => readWorkersBinding(binding, "R2Driver") : binding;
|
|
241
243
|
this.publicUrl = options.publicUrl ? trimTrailingSlashes(options.publicUrl) : void 0;
|
|
242
244
|
this.prefix = trimSlashes(options.prefix ?? "");
|
|
243
245
|
this.diskVisibility = options.visibility ?? (options.publicUrl ? "public" : "private");
|
|
@@ -339,8 +341,13 @@ var R2Driver = class {
|
|
|
339
341
|
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.");
|
|
340
342
|
const expiresIn = Math.floor((expiration.getTime() - Date.now()) / 1e3);
|
|
341
343
|
if (expiresIn > MAX_PRESIGN_SECONDS) throw new Error(`R2Driver.temporaryUrl(): R2 presigned URLs may be valid for at most 7 days (requested ${expiresIn}s).`);
|
|
344
|
+
const bucketUrl = `https://${this.presign.accountId}.r2.cloudflarestorage.com/${this.presign.bucket}`;
|
|
345
|
+
const url = `${bucketUrl}/${encodeKey(this.key(path))}`;
|
|
346
|
+
const signedPath = new URL(url).pathname;
|
|
347
|
+
const rootPath = trimTrailingSlashes(new URL(`${bucketUrl}/${encodeKey(this.prefix)}`).pathname);
|
|
348
|
+
if (signedPath !== rootPath && !signedPath.startsWith(`${rootPath}/`)) throw new Error(`R2Driver.temporaryUrl(): path escapes the storage root: "${path}"`);
|
|
342
349
|
return presignGetUrl({
|
|
343
|
-
url
|
|
350
|
+
url,
|
|
344
351
|
accessKeyId: this.presign.accessKeyId,
|
|
345
352
|
secretAccessKey: this.presign.secretAccessKey,
|
|
346
353
|
region: "auto",
|
|
@@ -459,6 +466,19 @@ function trimSlashes(value) {
|
|
|
459
466
|
while (end > start && value[end - 1] === "/") end--;
|
|
460
467
|
return value.slice(start, end);
|
|
461
468
|
}
|
|
469
|
+
/**
|
|
470
|
+
* The arguments `StorageManager.registerDisk()` takes for an R2 disk: its factory, and the
|
|
471
|
+
* description introspection reports without building it (RFC 0035 §2.1). One options object
|
|
472
|
+
* feeds both, so the binding the deploy sees is the one the driver reads.
|
|
473
|
+
* @example storage.registerDisk('media', ...r2Disk({ binding: 'MEDIA', publicUrl }))
|
|
474
|
+
*/
|
|
475
|
+
function r2Disk(options) {
|
|
476
|
+
const binding = typeof options.binding === "string" ? options.binding : void 0;
|
|
477
|
+
return [() => new R2Driver(options), binding ? {
|
|
478
|
+
driver: "r2",
|
|
479
|
+
binding
|
|
480
|
+
} : { driver: "r2" }];
|
|
481
|
+
}
|
|
462
482
|
//#endregion
|
|
463
483
|
//#region src/index.ts
|
|
464
484
|
const factory = definePlugin({
|
|
@@ -471,4 +491,4 @@ function cloudflarePlugin(config = {}) {
|
|
|
471
491
|
return factory(config);
|
|
472
492
|
}
|
|
473
493
|
//#endregion
|
|
474
|
-
export { OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, R2Driver, WORKER_SIZE_LIMIT, WORKER_SIZE_WARN_SHARE, attributeBundle, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, parseWranglerSize, printBundleReport, renderBundleReport, reportBundleSize, resetWorkersEnv, sweepOAuthStorage };
|
|
494
|
+
export { OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, R2Driver, WORKER_SIZE_LIMIT, WORKER_SIZE_WARN_SHARE, attributeBundle, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, parseWranglerSize, printBundleReport, r2Disk, renderBundleReport, reportBundleSize, resetWorkersEnv, sweepOAuthStorage };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//#region src/worker-manifest.ts
|
|
2
|
+
/**
|
|
3
|
+
* The build manifest `cloudflare:build` writes for the `cf` backend (RFC 0035 §3):
|
|
4
|
+
* what `gurenWorker()` turns into `cloudflare.config.ts` bindings. It is written
|
|
5
|
+
* by the Bun build and read under Node by `cf`, so this module imports nothing.
|
|
6
|
+
* On the Wrangler backend it holds only `version` and `resolved`.
|
|
7
|
+
*/
|
|
8
|
+
/** The file name inside the output directory. */
|
|
9
|
+
const WORKER_MANIFEST_FILE = "guren-worker.json";
|
|
10
|
+
/** The `cf` backend's output directory, relative to the app root (RFC 0035 §3.3). */
|
|
11
|
+
const CF_OUTPUT_DIR = ".guren/cloudflare";
|
|
12
|
+
/** The Wrangler backend's, which the committed wrangler.jsonc points into. */
|
|
13
|
+
const WRANGLER_OUTPUT_DIR = ".cloudflare";
|
|
14
|
+
/** The output directory of each backend, which the build writes and the deploy reads. */
|
|
15
|
+
function outputDirFor(backend) {
|
|
16
|
+
return backend === "cf" ? CF_OUTPUT_DIR : WRANGLER_OUTPUT_DIR;
|
|
17
|
+
}
|
|
18
|
+
/** Inside the output directory: the flattened copy of `db/migrations`. */
|
|
19
|
+
const D1_MIGRATIONS_DIR = "d1-migrations";
|
|
20
|
+
/** The Wrangler backend's deploy config, rendered into its output directory with the resolved ids. */
|
|
21
|
+
const WRANGLER_DEPLOY_CONFIG_FILE = "wrangler.deploy.json";
|
|
22
|
+
/** The name `cf` and Wrangler provision a binding under: `<worker>-<binding>`, `_` as `-` (RFC 0035 §4). */
|
|
23
|
+
function autoProvisionedName(worker, binding) {
|
|
24
|
+
return `${worker}-${binding.toLowerCase().replaceAll("_", "-")}`;
|
|
25
|
+
}
|
|
26
|
+
/** A binding's resource name: one the config states, then `config/cloudflare.ts`'s, then the default. */
|
|
27
|
+
function resourceName(worker, binding, resourceNames, stated) {
|
|
28
|
+
return stated ?? resourceNames?.[binding] ?? autoProvisionedName(worker, binding);
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { WRANGLER_OUTPUT_DIR as a, WRANGLER_DEPLOY_CONFIG_FILE as i, D1_MIGRATIONS_DIR as n, outputDirFor as o, WORKER_MANIFEST_FILE as r, resourceName as s, CF_OUTPUT_DIR as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@guren/plugin-cloudflare",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.1",
|
|
4
4
|
"description": "Deploy a Guren application to Cloudflare Workers, with D1 as the database.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"guren",
|
|
@@ -32,8 +32,10 @@
|
|
|
32
32
|
"commands": {
|
|
33
33
|
"entry": "./dist/commands.js",
|
|
34
34
|
"names": [
|
|
35
|
+
"cloudflare:init",
|
|
35
36
|
"cloudflare:build",
|
|
36
|
-
"cloudflare:size"
|
|
37
|
+
"cloudflare:size",
|
|
38
|
+
"cloudflare:deploy"
|
|
37
39
|
]
|
|
38
40
|
}
|
|
39
41
|
},
|
|
@@ -51,6 +53,10 @@
|
|
|
51
53
|
"./env": {
|
|
52
54
|
"types": "./dist/env.d.ts",
|
|
53
55
|
"default": "./dist/env.js"
|
|
56
|
+
},
|
|
57
|
+
"./config": {
|
|
58
|
+
"types": "./dist/config.d.ts",
|
|
59
|
+
"default": "./dist/config.js"
|
|
54
60
|
}
|
|
55
61
|
},
|
|
56
62
|
"scripts": {
|
|
@@ -59,10 +65,11 @@
|
|
|
59
65
|
"typecheck": "tsc --noEmit"
|
|
60
66
|
},
|
|
61
67
|
"dependencies": {
|
|
62
|
-
"@guren/core": "^1.
|
|
68
|
+
"@guren/core": "^1.25.0",
|
|
63
69
|
"citty": "^0.1.6"
|
|
64
70
|
},
|
|
65
71
|
"devDependencies": {
|
|
72
|
+
"@cloudflare/config": "0.27.0",
|
|
66
73
|
"@cloudflare/workers-oauth-provider": "^0.10.3",
|
|
67
74
|
"@cloudflare/workers-types": "^4.20260702.1",
|
|
68
75
|
"@types/node": "^20.14.10",
|
|
@@ -39,6 +39,14 @@ import {
|
|
|
39
39
|
*/
|
|
40
40
|
const LOGIN_PATH = '/login'
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* The guard the consenting user is read from: the session guard `auth.useModel()`
|
|
44
|
+
* registers. Never an unqualified `this.auth.id()`, which answers with an API
|
|
45
|
+
* token's user for a request carrying `Authorization: Bearer`, and a grant minted
|
|
46
|
+
* for a token outlives revoking it. Change this if your session guard has another name.
|
|
47
|
+
*/
|
|
48
|
+
const SESSION_GUARD = 'web'
|
|
49
|
+
|
|
42
50
|
/**
|
|
43
51
|
* What a client that sent no `scope` is offered. RFC 6749 §3.3 requires a default
|
|
44
52
|
* or a refusal, and the MCP clients measured (Claude's connector, MCP Inspector)
|
|
@@ -55,7 +63,7 @@ interface WorkerEnvWithProvider {
|
|
|
55
63
|
export default class McpOAuthController extends Controller {
|
|
56
64
|
/** GET /oauth/authorize — render the consent screen. */
|
|
57
65
|
async show(): Promise<Response> {
|
|
58
|
-
const userId = await this.auth.id()
|
|
66
|
+
const userId = await this.auth.guard(SESSION_GUARD).id()
|
|
59
67
|
if (userId === null || userId === undefined) {
|
|
60
68
|
return this.redirect(this.loginUrl())
|
|
61
69
|
}
|
|
@@ -69,6 +77,8 @@ export default class McpOAuthController extends Controller {
|
|
|
69
77
|
|
|
70
78
|
return this.view(McpOAuthConsentPage, {
|
|
71
79
|
clientName: client?.clientName ?? parsed.clientId,
|
|
80
|
+
// From the request, never `client.redirectUris`: a client may register several.
|
|
81
|
+
redirectTarget: redirectTargetOf(parsed.redirectUri),
|
|
72
82
|
query: new URL(this.ctx.req.url).searchParams.toString(),
|
|
73
83
|
tools: this.offeredTools(parsed.scope),
|
|
74
84
|
csrfToken: getCsrfToken(this.ctx),
|
|
@@ -77,7 +87,7 @@ export default class McpOAuthController extends Controller {
|
|
|
77
87
|
|
|
78
88
|
/** POST /oauth/authorize — record the decision and hand back to the provider. */
|
|
79
89
|
async approve(): Promise<Response> {
|
|
80
|
-
const userId = await this.auth.id()
|
|
90
|
+
const userId = await this.auth.guard(SESSION_GUARD).id()
|
|
81
91
|
if (userId === null || userId === undefined) {
|
|
82
92
|
return this.redirect(this.loginUrl())
|
|
83
93
|
}
|
|
@@ -222,6 +232,21 @@ export default class McpOAuthController extends Controller {
|
|
|
222
232
|
}
|
|
223
233
|
}
|
|
224
234
|
|
|
235
|
+
/**
|
|
236
|
+
* The redirect URI as `protocol//host`, or the scheme alone if it has no host,
|
|
237
|
+
* read by the `new URL` parse `completeAuthorization` redirects with, so userinfo
|
|
238
|
+
* like `https://claude.ai@attacker.example` shows the host the code really goes to.
|
|
239
|
+
* One that will not parse is shown as it came; the page escapes it.
|
|
240
|
+
*/
|
|
241
|
+
function redirectTargetOf(redirectUri: string): string {
|
|
242
|
+
try {
|
|
243
|
+
const { protocol, host } = new URL(redirectUri)
|
|
244
|
+
return host ? `${protocol}//${host}` : protocol
|
|
245
|
+
} catch {
|
|
246
|
+
return redirectUri
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
225
250
|
/** One value from a parsed body field that may legally hold several. */
|
|
226
251
|
function single(value: unknown): string {
|
|
227
252
|
return typeof value === 'string' ? value : ''
|
|
@@ -26,6 +26,8 @@ export const QUERY_FIELD = 'authorize_query'
|
|
|
26
26
|
export interface McpOAuthConsentPageProps {
|
|
27
27
|
/** The client's own registered name, or its id when it registered none. */
|
|
28
28
|
clientName: string
|
|
29
|
+
/** Where approving sends the authorization code: this request's redirect URI, reduced to scheme and host. */
|
|
30
|
+
redirectTarget: string
|
|
29
31
|
/** The authorize request's query string, handed back on submit. */
|
|
30
32
|
query: string
|
|
31
33
|
/** The tools this request may grant — already intersected with what it asked for. */
|
|
@@ -44,6 +46,8 @@ const STYLES = `
|
|
|
44
46
|
.desc { display: block; margin: .25rem 0 0 1.75rem; opacity: .8; }
|
|
45
47
|
.badge { border: 1px solid currentColor; border-radius: .5rem; font-size: .75rem; margin-left: .5rem; padding: 0 .4rem; }
|
|
46
48
|
.empty { opacity: .8; }
|
|
49
|
+
.target { border: 1px solid rgba(128,128,128,.35); border-radius: .5rem; margin: 1rem 0; padding: .75rem; }
|
|
50
|
+
.host { display: block; font-family: ui-monospace, monospace; font-weight: 600; overflow-wrap: anywhere; }
|
|
47
51
|
code { font-family: ui-monospace, monospace; font-size: .9em; }
|
|
48
52
|
button { font: inherit; padding: .5rem 1rem; }
|
|
49
53
|
`
|
|
@@ -94,8 +98,15 @@ const NothingToGrant: FC = () => (
|
|
|
94
98
|
</>
|
|
95
99
|
)
|
|
96
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Registration at `/oauth/register` is open, so the name is whatever the caller
|
|
103
|
+
* chose and the redirect target is the only part of this page it cannot fake. The
|
|
104
|
+
* target stays text, never an `href`. An app that creates its own clients with
|
|
105
|
+
* `createClient()` and closes registration removes the label and its sentence by hand.
|
|
106
|
+
*/
|
|
97
107
|
export const McpOAuthConsentPage: FC<McpOAuthConsentPageProps> = ({
|
|
98
108
|
clientName,
|
|
109
|
+
redirectTarget,
|
|
99
110
|
query,
|
|
100
111
|
tools,
|
|
101
112
|
csrfToken,
|
|
@@ -109,8 +120,17 @@ export const McpOAuthConsentPage: FC<McpOAuthConsentPageProps> = ({
|
|
|
109
120
|
</head>
|
|
110
121
|
<body>
|
|
111
122
|
<h1>
|
|
112
|
-
<strong>{clientName}</strong>
|
|
123
|
+
A client calling itself <strong>{clientName}</strong>{' '}
|
|
124
|
+
<span class="badge">unverified</span> is asking to use this application's tools
|
|
113
125
|
</h1>
|
|
126
|
+
<p>
|
|
127
|
+
This application has not verified that name, and anyone can register a client under any
|
|
128
|
+
name. Go by where the access goes, not by what the client calls itself.
|
|
129
|
+
</p>
|
|
130
|
+
<p class="target">
|
|
131
|
+
Approving hands access to whoever controls{' '}
|
|
132
|
+
<span class="host">{redirectTarget}</span>
|
|
133
|
+
</p>
|
|
114
134
|
<p>
|
|
115
135
|
Approving lets it act as you, through the tools you select. Uncheck anything you would
|
|
116
136
|
rather it could not do.
|