Repository navigation
Expand file tree
/
Copy pathauth.ts
More file actions
2610 lines (2394 loc) · 111 KB
/
Copy pathauth.ts
File metadata and controls
2610 lines (2394 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { CORS_IS_POSSIBLE } from '@modelcontextprotocol/client/_shims';
import type {
AuthorizationServerMetadata,
FetchLike,
OAuthClientInformation,
OAuthClientInformationFull,
OAuthClientInformationMixed,
OAuthClientMetadata,
OAuthMetadata,
OAuthProtectedResourceMetadata,
OAuthTokens,
StoredOAuthClientInformation,
StoredOAuthTokens
} from '@modelcontextprotocol/core-internal';
import {
brandedHasInstance,
checkResourceAllowed,
fetchWithinOrigin,
LATEST_PROTOCOL_VERSION,
OAuthClientInformationFullSchema,
OAuthError,
OAuthErrorCode,
OAuthErrorResponseSchema,
OAuthMetadataSchema,
OAuthProtectedResourceMetadataSchema,
OAuthTokensSchema,
OpenIdProviderDiscoveryMetadataSchema,
resourceUrlFromServerUrl,
stampErrorBrands,
withoutIssuer
} from '@modelcontextprotocol/core-internal';
import pkceChallenge from 'pkce-challenge';
import { AuthorizationServerMismatchError, InsecureTokenEndpointError, IssuerMismatchError, RegistrationRejectedError } from './authErrors';
import type { DpopSession } from './dpop';
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- referenced in JSDoc {@linkcode}
import type { withDpopFromProvider, withOAuth } from './middleware';
// Re-exported for back-compat — the canonical home is ./authErrors.js.
export { AuthorizationServerMismatchError, InsecureTokenEndpointError, IssuerMismatchError, RegistrationRejectedError } from './authErrors';
/**
* Function type for adding client authentication to token requests.
*/
export type AddClientAuthentication = (
headers: Headers,
params: URLSearchParams,
url: string | URL,
metadata?: AuthorizationServerMetadata
) => void | Promise<void>;
/**
* Context passed to {@linkcode AuthProvider.onUnauthorized} when the server
* responds with 401. Provides everything needed to refresh credentials.
*/
export interface UnauthorizedContext {
/** The 401 response — inspect `WWW-Authenticate` for resource metadata, scope, etc. */
response: Response;
/** The MCP server URL, for passing to {@linkcode auth} or discovery helpers. */
serverUrl: URL;
/** Fetch function configured with the transport's `requestInit`, for making auth requests. */
fetchFn: FetchLike;
}
/**
* Minimal interface for authenticating MCP client transports with bearer tokens.
*
* Transports call {@linkcode AuthProvider.token | token()} before every request
* to obtain the current token, and {@linkcode AuthProvider.onUnauthorized | onUnauthorized()}
* (if provided) when the server responds with 401, giving the provider a chance
* to refresh credentials before the transport retries once.
*
* For simple cases (API keys, gateway-managed tokens), implement only `token()`:
* ```typescript
* const authProvider: AuthProvider = { token: async () => process.env.API_KEY };
* ```
*
* For OAuth flows, pass an {@linkcode OAuthClientProvider} directly — transports
* accept either shape and adapt OAuth providers automatically via {@linkcode adaptOAuthProvider}.
*/
export interface AuthProvider {
/**
* Returns the current bearer token, or `undefined` if no token is available.
* Called before every request.
*/
token(): Promise<string | undefined>;
/**
* Called when the server responds with 401. If provided, the transport will
* await this, then retry the request once. If the retry also gets 401, the
* transport throws `SdkHttpError` (`SdkErrorCode.ClientHttpAuthentication`). If
* this method is not provided, the transport throws {@linkcode UnauthorizedError}.
*
* Implementations should refresh tokens, re-authenticate, etc. — whatever is
* needed so the next `token()` call returns a valid token.
*/
onUnauthorized?(ctx: UnauthorizedContext): Promise<void>;
}
/**
* Context passed to the credential-persistence methods on
* {@linkcode OAuthClientProvider} — `clientInformation` / `saveClientInformation`
* and `tokens` / `saveTokens`. Carries the resolved authorization-server `issuer`
* so provider implementations can key persisted credentials per authorization
* server (RFC 6749 §2.2 — client identifiers are unique to the AS that issued
* them). Providers that store a single credential set may ignore it.
*/
export interface OAuthClientInformationContext {
/**
* The authorization server's `issuer` identifier from its validated metadata
* document, used as the binding key for persisted credentials.
*/
issuer: string;
}
/**
* SEP-2352 stamp check: returns `stored` only when its `issuer` stamp matches the
* resolved authorization server. A stamp that names a *different* issuer reads back
* as `undefined`, so a credential issued by one authorization server is never reused
* at another — the flow falls through to re-registration / re-authorization exactly
* as if nothing were stored. An unstamped value (legacy provider or pre-SEP-2352
* storage) is returned as-is with a `console.warn`; {@linkcode auth} writes the
* stamp back on first use so the window closes after one call.
*
* {@linkcode auth} stamps every value it writes via `saveTokens` / `saveClientInformation`,
* so a provider that round-trips the stored object verbatim is protected with no extra
* code. Providers that hold credentials for multiple authorization servers key their
* storage on `ctx.issuer` instead.
*
* @param opts.canPersistStamp - When `false`, suppresses the unstamped-credential
* warning: the caller cannot back-stamp (no `saveClientInformation`), so the
* "binding on first use" claim would be false and would fire on every call.
*/
export function discardIfIssuerMismatch<T extends { issuer?: string }>(
stored: T | null | undefined,
issuer: string,
opts?: { canPersistStamp?: boolean }
): T | undefined {
// Nothing stored (`null` from a `JSON.parse(storage.getItem(...))`-style getter included).
if (!stored) return undefined;
// A stamp that is not a string (raw storage) counts as no stamp.
if (typeof stored.issuer !== 'string') {
if (opts?.canPersistStamp !== false) {
console.warn(
`[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or ` +
`provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ` +
`ensure your provider round-trips the issuer field.`
);
}
return stored.issuer === undefined ? stored : { ...stored, issuer: undefined };
}
return issuersMatch(stored.issuer, issuer) ? stored : undefined;
}
/**
* SEP-2352 issuer-identity comparison. Tolerates a single trailing `/` difference,
* mirroring the RFC 8414 §3.3 "one narrow tolerance" applied at metadata-echo
* validation in {@linkcode discoverAuthorizationServerMetadata}: when the SDK
* derives an issuer from `String(new URL(...))` (always slash-suffixed) and the AS
* publishes a slash-free `metadata.issuer`, the two name the same authorization
* server.
*/
function issuersMatch(a: string, b: string): boolean {
return a === b || (a.endsWith('/') && a.slice(0, -1) === b) || (b.endsWith('/') && b.slice(0, -1) === a);
}
/**
* Type guard distinguishing `OAuthClientProvider` from a minimal `AuthProvider`.
* Transports use this at construction time to classify the `authProvider` option.
*
* Checks for `tokens()` + `clientInformation()` — two required `OAuthClientProvider`
* methods that a minimal `AuthProvider` `{ token: ... }` would never have.
*/
export function isOAuthClientProvider(provider: AuthProvider | OAuthClientProvider | undefined): provider is OAuthClientProvider {
if (provider == null) return false;
const p = provider as OAuthClientProvider;
return typeof p.tokens === 'function' && typeof p.clientInformation === 'function';
}
/**
* Standard `onUnauthorized` behavior for OAuth providers: extracts
* `WWW-Authenticate` parameters from the 401 response and runs {@linkcode auth}.
* Used by {@linkcode adaptOAuthProvider} to bridge `OAuthClientProvider` to `AuthProvider`.
*/
export async function handleOAuthUnauthorized(
provider: OAuthClientProvider,
ctx: UnauthorizedContext,
extraAuthOptions?: Pick<AuthOptions, 'skipIssuerMetadataValidation'>
): Promise<void> {
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(ctx.response);
const result = await auth(provider, {
serverUrl: ctx.serverUrl,
resourceMetadataUrl,
scope,
fetchFn: ctx.fetchFn,
...extraAuthOptions
});
if (result !== 'AUTHORIZED') {
throw new UnauthorizedError();
}
}
/**
* Adapts an `OAuthClientProvider` to the minimal `AuthProvider` interface that
* transports consume. Called once at transport construction — the transport stores
* the adapted provider for `_commonHeaders()` and 401 handling, while keeping the
* original `OAuthClientProvider` for OAuth-specific paths (`finishAuth()`, 403 `insufficient_scope` step-up).
*
* SEP-2352 note: `token()` here is the per-request `Authorization: Bearer …` read for
* the *resource server* (the MCP transport URL), not an authorization server. No OAuth
* discovery has run at this layer, so there is no `issuer` to pass as `ctx` and no
* {@linkcode discardIfIssuerMismatch} check to apply — the access token is sent only to
* the resource server, never to an AS, so the SEP-2352 cross-AS isolation invariant is
* not in scope. Providers that key storage on `ctx.issuer` MUST treat `ctx === undefined`
* as "return the most-recently-saved token set" (the only consumer is the resource server
* the token was minted for); providers that round-trip a single blob need no change.
*
* SEP-1932 (DPoP) note: DPoP request-signing is deliberately *not* done here. When the provider
* implements {@linkcode OAuthClientProvider.dpop | dpop()}, the transports wrap their
* resource-server `fetch` with {@linkcode withDpopFromProvider}, which upgrades the `Bearer` header
* this adapter produces to `DPoP` + proof for DPoP-bound tokens and handles nonce challenges — at
* the one layer that sees the real method, URL and response of every request.
*/
export function adaptOAuthProvider(
provider: OAuthClientProvider,
extraAuthOptions?: Pick<AuthOptions, 'skipIssuerMetadataValidation'>
): AuthProvider {
return {
token: async () => {
const tokens = await provider.tokens();
return tokens?.access_token;
},
onUnauthorized: async ctx => handleOAuthUnauthorized(provider, ctx, extraAuthOptions)
};
}
/**
* Implements an end-to-end OAuth client to be used with one MCP server.
*
* This client relies upon a concept of an authorized "session," the exact
* meaning of which is application-defined. Tokens, authorization codes, and
* code verifiers should not cross different sessions.
*
* Transports accept `OAuthClientProvider` directly via the `authProvider` option —
* they adapt it to {@linkcode AuthProvider} internally via {@linkcode adaptOAuthProvider}.
* No changes are needed to existing implementations.
*/
export interface OAuthClientProvider {
/**
* The URL to redirect the user agent to after authorization.
* Return `undefined` for non-interactive flows that don't require user interaction
* (e.g., `client_credentials`, `jwt-bearer`).
*/
get redirectUrl(): string | URL | undefined;
/**
* External URL the server should use to fetch client metadata document
*/
clientMetadataUrl?: string;
/**
* When `true`, {@linkcode auth} does not add `prompt=consent` to the authorization
* request when the requested scope includes `offline_access`.
*
* OIDC Core §11 allows omitting it when other conditions already permit offline
* access, e.g. an administrator granted tenant-wide consent. Some authorization
* servers (such as Microsoft Entra ID with user consent disabled) reject a forced
* consent prompt from non-admin users even though consent is already in place.
*
* @default false
*/
skipOfflineAccessConsentPrompt?: boolean;
/**
* Metadata about this OAuth client.
*/
get clientMetadata(): OAuthClientMetadata;
/**
* Returns an OAuth2 state parameter.
*/
state?(): string | Promise<string>;
/**
* Loads information about this OAuth client, as registered already with the
* server, or returns `undefined` if the client is not registered with the
* server.
*
* @param ctx - Carries the resolved authorization-server `issuer`. Providers
* that persist credentials per authorization server should return the entry
* keyed by `ctx.issuer`. Providers with a single credential set may ignore it.
*/
clientInformation(
ctx?: OAuthClientInformationContext
): StoredOAuthClientInformation | undefined | Promise<StoredOAuthClientInformation | undefined>;
/**
* If implemented, this permits the OAuth client to dynamically register with
* the server. Client information saved this way should later be read via
* {@linkcode OAuthClientProvider.clientInformation | clientInformation()}.
*
* This method is not required to be implemented if client information is
* statically known (e.g., pre-registered).
*
* @param ctx - Carries the resolved authorization-server `issuer`. Providers
* that persist credentials per authorization server should store the entry
* keyed by `ctx.issuer`.
*/
saveClientInformation?(clientInformation: StoredOAuthClientInformation, ctx?: OAuthClientInformationContext): void | Promise<void>;
/**
* Loads any existing OAuth tokens for the current session, or returns
* `undefined` if there are no saved tokens.
*
* @param ctx - Carries the resolved authorization-server `issuer`. Providers
* that persist tokens per authorization server should return the entry
* keyed by `ctx.issuer`. Providers with a single token set may ignore it.
* When called with no `ctx` — the transport's per-request bearer-token
* read — return the most-recently-saved token set; do not return
* `undefined` for `ctx === undefined`.
*/
tokens(ctx?: OAuthClientInformationContext): StoredOAuthTokens | undefined | Promise<StoredOAuthTokens | undefined>;
/**
* Stores new OAuth tokens for the current session, after a successful
* authorization.
*
* @param ctx - Carries the resolved authorization-server `issuer`. Providers
* that persist tokens per authorization server should store the entry
* keyed by `ctx.issuer`.
*/
saveTokens(tokens: StoredOAuthTokens, ctx?: OAuthClientInformationContext): void | Promise<void>;
/**
* Invoked to redirect the user agent to the given URL to begin the authorization flow.
*/
redirectToAuthorization(authorizationUrl: URL): void | Promise<void>;
/**
* Saves a PKCE code verifier for the current session, before redirecting to
* the authorization flow.
*/
saveCodeVerifier(codeVerifier: string): void | Promise<void>;
/**
* Loads the PKCE code verifier for the current session, necessary to validate
* the authorization result.
*/
codeVerifier(): string | Promise<string>;
/**
* Adds custom client authentication to OAuth token requests.
*
* This optional method allows implementations to customize how client credentials
* are included in token exchange and refresh requests. When provided, this method
* is called instead of the default authentication logic, giving full control over
* the authentication mechanism.
*
* Common use cases include:
* - Supporting authentication methods beyond the standard OAuth 2.0 methods
* - Adding custom headers for proprietary authentication schemes
* - Implementing client assertion-based authentication (e.g., JWT bearer tokens)
*
* @param headers - The request headers (can be modified to add authentication)
* @param params - The request body parameters (can be modified to add credentials)
* @param url - The token endpoint URL being called
* @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods
*/
addClientAuthentication?: AddClientAuthentication;
/**
* Enables DPoP (RFC 9449 / SEP-1932) sender-constrained tokens when implemented. When this
* resolves to a {@linkcode DpopSession}, {@linkcode auth} signs a DPoP proof into the token
* request, and the transports (and {@linkcode withOAuth}) present a resulting `token_type: DPoP`
* access token with the `DPoP` Authorization scheme plus a fresh per-request proof instead of
* `Bearer`, by wrapping their resource-server `fetch` with {@linkcode withDpopFromProvider}.
*
* Return the *same* session across calls — the AS/RS nonce state and signing key it holds are
* meant to persist for the life of this client registration. A minimal implementation:
* ```typescript
* class MyProvider implements OAuthClientProvider {
* private _dpop = DpopSession.create();
* dpop() { return this._dpop; }
* // ...
* }
* ```
*
* Left undefined (the default), the provider behaves exactly as before this option existed:
* plain Bearer tokens throughout.
*/
dpop?(): DpopSession | undefined | Promise<DpopSession | undefined>;
/**
* If defined, overrides the selection and validation of the
* RFC 8707 Resource Indicator. If left undefined, default
* validation behavior will be used.
*
* Implementations must verify the returned resource matches the MCP server.
*/
validateResourceURL?(serverUrl: string | URL, resource?: string): Promise<URL | undefined>;
/**
* Returns the `scope` that {@linkcode auth} sends on a refresh-token request. Left undefined
* (the default), or when it returns `undefined` or `''`, the request carries no `scope`, which
* asks for the scope already granted (RFC 6749 §6).
*
* Implement it only for an authorization server that rejects a refresh without `scope`:
* other servers may reject or narrow a refresh that carries one. The returned value must
* not include a scope that was not originally granted.
*
* @param tokens - The stored tokens being refreshed; `tokens.scope` is the scope last saved with them.
*/
scopeForRefresh?(tokens: StoredOAuthTokens): string | undefined | Promise<string | undefined>;
/**
* If implemented, provides a way for the client to invalidate (e.g. delete) the specified
* credentials, in the case where the server has indicated that they are no longer valid.
* This avoids requiring the user to intervene manually.
*/
invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): void | Promise<void>;
/**
* Prepares grant-specific parameters for a token request.
*
* This optional method allows providers to customize the token request based on
* the grant type they support. When implemented, it returns the grant type and
* any grant-specific parameters needed for the token exchange.
*
* If not implemented, the default behavior depends on the flow:
* - For authorization code flow: uses `code`, `code_verifier`, and `redirect_uri`
* - For `client_credentials`: detected via `grant_types` in {@linkcode OAuthClientProvider.clientMetadata | clientMetadata}
*
* @param scope - Optional scope to request
* @returns Grant type and parameters, or `undefined` to use default behavior
*
* @example
* // For client_credentials grant:
* prepareTokenRequest(scope) {
* return {
* grantType: 'client_credentials',
* params: scope ? { scope } : {}
* };
* }
*
* @example
* // For authorization_code grant (default behavior):
* async prepareTokenRequest() {
* return {
* grantType: 'authorization_code',
* params: {
* code: this.authorizationCode,
* code_verifier: await this.codeVerifier(),
* redirect_uri: String(this.redirectUrl)
* }
* };
* }
*/
prepareTokenRequest?(scope?: string): URLSearchParams | Promise<URLSearchParams | undefined> | undefined;
/**
* Saves the resolved authorization-server **issuer**. Called after a successful
* token exchange (timing changed in v2: was post-discovery, now post-`saveTokens`).
*
* @deprecated Superseded by the `issuer` stamp on stored tokens / client credentials
* (SEP-2352). {@linkcode auth} still **writes** this for back-compat with providers
* that read it (e.g. Cross-App Access), but the SDK never reads it. Prefer reading
* the `issuer` field on the value passed to {@linkcode saveTokens} /
* {@linkcode saveClientInformation}, or the `ctx.issuer` argument.
*/
saveAuthorizationServerUrl?(authorizationServerUrl: string): void | Promise<void>;
/**
* Returns the previously saved authorization server URL, if available.
*
* @deprecated Superseded by the `issuer` stamp on stored tokens / client credentials
* (SEP-2352). The SDK never reads this method; it remains for provider implementations
* that consume the value internally (e.g. Cross-App Access).
*/
authorizationServerUrl?(): string | undefined | Promise<string | undefined>;
/**
* Saves the resource URL after RFC 9728 discovery.
* This method is called by {@linkcode auth} after successful discovery of the
* resource metadata.
*
* Providers implementing Cross-App Access or other flows that need access to
* the discovered resource URL should implement this method.
*
* @param resourceUrl - The resource URL discovered via RFC 9728
*/
saveResourceUrl?(resourceUrl: string): void | Promise<void>;
/**
* Returns the previously saved resource URL, if available.
*
* Providers implementing Cross-App Access can use this to access the
* resource URL discovered during the OAuth flow.
*
* @returns The resource URL, or `undefined` if not available
*/
resourceUrl?(): string | undefined | Promise<string | undefined>;
/**
* Saves the OAuth discovery state after RFC 9728 and authorization server metadata
* discovery. Providers can persist this state to avoid redundant discovery requests
* on subsequent {@linkcode auth} calls.
*
* This state can also be provided out-of-band (e.g., from a previous session or
* external configuration) to bootstrap the OAuth flow without discovery.
*
* Called by {@linkcode auth} after successful discovery.
*
* MUST persist with the same durability as `codeVerifier` (survives the redirect
* round-trip).
*/
saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;
/**
* Returns previously saved discovery state, or `undefined` if none is cached.
*
* When available, {@linkcode auth} restores the discovery state (authorization server
* URL, resource metadata, etc.) instead of performing RFC 9728 discovery, reducing
* latency on subsequent calls.
*
* Hosts should call {@linkcode invalidateCredentials} with scope `'discovery'`
* on repeated 401s so a changed `authorization_servers` list is picked up; the
* SDK does not invoke that scope itself.
*
* MUST persist with the same durability as `codeVerifier` (survives the redirect
* round-trip).
*/
discoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;
}
/**
* Discovery state that can be persisted across sessions by an {@linkcode OAuthClientProvider}.
*
* Contains the results of RFC 9728 protected resource metadata discovery and
* authorization server metadata discovery. Persisting this state avoids
* redundant discovery HTTP requests on subsequent {@linkcode auth} calls.
*/
// TODO: Consider adding `authorizationServerMetadataUrl` to capture the exact well-known URL
// at which authorization server metadata was discovered. This would require
// `discoverAuthorizationServerMetadata()` to return the successful discovery URL.
export interface OAuthDiscoveryState extends OAuthServerInfo {
/** The URL at which the protected resource metadata was found, if available. */
resourceMetadataUrl?: string;
}
export type AuthResult = 'AUTHORIZED' | 'REDIRECT';
export class UnauthorizedError extends Error {
static {
Object.defineProperty(this, 'mcpBrand', { value: 'mcp.UnauthorizedError' });
}
static override [Symbol.hasInstance](value: unknown): boolean {
return brandedHasInstance(this, value);
}
/**
* Brand-based type guard: equivalent to `value instanceof this`, as an
* explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads
* the caller's own brand via `this`, so every branded subclass gets a
* correctly-scoped guard by inheritance. Must be invoked on the class —
* in callback position write `v => SdkError.isInstance(v)`, not
* `.filter(SdkError.isInstance)` (detached calls throw rather than
* silently matching nothing).
*/
static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {
if (typeof this !== 'function') {
throw new TypeError(
'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'
);
}
return brandedHasInstance(this, value);
}
constructor(message?: string) {
super(message ?? 'Unauthorized');
this.name = 'UnauthorizedError';
stampErrorBrands(this, new.target);
}
}
/**
* Validates the `iss` parameter from an authorization response against the
* issuer recorded from the authorization server's validated metadata, per
* RFC 9207 §2.4 and the MCP specification's four-row decision table.
*
* | `issParameterSupported` | `iss` | Action |
* | ----------------------- | ------- | ------------------------------------------------ |
* | `true` | present | compare; throw {@linkcode IssuerMismatchError} on mismatch |
* | `true` | absent | throw {@linkcode IssuerMismatchError} |
* | `false` | present | compare; throw {@linkcode IssuerMismatchError} on mismatch |
* | `false` | absent | proceed (no-op) |
*
* Comparison is **simple string equality** (RFC 3986 §6.2.1). Scheme/host case
* folding, default-port elision, trailing-slash, and percent-encoding
* normalization are explicitly **not** applied — any difference is a mismatch.
*
* When `expectedIssuer` is `undefined` (no validated metadata document exists),
* the check has no authentic baseline and degenerates to a no-op.
*
* @throws {IssuerMismatchError} with `kind: 'authorization_response'`
*/
/**
* Reads RFC 9207's `authorization_response_iss_parameter_supported` from
* authorization-server metadata. Only a literal `true` counts as advertised;
* absent, `false`, or a non-boolean wire value (coerced to `undefined` by the
* schema) means not advertised.
*/
function isIssParameterSupported(metadata: AuthorizationServerMetadata | undefined): boolean {
return metadata?.authorization_response_iss_parameter_supported === true;
}
export function validateAuthorizationResponseIssuer({
iss,
expectedIssuer,
issParameterSupported
}: {
/** The form-urldecoded `iss` query parameter from the authorization callback, or `undefined` if absent. */
iss: string | undefined;
/** The `issuer` value from the authorization server's validated metadata document. */
expectedIssuer: string | undefined;
/** Whether the metadata advertised `authorization_response_iss_parameter_supported: true`. */
issParameterSupported: boolean;
}): void {
if (expectedIssuer === undefined) {
// No validated metadata document → no recorded issuer → no comparison (table row 4).
return;
}
if (iss === undefined) {
if (issParameterSupported) {
// Row 2: AS advertised that it always sends `iss`; absence is a stripped-parameter attack indicator.
throw new IssuerMismatchError('authorization_response', expectedIssuer, undefined);
}
// Row 4: not advertised, not present → proceed.
return;
}
// Rows 1 & 3: present → compare with simple string comparison only.
if (iss !== expectedIssuer) {
throw new IssuerMismatchError('authorization_response', expectedIssuer, iss);
}
}
/**
* Computes the union of one or more OAuth `scope` strings.
*
* Each argument is a space-delimited scope string per RFC 6749 §3.3, or
* `undefined`. The result is a single space-delimited string containing each
* distinct scope token exactly once, in first-seen order, or `undefined` if
* every input is empty/undefined.
*
* No hierarchical deduplication is performed: a union may contain semantically
* redundant entries (e.g., a broad scope alongside a narrower one it implies).
* Authorization servers normalize such redundancy during token issuance; the
* spec's step-up flow does not require clients to.
*
* Used by the transport's `403 insufficient_scope` step-up path to accumulate
* previously-requested scopes with newly-challenged scopes so re-authorization
* does not lose previously-granted permissions.
*/
export function computeScopeUnion(...scopes: ReadonlyArray<string | undefined>): string | undefined {
const seen = new Set<string>();
for (const scope of scopes) {
if (!scope) continue;
for (const token of scope.split(/\s+/)) {
if (token) seen.add(token);
}
}
return seen.size > 0 ? [...seen].join(' ') : undefined;
}
/**
* Whether `union` contains at least one scope token not present in `current`.
* Both arguments are space-delimited scope strings per RFC 6749 §3.3.
*
* Used to gate the step-up refresh bypass: when the union of previously-requested
* and newly-challenged scopes is a strict superset of the current token's
* granted scope, refreshing cannot widen the grant (RFC 6749 §6), so the
* transport must force a fresh authorization request instead. When the current
* token already covers the union, refresh remains valid.
*
* An undefined or empty `current` is treated as the empty set, so any non-empty
* `union` is a strict superset. Note that per RFC 6749 §3.3 an authorization
* server MAY omit the token's `scope` field when it equals the requested scope;
* this helper is conservative and treats an absent token `scope` as empty, so
* step-up always forces a fresh authorization request in that case rather than
* risking a refresh that silently drops the widened scope.
*/
export function isStrictScopeSuperset(union: string | undefined, current: string | undefined): boolean {
if (!union) return false;
const currentSet = new Set((current ?? '').split(/\s+/).filter(Boolean));
for (const token of union.split(/\s+/)) {
if (token && !currentSet.has(token)) return true;
}
return false;
}
/**
* Shared `finishAuth` resolver for the `(code, iss?)` and `(URLSearchParams)` overloads.
*
* For the `URLSearchParams` form, only `iss` and `code` are read up front. When a `code` is
* present the returned values flow into {@linkcode auth}, which runs
* {@linkcode validateAuthorizationResponseIssuer} against freshly-discovered metadata before
* the code is redeemed — so on mismatch the thrown {@linkcode IssuerMismatchError} carries no
* `error`/`error_description`/`error_uri` text from the callback (those are attacker-controlled
* in a mix-up). When no `code` is present (an error-shaped callback), `iss` is validated here
* against the provider's recorded discovery state — or, when the provider does not implement
* `discoveryState`, against freshly-discovered metadata mirroring what {@linkcode auth} does on
* the code-present path — **before** the callback's error parameters are read; only after that
* passes are they surfaced as an {@linkcode OAuthError}. When no issuer baseline can be
* obtained either way, a generic {@linkcode UnauthorizedError} is thrown without surfacing the
* callback's `error`/`error_description`/`error_uri`.
*
* @internal Exported for the transport `finishAuth` overloads; not part of the public barrel.
*/
export async function resolveAuthorizationCallbackParams(
codeOrParams: string | URLSearchParams,
iss: string | undefined,
provider: OAuthClientProvider,
serverUrl: string | URL,
opts?: { fetchFn?: FetchLike; resourceMetadataUrl?: URL }
): Promise<{ authorizationCode: string; iss: string | undefined }> {
if (typeof codeOrParams === 'string') {
return { authorizationCode: codeOrParams, iss };
}
const issParam = codeOrParams.get('iss') ?? undefined;
const code = codeOrParams.get('code');
if (code) {
return { authorizationCode: code, iss: issParam };
}
// No code → error response. Gate the (potentially attacker-supplied) error params on the
// issuer first. Prefer the provider's recorded discovery state; when absent, mirror auth()'s
// code-present path and run a fresh discovery so the iss gate has an authentic baseline.
const discoveryState = await provider.discoveryState?.();
let metadata = discoveryState?.authorizationServerMetadata;
if (!metadata) {
try {
const serverInfo = await discoverOAuthServerInfo(serverUrl, opts);
metadata = serverInfo.authorizationServerMetadata;
} catch {
metadata = undefined;
}
}
if (!metadata) {
// No authentic baseline → cannot prove the error params came from our AS. Do NOT surface
// attacker-controllable `error`/`error_description`/`error_uri` here.
throw new UnauthorizedError('Authorization callback failed and the issuer could not be verified');
}
validateAuthorizationResponseIssuer({
iss: issParam,
expectedIssuer: metadata.issuer,
issParameterSupported: isIssParameterSupported(metadata)
});
const error = codeOrParams.get('error');
if (error) {
throw new OAuthError(error, codeOrParams.get('error_description') ?? error, codeOrParams.get('error_uri') ?? undefined);
}
throw new UnauthorizedError('Authorization callback contained neither `code` nor `error`');
}
export type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none';
function isClientAuthMethod(method: string): method is ClientAuthMethod {
return ['client_secret_basic', 'client_secret_post', 'none'].includes(method);
}
const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';
const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';
/**
* Determines the best client authentication method to use based on server support and client configuration.
*
* Priority order (highest to lowest):
* 1. `client_secret_basic` (if client secret is available)
* 2. `client_secret_post` (if client secret is available)
* 3. `none` (for public clients)
*
* @param clientInformation - OAuth client information containing credentials
* @param supportedMethods - Authentication methods supported by the authorization server
* @returns The selected authentication method
*/
export function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod {
const hasClientSecret = clientInformation.client_secret !== undefined;
// Prefer the method returned by the server during client registration, if valid.
// When server metadata is present we also require the method to be listed as supported;
// when supportedMethods is empty (metadata omitted the field) the DCR hint stands alone.
if (
'token_endpoint_auth_method' in clientInformation &&
clientInformation.token_endpoint_auth_method &&
isClientAuthMethod(clientInformation.token_endpoint_auth_method) &&
(supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))
) {
return clientInformation.token_endpoint_auth_method;
}
// If server metadata omits token_endpoint_auth_methods_supported, RFC 8414 §2 says the
// default is client_secret_basic. RFC 6749 §2.3.1 also requires servers to support HTTP
// Basic authentication for clients with a secret, making it the safest default.
if (supportedMethods.length === 0) {
return hasClientSecret ? 'client_secret_basic' : 'none';
}
// Try methods in priority order (most secure first)
if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {
return 'client_secret_basic';
}
if (hasClientSecret && supportedMethods.includes('client_secret_post')) {
return 'client_secret_post';
}
if (supportedMethods.includes('none')) {
return 'none';
}
// Fallback: use what we have
return hasClientSecret ? 'client_secret_post' : 'none';
}
/**
* Applies client authentication to the request based on the specified method.
*
* Implements OAuth 2.1 client authentication methods:
* - `client_secret_basic`: HTTP Basic authentication (RFC 6749 Section 2.3.1)
* - `client_secret_post`: Credentials in request body (RFC 6749 Section 2.3.1)
* - `none`: Public client authentication (RFC 6749 Section 2.1)
*
* @param method - The authentication method to use
* @param clientInformation - OAuth client information containing credentials
* @param headers - HTTP headers object to modify
* @param params - URL search parameters to modify
* @throws {Error} When required credentials are missing
*/
export function applyClientAuthentication(
method: ClientAuthMethod,
clientInformation: OAuthClientInformation,
headers: Headers,
params: URLSearchParams
): void {
const { client_id, client_secret } = clientInformation;
switch (method) {
case 'client_secret_basic': {
applyBasicAuth(client_id, client_secret, headers);
return;
}
case 'client_secret_post': {
applyPostAuth(client_id, client_secret, params);
return;
}
case 'none': {
applyPublicAuth(client_id, params);
return;
}
default: {
throw new Error(`Unsupported client authentication method: ${method}`);
}
}
}
/**
* Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)
*/
export function applyBasicAuth(clientId: string, clientSecret: string | undefined, headers: Headers): void {
if (!clientSecret) {
throw new Error('client_secret_basic authentication requires a client_secret');
}
const credentials = btoa(`${clientId}:${clientSecret}`);
headers.set('Authorization', `Basic ${credentials}`);
}
/**
* Applies POST body authentication (RFC 6749 Section 2.3.1)
*/
export function applyPostAuth(clientId: string, clientSecret: string | undefined, params: URLSearchParams): void {
params.set('client_id', clientId);
if (clientSecret) {
params.set('client_secret', clientSecret);
}
}
/**
* Applies public client authentication (RFC 6749 Section 2.1)
*/
export function applyPublicAuth(clientId: string, params: URLSearchParams): void {
params.set('client_id', clientId);
}
/**
* Loopback hosts exempt from the in-transit `https:` requirement (RFC 8252 §7.3).
* Includes bare `localhost` and any name ending in `.localhost` (RFC 6761 §6.3).
*/
function isLoopbackHost(hostname: string): boolean {
return (
hostname === 'localhost' ||
hostname.endsWith('.localhost') ||
hostname === '127.0.0.1' ||
hostname === '[::1]' ||
hostname === '::1'
);
}
/**
* Refuse to send credentials to a non-TLS token endpoint. The MCP authorization
* specification requires authorization server endpoints to use HTTPS. Loopback
* hosts are exempt here for local development.
*
* @throws {@linkcode InsecureTokenEndpointError} if the endpoint is insecure.
*/
export function assertSecureTokenEndpoint(tokenEndpoint: string | URL): URL {
const url = new URL(String(tokenEndpoint));
if (url.protocol !== 'https:' && !isLoopbackHost(url.hostname)) {
throw new InsecureTokenEndpointError(url.href);
}
return url;
}
/**
* Derives an OIDC `application_type` from a client's registered redirect URIs
* when the consumer has not set one explicitly (SEP-837). Loopback hosts and
* non-`http(s)` custom URI schemes indicate a native application (RFC 8252);
* everything else is treated as a web application. The result is a heuristic
* default — callers that know better should set `clientMetadata.application_type`
* themselves, which {@linkcode resolveClientMetadata} never overwrites.
*
* A mixed redirect set (for example a public `https:` URI alongside a loopback
* URI) is inherently ambiguous under OIDC DCR §2 — neither value satisfies the
* AS for both URIs — so consumers with mixed sets should set `application_type`
* explicitly rather than relying on this heuristic.
*/
function deriveApplicationType(redirectUris: readonly string[] | undefined): 'native' | 'web' {
for (const raw of redirectUris ?? []) {
let url: URL;
try {
url = new URL(raw);
} catch {
continue;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return 'native';
if (isLoopbackHost(url.hostname)) return 'native';
}
return 'web';
}
/**
* Reads {@linkcode OAuthClientProvider.clientMetadata | clientMetadata} from the
* provider and fills the SEP-837 / SEP-2207 defaults the SDK relies on, so
* {@linkcode registerClient} sees a consistent, fully-populated document.
*
* - `grant_types` defaults to `['authorization_code', 'refresh_token']` for
* interactive providers (those with a {@linkcode OAuthClientProvider.redirectUrl | redirectUrl})
* so authorization servers that gate refresh-token issuance on the registered
* grant types issue one (SEP-2207). Non-interactive providers (no
* `redirectUrl`) get no `grant_types` default. This default applies to the
* Dynamic Client Registration body only — it does **not** drive
* {@linkcode determineScope}'s `offline_access` augmentation.
* - `application_type` defaults from `redirect_uris`: loopback redirect hosts
* and custom URI schemes → `'native'`, otherwise `'web'` (SEP-837 / RFC 8252).
*
* A field the consumer set explicitly is **never** overwritten. {@linkcode auth}
* calls this once at the top of the flow; direct callers of
* {@linkcode registerClient} that want the same defaults should pass the result
* of this function as `clientMetadata`.
*/
export function resolveClientMetadata(provider: Pick<OAuthClientProvider, 'clientMetadata' | 'redirectUrl'>): OAuthClientMetadata {
const clientMetadata = provider.clientMetadata;
return {
...clientMetadata,
grant_types:
clientMetadata.grant_types ?? (provider.redirectUrl === undefined ? undefined : ['authorization_code', 'refresh_token']),
application_type: clientMetadata.application_type ?? deriveApplicationType(clientMetadata.redirect_uris)
};
}
/**
* Parses an OAuth error response from a string or Response object.
*
* If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
* and an {@linkcode OAuthError} will be returned with the appropriate error code.
* If parsing fails, it falls back to a generic {@linkcode OAuthErrorCode.ServerError | ServerError} that includes
* the response status (if available) and original content.
*
* @param input - A Response object or string containing the error response
* @returns A Promise that resolves to an {@linkcode OAuthError} instance
*/
export async function parseErrorResponse(input: Response | string): Promise<OAuthError> {
const statusCode = input instanceof Response ? input.status : undefined;
const body = input instanceof Response ? await input.text() : input;
try {
const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
return OAuthError.fromResponse(result);
} catch (error) {
// Not a valid OAuth error response, but try to inform the user of the raw data anyway
const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`;