@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.
@@ -0,0 +1,776 @@
1
+ import { parseWorkerIr } from './ir.js';
2
+ const DEFAULT_COMPATIBILITY_DATE = '2026-08-27';
3
+ export function generateCloudflareWorkerFiles(input) {
4
+ const ir = parseWorkerIr(input);
5
+ return [
6
+ {
7
+ path: 'package.json',
8
+ contents: `${JSON.stringify(createPackageJson(ir.name), null, 2)}\n`
9
+ },
10
+ {
11
+ path: 'wrangler.jsonc',
12
+ contents: createWranglerJsonc(ir)
13
+ },
14
+ {
15
+ path: 'tsconfig.json',
16
+ contents: createTsconfigJson()
17
+ },
18
+ {
19
+ path: 'src/index.ts',
20
+ contents: createWorkerSource(ir)
21
+ }
22
+ ];
23
+ }
24
+ function createTsconfigJson() {
25
+ return `${JSON.stringify({
26
+ compilerOptions: {
27
+ target: 'ES2022',
28
+ module: 'ESNext',
29
+ moduleResolution: 'Bundler',
30
+ strict: true,
31
+ lib: ['ES2022'],
32
+ types: ['@cloudflare/workers-types']
33
+ },
34
+ include: ['src/**/*.ts']
35
+ }, null, 2)}\n`;
36
+ }
37
+ function createPackageJson(name) {
38
+ return {
39
+ name,
40
+ version: '0.1.0',
41
+ private: true,
42
+ type: 'module',
43
+ scripts: {
44
+ dev: 'wrangler dev',
45
+ deploy: 'wrangler deploy',
46
+ typecheck: 'tsc --noEmit'
47
+ },
48
+ dependencies: {
49
+ hono: '^4.10.7'
50
+ },
51
+ devDependencies: {
52
+ '@cloudflare/workers-types': '^5.20260826.1',
53
+ typescript: '^5.9.3',
54
+ wrangler: '^4.0.0'
55
+ }
56
+ };
57
+ }
58
+ function createWranglerJsonc(ir) {
59
+ const lines = [
60
+ '{',
61
+ ` "name": ${JSON.stringify(ir.name)},`,
62
+ ' "main": "src/index.ts",',
63
+ ` "compatibility_date": ${JSON.stringify(ir.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE)}`
64
+ ];
65
+ const d1 = storageOfKind(ir.storage, 'd1');
66
+ const kv = storageOfKind(ir.storage, 'kv');
67
+ const r2 = storageOfKind(ir.storage, 'r2');
68
+ const durableObjects = storageOfKind(ir.storage, 'durable-object');
69
+ if (d1.length > 0) {
70
+ lines.push(',', ' "d1_databases": [');
71
+ lines.push(...d1.map((binding, index) => [
72
+ ' {',
73
+ ` "binding": ${JSON.stringify(binding.binding)},`,
74
+ ` "database_name": ${JSON.stringify(binding.name)},`,
75
+ ` "database_id": "REPLACE_WITH_${binding.binding}_DATABASE_ID"`,
76
+ ` }${index === d1.length - 1 ? '' : ','}`
77
+ ].join('\n')));
78
+ lines.push(' ]');
79
+ }
80
+ if (kv.length > 0) {
81
+ lines.push(',', ' "kv_namespaces": [');
82
+ lines.push(...kv.map((binding, index) => [
83
+ ' {',
84
+ ` "binding": ${JSON.stringify(binding.binding)},`,
85
+ ` "id": "REPLACE_WITH_${binding.binding}_NAMESPACE_ID"`,
86
+ ` }${index === kv.length - 1 ? '' : ','}`
87
+ ].join('\n')));
88
+ lines.push(' ]');
89
+ }
90
+ if (r2.length > 0) {
91
+ lines.push(',', ' "r2_buckets": [');
92
+ lines.push(...r2.map((binding, index) => [
93
+ ' {',
94
+ ` "binding": ${JSON.stringify(binding.binding)},`,
95
+ ` "bucket_name": ${JSON.stringify(binding.name)}`,
96
+ ` }${index === r2.length - 1 ? '' : ','}`
97
+ ].join('\n')));
98
+ lines.push(' ]');
99
+ }
100
+ if (durableObjects.length > 0) {
101
+ lines.push(',', ' "durable_objects": {');
102
+ lines.push(' "bindings": [');
103
+ lines.push(...durableObjects.map((binding, index) => [
104
+ ' {',
105
+ ` "name": ${JSON.stringify(binding.binding)},`,
106
+ ` "class_name": ${JSON.stringify(binding.name)}`,
107
+ ` }${index === durableObjects.length - 1 ? '' : ','}`
108
+ ].join('\n')));
109
+ lines.push(' ]', ' }');
110
+ }
111
+ lines.push('}', '');
112
+ return lines.join('\n');
113
+ }
114
+ function createWorkerSource(ir) {
115
+ const routeLines = ir.handlers.length === 0
116
+ ? [
117
+ "app.get('/', (c) => c.text('Generated by turbowarp-cloudflare-worker.'));"
118
+ ]
119
+ : ir.handlers.map((handler) => `app.${handler.method.toLowerCase()}(${JSON.stringify(handler.path)}, (c) => c.text(${JSON.stringify(handler.responseText)}));`);
120
+ return [
121
+ "import {Hono} from 'hono';",
122
+ '',
123
+ 'type Env = {',
124
+ ...createEnvLines(ir),
125
+ '};',
126
+ '',
127
+ 'const app = new Hono<{Bindings: Env}>();',
128
+ '',
129
+ ...createAuthLines(ir),
130
+ ...routeLines,
131
+ '',
132
+ 'export default app;',
133
+ ''
134
+ ].join('\n');
135
+ }
136
+ function createAuthLines(ir) {
137
+ if (!ir.auth) {
138
+ return ['// Add auth middleware here when the IR enables external OAuth/OIDC.'];
139
+ }
140
+ const loginPath = ir.auth.loginPath ?? '/auth/login';
141
+ const callbackPath = ir.auth.callbackPath ?? '/auth/callback';
142
+ const logoutPath = ir.auth.logoutPath ?? '/auth/logout';
143
+ const mePath = ir.auth.mePath ?? '/auth/me';
144
+ const protectedRoutes = ir.auth.protectedRoutes ?? [];
145
+ const providerMap = createProviderMap(ir.auth.providers, callbackPath);
146
+ const loginProviderPath = `${loginPath}/:provider`;
147
+ const callbackProviderPath = `${callbackPath}/:provider`;
148
+ return [
149
+ '// Authentication is delegated to external OAuth/OIDC providers.',
150
+ `// MVP providers: ${ir.auth.providers.join(', ') || 'none configured'}.`,
151
+ '// Secrets such as client IDs, client secrets, cookie keys, issuer, and audience must stay in Cloudflare secrets or environment variables.',
152
+ '// The generated flow covers authorization redirect, state verification, token exchange, and signed session cookies.',
153
+ '// Review provider scopes and profile mapping before production use.',
154
+ `const oauthProviders: Record<string, ProviderConfig> = ${JSON.stringify(providerMap, null, 2)};`,
155
+ `const authSession: {mode: AuthSessionMode} = {mode: ${JSON.stringify(ir.auth.session ?? 'signed-cookie')}};`,
156
+ `const defaultBearerJwtIssuer = ${JSON.stringify(`https://${ir.name}.workers.dev`)};`,
157
+ `const defaultBearerJwtAudience = ${JSON.stringify(ir.name)};`,
158
+ `const protectedRoutes: readonly ProtectedRoute[] = ${JSON.stringify(protectedRoutes, null, 2)};`,
159
+ '',
160
+ `app.get(${JSON.stringify(loginPath)}, (c) => {`,
161
+ ' const firstProvider = Object.keys(oauthProviders)[0];',
162
+ " if (!firstProvider) return c.text('No OAuth/OIDC provider configured.', 500);",
163
+ ` return c.redirect(${JSON.stringify(loginPath)} + '/' + firstProvider);`,
164
+ '});',
165
+ '',
166
+ `app.get(${JSON.stringify(loginProviderPath)}, async (c) => {`,
167
+ ' const providerName = c.req.param("provider");',
168
+ ' const provider = oauthProviders[providerName as keyof typeof oauthProviders];',
169
+ " if (!provider) return c.text('Unknown OAuth/OIDC provider.', 404);",
170
+ ' const state = randomToken();',
171
+ ' const nonce = randomToken();',
172
+ ' const codeVerifier = randomToken();',
173
+ ' const codeChallenge = await sha256Base64Url(codeVerifier);',
174
+ ' const redirectUri = new URL(c.req.url).origin + provider.callbackPath;',
175
+ ' const authorizationUrl = new URL(provider.authorizationEndpoint);',
176
+ " authorizationUrl.searchParams.set('client_id', requiredEnv(c.env, provider.clientIdEnv));",
177
+ " authorizationUrl.searchParams.set('redirect_uri', redirectUri);",
178
+ " authorizationUrl.searchParams.set('response_type', 'code');",
179
+ " authorizationUrl.searchParams.set('scope', provider.scopes.join(' '));",
180
+ " authorizationUrl.searchParams.set('state', state);",
181
+ " authorizationUrl.searchParams.set('code_challenge', codeChallenge);",
182
+ " authorizationUrl.searchParams.set('code_challenge_method', 'S256');",
183
+ ' if (provider.usesOidc) authorizationUrl.searchParams.set("nonce", nonce);',
184
+ ' for (const [name, value] of Object.entries(provider.authorizationParams ?? {})) {',
185
+ ' authorizationUrl.searchParams.set(name, value);',
186
+ ' }',
187
+ ' return redirectWithCookies(authorizationUrl.toString(), [',
188
+ " serializeCookie('tw_oauth_state', `${providerName}.${state}`, {",
189
+ ' httpOnly: true,',
190
+ " sameSite: 'Lax',",
191
+ ' secure: true,',
192
+ " path: provider.callbackPath,",
193
+ ' maxAge: 600',
194
+ ' }),',
195
+ " serializeCookie('tw_oauth_pkce', `${providerName}.${codeVerifier}.${nonce}`, {",
196
+ ' httpOnly: true,',
197
+ " sameSite: 'Lax',",
198
+ ' secure: true,',
199
+ " path: provider.callbackPath,",
200
+ ' maxAge: 600',
201
+ ' })',
202
+ ' ]);',
203
+ '});',
204
+ '',
205
+ `app.get(${JSON.stringify(callbackProviderPath)}, async (c) => {`,
206
+ ' const providerName = c.req.param("provider");',
207
+ ' const provider = oauthProviders[providerName as keyof typeof oauthProviders];',
208
+ " if (!provider) return c.text('Unknown OAuth/OIDC provider.', 404);",
209
+ " const error = c.req.query('error');",
210
+ " if (error) return c.text(`OAuth/OIDC error: ${error}`, 400);",
211
+ " const code = c.req.query('code');",
212
+ " const state = c.req.query('state');",
213
+ " if (!code || !state) return c.text('Missing OAuth/OIDC callback parameters.', 400);",
214
+ " const cookies = parseCookies(c.req.header('Cookie') ?? '');",
215
+ " if (cookies.tw_oauth_state !== `${providerName}.${state}`) {",
216
+ " return c.text('Invalid OAuth/OIDC state.', 400);",
217
+ ' }',
218
+ " const pkceParts = cookies.tw_oauth_pkce?.split('.') ?? [];",
219
+ ' const codeVerifier = pkceParts[0] === providerName ? pkceParts[1] : undefined;',
220
+ ' const nonce = pkceParts[0] === providerName ? pkceParts[2] : undefined;',
221
+ " if (!codeVerifier) return c.text('Missing OAuth/OIDC PKCE verifier.', 400);",
222
+ " if (provider.usesOidc && !nonce) return c.text('Missing OAuth/OIDC nonce.', 400);",
223
+ ' const redirectUri = new URL(c.req.url).origin + provider.callbackPath;',
224
+ ' const tokenResponse = await exchangeAuthorizationCode(c.env, provider, code, redirectUri, codeVerifier);',
225
+ ' const identity = await loadProviderIdentity(c.env, provider, tokenResponse, nonce);',
226
+ ' const session = await signSession(c.env, {',
227
+ ' provider: providerName,',
228
+ ' subject: identity.subject,',
229
+ ' name: identity.name,',
230
+ ' email: identity.email,',
231
+ ' expiresAt: Math.floor(Date.now() / 1000) + 60 * 60 * 24',
232
+ ' });',
233
+ ' return redirectWithCookies("/", [',
234
+ " serializeCookie('tw_oauth_state', '', {path: provider.callbackPath, maxAge: 0}),",
235
+ " serializeCookie('tw_oauth_pkce', '', {path: provider.callbackPath, maxAge: 0}),",
236
+ " serializeCookie('tw_session', session, {",
237
+ ' httpOnly: true,',
238
+ " sameSite: 'Lax',",
239
+ ' secure: true,',
240
+ " path: '/',",
241
+ ' maxAge: 60 * 60 * 24',
242
+ ' })',
243
+ ' ]);',
244
+ '});',
245
+ '',
246
+ `app.get(${JSON.stringify(logoutPath)}, (c) => {`,
247
+ ' return redirectWithCookies("/", [',
248
+ " serializeCookie('tw_session', '', {path: '/', maxAge: 0})",
249
+ ' ]);',
250
+ '});',
251
+ '',
252
+ `app.get(${JSON.stringify(mePath)}, async (c) => {`,
253
+ ' if (authSession.mode === "cloudflare-access") {',
254
+ ' const subject = c.req.header("Cf-Access-Authenticated-User-Email");',
255
+ ' return c.json({',
256
+ ' authenticated: Boolean(subject),',
257
+ ' user: subject ? {provider: "cloudflare-access", subject, email: subject} : null',
258
+ ' }, subject ? 200 : 401);',
259
+ ' }',
260
+ " const sessionCookie = parseCookies(c.req.header('Cookie') ?? '').tw_session;",
261
+ ' const session = sessionCookie ? await readSignedSession(c.env, sessionCookie) : null;',
262
+ ' return c.json({authenticated: Boolean(session), user: session}, session ? 200 : 401);',
263
+ '});',
264
+ '',
265
+ 'for (const route of protectedRoutes) {',
266
+ ' app.use(route.path, async (c, next) => {',
267
+ " if (route.method !== '*' && route.method !== c.req.method.toUpperCase()) {",
268
+ ' await next();',
269
+ ' return;',
270
+ ' }',
271
+ ' if (route.auth === "bearer-jwt") {',
272
+ ' const result = await verifyBearerRequest(c.req.raw, c.env, route);',
273
+ ' if (!result.ok) {',
274
+ ' return c.json({error: result.error}, result.status);',
275
+ ' }',
276
+ ' await next();',
277
+ ' return;',
278
+ ' }',
279
+ ' if (await hasAuthenticatedIdentity(c.req.raw, c.env)) {',
280
+ ' await next();',
281
+ ' return;',
282
+ ' }',
283
+ ' if (route.onUnauthenticated === "json-401") {',
284
+ " return c.json({error: 'authentication_required'}, 401);",
285
+ ' }',
286
+ ' if (route.onUnauthenticated === "forbid-403") {',
287
+ " return c.text('Forbidden', 403);",
288
+ ' }',
289
+ ` return c.redirect(${JSON.stringify(loginPath)});`,
290
+ ' });',
291
+ '}',
292
+ '',
293
+ 'async function hasAuthenticatedIdentity(request: Request, env: Env): Promise<boolean> {',
294
+ ' if (authSession.mode === "cloudflare-access") {',
295
+ " return request.headers.has('Cf-Access-Jwt-Assertion');",
296
+ ' }',
297
+ ' if (authSession.mode === "bearer-jwt") {',
298
+ " // TODO: Validate provider-issued bearer JWTs against issuer, audience, and JWKS.",
299
+ ' return false;',
300
+ ' }',
301
+ " const sessionCookie = parseCookies(request.headers.get('Cookie') ?? '').tw_session;",
302
+ ' return sessionCookie ? (await readSignedSession(env, sessionCookie)) !== null : false;',
303
+ '}',
304
+ '',
305
+ 'type ProviderConfig = {',
306
+ ' authorizationEndpoint: string;',
307
+ ' tokenEndpoint: string;',
308
+ ' userInfoEndpoint?: string;',
309
+ ' emailsEndpoint?: string;',
310
+ ' jwksEndpoint?: string;',
311
+ ' issuer?: string;',
312
+ ' issuerPrefix?: string;',
313
+ ' usesOidc: boolean;',
314
+ ' authorizationParams?: Record<string, string>;',
315
+ ' scopes: readonly string[];',
316
+ ' clientIdEnv: string;',
317
+ ' clientSecretEnv: string;',
318
+ ' callbackPath: string;',
319
+ '};',
320
+ '',
321
+ 'type AuthSessionMode = "signed-cookie" | "bearer-jwt" | "cloudflare-access";',
322
+ '',
323
+ 'type ProtectedRoute = {',
324
+ ' method: string;',
325
+ ' path: string;',
326
+ ' onUnauthenticated: "redirect-login" | "json-401" | "forbid-403";',
327
+ ' auth?: "session" | "bearer-jwt";',
328
+ ' requiredRole?: string;',
329
+ ' requiredScopes?: readonly string[];',
330
+ '};',
331
+ '',
332
+ 'type TokenResponse = {',
333
+ ' access_token?: string;',
334
+ ' id_token?: string;',
335
+ ' token_type?: string;',
336
+ ' expires_in?: number;',
337
+ '};',
338
+ '',
339
+ 'type JwksKey = JsonWebKey & {kid?: string; kty?: string};',
340
+ '',
341
+ 'type SessionIdentity = {',
342
+ ' provider: string;',
343
+ ' subject: string;',
344
+ ' name?: string;',
345
+ ' email?: string;',
346
+ ' expiresAt: number;',
347
+ '};',
348
+ '',
349
+ 'type BearerClaims = {',
350
+ ' iss?: string;',
351
+ ' aud?: string | string[];',
352
+ ' sub?: string;',
353
+ ' role?: string;',
354
+ ' scope?: string;',
355
+ ' iat?: number;',
356
+ ' exp?: number;',
357
+ '};',
358
+ '',
359
+ 'type BearerVerificationResult =',
360
+ ' | {ok: true; claims: BearerClaims}',
361
+ ' | {ok: false; status: 401 | 403; error: string};',
362
+ '',
363
+ 'async function verifyBearerRequest(',
364
+ ' request: Request,',
365
+ ' env: Env,',
366
+ ' route: ProtectedRoute',
367
+ '): Promise<BearerVerificationResult> {',
368
+ " const authorization = request.headers.get('Authorization') ?? '';",
369
+ " const match = /^Bearer\\s+(.+)$/i.exec(authorization);",
370
+ ' if (!match) return {ok: false, status: 401, error: "authentication_required"};',
371
+ ' const tokenResult = await verifyEs256BearerJwt(env, match[1]);',
372
+ ' if (!tokenResult.ok) return tokenResult;',
373
+ ' if (route.requiredRole && tokenResult.claims.role !== route.requiredRole) {',
374
+ ' return {ok: false, status: 403, error: "insufficient_role"};',
375
+ ' }',
376
+ " const scopes = new Set((tokenResult.claims.scope ?? '').split(/\\s+/).filter(Boolean));",
377
+ ' for (const scope of route.requiredScopes ?? []) {',
378
+ ' if (!scopes.has(scope)) return {ok: false, status: 403, error: "insufficient_scope"};',
379
+ ' }',
380
+ ' return tokenResult;',
381
+ '}',
382
+ '',
383
+ 'async function verifyEs256BearerJwt(env: Env, token: string): Promise<BearerVerificationResult> {',
384
+ ' const [encodedHeader, encodedPayload, encodedSignature] = token.split(".");',
385
+ ' if (!encodedHeader || !encodedPayload || !encodedSignature) {',
386
+ ' return {ok: false, status: 401, error: "invalid_token"};',
387
+ ' }',
388
+ ' let header: Record<string, unknown>;',
389
+ ' let claims: BearerClaims;',
390
+ ' try {',
391
+ ' header = JSON.parse(base64UrlDecode(encodedHeader)) as Record<string, unknown>;',
392
+ ' claims = JSON.parse(base64UrlDecode(encodedPayload)) as BearerClaims;',
393
+ ' } catch {',
394
+ ' return {ok: false, status: 401, error: "invalid_token"};',
395
+ ' }',
396
+ ' if (header.alg !== "ES256") return {ok: false, status: 401, error: "invalid_token"};',
397
+ ' const expectedIssuer = env.BEARER_JWT_ISSUER ?? defaultBearerJwtIssuer;',
398
+ ' const expectedAudience = env.BEARER_JWT_AUDIENCE ?? defaultBearerJwtAudience;',
399
+ ' if (claims.iss !== expectedIssuer) {',
400
+ ' return {ok: false, status: 401, error: "invalid_token"};',
401
+ ' }',
402
+ ' const audience = claims.aud;',
403
+ ' const audienceMatches = Array.isArray(audience)',
404
+ ' ? audience.includes(expectedAudience)',
405
+ ' : audience === expectedAudience;',
406
+ ' if (!audienceMatches) return {ok: false, status: 401, error: "invalid_token"};',
407
+ ' if (!claims.exp || claims.exp <= Math.floor(Date.now() / 1000)) {',
408
+ ' return {ok: false, status: 401, error: "invalid_token"};',
409
+ ' }',
410
+ ' const jwks = JSON.parse(env.BEARER_JWKS) as {keys?: JwksKey[]};',
411
+ ' const key = jwks.keys?.find((item) => item.kid === header.kid && item.kty === "EC");',
412
+ ' if (!key) return {ok: false, status: 401, error: "invalid_token"};',
413
+ ' const cryptoKey = await crypto.subtle.importKey(',
414
+ ' "jwk",',
415
+ ' key,',
416
+ ' {name: "ECDSA", namedCurve: "P-256"},',
417
+ ' false,',
418
+ ' ["verify"]',
419
+ ' );',
420
+ ' const verified = await crypto.subtle.verify(',
421
+ ' {name: "ECDSA", hash: "SHA-256"},',
422
+ ' cryptoKey,',
423
+ ' base64UrlToBytes(encodedSignature),',
424
+ ' new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`)',
425
+ ' );',
426
+ ' return verified',
427
+ ' ? {ok: true, claims}',
428
+ ' : {ok: false, status: 401, error: "invalid_token"};',
429
+ '}',
430
+ '',
431
+ 'async function exchangeAuthorizationCode(',
432
+ ' env: Env,',
433
+ ' provider: ProviderConfig,',
434
+ ' code: string,',
435
+ ' redirectUri: string,',
436
+ ' codeVerifier: string',
437
+ '): Promise<TokenResponse> {',
438
+ ' const body = new URLSearchParams({',
439
+ ' grant_type: "authorization_code",',
440
+ ' code,',
441
+ ' redirect_uri: redirectUri,',
442
+ ' client_id: requiredEnv(env, provider.clientIdEnv),',
443
+ ' client_secret: requiredEnv(env, provider.clientSecretEnv),',
444
+ ' code_verifier: codeVerifier',
445
+ ' });',
446
+ " const response = await fetch(provider.tokenEndpoint, {",
447
+ " method: 'POST',",
448
+ " headers: {Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'},",
449
+ ' body',
450
+ ' });',
451
+ ' if (!response.ok) {',
452
+ " throw new Error(`OAuth/OIDC token exchange failed: ${response.status}`);",
453
+ ' }',
454
+ ' return (await response.json()) as TokenResponse;',
455
+ '}',
456
+ '',
457
+ 'async function loadProviderIdentity(',
458
+ ' env: Env,',
459
+ ' provider: ProviderConfig,',
460
+ ' tokenResponse: TokenResponse,',
461
+ ' expectedNonce: string | undefined',
462
+ '): Promise<Omit<SessionIdentity, "provider" | "expiresAt">> {',
463
+ ' if (tokenResponse.id_token) {',
464
+ ' const claims = await verifyOidcIdToken(env, provider, tokenResponse.id_token, expectedNonce);',
465
+ ' return {',
466
+ ' subject: providerSubject(provider, claims),',
467
+ ' name: stringClaim(claims.name),',
468
+ ' email: stringClaim(claims.email)',
469
+ ' };',
470
+ ' }',
471
+ ' if (provider.userInfoEndpoint && tokenResponse.access_token) {',
472
+ ' const response = await fetch(provider.userInfoEndpoint, {',
473
+ " headers: {Authorization: `Bearer ${tokenResponse.access_token}`, Accept: 'application/json'}",
474
+ ' });',
475
+ ' if (response.ok) {',
476
+ ' const profile = (await response.json()) as Record<string, unknown>;',
477
+ ' return {',
478
+ ' subject: providerSubject(provider, profile),',
479
+ ' name: stringClaim(profile.name) ?? stringClaim(profile.login),',
480
+ ' email: stringClaim(profile.email) ?? (await loadGithubPrimaryEmail(provider, tokenResponse.access_token))',
481
+ ' };',
482
+ ' }',
483
+ ' }',
484
+ ' return {subject: "unknown"};',
485
+ '}',
486
+ '',
487
+ 'async function verifyOidcIdToken(',
488
+ ' env: Env,',
489
+ ' provider: ProviderConfig,',
490
+ ' token: string,',
491
+ ' expectedNonce: string | undefined',
492
+ '): Promise<Record<string, unknown>> {',
493
+ ' if (!provider.usesOidc || !provider.jwksEndpoint) throw new Error("Provider does not support OIDC ID token verification.");',
494
+ ' const [encodedHeader, encodedPayload, encodedSignature] = token.split(".");',
495
+ ' if (!encodedHeader || !encodedPayload || !encodedSignature) throw new Error("Invalid OIDC ID token format.");',
496
+ ' const header = JSON.parse(base64UrlDecode(encodedHeader)) as Record<string, unknown>;',
497
+ ' const claims = JSON.parse(base64UrlDecode(encodedPayload)) as Record<string, unknown>;',
498
+ ' if (header.alg !== "RS256") throw new Error("Unsupported OIDC ID token alg.");',
499
+ ' const issuer = stringClaim(claims.iss);',
500
+ ' if (provider.issuer && issuer !== provider.issuer) throw new Error("Invalid OIDC issuer.");',
501
+ ' if (provider.issuerPrefix && !issuer?.startsWith(provider.issuerPrefix)) throw new Error("Invalid OIDC issuer.");',
502
+ ' const audience = claims.aud;',
503
+ ' const expectedAudience = requiredEnv(env, provider.clientIdEnv);',
504
+ ' const audienceMatches = Array.isArray(audience)',
505
+ ' ? audience.includes(expectedAudience)',
506
+ ' : audience === expectedAudience;',
507
+ ' if (!audienceMatches) throw new Error("Invalid OIDC audience.");',
508
+ ' const expiresAt = typeof claims.exp === "number" ? claims.exp : 0;',
509
+ ' if (expiresAt <= Math.floor(Date.now() / 1000)) throw new Error("Expired OIDC ID token.");',
510
+ ' if (!expectedNonce || claims.nonce !== expectedNonce) throw new Error("Invalid OIDC nonce.");',
511
+ ' await verifyJwtSignature(provider.jwksEndpoint, encodedHeader, encodedPayload, encodedSignature, stringClaim(header.kid));',
512
+ ' return claims;',
513
+ '}',
514
+ '',
515
+ 'async function verifyJwtSignature(',
516
+ ' jwksEndpoint: string,',
517
+ ' encodedHeader: string,',
518
+ ' encodedPayload: string,',
519
+ ' encodedSignature: string,',
520
+ ' keyId: string | undefined',
521
+ '): Promise<void> {',
522
+ ' const response = await fetch(jwksEndpoint, {headers: {Accept: "application/json"}});',
523
+ ' if (!response.ok) throw new Error(`JWKS fetch failed: ${response.status}`);',
524
+ ' const jwks = (await response.json()) as {keys?: JwksKey[]};',
525
+ ' const key = jwks.keys?.find((item) => item.kid === keyId && item.kty === "RSA");',
526
+ ' if (!key) throw new Error("OIDC signing key not found.");',
527
+ ' const cryptoKey = await crypto.subtle.importKey(',
528
+ ' "jwk",',
529
+ ' key,',
530
+ ' {name: "RSASSA-PKCS1-v1_5", hash: "SHA-256"},',
531
+ ' false,',
532
+ ' ["verify"]',
533
+ ' );',
534
+ ' const verified = await crypto.subtle.verify(',
535
+ ' "RSASSA-PKCS1-v1_5",',
536
+ ' cryptoKey,',
537
+ ' base64UrlToBytes(encodedSignature),',
538
+ ' new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`)',
539
+ ' );',
540
+ ' if (!verified) throw new Error("Invalid OIDC ID token signature.");',
541
+ '}',
542
+ '',
543
+ 'async function loadGithubPrimaryEmail(',
544
+ ' provider: ProviderConfig,',
545
+ ' accessToken: string | undefined',
546
+ '): Promise<string | undefined> {',
547
+ ' if (!provider.emailsEndpoint || !accessToken) return undefined;',
548
+ ' const response = await fetch(provider.emailsEndpoint, {',
549
+ ' headers: {Authorization: `Bearer ${accessToken}`, Accept: "application/vnd.github+json"}',
550
+ ' });',
551
+ ' if (!response.ok) return undefined;',
552
+ ' const emails = (await response.json()) as Array<Record<string, unknown>>;',
553
+ ' const primary = emails.find((email) => email.primary === true && email.verified === true);',
554
+ ' return stringClaim(primary?.email);',
555
+ '}',
556
+ '',
557
+ 'async function signSession(env: Env, identity: SessionIdentity): Promise<string> {',
558
+ ' const payload = base64UrlEncode(JSON.stringify(identity));',
559
+ " const signature = await hmacSha256(payload, requiredEnv(env, 'SESSION_SECRET'));",
560
+ ' return `${payload}.${signature}`;',
561
+ '}',
562
+ '',
563
+ 'async function readSignedSession(env: Env, cookie: string): Promise<SessionIdentity | null> {',
564
+ " const [payload, signature] = cookie.split('.');",
565
+ ' if (!payload || !signature) return null;',
566
+ " const expected = await hmacSha256(payload, requiredEnv(env, 'SESSION_SECRET'));",
567
+ ' if (signature !== expected) return null;',
568
+ ' try {',
569
+ ' const session = JSON.parse(base64UrlDecode(payload)) as SessionIdentity;',
570
+ " return typeof session.expiresAt === 'number' && session.expiresAt > Math.floor(Date.now() / 1000)",
571
+ ' ? session',
572
+ ' : null;',
573
+ ' } catch {',
574
+ ' return null;',
575
+ ' }',
576
+ '}',
577
+ '',
578
+ 'function decodeJwtPayload(token: string): Record<string, unknown> {',
579
+ " const payload = token.split('.')[1];",
580
+ ' if (!payload) return {};',
581
+ ' try {',
582
+ ' return JSON.parse(base64UrlDecode(payload)) as Record<string, unknown>;',
583
+ ' } catch {',
584
+ ' return {};',
585
+ ' }',
586
+ '}',
587
+ '',
588
+ 'async function hmacSha256(value: string, secret: string): Promise<string> {',
589
+ " const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), {name: 'HMAC', hash: 'SHA-256'}, false, ['sign']);",
590
+ " const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value));",
591
+ ' return base64UrlEncode(new Uint8Array(signature));',
592
+ '}',
593
+ '',
594
+ 'async function sha256Base64Url(value: string): Promise<string> {',
595
+ ' const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));',
596
+ ' return base64UrlEncode(new Uint8Array(digest));',
597
+ '}',
598
+ '',
599
+ 'function randomToken(): string {',
600
+ ' const bytes = new Uint8Array(32);',
601
+ ' crypto.getRandomValues(bytes);',
602
+ ' return base64UrlEncode(bytes);',
603
+ '}',
604
+ '',
605
+ 'function parseCookies(header: string): Record<string, string> {',
606
+ ' return Object.fromEntries(',
607
+ " header.split(';').flatMap((part) => {",
608
+ " const index = part.indexOf('=');",
609
+ ' if (index === -1) return [];',
610
+ ' return [[part.slice(0, index).trim(), decodeURIComponent(part.slice(index + 1))]];',
611
+ ' })',
612
+ ' );',
613
+ '}',
614
+ '',
615
+ 'function serializeCookie(',
616
+ ' name: string,',
617
+ ' value: string,',
618
+ ' options: {httpOnly?: boolean; sameSite?: "Lax" | "Strict" | "None"; secure?: boolean; path?: string; maxAge?: number}',
619
+ '): string {',
620
+ ' const parts = [`${name}=${encodeURIComponent(value)}`];',
621
+ ' if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);',
622
+ ' if (options.path) parts.push(`Path=${options.path}`);',
623
+ ' if (options.httpOnly) parts.push("HttpOnly");',
624
+ ' if (options.secure) parts.push("Secure");',
625
+ ' if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);',
626
+ " return parts.join('; ');",
627
+ '}',
628
+ '',
629
+ 'function redirectWithCookies(location: string, cookies: readonly string[]): Response {',
630
+ ' const headers = new Headers({Location: location});',
631
+ " for (const cookie of cookies) headers.append('Set-Cookie', cookie);",
632
+ ' return new Response(null, {status: 302, headers});',
633
+ '}',
634
+ '',
635
+ 'function requiredEnv(env: Env, name: string): string {',
636
+ ' const value = (env as unknown as Record<string, string | undefined>)[name];',
637
+ ' if (!value) throw new Error(`Missing required environment variable: ${name}`);',
638
+ ' return value;',
639
+ '}',
640
+ '',
641
+ 'function stringClaim(value: unknown): string | undefined {',
642
+ " return typeof value === 'string' && value.length > 0 ? value : undefined;",
643
+ '}',
644
+ '',
645
+ 'function subjectClaim(value: unknown): string | undefined {',
646
+ " if (typeof value === 'string' && value.length > 0) return value;",
647
+ ' if (typeof value === "number" && Number.isFinite(value)) return String(value);',
648
+ ' return undefined;',
649
+ '}',
650
+ '',
651
+ 'function providerSubject(provider: ProviderConfig, claims: Record<string, unknown>): string {',
652
+ ' const providerName = providerNameFromConfig(provider);',
653
+ ' const subject =',
654
+ ' subjectClaim(claims.sub) ??',
655
+ ' subjectClaim(claims.id) ??',
656
+ ' stringClaim(claims.login) ??',
657
+ ' "unknown";',
658
+ ' return `${providerName}:${subject}`;',
659
+ '}',
660
+ '',
661
+ 'function providerNameFromConfig(provider: ProviderConfig): string {',
662
+ ' const entry = Object.entries(oauthProviders).find(([, config]) => config === provider);',
663
+ ' return entry?.[0] ?? "oauth";',
664
+ '}',
665
+ '',
666
+ 'function base64UrlEncode(value: string | Uint8Array): string {',
667
+ " const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : value;",
668
+ " let binary = '';",
669
+ ' for (const byte of bytes) binary += String.fromCharCode(byte);',
670
+ " return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');",
671
+ '}',
672
+ '',
673
+ 'function base64UrlDecode(value: string): string {',
674
+ " const padded = value.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(value.length / 4) * 4, '=');",
675
+ ' const binary = atob(padded);',
676
+ ' const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));',
677
+ ' return new TextDecoder().decode(bytes);',
678
+ '}',
679
+ '',
680
+ 'function base64UrlToBytes(value: string): Uint8Array {',
681
+ " const padded = value.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(value.length / 4) * 4, '=');",
682
+ ' const binary = atob(padded);',
683
+ ' return Uint8Array.from(binary, (char) => char.charCodeAt(0));',
684
+ '}',
685
+ ''
686
+ ];
687
+ }
688
+ function createProviderMap(providers, callbackBasePath) {
689
+ const providerSet = new Set(providers ?? []);
690
+ const result = {};
691
+ if (providerSet.has('google')) {
692
+ result.google = {
693
+ authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
694
+ tokenEndpoint: 'https://oauth2.googleapis.com/token',
695
+ userInfoEndpoint: 'https://openidconnect.googleapis.com/v1/userinfo',
696
+ jwksEndpoint: 'https://www.googleapis.com/oauth2/v3/certs',
697
+ issuer: 'https://accounts.google.com',
698
+ usesOidc: true,
699
+ authorizationParams: { prompt: 'select_account' },
700
+ scopes: ['openid', 'email', 'profile'],
701
+ clientIdEnv: 'GOOGLE_CLIENT_ID',
702
+ clientSecretEnv: 'GOOGLE_CLIENT_SECRET',
703
+ callbackPath: `${callbackBasePath}/google`
704
+ };
705
+ }
706
+ if (providerSet.has('microsoft')) {
707
+ result.microsoft = {
708
+ authorizationEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
709
+ tokenEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
710
+ userInfoEndpoint: 'https://graph.microsoft.com/oidc/userinfo',
711
+ jwksEndpoint: 'https://login.microsoftonline.com/common/discovery/v2.0/keys',
712
+ issuerPrefix: 'https://login.microsoftonline.com/',
713
+ usesOidc: true,
714
+ authorizationParams: { prompt: 'select_account' },
715
+ scopes: ['openid', 'email', 'profile'],
716
+ clientIdEnv: 'MICROSOFT_CLIENT_ID',
717
+ clientSecretEnv: 'MICROSOFT_CLIENT_SECRET',
718
+ callbackPath: `${callbackBasePath}/microsoft`
719
+ };
720
+ }
721
+ if (providerSet.has('github')) {
722
+ result.github = {
723
+ authorizationEndpoint: 'https://github.com/login/oauth/authorize',
724
+ tokenEndpoint: 'https://github.com/login/oauth/access_token',
725
+ userInfoEndpoint: 'https://api.github.com/user',
726
+ emailsEndpoint: 'https://api.github.com/user/emails',
727
+ usesOidc: false,
728
+ scopes: ['read:user', 'user:email'],
729
+ clientIdEnv: 'GITHUB_CLIENT_ID',
730
+ clientSecretEnv: 'GITHUB_CLIENT_SECRET',
731
+ callbackPath: `${callbackBasePath}/github`
732
+ };
733
+ }
734
+ return result;
735
+ }
736
+ function createEnvLines(ir) {
737
+ const lines = [];
738
+ if (!ir.storage || ir.storage.length === 0) {
739
+ lines.push(' // Bindings are added when D1, KV, R2, or Durable Objects appear in the IR.');
740
+ }
741
+ else {
742
+ lines.push(...ir.storage.map((binding) => ` ${binding.binding}: ${bindingType(binding)};`));
743
+ }
744
+ if (ir.auth && ir.auth.session !== 'cloudflare-access') {
745
+ for (const provider of ir.auth.providers) {
746
+ lines.push(` ${providerEnvPrefix(provider)}_CLIENT_ID: string;`);
747
+ lines.push(` ${providerEnvPrefix(provider)}_CLIENT_SECRET: string;`);
748
+ }
749
+ lines.push(' SESSION_SECRET: string;');
750
+ }
751
+ if (ir.auth?.protectedRoutes?.some((route) => route.auth === 'bearer-jwt')) {
752
+ lines.push(' BEARER_JWKS: string;');
753
+ lines.push(' BEARER_JWT_ISSUER?: string;');
754
+ lines.push(' BEARER_JWT_AUDIENCE?: string;');
755
+ }
756
+ return lines;
757
+ }
758
+ function providerEnvPrefix(provider) {
759
+ return provider.toUpperCase();
760
+ }
761
+ function bindingType(binding) {
762
+ switch (binding.kind) {
763
+ case 'd1':
764
+ return 'D1Database';
765
+ case 'kv':
766
+ return 'KVNamespace';
767
+ case 'r2':
768
+ return 'R2Bucket';
769
+ case 'durable-object':
770
+ return 'DurableObjectNamespace';
771
+ }
772
+ }
773
+ function storageOfKind(storage, kind) {
774
+ return storage?.filter((binding) => binding.kind === kind) ?? [];
775
+ }
776
+ //# sourceMappingURL=generator.js.map