@cloudflare/workers-oauth-provider 0.0.0-89df9a6

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