@cloudflare/workers-oauth-provider 0.1.0 → 0.2.2

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