@vitemcp/server 1.0.0

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,961 @@
1
+ interface ClientIdMetadataOptions {
2
+ /**
3
+ * Trust policy: hosts allowed to serve metadata. Exact match, or suffix when
4
+ * written `.example.com`. Omitted allows any public host.
5
+ */
6
+ allowedDomains?: string[];
7
+ /** How long a fetched document may be reused when the response gives no cache headers. */
8
+ defaultCacheTtlMs?: number;
9
+ /** Whether CIMD is served at all. */
10
+ enabled?: boolean;
11
+ /** Abort a metadata fetch after this long. */
12
+ fetchTimeoutMs?: number;
13
+ /** Reject documents larger than this. */
14
+ maxDocumentBytes?: number;
15
+ }
16
+
17
+ /**
18
+ * OAuth Proxy Types
19
+ * Type definitions for the OAuth 2.1 Proxy implementation
20
+ */
21
+ /**
22
+ * Default TTL values for token expiration (in seconds)
23
+ */
24
+ declare const DEFAULT_ACCESS_TOKEN_TTL = 3600;
25
+ declare const DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH = 31536000;
26
+ declare const DEFAULT_REFRESH_TOKEN_TTL = 2592000;
27
+ declare const DEFAULT_AUTHORIZATION_CODE_TTL = 300;
28
+ declare const DEFAULT_TRANSACTION_TTL = 600;
29
+ /**
30
+ * OAuth authorization request parameters
31
+ */
32
+ interface AuthorizationParams {
33
+ [key: string]: unknown;
34
+ client_id: string;
35
+ code_challenge?: string;
36
+ code_challenge_method?: string;
37
+ redirect_uri: string;
38
+ response_type: string;
39
+ scope?: string;
40
+ state?: string;
41
+ }
42
+ /**
43
+ * Authorization code storage with PKCE validation
44
+ */
45
+ interface ClientCode {
46
+ /** Client ID that owns this code */
47
+ clientId: string;
48
+ /** Authorization code */
49
+ code: string;
50
+ /** PKCE code challenge for validation */
51
+ codeChallenge: string;
52
+ /** PKCE code challenge method */
53
+ codeChallengeMethod: string;
54
+ /** Code creation timestamp */
55
+ createdAt: Date;
56
+ /** Code expiration timestamp */
57
+ expiresAt: Date;
58
+ transactionId: string;
59
+ /** Upstream tokens obtained from provider */
60
+ upstreamTokens: UpstreamTokenSet;
61
+ /** Whether code has been used */
62
+ used?: boolean;
63
+ }
64
+ /**
65
+ * Consent data for user approval
66
+ */
67
+ interface ConsentData {
68
+ clientName: string;
69
+ provider: string;
70
+ scope: string[];
71
+ timestamp: number;
72
+ transactionId: string;
73
+ }
74
+ /**
75
+ * Custom claims passthrough configuration
76
+ */
77
+ interface CustomClaimsPassthroughConfig {
78
+ /** Allow nested objects/arrays in claims. Default: false (only primitives) */
79
+ allowComplexClaims?: boolean;
80
+ /** Only passthrough these specific claims (allowlist). Default: undefined (allow all non-protected) */
81
+ allowedClaims?: string[];
82
+ /** Never passthrough these claims (blocklist, in addition to protected claims). Default: [] */
83
+ blockedClaims?: string[];
84
+ /** Prefix upstream claims to prevent collisions. Default: false (no prefix) */
85
+ claimPrefix?: false | string;
86
+ /** Enable passthrough from upstream access token (if JWT format). Default: true */
87
+ fromAccessToken?: boolean;
88
+ /** Enable passthrough from upstream ID token. Default: true */
89
+ fromIdToken?: boolean;
90
+ /** Maximum length for claim values. Default: 2000 */
91
+ maxClaimValueSize?: number;
92
+ }
93
+ /**
94
+ * Client metadata for storage
95
+ */
96
+ interface DCRClientMetadata {
97
+ /** OpenID Connect application type (`"native"` or `"web"`). */
98
+ application_type?: "native" | "web";
99
+ client_name?: string;
100
+ client_uri?: string;
101
+ contacts?: string[];
102
+ jwks?: Record<string, unknown>;
103
+ jwks_uri?: string;
104
+ logo_uri?: string;
105
+ policy_uri?: string;
106
+ scope?: string;
107
+ software_id?: string;
108
+ software_version?: string;
109
+ tos_uri?: string;
110
+ }
111
+ /**
112
+ * RFC 7591 Dynamic Client Registration Request
113
+ */
114
+ interface DCRRequest {
115
+ /**
116
+ * OpenID Connect application type: `"native"` for local/loopback clients,
117
+ * `"web"` for hosted ones. Required of MCP clients by SEP-837 so that
118
+ * OpenID-aware authorization servers do not mis-apply redirect-URI rules.
119
+ */
120
+ application_type?: "native" | "web";
121
+ client_name?: string;
122
+ /** Client homepage URL */
123
+ client_uri?: string;
124
+ /** Contact email addresses */
125
+ contacts?: string[];
126
+ /** Allowed grant types */
127
+ grant_types?: string[];
128
+ /** JWKS object */
129
+ jwks?: Record<string, unknown>;
130
+ jwks_uri?: string;
131
+ /** Client logo URL */
132
+ logo_uri?: string;
133
+ /** Privacy policy URL */
134
+ policy_uri?: string;
135
+ /** REQUIRED: Array of redirect URIs */
136
+ redirect_uris: string[];
137
+ /** Allowed response types */
138
+ response_types?: string[];
139
+ /** Requested scope */
140
+ scope?: string;
141
+ /** Software identifier */
142
+ software_id?: string;
143
+ software_version?: string;
144
+ /** Token endpoint authentication method */
145
+ token_endpoint_auth_method?: string;
146
+ /** Terms of service URL */
147
+ tos_uri?: string;
148
+ }
149
+ /**
150
+ * RFC 7591 Dynamic Client Registration Response
151
+ */
152
+ interface DCRResponse {
153
+ /** Echoed application type, so the client can confirm what was registered. */
154
+ application_type?: "native" | "web";
155
+ /** REQUIRED: Client identifier */
156
+ client_id: string;
157
+ /** Client ID issued timestamp */
158
+ client_id_issued_at?: number;
159
+ client_name?: string;
160
+ client_secret?: string;
161
+ /** Client secret expiration (0 = never) */
162
+ client_secret_expires_at?: number;
163
+ client_uri?: string;
164
+ contacts?: string[];
165
+ grant_types?: string[];
166
+ jwks?: Record<string, unknown>;
167
+ jwks_uri?: string;
168
+ logo_uri?: string;
169
+ policy_uri?: string;
170
+ /** Echo back all registered metadata */
171
+ redirect_uris: string[];
172
+ registration_access_token?: string;
173
+ registration_client_uri?: string;
174
+ response_types?: string[];
175
+ scope?: string;
176
+ software_id?: string;
177
+ software_version?: string;
178
+ token_endpoint_auth_method?: string;
179
+ tos_uri?: string;
180
+ }
181
+ /**
182
+ * OAuth error response
183
+ */
184
+ interface OAuthError {
185
+ error: string;
186
+ error_description?: string;
187
+ error_uri?: string;
188
+ }
189
+ /**
190
+ * OAuth Proxy provider for pre-configured providers
191
+ */
192
+ interface OAuthProviderConfig {
193
+ baseUrl: string;
194
+ clientId: string;
195
+ clientSecret: string;
196
+ consentRequired?: boolean;
197
+ scopes?: string[];
198
+ }
199
+ /**
200
+ * Configuration for the OAuth Proxy
201
+ */
202
+ interface OAuthProxyConfig {
203
+ /** Access token TTL in seconds (default: 3600) */
204
+ accessTokenTtl?: number;
205
+ /**
206
+ * Allow-list of redirect URI patterns accepted by Dynamic Client Registration.
207
+ *
208
+ * A client calling POST /oauth/register must present a `redirect_uri` that
209
+ * matches one of these patterns (exact string or glob with `*` / `?`);
210
+ * otherwise the registration is rejected with `invalid_redirect_uri`. Once
211
+ * registered, the same exact URI must be echoed back at /oauth/authorize —
212
+ * the proxy performs an exact per-client match per RFC 6749 §3.1.2.3.
213
+ *
214
+ * Behaviour by value:
215
+ * - `undefined` (default): allow `http://localhost:*` and `http://127.0.0.1:*`
216
+ * only. Covers the standard MCP use-case of dynamic loopback ports.
217
+ * - `[]` (empty array): DCR rejects every URI — use for deployments that
218
+ * configure patterns explicitly and want no implicit fallback.
219
+ * - `["pattern", ...]`: accept URIs matching any glob pattern in the list.
220
+ *
221
+ * Do not widen the default beyond loopback addresses — allowing arbitrary
222
+ * https URLs enables CWE-601 open-redirect / authorization-code theft.
223
+ */
224
+ allowedRedirectUriPatterns?: string[];
225
+ /** Authorization code TTL in seconds (default: 300) */
226
+ authorizationCodeTtl?: number;
227
+ /** Base URL of this proxy server */
228
+ baseUrl: string;
229
+ /**
230
+ * Client ID Metadata Document support (the mechanism that supersedes DCR).
231
+ *
232
+ * Enabled by default. Because resolving a URL-formatted `client_id` means
233
+ * fetching a client-supplied URL, the resolver refuses internal addresses,
234
+ * does not follow redirects, and caps both response size and time; set
235
+ * `allowedDomains` to narrow it further to hosts you trust.
236
+ */
237
+ clientIdMetadata?: ClientIdMetadataOptions;
238
+ /** Require user consent (default: true) */
239
+ consentRequired?: boolean;
240
+ /** Secret key for signing consent cookies */
241
+ consentSigningKey?: string;
242
+ /**
243
+ * Custom claims passthrough configuration.
244
+ * When enabled (default), extracts custom claims from upstream access token and ID token
245
+ * and includes them in the proxy's issued JWT tokens.
246
+ * This enables authorization based on upstream roles, permissions, etc.
247
+ * Set to false to disable claims passthrough entirely.
248
+ * Default: true (enabled with default settings)
249
+ */
250
+ customClaimsPassthrough?: boolean | CustomClaimsPassthroughConfig;
251
+ /** Enable token swap pattern (default: true) - issues short-lived JWTs instead of passing through upstream tokens */
252
+ enableTokenSwap?: boolean;
253
+ /** Encryption key for token storage (default: auto-generated). Set to false to disable encryption. */
254
+ encryptionKey?: false | string;
255
+ /**
256
+ * Extra query parameters appended to the upstream authorization URL.
257
+ * Required by providers such as Google, which only issues a refresh_token
258
+ * when the authorization request carries `access_type=offline` (and
259
+ * re-issues it on re-auth with `prompt=consent`). Without these, access
260
+ * expires after the upstream token TTL and can never be renewed.
261
+ *
262
+ * Core OAuth parameters managed by the proxy (client_id, redirect_uri,
263
+ * response_type, state, scope, code_challenge, code_challenge_method)
264
+ * cannot be overridden — entries with those keys are ignored.
265
+ */
266
+ extraAuthorizationParams?: Record<string, string>;
267
+ /** Forward client's PKCE to upstream (default: false) */
268
+ forwardPkce?: boolean;
269
+ /** Secret key for signing JWTs when token swap is enabled */
270
+ jwtSigningKey?: string;
271
+ /** OAuth callback path (default: /oauth/callback) */
272
+ redirectPath?: string;
273
+ /** Refresh token TTL in seconds (default: 2592000) */
274
+ refreshTokenTtl?: number;
275
+ /** Scopes to request from upstream provider */
276
+ scopes?: string[];
277
+ /** Custom token storage backend */
278
+ tokenStorage?: TokenStorage;
279
+ /** Custom token verifier for validating upstream tokens */
280
+ tokenVerifier?: TokenVerifier;
281
+ /** Transaction TTL in seconds (default: 600) */
282
+ transactionTtl?: number;
283
+ /** Upstream provider's authorization endpoint URL */
284
+ upstreamAuthorizationEndpoint: string;
285
+ /** Pre-registered client ID with upstream provider */
286
+ upstreamClientId: string;
287
+ /** Pre-registered client secret with upstream provider */
288
+ upstreamClientSecret: string;
289
+ /**
290
+ * Issuer identifier of the upstream authorization server, used to validate
291
+ * the `iss` parameter on authorization responses (RFC 9207).
292
+ *
293
+ * Defaults to the origin of `upstreamAuthorizationEndpoint`. Set this when
294
+ * the provider's issuer differs from that origin.
295
+ */
296
+ upstreamIssuer?: string;
297
+ /** Timeout in milliseconds for upstream token/refresh HTTP requests (default: 10000) */
298
+ upstreamRequestTimeoutMs?: number;
299
+ /** Upstream provider's token endpoint URL */
300
+ upstreamTokenEndpoint: string;
301
+ /** Upstream token endpoint authentication method (default: "client_secret_basic") */
302
+ upstreamTokenEndpointAuthMethod?: "client_secret_basic" | "client_secret_post";
303
+ }
304
+ /**
305
+ * OAuth transaction tracking active authorization flows
306
+ */
307
+ interface OAuthTransaction {
308
+ /** Client's callback URL */
309
+ clientCallbackUrl: string;
310
+ /** Client's PKCE code challenge */
311
+ clientCodeChallenge: string;
312
+ /** Client's PKCE code challenge method (S256 or plain) */
313
+ clientCodeChallengeMethod: string;
314
+ /** Client ID from registration */
315
+ clientId: string;
316
+ /** Whether user consent was given */
317
+ consentGiven?: boolean;
318
+ /** Transaction creation timestamp */
319
+ createdAt: Date;
320
+ /** Transaction expiration timestamp */
321
+ expiresAt: Date;
322
+ /** Unique transaction ID */
323
+ id: string;
324
+ /** Additional state data */
325
+ metadata?: Record<string, unknown>;
326
+ /** Proxy-generated PKCE challenge for upstream */
327
+ proxyCodeChallenge: string;
328
+ /** Proxy-generated PKCE verifier for upstream */
329
+ proxyCodeVerifier: string;
330
+ /** Requested scopes */
331
+ scope: string[];
332
+ /** OAuth state parameter */
333
+ state: string;
334
+ /**
335
+ * Issuer identifier of the upstream authorization server this transaction
336
+ * was started against, recorded so the `iss` returned on the callback can be
337
+ * validated against it (RFC 9207).
338
+ */
339
+ upstreamIssuer: string;
340
+ }
341
+ /**
342
+ * PKCE pair
343
+ */
344
+ interface PKCEPair {
345
+ challenge: string;
346
+ verifier: string;
347
+ }
348
+ /**
349
+ * Dynamic client registration data
350
+ */
351
+ interface ProxyDCRClient {
352
+ /** Primary (first) registered callback URL */
353
+ callbackUrl: string;
354
+ /** Proxy-issued client ID (not the upstream provider's client_id) */
355
+ clientId: string;
356
+ /** Proxy-issued client secret (not the upstream provider's client_secret) */
357
+ clientSecret?: string;
358
+ /** Client metadata from registration request */
359
+ metadata?: DCRClientMetadata;
360
+ /** All redirect URIs registered by this client */
361
+ redirectUris: string[];
362
+ /** Client registration timestamp */
363
+ registeredAt: Date;
364
+ }
365
+ /**
366
+ * OAuth refresh token request
367
+ */
368
+ interface RefreshRequest {
369
+ client_id: string;
370
+ client_secret?: string;
371
+ grant_type: "refresh_token";
372
+ refresh_token: string;
373
+ scope?: string;
374
+ }
375
+ /**
376
+ * Token mapping for JWT swap pattern
377
+ * Maps JTI to upstream token reference
378
+ */
379
+ interface TokenMapping {
380
+ clientId: string;
381
+ /** Creation timestamp */
382
+ createdAt: Date;
383
+ /** Expiration timestamp */
384
+ expiresAt: Date;
385
+ /** JTI from ViteMCP JWT */
386
+ jti: string;
387
+ /** Scopes */
388
+ scope: string[];
389
+ /** Reference to upstream token set */
390
+ upstreamTokenKey: string;
391
+ }
392
+ /**
393
+ * OAuth token request
394
+ */
395
+ interface TokenRequest {
396
+ client_id: string;
397
+ client_secret?: string;
398
+ code: string;
399
+ code_verifier?: string;
400
+ grant_type: "authorization_code";
401
+ redirect_uri: string;
402
+ }
403
+ /**
404
+ * OAuth token response
405
+ */
406
+ interface TokenResponse {
407
+ access_token: string;
408
+ expires_in: number;
409
+ id_token?: string;
410
+ refresh_token?: string;
411
+ scope?: string;
412
+ token_type: string;
413
+ }
414
+ /**
415
+ * Token storage interface
416
+ */
417
+ interface TokenStorage {
418
+ /** Clean up expired entries */
419
+ cleanup(): Promise<void>;
420
+ /** Delete a value */
421
+ delete(key: string): Promise<void>;
422
+ /** Retrieve a value */
423
+ get(key: string): Promise<null | unknown>;
424
+ /** Save a value with optional TTL */
425
+ save(key: string, value: unknown, ttl?: number): Promise<void>;
426
+ /**
427
+ * Atomically retrieve a value and delete it, returning `null` if the key was
428
+ * absent. At most one caller may observe a given value.
429
+ *
430
+ * Optional, but **required for correctness whenever concurrent requests can
431
+ * reach the same record** — which includes a single process, since the check
432
+ * and the delete straddle an await. The OAuth proxy consumes authorization
433
+ * codes, transactions and refresh-token mappings through it, and single-use
434
+ * enforcement depends on the atomicity. Without it the proxy falls back to a
435
+ * non-atomic get + delete, where two concurrent requests can both redeem the
436
+ * same authorization code, or both redeem the same refresh token and walk
437
+ * away with two independent token chains.
438
+ *
439
+ * Most backends expose a suitable primitive: Redis `GETDEL`, DynamoDB
440
+ * `DeleteItem` with `ReturnValues: "ALL_OLD"`, or SQL
441
+ * `DELETE ... RETURNING *`.
442
+ */
443
+ take?(key: string): Promise<null | unknown>;
444
+ }
445
+ /**
446
+ * Token verification result
447
+ */
448
+ interface TokenVerificationResult {
449
+ claims?: Record<string, unknown>;
450
+ error?: string;
451
+ valid: boolean;
452
+ }
453
+ /**
454
+ * Token verifier for validating upstream tokens
455
+ */
456
+ interface TokenVerifier {
457
+ verify(token: string): Promise<TokenVerificationResult>;
458
+ }
459
+ /**
460
+ * Token set from upstream OAuth provider
461
+ */
462
+ interface UpstreamTokenSet {
463
+ accessToken: string;
464
+ /** Token expiration in seconds */
465
+ expiresIn: number;
466
+ /** ID token (for OIDC) */
467
+ idToken?: string;
468
+ /** Token issuance timestamp */
469
+ issuedAt: Date;
470
+ /** Refresh token expiration in seconds (if provided by upstream) */
471
+ refreshExpiresIn?: number;
472
+ /** Refresh token (if provided) */
473
+ refreshToken?: string;
474
+ /** Granted scopes */
475
+ scope: string[];
476
+ /** Token type (usually "Bearer") */
477
+ tokenType: string;
478
+ }
479
+
480
+ /**
481
+ * OAuth 2.1 Proxy Implementation
482
+ * Provides DCR-compatible interface for non-DCR OAuth providers
483
+ */
484
+
485
+ /**
486
+ * OAuth 2.1 Proxy
487
+ * Acts as transparent intermediary between MCP clients and upstream OAuth providers
488
+ */
489
+ declare class OAuthProxy {
490
+ private claimsExtractor;
491
+ private cleanupInterval;
492
+ private clientIdMetadata;
493
+ private config;
494
+ private consentManager;
495
+ private issuerNs;
496
+ private jwtIssuer?;
497
+ /**
498
+ * Keyed by proxy-issued client_id for authorize/token-exchange lookups and
499
+ * for the defence-in-depth callback checks. A registration never changes
500
+ * after it is written, so caching it locally cannot go stale; it is also
501
+ * persisted, so another instance can hydrate it.
502
+ */
503
+ private registeredClientsByClientId;
504
+ private stateStore;
505
+ private tokenStorage;
506
+ constructor(config: OAuthProxyConfig);
507
+ /**
508
+ * OAuth authorization endpoint
509
+ */
510
+ authorize(params: AuthorizationParams): Promise<Response>;
511
+ /**
512
+ * Stop cleanup interval and destroy resources
513
+ */
514
+ destroy(): void;
515
+ /**
516
+ * Token endpoint - exchange authorization code for tokens
517
+ */
518
+ exchangeAuthorizationCode(request: TokenRequest): Promise<TokenResponse>;
519
+ /**
520
+ * Token endpoint - refresh access token
521
+ */
522
+ exchangeRefreshToken(request: RefreshRequest): Promise<TokenResponse>;
523
+ /**
524
+ * Get OAuth discovery metadata
525
+ */
526
+ getAuthorizationServerMetadata(): {
527
+ authorizationEndpoint: string;
528
+ authorizationResponseIssParameterSupported?: boolean;
529
+ clientIdMetadataDocumentSupported?: boolean;
530
+ codeChallengeMethodsSupported?: string[];
531
+ dpopSigningAlgValuesSupported?: string[];
532
+ grantTypesSupported?: string[];
533
+ introspectionEndpoint?: string;
534
+ issuer: string;
535
+ jwksUri?: string;
536
+ opPolicyUri?: string;
537
+ opTosUri?: string;
538
+ registrationEndpoint?: string;
539
+ responseModesSupported?: string[];
540
+ responseTypesSupported: string[];
541
+ revocationEndpoint?: string;
542
+ scopesSupported?: string[];
543
+ serviceDocumentation?: string;
544
+ tokenEndpoint: string;
545
+ tokenEndpointAuthMethodsSupported?: string[];
546
+ tokenEndpointAuthSigningAlgValuesSupported?: string[];
547
+ uiLocalesSupported?: string[];
548
+ };
549
+ /**
550
+ * Handle OAuth callback from upstream provider
551
+ */
552
+ handleCallback(request: Request): Promise<Response>;
553
+ /**
554
+ * Handle consent form submission
555
+ */
556
+ handleConsent(request: Request): Promise<Response>;
557
+ /**
558
+ * Load upstream tokens from a ViteMCP JWT
559
+ */
560
+ loadUpstreamTokens(vitemcpToken: string): Promise<null | UpstreamTokenSet>;
561
+ /**
562
+ * RFC 7591 Dynamic Client Registration
563
+ */
564
+ registerClient(request: DCRRequest): Promise<DCRResponse>;
565
+ /**
566
+ * Calculate access token TTL from upstream tokens
567
+ */
568
+ private calculateAccessTokenTtl;
569
+ /**
570
+ * Periodic maintenance hook. Expiry is enforced by the token storage.
571
+ */
572
+ private cleanup;
573
+ /**
574
+ * Create a new OAuth transaction
575
+ */
576
+ private createTransaction;
577
+ /**
578
+ * Exchange authorization code with upstream provider
579
+ */
580
+ private exchangeUpstreamCode;
581
+ /**
582
+ * Extract JTI from a JWT token
583
+ */
584
+ private extractJti;
585
+ /**
586
+ * Extract custom claims from upstream tokens
587
+ * Combines claims from access token and ID token (if present)
588
+ */
589
+ private extractUpstreamClaims;
590
+ /**
591
+ * POST to the upstream token endpoint with a bounded wait.
592
+ *
593
+ * Maps an abort of the configured timeout signal to a clean OAuth error
594
+ * instead of letting the raw `TimeoutError`/`AbortError` propagate.
595
+ */
596
+ private fetchUpstream;
597
+ /**
598
+ * Generate authorization code for client
599
+ */
600
+ private generateAuthorizationCode;
601
+ /**
602
+ * Generate secure random ID
603
+ */
604
+ private generateId;
605
+ /**
606
+ * Generate signing key for consent cookies
607
+ */
608
+ private generateSigningKey;
609
+ /**
610
+ * Generate Basic auth header value for upstream token endpoint
611
+ * Per RFC 6749 Section 2.3.1, credentials must be URL-encoded before base64 encoding
612
+ */
613
+ private getBasicAuthHeader;
614
+ /**
615
+ * Get provider name for display
616
+ */
617
+ private getProviderName;
618
+ /**
619
+ * Issuer identifier of the upstream authorization server.
620
+ *
621
+ * Defaults to the origin of the configured authorization endpoint, which is
622
+ * what RFC 8414 issuers look like in practice; override with
623
+ * `upstreamIssuer` when the provider's issuer differs from its endpoint host
624
+ * (e.g. a tenant-scoped path).
625
+ */
626
+ private getUpstreamIssuer;
627
+ /**
628
+ * Handle passthrough mode refresh - forward refresh token directly to upstream
629
+ */
630
+ private handlePassthroughRefresh;
631
+ /**
632
+ * Handle swap mode refresh - verify ViteMCP JWT and issue new tokens
633
+ */
634
+ private handleSwapModeRefresh;
635
+ /**
636
+ * Issue swapped tokens (JWT pattern)
637
+ * Issues short-lived ViteMCP JWTs and stores upstream tokens securely
638
+ */
639
+ private issueSwappedTokens;
640
+ /**
641
+ * Issue swapped tokens for refresh flow
642
+ */
643
+ private issueSwappedTokensForRefresh;
644
+ /**
645
+ * Match URI against pattern (supports wildcards)
646
+ */
647
+ private matchesPattern;
648
+ /**
649
+ * Parse token response that can be either JSON or URL-encoded
650
+ * GitHub Apps return URL-encoded format, most providers return JSON
651
+ */
652
+ private parseTokenResponse;
653
+ /**
654
+ * Redirect to upstream OAuth provider
655
+ */
656
+ private redirectToUpstream;
657
+ /**
658
+ * Refresh upstream tokens with provider
659
+ */
660
+ private refreshUpstreamTokens;
661
+ /**
662
+ * Redirect URIs the given client is allowed to use.
663
+ *
664
+ * A URL-formatted client_id is resolved as a Client ID Metadata Document
665
+ * (the preferred mechanism on this revision); anything else must have been
666
+ * registered through DCR.
667
+ */
668
+ private resolveClientRedirectUris;
669
+ /**
670
+ * Put a claimed refresh-token mapping back after a rotation failed, keeping
671
+ * whatever lifetime it had left.
672
+ *
673
+ * A mapping that is already expired, or that carries no usable expiry, is
674
+ * dropped instead. Inventing a TTL here would extend the lifetime of a
675
+ * credential in a security path, and every mapping this proxy writes records
676
+ * `expiresAt`.
677
+ */
678
+ private restoreMapping;
679
+ /**
680
+ * Start periodic cleanup of expired transactions and codes
681
+ */
682
+ private startCleanup;
683
+ /**
684
+ * Atomically claim a token mapping, mirroring `OAuthProxyStateStore`: at most
685
+ * one caller — across all processes sharing the storage — can receive a given
686
+ * mapping, which is what makes single use enforceable. Falls back to a
687
+ * non-atomic get + delete for storages that do not implement `take`.
688
+ */
689
+ private takeMapping;
690
+ /**
691
+ * Validate a redirect URI against the configured allow-list.
692
+ *
693
+ * Behaviour by configuration value:
694
+ * - `undefined` (not set): allow localhost/127.0.0.1 only — safe default
695
+ * that covers the common MCP use-case of dynamic loopback ports without
696
+ * opening the proxy to arbitrary redirect URIs.
697
+ * - `[]` (empty array): reject every URI — opt-in strict mode for deployments
698
+ * that want full control and will configure patterns explicitly.
699
+ * - `["pattern", ...]`: accept URIs matching any of the glob patterns.
700
+ *
701
+ * Prior versions defaulted to `["https://*", "http://localhost:*"]` which
702
+ * matched any https URL, enabling CWE-601 open-redirect / authorization-code
703
+ * theft. Do not loosen the default beyond loopback addresses.
704
+ */
705
+ private validateRedirectUri;
706
+ }
707
+ declare class OAuthProxyError extends Error {
708
+ code: string;
709
+ description?: string | undefined;
710
+ statusCode: number;
711
+ constructor(code: string, description?: string | undefined, statusCode?: number);
712
+ toJSON(): OAuthError;
713
+ toResponse(): Response;
714
+ }
715
+
716
+ /**
717
+ * AuthProvider Base Class
718
+ * High-level abstraction for OAuth authentication that simplifies configuration
719
+ */
720
+
721
+ /**
722
+ * Configuration common to all OAuth providers.
723
+ */
724
+ interface AuthProviderConfig {
725
+ /**
726
+ * Allow-list of redirect URI patterns accepted by Dynamic Client
727
+ * Registration. Required for any deployment that exposes /oauth/register
728
+ * or /oauth/authorize — an empty/unset list rejects every URI.
729
+ *
730
+ * Example: `["https://yourapp.example.com/*"]`
731
+ *
732
+ * Prior versions defaulted to `["http://localhost:*", "https://*"]`, which
733
+ * enabled CWE-601 open-redirect / authorization-code theft. See the
734
+ * SECURITY advisory before loosening this.
735
+ */
736
+ allowedRedirectUriPatterns?: string[];
737
+ /** Base URL where the MCP server is accessible */
738
+ baseUrl: string;
739
+ /** OAuth client ID */
740
+ clientId: string;
741
+ /** OAuth client secret */
742
+ clientSecret: string;
743
+ /** Require user consent screen (default: true) */
744
+ consentRequired?: boolean;
745
+ /** Encryption key for token storage (auto-generated if not provided, set to false to disable) */
746
+ encryptionKey?: false | string;
747
+ /** JWT signing key (auto-generated if not provided) */
748
+ jwtSigningKey?: string;
749
+ /** Scopes to request (defaults vary by provider) */
750
+ scopes?: string[];
751
+ /** Token storage backend (default: MemoryTokenStorage) */
752
+ tokenStorage?: TokenStorage;
753
+ }
754
+ /**
755
+ * Configuration for generic OAuth provider (user-specified endpoints).
756
+ */
757
+ interface GenericOAuthProviderConfig extends AuthProviderConfig {
758
+ /** OAuth authorization endpoint URL */
759
+ authorizationEndpoint: string;
760
+ /** OAuth token endpoint URL */
761
+ tokenEndpoint: string;
762
+ /** Token endpoint auth method (default: "client_secret_basic") */
763
+ tokenEndpointAuthMethod?: "client_secret_basic" | "client_secret_post";
764
+ }
765
+ /**
766
+ * Standard session type for OAuth providers.
767
+ * Contains the upstream access token and optional metadata.
768
+ */
769
+ interface OAuthSession {
770
+ /** The upstream OAuth access token */
771
+ accessToken: string;
772
+ /** Additional claims extracted from the token (if customClaimsPassthrough enabled) */
773
+ claims?: Record<string, unknown>;
774
+ /** Token expiration time (Unix timestamp in seconds) */
775
+ expiresAt?: number;
776
+ /** ID token from OIDC providers */
777
+ idToken?: string;
778
+ /** Refresh token (if available) */
779
+ refreshToken?: string;
780
+ /** Scopes granted by the OAuth provider */
781
+ scopes?: string[];
782
+ }
783
+ /**
784
+ * Abstract base class for OAuth providers.
785
+ * Encapsulates OAuthProxy creation, authenticate function, and oauth config.
786
+ *
787
+ * Subclasses only need to implement the endpoint and default scope methods.
788
+ */
789
+ declare abstract class AuthProvider<TSession extends OAuthSession = OAuthSession> {
790
+ protected config: AuthProviderConfig;
791
+ /**
792
+ * Get the proxy, creating it lazily if needed.
793
+ */
794
+ protected get proxy(): OAuthProxy;
795
+ private _proxy;
796
+ constructor(config: AuthProviderConfig);
797
+ /**
798
+ * Authenticate function to be used by ViteMCP.
799
+ * Extracts Bearer token, validates it, and returns session with upstream access token.
800
+ */
801
+ authenticate(request: Request | undefined): Promise<TSession | undefined>;
802
+ /**
803
+ * Get the OAuth configuration object for ViteMCP ServerOptions.
804
+ */
805
+ getOAuthConfig(): {
806
+ authorizationServer: ReturnType<OAuthProxy["getAuthorizationServerMetadata"]>;
807
+ enabled: true;
808
+ protectedResource: {
809
+ authorizationServers: string[];
810
+ resource: string;
811
+ scopesSupported: string[];
812
+ };
813
+ proxy: OAuthProxy;
814
+ };
815
+ /**
816
+ * Get the OAuthProxy instance (for advanced use cases).
817
+ */
818
+ getProxy(): OAuthProxy;
819
+ /** Create the underlying OAuthProxy with provider-specific configuration */
820
+ protected abstract createProxy(): OAuthProxy;
821
+ /**
822
+ * Create a session object from upstream tokens.
823
+ * Override in subclasses to add provider-specific session data.
824
+ */
825
+ protected createSession(upstreamTokens: UpstreamTokenSet): TSession;
826
+ /** Get the authorization endpoint for this provider */
827
+ protected abstract getAuthorizationEndpoint(): string;
828
+ /** Default scopes for this provider */
829
+ protected abstract getDefaultScopes(): string[];
830
+ /** Get the token endpoint for this provider */
831
+ protected abstract getTokenEndpoint(): string;
832
+ }
833
+
834
+ /**
835
+ * Authentication Helper Functions
836
+ * Utility functions for use with canAccess on tools, resources, and prompts
837
+ */
838
+
839
+ type SessionAuth = Record<string, unknown> | undefined;
840
+ /**
841
+ * Extract and type-cast OAuth session from canAccess context.
842
+ * Throws if session is undefined (use with canAccess: requireAuth).
843
+ */
844
+ declare function getAuthSession<T extends OAuthSession = OAuthSession>(session: SessionAuth): T;
845
+ /**
846
+ * Combines multiple canAccess checks with AND logic.
847
+ */
848
+ declare function requireAll<T extends SessionAuth>(...checks: Array<((auth: T) => boolean) | boolean>): (auth: T) => boolean;
849
+ /**
850
+ * Combines multiple canAccess checks with OR logic.
851
+ */
852
+ declare function requireAny<T extends SessionAuth>(...checks: Array<((auth: T) => boolean) | boolean>): (auth: T) => boolean;
853
+ /**
854
+ * Requires any authenticated session.
855
+ */
856
+ declare function requireAuth<T extends SessionAuth>(auth: T): boolean;
857
+ /**
858
+ * Requires session to have a specific role (OR logic for multiple roles).
859
+ */
860
+ declare function requireRole<T extends SessionAuth>(...allowedRoles: string[]): (auth: T) => boolean;
861
+ /**
862
+ * Requires session to have specific scopes.
863
+ */
864
+ declare function requireScopes<T extends SessionAuth>(...requiredScopes: string[]): (auth: T) => boolean;
865
+
866
+ /**
867
+ * Microsoft Azure/Entra ID OAuth Provider
868
+ * Pre-configured OAuth provider for Microsoft Identity Platform
869
+ */
870
+
871
+ /**
872
+ * Azure-specific configuration
873
+ */
874
+ interface AzureProviderConfig extends AuthProviderConfig {
875
+ /** Tenant ID or 'common', 'organizations', 'consumers' (default: 'common') */
876
+ tenantId?: string;
877
+ }
878
+ /**
879
+ * Azure-specific session with additional user info
880
+ */
881
+ interface AzureSession extends OAuthSession {
882
+ upn?: string;
883
+ }
884
+ /**
885
+ * Microsoft Azure AD / Entra ID OAuth 2.0 Provider
886
+ * Callback URL: {baseUrl}/oauth/callback
887
+ */
888
+ declare class AzureProvider extends AuthProvider<AzureSession> {
889
+ private tenantId;
890
+ constructor(config: AzureProviderConfig);
891
+ protected createProxy(): OAuthProxy;
892
+ protected getAuthorizationEndpoint(): string;
893
+ protected getDefaultScopes(): string[];
894
+ protected getTokenEndpoint(): string;
895
+ }
896
+
897
+ /**
898
+ * GitHub OAuth Provider
899
+ * Pre-configured OAuth provider for GitHub OAuth Apps
900
+ */
901
+
902
+ /**
903
+ * GitHub-specific session with additional user info
904
+ */
905
+ interface GitHubSession extends OAuthSession {
906
+ username?: string;
907
+ }
908
+ /**
909
+ * GitHub OAuth 2.0 Provider
910
+ * Callback URL: {baseUrl}/oauth/callback
911
+ */
912
+ declare class GitHubProvider extends AuthProvider<GitHubSession> {
913
+ constructor(config: AuthProviderConfig);
914
+ protected createProxy(): OAuthProxy;
915
+ protected getAuthorizationEndpoint(): string;
916
+ protected getDefaultScopes(): string[];
917
+ protected getTokenEndpoint(): string;
918
+ }
919
+
920
+ /**
921
+ * Google OAuth Provider
922
+ * Pre-configured OAuth provider for Google Identity Platform
923
+ */
924
+
925
+ /**
926
+ * Google-specific session with additional user info
927
+ */
928
+ interface GoogleSession extends OAuthSession {
929
+ email?: string;
930
+ }
931
+ /**
932
+ * Google OAuth 2.0 Provider
933
+ * Callback URL: {baseUrl}/oauth/callback
934
+ */
935
+ declare class GoogleProvider extends AuthProvider<GoogleSession> {
936
+ constructor(config: AuthProviderConfig);
937
+ protected createProxy(): OAuthProxy;
938
+ protected getAuthorizationEndpoint(): string;
939
+ protected getDefaultScopes(): string[];
940
+ protected getTokenEndpoint(): string;
941
+ }
942
+
943
+ /**
944
+ * Generic OAuth Provider
945
+ * For any OAuth 2.0 compliant authorization server
946
+ */
947
+
948
+ /**
949
+ * Generic OAuth provider for any OAuth 2.0 compliant authorization server.
950
+ * Use when there's no built-in provider for your identity provider.
951
+ */
952
+ declare class OAuthProvider<TSession extends OAuthSession = OAuthSession> extends AuthProvider<TSession> {
953
+ protected genericConfig: GenericOAuthProviderConfig;
954
+ constructor(config: GenericOAuthProviderConfig);
955
+ protected createProxy(): OAuthProxy;
956
+ protected getAuthorizationEndpoint(): string;
957
+ protected getDefaultScopes(): string[];
958
+ protected getTokenEndpoint(): string;
959
+ }
960
+
961
+ export { AuthProvider as A, type DCRClientMetadata as B, type ConsentData as C, DEFAULT_ACCESS_TOKEN_TTL as D, type DCRRequest as E, type DCRResponse as F, GitHubProvider as G, type OAuthError as H, type OAuthProviderConfig as I, type OAuthProxyConfig as J, type ProxyDCRClient as K, type TokenMapping as L, type TokenRequest as M, type TokenResponse as N, type OAuthSession as O, type PKCEPair as P, type RefreshRequest as R, type TokenStorage as T, type UpstreamTokenSet as U, OAuthProxy as a, AzureProvider as b, GoogleProvider as c, OAuthProvider as d, requireAny as e, requireAuth as f, getAuthSession as g, requireRole as h, requireScopes as i, type AuthProviderConfig as j, type AzureProviderConfig as k, type AzureSession as l, type GenericOAuthProviderConfig as m, type GitHubSession as n, type GoogleSession as o, type OAuthTransaction as p, type TokenVerifier as q, requireAll as r, type TokenVerificationResult as s, OAuthProxyError as t, DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH as u, DEFAULT_AUTHORIZATION_CODE_TTL as v, DEFAULT_REFRESH_TOKEN_TTL as w, DEFAULT_TRANSACTION_TTL as x, type AuthorizationParams as y, type ClientCode as z };