@kubohiroya/turbowarp-cloudflare-worker 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +373 -0
- package/README.ja.md +105 -0
- package/README.md +51 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +126 -0
- package/dist/cli.js.map +1 -0
- package/dist/extension-manifest.json +149 -0
- package/dist/generator.d.ts +2 -0
- package/dist/generator.js +776 -0
- package/dist/generator.js.map +1 -0
- package/dist/ir.d.ts +50 -0
- package/dist/ir.js +168 -0
- package/dist/ir.js.map +1 -0
- package/dist/jwt.d.ts +23 -0
- package/dist/jwt.js +81 -0
- package/dist/jwt.js.map +1 -0
- package/dist/turbowarp-cloudflare-worker.js +1218 -0
- package/docs/architecture.ja.md +97 -0
- package/docs/architecture.md +7 -0
- package/docs/auth-blocks.ja.md +154 -0
- package/docs/index.html +31 -0
- package/package.json +80 -0
- package/schemas/extension-manifest.schema.json +49 -0
- package/src/block-definitions.json +115 -0
- package/src/cli.ts +146 -0
- package/src/config.ts +12 -0
- package/src/extension-manifest.ts +159 -0
- package/src/extension.ts +197 -0
- package/src/generator.ts +828 -0
- package/src/globals.d.ts +25 -0
- package/src/index.ts +8 -0
- package/src/ir.ts +246 -0
- package/src/jwt.ts +144 -0
|
@@ -0,0 +1,1218 @@
|
|
|
1
|
+
// Name: TurboWarp Cloudflare Worker
|
|
2
|
+
// ID: kubohiroyacloudflareworker
|
|
3
|
+
// Description: Cloudflare Workers generation blocks for turbowarp-http-server.
|
|
4
|
+
// By: Hiroya Kubo
|
|
5
|
+
// License: MPL-2.0
|
|
6
|
+
|
|
7
|
+
(function (Scratch) {
|
|
8
|
+
'use strict';
|
|
9
|
+
|
|
10
|
+
//#region src/config.ts
|
|
11
|
+
var extensionConfig = {
|
|
12
|
+
id: "kubohiroyacloudflareworker",
|
|
13
|
+
slug: "turbowarp-cloudflare-worker",
|
|
14
|
+
name: "TurboWarp Cloudflare Worker",
|
|
15
|
+
description: "Cloudflare Workers generation blocks for turbowarp-http-server.",
|
|
16
|
+
author: "Hiroya Kubo",
|
|
17
|
+
license: "MPL-2.0",
|
|
18
|
+
unsandboxed: false,
|
|
19
|
+
docsURI: "https://kubohiroya.github.io/turbowarp-cloudflare-worker/",
|
|
20
|
+
blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNCIgeT0iOCIgd2lkdGg9IjE4IiBoZWlnaHQ9IjE0IiByeD0iMyIgZmlsbD0iIzRDOTdGRiIvPjxyZWN0IHg9IjI2IiB5PSI4IiB3aWR0aD0iMTgiIGhlaWdodD0iMTQiIHJ4PSIzIiBmaWxsPSIjNTlDMDU5Ii8+PHJlY3QgeD0iMTUiIHk9IjI2IiB3aWR0aD0iMTgiIGhlaWdodD0iMTQiIHJ4PSIzIiBmaWxsPSIjRkZBQjE5Ii8+PC9zdmc+"
|
|
21
|
+
};
|
|
22
|
+
var block_definitions_default = {
|
|
23
|
+
extensionName: "TurboWarp HTTP Server Cloudflare",
|
|
24
|
+
blocks: [
|
|
25
|
+
{
|
|
26
|
+
"opcode": "createHandlerIr",
|
|
27
|
+
"category": "core",
|
|
28
|
+
"blockType": "REPORTER",
|
|
29
|
+
"text": "Cloudflare handler [METHOD] [PATH] returns [BODY]",
|
|
30
|
+
"description": "Creates a minimal HTTP handler IR JSON entry for the Cloudflare generator.",
|
|
31
|
+
"arguments": {
|
|
32
|
+
"METHOD": {
|
|
33
|
+
"type": "STRING",
|
|
34
|
+
"defaultValue": "GET"
|
|
35
|
+
},
|
|
36
|
+
"PATH": {
|
|
37
|
+
"type": "STRING",
|
|
38
|
+
"defaultValue": "/hello"
|
|
39
|
+
},
|
|
40
|
+
"BODY": {
|
|
41
|
+
"type": "STRING",
|
|
42
|
+
"defaultValue": "Hello from TurboWarp"
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
"opcode": "createWorkerIr",
|
|
48
|
+
"category": "core",
|
|
49
|
+
"blockType": "REPORTER",
|
|
50
|
+
"text": "Cloudflare Worker [NAME] with handlers JSON [HANDLERS]",
|
|
51
|
+
"description": "Creates a deployable Worker IR JSON document from handler entries.",
|
|
52
|
+
"arguments": {
|
|
53
|
+
"NAME": {
|
|
54
|
+
"type": "STRING",
|
|
55
|
+
"defaultValue": "tw-http-app"
|
|
56
|
+
},
|
|
57
|
+
"HANDLERS": {
|
|
58
|
+
"type": "STRING",
|
|
59
|
+
"defaultValue": "[]"
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
"opcode": "generateFilesJson",
|
|
65
|
+
"category": "core",
|
|
66
|
+
"blockType": "REPORTER",
|
|
67
|
+
"text": "generated Cloudflare files JSON from IR [IR]",
|
|
68
|
+
"description": "Runs the Cloudflare Workers/Hono generator and returns GeneratedFile[] as JSON.",
|
|
69
|
+
"arguments": { "IR": {
|
|
70
|
+
"type": "STRING",
|
|
71
|
+
"defaultValue": "{\"name\":\"tw-http-app\",\"handlers\":[]}"
|
|
72
|
+
} }
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
"kind": "separator",
|
|
76
|
+
"category": "auth"
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
"opcode": "createProtectedRouteIr",
|
|
80
|
+
"category": "auth",
|
|
81
|
+
"blockType": "REPORTER",
|
|
82
|
+
"text": "protected route [METHOD] [PATH] when unauthenticated [ON_UNAUTHENTICATED]",
|
|
83
|
+
"description": "Creates an auth guard IR entry for a route protected by external OAuth/OIDC.",
|
|
84
|
+
"arguments": {
|
|
85
|
+
"METHOD": {
|
|
86
|
+
"type": "STRING",
|
|
87
|
+
"defaultValue": "GET"
|
|
88
|
+
},
|
|
89
|
+
"PATH": {
|
|
90
|
+
"type": "STRING",
|
|
91
|
+
"defaultValue": "/private"
|
|
92
|
+
},
|
|
93
|
+
"ON_UNAUTHENTICATED": {
|
|
94
|
+
"type": "STRING",
|
|
95
|
+
"defaultValue": "redirect-login"
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
"opcode": "createAuthIr",
|
|
101
|
+
"category": "auth",
|
|
102
|
+
"blockType": "REPORTER",
|
|
103
|
+
"text": "external OAuth/OIDC auth providers [PROVIDERS] protected routes JSON [PROTECTED_ROUTES]",
|
|
104
|
+
"description": "Creates auth IR for Google, Microsoft, and GitHub account sign-in.",
|
|
105
|
+
"arguments": {
|
|
106
|
+
"PROVIDERS": {
|
|
107
|
+
"type": "STRING",
|
|
108
|
+
"defaultValue": "google,github"
|
|
109
|
+
},
|
|
110
|
+
"PROTECTED_ROUTES": {
|
|
111
|
+
"type": "STRING",
|
|
112
|
+
"defaultValue": "[]"
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
"opcode": "createBearerRouteIr",
|
|
118
|
+
"category": "auth",
|
|
119
|
+
"blockType": "REPORTER",
|
|
120
|
+
"text": "API route [METHOD] [PATH] requires bearer token",
|
|
121
|
+
"description": "Creates a protected route IR entry that requires a valid self-issued ES256 bearer JWT.",
|
|
122
|
+
"arguments": {
|
|
123
|
+
"METHOD": {
|
|
124
|
+
"type": "STRING",
|
|
125
|
+
"defaultValue": "GET"
|
|
126
|
+
},
|
|
127
|
+
"PATH": {
|
|
128
|
+
"type": "STRING",
|
|
129
|
+
"defaultValue": "/api/items"
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
"opcode": "createBearerRoleRouteIr",
|
|
135
|
+
"category": "auth",
|
|
136
|
+
"blockType": "REPORTER",
|
|
137
|
+
"text": "API route [METHOD] [PATH] requires bearer role [ROLE]",
|
|
138
|
+
"description": "Creates a bearer JWT protected route IR entry that also requires a role claim.",
|
|
139
|
+
"arguments": {
|
|
140
|
+
"METHOD": {
|
|
141
|
+
"type": "STRING",
|
|
142
|
+
"defaultValue": "POST"
|
|
143
|
+
},
|
|
144
|
+
"PATH": {
|
|
145
|
+
"type": "STRING",
|
|
146
|
+
"defaultValue": "/api/admin"
|
|
147
|
+
},
|
|
148
|
+
"ROLE": {
|
|
149
|
+
"type": "STRING",
|
|
150
|
+
"defaultValue": "admin"
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
"opcode": "createBearerScopeRouteIr",
|
|
156
|
+
"category": "auth",
|
|
157
|
+
"blockType": "REPORTER",
|
|
158
|
+
"text": "API route [METHOD] [PATH] requires bearer scope [SCOPE]",
|
|
159
|
+
"description": "Creates a bearer JWT protected route IR entry that also requires one or more scopes.",
|
|
160
|
+
"arguments": {
|
|
161
|
+
"METHOD": {
|
|
162
|
+
"type": "STRING",
|
|
163
|
+
"defaultValue": "POST"
|
|
164
|
+
},
|
|
165
|
+
"PATH": {
|
|
166
|
+
"type": "STRING",
|
|
167
|
+
"defaultValue": "/api/posts"
|
|
168
|
+
},
|
|
169
|
+
"SCOPE": {
|
|
170
|
+
"type": "STRING",
|
|
171
|
+
"defaultValue": "posts:write"
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
"opcode": "createWorkerIrWithAuth",
|
|
177
|
+
"category": "auth",
|
|
178
|
+
"blockType": "REPORTER",
|
|
179
|
+
"text": "Cloudflare Worker [NAME] with handlers JSON [HANDLERS] and auth JSON [AUTH]",
|
|
180
|
+
"description": "Creates Worker IR with an external OAuth/OIDC auth policy.",
|
|
181
|
+
"arguments": {
|
|
182
|
+
"NAME": {
|
|
183
|
+
"type": "STRING",
|
|
184
|
+
"defaultValue": "tw-http-app"
|
|
185
|
+
},
|
|
186
|
+
"HANDLERS": {
|
|
187
|
+
"type": "STRING",
|
|
188
|
+
"defaultValue": "[]"
|
|
189
|
+
},
|
|
190
|
+
"AUTH": {
|
|
191
|
+
"type": "STRING",
|
|
192
|
+
"defaultValue": "{\"mode\":\"external-oauth-oidc\",\"providers\":[\"google\"],\"protectedRoutes\":[]}"
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
]
|
|
197
|
+
};
|
|
198
|
+
//#endregion
|
|
199
|
+
//#region src/ir.ts
|
|
200
|
+
function normalizeHttpMethod(value) {
|
|
201
|
+
const normalized = value.trim().toUpperCase();
|
|
202
|
+
if (isHttpMethod(normalized)) return normalized;
|
|
203
|
+
throw new TypeError(`Unsupported HTTP method: ${value}`);
|
|
204
|
+
}
|
|
205
|
+
function normalizeRoutePath(value) {
|
|
206
|
+
const trimmed = value.trim();
|
|
207
|
+
if (!trimmed.startsWith("/")) return `/${trimmed}`;
|
|
208
|
+
return trimmed || "/";
|
|
209
|
+
}
|
|
210
|
+
function parseWorkerIr(value) {
|
|
211
|
+
if (!isRecord(value)) throw new TypeError("Cloudflare Worker IR must be an object.");
|
|
212
|
+
const name = requireString(value.name, "IR name");
|
|
213
|
+
const handlers = Array.isArray(value.handlers) ? value.handlers.map((handler, index) => parseHandlerIr(handler, index)) : [];
|
|
214
|
+
const compatibilityDate = value.compatibilityDate === void 0 ? void 0 : requireString(value.compatibilityDate, "IR compatibilityDate");
|
|
215
|
+
const auth = value.auth === void 0 ? void 0 : parseAuthBindingIr(value.auth);
|
|
216
|
+
const storage = value.storage === void 0 ? void 0 : parseStorageBindings(value.storage);
|
|
217
|
+
return {
|
|
218
|
+
name,
|
|
219
|
+
handlers,
|
|
220
|
+
...compatibilityDate === void 0 ? {} : { compatibilityDate },
|
|
221
|
+
...auth === void 0 ? {} : { auth },
|
|
222
|
+
...storage === void 0 ? {} : { storage }
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function parseHandlerIr(value, index) {
|
|
226
|
+
if (!isRecord(value)) throw new TypeError(`Handler at index ${index} must be an object.`);
|
|
227
|
+
return {
|
|
228
|
+
method: normalizeHttpMethod(requireString(value.method, `Handler ${index} method`)),
|
|
229
|
+
path: normalizeRoutePath(requireString(value.path, `Handler ${index} path`)),
|
|
230
|
+
responseText: requireString(value.responseText, `Handler ${index} responseText`)
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
function parseAuthBindingIr(value) {
|
|
234
|
+
if (!isRecord(value)) throw new TypeError("IR auth must be an object.");
|
|
235
|
+
const mode = requireString(value.mode, "IR auth mode");
|
|
236
|
+
if (mode !== "external-oauth-oidc") throw new TypeError(`Unsupported auth mode: ${mode}`);
|
|
237
|
+
return {
|
|
238
|
+
mode,
|
|
239
|
+
providers: Array.isArray(value.providers) ? value.providers.map((provider) => requireAuthProvider(provider)) : [],
|
|
240
|
+
...value.session === void 0 ? {} : { session: requireAuthSessionMode(value.session) },
|
|
241
|
+
...value.loginPath === void 0 ? {} : { loginPath: normalizeRoutePath(requireString(value.loginPath, "IR auth loginPath")) },
|
|
242
|
+
...value.callbackPath === void 0 ? {} : { callbackPath: normalizeRoutePath(requireString(value.callbackPath, "IR auth callbackPath")) },
|
|
243
|
+
...value.logoutPath === void 0 ? {} : { logoutPath: normalizeRoutePath(requireString(value.logoutPath, "IR auth logoutPath")) },
|
|
244
|
+
...value.mePath === void 0 ? {} : { mePath: normalizeRoutePath(requireString(value.mePath, "IR auth mePath")) },
|
|
245
|
+
...value.protectedRoutes === void 0 ? {} : { protectedRoutes: parseProtectedRoutes(value.protectedRoutes) },
|
|
246
|
+
...value.jwtIssuerEnv === void 0 ? {} : { jwtIssuerEnv: requireString(value.jwtIssuerEnv, "IR auth jwtIssuerEnv") },
|
|
247
|
+
...value.jwtAudienceEnv === void 0 ? {} : { jwtAudienceEnv: requireString(value.jwtAudienceEnv, "IR auth jwtAudienceEnv") }
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function parseProtectedRoutes(value) {
|
|
251
|
+
if (!Array.isArray(value)) throw new TypeError("IR auth protectedRoutes must be an array.");
|
|
252
|
+
return value.map((route, index) => {
|
|
253
|
+
if (!isRecord(route)) throw new TypeError(`Protected route at index ${index} must be an object.`);
|
|
254
|
+
return {
|
|
255
|
+
method: route.method === "*" ? "*" : normalizeHttpMethod(requireString(route.method, `Protected route ${index} method`)),
|
|
256
|
+
path: normalizeRoutePath(requireString(route.path, `Protected route ${index} path`)),
|
|
257
|
+
onUnauthenticated: requireUnauthenticatedAction(route.onUnauthenticated, `Protected route ${index} onUnauthenticated`),
|
|
258
|
+
...route.auth === void 0 ? {} : { auth: requireProtectedRouteAuth(route.auth, `Protected route ${index} auth`) },
|
|
259
|
+
...route.requiredRole === void 0 ? {} : { requiredRole: requireString(route.requiredRole, `Protected route ${index} requiredRole`) },
|
|
260
|
+
...route.requiredScopes === void 0 ? {} : { requiredScopes: parseStringArray(route.requiredScopes, `Protected route ${index} requiredScopes`) }
|
|
261
|
+
};
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
function parseStorageBindings(value) {
|
|
265
|
+
if (!Array.isArray(value)) throw new TypeError("IR storage must be an array.");
|
|
266
|
+
return value.map((binding, index) => {
|
|
267
|
+
if (!isRecord(binding)) throw new TypeError(`Storage binding at index ${index} must be an object.`);
|
|
268
|
+
return {
|
|
269
|
+
kind: requireStorageKind(binding.kind),
|
|
270
|
+
binding: requireString(binding.binding, `Storage binding ${index} binding`),
|
|
271
|
+
name: requireString(binding.name, `Storage binding ${index} name`)
|
|
272
|
+
};
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
function isHttpMethod(value) {
|
|
276
|
+
return [
|
|
277
|
+
"GET",
|
|
278
|
+
"POST",
|
|
279
|
+
"PUT",
|
|
280
|
+
"PATCH",
|
|
281
|
+
"DELETE",
|
|
282
|
+
"OPTIONS",
|
|
283
|
+
"HEAD"
|
|
284
|
+
].includes(value);
|
|
285
|
+
}
|
|
286
|
+
function requireAuthProvider(value) {
|
|
287
|
+
if (value === "google" || value === "microsoft" || value === "github") return value;
|
|
288
|
+
throw new TypeError(`Unsupported auth provider: ${String(value)}`);
|
|
289
|
+
}
|
|
290
|
+
function requireAuthSessionMode(value) {
|
|
291
|
+
if (value === "signed-cookie" || value === "bearer-jwt" || value === "cloudflare-access") return value;
|
|
292
|
+
throw new TypeError(`Unsupported auth session mode: ${String(value)}`);
|
|
293
|
+
}
|
|
294
|
+
function requireUnauthenticatedAction(value, label) {
|
|
295
|
+
if (value === "redirect-login" || value === "json-401" || value === "forbid-403") return value;
|
|
296
|
+
throw new TypeError(`${label} must be redirect-login, json-401, or forbid-403.`);
|
|
297
|
+
}
|
|
298
|
+
function requireProtectedRouteAuth(value, label) {
|
|
299
|
+
if (value === "session" || value === "bearer-jwt") return value;
|
|
300
|
+
throw new TypeError(`${label} must be session or bearer-jwt.`);
|
|
301
|
+
}
|
|
302
|
+
function parseStringArray(value, label) {
|
|
303
|
+
if (!Array.isArray(value)) throw new TypeError(`${label} must be an array.`);
|
|
304
|
+
return value.map((item, index) => requireString(item, `${label}[${index}]`));
|
|
305
|
+
}
|
|
306
|
+
function requireStorageKind(value) {
|
|
307
|
+
if (value === "d1" || value === "kv" || value === "r2" || value === "durable-object") return value;
|
|
308
|
+
throw new TypeError(`Unsupported storage kind: ${String(value)}`);
|
|
309
|
+
}
|
|
310
|
+
function requireString(value, label) {
|
|
311
|
+
if (typeof value !== "string" || value.length === 0) throw new TypeError(`${label} must be a non-empty string.`);
|
|
312
|
+
return value;
|
|
313
|
+
}
|
|
314
|
+
function isRecord(value) {
|
|
315
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/generator.ts
|
|
319
|
+
var DEFAULT_COMPATIBILITY_DATE = "2026-08-27";
|
|
320
|
+
function generateCloudflareWorkerFiles(input) {
|
|
321
|
+
const ir = parseWorkerIr(input);
|
|
322
|
+
return [
|
|
323
|
+
{
|
|
324
|
+
path: "package.json",
|
|
325
|
+
contents: `${JSON.stringify(createPackageJson(ir.name), null, 2)}\n`
|
|
326
|
+
},
|
|
327
|
+
{
|
|
328
|
+
path: "wrangler.jsonc",
|
|
329
|
+
contents: createWranglerJsonc(ir)
|
|
330
|
+
},
|
|
331
|
+
{
|
|
332
|
+
path: "tsconfig.json",
|
|
333
|
+
contents: createTsconfigJson()
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
path: "src/index.ts",
|
|
337
|
+
contents: createWorkerSource(ir)
|
|
338
|
+
}
|
|
339
|
+
];
|
|
340
|
+
}
|
|
341
|
+
function createTsconfigJson() {
|
|
342
|
+
return `${JSON.stringify({
|
|
343
|
+
compilerOptions: {
|
|
344
|
+
target: "ES2022",
|
|
345
|
+
module: "ESNext",
|
|
346
|
+
moduleResolution: "Bundler",
|
|
347
|
+
strict: true,
|
|
348
|
+
lib: ["ES2022"],
|
|
349
|
+
types: ["@cloudflare/workers-types"]
|
|
350
|
+
},
|
|
351
|
+
include: ["src/**/*.ts"]
|
|
352
|
+
}, null, 2)}\n`;
|
|
353
|
+
}
|
|
354
|
+
function createPackageJson(name) {
|
|
355
|
+
return {
|
|
356
|
+
name,
|
|
357
|
+
version: "0.1.0",
|
|
358
|
+
private: true,
|
|
359
|
+
type: "module",
|
|
360
|
+
scripts: {
|
|
361
|
+
dev: "wrangler dev",
|
|
362
|
+
deploy: "wrangler deploy",
|
|
363
|
+
typecheck: "tsc --noEmit"
|
|
364
|
+
},
|
|
365
|
+
dependencies: { hono: "^4.10.7" },
|
|
366
|
+
devDependencies: {
|
|
367
|
+
"@cloudflare/workers-types": "^5.20260826.1",
|
|
368
|
+
typescript: "^5.9.3",
|
|
369
|
+
wrangler: "^4.0.0"
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
function createWranglerJsonc(ir) {
|
|
374
|
+
const lines = [
|
|
375
|
+
"{",
|
|
376
|
+
` "name": ${JSON.stringify(ir.name)},`,
|
|
377
|
+
" \"main\": \"src/index.ts\",",
|
|
378
|
+
` "compatibility_date": ${JSON.stringify(ir.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE)}`
|
|
379
|
+
];
|
|
380
|
+
const d1 = storageOfKind(ir.storage, "d1");
|
|
381
|
+
const kv = storageOfKind(ir.storage, "kv");
|
|
382
|
+
const r2 = storageOfKind(ir.storage, "r2");
|
|
383
|
+
const durableObjects = storageOfKind(ir.storage, "durable-object");
|
|
384
|
+
if (d1.length > 0) {
|
|
385
|
+
lines.push(",", " \"d1_databases\": [");
|
|
386
|
+
lines.push(...d1.map((binding, index) => [
|
|
387
|
+
" {",
|
|
388
|
+
` "binding": ${JSON.stringify(binding.binding)},`,
|
|
389
|
+
` "database_name": ${JSON.stringify(binding.name)},`,
|
|
390
|
+
` "database_id": "REPLACE_WITH_${binding.binding}_DATABASE_ID"`,
|
|
391
|
+
` }${index === d1.length - 1 ? "" : ","}`
|
|
392
|
+
].join("\n")));
|
|
393
|
+
lines.push(" ]");
|
|
394
|
+
}
|
|
395
|
+
if (kv.length > 0) {
|
|
396
|
+
lines.push(",", " \"kv_namespaces\": [");
|
|
397
|
+
lines.push(...kv.map((binding, index) => [
|
|
398
|
+
" {",
|
|
399
|
+
` "binding": ${JSON.stringify(binding.binding)},`,
|
|
400
|
+
` "id": "REPLACE_WITH_${binding.binding}_NAMESPACE_ID"`,
|
|
401
|
+
` }${index === kv.length - 1 ? "" : ","}`
|
|
402
|
+
].join("\n")));
|
|
403
|
+
lines.push(" ]");
|
|
404
|
+
}
|
|
405
|
+
if (r2.length > 0) {
|
|
406
|
+
lines.push(",", " \"r2_buckets\": [");
|
|
407
|
+
lines.push(...r2.map((binding, index) => [
|
|
408
|
+
" {",
|
|
409
|
+
` "binding": ${JSON.stringify(binding.binding)},`,
|
|
410
|
+
` "bucket_name": ${JSON.stringify(binding.name)}`,
|
|
411
|
+
` }${index === r2.length - 1 ? "" : ","}`
|
|
412
|
+
].join("\n")));
|
|
413
|
+
lines.push(" ]");
|
|
414
|
+
}
|
|
415
|
+
if (durableObjects.length > 0) {
|
|
416
|
+
lines.push(",", " \"durable_objects\": {");
|
|
417
|
+
lines.push(" \"bindings\": [");
|
|
418
|
+
lines.push(...durableObjects.map((binding, index) => [
|
|
419
|
+
" {",
|
|
420
|
+
` "name": ${JSON.stringify(binding.binding)},`,
|
|
421
|
+
` "class_name": ${JSON.stringify(binding.name)}`,
|
|
422
|
+
` }${index === durableObjects.length - 1 ? "" : ","}`
|
|
423
|
+
].join("\n")));
|
|
424
|
+
lines.push(" ]", " }");
|
|
425
|
+
}
|
|
426
|
+
lines.push("}", "");
|
|
427
|
+
return lines.join("\n");
|
|
428
|
+
}
|
|
429
|
+
function createWorkerSource(ir) {
|
|
430
|
+
const routeLines = ir.handlers.length === 0 ? ["app.get('/', (c) => c.text('Generated by turbowarp-cloudflare-worker.'));"] : ir.handlers.map((handler) => `app.${handler.method.toLowerCase()}(${JSON.stringify(handler.path)}, (c) => c.text(${JSON.stringify(handler.responseText)}));`);
|
|
431
|
+
return [
|
|
432
|
+
"import {Hono} from 'hono';",
|
|
433
|
+
"",
|
|
434
|
+
"type Env = {",
|
|
435
|
+
...createEnvLines(ir),
|
|
436
|
+
"};",
|
|
437
|
+
"",
|
|
438
|
+
"const app = new Hono<{Bindings: Env}>();",
|
|
439
|
+
"",
|
|
440
|
+
...createAuthLines(ir),
|
|
441
|
+
...routeLines,
|
|
442
|
+
"",
|
|
443
|
+
"export default app;",
|
|
444
|
+
""
|
|
445
|
+
].join("\n");
|
|
446
|
+
}
|
|
447
|
+
function createAuthLines(ir) {
|
|
448
|
+
if (!ir.auth) return ["// Add auth middleware here when the IR enables external OAuth/OIDC."];
|
|
449
|
+
const loginPath = ir.auth.loginPath ?? "/auth/login";
|
|
450
|
+
const callbackPath = ir.auth.callbackPath ?? "/auth/callback";
|
|
451
|
+
const logoutPath = ir.auth.logoutPath ?? "/auth/logout";
|
|
452
|
+
const mePath = ir.auth.mePath ?? "/auth/me";
|
|
453
|
+
const protectedRoutes = ir.auth.protectedRoutes ?? [];
|
|
454
|
+
const providerMap = createProviderMap(ir.auth.providers, callbackPath);
|
|
455
|
+
const loginProviderPath = `${loginPath}/:provider`;
|
|
456
|
+
const callbackProviderPath = `${callbackPath}/:provider`;
|
|
457
|
+
return [
|
|
458
|
+
"// Authentication is delegated to external OAuth/OIDC providers.",
|
|
459
|
+
`// MVP providers: ${ir.auth.providers.join(", ") || "none configured"}.`,
|
|
460
|
+
"// Secrets such as client IDs, client secrets, cookie keys, issuer, and audience must stay in Cloudflare secrets or environment variables.",
|
|
461
|
+
"// The generated flow covers authorization redirect, state verification, token exchange, and signed session cookies.",
|
|
462
|
+
"// Review provider scopes and profile mapping before production use.",
|
|
463
|
+
`const oauthProviders: Record<string, ProviderConfig> = ${JSON.stringify(providerMap, null, 2)};`,
|
|
464
|
+
`const authSession: {mode: AuthSessionMode} = {mode: ${JSON.stringify(ir.auth.session ?? "signed-cookie")}};`,
|
|
465
|
+
`const defaultBearerJwtIssuer = ${JSON.stringify(`https://${ir.name}.workers.dev`)};`,
|
|
466
|
+
`const defaultBearerJwtAudience = ${JSON.stringify(ir.name)};`,
|
|
467
|
+
`const protectedRoutes: readonly ProtectedRoute[] = ${JSON.stringify(protectedRoutes, null, 2)};`,
|
|
468
|
+
"",
|
|
469
|
+
`app.get(${JSON.stringify(loginPath)}, (c) => {`,
|
|
470
|
+
" const firstProvider = Object.keys(oauthProviders)[0];",
|
|
471
|
+
" if (!firstProvider) return c.text('No OAuth/OIDC provider configured.', 500);",
|
|
472
|
+
` return c.redirect(${JSON.stringify(loginPath)} + '/' + firstProvider);`,
|
|
473
|
+
"});",
|
|
474
|
+
"",
|
|
475
|
+
`app.get(${JSON.stringify(loginProviderPath)}, async (c) => {`,
|
|
476
|
+
" const providerName = c.req.param(\"provider\");",
|
|
477
|
+
" const provider = oauthProviders[providerName as keyof typeof oauthProviders];",
|
|
478
|
+
" if (!provider) return c.text('Unknown OAuth/OIDC provider.', 404);",
|
|
479
|
+
" const state = randomToken();",
|
|
480
|
+
" const nonce = randomToken();",
|
|
481
|
+
" const codeVerifier = randomToken();",
|
|
482
|
+
" const codeChallenge = await sha256Base64Url(codeVerifier);",
|
|
483
|
+
" const redirectUri = new URL(c.req.url).origin + provider.callbackPath;",
|
|
484
|
+
" const authorizationUrl = new URL(provider.authorizationEndpoint);",
|
|
485
|
+
" authorizationUrl.searchParams.set('client_id', requiredEnv(c.env, provider.clientIdEnv));",
|
|
486
|
+
" authorizationUrl.searchParams.set('redirect_uri', redirectUri);",
|
|
487
|
+
" authorizationUrl.searchParams.set('response_type', 'code');",
|
|
488
|
+
" authorizationUrl.searchParams.set('scope', provider.scopes.join(' '));",
|
|
489
|
+
" authorizationUrl.searchParams.set('state', state);",
|
|
490
|
+
" authorizationUrl.searchParams.set('code_challenge', codeChallenge);",
|
|
491
|
+
" authorizationUrl.searchParams.set('code_challenge_method', 'S256');",
|
|
492
|
+
" if (provider.usesOidc) authorizationUrl.searchParams.set(\"nonce\", nonce);",
|
|
493
|
+
" for (const [name, value] of Object.entries(provider.authorizationParams ?? {})) {",
|
|
494
|
+
" authorizationUrl.searchParams.set(name, value);",
|
|
495
|
+
" }",
|
|
496
|
+
" return redirectWithCookies(authorizationUrl.toString(), [",
|
|
497
|
+
" serializeCookie('tw_oauth_state', `${providerName}.${state}`, {",
|
|
498
|
+
" httpOnly: true,",
|
|
499
|
+
" sameSite: 'Lax',",
|
|
500
|
+
" secure: true,",
|
|
501
|
+
" path: provider.callbackPath,",
|
|
502
|
+
" maxAge: 600",
|
|
503
|
+
" }),",
|
|
504
|
+
" serializeCookie('tw_oauth_pkce', `${providerName}.${codeVerifier}.${nonce}`, {",
|
|
505
|
+
" httpOnly: true,",
|
|
506
|
+
" sameSite: 'Lax',",
|
|
507
|
+
" secure: true,",
|
|
508
|
+
" path: provider.callbackPath,",
|
|
509
|
+
" maxAge: 600",
|
|
510
|
+
" })",
|
|
511
|
+
" ]);",
|
|
512
|
+
"});",
|
|
513
|
+
"",
|
|
514
|
+
`app.get(${JSON.stringify(callbackProviderPath)}, async (c) => {`,
|
|
515
|
+
" const providerName = c.req.param(\"provider\");",
|
|
516
|
+
" const provider = oauthProviders[providerName as keyof typeof oauthProviders];",
|
|
517
|
+
" if (!provider) return c.text('Unknown OAuth/OIDC provider.', 404);",
|
|
518
|
+
" const error = c.req.query('error');",
|
|
519
|
+
" if (error) return c.text(`OAuth/OIDC error: ${error}`, 400);",
|
|
520
|
+
" const code = c.req.query('code');",
|
|
521
|
+
" const state = c.req.query('state');",
|
|
522
|
+
" if (!code || !state) return c.text('Missing OAuth/OIDC callback parameters.', 400);",
|
|
523
|
+
" const cookies = parseCookies(c.req.header('Cookie') ?? '');",
|
|
524
|
+
" if (cookies.tw_oauth_state !== `${providerName}.${state}`) {",
|
|
525
|
+
" return c.text('Invalid OAuth/OIDC state.', 400);",
|
|
526
|
+
" }",
|
|
527
|
+
" const pkceParts = cookies.tw_oauth_pkce?.split('.') ?? [];",
|
|
528
|
+
" const codeVerifier = pkceParts[0] === providerName ? pkceParts[1] : undefined;",
|
|
529
|
+
" const nonce = pkceParts[0] === providerName ? pkceParts[2] : undefined;",
|
|
530
|
+
" if (!codeVerifier) return c.text('Missing OAuth/OIDC PKCE verifier.', 400);",
|
|
531
|
+
" if (provider.usesOidc && !nonce) return c.text('Missing OAuth/OIDC nonce.', 400);",
|
|
532
|
+
" const redirectUri = new URL(c.req.url).origin + provider.callbackPath;",
|
|
533
|
+
" const tokenResponse = await exchangeAuthorizationCode(c.env, provider, code, redirectUri, codeVerifier);",
|
|
534
|
+
" const identity = await loadProviderIdentity(c.env, provider, tokenResponse, nonce);",
|
|
535
|
+
" const session = await signSession(c.env, {",
|
|
536
|
+
" provider: providerName,",
|
|
537
|
+
" subject: identity.subject,",
|
|
538
|
+
" name: identity.name,",
|
|
539
|
+
" email: identity.email,",
|
|
540
|
+
" expiresAt: Math.floor(Date.now() / 1000) + 60 * 60 * 24",
|
|
541
|
+
" });",
|
|
542
|
+
" return redirectWithCookies(\"/\", [",
|
|
543
|
+
" serializeCookie('tw_oauth_state', '', {path: provider.callbackPath, maxAge: 0}),",
|
|
544
|
+
" serializeCookie('tw_oauth_pkce', '', {path: provider.callbackPath, maxAge: 0}),",
|
|
545
|
+
" serializeCookie('tw_session', session, {",
|
|
546
|
+
" httpOnly: true,",
|
|
547
|
+
" sameSite: 'Lax',",
|
|
548
|
+
" secure: true,",
|
|
549
|
+
" path: '/',",
|
|
550
|
+
" maxAge: 60 * 60 * 24",
|
|
551
|
+
" })",
|
|
552
|
+
" ]);",
|
|
553
|
+
"});",
|
|
554
|
+
"",
|
|
555
|
+
`app.get(${JSON.stringify(logoutPath)}, (c) => {`,
|
|
556
|
+
" return redirectWithCookies(\"/\", [",
|
|
557
|
+
" serializeCookie('tw_session', '', {path: '/', maxAge: 0})",
|
|
558
|
+
" ]);",
|
|
559
|
+
"});",
|
|
560
|
+
"",
|
|
561
|
+
`app.get(${JSON.stringify(mePath)}, async (c) => {`,
|
|
562
|
+
" if (authSession.mode === \"cloudflare-access\") {",
|
|
563
|
+
" const subject = c.req.header(\"Cf-Access-Authenticated-User-Email\");",
|
|
564
|
+
" return c.json({",
|
|
565
|
+
" authenticated: Boolean(subject),",
|
|
566
|
+
" user: subject ? {provider: \"cloudflare-access\", subject, email: subject} : null",
|
|
567
|
+
" }, subject ? 200 : 401);",
|
|
568
|
+
" }",
|
|
569
|
+
" const sessionCookie = parseCookies(c.req.header('Cookie') ?? '').tw_session;",
|
|
570
|
+
" const session = sessionCookie ? await readSignedSession(c.env, sessionCookie) : null;",
|
|
571
|
+
" return c.json({authenticated: Boolean(session), user: session}, session ? 200 : 401);",
|
|
572
|
+
"});",
|
|
573
|
+
"",
|
|
574
|
+
"for (const route of protectedRoutes) {",
|
|
575
|
+
" app.use(route.path, async (c, next) => {",
|
|
576
|
+
" if (route.method !== '*' && route.method !== c.req.method.toUpperCase()) {",
|
|
577
|
+
" await next();",
|
|
578
|
+
" return;",
|
|
579
|
+
" }",
|
|
580
|
+
" if (route.auth === \"bearer-jwt\") {",
|
|
581
|
+
" const result = await verifyBearerRequest(c.req.raw, c.env, route);",
|
|
582
|
+
" if (!result.ok) {",
|
|
583
|
+
" return c.json({error: result.error}, result.status);",
|
|
584
|
+
" }",
|
|
585
|
+
" await next();",
|
|
586
|
+
" return;",
|
|
587
|
+
" }",
|
|
588
|
+
" if (await hasAuthenticatedIdentity(c.req.raw, c.env)) {",
|
|
589
|
+
" await next();",
|
|
590
|
+
" return;",
|
|
591
|
+
" }",
|
|
592
|
+
" if (route.onUnauthenticated === \"json-401\") {",
|
|
593
|
+
" return c.json({error: 'authentication_required'}, 401);",
|
|
594
|
+
" }",
|
|
595
|
+
" if (route.onUnauthenticated === \"forbid-403\") {",
|
|
596
|
+
" return c.text('Forbidden', 403);",
|
|
597
|
+
" }",
|
|
598
|
+
` return c.redirect(${JSON.stringify(loginPath)});`,
|
|
599
|
+
" });",
|
|
600
|
+
"}",
|
|
601
|
+
"",
|
|
602
|
+
"async function hasAuthenticatedIdentity(request: Request, env: Env): Promise<boolean> {",
|
|
603
|
+
" if (authSession.mode === \"cloudflare-access\") {",
|
|
604
|
+
" return request.headers.has('Cf-Access-Jwt-Assertion');",
|
|
605
|
+
" }",
|
|
606
|
+
" if (authSession.mode === \"bearer-jwt\") {",
|
|
607
|
+
" // TODO: Validate provider-issued bearer JWTs against issuer, audience, and JWKS.",
|
|
608
|
+
" return false;",
|
|
609
|
+
" }",
|
|
610
|
+
" const sessionCookie = parseCookies(request.headers.get('Cookie') ?? '').tw_session;",
|
|
611
|
+
" return sessionCookie ? (await readSignedSession(env, sessionCookie)) !== null : false;",
|
|
612
|
+
"}",
|
|
613
|
+
"",
|
|
614
|
+
"type ProviderConfig = {",
|
|
615
|
+
" authorizationEndpoint: string;",
|
|
616
|
+
" tokenEndpoint: string;",
|
|
617
|
+
" userInfoEndpoint?: string;",
|
|
618
|
+
" emailsEndpoint?: string;",
|
|
619
|
+
" jwksEndpoint?: string;",
|
|
620
|
+
" issuer?: string;",
|
|
621
|
+
" issuerPrefix?: string;",
|
|
622
|
+
" usesOidc: boolean;",
|
|
623
|
+
" authorizationParams?: Record<string, string>;",
|
|
624
|
+
" scopes: readonly string[];",
|
|
625
|
+
" clientIdEnv: string;",
|
|
626
|
+
" clientSecretEnv: string;",
|
|
627
|
+
" callbackPath: string;",
|
|
628
|
+
"};",
|
|
629
|
+
"",
|
|
630
|
+
"type AuthSessionMode = \"signed-cookie\" | \"bearer-jwt\" | \"cloudflare-access\";",
|
|
631
|
+
"",
|
|
632
|
+
"type ProtectedRoute = {",
|
|
633
|
+
" method: string;",
|
|
634
|
+
" path: string;",
|
|
635
|
+
" onUnauthenticated: \"redirect-login\" | \"json-401\" | \"forbid-403\";",
|
|
636
|
+
" auth?: \"session\" | \"bearer-jwt\";",
|
|
637
|
+
" requiredRole?: string;",
|
|
638
|
+
" requiredScopes?: readonly string[];",
|
|
639
|
+
"};",
|
|
640
|
+
"",
|
|
641
|
+
"type TokenResponse = {",
|
|
642
|
+
" access_token?: string;",
|
|
643
|
+
" id_token?: string;",
|
|
644
|
+
" token_type?: string;",
|
|
645
|
+
" expires_in?: number;",
|
|
646
|
+
"};",
|
|
647
|
+
"",
|
|
648
|
+
"type JwksKey = JsonWebKey & {kid?: string; kty?: string};",
|
|
649
|
+
"",
|
|
650
|
+
"type SessionIdentity = {",
|
|
651
|
+
" provider: string;",
|
|
652
|
+
" subject: string;",
|
|
653
|
+
" name?: string;",
|
|
654
|
+
" email?: string;",
|
|
655
|
+
" expiresAt: number;",
|
|
656
|
+
"};",
|
|
657
|
+
"",
|
|
658
|
+
"type BearerClaims = {",
|
|
659
|
+
" iss?: string;",
|
|
660
|
+
" aud?: string | string[];",
|
|
661
|
+
" sub?: string;",
|
|
662
|
+
" role?: string;",
|
|
663
|
+
" scope?: string;",
|
|
664
|
+
" iat?: number;",
|
|
665
|
+
" exp?: number;",
|
|
666
|
+
"};",
|
|
667
|
+
"",
|
|
668
|
+
"type BearerVerificationResult =",
|
|
669
|
+
" | {ok: true; claims: BearerClaims}",
|
|
670
|
+
" | {ok: false; status: 401 | 403; error: string};",
|
|
671
|
+
"",
|
|
672
|
+
"async function verifyBearerRequest(",
|
|
673
|
+
" request: Request,",
|
|
674
|
+
" env: Env,",
|
|
675
|
+
" route: ProtectedRoute",
|
|
676
|
+
"): Promise<BearerVerificationResult> {",
|
|
677
|
+
" const authorization = request.headers.get('Authorization') ?? '';",
|
|
678
|
+
" const match = /^Bearer\\s+(.+)$/i.exec(authorization);",
|
|
679
|
+
" if (!match) return {ok: false, status: 401, error: \"authentication_required\"};",
|
|
680
|
+
" const tokenResult = await verifyEs256BearerJwt(env, match[1]);",
|
|
681
|
+
" if (!tokenResult.ok) return tokenResult;",
|
|
682
|
+
" if (route.requiredRole && tokenResult.claims.role !== route.requiredRole) {",
|
|
683
|
+
" return {ok: false, status: 403, error: \"insufficient_role\"};",
|
|
684
|
+
" }",
|
|
685
|
+
" const scopes = new Set((tokenResult.claims.scope ?? '').split(/\\s+/).filter(Boolean));",
|
|
686
|
+
" for (const scope of route.requiredScopes ?? []) {",
|
|
687
|
+
" if (!scopes.has(scope)) return {ok: false, status: 403, error: \"insufficient_scope\"};",
|
|
688
|
+
" }",
|
|
689
|
+
" return tokenResult;",
|
|
690
|
+
"}",
|
|
691
|
+
"",
|
|
692
|
+
"async function verifyEs256BearerJwt(env: Env, token: string): Promise<BearerVerificationResult> {",
|
|
693
|
+
" const [encodedHeader, encodedPayload, encodedSignature] = token.split(\".\");",
|
|
694
|
+
" if (!encodedHeader || !encodedPayload || !encodedSignature) {",
|
|
695
|
+
" return {ok: false, status: 401, error: \"invalid_token\"};",
|
|
696
|
+
" }",
|
|
697
|
+
" let header: Record<string, unknown>;",
|
|
698
|
+
" let claims: BearerClaims;",
|
|
699
|
+
" try {",
|
|
700
|
+
" header = JSON.parse(base64UrlDecode(encodedHeader)) as Record<string, unknown>;",
|
|
701
|
+
" claims = JSON.parse(base64UrlDecode(encodedPayload)) as BearerClaims;",
|
|
702
|
+
" } catch {",
|
|
703
|
+
" return {ok: false, status: 401, error: \"invalid_token\"};",
|
|
704
|
+
" }",
|
|
705
|
+
" if (header.alg !== \"ES256\") return {ok: false, status: 401, error: \"invalid_token\"};",
|
|
706
|
+
" const expectedIssuer = env.BEARER_JWT_ISSUER ?? defaultBearerJwtIssuer;",
|
|
707
|
+
" const expectedAudience = env.BEARER_JWT_AUDIENCE ?? defaultBearerJwtAudience;",
|
|
708
|
+
" if (claims.iss !== expectedIssuer) {",
|
|
709
|
+
" return {ok: false, status: 401, error: \"invalid_token\"};",
|
|
710
|
+
" }",
|
|
711
|
+
" const audience = claims.aud;",
|
|
712
|
+
" const audienceMatches = Array.isArray(audience)",
|
|
713
|
+
" ? audience.includes(expectedAudience)",
|
|
714
|
+
" : audience === expectedAudience;",
|
|
715
|
+
" if (!audienceMatches) return {ok: false, status: 401, error: \"invalid_token\"};",
|
|
716
|
+
" if (!claims.exp || claims.exp <= Math.floor(Date.now() / 1000)) {",
|
|
717
|
+
" return {ok: false, status: 401, error: \"invalid_token\"};",
|
|
718
|
+
" }",
|
|
719
|
+
" const jwks = JSON.parse(env.BEARER_JWKS) as {keys?: JwksKey[]};",
|
|
720
|
+
" const key = jwks.keys?.find((item) => item.kid === header.kid && item.kty === \"EC\");",
|
|
721
|
+
" if (!key) return {ok: false, status: 401, error: \"invalid_token\"};",
|
|
722
|
+
" const cryptoKey = await crypto.subtle.importKey(",
|
|
723
|
+
" \"jwk\",",
|
|
724
|
+
" key,",
|
|
725
|
+
" {name: \"ECDSA\", namedCurve: \"P-256\"},",
|
|
726
|
+
" false,",
|
|
727
|
+
" [\"verify\"]",
|
|
728
|
+
" );",
|
|
729
|
+
" const verified = await crypto.subtle.verify(",
|
|
730
|
+
" {name: \"ECDSA\", hash: \"SHA-256\"},",
|
|
731
|
+
" cryptoKey,",
|
|
732
|
+
" base64UrlToBytes(encodedSignature),",
|
|
733
|
+
" new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`)",
|
|
734
|
+
" );",
|
|
735
|
+
" return verified",
|
|
736
|
+
" ? {ok: true, claims}",
|
|
737
|
+
" : {ok: false, status: 401, error: \"invalid_token\"};",
|
|
738
|
+
"}",
|
|
739
|
+
"",
|
|
740
|
+
"async function exchangeAuthorizationCode(",
|
|
741
|
+
" env: Env,",
|
|
742
|
+
" provider: ProviderConfig,",
|
|
743
|
+
" code: string,",
|
|
744
|
+
" redirectUri: string,",
|
|
745
|
+
" codeVerifier: string",
|
|
746
|
+
"): Promise<TokenResponse> {",
|
|
747
|
+
" const body = new URLSearchParams({",
|
|
748
|
+
" grant_type: \"authorization_code\",",
|
|
749
|
+
" code,",
|
|
750
|
+
" redirect_uri: redirectUri,",
|
|
751
|
+
" client_id: requiredEnv(env, provider.clientIdEnv),",
|
|
752
|
+
" client_secret: requiredEnv(env, provider.clientSecretEnv),",
|
|
753
|
+
" code_verifier: codeVerifier",
|
|
754
|
+
" });",
|
|
755
|
+
" const response = await fetch(provider.tokenEndpoint, {",
|
|
756
|
+
" method: 'POST',",
|
|
757
|
+
" headers: {Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'},",
|
|
758
|
+
" body",
|
|
759
|
+
" });",
|
|
760
|
+
" if (!response.ok) {",
|
|
761
|
+
" throw new Error(`OAuth/OIDC token exchange failed: ${response.status}`);",
|
|
762
|
+
" }",
|
|
763
|
+
" return (await response.json()) as TokenResponse;",
|
|
764
|
+
"}",
|
|
765
|
+
"",
|
|
766
|
+
"async function loadProviderIdentity(",
|
|
767
|
+
" env: Env,",
|
|
768
|
+
" provider: ProviderConfig,",
|
|
769
|
+
" tokenResponse: TokenResponse,",
|
|
770
|
+
" expectedNonce: string | undefined",
|
|
771
|
+
"): Promise<Omit<SessionIdentity, \"provider\" | \"expiresAt\">> {",
|
|
772
|
+
" if (tokenResponse.id_token) {",
|
|
773
|
+
" const claims = await verifyOidcIdToken(env, provider, tokenResponse.id_token, expectedNonce);",
|
|
774
|
+
" return {",
|
|
775
|
+
" subject: providerSubject(provider, claims),",
|
|
776
|
+
" name: stringClaim(claims.name),",
|
|
777
|
+
" email: stringClaim(claims.email)",
|
|
778
|
+
" };",
|
|
779
|
+
" }",
|
|
780
|
+
" if (provider.userInfoEndpoint && tokenResponse.access_token) {",
|
|
781
|
+
" const response = await fetch(provider.userInfoEndpoint, {",
|
|
782
|
+
" headers: {Authorization: `Bearer ${tokenResponse.access_token}`, Accept: 'application/json'}",
|
|
783
|
+
" });",
|
|
784
|
+
" if (response.ok) {",
|
|
785
|
+
" const profile = (await response.json()) as Record<string, unknown>;",
|
|
786
|
+
" return {",
|
|
787
|
+
" subject: providerSubject(provider, profile),",
|
|
788
|
+
" name: stringClaim(profile.name) ?? stringClaim(profile.login),",
|
|
789
|
+
" email: stringClaim(profile.email) ?? (await loadGithubPrimaryEmail(provider, tokenResponse.access_token))",
|
|
790
|
+
" };",
|
|
791
|
+
" }",
|
|
792
|
+
" }",
|
|
793
|
+
" return {subject: \"unknown\"};",
|
|
794
|
+
"}",
|
|
795
|
+
"",
|
|
796
|
+
"async function verifyOidcIdToken(",
|
|
797
|
+
" env: Env,",
|
|
798
|
+
" provider: ProviderConfig,",
|
|
799
|
+
" token: string,",
|
|
800
|
+
" expectedNonce: string | undefined",
|
|
801
|
+
"): Promise<Record<string, unknown>> {",
|
|
802
|
+
" if (!provider.usesOidc || !provider.jwksEndpoint) throw new Error(\"Provider does not support OIDC ID token verification.\");",
|
|
803
|
+
" const [encodedHeader, encodedPayload, encodedSignature] = token.split(\".\");",
|
|
804
|
+
" if (!encodedHeader || !encodedPayload || !encodedSignature) throw new Error(\"Invalid OIDC ID token format.\");",
|
|
805
|
+
" const header = JSON.parse(base64UrlDecode(encodedHeader)) as Record<string, unknown>;",
|
|
806
|
+
" const claims = JSON.parse(base64UrlDecode(encodedPayload)) as Record<string, unknown>;",
|
|
807
|
+
" if (header.alg !== \"RS256\") throw new Error(\"Unsupported OIDC ID token alg.\");",
|
|
808
|
+
" const issuer = stringClaim(claims.iss);",
|
|
809
|
+
" if (provider.issuer && issuer !== provider.issuer) throw new Error(\"Invalid OIDC issuer.\");",
|
|
810
|
+
" if (provider.issuerPrefix && !issuer?.startsWith(provider.issuerPrefix)) throw new Error(\"Invalid OIDC issuer.\");",
|
|
811
|
+
" const audience = claims.aud;",
|
|
812
|
+
" const expectedAudience = requiredEnv(env, provider.clientIdEnv);",
|
|
813
|
+
" const audienceMatches = Array.isArray(audience)",
|
|
814
|
+
" ? audience.includes(expectedAudience)",
|
|
815
|
+
" : audience === expectedAudience;",
|
|
816
|
+
" if (!audienceMatches) throw new Error(\"Invalid OIDC audience.\");",
|
|
817
|
+
" const expiresAt = typeof claims.exp === \"number\" ? claims.exp : 0;",
|
|
818
|
+
" if (expiresAt <= Math.floor(Date.now() / 1000)) throw new Error(\"Expired OIDC ID token.\");",
|
|
819
|
+
" if (!expectedNonce || claims.nonce !== expectedNonce) throw new Error(\"Invalid OIDC nonce.\");",
|
|
820
|
+
" await verifyJwtSignature(provider.jwksEndpoint, encodedHeader, encodedPayload, encodedSignature, stringClaim(header.kid));",
|
|
821
|
+
" return claims;",
|
|
822
|
+
"}",
|
|
823
|
+
"",
|
|
824
|
+
"async function verifyJwtSignature(",
|
|
825
|
+
" jwksEndpoint: string,",
|
|
826
|
+
" encodedHeader: string,",
|
|
827
|
+
" encodedPayload: string,",
|
|
828
|
+
" encodedSignature: string,",
|
|
829
|
+
" keyId: string | undefined",
|
|
830
|
+
"): Promise<void> {",
|
|
831
|
+
" const response = await fetch(jwksEndpoint, {headers: {Accept: \"application/json\"}});",
|
|
832
|
+
" if (!response.ok) throw new Error(`JWKS fetch failed: ${response.status}`);",
|
|
833
|
+
" const jwks = (await response.json()) as {keys?: JwksKey[]};",
|
|
834
|
+
" const key = jwks.keys?.find((item) => item.kid === keyId && item.kty === \"RSA\");",
|
|
835
|
+
" if (!key) throw new Error(\"OIDC signing key not found.\");",
|
|
836
|
+
" const cryptoKey = await crypto.subtle.importKey(",
|
|
837
|
+
" \"jwk\",",
|
|
838
|
+
" key,",
|
|
839
|
+
" {name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\"},",
|
|
840
|
+
" false,",
|
|
841
|
+
" [\"verify\"]",
|
|
842
|
+
" );",
|
|
843
|
+
" const verified = await crypto.subtle.verify(",
|
|
844
|
+
" \"RSASSA-PKCS1-v1_5\",",
|
|
845
|
+
" cryptoKey,",
|
|
846
|
+
" base64UrlToBytes(encodedSignature),",
|
|
847
|
+
" new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`)",
|
|
848
|
+
" );",
|
|
849
|
+
" if (!verified) throw new Error(\"Invalid OIDC ID token signature.\");",
|
|
850
|
+
"}",
|
|
851
|
+
"",
|
|
852
|
+
"async function loadGithubPrimaryEmail(",
|
|
853
|
+
" provider: ProviderConfig,",
|
|
854
|
+
" accessToken: string | undefined",
|
|
855
|
+
"): Promise<string | undefined> {",
|
|
856
|
+
" if (!provider.emailsEndpoint || !accessToken) return undefined;",
|
|
857
|
+
" const response = await fetch(provider.emailsEndpoint, {",
|
|
858
|
+
" headers: {Authorization: `Bearer ${accessToken}`, Accept: \"application/vnd.github+json\"}",
|
|
859
|
+
" });",
|
|
860
|
+
" if (!response.ok) return undefined;",
|
|
861
|
+
" const emails = (await response.json()) as Array<Record<string, unknown>>;",
|
|
862
|
+
" const primary = emails.find((email) => email.primary === true && email.verified === true);",
|
|
863
|
+
" return stringClaim(primary?.email);",
|
|
864
|
+
"}",
|
|
865
|
+
"",
|
|
866
|
+
"async function signSession(env: Env, identity: SessionIdentity): Promise<string> {",
|
|
867
|
+
" const payload = base64UrlEncode(JSON.stringify(identity));",
|
|
868
|
+
" const signature = await hmacSha256(payload, requiredEnv(env, 'SESSION_SECRET'));",
|
|
869
|
+
" return `${payload}.${signature}`;",
|
|
870
|
+
"}",
|
|
871
|
+
"",
|
|
872
|
+
"async function readSignedSession(env: Env, cookie: string): Promise<SessionIdentity | null> {",
|
|
873
|
+
" const [payload, signature] = cookie.split('.');",
|
|
874
|
+
" if (!payload || !signature) return null;",
|
|
875
|
+
" const expected = await hmacSha256(payload, requiredEnv(env, 'SESSION_SECRET'));",
|
|
876
|
+
" if (signature !== expected) return null;",
|
|
877
|
+
" try {",
|
|
878
|
+
" const session = JSON.parse(base64UrlDecode(payload)) as SessionIdentity;",
|
|
879
|
+
" return typeof session.expiresAt === 'number' && session.expiresAt > Math.floor(Date.now() / 1000)",
|
|
880
|
+
" ? session",
|
|
881
|
+
" : null;",
|
|
882
|
+
" } catch {",
|
|
883
|
+
" return null;",
|
|
884
|
+
" }",
|
|
885
|
+
"}",
|
|
886
|
+
"",
|
|
887
|
+
"function decodeJwtPayload(token: string): Record<string, unknown> {",
|
|
888
|
+
" const payload = token.split('.')[1];",
|
|
889
|
+
" if (!payload) return {};",
|
|
890
|
+
" try {",
|
|
891
|
+
" return JSON.parse(base64UrlDecode(payload)) as Record<string, unknown>;",
|
|
892
|
+
" } catch {",
|
|
893
|
+
" return {};",
|
|
894
|
+
" }",
|
|
895
|
+
"}",
|
|
896
|
+
"",
|
|
897
|
+
"async function hmacSha256(value: string, secret: string): Promise<string> {",
|
|
898
|
+
" const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), {name: 'HMAC', hash: 'SHA-256'}, false, ['sign']);",
|
|
899
|
+
" const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value));",
|
|
900
|
+
" return base64UrlEncode(new Uint8Array(signature));",
|
|
901
|
+
"}",
|
|
902
|
+
"",
|
|
903
|
+
"async function sha256Base64Url(value: string): Promise<string> {",
|
|
904
|
+
" const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));",
|
|
905
|
+
" return base64UrlEncode(new Uint8Array(digest));",
|
|
906
|
+
"}",
|
|
907
|
+
"",
|
|
908
|
+
"function randomToken(): string {",
|
|
909
|
+
" const bytes = new Uint8Array(32);",
|
|
910
|
+
" crypto.getRandomValues(bytes);",
|
|
911
|
+
" return base64UrlEncode(bytes);",
|
|
912
|
+
"}",
|
|
913
|
+
"",
|
|
914
|
+
"function parseCookies(header: string): Record<string, string> {",
|
|
915
|
+
" return Object.fromEntries(",
|
|
916
|
+
" header.split(';').flatMap((part) => {",
|
|
917
|
+
" const index = part.indexOf('=');",
|
|
918
|
+
" if (index === -1) return [];",
|
|
919
|
+
" return [[part.slice(0, index).trim(), decodeURIComponent(part.slice(index + 1))]];",
|
|
920
|
+
" })",
|
|
921
|
+
" );",
|
|
922
|
+
"}",
|
|
923
|
+
"",
|
|
924
|
+
"function serializeCookie(",
|
|
925
|
+
" name: string,",
|
|
926
|
+
" value: string,",
|
|
927
|
+
" options: {httpOnly?: boolean; sameSite?: \"Lax\" | \"Strict\" | \"None\"; secure?: boolean; path?: string; maxAge?: number}",
|
|
928
|
+
"): string {",
|
|
929
|
+
" const parts = [`${name}=${encodeURIComponent(value)}`];",
|
|
930
|
+
" if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);",
|
|
931
|
+
" if (options.path) parts.push(`Path=${options.path}`);",
|
|
932
|
+
" if (options.httpOnly) parts.push(\"HttpOnly\");",
|
|
933
|
+
" if (options.secure) parts.push(\"Secure\");",
|
|
934
|
+
" if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);",
|
|
935
|
+
" return parts.join('; ');",
|
|
936
|
+
"}",
|
|
937
|
+
"",
|
|
938
|
+
"function redirectWithCookies(location: string, cookies: readonly string[]): Response {",
|
|
939
|
+
" const headers = new Headers({Location: location});",
|
|
940
|
+
" for (const cookie of cookies) headers.append('Set-Cookie', cookie);",
|
|
941
|
+
" return new Response(null, {status: 302, headers});",
|
|
942
|
+
"}",
|
|
943
|
+
"",
|
|
944
|
+
"function requiredEnv(env: Env, name: string): string {",
|
|
945
|
+
" const value = (env as unknown as Record<string, string | undefined>)[name];",
|
|
946
|
+
" if (!value) throw new Error(`Missing required environment variable: ${name}`);",
|
|
947
|
+
" return value;",
|
|
948
|
+
"}",
|
|
949
|
+
"",
|
|
950
|
+
"function stringClaim(value: unknown): string | undefined {",
|
|
951
|
+
" return typeof value === 'string' && value.length > 0 ? value : undefined;",
|
|
952
|
+
"}",
|
|
953
|
+
"",
|
|
954
|
+
"function subjectClaim(value: unknown): string | undefined {",
|
|
955
|
+
" if (typeof value === 'string' && value.length > 0) return value;",
|
|
956
|
+
" if (typeof value === \"number\" && Number.isFinite(value)) return String(value);",
|
|
957
|
+
" return undefined;",
|
|
958
|
+
"}",
|
|
959
|
+
"",
|
|
960
|
+
"function providerSubject(provider: ProviderConfig, claims: Record<string, unknown>): string {",
|
|
961
|
+
" const providerName = providerNameFromConfig(provider);",
|
|
962
|
+
" const subject =",
|
|
963
|
+
" subjectClaim(claims.sub) ??",
|
|
964
|
+
" subjectClaim(claims.id) ??",
|
|
965
|
+
" stringClaim(claims.login) ??",
|
|
966
|
+
" \"unknown\";",
|
|
967
|
+
" return `${providerName}:${subject}`;",
|
|
968
|
+
"}",
|
|
969
|
+
"",
|
|
970
|
+
"function providerNameFromConfig(provider: ProviderConfig): string {",
|
|
971
|
+
" const entry = Object.entries(oauthProviders).find(([, config]) => config === provider);",
|
|
972
|
+
" return entry?.[0] ?? \"oauth\";",
|
|
973
|
+
"}",
|
|
974
|
+
"",
|
|
975
|
+
"function base64UrlEncode(value: string | Uint8Array): string {",
|
|
976
|
+
" const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : value;",
|
|
977
|
+
" let binary = '';",
|
|
978
|
+
" for (const byte of bytes) binary += String.fromCharCode(byte);",
|
|
979
|
+
" return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');",
|
|
980
|
+
"}",
|
|
981
|
+
"",
|
|
982
|
+
"function base64UrlDecode(value: string): string {",
|
|
983
|
+
" const padded = value.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(value.length / 4) * 4, '=');",
|
|
984
|
+
" const binary = atob(padded);",
|
|
985
|
+
" const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));",
|
|
986
|
+
" return new TextDecoder().decode(bytes);",
|
|
987
|
+
"}",
|
|
988
|
+
"",
|
|
989
|
+
"function base64UrlToBytes(value: string): Uint8Array {",
|
|
990
|
+
" const padded = value.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(value.length / 4) * 4, '=');",
|
|
991
|
+
" const binary = atob(padded);",
|
|
992
|
+
" return Uint8Array.from(binary, (char) => char.charCodeAt(0));",
|
|
993
|
+
"}",
|
|
994
|
+
""
|
|
995
|
+
];
|
|
996
|
+
}
|
|
997
|
+
function createProviderMap(providers, callbackBasePath) {
|
|
998
|
+
const providerSet = new Set(providers ?? []);
|
|
999
|
+
const result = {};
|
|
1000
|
+
if (providerSet.has("google")) result.google = {
|
|
1001
|
+
authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
1002
|
+
tokenEndpoint: "https://oauth2.googleapis.com/token",
|
|
1003
|
+
userInfoEndpoint: "https://openidconnect.googleapis.com/v1/userinfo",
|
|
1004
|
+
jwksEndpoint: "https://www.googleapis.com/oauth2/v3/certs",
|
|
1005
|
+
issuer: "https://accounts.google.com",
|
|
1006
|
+
usesOidc: true,
|
|
1007
|
+
authorizationParams: { prompt: "select_account" },
|
|
1008
|
+
scopes: [
|
|
1009
|
+
"openid",
|
|
1010
|
+
"email",
|
|
1011
|
+
"profile"
|
|
1012
|
+
],
|
|
1013
|
+
clientIdEnv: "GOOGLE_CLIENT_ID",
|
|
1014
|
+
clientSecretEnv: "GOOGLE_CLIENT_SECRET",
|
|
1015
|
+
callbackPath: `${callbackBasePath}/google`
|
|
1016
|
+
};
|
|
1017
|
+
if (providerSet.has("microsoft")) result.microsoft = {
|
|
1018
|
+
authorizationEndpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
|
|
1019
|
+
tokenEndpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
|
|
1020
|
+
userInfoEndpoint: "https://graph.microsoft.com/oidc/userinfo",
|
|
1021
|
+
jwksEndpoint: "https://login.microsoftonline.com/common/discovery/v2.0/keys",
|
|
1022
|
+
issuerPrefix: "https://login.microsoftonline.com/",
|
|
1023
|
+
usesOidc: true,
|
|
1024
|
+
authorizationParams: { prompt: "select_account" },
|
|
1025
|
+
scopes: [
|
|
1026
|
+
"openid",
|
|
1027
|
+
"email",
|
|
1028
|
+
"profile"
|
|
1029
|
+
],
|
|
1030
|
+
clientIdEnv: "MICROSOFT_CLIENT_ID",
|
|
1031
|
+
clientSecretEnv: "MICROSOFT_CLIENT_SECRET",
|
|
1032
|
+
callbackPath: `${callbackBasePath}/microsoft`
|
|
1033
|
+
};
|
|
1034
|
+
if (providerSet.has("github")) result.github = {
|
|
1035
|
+
authorizationEndpoint: "https://github.com/login/oauth/authorize",
|
|
1036
|
+
tokenEndpoint: "https://github.com/login/oauth/access_token",
|
|
1037
|
+
userInfoEndpoint: "https://api.github.com/user",
|
|
1038
|
+
emailsEndpoint: "https://api.github.com/user/emails",
|
|
1039
|
+
usesOidc: false,
|
|
1040
|
+
scopes: ["read:user", "user:email"],
|
|
1041
|
+
clientIdEnv: "GITHUB_CLIENT_ID",
|
|
1042
|
+
clientSecretEnv: "GITHUB_CLIENT_SECRET",
|
|
1043
|
+
callbackPath: `${callbackBasePath}/github`
|
|
1044
|
+
};
|
|
1045
|
+
return result;
|
|
1046
|
+
}
|
|
1047
|
+
function createEnvLines(ir) {
|
|
1048
|
+
const lines = [];
|
|
1049
|
+
if (!ir.storage || ir.storage.length === 0) lines.push(" // Bindings are added when D1, KV, R2, or Durable Objects appear in the IR.");
|
|
1050
|
+
else lines.push(...ir.storage.map((binding) => ` ${binding.binding}: ${bindingType(binding)};`));
|
|
1051
|
+
if (ir.auth && ir.auth.session !== "cloudflare-access") {
|
|
1052
|
+
for (const provider of ir.auth.providers) {
|
|
1053
|
+
lines.push(` ${providerEnvPrefix(provider)}_CLIENT_ID: string;`);
|
|
1054
|
+
lines.push(` ${providerEnvPrefix(provider)}_CLIENT_SECRET: string;`);
|
|
1055
|
+
}
|
|
1056
|
+
lines.push(" SESSION_SECRET: string;");
|
|
1057
|
+
}
|
|
1058
|
+
if (ir.auth?.protectedRoutes?.some((route) => route.auth === "bearer-jwt")) {
|
|
1059
|
+
lines.push(" BEARER_JWKS: string;");
|
|
1060
|
+
lines.push(" BEARER_JWT_ISSUER?: string;");
|
|
1061
|
+
lines.push(" BEARER_JWT_AUDIENCE?: string;");
|
|
1062
|
+
}
|
|
1063
|
+
return lines;
|
|
1064
|
+
}
|
|
1065
|
+
function providerEnvPrefix(provider) {
|
|
1066
|
+
return provider.toUpperCase();
|
|
1067
|
+
}
|
|
1068
|
+
function bindingType(binding) {
|
|
1069
|
+
switch (binding.kind) {
|
|
1070
|
+
case "d1": return "D1Database";
|
|
1071
|
+
case "kv": return "KVNamespace";
|
|
1072
|
+
case "r2": return "R2Bucket";
|
|
1073
|
+
case "durable-object": return "DurableObjectNamespace";
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
function storageOfKind(storage, kind) {
|
|
1077
|
+
return storage?.filter((binding) => binding.kind === kind) ?? [];
|
|
1078
|
+
}
|
|
1079
|
+
//#endregion
|
|
1080
|
+
//#region src/extension.ts
|
|
1081
|
+
var paletteDefinitions = block_definitions_default.blocks;
|
|
1082
|
+
var authBlockIconUri = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNiIgeT0iMTgiIHdpZHRoPSIzNiIgaGVpZ2h0PSIyNCIgcng9IjQiIGZpbGw9IiNGNzk1MjEiLz48cGF0aCBkPSJNMTUgMTh2LTZjMC01IDQtOSA5LTlzOSA0IDkgOXY2IiBmaWxsPSJub25lIiBzdHJva2U9IiMxRjI5MzciIHN0cm9rZS13aWR0aD0iNCIvPjxjaXJjbGUgY3g9IjI0IiBjeT0iMzAiIHI9IjMiIGZpbGw9IiMxRjI5MzciLz48L3N2Zz4=";
|
|
1083
|
+
var CloudflareExtension = class {
|
|
1084
|
+
getInfo() {
|
|
1085
|
+
return {
|
|
1086
|
+
id: extensionConfig.id,
|
|
1087
|
+
name: Scratch.translate(block_definitions_default.extensionName),
|
|
1088
|
+
docsURI: extensionConfig.docsURI,
|
|
1089
|
+
blockIconURI: extensionConfig.blockIconURI,
|
|
1090
|
+
blocks: paletteDefinitions.map((block) => this.toScratchPaletteEntry(block))
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
createHandlerIr(args) {
|
|
1094
|
+
const handler = {
|
|
1095
|
+
method: normalizeHttpMethod(Scratch.Cast.toString(args.METHOD)),
|
|
1096
|
+
path: normalizeRoutePath(Scratch.Cast.toString(args.PATH)),
|
|
1097
|
+
responseText: Scratch.Cast.toString(args.BODY)
|
|
1098
|
+
};
|
|
1099
|
+
return JSON.stringify(handler);
|
|
1100
|
+
}
|
|
1101
|
+
createWorkerIr(args) {
|
|
1102
|
+
const parsedHandlers = JSON.parse(Scratch.Cast.toString(args.HANDLERS));
|
|
1103
|
+
const handlers = Array.isArray(parsedHandlers) ? parsedHandlers : [parsedHandlers];
|
|
1104
|
+
const ir = parseWorkerIr({
|
|
1105
|
+
name: Scratch.Cast.toString(args.NAME),
|
|
1106
|
+
handlers
|
|
1107
|
+
});
|
|
1108
|
+
return JSON.stringify(ir);
|
|
1109
|
+
}
|
|
1110
|
+
createProtectedRouteIr(args) {
|
|
1111
|
+
const rawMethod = Scratch.Cast.toString(args.METHOD).trim().toUpperCase();
|
|
1112
|
+
const rawAction = Scratch.Cast.toString(args.ON_UNAUTHENTICATED).trim();
|
|
1113
|
+
const route = {
|
|
1114
|
+
method: rawMethod === "*" ? "*" : normalizeHttpMethod(rawMethod),
|
|
1115
|
+
path: normalizeRoutePath(Scratch.Cast.toString(args.PATH)),
|
|
1116
|
+
onUnauthenticated: rawAction === "json-401" || rawAction === "forbid-403" ? rawAction : "redirect-login"
|
|
1117
|
+
};
|
|
1118
|
+
return JSON.stringify(route);
|
|
1119
|
+
}
|
|
1120
|
+
createBearerRouteIr(args) {
|
|
1121
|
+
const route = {
|
|
1122
|
+
method: normalizeMethodOrWildcard(Scratch.Cast.toString(args.METHOD)),
|
|
1123
|
+
path: normalizeRoutePath(Scratch.Cast.toString(args.PATH)),
|
|
1124
|
+
onUnauthenticated: "json-401",
|
|
1125
|
+
auth: "bearer-jwt"
|
|
1126
|
+
};
|
|
1127
|
+
return JSON.stringify(route);
|
|
1128
|
+
}
|
|
1129
|
+
createBearerRoleRouteIr(args) {
|
|
1130
|
+
const route = {
|
|
1131
|
+
method: normalizeMethodOrWildcard(Scratch.Cast.toString(args.METHOD)),
|
|
1132
|
+
path: normalizeRoutePath(Scratch.Cast.toString(args.PATH)),
|
|
1133
|
+
onUnauthenticated: "json-401",
|
|
1134
|
+
auth: "bearer-jwt",
|
|
1135
|
+
requiredRole: Scratch.Cast.toString(args.ROLE)
|
|
1136
|
+
};
|
|
1137
|
+
return JSON.stringify(route);
|
|
1138
|
+
}
|
|
1139
|
+
createBearerScopeRouteIr(args) {
|
|
1140
|
+
const route = {
|
|
1141
|
+
method: normalizeMethodOrWildcard(Scratch.Cast.toString(args.METHOD)),
|
|
1142
|
+
path: normalizeRoutePath(Scratch.Cast.toString(args.PATH)),
|
|
1143
|
+
onUnauthenticated: "json-401",
|
|
1144
|
+
auth: "bearer-jwt",
|
|
1145
|
+
requiredScopes: parseScopes(Scratch.Cast.toString(args.SCOPE))
|
|
1146
|
+
};
|
|
1147
|
+
return JSON.stringify(route);
|
|
1148
|
+
}
|
|
1149
|
+
createAuthIr(args) {
|
|
1150
|
+
const parsedRoutes = JSON.parse(Scratch.Cast.toString(args.PROTECTED_ROUTES));
|
|
1151
|
+
const protectedRoutes = Array.isArray(parsedRoutes) ? parsedRoutes : [parsedRoutes];
|
|
1152
|
+
const auth = {
|
|
1153
|
+
mode: "external-oauth-oidc",
|
|
1154
|
+
providers: parseProviders(Scratch.Cast.toString(args.PROVIDERS)),
|
|
1155
|
+
session: "signed-cookie",
|
|
1156
|
+
loginPath: "/auth/login",
|
|
1157
|
+
callbackPath: "/auth/callback",
|
|
1158
|
+
logoutPath: "/auth/logout",
|
|
1159
|
+
mePath: "/auth/me",
|
|
1160
|
+
protectedRoutes
|
|
1161
|
+
};
|
|
1162
|
+
return JSON.stringify(parseWorkerIr({
|
|
1163
|
+
name: "auth-validation",
|
|
1164
|
+
handlers: [],
|
|
1165
|
+
auth
|
|
1166
|
+
}).auth);
|
|
1167
|
+
}
|
|
1168
|
+
createWorkerIrWithAuth(args) {
|
|
1169
|
+
const parsedHandlers = JSON.parse(Scratch.Cast.toString(args.HANDLERS));
|
|
1170
|
+
const handlers = Array.isArray(parsedHandlers) ? parsedHandlers : [parsedHandlers];
|
|
1171
|
+
const auth = JSON.parse(Scratch.Cast.toString(args.AUTH));
|
|
1172
|
+
const ir = parseWorkerIr({
|
|
1173
|
+
name: Scratch.Cast.toString(args.NAME),
|
|
1174
|
+
handlers,
|
|
1175
|
+
auth
|
|
1176
|
+
});
|
|
1177
|
+
return JSON.stringify(ir);
|
|
1178
|
+
}
|
|
1179
|
+
generateFilesJson(args) {
|
|
1180
|
+
const ir = JSON.parse(Scratch.Cast.toString(args.IR));
|
|
1181
|
+
return JSON.stringify(generateCloudflareWorkerFiles(ir));
|
|
1182
|
+
}
|
|
1183
|
+
toScratchPaletteEntry(block) {
|
|
1184
|
+
if (isSeparatorDefinition(block)) return "---";
|
|
1185
|
+
const scratchBlock = {
|
|
1186
|
+
opcode: block.opcode,
|
|
1187
|
+
blockType: Scratch.BlockType[block.blockType],
|
|
1188
|
+
text: Scratch.translate(block.text),
|
|
1189
|
+
arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
|
|
1190
|
+
type: Scratch.ArgumentType[argument.type],
|
|
1191
|
+
defaultValue: argument.defaultValue
|
|
1192
|
+
}]))
|
|
1193
|
+
};
|
|
1194
|
+
if (block.category === "auth") scratchBlock.blockIconURI = authBlockIconUri;
|
|
1195
|
+
return scratchBlock;
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
function isSeparatorDefinition(block) {
|
|
1199
|
+
return "kind" in block && block.kind === "separator";
|
|
1200
|
+
}
|
|
1201
|
+
function parseProviders(value) {
|
|
1202
|
+
const normalized = value.split(",").map((provider) => provider.trim().toLowerCase()).filter((provider) => provider.length > 0).filter((provider) => provider === "google" || provider === "microsoft" || provider === "github");
|
|
1203
|
+
return [...new Set(normalized)];
|
|
1204
|
+
}
|
|
1205
|
+
function normalizeMethodOrWildcard(value) {
|
|
1206
|
+
const normalized = value.trim().toUpperCase();
|
|
1207
|
+
return normalized === "*" ? "*" : normalizeHttpMethod(normalized);
|
|
1208
|
+
}
|
|
1209
|
+
function parseScopes(value) {
|
|
1210
|
+
return value.split(/[,\s]+/).map((scope) => scope.trim()).filter((scope) => scope.length > 0);
|
|
1211
|
+
}
|
|
1212
|
+
//#endregion
|
|
1213
|
+
//#region src/index.ts
|
|
1214
|
+
if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
|
|
1215
|
+
Scratch.extensions.register(new CloudflareExtension());
|
|
1216
|
+
//#endregion
|
|
1217
|
+
|
|
1218
|
+
})(Scratch);
|