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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,608 @@
1
+ import { WorkerEntrypoint } from 'cloudflare:workers';
2
+
3
+ /**
4
+ * Aliases for either type of Handler that makes .fetch required
5
+ */
6
+ type ExportedHandlerWithFetch = ExportedHandler & Pick<Required<ExportedHandler>, 'fetch'>;
7
+ type WorkerEntrypointWithFetch = WorkerEntrypoint & Pick<Required<WorkerEntrypoint>, 'fetch'>;
8
+ /**
9
+ * Configuration options for the OAuth Provider
10
+ */
11
+ /**
12
+ * Result of a token exchange callback function.
13
+ * Allows updating the props stored in both the access token and the grant.
14
+ */
15
+ interface TokenExchangeCallbackResult {
16
+ /**
17
+ * New props to be stored specifically with the access token.
18
+ * If not provided but newProps is, the access token will use newProps.
19
+ * If neither is provided, the original props will be used.
20
+ */
21
+ accessTokenProps?: any;
22
+ /**
23
+ * New props to replace the props stored in the grant itself.
24
+ * These props will be used for all future token refreshes.
25
+ * If accessTokenProps is not provided, these props will also be used for the current access token.
26
+ * If not provided, the original props will be used.
27
+ */
28
+ newProps?: any;
29
+ /**
30
+ * Override the default access token TTL (time-to-live) for this specific token.
31
+ * This is especially useful when the application is also an OAuth client to another service
32
+ * and wants to match its access token TTL to the upstream access token TTL.
33
+ * Value should be in seconds.
34
+ */
35
+ accessTokenTTL?: number;
36
+ /**
37
+ * Override the default refresh token TTL (time-to-live) for this specific grant.
38
+ * Value should be in seconds.
39
+ * Note: This is only honored during authorization code exchange. If returned during
40
+ * refresh token exchange, it will be ignored.
41
+ */
42
+ refreshTokenTTL?: number;
43
+ }
44
+ /**
45
+ * Options for token exchange callback functions
46
+ */
47
+ interface TokenExchangeCallbackOptions {
48
+ /**
49
+ * The type of grant being processed.
50
+ * 'authorization_code' for initial code exchange,
51
+ * 'refresh_token' for refresh token exchange.
52
+ */
53
+ grantType: 'authorization_code' | 'refresh_token';
54
+ /**
55
+ * Client that received this grant
56
+ */
57
+ clientId: string;
58
+ /**
59
+ * User who authorized this grant
60
+ */
61
+ userId: string;
62
+ /**
63
+ * List of scopes that were granted
64
+ */
65
+ scope: string[];
66
+ /**
67
+ * Application-specific properties currently associated with this grant
68
+ */
69
+ props: any;
70
+ }
71
+ /**
72
+ * Input parameters for the resolveExternalToken callback function
73
+ */
74
+ interface ResolveExternalTokenInput {
75
+ /**
76
+ * The token string that was provided in the Authorization header
77
+ */
78
+ token: string;
79
+ /**
80
+ * The original HTTP request
81
+ */
82
+ request: Request;
83
+ /**
84
+ * Cloudflare Worker environment variables
85
+ */
86
+ env: any;
87
+ }
88
+ /**
89
+ * Result returned from the resolveExternalToken callback function
90
+ */
91
+ interface ResolveExternalTokenResult {
92
+ /**
93
+ * Application-specific properties that will be passed to the API handlers
94
+ * These properties are set in the execution context (ctx.props) when the external token is validated
95
+ */
96
+ props: any;
97
+ }
98
+ interface OAuthProviderOptions {
99
+ /**
100
+ * URL(s) for API routes. Requests with URLs starting with any of these prefixes
101
+ * will be treated as API requests and require a valid access token.
102
+ * Can be a single route or an array of routes. Each route can be a full URL or just a path.
103
+ *
104
+ * Used with `apiHandler` for the single-handler configuration. This is incompatible with
105
+ * the `apiHandlers` property. You must use either `apiRoute` + `apiHandler` OR `apiHandlers`, not both.
106
+ */
107
+ apiRoute?: string | string[];
108
+ /**
109
+ * Handler for API requests that have a valid access token.
110
+ * This handler will receive the authenticated user properties in ctx.props.
111
+ * Can be either an ExportedHandler object with a fetch method or a class extending WorkerEntrypoint.
112
+ *
113
+ * Used with `apiRoute` for the single-handler configuration. This is incompatible with
114
+ * the `apiHandlers` property. You must use either `apiRoute` + `apiHandler` OR `apiHandlers`, not both.
115
+ */
116
+ apiHandler?: ExportedHandlerWithFetch | (new (ctx: ExecutionContext, env: any) => WorkerEntrypointWithFetch);
117
+ /**
118
+ * Map of API routes to their corresponding handlers for the multi-handler configuration.
119
+ * The keys are the API routes (strings only, not arrays), and the values are the handlers.
120
+ * Each route can be a full URL or just a path, and each handler can be either an ExportedHandler
121
+ * object with a fetch method or a class extending WorkerEntrypoint.
122
+ *
123
+ * This is incompatible with the `apiRoute` and `apiHandler` properties. You must use either
124
+ * `apiRoute` + `apiHandler` (single-handler configuration) OR `apiHandlers` (multi-handler
125
+ * configuration), not both.
126
+ */
127
+ apiHandlers?: Record<string, ExportedHandlerWithFetch | (new (ctx: ExecutionContext, env: any) => WorkerEntrypointWithFetch)>;
128
+ /**
129
+ * Handler for all non-API requests or API requests without a valid token.
130
+ * Can be either an ExportedHandler object with a fetch method or a class extending WorkerEntrypoint.
131
+ */
132
+ defaultHandler: ExportedHandler | (new (ctx: ExecutionContext, env: any) => WorkerEntrypointWithFetch);
133
+ /**
134
+ * URL of the OAuth authorization endpoint where users can grant permissions.
135
+ * This URL is used in OAuth metadata and is not handled by the provider itself.
136
+ */
137
+ authorizeEndpoint: string;
138
+ /**
139
+ * URL of the token endpoint which the provider will implement.
140
+ * This endpoint handles token issuance, refresh, and revocation.
141
+ */
142
+ tokenEndpoint: string;
143
+ /**
144
+ * Optional URL for the client registration endpoint.
145
+ * If provided, the provider will implement dynamic client registration.
146
+ */
147
+ clientRegistrationEndpoint?: string;
148
+ /**
149
+ * Time-to-live for access tokens in seconds.
150
+ * Defaults to 1 hour (3600 seconds) if not specified.
151
+ */
152
+ accessTokenTTL?: number;
153
+ /**
154
+ * Time-to-live for refresh tokens in seconds.
155
+ * If not specified, refresh tokens do not expire.
156
+ * For example: 3600 = 1 hour, 2592000 = 30 days
157
+ */
158
+ refreshTokenTTL?: number;
159
+ /**
160
+ * List of scopes supported by this OAuth provider.
161
+ * If not provided, the 'scopes_supported' field will be omitted from the OAuth metadata.
162
+ */
163
+ scopesSupported?: string[];
164
+ /**
165
+ * Controls whether the OAuth implicit flow is allowed.
166
+ * This flow is discouraged in OAuth 2.1 due to security concerns.
167
+ * Defaults to false.
168
+ */
169
+ allowImplicitFlow?: boolean;
170
+ /**
171
+ * Controls whether public clients (clients without a secret, like SPAs) can register via the
172
+ * dynamic client registration endpoint. When true, only confidential clients can register.
173
+ * Note: Creating public clients via the OAuthHelpers.createClient() method is always allowed.
174
+ * Defaults to false.
175
+ */
176
+ disallowPublicClientRegistration?: boolean;
177
+ /**
178
+ * Optional callback function that is called during token exchange.
179
+ * This allows updating the props stored in both the access token and the grant.
180
+ * For example, if the application itself is also a client to some other OAuth API,
181
+ * it may want to perform the equivalent upstream token exchange, and store the result in the props.
182
+ *
183
+ * The callback can return new props values that will be stored with the token or grant.
184
+ * If the callback returns nothing or undefined for a props field, the original props will be used.
185
+ */
186
+ tokenExchangeCallback?: (options: TokenExchangeCallbackOptions) => Promise<TokenExchangeCallbackResult | void> | TokenExchangeCallbackResult | void;
187
+ /**
188
+ * Optional callback function that is called when a provided token was not found in the internal KV.
189
+ * This allows authentication through external OAuth servers.
190
+ * For example, if a request includes an authenticated token from a different OAuth authentication server,
191
+ * the callback can be used to authenticate it and set the context props through it.
192
+ *
193
+ * The callback can optionally return props values that will passed-through to the apiHandlers.
194
+ * The callback can return `null` to signal resolution failure.
195
+ */
196
+ resolveExternalToken?: (input: ResolveExternalTokenInput) => Promise<ResolveExternalTokenResult | null>;
197
+ /**
198
+ * Optional callback function that is called whenever the OAuthProvider returns an error response
199
+ * This allows the client to emit notifications or perform other actions when an error occurs.
200
+ *
201
+ * If the function returns a Response, that will be used in place of the OAuthProvider's default one.
202
+ */
203
+ onError?: (error: {
204
+ code: string;
205
+ description: string;
206
+ status: number;
207
+ headers: Record<string, string>;
208
+ }) => Response | void;
209
+ }
210
+ /**
211
+ * Helper methods for OAuth operations provided to handler functions
212
+ */
213
+ interface OAuthHelpers {
214
+ /**
215
+ * Parses an OAuth authorization request from the HTTP request
216
+ * @param request - The HTTP request containing OAuth parameters
217
+ * @returns The parsed authorization request parameters
218
+ */
219
+ parseAuthRequest(request: Request): Promise<AuthRequest>;
220
+ /**
221
+ * Looks up a client by its client ID
222
+ * @param clientId - The client ID to look up
223
+ * @returns A Promise resolving to the client info, or null if not found
224
+ */
225
+ lookupClient(clientId: string): Promise<ClientInfo | null>;
226
+ /**
227
+ * Completes an authorization request by creating a grant and authorization code
228
+ * @param options - Options specifying the grant details
229
+ * @returns A Promise resolving to an object containing the redirect URL
230
+ */
231
+ completeAuthorization(options: CompleteAuthorizationOptions): Promise<{
232
+ redirectTo: string;
233
+ }>;
234
+ /**
235
+ * Creates a new OAuth client
236
+ * @param clientInfo - Partial client information to create the client with
237
+ * @returns A Promise resolving to the created client info
238
+ */
239
+ createClient(clientInfo: Partial<ClientInfo>): Promise<ClientInfo>;
240
+ /**
241
+ * Lists all registered OAuth clients with pagination support
242
+ * @param options - Optional pagination parameters (limit and cursor)
243
+ * @returns A Promise resolving to the list result with items and optional cursor
244
+ */
245
+ listClients(options?: ListOptions): Promise<ListResult<ClientInfo>>;
246
+ /**
247
+ * Updates an existing OAuth client
248
+ * @param clientId - The ID of the client to update
249
+ * @param updates - Partial client information with fields to update
250
+ * @returns A Promise resolving to the updated client info, or null if not found
251
+ */
252
+ updateClient(clientId: string, updates: Partial<ClientInfo>): Promise<ClientInfo | null>;
253
+ /**
254
+ * Deletes an OAuth client
255
+ * @param clientId - The ID of the client to delete
256
+ * @returns A Promise resolving when the deletion is confirmed.
257
+ */
258
+ deleteClient(clientId: string): Promise<void>;
259
+ /**
260
+ * Lists all authorization grants for a specific user with pagination support
261
+ * Returns a summary of each grant without sensitive information
262
+ * @param userId - The ID of the user whose grants to list
263
+ * @param options - Optional pagination parameters (limit and cursor)
264
+ * @returns A Promise resolving to the list result with grant summaries and optional cursor
265
+ */
266
+ listUserGrants(userId: string, options?: ListOptions): Promise<ListResult<GrantSummary>>;
267
+ /**
268
+ * Revokes an authorization grant
269
+ * @param grantId - The ID of the grant to revoke
270
+ * @param userId - The ID of the user who owns the grant
271
+ * @returns A Promise resolving when the revocation is confirmed.
272
+ */
273
+ revokeGrant(grantId: string, userId: string): Promise<void>;
274
+ }
275
+ /**
276
+ * Parsed OAuth authorization request parameters
277
+ */
278
+ interface AuthRequest {
279
+ /**
280
+ * OAuth response type (e.g., "code" for authorization code flow)
281
+ */
282
+ responseType: string;
283
+ /**
284
+ * Client identifier for the OAuth client
285
+ */
286
+ clientId: string;
287
+ /**
288
+ * URL to redirect to after authorization
289
+ */
290
+ redirectUri: string;
291
+ /**
292
+ * Array of requested permission scopes
293
+ */
294
+ scope: string[];
295
+ /**
296
+ * Client state value to be returned in the redirect
297
+ */
298
+ state: string;
299
+ /**
300
+ * PKCE code challenge (RFC 7636)
301
+ */
302
+ codeChallenge?: string;
303
+ /**
304
+ * PKCE code challenge method (plain or S256)
305
+ */
306
+ codeChallengeMethod?: string;
307
+ }
308
+ /**
309
+ * OAuth client registration information
310
+ */
311
+ interface ClientInfo {
312
+ /**
313
+ * Unique identifier for the client
314
+ */
315
+ clientId: string;
316
+ /**
317
+ * Secret used to authenticate the client (stored as a hash)
318
+ * Only present for confidential clients; undefined for public clients.
319
+ */
320
+ clientSecret?: string;
321
+ /**
322
+ * List of allowed redirect URIs for the client
323
+ */
324
+ redirectUris: string[];
325
+ /**
326
+ * Human-readable name of the client application
327
+ */
328
+ clientName?: string;
329
+ /**
330
+ * URL to the client's logo
331
+ */
332
+ logoUri?: string;
333
+ /**
334
+ * URL to the client's homepage
335
+ */
336
+ clientUri?: string;
337
+ /**
338
+ * URL to the client's privacy policy
339
+ */
340
+ policyUri?: string;
341
+ /**
342
+ * URL to the client's terms of service
343
+ */
344
+ tosUri?: string;
345
+ /**
346
+ * URL to the client's JSON Web Key Set for validating signatures
347
+ */
348
+ jwksUri?: string;
349
+ /**
350
+ * List of email addresses for contacting the client developers
351
+ */
352
+ contacts?: string[];
353
+ /**
354
+ * List of grant types the client supports
355
+ */
356
+ grantTypes?: string[];
357
+ /**
358
+ * List of response types the client supports
359
+ */
360
+ responseTypes?: string[];
361
+ /**
362
+ * Unix timestamp when the client was registered
363
+ */
364
+ registrationDate?: number;
365
+ /**
366
+ * The authentication method used by the client at the token endpoint.
367
+ * Values include:
368
+ * - 'client_secret_basic': Uses HTTP Basic Auth with client ID and secret (default for confidential clients)
369
+ * - 'client_secret_post': Uses POST parameters for client authentication
370
+ * - 'none': Used for public clients that can't securely store secrets (SPAs, mobile apps, etc.)
371
+ *
372
+ * Public clients use 'none', while confidential clients use either 'client_secret_basic' or 'client_secret_post'.
373
+ */
374
+ tokenEndpointAuthMethod: string;
375
+ }
376
+ /**
377
+ * Options for completing an authorization request
378
+ */
379
+ interface CompleteAuthorizationOptions {
380
+ /**
381
+ * The original parsed authorization request
382
+ */
383
+ request: AuthRequest;
384
+ /**
385
+ * Identifier for the user granting the authorization
386
+ */
387
+ userId: string;
388
+ /**
389
+ * Application-specific metadata to associate with this grant
390
+ */
391
+ metadata: any;
392
+ /**
393
+ * List of scopes that were actually granted (may differ from requested scopes)
394
+ */
395
+ scope: string[];
396
+ /**
397
+ * Application-specific properties to include with API requests
398
+ * authorized by this grant
399
+ */
400
+ props: any;
401
+ }
402
+ /**
403
+ * Authorization grant record
404
+ */
405
+ interface Grant {
406
+ /**
407
+ * Unique identifier for the grant
408
+ */
409
+ id: string;
410
+ /**
411
+ * Client that received this grant
412
+ */
413
+ clientId: string;
414
+ /**
415
+ * User who authorized this grant
416
+ */
417
+ userId: string;
418
+ /**
419
+ * List of scopes that were granted
420
+ */
421
+ scope: string[];
422
+ /**
423
+ * Application-specific metadata associated with this grant
424
+ */
425
+ metadata: any;
426
+ /**
427
+ * Encrypted application-specific properties
428
+ */
429
+ encryptedProps: string;
430
+ /**
431
+ * Unix timestamp when the grant was created
432
+ */
433
+ createdAt: number;
434
+ /**
435
+ * Unix timestamp when the grant expires (if TTL is configured)
436
+ */
437
+ expiresAt?: number;
438
+ /**
439
+ * The hash of the current refresh token associated with this grant
440
+ */
441
+ refreshTokenId?: string;
442
+ /**
443
+ * Wrapped encryption key for the current refresh token
444
+ */
445
+ refreshTokenWrappedKey?: string;
446
+ /**
447
+ * The hash of the previous refresh token associated with this grant
448
+ * This token is still valid until the new token is first used
449
+ */
450
+ previousRefreshTokenId?: string;
451
+ /**
452
+ * Wrapped encryption key for the previous refresh token
453
+ */
454
+ previousRefreshTokenWrappedKey?: string;
455
+ /**
456
+ * The hash of the authorization code associated with this grant
457
+ * Only present during the authorization code exchange process
458
+ */
459
+ authCodeId?: string;
460
+ /**
461
+ * Wrapped encryption key for the authorization code
462
+ * Only present during the authorization code exchange process
463
+ */
464
+ authCodeWrappedKey?: string;
465
+ /**
466
+ * PKCE code challenge for this authorization
467
+ * Only present during the authorization code exchange process
468
+ */
469
+ codeChallenge?: string;
470
+ /**
471
+ * PKCE code challenge method (plain or S256)
472
+ * Only present during the authorization code exchange process
473
+ */
474
+ codeChallengeMethod?: string;
475
+ }
476
+ /**
477
+ * Token record stored in KV
478
+ * Note: The actual token format is "{userId}:{grantId}:{random-secret}"
479
+ * but we still only store the hash of the full token string.
480
+ * This contains only access tokens; refresh tokens are stored within the grant records.
481
+ */
482
+ interface Token {
483
+ /**
484
+ * Unique identifier for the token (hash of the actual token)
485
+ */
486
+ id: string;
487
+ /**
488
+ * Identifier of the grant this token is associated with
489
+ */
490
+ grantId: string;
491
+ /**
492
+ * User ID associated with this token
493
+ */
494
+ userId: string;
495
+ /**
496
+ * Unix timestamp when the token was created
497
+ */
498
+ createdAt: number;
499
+ /**
500
+ * Unix timestamp when the token expires
501
+ */
502
+ expiresAt: number;
503
+ /**
504
+ * The encryption key for props, wrapped with this token
505
+ */
506
+ wrappedEncryptionKey: string;
507
+ /**
508
+ * Denormalized grant information for faster access
509
+ */
510
+ grant: {
511
+ /**
512
+ * Client that received this grant
513
+ */
514
+ clientId: string;
515
+ /**
516
+ * List of scopes that were granted
517
+ */
518
+ scope: string[];
519
+ /**
520
+ * Encrypted application-specific properties
521
+ */
522
+ encryptedProps: string;
523
+ };
524
+ }
525
+ /**
526
+ * Options for listing operations that support pagination
527
+ */
528
+ interface ListOptions {
529
+ /**
530
+ * Maximum number of items to return (max 1000)
531
+ */
532
+ limit?: number;
533
+ /**
534
+ * Cursor for pagination (from a previous listing operation)
535
+ */
536
+ cursor?: string;
537
+ }
538
+ /**
539
+ * Result of a listing operation with pagination support
540
+ */
541
+ interface ListResult<T> {
542
+ /**
543
+ * The list of items
544
+ */
545
+ items: T[];
546
+ /**
547
+ * Cursor to get the next page of results, if there are more results
548
+ */
549
+ cursor?: string;
550
+ }
551
+ /**
552
+ * Public representation of a grant, with sensitive data removed
553
+ * Used for list operations where the complete grant data isn't needed
554
+ */
555
+ interface GrantSummary {
556
+ /**
557
+ * Unique identifier for the grant
558
+ */
559
+ id: string;
560
+ /**
561
+ * Client that received this grant
562
+ */
563
+ clientId: string;
564
+ /**
565
+ * User who authorized this grant
566
+ */
567
+ userId: string;
568
+ /**
569
+ * List of scopes that were granted
570
+ */
571
+ scope: string[];
572
+ /**
573
+ * Application-specific metadata associated with this grant
574
+ */
575
+ metadata: any;
576
+ /**
577
+ * Unix timestamp when the grant was created
578
+ */
579
+ createdAt: number;
580
+ /**
581
+ * Unix timestamp when the grant expires (if TTL is configured)
582
+ */
583
+ expiresAt?: number;
584
+ }
585
+ /**
586
+ * OAuth 2.0 Provider implementation for Cloudflare Workers
587
+ * Implements authorization code flow with support for refresh tokens
588
+ * and dynamic client registration.
589
+ */
590
+ declare class OAuthProvider {
591
+ #private;
592
+ /**
593
+ * Creates a new OAuth provider instance
594
+ * @param options - Configuration options for the provider
595
+ */
596
+ constructor(options: OAuthProviderOptions);
597
+ /**
598
+ * Main fetch handler for the Worker
599
+ * Routes requests to the appropriate handler based on the URL
600
+ * @param request - The HTTP request
601
+ * @param env - Cloudflare Worker environment variables
602
+ * @param ctx - Cloudflare Worker execution context
603
+ * @returns A Promise resolving to an HTTP Response
604
+ */
605
+ fetch(request: Request, env: any, ctx: ExecutionContext): Promise<Response>;
606
+ }
607
+
608
+ export { type AuthRequest, type ClientInfo, type CompleteAuthorizationOptions, type Grant, type GrantSummary, type ListOptions, type ListResult, type OAuthHelpers, OAuthProvider, type OAuthProviderOptions, type ResolveExternalTokenInput, type ResolveExternalTokenResult, type Token, type TokenExchangeCallbackOptions, type TokenExchangeCallbackResult, OAuthProvider as default };