-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathoauth-proxy.ts
More file actions
833 lines (739 loc) · 29.3 KB
/
oauth-proxy.ts
File metadata and controls
833 lines (739 loc) · 29.3 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
/**
* MCP OAuth Proxy — GitLab upstream
*
* Builds an OAuthServerProvider that handles the MCP spec OAuth flow while
* delegating actual authentication to a GitLab instance.
*
* ### Why not pure GitLab DCR?
*
* GitLab restricts dynamically registered (unverified) applications to the
* `mcp` scope, which is insufficient for API calls (need `api` or `read_api`).
* To work around this, the MCP server uses a **pre-registered GitLab OAuth
* application** (set via GITLAB_OAUTH_APP_ID env var) with the required scopes,
* and handles DCR locally — each MCP client gets a unique virtual client_id
* mapped to the real GitLab app.
*
* ### Flow (callback proxy mode — GITLAB_OAUTH_CALLBACK_PROXY=true)
*
* When callback proxy mode is enabled, the MCP server acts as a full OAuth
* intermediary, similar to the Atlassian MCP's OAuthProxy pattern. Only ONE
* fixed callback URL needs to be registered with GitLab, regardless of how
* many MCP clients connect.
*
* 1. MCP client calls POST /register (DCR) — proxy stores redirect_uris locally
* and returns a virtual client_id.
* 2. MCP client redirects to /authorize — proxy stores the client's original
* redirect_uri and state, generates its own PKCE pair, then redirects to
* GitLab using the MCP server's fixed /callback URL as redirect_uri.
* 3. User authorizes on GitLab — GitLab redirects to the MCP server's /callback.
* 4. /callback handler exchanges the code with GitLab for tokens, stores them
* server-side, generates a new proxy auth code, and redirects to the client's
* original redirect_uri with the proxy code.
* 5. MCP client calls POST /token with the proxy code — proxy returns the
* stored GitLab tokens.
*
* ### Flow (passthrough mode — default)
*
* 1. MCP client calls POST /register (DCR) — proxy stores redirect_uris locally
* and returns a virtual client_id.
* 2. MCP client redirects to /authorize — proxy replaces the virtual client_id
* with the real GitLab app client_id and forwards to GitLab.
* 3. User authorizes on GitLab — redirect comes back with auth code.
* 4. MCP client calls POST /token — proxy exchanges the code with GitLab using
* the real client_id.
*
* Activated when GITLAB_MCP_OAUTH=true. All other auth modes are unaffected.
*/
import { InvalidTokenError, ServerError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
import type {
OAuthClientInformationFull,
OAuthTokens,
OAuthTokenRevocationRequest,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { OAuthTokensSchema } from "@modelcontextprotocol/sdk/shared/auth.js";
import type { OAuthRegisteredClientsStore } from "@modelcontextprotocol/sdk/server/auth/clients.js";
import type { AuthorizationParams, OAuthServerProvider } from "@modelcontextprotocol/sdk/server/auth/provider.js";
import type { Response } from "express";
import { randomUUID, randomBytes, createHash } from "node:crypto";
import { pino } from "pino";
import type { Request } from "express";
import {
looksLikeStatelessClientId,
mintClientId,
openClientId,
} from "./stateless/client-id.js";
import {
looksLikeStatelessState,
mintPendingAuthState,
openPendingAuthState,
} from "./stateless/pending-auth.js";
import {
looksLikeStatelessStoredTokensCode,
mintStoredTokensCode,
openStoredTokensCode,
} from "./stateless/stored-tokens.js";
import type { StatelessKeyMaterial } from "./stateless/index.js";
const logger = pino({ name: "gitlab-mcp-oauth-proxy" });
/**
* Shape of the response from GitLab's /oauth/token/info endpoint.
* @see https://docs.gitlab.com/ee/api/oauth2.html#retrieve-the-token-information
*/
export interface GitLabTokenInfo {
resource_owner_id: number;
scopes: string[];
expires_in_seconds: number | null;
application: { uid: string } | null;
created_at: number;
}
// ---------------------------------------------------------------------------
// GitLab OAuth Server Provider
// ---------------------------------------------------------------------------
/**
* Minimum GitLab scopes required for the MCP server to function.
* Injected into the authorization request when the client does not request them.
*/
const REQUIRED_GITLAB_SCOPES_RW = ["api"];
const REQUIRED_GITLAB_SCOPES_RO = ["read_api"];
// ---------------------------------------------------------------------------
// Callback proxy mode — pending auth transactions
// ---------------------------------------------------------------------------
const PENDING_AUTH_MAX_SIZE = 1000;
const PENDING_AUTH_TTL_MS = 10 * 60 * 1000; // 10 minutes
const CLIENT_CACHE_MAX_SIZE = 1000;
/**
* Stateless-mode configuration for the OAuth provider.
*
* When `material` is set, DCR entries, callback-proxy pending-auth
* transactions, and callback-proxy stored-token entries are serialised into
* the opaque OAuth values themselves rather than held in a per-pod in-memory
* cache. This makes the provider safe to run behind a load balancer that
* distributes requests across multiple pods with no session affinity.
*/
export interface StatelessOAuthOptions {
material: StatelessKeyMaterial;
clientTtlSeconds: number;
/** TTL for sealed OAuth `state` values (default 600s). */
pendingTtlSeconds: number;
/** TTL for sealed proxy authorization codes (default 600s). */
storedTtlSeconds: number;
}
/** Stored while user is on GitLab consent screen. Keyed by `state`. */
interface PendingAuthTransaction {
clientId: string;
clientRedirectUri: string;
clientState: string | undefined;
clientCodeChallenge: string;
proxyCodeVerifier: string;
createdAt: number;
}
/** Stored after /callback exchanges the code. Keyed by proxy auth code. */
interface StoredTokenEntry {
tokens: OAuthTokens;
clientId: string;
clientCodeChallenge: string; // for PKCE verification when client calls /token
clientRedirectUri: string;
createdAt: number;
}
class BoundedLRUMap<V> {
private readonly _map = new Map<string, V>();
private readonly _maxSize: number;
constructor(maxSize: number) {
this._maxSize = maxSize;
}
get(key: string): V | undefined {
const v = this._map.get(key);
if (v !== undefined) {
this._map.delete(key);
this._map.set(key, v);
}
return v;
}
/** Get and remove in one operation — for one-time-use entries. */
getAndDelete(key: string): V | undefined {
const v = this._map.get(key);
if (v !== undefined) this._map.delete(key);
return v;
}
set(key: string, value: V): void {
if (this._map.has(key)) this._map.delete(key);
else if (this._map.size >= this._maxSize) {
const lruKey = this._map.keys().next().value;
if (lruKey !== undefined) this._map.delete(lruKey);
}
this._map.set(key, value);
}
delete(key: string): boolean {
return this._map.delete(key);
}
get size(): number {
return this._map.size;
}
}
class GitLabOAuthServerProvider implements OAuthServerProvider {
/**
* Tell the SDK not to validate PKCE locally.
* - Passthrough mode: GitLab handles PKCE validation.
* - Callback proxy mode: we verify the client's PKCE manually in
* exchangeAuthorizationCode() after looking up stored tokens.
*/
readonly skipLocalPkceValidation = true;
private readonly _gitlabBaseUrl: string;
private readonly _gitlabAppId: string;
private readonly _resourceName: string;
private readonly _requiredScopes: string[];
private readonly _clientCache = new BoundedLRUMap<OAuthClientInformationFull>(CLIENT_CACHE_MAX_SIZE);
// Callback proxy mode fields
private readonly _callbackProxyEnabled: boolean;
private readonly _callbackUrl: string;
private readonly _pendingAuth = new BoundedLRUMap<PendingAuthTransaction>(PENDING_AUTH_MAX_SIZE);
private readonly _storedTokens = new BoundedLRUMap<StoredTokenEntry>(PENDING_AUTH_MAX_SIZE);
// Stateless mode (optional). When set, DCR and callback-proxy state are
// serialised into opaque OAuth values and the in-memory caches above are
// bypassed. Enabled independently of callback-proxy mode.
private readonly _stateless: StatelessOAuthOptions | null;
constructor(
gitlabBaseUrl: string,
gitlabAppId: string,
resourceName: string,
readOnly: boolean,
customScopes?: string[],
callbackProxyEnabled = false,
callbackUrl = "",
stateless: StatelessOAuthOptions | null = null
) {
this._gitlabBaseUrl = gitlabBaseUrl;
this._gitlabAppId = gitlabAppId;
this._resourceName = resourceName;
this._requiredScopes =
customScopes && customScopes.length > 0
? customScopes
: readOnly
? REQUIRED_GITLAB_SCOPES_RO
: REQUIRED_GITLAB_SCOPES_RW;
this._callbackProxyEnabled = callbackProxyEnabled;
this._callbackUrl = callbackUrl;
this._stateless = stateless;
if (callbackProxyEnabled && !callbackUrl) {
throw new Error("callbackUrl is required when callbackProxyEnabled is true");
}
if (callbackProxyEnabled) {
logger.info(`Callback proxy mode enabled — fixed callback URL: ${callbackUrl}`);
}
if (stateless) {
logger.info(
`Stateless mode enabled (client_id TTL: ${stateless.clientTtlSeconds}s, ` +
`pending TTL: ${stateless.pendingTtlSeconds}s, ` +
`stored TTL: ${stateless.storedTtlSeconds}s)`
);
}
}
// ---- Client store (local DCR) ------------------------------------------
get clientsStore(): OAuthRegisteredClientsStore {
const cache = this._clientCache;
const resourceName = this._resourceName;
const stateless = this._stateless;
return {
getClient: async (clientId: string) => {
// Stateless path: a signed client_id carries the registration.
// If verification succeeds, reconstruct the OAuthClientInformationFull.
if (stateless && looksLikeStatelessClientId(clientId)) {
const payload = openClientId(
stateless.material,
clientId,
stateless.clientTtlSeconds
);
if (!payload) {
logger.warn(`DCR: stateless client_id rejected (bad signature or expired)`);
// Mimic legacy behaviour: return a stub so the SDK surfaces the
// standard InvalidClientError path. We return null to let the SDK
// handler emit a proper OAuth error.
return undefined;
}
return {
client_id: clientId,
client_id_issued_at: payload.iat,
redirect_uris: payload.ruris,
token_endpoint_auth_method: "none",
grant_types: payload.gt ?? ["authorization_code"],
client_name: payload.cn ?? resourceName,
};
}
const cached = cache.get(clientId);
if (cached) return cached;
// Unknown client — return a minimal stub so token exchange can proceed
// (GitLab is the ultimate validator).
return {
client_id: clientId,
redirect_uris: [],
token_endpoint_auth_method: "none" as const,
};
},
registerClient: async (
client: Omit<OAuthClientInformationFull, "client_id" | "client_id_issued_at">
) => {
const grantTypes = client.grant_types ?? ["authorization_code"];
const redirectUris = client.redirect_uris ?? [];
const clientName = client.client_name
? `${client.client_name} via ${resourceName}`
: resourceName;
// Stateless path: mint a signed client_id and return the registration
// without touching the in-memory cache.
if (stateless) {
const issuedAt = Math.floor(Date.now() / 1000);
const clientId = mintClientId(stateless.material, {
redirectUris,
grantTypes,
clientName,
});
const registered: OAuthClientInformationFull = {
client_id: clientId,
client_id_issued_at: issuedAt,
redirect_uris: redirectUris,
token_endpoint_auth_method: "none",
grant_types: grantTypes,
client_name: clientName,
};
logger.info(
`DCR (stateless): issued signed client_id (name: ${clientName}, ruris: ${redirectUris.length})`
);
return registered;
}
// Generate a virtual client_id; all real OAuth operations use _gitlabAppId.
const virtualClientId = randomUUID();
const registered: OAuthClientInformationFull = {
client_id: virtualClientId,
client_id_issued_at: Math.floor(Date.now() / 1000),
redirect_uris: redirectUris,
token_endpoint_auth_method: "none",
grant_types: grantTypes,
client_name: clientName,
};
cache.set(virtualClientId, registered);
logger.info(
`DCR: registered virtual client ${virtualClientId} (name: ${registered.client_name})`
);
return registered;
},
};
}
// ---- Authorize ---------------------------------------------------------
async authorize(
client: OAuthClientInformationFull,
params: AuthorizationParams,
res: Response
): Promise<void> {
const scopes = params.scopes ?? [];
const hasRequired = this._requiredScopes.some((s) => scopes.includes(s));
const effectiveScopes = hasRequired
? scopes
: [...new Set([...scopes, ...this._requiredScopes])];
// Build the GitLab authorize URL with the REAL app client_id
const targetUrl = new URL(`${this._gitlabBaseUrl}/oauth/authorize`);
if (this._callbackProxyEnabled) {
// --- Callback proxy mode ---
// Generate a proxy PKCE pair (MCP server ↔ GitLab)
const proxyCodeVerifier = randomBytes(32).toString("base64url");
const proxyCodeChallenge = createHash("sha256")
.update(proxyCodeVerifier)
.digest("base64url");
// Correlate the callback via either a sealed state (stateless mode) or
// a random UUID stored in the pendingAuth LRU (legacy mode).
const stateless = this._stateless;
const proxyState = stateless
? mintPendingAuthState(stateless.material, {
clientId: client.client_id,
clientRedirectUri: params.redirectUri,
clientState: params.state,
clientCodeChallenge: params.codeChallenge,
proxyCodeVerifier,
})
: randomUUID();
if (!stateless) {
// Store the client's original params so /callback can redirect back.
// Stateless mode carries these inside proxyState itself.
this._pendingAuth.set(proxyState, {
clientId: client.client_id,
clientRedirectUri: params.redirectUri,
clientState: params.state,
clientCodeChallenge: params.codeChallenge,
proxyCodeVerifier,
createdAt: Date.now(),
});
}
const searchParams = new URLSearchParams({
client_id: this._gitlabAppId,
response_type: "code",
redirect_uri: this._callbackUrl,
code_challenge: proxyCodeChallenge,
code_challenge_method: "S256",
state: proxyState,
});
if (effectiveScopes.length) searchParams.set("scope", effectiveScopes.join(" "));
if (params.resource) searchParams.set("resource", params.resource.href);
targetUrl.search = searchParams.toString();
logger.info(
`authorize (callback proxy): redirecting to GitLab with fixed callback URL (app: ${this._gitlabAppId}, scopes: ${effectiveScopes.join(" ")})`
);
} else {
// --- Passthrough mode (original behavior) ---
const searchParams = new URLSearchParams({
client_id: this._gitlabAppId,
response_type: "code",
redirect_uri: params.redirectUri,
code_challenge: params.codeChallenge,
code_challenge_method: "S256",
});
if (params.state) searchParams.set("state", params.state);
if (effectiveScopes.length) searchParams.set("scope", effectiveScopes.join(" "));
if (params.resource) searchParams.set("resource", params.resource.href);
targetUrl.search = searchParams.toString();
logger.info(
`authorize: redirecting to GitLab (app: ${this._gitlabAppId}, scopes: ${effectiveScopes.join(" ")})`
);
}
res.redirect(targetUrl.toString());
}
// ---- PKCE challenge (delegated to GitLab) ------------------------------
async challengeForAuthorizationCode(
_client: OAuthClientInformationFull,
_authorizationCode: string
): Promise<string> {
return "";
}
// ---- Token exchange ----------------------------------------------------
async exchangeAuthorizationCode(
client: OAuthClientInformationFull,
authorizationCode: string,
codeVerifier?: string,
redirectUri?: string,
resource?: URL
): Promise<OAuthTokens> {
if (this._callbackProxyEnabled) {
// --- Callback proxy mode ---
// The authorizationCode is a proxy code we generated in handleCallback().
// It is either a sealed token (stateless mode) or a random UUID that
// keys into the _storedTokens LRU (legacy mode).
const stateless = this._stateless;
let entry: {
tokens: OAuthTokens;
clientId: string;
clientCodeChallenge: string;
clientRedirectUri: string;
} | null = null;
if (stateless && looksLikeStatelessStoredTokensCode(authorizationCode)) {
const payload = openStoredTokensCode(
stateless.material,
authorizationCode,
stateless.storedTtlSeconds
);
if (!payload) {
throw new ServerError("Invalid or expired authorization code");
}
entry = {
tokens: payload.t,
clientId: payload.cid,
clientCodeChallenge: payload.ccc,
clientRedirectUri: payload.cru,
};
// NOTE: Stateless mode cannot enforce one-time use without a shared
// store. Replay is mitigated by short TTL + client PKCE verification
// below (attacker needs the code_verifier). Documented in
// stateless/stored-tokens.ts.
} else {
const lru = this._storedTokens.get(authorizationCode);
if (!lru) {
throw new ServerError("Invalid or expired authorization code");
}
if (Date.now() - lru.createdAt > PENDING_AUTH_TTL_MS) {
this._storedTokens.delete(authorizationCode);
throw new ServerError("Authorization code expired — please restart the OAuth flow");
}
// One-time use: delete after validation
this._storedTokens.delete(authorizationCode);
entry = {
tokens: lru.tokens,
clientId: lru.clientId,
clientCodeChallenge: lru.clientCodeChallenge,
clientRedirectUri: lru.clientRedirectUri,
};
}
// Bind the proxy code to the client and redirect_uri that initiated
// /authorize, preserving the normal OAuth authorization-code invariant.
if (client.client_id !== entry.clientId) {
throw new ServerError("Invalid client for authorization code");
}
if (redirectUri !== entry.clientRedirectUri) {
throw new ServerError("Invalid redirect_uri for authorization code");
}
// Verify client PKCE: the client's code_verifier must match the
// code_challenge stored during /authorize.
if (entry.clientCodeChallenge) {
if (!codeVerifier) {
throw new ServerError("PKCE code_verifier is required");
}
const computed = createHash("sha256").update(codeVerifier).digest("base64url");
if (computed !== entry.clientCodeChallenge) {
throw new ServerError("PKCE verification failed");
}
}
return entry.tokens;
}
// --- Passthrough mode (original behavior) ---
const params = new URLSearchParams({
grant_type: "authorization_code",
client_id: this._gitlabAppId,
code: authorizationCode,
});
if (codeVerifier) params.append("code_verifier", codeVerifier);
if (redirectUri) params.append("redirect_uri", redirectUri);
if (resource) params.append("resource", resource.href);
const response = await fetch(`${this._gitlabBaseUrl}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params.toString(),
});
if (!response.ok) {
const body = await response.text();
logger.error(`Token exchange failed (${response.status}): ${body}`);
throw new ServerError(`Token exchange failed: ${response.status}`);
}
const data = await response.json();
return OAuthTokensSchema.parse(data);
}
// ---- Refresh token -----------------------------------------------------
async exchangeRefreshToken(
_client: OAuthClientInformationFull,
refreshToken: string,
scopes?: string[],
resource?: URL
): Promise<OAuthTokens> {
const params = new URLSearchParams({
grant_type: "refresh_token",
client_id: this._gitlabAppId,
refresh_token: refreshToken,
});
if (scopes?.length) params.set("scope", scopes.join(" "));
if (resource) params.set("resource", resource.href);
const response = await fetch(`${this._gitlabBaseUrl}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params.toString(),
});
if (!response.ok) {
const body = await response.text();
logger.error(`Token refresh failed (${response.status}): ${body}`);
throw new ServerError(`Token refresh failed: ${response.status}`);
}
const data = await response.json();
return OAuthTokensSchema.parse(data);
}
// ---- Verify access token -----------------------------------------------
async verifyAccessToken(token: string): Promise<AuthInfo> {
const res = await fetch(`${this._gitlabBaseUrl}/oauth/token/info`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
throw new InvalidTokenError("Invalid or expired GitLab OAuth token");
}
const info = (await res.json()) as GitLabTokenInfo;
return {
token,
clientId: info.application?.uid ?? "dynamic",
scopes: info.scopes ?? [],
expiresAt:
info.expires_in_seconds != null
? Math.floor(Date.now() / 1000) + info.expires_in_seconds
: undefined,
};
}
// ---- Callback handler (callback proxy mode) ----------------------------
/**
* Handle the OAuth callback from GitLab.
* Exchanges the auth code for tokens, stores them, generates a proxy code,
* and redirects to the MCP client's original callback URL.
*
* Mount this as GET /callback in the Express app.
*/
async handleCallback(req: Request, res: Response): Promise<void> {
if (!this._callbackProxyEnabled) {
res.status(404).send("Callback proxy mode is not enabled");
return;
}
const code = req.query.code as string | undefined;
const state = req.query.state as string | undefined;
const error = req.query.error as string | undefined;
if (error) {
logger.error(`GitLab OAuth error: ${error} — ${req.query.error_description ?? "(no description)"}`);
res.status(400).send("Authorization failed");
return;
}
if (!code || !state) {
res.status(400).send("Missing code or state parameter");
return;
}
// Look up the pending auth transaction. The sealed-state path carries
// the transaction inline; the legacy path fetches it from the LRU.
// Both produce the same normalized shape below.
const stateless = this._stateless;
let pending: {
clientId: string;
clientRedirectUri: string;
clientState: string | undefined;
clientCodeChallenge: string;
proxyCodeVerifier: string;
} | null = null;
if (stateless && looksLikeStatelessState(state)) {
const payload = openPendingAuthState(
stateless.material,
state,
stateless.pendingTtlSeconds
);
if (!payload) {
res.status(400).send("Unknown or expired state parameter");
return;
}
pending = {
clientId: payload.cid,
clientRedirectUri: payload.cru,
clientState: payload.cs,
clientCodeChallenge: payload.ccc,
proxyCodeVerifier: payload.pcv,
};
} else {
const lru = this._pendingAuth.getAndDelete(state);
if (!lru) {
res.status(400).send("Unknown or expired state parameter");
return;
}
if (Date.now() - lru.createdAt > PENDING_AUTH_TTL_MS) {
res.status(400).send("Authorization request expired");
return;
}
pending = {
clientId: lru.clientId,
clientRedirectUri: lru.clientRedirectUri,
clientState: lru.clientState,
clientCodeChallenge: lru.clientCodeChallenge,
proxyCodeVerifier: lru.proxyCodeVerifier,
};
}
// Exchange the GitLab auth code for tokens using the proxy's PKCE verifier
try {
const tokenParams = new URLSearchParams({
grant_type: "authorization_code",
client_id: this._gitlabAppId,
code,
redirect_uri: this._callbackUrl,
code_verifier: pending.proxyCodeVerifier,
});
const tokenResponse = await fetch(`${this._gitlabBaseUrl}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: tokenParams.toString(),
});
if (!tokenResponse.ok) {
const body = await tokenResponse.text();
logger.error(`Callback token exchange failed (${tokenResponse.status}): ${body}`);
res.status(502).send("Token exchange with GitLab failed");
return;
}
const tokens = OAuthTokensSchema.parse(await tokenResponse.json());
// Generate a proxy auth code for the MCP client. Sealed in stateless
// mode; random UUID + LRU entry in legacy mode.
const proxyCode = stateless
? mintStoredTokensCode(stateless.material, {
tokens,
clientId: pending.clientId,
clientRedirectUri: pending.clientRedirectUri,
clientCodeChallenge: pending.clientCodeChallenge,
})
: (() => {
const id = randomUUID();
this._storedTokens.set(id, {
tokens,
clientId: pending!.clientId,
clientCodeChallenge: pending!.clientCodeChallenge,
clientRedirectUri: pending!.clientRedirectUri,
createdAt: Date.now(),
});
return id;
})();
// Redirect to the MCP client's original callback URL
const clientCallback = new URL(pending.clientRedirectUri);
clientCallback.searchParams.set("code", proxyCode);
if (pending.clientState) {
clientCallback.searchParams.set("state", pending.clientState);
}
logger.info(
`callback: exchanged code with GitLab, redirecting to client callback`
);
res.redirect(clientCallback.toString());
} catch (err) {
logger.error({ err }, "Callback handler error");
res.status(500).send("Internal error during token exchange");
}
}
// ---- Revoke token ------------------------------------------------------
async revokeToken(
_client: OAuthClientInformationFull,
request: OAuthTokenRevocationRequest
): Promise<void> {
const params = new URLSearchParams({
token: request.token,
client_id: this._gitlabAppId,
});
if (request.token_type_hint) {
params.set("token_type_hint", request.token_type_hint);
}
const response = await fetch(`${this._gitlabBaseUrl}/oauth/revoke`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params.toString(),
});
if (!response.ok) {
throw new ServerError(`Token revocation failed: ${response.status}`);
}
await response.body?.cancel();
}
}
// ---------------------------------------------------------------------------
// Factory
// ---------------------------------------------------------------------------
/**
* Build a GitLabOAuthServerProvider for the given GitLab instance.
*
* @param gitlabBaseUrl Root URL of the GitLab instance (no trailing slash, no /api/v4).
* @param gitlabAppId Client ID of the pre-registered GitLab OAuth application.
* @param resourceName Human-readable name shown on the GitLab consent screen.
* @param readOnly When true and customScopes is not set, restricts to read_api scope.
* @param customScopes Explicit list of GitLab scopes to require. Overrides readOnly when set.
* @param callbackProxyEnabled When true, the MCP server handles the OAuth callback internally.
* Only ONE fixed callback URL needs to be registered with GitLab.
* @param callbackUrl The fixed callback URL (e.g. https://mcp.example.com/callback).
* Required when callbackProxyEnabled is true.
* @param stateless Optional stateless-mode options. When set, DCR and later
* callback-proxy state is encoded into opaque OAuth values
* instead of an in-memory cache, enabling multi-pod deploys.
*/
export function createGitLabOAuthProvider(
gitlabBaseUrl: string,
gitlabAppId: string,
resourceName = "GitLab MCP Server",
readOnly = false,
customScopes?: string[],
callbackProxyEnabled = false,
callbackUrl = "",
stateless: StatelessOAuthOptions | null = null
): GitLabOAuthServerProvider {
return new GitLabOAuthServerProvider(
gitlabBaseUrl,
gitlabAppId,
resourceName,
readOnly,
customScopes,
callbackProxyEnabled,
callbackUrl,
stateless
);
}