@cloudflare/workers-oauth-provider 0.0.0-0982a1c

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,1579 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+
9
+ // src/oauth-provider.ts
10
+ import { WorkerEntrypoint } from "cloudflare:workers";
11
+ var _impl;
12
+ var OAuthProvider = class {
13
+ /**
14
+ * Creates a new OAuth provider instance
15
+ * @param options - Configuration options for the provider
16
+ */
17
+ constructor(options) {
18
+ __privateAdd(this, _impl);
19
+ __privateSet(this, _impl, new OAuthProviderImpl(options));
20
+ }
21
+ /**
22
+ * Main fetch handler for the Worker
23
+ * Routes requests to the appropriate handler based on the URL
24
+ * @param request - The HTTP request
25
+ * @param env - Cloudflare Worker environment variables
26
+ * @param ctx - Cloudflare Worker execution context
27
+ * @returns A Promise resolving to an HTTP Response
28
+ */
29
+ fetch(request, env, ctx) {
30
+ return __privateGet(this, _impl).fetch(request, env, ctx);
31
+ }
32
+ };
33
+ _impl = new WeakMap();
34
+ var OAuthProviderImpl = class {
35
+ /**
36
+ * Creates a new OAuth provider instance
37
+ * @param options - Configuration options for the provider
38
+ */
39
+ constructor(options) {
40
+ this.typedApiHandlers = [];
41
+ const hasSingleHandlerConfig = !!(options.apiRoute && options.apiHandler);
42
+ const hasMultiHandlerConfig = !!options.apiHandlers;
43
+ if (hasSingleHandlerConfig && hasMultiHandlerConfig) {
44
+ throw new TypeError(
45
+ "Cannot use both apiRoute/apiHandler and apiHandlers. Use either apiRoute + apiHandler OR apiHandlers, not both."
46
+ );
47
+ }
48
+ if (!hasSingleHandlerConfig && !hasMultiHandlerConfig) {
49
+ throw new TypeError(
50
+ "Must provide either apiRoute + apiHandler OR apiHandlers. No API route configuration provided."
51
+ );
52
+ }
53
+ this.typedDefaultHandler = this.validateHandler(options.defaultHandler, "defaultHandler");
54
+ if (hasSingleHandlerConfig) {
55
+ const apiHandler = this.validateHandler(options.apiHandler, "apiHandler");
56
+ if (Array.isArray(options.apiRoute)) {
57
+ options.apiRoute.forEach((route, index) => {
58
+ this.validateEndpoint(route, `apiRoute[${index}]`);
59
+ this.typedApiHandlers.push([route, apiHandler]);
60
+ });
61
+ } else {
62
+ this.validateEndpoint(options.apiRoute, "apiRoute");
63
+ this.typedApiHandlers.push([options.apiRoute, apiHandler]);
64
+ }
65
+ } else {
66
+ for (const [route, handler] of Object.entries(options.apiHandlers)) {
67
+ this.validateEndpoint(route, `apiHandlers key: ${route}`);
68
+ this.typedApiHandlers.push([route, this.validateHandler(handler, `apiHandlers[${route}]`)]);
69
+ }
70
+ }
71
+ this.validateEndpoint(options.authorizeEndpoint, "authorizeEndpoint");
72
+ this.validateEndpoint(options.tokenEndpoint, "tokenEndpoint");
73
+ if (options.clientRegistrationEndpoint) {
74
+ this.validateEndpoint(options.clientRegistrationEndpoint, "clientRegistrationEndpoint");
75
+ }
76
+ this.options = {
77
+ accessTokenTTL: DEFAULT_ACCESS_TOKEN_TTL,
78
+ onError: ({ status, code, description }) => console.warn(`OAuth error response: ${status} ${code} - ${description}`),
79
+ ...options
80
+ };
81
+ }
82
+ /**
83
+ * Validates that an endpoint is either an absolute path or a full URL
84
+ * @param endpoint - The endpoint to validate
85
+ * @param name - The name of the endpoint property for error messages
86
+ * @throws TypeError if the endpoint is invalid
87
+ */
88
+ validateEndpoint(endpoint, name) {
89
+ if (this.isPath(endpoint)) {
90
+ if (!endpoint.startsWith("/")) {
91
+ throw new TypeError(`${name} path must be an absolute path starting with /`);
92
+ }
93
+ } else {
94
+ try {
95
+ new URL(endpoint);
96
+ } catch (e) {
97
+ throw new TypeError(`${name} must be either an absolute path starting with / or a valid URL`);
98
+ }
99
+ }
100
+ }
101
+ /**
102
+ * Validates that a handler is either an ExportedHandler or a class extending WorkerEntrypoint
103
+ * @param handler - The handler to validate
104
+ * @param name - The name of the handler property for error messages
105
+ * @returns The type of the handler (EXPORTED_HANDLER or WORKER_ENTRYPOINT)
106
+ * @throws TypeError if the handler is invalid
107
+ */
108
+ validateHandler(handler, name) {
109
+ if (typeof handler === "object" && handler !== null && typeof handler.fetch === "function") {
110
+ return { type: 0 /* EXPORTED_HANDLER */, handler };
111
+ }
112
+ if (typeof handler === "function" && handler.prototype instanceof WorkerEntrypoint) {
113
+ return { type: 1 /* WORKER_ENTRYPOINT */, handler };
114
+ }
115
+ throw new TypeError(
116
+ `${name} must be either an ExportedHandler object with a fetch method or a class extending WorkerEntrypoint`
117
+ );
118
+ }
119
+ /**
120
+ * Main fetch handler for the Worker
121
+ * Routes requests to the appropriate handler based on the URL
122
+ * @param request - The HTTP request
123
+ * @param env - Cloudflare Worker environment variables
124
+ * @param ctx - Cloudflare Worker execution context
125
+ * @returns A Promise resolving to an HTTP Response
126
+ */
127
+ async fetch(request, env, ctx) {
128
+ const url = new URL(request.url);
129
+ if (request.method === "OPTIONS") {
130
+ if (this.isApiRequest(url) || url.pathname === "/.well-known/oauth-authorization-server" || this.isTokenEndpoint(url) || this.options.clientRegistrationEndpoint && this.isClientRegistrationEndpoint(url)) {
131
+ return this.addCorsHeaders(
132
+ new Response(null, {
133
+ status: 204,
134
+ headers: { "Content-Length": "0" }
135
+ }),
136
+ request
137
+ );
138
+ }
139
+ }
140
+ if (url.pathname === "/.well-known/oauth-authorization-server") {
141
+ const response = await this.handleMetadataDiscovery(url);
142
+ return this.addCorsHeaders(response, request);
143
+ }
144
+ if (this.isTokenEndpoint(url)) {
145
+ const parsed = await this.parseTokenEndpointRequest(request, env);
146
+ if (parsed instanceof Response) {
147
+ return this.addCorsHeaders(parsed, request);
148
+ }
149
+ let response;
150
+ if (parsed.isRevocationRequest) {
151
+ response = await this.handleRevocationRequest(parsed.body, env);
152
+ } else {
153
+ response = await this.handleTokenRequest(parsed.body, parsed.clientInfo, env);
154
+ }
155
+ return this.addCorsHeaders(response, request);
156
+ }
157
+ if (this.options.clientRegistrationEndpoint && this.isClientRegistrationEndpoint(url)) {
158
+ const response = await this.handleClientRegistration(request, env);
159
+ return this.addCorsHeaders(response, request);
160
+ }
161
+ if (this.isApiRequest(url)) {
162
+ const response = await this.handleApiRequest(request, env, ctx);
163
+ return this.addCorsHeaders(response, request);
164
+ }
165
+ if (!env.OAUTH_PROVIDER) {
166
+ env.OAUTH_PROVIDER = this.createOAuthHelpers(env);
167
+ }
168
+ if (this.typedDefaultHandler.type === 0 /* EXPORTED_HANDLER */) {
169
+ return this.typedDefaultHandler.handler.fetch(
170
+ request,
171
+ env,
172
+ ctx
173
+ );
174
+ } else {
175
+ const handler = new this.typedDefaultHandler.handler(ctx, env);
176
+ return handler.fetch(request);
177
+ }
178
+ }
179
+ /**
180
+ * Determines if an endpoint configuration is a path or a full URL
181
+ * @param endpoint - The endpoint configuration
182
+ * @returns True if the endpoint is a path (starts with /), false if it's a full URL
183
+ */
184
+ isPath(endpoint) {
185
+ return endpoint.startsWith("/");
186
+ }
187
+ /**
188
+ * Matches a URL against an endpoint pattern that can be a full URL or just a path
189
+ * @param url - The URL to check
190
+ * @param endpoint - The endpoint pattern (full URL or path)
191
+ * @returns True if the URL matches the endpoint pattern
192
+ */
193
+ matchEndpoint(url, endpoint) {
194
+ if (this.isPath(endpoint)) {
195
+ return url.pathname === endpoint;
196
+ } else {
197
+ const endpointUrl = new URL(endpoint);
198
+ return url.hostname === endpointUrl.hostname && url.pathname === endpointUrl.pathname;
199
+ }
200
+ }
201
+ /**
202
+ * Checks if a URL matches the configured token endpoint
203
+ * @param url - The URL to check
204
+ * @returns True if the URL matches the token endpoint
205
+ */
206
+ isTokenEndpoint(url) {
207
+ return this.matchEndpoint(url, this.options.tokenEndpoint);
208
+ }
209
+ /**
210
+ * Checks if a URL matches the configured client registration endpoint
211
+ * @param url - The URL to check
212
+ * @returns True if the URL matches the client registration endpoint
213
+ */
214
+ isClientRegistrationEndpoint(url) {
215
+ if (!this.options.clientRegistrationEndpoint) return false;
216
+ return this.matchEndpoint(url, this.options.clientRegistrationEndpoint);
217
+ }
218
+ /**
219
+ * Parses and validates a token endpoint request (used for both token exchange and revocation)
220
+ * @param request - The HTTP request to parse
221
+ * @returns Promise with parsed body and client info, or error response
222
+ */
223
+ async parseTokenEndpointRequest(request, env) {
224
+ if (request.method !== "POST") {
225
+ return this.createErrorResponse("invalid_request", "Method not allowed", 405);
226
+ }
227
+ let contentType = request.headers.get("Content-Type") || "";
228
+ let body = {};
229
+ if (!contentType.includes("application/x-www-form-urlencoded")) {
230
+ return this.createErrorResponse("invalid_request", "Content-Type must be application/x-www-form-urlencoded", 400);
231
+ }
232
+ const formData = await request.formData();
233
+ for (const [key, value] of formData.entries()) {
234
+ body[key] = value;
235
+ }
236
+ const authHeader = request.headers.get("Authorization");
237
+ let clientId = "";
238
+ let clientSecret = "";
239
+ if (authHeader && authHeader.startsWith("Basic ")) {
240
+ const credentials = atob(authHeader.substring(6));
241
+ const [id, secret] = credentials.split(":", 2);
242
+ clientId = decodeURIComponent(id);
243
+ clientSecret = decodeURIComponent(secret || "");
244
+ } else {
245
+ clientId = body.client_id;
246
+ clientSecret = body.client_secret || "";
247
+ }
248
+ if (!clientId) {
249
+ return this.createErrorResponse("invalid_client", "Client ID is required", 401);
250
+ }
251
+ const clientInfo = await this.getClient(env, clientId);
252
+ if (!clientInfo) {
253
+ return this.createErrorResponse("invalid_client", "Client not found", 401);
254
+ }
255
+ const isPublicClient = clientInfo.tokenEndpointAuthMethod === "none";
256
+ if (!isPublicClient) {
257
+ if (!clientSecret) {
258
+ return this.createErrorResponse("invalid_client", "Client authentication failed: missing client_secret", 401);
259
+ }
260
+ if (!clientInfo.clientSecret) {
261
+ return this.createErrorResponse(
262
+ "invalid_client",
263
+ "Client authentication failed: client has no registered secret",
264
+ 401
265
+ );
266
+ }
267
+ const providedSecretHash = await hashSecret(clientSecret);
268
+ if (providedSecretHash !== clientInfo.clientSecret) {
269
+ return this.createErrorResponse("invalid_client", "Client authentication failed: invalid client_secret", 401);
270
+ }
271
+ }
272
+ const isRevocationRequest = !body.grant_type && !!body.token;
273
+ return {
274
+ body,
275
+ clientInfo,
276
+ isRevocationRequest
277
+ };
278
+ }
279
+ /**
280
+ * Checks if a URL matches a specific API route
281
+ * @param url - The URL to check
282
+ * @param route - The API route to check against
283
+ * @returns True if the URL matches the API route
284
+ */
285
+ matchApiRoute(url, route) {
286
+ if (this.isPath(route)) {
287
+ return url.pathname.startsWith(route);
288
+ } else {
289
+ const apiUrl = new URL(route);
290
+ return url.hostname === apiUrl.hostname && url.pathname.startsWith(apiUrl.pathname);
291
+ }
292
+ }
293
+ /**
294
+ * Checks if a URL is an API request based on the configured API route(s)
295
+ * @param url - The URL to check
296
+ * @returns True if the URL matches any of the API routes
297
+ */
298
+ isApiRequest(url) {
299
+ for (const [route, _] of this.typedApiHandlers) {
300
+ if (this.matchApiRoute(url, route)) {
301
+ return true;
302
+ }
303
+ }
304
+ return false;
305
+ }
306
+ /**
307
+ * Finds the appropriate API handler for a URL
308
+ * @param url - The URL to find a handler for
309
+ * @returns The TypedHandler for the URL, or undefined if no handler matches
310
+ */
311
+ findApiHandlerForUrl(url) {
312
+ for (const [route, handler] of this.typedApiHandlers) {
313
+ if (this.matchApiRoute(url, route)) {
314
+ return handler;
315
+ }
316
+ }
317
+ return void 0;
318
+ }
319
+ /**
320
+ * Gets the full URL for an endpoint, using the provided request URL's
321
+ * origin for endpoints specified as just paths
322
+ * @param endpoint - The endpoint configuration (path or full URL)
323
+ * @param requestUrl - The URL of the incoming request
324
+ * @returns The full URL for the endpoint
325
+ */
326
+ getFullEndpointUrl(endpoint, requestUrl) {
327
+ if (this.isPath(endpoint)) {
328
+ return `${requestUrl.origin}${endpoint}`;
329
+ } else {
330
+ return endpoint;
331
+ }
332
+ }
333
+ /**
334
+ * Adds CORS headers to a response
335
+ * @param response - The response to add CORS headers to
336
+ * @param request - The original request
337
+ * @returns A new Response with CORS headers added
338
+ */
339
+ addCorsHeaders(response, request) {
340
+ const origin = request.headers.get("Origin");
341
+ if (!origin) {
342
+ return response;
343
+ }
344
+ const newResponse = new Response(response.body, response);
345
+ newResponse.headers.set("Access-Control-Allow-Origin", origin);
346
+ newResponse.headers.set("Access-Control-Allow-Methods", "*");
347
+ newResponse.headers.set("Access-Control-Allow-Headers", "Authorization, *");
348
+ newResponse.headers.set("Access-Control-Max-Age", "86400");
349
+ return newResponse;
350
+ }
351
+ /**
352
+ * Handles the OAuth metadata discovery endpoint
353
+ * Implements RFC 8414 for OAuth Server Metadata
354
+ * @param requestUrl - The URL of the incoming request
355
+ * @returns Response with OAuth server metadata
356
+ */
357
+ async handleMetadataDiscovery(requestUrl) {
358
+ const tokenEndpoint = this.getFullEndpointUrl(this.options.tokenEndpoint, requestUrl);
359
+ const authorizeEndpoint = this.getFullEndpointUrl(this.options.authorizeEndpoint, requestUrl);
360
+ let registrationEndpoint = void 0;
361
+ if (this.options.clientRegistrationEndpoint) {
362
+ registrationEndpoint = this.getFullEndpointUrl(this.options.clientRegistrationEndpoint, requestUrl);
363
+ }
364
+ const responseTypesSupported = ["code"];
365
+ if (this.options.allowImplicitFlow) {
366
+ responseTypesSupported.push("token");
367
+ }
368
+ const metadata = {
369
+ issuer: new URL(tokenEndpoint).origin,
370
+ authorization_endpoint: authorizeEndpoint,
371
+ token_endpoint: tokenEndpoint,
372
+ // not implemented: jwks_uri
373
+ registration_endpoint: registrationEndpoint,
374
+ scopes_supported: this.options.scopesSupported,
375
+ response_types_supported: responseTypesSupported,
376
+ response_modes_supported: ["query"],
377
+ grant_types_supported: ["authorization_code", "refresh_token"],
378
+ // Support "none" auth method for public clients
379
+ token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],
380
+ // not implemented: token_endpoint_auth_signing_alg_values_supported
381
+ // not implemented: service_documentation
382
+ // not implemented: ui_locales_supported
383
+ // not implemented: op_policy_uri
384
+ // not implemented: op_tos_uri
385
+ revocation_endpoint: tokenEndpoint,
386
+ // Reusing token endpoint for revocation
387
+ // not implemented: revocation_endpoint_auth_methods_supported
388
+ // not implemented: revocation_endpoint_auth_signing_alg_values_supported
389
+ // not implemented: introspection_endpoint
390
+ // not implemented: introspection_endpoint_auth_methods_supported
391
+ // not implemented: introspection_endpoint_auth_signing_alg_values_supported
392
+ code_challenge_methods_supported: ["plain", "S256"]
393
+ // PKCE support
394
+ };
395
+ return new Response(JSON.stringify(metadata), {
396
+ headers: { "Content-Type": "application/json" }
397
+ });
398
+ }
399
+ /**
400
+ * Handles client authentication and token issuance via the token endpoint
401
+ * Supports authorization_code and refresh_token grant types
402
+ * @param body - The parsed request body
403
+ * @param clientInfo - The authenticated client information
404
+ * @param env - Cloudflare Worker environment variables
405
+ * @returns Response with token data or error
406
+ */
407
+ async handleTokenRequest(body, clientInfo, env) {
408
+ const grantType = body.grant_type;
409
+ if (grantType === "authorization_code") {
410
+ return this.handleAuthorizationCodeGrant(body, clientInfo, env);
411
+ } else if (grantType === "refresh_token") {
412
+ return this.handleRefreshTokenGrant(body, clientInfo, env);
413
+ } else {
414
+ return this.createErrorResponse("unsupported_grant_type", "Grant type not supported");
415
+ }
416
+ }
417
+ /**
418
+ * Handles the authorization code grant type
419
+ * Exchanges an authorization code for access and refresh tokens
420
+ * @param body - The parsed request body
421
+ * @param clientInfo - The authenticated client information
422
+ * @param env - Cloudflare Worker environment variables
423
+ * @returns Response with token data or error
424
+ */
425
+ async handleAuthorizationCodeGrant(body, clientInfo, env) {
426
+ const code = body.code;
427
+ const redirectUri = body.redirect_uri;
428
+ const codeVerifier = body.code_verifier;
429
+ if (!code) {
430
+ return this.createErrorResponse("invalid_request", "Authorization code is required");
431
+ }
432
+ const codeParts = code.split(":");
433
+ if (codeParts.length !== 3) {
434
+ return this.createErrorResponse("invalid_grant", "Invalid authorization code format");
435
+ }
436
+ const [userId, grantId, _] = codeParts;
437
+ const grantKey = `grant:${userId}:${grantId}`;
438
+ const grantData = await env.OAUTH_KV.get(grantKey, { type: "json" });
439
+ if (!grantData) {
440
+ return this.createErrorResponse("invalid_grant", "Grant not found or authorization code expired");
441
+ }
442
+ if (!grantData.authCodeId) {
443
+ return this.createErrorResponse("invalid_grant", "Authorization code already used");
444
+ }
445
+ const codeHash = await hashSecret(code);
446
+ if (codeHash !== grantData.authCodeId) {
447
+ return this.createErrorResponse("invalid_grant", "Invalid authorization code");
448
+ }
449
+ if (grantData.clientId !== clientInfo.clientId) {
450
+ return this.createErrorResponse("invalid_grant", "Client ID mismatch");
451
+ }
452
+ const isPkceEnabled = !!grantData.codeChallenge;
453
+ if (!redirectUri && !isPkceEnabled) {
454
+ return this.createErrorResponse("invalid_request", "redirect_uri is required when not using PKCE");
455
+ }
456
+ if (redirectUri && !clientInfo.redirectUris.includes(redirectUri)) {
457
+ return this.createErrorResponse("invalid_grant", "Invalid redirect URI");
458
+ }
459
+ if (!isPkceEnabled && codeVerifier) {
460
+ return this.createErrorResponse("invalid_request", "code_verifier provided for a flow that did not use PKCE");
461
+ }
462
+ if (isPkceEnabled) {
463
+ if (!codeVerifier) {
464
+ return this.createErrorResponse("invalid_request", "code_verifier is required for PKCE");
465
+ }
466
+ let calculatedChallenge;
467
+ if (grantData.codeChallengeMethod === "S256") {
468
+ const encoder = new TextEncoder();
469
+ const data = encoder.encode(codeVerifier);
470
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
471
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
472
+ calculatedChallenge = base64UrlEncode(String.fromCharCode(...hashArray));
473
+ } else {
474
+ calculatedChallenge = codeVerifier;
475
+ }
476
+ if (calculatedChallenge !== grantData.codeChallenge) {
477
+ return this.createErrorResponse("invalid_grant", "Invalid PKCE code_verifier");
478
+ }
479
+ }
480
+ const accessTokenSecret = generateRandomString(TOKEN_LENGTH);
481
+ const accessToken = `${userId}:${grantId}:${accessTokenSecret}`;
482
+ const accessTokenId = await generateTokenId(accessToken);
483
+ let accessTokenTTL = this.options.accessTokenTTL;
484
+ let refreshTokenTTL = this.options.refreshTokenTTL;
485
+ const encryptionKey = await unwrapKeyWithToken(code, grantData.authCodeWrappedKey);
486
+ let grantEncryptionKey = encryptionKey;
487
+ let accessTokenEncryptionKey = encryptionKey;
488
+ let encryptedAccessTokenProps = grantData.encryptedProps;
489
+ if (this.options.tokenExchangeCallback) {
490
+ const decryptedProps = await decryptProps(encryptionKey, grantData.encryptedProps);
491
+ let grantProps = decryptedProps;
492
+ let accessTokenProps = decryptedProps;
493
+ const callbackOptions = {
494
+ grantType: "authorization_code",
495
+ clientId: clientInfo.clientId,
496
+ userId,
497
+ scope: grantData.scope,
498
+ props: decryptedProps
499
+ };
500
+ const callbackResult = await Promise.resolve(this.options.tokenExchangeCallback(callbackOptions));
501
+ if (callbackResult) {
502
+ if (callbackResult.newProps) {
503
+ grantProps = callbackResult.newProps;
504
+ if (!callbackResult.accessTokenProps) {
505
+ accessTokenProps = callbackResult.newProps;
506
+ }
507
+ }
508
+ if (callbackResult.accessTokenProps) {
509
+ accessTokenProps = callbackResult.accessTokenProps;
510
+ }
511
+ if (callbackResult.accessTokenTTL !== void 0) {
512
+ accessTokenTTL = callbackResult.accessTokenTTL;
513
+ }
514
+ if ("refreshTokenTTL" in callbackResult) {
515
+ refreshTokenTTL = callbackResult.refreshTokenTTL;
516
+ }
517
+ }
518
+ const grantResult = await encryptProps(grantProps);
519
+ grantData.encryptedProps = grantResult.encryptedData;
520
+ grantEncryptionKey = grantResult.key;
521
+ if (accessTokenProps !== grantProps) {
522
+ const tokenResult = await encryptProps(accessTokenProps);
523
+ encryptedAccessTokenProps = tokenResult.encryptedData;
524
+ accessTokenEncryptionKey = tokenResult.key;
525
+ } else {
526
+ encryptedAccessTokenProps = grantData.encryptedProps;
527
+ accessTokenEncryptionKey = grantEncryptionKey;
528
+ }
529
+ }
530
+ const now = Math.floor(Date.now() / 1e3);
531
+ const accessTokenExpiresAt = now + accessTokenTTL;
532
+ const useRefreshToken = refreshTokenTTL !== 0;
533
+ const accessTokenWrappedKey = await wrapKeyWithToken(accessToken, accessTokenEncryptionKey);
534
+ delete grantData.authCodeId;
535
+ delete grantData.codeChallenge;
536
+ delete grantData.codeChallengeMethod;
537
+ delete grantData.authCodeWrappedKey;
538
+ let refreshToken;
539
+ if (useRefreshToken) {
540
+ const refreshTokenSecret = generateRandomString(TOKEN_LENGTH);
541
+ refreshToken = `${userId}:${grantId}:${refreshTokenSecret}`;
542
+ const refreshTokenId = await generateTokenId(refreshToken);
543
+ const refreshTokenWrappedKey = await wrapKeyWithToken(refreshToken, grantEncryptionKey);
544
+ const expiresAt = refreshTokenTTL !== void 0 ? now + refreshTokenTTL : void 0;
545
+ grantData.refreshTokenId = refreshTokenId;
546
+ grantData.refreshTokenWrappedKey = refreshTokenWrappedKey;
547
+ grantData.previousRefreshTokenId = void 0;
548
+ grantData.previousRefreshTokenWrappedKey = void 0;
549
+ grantData.expiresAt = expiresAt;
550
+ }
551
+ await this.saveGrantWithTTL(env, grantKey, grantData, now);
552
+ const accessTokenData = {
553
+ id: accessTokenId,
554
+ grantId,
555
+ userId,
556
+ createdAt: now,
557
+ expiresAt: accessTokenExpiresAt,
558
+ wrappedEncryptionKey: accessTokenWrappedKey,
559
+ grant: {
560
+ clientId: grantData.clientId,
561
+ scope: grantData.scope,
562
+ encryptedProps: encryptedAccessTokenProps
563
+ }
564
+ };
565
+ await env.OAUTH_KV.put(`token:${userId}:${grantId}:${accessTokenId}`, JSON.stringify(accessTokenData), {
566
+ expirationTtl: accessTokenTTL
567
+ });
568
+ const tokenResponse = {
569
+ access_token: accessToken,
570
+ token_type: "bearer",
571
+ expires_in: accessTokenTTL,
572
+ scope: grantData.scope.join(" ")
573
+ };
574
+ if (refreshToken) {
575
+ tokenResponse.refresh_token = refreshToken;
576
+ }
577
+ return new Response(JSON.stringify(tokenResponse), {
578
+ headers: { "Content-Type": "application/json" }
579
+ });
580
+ }
581
+ /**
582
+ * Handles the refresh token grant type
583
+ * Issues a new access token using a refresh token
584
+ * @param body - The parsed request body
585
+ * @param clientInfo - The authenticated client information
586
+ * @param env - Cloudflare Worker environment variables
587
+ * @returns Response with token data or error
588
+ */
589
+ async handleRefreshTokenGrant(body, clientInfo, env) {
590
+ const refreshToken = body.refresh_token;
591
+ if (!refreshToken) {
592
+ return this.createErrorResponse("invalid_request", "Refresh token is required");
593
+ }
594
+ const tokenParts = refreshToken.split(":");
595
+ if (tokenParts.length !== 3) {
596
+ return this.createErrorResponse("invalid_grant", "Invalid token format");
597
+ }
598
+ const [userId, grantId, _] = tokenParts;
599
+ const providedTokenHash = await generateTokenId(refreshToken);
600
+ const grantKey = `grant:${userId}:${grantId}`;
601
+ const grantData = await env.OAUTH_KV.get(grantKey, { type: "json" });
602
+ if (!grantData) {
603
+ return this.createErrorResponse("invalid_grant", "Grant not found");
604
+ }
605
+ const isCurrentToken = grantData.refreshTokenId === providedTokenHash;
606
+ const isPreviousToken = grantData.previousRefreshTokenId === providedTokenHash;
607
+ if (!isCurrentToken && !isPreviousToken) {
608
+ return this.createErrorResponse("invalid_grant", "Invalid refresh token");
609
+ }
610
+ if (grantData.clientId !== clientInfo.clientId) {
611
+ return this.createErrorResponse("invalid_grant", "Client ID mismatch");
612
+ }
613
+ if (grantData.expiresAt !== void 0) {
614
+ const now2 = Math.floor(Date.now() / 1e3);
615
+ if (now2 >= grantData.expiresAt) {
616
+ return this.createErrorResponse("invalid_grant", "Refresh token has expired");
617
+ }
618
+ }
619
+ const accessTokenSecret = generateRandomString(TOKEN_LENGTH);
620
+ const newAccessToken = `${userId}:${grantId}:${accessTokenSecret}`;
621
+ const accessTokenId = await generateTokenId(newAccessToken);
622
+ let accessTokenTTL = this.options.accessTokenTTL;
623
+ let wrappedKeyToUse;
624
+ if (isCurrentToken) {
625
+ wrappedKeyToUse = grantData.refreshTokenWrappedKey;
626
+ } else {
627
+ wrappedKeyToUse = grantData.previousRefreshTokenWrappedKey;
628
+ }
629
+ const encryptionKey = await unwrapKeyWithToken(refreshToken, wrappedKeyToUse);
630
+ let grantEncryptionKey = encryptionKey;
631
+ let accessTokenEncryptionKey = encryptionKey;
632
+ let encryptedAccessTokenProps = grantData.encryptedProps;
633
+ let grantPropsChanged = false;
634
+ if (this.options.tokenExchangeCallback) {
635
+ const decryptedProps = await decryptProps(encryptionKey, grantData.encryptedProps);
636
+ let grantProps = decryptedProps;
637
+ let accessTokenProps = decryptedProps;
638
+ const callbackOptions = {
639
+ grantType: "refresh_token",
640
+ clientId: clientInfo.clientId,
641
+ userId,
642
+ scope: grantData.scope,
643
+ props: decryptedProps
644
+ };
645
+ const callbackResult = await Promise.resolve(this.options.tokenExchangeCallback(callbackOptions));
646
+ if (callbackResult) {
647
+ if (callbackResult.newProps) {
648
+ grantProps = callbackResult.newProps;
649
+ grantPropsChanged = true;
650
+ if (!callbackResult.accessTokenProps) {
651
+ accessTokenProps = callbackResult.newProps;
652
+ }
653
+ }
654
+ if (callbackResult.accessTokenProps) {
655
+ accessTokenProps = callbackResult.accessTokenProps;
656
+ }
657
+ if (callbackResult.accessTokenTTL !== void 0) {
658
+ accessTokenTTL = callbackResult.accessTokenTTL;
659
+ }
660
+ if ("refreshTokenTTL" in callbackResult) {
661
+ return this.createErrorResponse(
662
+ "invalid_request",
663
+ "refreshTokenTTL cannot be changed during refresh token exchange"
664
+ );
665
+ }
666
+ }
667
+ if (grantPropsChanged) {
668
+ const grantResult = await encryptProps(grantProps);
669
+ grantData.encryptedProps = grantResult.encryptedData;
670
+ if (grantResult.key !== encryptionKey) {
671
+ grantEncryptionKey = grantResult.key;
672
+ wrappedKeyToUse = await wrapKeyWithToken(refreshToken, grantEncryptionKey);
673
+ } else {
674
+ grantEncryptionKey = grantResult.key;
675
+ }
676
+ }
677
+ if (accessTokenProps !== grantProps) {
678
+ const tokenResult = await encryptProps(accessTokenProps);
679
+ encryptedAccessTokenProps = tokenResult.encryptedData;
680
+ accessTokenEncryptionKey = tokenResult.key;
681
+ } else {
682
+ encryptedAccessTokenProps = grantData.encryptedProps;
683
+ accessTokenEncryptionKey = grantEncryptionKey;
684
+ }
685
+ }
686
+ const now = Math.floor(Date.now() / 1e3);
687
+ if (grantData.expiresAt !== void 0) {
688
+ const remainingRefreshTokenLifetime = grantData.expiresAt - now;
689
+ if (remainingRefreshTokenLifetime > 0) {
690
+ accessTokenTTL = Math.min(accessTokenTTL, remainingRefreshTokenLifetime);
691
+ }
692
+ }
693
+ const accessTokenExpiresAt = now + accessTokenTTL;
694
+ const accessTokenWrappedKey = await wrapKeyWithToken(newAccessToken, accessTokenEncryptionKey);
695
+ const refreshTokenSecret = generateRandomString(TOKEN_LENGTH);
696
+ const newRefreshToken = `${userId}:${grantId}:${refreshTokenSecret}`;
697
+ const newRefreshTokenId = await generateTokenId(newRefreshToken);
698
+ const newRefreshTokenWrappedKey = await wrapKeyWithToken(newRefreshToken, grantEncryptionKey);
699
+ grantData.previousRefreshTokenId = providedTokenHash;
700
+ grantData.previousRefreshTokenWrappedKey = wrappedKeyToUse;
701
+ grantData.refreshTokenId = newRefreshTokenId;
702
+ grantData.refreshTokenWrappedKey = newRefreshTokenWrappedKey;
703
+ await this.saveGrantWithTTL(env, grantKey, grantData, now);
704
+ const accessTokenData = {
705
+ id: accessTokenId,
706
+ grantId,
707
+ userId,
708
+ createdAt: now,
709
+ expiresAt: accessTokenExpiresAt,
710
+ wrappedEncryptionKey: accessTokenWrappedKey,
711
+ grant: {
712
+ clientId: grantData.clientId,
713
+ scope: grantData.scope,
714
+ encryptedProps: encryptedAccessTokenProps
715
+ }
716
+ };
717
+ await env.OAUTH_KV.put(`token:${userId}:${grantId}:${accessTokenId}`, JSON.stringify(accessTokenData), {
718
+ expirationTtl: accessTokenTTL
719
+ });
720
+ const tokenResponse = {
721
+ access_token: newAccessToken,
722
+ token_type: "bearer",
723
+ expires_in: accessTokenTTL,
724
+ refresh_token: newRefreshToken,
725
+ scope: grantData.scope.join(" ")
726
+ };
727
+ return new Response(JSON.stringify(tokenResponse), {
728
+ headers: { "Content-Type": "application/json" }
729
+ });
730
+ }
731
+ /**
732
+ * Handles OAuth 2.0 token revocation requests (RFC 7009)
733
+ * @param body - The parsed request body containing revocation parameters
734
+ * @param env - Cloudflare Worker environment variables
735
+ * @returns Response confirming revocation or error
736
+ */
737
+ async handleRevocationRequest(body, env) {
738
+ return this.revokeToken(body, env);
739
+ }
740
+ /**
741
+ * - Access tokens: Revokes only the specific token
742
+ * - Refresh tokens: Revokes the entire grant (access + refresh tokens)
743
+ * @param body - The parsed request body containing token parameter
744
+ * @param env - Cloudflare Worker environment variables
745
+ * @returns Response confirming revocation or error
746
+ */
747
+ async revokeToken(body, env) {
748
+ const token = body.token;
749
+ if (!token) {
750
+ return this.createErrorResponse("invalid_request", "Token parameter is required");
751
+ }
752
+ const tokenParts = token.split(":");
753
+ if (tokenParts.length !== 3) {
754
+ return new Response("", { status: 200 });
755
+ }
756
+ const [userId, grantId, _] = tokenParts;
757
+ const tokenId = await generateTokenId(token);
758
+ const isAccessToken = await this.validateAccessToken(tokenId, userId, grantId, env);
759
+ const isRefreshToken = await this.validateRefreshToken(tokenId, userId, grantId, env);
760
+ if (isAccessToken) {
761
+ await this.revokeSpecificAccessToken(tokenId, userId, grantId, env);
762
+ } else if (isRefreshToken) {
763
+ await this.createOAuthHelpers(env).revokeGrant(grantId, userId);
764
+ }
765
+ return new Response("", { status: 200 });
766
+ }
767
+ /**
768
+ * Revokes a specific access token without affecting the refresh token
769
+ * @param tokenId - The hashed token ID
770
+ * @param userId - The user ID extracted from the token
771
+ * @param grantId - The grant ID extracted from the token
772
+ * @param env - Cloudflare Worker environment variables
773
+ */
774
+ async revokeSpecificAccessToken(tokenId, userId, grantId, env) {
775
+ const tokenKey = `token:${userId}:${grantId}:${tokenId}`;
776
+ await env.OAUTH_KV.delete(tokenKey);
777
+ }
778
+ /**
779
+ * Validates if a token is a valid access token
780
+ * @param tokenId - The hashed token ID
781
+ * @param userId - The user ID extracted from the token
782
+ * @param grantId - The grant ID extracted from the token
783
+ * @param env - Cloudflare Worker environment variables
784
+ * @returns Promise<boolean> indicating if the token is valid
785
+ */
786
+ async validateAccessToken(tokenId, userId, grantId, env) {
787
+ const tokenKey = `token:${userId}:${grantId}:${tokenId}`;
788
+ const tokenData = await env.OAUTH_KV.get(tokenKey, { type: "json" });
789
+ if (!tokenData) {
790
+ return false;
791
+ }
792
+ const now = Math.floor(Date.now() / 1e3);
793
+ return tokenData.expiresAt >= now;
794
+ }
795
+ /**
796
+ * Validates if a token is a valid refresh token
797
+ * @param tokenId - The hashed token ID
798
+ * @param userId - The user ID extracted from the token
799
+ * @param grantId - The grant ID extracted from the token
800
+ * @param env - Cloudflare Worker environment variables
801
+ * @returns Promise<boolean> indicating if the token is valid
802
+ */
803
+ async validateRefreshToken(tokenId, userId, grantId, env) {
804
+ const grantKey = `grant:${userId}:${grantId}`;
805
+ const grantData = await env.OAUTH_KV.get(grantKey, { type: "json" });
806
+ if (!grantData) {
807
+ return false;
808
+ }
809
+ return grantData.refreshTokenId === tokenId || grantData.previousRefreshTokenId === tokenId;
810
+ }
811
+ /**
812
+ * Handles the dynamic client registration endpoint (RFC 7591)
813
+ * @param request - The HTTP request
814
+ * @param env - Cloudflare Worker environment variables
815
+ * @returns Response with client registration data or error
816
+ */
817
+ async handleClientRegistration(request, env) {
818
+ if (!this.options.clientRegistrationEndpoint) {
819
+ return this.createErrorResponse("not_implemented", "Client registration is not enabled", 501);
820
+ }
821
+ if (request.method !== "POST") {
822
+ return this.createErrorResponse("invalid_request", "Method not allowed", 405);
823
+ }
824
+ const contentLength = parseInt(request.headers.get("Content-Length") || "0", 10);
825
+ if (contentLength > 1048576) {
826
+ return this.createErrorResponse("invalid_request", "Request payload too large, must be under 1 MiB", 413);
827
+ }
828
+ let clientMetadata;
829
+ try {
830
+ const text = await request.text();
831
+ if (text.length > 1048576) {
832
+ return this.createErrorResponse("invalid_request", "Request payload too large, must be under 1 MiB", 413);
833
+ }
834
+ clientMetadata = JSON.parse(text);
835
+ } catch (error) {
836
+ return this.createErrorResponse("invalid_request", "Invalid JSON payload", 400);
837
+ }
838
+ const validateStringField = (field) => {
839
+ if (field === void 0) {
840
+ return void 0;
841
+ }
842
+ if (typeof field !== "string") {
843
+ throw new Error("Field must be a string");
844
+ }
845
+ return field;
846
+ };
847
+ const validateStringArray = (arr) => {
848
+ if (arr === void 0) {
849
+ return void 0;
850
+ }
851
+ if (!Array.isArray(arr)) {
852
+ throw new Error("Field must be an array");
853
+ }
854
+ for (const item of arr) {
855
+ if (typeof item !== "string") {
856
+ throw new Error("All array elements must be strings");
857
+ }
858
+ }
859
+ return arr;
860
+ };
861
+ const authMethod = validateStringField(clientMetadata.token_endpoint_auth_method) || "client_secret_basic";
862
+ const isPublicClient = authMethod === "none";
863
+ if (isPublicClient && this.options.disallowPublicClientRegistration) {
864
+ return this.createErrorResponse("invalid_client_metadata", "Public client registration is not allowed");
865
+ }
866
+ const clientId = generateRandomString(16);
867
+ let clientSecret;
868
+ let hashedSecret;
869
+ if (!isPublicClient) {
870
+ clientSecret = generateRandomString(32);
871
+ hashedSecret = await hashSecret(clientSecret);
872
+ }
873
+ let clientInfo;
874
+ try {
875
+ const redirectUris = validateStringArray(clientMetadata.redirect_uris);
876
+ if (!redirectUris || redirectUris.length === 0) {
877
+ throw new Error("At least one redirect URI is required");
878
+ }
879
+ for (const uri of redirectUris) {
880
+ validateRedirectUriScheme(uri);
881
+ }
882
+ clientInfo = {
883
+ clientId,
884
+ redirectUris,
885
+ clientName: validateStringField(clientMetadata.client_name),
886
+ logoUri: validateStringField(clientMetadata.logo_uri),
887
+ clientUri: validateStringField(clientMetadata.client_uri),
888
+ policyUri: validateStringField(clientMetadata.policy_uri),
889
+ tosUri: validateStringField(clientMetadata.tos_uri),
890
+ jwksUri: validateStringField(clientMetadata.jwks_uri),
891
+ contacts: validateStringArray(clientMetadata.contacts),
892
+ grantTypes: validateStringArray(clientMetadata.grant_types) || ["authorization_code", "refresh_token"],
893
+ responseTypes: validateStringArray(clientMetadata.response_types) || ["code"],
894
+ registrationDate: Math.floor(Date.now() / 1e3),
895
+ tokenEndpointAuthMethod: authMethod
896
+ };
897
+ if (!isPublicClient && hashedSecret) {
898
+ clientInfo.clientSecret = hashedSecret;
899
+ }
900
+ } catch (error) {
901
+ return this.createErrorResponse(
902
+ "invalid_client_metadata",
903
+ error instanceof Error ? error.message : "Invalid client metadata"
904
+ );
905
+ }
906
+ await env.OAUTH_KV.put(`client:${clientId}`, JSON.stringify(clientInfo));
907
+ const response = {
908
+ client_id: clientInfo.clientId,
909
+ redirect_uris: clientInfo.redirectUris,
910
+ client_name: clientInfo.clientName,
911
+ logo_uri: clientInfo.logoUri,
912
+ client_uri: clientInfo.clientUri,
913
+ policy_uri: clientInfo.policyUri,
914
+ tos_uri: clientInfo.tosUri,
915
+ jwks_uri: clientInfo.jwksUri,
916
+ contacts: clientInfo.contacts,
917
+ grant_types: clientInfo.grantTypes,
918
+ response_types: clientInfo.responseTypes,
919
+ token_endpoint_auth_method: clientInfo.tokenEndpointAuthMethod,
920
+ registration_client_uri: `${this.options.clientRegistrationEndpoint}/${clientId}`,
921
+ client_id_issued_at: clientInfo.registrationDate
922
+ };
923
+ if (clientSecret) {
924
+ response.client_secret = clientSecret;
925
+ }
926
+ return new Response(JSON.stringify(response), {
927
+ status: 201,
928
+ headers: { "Content-Type": "application/json" }
929
+ });
930
+ }
931
+ /**
932
+ * Handles API requests by validating the access token and calling the API handler
933
+ * @param request - The HTTP request
934
+ * @param env - Cloudflare Worker environment variables
935
+ * @param ctx - Cloudflare Worker execution context
936
+ * @returns Response from the API handler or error
937
+ */
938
+ async handleApiRequest(request, env, ctx) {
939
+ const authHeader = request.headers.get("Authorization");
940
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
941
+ return this.createErrorResponse("invalid_token", "Missing or invalid access token", 401, {
942
+ "WWW-Authenticate": 'Bearer realm="OAuth", error="invalid_token", error_description="Missing or invalid access token"'
943
+ });
944
+ }
945
+ const accessToken = authHeader.substring(7);
946
+ const parts = accessToken.split(":");
947
+ const isPossiblyInternalFormat = parts.length === 3;
948
+ let tokenData = null;
949
+ let userId = "";
950
+ let grantId = "";
951
+ if (isPossiblyInternalFormat) {
952
+ [userId, grantId] = parts;
953
+ const id = await generateTokenId(accessToken);
954
+ tokenData = await env.OAUTH_KV.get(`token:${userId}:${grantId}:${id}`, { type: "json" });
955
+ }
956
+ if (!tokenData && !this.options.resolveExternalToken) {
957
+ return this.createErrorResponse("invalid_token", "Invalid access token", 401, {
958
+ "WWW-Authenticate": 'Bearer realm="OAuth", error="invalid_token"'
959
+ });
960
+ }
961
+ if (tokenData) {
962
+ const now = Math.floor(Date.now() / 1e3);
963
+ if (tokenData.expiresAt < now) {
964
+ return this.createErrorResponse("invalid_token", "Access token expired", 401, {
965
+ "WWW-Authenticate": 'Bearer realm="OAuth", error="invalid_token"'
966
+ });
967
+ }
968
+ const encryptionKey = await unwrapKeyWithToken(accessToken, tokenData.wrappedEncryptionKey);
969
+ const decryptedProps = await decryptProps(encryptionKey, tokenData.grant.encryptedProps);
970
+ ctx.props = decryptedProps;
971
+ } else if (this.options.resolveExternalToken) {
972
+ const ext = await this.options.resolveExternalToken({ token: accessToken, request, env });
973
+ if (!ext) {
974
+ return this.createErrorResponse("invalid_token", "Invalid access token", 401, {
975
+ "WWW-Authenticate": 'Bearer realm="OAuth", error="invalid_token"'
976
+ });
977
+ }
978
+ ctx.props = ext.props;
979
+ }
980
+ if (!env.OAUTH_PROVIDER) {
981
+ env.OAUTH_PROVIDER = this.createOAuthHelpers(env);
982
+ }
983
+ const url = new URL(request.url);
984
+ const apiHandler = this.findApiHandlerForUrl(url);
985
+ if (!apiHandler) {
986
+ return this.createErrorResponse("invalid_request", "No handler found for API route", 404);
987
+ }
988
+ if (apiHandler.type === 0 /* EXPORTED_HANDLER */) {
989
+ return apiHandler.handler.fetch(request, env, ctx);
990
+ } else {
991
+ const handler = new apiHandler.handler(ctx, env);
992
+ return handler.fetch(request);
993
+ }
994
+ }
995
+ /**
996
+ * Creates the helper methods object for OAuth operations
997
+ * This is passed to the handler functions to allow them to interact with the OAuth system
998
+ * @param env - Cloudflare Worker environment variables
999
+ * @returns An instance of OAuthHelpers
1000
+ */
1001
+ createOAuthHelpers(env) {
1002
+ return new OAuthHelpersImpl(env, this);
1003
+ }
1004
+ /**
1005
+ * Saves a grant to KV with appropriate TTL based on expiration
1006
+ * @param env - The environment bindings
1007
+ * @param grantKey - The KV key for the grant
1008
+ * @param grantData - The grant data to save
1009
+ * @param now - Current timestamp in seconds
1010
+ */
1011
+ async saveGrantWithTTL(env, grantKey, grantData, now) {
1012
+ const kvOptions = grantData.expiresAt !== void 0 ? { expiration: grantData.expiresAt } : {};
1013
+ await env.OAUTH_KV.put(grantKey, JSON.stringify(grantData), kvOptions);
1014
+ }
1015
+ /**
1016
+ * Fetches client information from KV storage
1017
+ * This method is not private because `OAuthHelpers` needs to call it. Note that since
1018
+ * `OAuthProviderImpl` is not exposed outside this module, this is still effectively
1019
+ * module-private.
1020
+ * @param env - Cloudflare Worker environment variables
1021
+ * @param clientId - The client ID to look up
1022
+ * @returns The client information, or null if not found
1023
+ */
1024
+ getClient(env, clientId) {
1025
+ const clientKey = `client:${clientId}`;
1026
+ return env.OAUTH_KV.get(clientKey, { type: "json" });
1027
+ }
1028
+ /**
1029
+ * Helper function to create OAuth error responses
1030
+ * @param code - OAuth error code (e.g., 'invalid_request', 'invalid_token')
1031
+ * @param description - Human-readable error description
1032
+ * @param status - HTTP status code (default: 400)
1033
+ * @param headers - Additional headers to include
1034
+ * @returns A Response object with the error
1035
+ */
1036
+ createErrorResponse(code, description, status = 400, headers = {}) {
1037
+ const customErrorResponse = this.options.onError?.({ code, description, status, headers });
1038
+ if (customErrorResponse) return customErrorResponse;
1039
+ const body = JSON.stringify({
1040
+ error: code,
1041
+ error_description: description
1042
+ });
1043
+ return new Response(body, {
1044
+ status,
1045
+ headers: {
1046
+ "Content-Type": "application/json",
1047
+ ...headers
1048
+ }
1049
+ });
1050
+ }
1051
+ };
1052
+ var DEFAULT_ACCESS_TOKEN_TTL = 60 * 60;
1053
+ var TOKEN_LENGTH = 32;
1054
+ async function hashSecret(secret) {
1055
+ return generateTokenId(secret);
1056
+ }
1057
+ function generateRandomString(length) {
1058
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1059
+ let result = "";
1060
+ const values = new Uint8Array(length);
1061
+ crypto.getRandomValues(values);
1062
+ for (let i = 0; i < length; i++) {
1063
+ result += characters.charAt(values[i] % characters.length);
1064
+ }
1065
+ return result;
1066
+ }
1067
+ async function generateTokenId(token) {
1068
+ const encoder = new TextEncoder();
1069
+ const data = encoder.encode(token);
1070
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1071
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
1072
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
1073
+ return hashHex;
1074
+ }
1075
+ function validateRedirectUriScheme(redirectUri) {
1076
+ const dangerousSchemes = ["javascript:", "data:", "vbscript:", "file:", "mailto:", "blob:"];
1077
+ const normalized = redirectUri.trim();
1078
+ for (let i = 0; i < normalized.length; i++) {
1079
+ const code = normalized.charCodeAt(i);
1080
+ if (code >= 0 && code <= 31 || code >= 127 && code <= 159) {
1081
+ throw new Error("Invalid redirect URI");
1082
+ }
1083
+ }
1084
+ const colonIndex = normalized.indexOf(":");
1085
+ if (colonIndex === -1) {
1086
+ throw new Error("Invalid redirect URI");
1087
+ }
1088
+ const scheme = normalized.substring(0, colonIndex + 1).toLowerCase();
1089
+ for (const dangerousScheme of dangerousSchemes) {
1090
+ if (scheme === dangerousScheme) {
1091
+ throw new Error("Invalid redirect URI");
1092
+ }
1093
+ }
1094
+ }
1095
+ function base64UrlEncode(str) {
1096
+ return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1097
+ }
1098
+ function arrayBufferToBase64(buffer) {
1099
+ return btoa(String.fromCharCode(...new Uint8Array(buffer)));
1100
+ }
1101
+ function base64ToArrayBuffer(base64) {
1102
+ const binaryString = atob(base64);
1103
+ const bytes = new Uint8Array(binaryString.length);
1104
+ for (let i = 0; i < binaryString.length; i++) {
1105
+ bytes[i] = binaryString.charCodeAt(i);
1106
+ }
1107
+ return bytes.buffer;
1108
+ }
1109
+ async function encryptProps(data) {
1110
+ const key = await crypto.subtle.generateKey(
1111
+ {
1112
+ name: "AES-GCM",
1113
+ length: 256
1114
+ },
1115
+ true,
1116
+ // extractable
1117
+ ["encrypt", "decrypt"]
1118
+ );
1119
+ const iv = new Uint8Array(12);
1120
+ const jsonData = JSON.stringify(data);
1121
+ const encoder = new TextEncoder();
1122
+ const encodedData = encoder.encode(jsonData);
1123
+ const encryptedBuffer = await crypto.subtle.encrypt(
1124
+ {
1125
+ name: "AES-GCM",
1126
+ iv
1127
+ },
1128
+ key,
1129
+ encodedData
1130
+ );
1131
+ return {
1132
+ encryptedData: arrayBufferToBase64(encryptedBuffer),
1133
+ key
1134
+ };
1135
+ }
1136
+ async function decryptProps(key, encryptedData) {
1137
+ const encryptedBuffer = base64ToArrayBuffer(encryptedData);
1138
+ const iv = new Uint8Array(12);
1139
+ const decryptedBuffer = await crypto.subtle.decrypt(
1140
+ {
1141
+ name: "AES-GCM",
1142
+ iv
1143
+ },
1144
+ key,
1145
+ encryptedBuffer
1146
+ );
1147
+ const decoder = new TextDecoder();
1148
+ const jsonData = decoder.decode(decryptedBuffer);
1149
+ return JSON.parse(jsonData);
1150
+ }
1151
+ var WRAPPING_KEY_HMAC_KEY = new Uint8Array([
1152
+ 34,
1153
+ 126,
1154
+ 38,
1155
+ 134,
1156
+ 141,
1157
+ 241,
1158
+ 225,
1159
+ 109,
1160
+ 128,
1161
+ 112,
1162
+ 234,
1163
+ 23,
1164
+ 151,
1165
+ 91,
1166
+ 71,
1167
+ 166,
1168
+ 130,
1169
+ 24,
1170
+ 250,
1171
+ 135,
1172
+ 40,
1173
+ 174,
1174
+ 222,
1175
+ 133,
1176
+ 181,
1177
+ 29,
1178
+ 74,
1179
+ 217,
1180
+ 150,
1181
+ 202,
1182
+ 202,
1183
+ 67
1184
+ ]);
1185
+ async function deriveKeyFromToken(tokenStr) {
1186
+ const encoder = new TextEncoder();
1187
+ const hmacKey = await crypto.subtle.importKey(
1188
+ "raw",
1189
+ WRAPPING_KEY_HMAC_KEY,
1190
+ { name: "HMAC", hash: "SHA-256" },
1191
+ false,
1192
+ ["sign"]
1193
+ );
1194
+ const hmacResult = await crypto.subtle.sign("HMAC", hmacKey, encoder.encode(tokenStr));
1195
+ return await crypto.subtle.importKey(
1196
+ "raw",
1197
+ hmacResult,
1198
+ { name: "AES-KW" },
1199
+ false,
1200
+ // not extractable
1201
+ ["wrapKey", "unwrapKey"]
1202
+ );
1203
+ }
1204
+ async function wrapKeyWithToken(tokenStr, keyToWrap) {
1205
+ const wrappingKey = await deriveKeyFromToken(tokenStr);
1206
+ const wrappedKeyBuffer = await crypto.subtle.wrapKey("raw", keyToWrap, wrappingKey, { name: "AES-KW" });
1207
+ return arrayBufferToBase64(wrappedKeyBuffer);
1208
+ }
1209
+ async function unwrapKeyWithToken(tokenStr, wrappedKeyBase64) {
1210
+ const wrappingKey = await deriveKeyFromToken(tokenStr);
1211
+ const wrappedKeyBuffer = base64ToArrayBuffer(wrappedKeyBase64);
1212
+ return await crypto.subtle.unwrapKey(
1213
+ "raw",
1214
+ wrappedKeyBuffer,
1215
+ wrappingKey,
1216
+ { name: "AES-KW" },
1217
+ { name: "AES-GCM" },
1218
+ true,
1219
+ // extractable
1220
+ ["encrypt", "decrypt"]
1221
+ );
1222
+ }
1223
+ var OAuthHelpersImpl = class {
1224
+ /**
1225
+ * Creates a new OAuthHelpers instance
1226
+ * @param env - Cloudflare Worker environment variables
1227
+ * @param provider - Reference to the parent provider instance
1228
+ */
1229
+ constructor(env, provider) {
1230
+ this.env = env;
1231
+ this.provider = provider;
1232
+ }
1233
+ /**
1234
+ * Parses an OAuth authorization request from the HTTP request
1235
+ * @param request - The HTTP request containing OAuth parameters
1236
+ * @returns The parsed authorization request parameters
1237
+ */
1238
+ async parseAuthRequest(request) {
1239
+ const url = new URL(request.url);
1240
+ const responseType = url.searchParams.get("response_type") || "";
1241
+ const clientId = url.searchParams.get("client_id") || "";
1242
+ const redirectUri = url.searchParams.get("redirect_uri") || "";
1243
+ const scope = (url.searchParams.get("scope") || "").split(" ").filter(Boolean);
1244
+ const state = url.searchParams.get("state") || "";
1245
+ const codeChallenge = url.searchParams.get("code_challenge") || void 0;
1246
+ const codeChallengeMethod = url.searchParams.get("code_challenge_method") || "plain";
1247
+ validateRedirectUriScheme(redirectUri);
1248
+ if (responseType === "token" && !this.provider.options.allowImplicitFlow) {
1249
+ throw new Error("The implicit grant flow is not enabled for this provider");
1250
+ }
1251
+ if (clientId) {
1252
+ const clientInfo = await this.lookupClient(clientId);
1253
+ if (!clientInfo) {
1254
+ throw new Error(`Invalid client. The clientId provided does not match to this client.`);
1255
+ }
1256
+ if (clientInfo && redirectUri) {
1257
+ if (!clientInfo.redirectUris.includes(redirectUri)) {
1258
+ throw new Error(
1259
+ `Invalid redirect URI. The redirect URI provided does not match any registered URI for this client.`
1260
+ );
1261
+ }
1262
+ }
1263
+ }
1264
+ return {
1265
+ responseType,
1266
+ clientId,
1267
+ redirectUri,
1268
+ scope,
1269
+ state,
1270
+ codeChallenge,
1271
+ codeChallengeMethod
1272
+ };
1273
+ }
1274
+ /**
1275
+ * Looks up a client by its client ID
1276
+ * @param clientId - The client ID to look up
1277
+ * @returns A Promise resolving to the client info, or null if not found
1278
+ */
1279
+ async lookupClient(clientId) {
1280
+ return await this.provider.getClient(this.env, clientId);
1281
+ }
1282
+ /**
1283
+ * Completes an authorization request by creating a grant and either:
1284
+ * - For authorization code flow: generating an authorization code
1285
+ * - For implicit flow: generating an access token directly
1286
+ * @param options - Options specifying the grant details
1287
+ * @returns A Promise resolving to an object containing the redirect URL
1288
+ */
1289
+ async completeAuthorization(options) {
1290
+ const { clientId, redirectUri } = options.request;
1291
+ if (!clientId || !redirectUri) {
1292
+ throw new Error("Client ID and Redirect URI are required in the authorization request.");
1293
+ }
1294
+ const clientInfo = await this.lookupClient(clientId);
1295
+ if (!clientInfo || !clientInfo.redirectUris.includes(redirectUri)) {
1296
+ throw new Error(
1297
+ "Invalid redirect URI. The redirect URI provided does not match any registered URI for this client."
1298
+ );
1299
+ }
1300
+ const grantId = generateRandomString(16);
1301
+ const { encryptedData, key: encryptionKey } = await encryptProps(options.props);
1302
+ const now = Math.floor(Date.now() / 1e3);
1303
+ if (options.request.responseType === "token") {
1304
+ const accessTokenSecret = generateRandomString(TOKEN_LENGTH);
1305
+ const accessToken = `${options.userId}:${grantId}:${accessTokenSecret}`;
1306
+ const accessTokenId = await generateTokenId(accessToken);
1307
+ const accessTokenTTL = this.provider.options.accessTokenTTL || DEFAULT_ACCESS_TOKEN_TTL;
1308
+ const accessTokenExpiresAt = now + accessTokenTTL;
1309
+ const accessTokenWrappedKey = await wrapKeyWithToken(accessToken, encryptionKey);
1310
+ const grant = {
1311
+ id: grantId,
1312
+ clientId: options.request.clientId,
1313
+ userId: options.userId,
1314
+ scope: options.scope,
1315
+ metadata: options.metadata,
1316
+ encryptedProps: encryptedData,
1317
+ createdAt: now
1318
+ };
1319
+ const grantKey = `grant:${options.userId}:${grantId}`;
1320
+ await this.env.OAUTH_KV.put(grantKey, JSON.stringify(grant));
1321
+ const accessTokenData = {
1322
+ id: accessTokenId,
1323
+ grantId,
1324
+ userId: options.userId,
1325
+ createdAt: now,
1326
+ expiresAt: accessTokenExpiresAt,
1327
+ wrappedEncryptionKey: accessTokenWrappedKey,
1328
+ grant: {
1329
+ clientId: options.request.clientId,
1330
+ scope: options.scope,
1331
+ encryptedProps: encryptedData
1332
+ }
1333
+ };
1334
+ await this.env.OAUTH_KV.put(
1335
+ `token:${options.userId}:${grantId}:${accessTokenId}`,
1336
+ JSON.stringify(accessTokenData),
1337
+ { expirationTtl: accessTokenTTL }
1338
+ );
1339
+ const redirectUrl = new URL(options.request.redirectUri);
1340
+ const fragment = new URLSearchParams();
1341
+ fragment.set("access_token", accessToken);
1342
+ fragment.set("token_type", "bearer");
1343
+ fragment.set("expires_in", accessTokenTTL.toString());
1344
+ fragment.set("scope", options.scope.join(" "));
1345
+ if (options.request.state) {
1346
+ fragment.set("state", options.request.state);
1347
+ }
1348
+ redirectUrl.hash = fragment.toString();
1349
+ return { redirectTo: redirectUrl.toString() };
1350
+ } else {
1351
+ const authCodeSecret = generateRandomString(32);
1352
+ const authCode = `${options.userId}:${grantId}:${authCodeSecret}`;
1353
+ const authCodeId = await hashSecret(authCode);
1354
+ const authCodeWrappedKey = await wrapKeyWithToken(authCode, encryptionKey);
1355
+ const grant = {
1356
+ id: grantId,
1357
+ clientId: options.request.clientId,
1358
+ userId: options.userId,
1359
+ scope: options.scope,
1360
+ metadata: options.metadata,
1361
+ encryptedProps: encryptedData,
1362
+ createdAt: now,
1363
+ authCodeId,
1364
+ // Store the auth code hash in the grant
1365
+ authCodeWrappedKey,
1366
+ // Store the wrapped key
1367
+ // Store PKCE parameters if provided
1368
+ codeChallenge: options.request.codeChallenge,
1369
+ codeChallengeMethod: options.request.codeChallengeMethod
1370
+ };
1371
+ const grantKey = `grant:${options.userId}:${grantId}`;
1372
+ const codeExpiresIn = 600;
1373
+ await this.env.OAUTH_KV.put(grantKey, JSON.stringify(grant), { expirationTtl: codeExpiresIn });
1374
+ const redirectUrl = new URL(options.request.redirectUri);
1375
+ redirectUrl.searchParams.set("code", authCode);
1376
+ if (options.request.state) {
1377
+ redirectUrl.searchParams.set("state", options.request.state);
1378
+ }
1379
+ return { redirectTo: redirectUrl.toString() };
1380
+ }
1381
+ }
1382
+ /**
1383
+ * Creates a new OAuth client
1384
+ * @param clientInfo - Partial client information to create the client with
1385
+ * @returns A Promise resolving to the created client info
1386
+ */
1387
+ async createClient(clientInfo) {
1388
+ const clientId = generateRandomString(16);
1389
+ const tokenEndpointAuthMethod = clientInfo.tokenEndpointAuthMethod || "client_secret_basic";
1390
+ const isPublicClient = tokenEndpointAuthMethod === "none";
1391
+ const newClient = {
1392
+ clientId,
1393
+ redirectUris: clientInfo.redirectUris || [],
1394
+ clientName: clientInfo.clientName,
1395
+ logoUri: clientInfo.logoUri,
1396
+ clientUri: clientInfo.clientUri,
1397
+ policyUri: clientInfo.policyUri,
1398
+ tosUri: clientInfo.tosUri,
1399
+ jwksUri: clientInfo.jwksUri,
1400
+ contacts: clientInfo.contacts,
1401
+ grantTypes: clientInfo.grantTypes || ["authorization_code", "refresh_token"],
1402
+ responseTypes: clientInfo.responseTypes || ["code"],
1403
+ registrationDate: Math.floor(Date.now() / 1e3),
1404
+ tokenEndpointAuthMethod
1405
+ };
1406
+ for (const uri of newClient.redirectUris) {
1407
+ validateRedirectUriScheme(uri);
1408
+ }
1409
+ let clientSecret;
1410
+ if (!isPublicClient) {
1411
+ clientSecret = generateRandomString(32);
1412
+ newClient.clientSecret = await hashSecret(clientSecret);
1413
+ }
1414
+ await this.env.OAUTH_KV.put(`client:${clientId}`, JSON.stringify(newClient));
1415
+ const clientResponse = { ...newClient };
1416
+ if (!isPublicClient && clientSecret) {
1417
+ clientResponse.clientSecret = clientSecret;
1418
+ }
1419
+ return clientResponse;
1420
+ }
1421
+ /**
1422
+ * Lists all registered OAuth clients with pagination support
1423
+ * @param options - Optional pagination parameters (limit and cursor)
1424
+ * @returns A Promise resolving to the list result with items and optional cursor
1425
+ */
1426
+ async listClients(options) {
1427
+ const listOptions = {
1428
+ prefix: "client:"
1429
+ };
1430
+ if (options?.limit !== void 0) {
1431
+ listOptions.limit = options.limit;
1432
+ }
1433
+ if (options?.cursor !== void 0) {
1434
+ listOptions.cursor = options.cursor;
1435
+ }
1436
+ const response = await this.env.OAUTH_KV.list(listOptions);
1437
+ const clients = [];
1438
+ const promises = response.keys.map(async (key) => {
1439
+ const clientId = key.name.substring("client:".length);
1440
+ const client = await this.provider.getClient(this.env, clientId);
1441
+ if (client) {
1442
+ clients.push(client);
1443
+ }
1444
+ });
1445
+ await Promise.all(promises);
1446
+ return {
1447
+ items: clients,
1448
+ cursor: response.list_complete ? void 0 : response.cursor
1449
+ };
1450
+ }
1451
+ /**
1452
+ * Updates an existing OAuth client
1453
+ * @param clientId - The ID of the client to update
1454
+ * @param updates - Partial client information with fields to update
1455
+ * @returns A Promise resolving to the updated client info, or null if not found
1456
+ */
1457
+ async updateClient(clientId, updates) {
1458
+ const client = await this.provider.getClient(this.env, clientId);
1459
+ if (!client) {
1460
+ return null;
1461
+ }
1462
+ let authMethod = updates.tokenEndpointAuthMethod || client.tokenEndpointAuthMethod || "client_secret_basic";
1463
+ const isPublicClient = authMethod === "none";
1464
+ let secretToStore = client.clientSecret;
1465
+ let originalSecret = void 0;
1466
+ if (isPublicClient) {
1467
+ secretToStore = void 0;
1468
+ } else if (updates.clientSecret) {
1469
+ originalSecret = updates.clientSecret;
1470
+ secretToStore = await hashSecret(updates.clientSecret);
1471
+ }
1472
+ const updatedClient = {
1473
+ ...client,
1474
+ ...updates,
1475
+ clientId: client.clientId,
1476
+ // Ensure clientId doesn't change
1477
+ tokenEndpointAuthMethod: authMethod
1478
+ // Use determined auth method
1479
+ };
1480
+ if (!isPublicClient && secretToStore) {
1481
+ updatedClient.clientSecret = secretToStore;
1482
+ } else {
1483
+ delete updatedClient.clientSecret;
1484
+ }
1485
+ await this.env.OAUTH_KV.put(`client:${clientId}`, JSON.stringify(updatedClient));
1486
+ const response = { ...updatedClient };
1487
+ if (!isPublicClient && originalSecret) {
1488
+ response.clientSecret = originalSecret;
1489
+ }
1490
+ return response;
1491
+ }
1492
+ /**
1493
+ * Deletes an OAuth client
1494
+ * @param clientId - The ID of the client to delete
1495
+ * @returns A Promise resolving when the deletion is confirmed.
1496
+ */
1497
+ async deleteClient(clientId) {
1498
+ await this.env.OAUTH_KV.delete(`client:${clientId}`);
1499
+ }
1500
+ /**
1501
+ * Lists all authorization grants for a specific user with pagination support
1502
+ * Returns a summary of each grant without sensitive information
1503
+ * @param userId - The ID of the user whose grants to list
1504
+ * @param options - Optional pagination parameters (limit and cursor)
1505
+ * @returns A Promise resolving to the list result with grant summaries and optional cursor
1506
+ */
1507
+ async listUserGrants(userId, options) {
1508
+ const listOptions = {
1509
+ prefix: `grant:${userId}:`
1510
+ };
1511
+ if (options?.limit !== void 0) {
1512
+ listOptions.limit = options.limit;
1513
+ }
1514
+ if (options?.cursor !== void 0) {
1515
+ listOptions.cursor = options.cursor;
1516
+ }
1517
+ const response = await this.env.OAUTH_KV.list(listOptions);
1518
+ const grantSummaries = [];
1519
+ const promises = response.keys.map(async (key) => {
1520
+ const grantData = await this.env.OAUTH_KV.get(key.name, { type: "json" });
1521
+ if (grantData) {
1522
+ const summary = {
1523
+ id: grantData.id,
1524
+ clientId: grantData.clientId,
1525
+ userId: grantData.userId,
1526
+ scope: grantData.scope,
1527
+ metadata: grantData.metadata,
1528
+ createdAt: grantData.createdAt,
1529
+ expiresAt: grantData.expiresAt
1530
+ };
1531
+ grantSummaries.push(summary);
1532
+ }
1533
+ });
1534
+ await Promise.all(promises);
1535
+ return {
1536
+ items: grantSummaries,
1537
+ cursor: response.list_complete ? void 0 : response.cursor
1538
+ };
1539
+ }
1540
+ /**
1541
+ * Revokes an authorization grant and all its associated access tokens
1542
+ * @param grantId - The ID of the grant to revoke
1543
+ * @param userId - The ID of the user who owns the grant
1544
+ * @returns A Promise resolving when the revocation is confirmed.
1545
+ */
1546
+ async revokeGrant(grantId, userId) {
1547
+ const grantKey = `grant:${userId}:${grantId}`;
1548
+ const tokenPrefix = `token:${userId}:${grantId}:`;
1549
+ let cursor;
1550
+ let allTokensDeleted = false;
1551
+ while (!allTokensDeleted) {
1552
+ const listOptions = {
1553
+ prefix: tokenPrefix
1554
+ };
1555
+ if (cursor) {
1556
+ listOptions.cursor = cursor;
1557
+ }
1558
+ const result = await this.env.OAUTH_KV.list(listOptions);
1559
+ if (result.keys.length > 0) {
1560
+ await Promise.all(
1561
+ result.keys.map((key) => {
1562
+ return this.env.OAUTH_KV.delete(key.name);
1563
+ })
1564
+ );
1565
+ }
1566
+ if (result.list_complete) {
1567
+ allTokensDeleted = true;
1568
+ } else {
1569
+ cursor = result.cursor;
1570
+ }
1571
+ }
1572
+ await this.env.OAUTH_KV.delete(grantKey);
1573
+ }
1574
+ };
1575
+ var oauth_provider_default = OAuthProvider;
1576
+ export {
1577
+ OAuthProvider,
1578
+ oauth_provider_default as default
1579
+ };