@cloudflare/workers-oauth-provider 0.1.0 → 0.2.3

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