-
-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathAuthTab.tsx
More file actions
668 lines (611 loc) · 22.8 KB
/
AuthTab.tsx
File metadata and controls
668 lines (611 loc) · 22.8 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
import { useState, useCallback, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { AlertCircle, RefreshCw, Shield } from "lucide-react";
import { EmptyState } from "./ui/empty-state";
import {
AuthSettings,
DEFAULT_AUTH_SETTINGS,
StatusMessage,
} from "@/shared/types.js";
import { Card, CardContent } from "./ui/card";
import {
initiateOAuth,
refreshOAuthTokens,
getStoredTokens,
clearOAuthData,
MCPOAuthOptions,
} from "../lib/oauth/mcp-oauth";
import { DebugMCPOAuthClientProvider } from "../lib/oauth/debug-oauth-provider";
import { ServerWithName } from "../hooks/use-app-state";
import {
OAuthFlowState,
EMPTY_OAUTH_FLOW_STATE,
} from "../lib/types/oauth-flow-types";
import { OAuthFlowProgressSimple } from "./oauth/OAuthFlowProgressSimple";
import { OAuthStateMachine } from "../lib/oauth/oauth-state-machine";
import type { MCPServerConfig } from "@mcpjam/sdk/browser";
interface StatusMessageProps {
message: StatusMessage;
}
const StatusMessageComponent = ({ message }: StatusMessageProps) => {
let bgColor: string;
let textColor: string;
let borderColor: string;
switch (message.type) {
case "error":
bgColor = "bg-red-50 dark:bg-red-950/50";
textColor = "text-red-700 dark:text-red-400";
borderColor = "border-red-200 dark:border-red-800";
break;
case "success":
bgColor = "bg-green-50 dark:bg-green-950/50";
textColor = "text-green-700 dark:text-green-400";
borderColor = "border-green-200 dark:border-green-800";
break;
case "info":
default:
bgColor = "bg-blue-50 dark:bg-blue-950/50";
textColor = "text-blue-700 dark:text-blue-400";
borderColor = "border-blue-200 dark:border-blue-800";
break;
}
return (
<div
className={`p-3 rounded-md border ${bgColor} ${borderColor} ${textColor} mb-4`}
>
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4" />
<p className="text-sm">{message.message}</p>
</div>
</div>
);
};
interface AuthTabProps {
serverConfig?: MCPServerConfig;
serverEntry?: ServerWithName;
serverName?: string;
}
export const AuthTab = ({
serverConfig,
serverEntry,
serverName,
}: AuthTabProps) => {
const [authSettings, setAuthSettings] = useState<AuthSettings>(
DEFAULT_AUTH_SETTINGS,
);
const [oauthFlowState, setOAuthFlowState] = useState<OAuthFlowState>(
EMPTY_OAUTH_FLOW_STATE,
);
const [showGuidedFlow, setShowGuidedFlow] = useState(false);
const updateAuthSettings = useCallback((updates: Partial<AuthSettings>) => {
setAuthSettings((prev) => ({ ...prev, ...updates }));
}, []);
const updateOAuthFlowState = useCallback(
(updates: Partial<OAuthFlowState>) => {
setOAuthFlowState((prev) => ({ ...prev, ...updates }));
},
[],
);
const resetOAuthFlow = useCallback(() => {
// Reset the guided flow state
setShowGuidedFlow(false);
updateOAuthFlowState(EMPTY_OAUTH_FLOW_STATE);
// Clear any debug OAuth artifacts to avoid stale client info/scope
if (authSettings.serverUrl) {
try {
const provider = new DebugMCPOAuthClientProvider(
authSettings.serverUrl,
);
provider.clear();
} catch (e) {
console.warn("Failed to clear debug OAuth provider state:", e);
}
}
}, [authSettings.serverUrl, updateOAuthFlowState]);
// Update auth settings when server config changes
useEffect(() => {
if (serverConfig && serverConfig.url && serverName) {
const serverUrl = serverConfig.url.toString();
// Check for existing tokens using the real OAuth system
const existingTokens = getStoredTokens(serverName);
updateAuthSettings({
serverUrl,
tokens: existingTokens,
error: null,
statusMessage: null,
});
} else {
updateAuthSettings(DEFAULT_AUTH_SETTINGS);
}
}, [serverConfig, serverName, updateAuthSettings]);
// Reset OAuth flow when component mounts or server changes
useEffect(() => {
// Reset the guided flow state when switching tabs or servers
resetOAuthFlow();
}, [serverName, resetOAuthFlow]);
const handleQuickRefresh = useCallback(async () => {
if (!serverConfig || !authSettings.serverUrl || !serverName) {
updateAuthSettings({
statusMessage: {
type: "error",
message: "Please select a server before refreshing tokens",
},
});
return;
}
updateAuthSettings({
isAuthenticating: true,
error: null,
statusMessage: null,
});
try {
let result;
if (authSettings.tokens) {
// If tokens exist, try to refresh them
result = await refreshOAuthTokens(serverName);
} else {
// If no tokens exist, initiate new OAuth flow
const oauthOptions: MCPOAuthOptions = {
serverName: serverName,
serverUrl: authSettings.serverUrl,
};
result = await initiateOAuth(oauthOptions);
}
if (result.success) {
// Check for updated tokens
const updatedTokens = getStoredTokens(serverName);
updateAuthSettings({
tokens: updatedTokens,
isAuthenticating: false,
statusMessage: {
type: "success",
message: authSettings.tokens
? "Tokens refreshed successfully!"
: result.serverConfig
? "OAuth authentication completed!"
: "OAuth flow initiated. You will be redirected to authorize access.",
},
});
// If redirect is needed, the browser will redirect automatically
// Clear success message after 3 seconds
setTimeout(() => {
updateAuthSettings({ statusMessage: null });
}, 3000);
} else {
updateAuthSettings({
isAuthenticating: false,
error: result.error || "OAuth operation failed",
statusMessage: {
type: "error",
message: `Failed: ${result.error || "OAuth operation failed"}`,
},
});
}
} catch (error) {
updateAuthSettings({
isAuthenticating: false,
error: error instanceof Error ? error.message : String(error),
statusMessage: {
type: "error",
message: `Failed: ${error instanceof Error ? error.message : String(error)}`,
},
});
}
}, [
serverConfig,
authSettings.serverUrl,
authSettings.tokens,
serverName,
updateAuthSettings,
]);
const handleNewOAuth = useCallback(async () => {
if (!serverConfig || !authSettings.serverUrl || !serverName) {
updateAuthSettings({
statusMessage: {
type: "error",
message: "Please select a server before starting OAuth",
},
});
return;
}
updateAuthSettings({
isAuthenticating: true,
error: null,
statusMessage: null,
});
try {
// Clear existing tokens first to force a fresh OAuth flow
clearOAuthData(serverName);
// Always initiate new OAuth flow (fresh start)
const oauthOptions: MCPOAuthOptions = {
serverName: serverName,
serverUrl: authSettings.serverUrl,
};
const result = await initiateOAuth(oauthOptions);
if (result.success) {
// Check for updated tokens
const updatedTokens = getStoredTokens(serverName);
updateAuthSettings({
tokens: updatedTokens,
isAuthenticating: false,
statusMessage: {
type: "success",
message: result.serverConfig
? "OAuth authentication completed!"
: "OAuth flow initiated. You will be redirected to authorize access.",
},
});
// Clear success message after 3 seconds
setTimeout(() => {
updateAuthSettings({ statusMessage: null });
}, 3000);
} else {
updateAuthSettings({
isAuthenticating: false,
error: result.error || "OAuth authentication failed",
statusMessage: {
type: "error",
message: `Failed: ${result.error || "OAuth authentication failed"}`,
},
});
}
} catch (error) {
updateAuthSettings({
isAuthenticating: false,
error: error instanceof Error ? error.message : String(error),
statusMessage: {
type: "error",
message: `Failed: ${error instanceof Error ? error.message : String(error)}`,
},
});
}
}, [serverConfig, authSettings.serverUrl, serverName, updateAuthSettings]);
// Initialize OAuth state machine
const oauthStateMachine = useMemo(() => {
if (!serverConfig || !serverName || !authSettings.serverUrl) return null;
const provider = new DebugMCPOAuthClientProvider(authSettings.serverUrl);
return new OAuthStateMachine({
state: oauthFlowState,
serverUrl: authSettings.serverUrl,
serverName,
provider,
updateState: updateOAuthFlowState,
});
}, [
serverConfig,
serverName,
authSettings.serverUrl,
oauthFlowState,
updateOAuthFlowState,
]);
const startGuidedFlow = useCallback(() => {
// First reset any existing flow state
resetOAuthFlow();
// Then start the new guided flow
setShowGuidedFlow(true);
updateOAuthFlowState(EMPTY_OAUTH_FLOW_STATE);
if (oauthStateMachine) {
oauthStateMachine.proceedToNextStep();
}
}, [oauthStateMachine, updateOAuthFlowState, resetOAuthFlow]);
const proceedToNextStep = useCallback(async () => {
if (oauthStateMachine) {
await oauthStateMachine.proceedToNextStep();
}
}, [oauthStateMachine]);
const exitGuidedFlow = useCallback(() => {
setShowGuidedFlow(false);
updateOAuthFlowState(EMPTY_OAUTH_FLOW_STATE);
// Refresh tokens after guided flow completion
if (serverName) {
const updatedTokens = getStoredTokens(serverName);
updateAuthSettings({ tokens: updatedTokens });
}
}, [serverName, updateAuthSettings, updateOAuthFlowState]);
const handleClearTokens = useCallback(() => {
if (serverConfig && authSettings.serverUrl && serverName) {
// Use the real OAuth system to clear tokens
clearOAuthData(serverName);
updateAuthSettings({
tokens: null,
error: null,
statusMessage: {
type: "success",
message: "OAuth tokens cleared successfully",
},
});
// Clear success message after 3 seconds
setTimeout(() => {
updateAuthSettings({ statusMessage: null });
}, 3000);
}
}, [serverConfig, authSettings.serverUrl, serverName, updateAuthSettings]);
// Check if server supports OAuth
// Only HTTP servers support OAuth (STDIO servers use process-based auth)
const isHttpServer = serverConfig && "url" in serverConfig;
const supportsOAuth = isHttpServer;
// Check if OAuth is currently configured/in-use
const hasOAuthConfigured =
serverName &&
(serverEntry?.oauthTokens ||
getStoredTokens(serverName) ||
serverEntry?.connectionStatus === "oauth-flow");
const contributionBanner = (
<div className="rounded-md border border-dashed border-primary/30 bg-primary/10 px-3 py-2 text-xs text-primary space-y-1">
<div>
<span className="font-medium">Help us improve this feature!</span>{" "}
We're looking for contributors to polish up this feature.
</div>
<a
href="https://discord.com/invite/JEnDtz8X6z"
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-xs font-medium text-primary underline hover:text-primary/80"
>
Join our Discord
</a>
</div>
);
if (!serverConfig) {
return (
<EmptyState
icon={Shield}
title="No Server Selected"
description="Connect to an MCP server to manage authentication and OAuth settings."
/>
);
}
if (!supportsOAuth) {
return (
<div className="h-full flex flex-col">
<div className="h-full flex flex-col bg-background">
{/* Header */}
<div className="flex items-center justify-between px-6 py-5 border-b border-border bg-background">
<div className="space-y-2">
<div className="flex items-center gap-3">
<RefreshCw className="h-4 w-4 text-muted-foreground" />
<h1 className="text-lg font-semibold text-foreground">
Authentication
</h1>
</div>
<p className="text-sm text-muted-foreground">
Manage OAuth authentication for the selected server
</p>
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-auto px-6 py-6">
<div className="space-y-6 max-w-2xl">
{contributionBanner}
{/* Server Info */}
<div className="rounded-md border p-4 space-y-2">
<h3 className="text-sm font-medium">Selected Server</h3>
<div className="text-xs text-muted-foreground">
<div>Name: {serverEntry?.name || "Unknown"}</div>
{isHttpServer && (
<div>URL: {(serverConfig as any).url.toString()}</div>
)}
{!isHttpServer && (
<div>Command: {(serverConfig as any).command}</div>
)}
<div>
Type: {isHttpServer ? "HTTP Server" : "STDIO Server"}
</div>
</div>
</div>
{/* No OAuth Support Message */}
<Card>
<CardContent className="pt-6">
<div className="text-center space-y-4">
<div className="mx-auto w-12 h-12 bg-muted rounded-full flex items-center justify-center">
<RefreshCw className="h-6 w-6 text-muted-foreground" />
</div>
<div className="space-y-2">
<h3 className="text-lg font-medium">
{!isHttpServer
? "No OAuth Support"
: "No Authentication Required"}
</h3>
<p className="text-sm text-muted-foreground max-w-md mx-auto">
{!isHttpServer
? "STDIO servers don't support OAuth authentication."
: `The HTTP server "${serverEntry?.name || "Unknown"}" is connected without OAuth authentication.`}
</p>
{isHttpServer && (
<p className="text-xs text-muted-foreground max-w-md mx-auto mt-2">
If this server supports OAuth, you can reconnect it
with OAuth enabled from the Servers tab.
</p>
)}
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</div>
);
}
return (
<div className="h-full flex flex-col">
<div className="h-full flex flex-col bg-background">
{/* Header */}
<div className="flex items-center justify-between px-6 py-5 border-b border-border bg-background">
<div className="space-y-2">
<div className="flex items-center gap-3">
<RefreshCw className="h-4 w-4 text-muted-foreground" />
<h1 className="text-lg font-semibold text-foreground">
Authentication
</h1>
</div>
<p className="text-sm text-muted-foreground">
Manage OAuth authentication for the selected server
</p>
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-auto px-6 py-6">
<div className="space-y-6 max-w-2xl">
{contributionBanner}
{/* Server Info */}
<div className="rounded-md border p-4 space-y-2">
<h3 className="text-sm font-medium">Selected Server</h3>
<div className="text-xs text-muted-foreground">
<div>Name: {serverEntry?.name || "Unknown"}</div>
{isHttpServer && (
<div>URL: {(serverConfig as any).url.toString()}</div>
)}
<div>Type: HTTP Server</div>
</div>
</div>
{/* OAuth Authentication */}
<div className="rounded-md border p-6 space-y-6">
<div className="flex items-center gap-2">
<RefreshCw className="h-5 w-5" />
<h3 className="text-lg font-medium">OAuth Authentication</h3>
</div>
<p className="text-sm text-muted-foreground mb-2">
{hasOAuthConfigured
? "Manage OAuth authentication for this server."
: "This server supports OAuth authentication. Use Quick OAuth to authenticate and get tokens."}
</p>
{authSettings.statusMessage && (
<StatusMessageComponent message={authSettings.statusMessage} />
)}
{authSettings.error && !authSettings.statusMessage && (
<div className="p-3 rounded-md border border-red-200 bg-red-50 text-red-700 mb-4">
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4" />
<p className="text-sm">{authSettings.error}</p>
</div>
</div>
)}
<div className="space-y-4">
{authSettings.tokens && (
<div className="space-y-2">
<p className="text-sm font-medium">Current Tokens:</p>
<div className="bg-muted p-3 rounded-md space-y-2">
<div>
<p className="text-xs font-medium text-muted-foreground">
Access Token:
</p>
<div className="text-xs font-mono overflow-x-auto">
{authSettings.tokens.access_token.substring(0, 40)}...
</div>
</div>
{authSettings.tokens.refresh_token && (
<div>
<p className="text-xs font-medium text-muted-foreground">
Refresh Token:
</p>
<div className="text-xs font-mono overflow-x-auto">
{authSettings.tokens.refresh_token.substring(0, 40)}
...
</div>
</div>
)}
<div className="flex gap-4 text-xs text-muted-foreground">
<span>Type: {authSettings.tokens.token_type}</span>
{authSettings.tokens.expires_in && (
<span>
Expires in: {authSettings.tokens.expires_in}s
</span>
)}
{authSettings.tokens.scope && (
<span>Scope: {authSettings.tokens.scope}</span>
)}
</div>
</div>
</div>
)}
<div className="flex gap-4">
<Button
onClick={
authSettings.tokens ? handleQuickRefresh : handleNewOAuth
}
disabled={authSettings.isAuthenticating || !serverConfig}
className="flex items-center gap-2"
variant={authSettings.tokens ? "outline" : "default"}
>
{authSettings.isAuthenticating ? (
<>
<RefreshCw className="h-4 w-4 animate-spin" />
{authSettings.tokens
? "Refreshing..."
: "Authenticating..."}
</>
) : (
<>
<RefreshCw className="h-4 w-4" />
{authSettings.tokens ? "Quick Refresh" : "Quick OAuth"}
</>
)}
</Button>
{authSettings.tokens && (
<Button
onClick={handleNewOAuth}
disabled={authSettings.isAuthenticating || !serverConfig}
className="flex items-center gap-2"
variant="default"
>
{authSettings.isAuthenticating ? (
<>
<RefreshCw className="h-4 w-4 animate-spin" />
Authenticating...
</>
) : (
<>
<RefreshCw className="h-4 w-4" />
Quick OAuth
</>
)}
</Button>
)}
<Button
variant="outline"
onClick={handleClearTokens}
disabled={!serverConfig || !authSettings.tokens}
>
Clear Tokens
</Button>
<Button
variant="secondary"
onClick={startGuidedFlow}
disabled={authSettings.isAuthenticating || !serverConfig}
>
Guided OAuth Flow
</Button>
</div>
<p className="text-xs text-muted-foreground">
{!serverConfig
? "Select a server to manage its OAuth authentication."
: authSettings.tokens
? "Use Quick Refresh to renew existing tokens, or Quick OAuth to start a fresh authentication flow."
: "Use Quick OAuth to authenticate with the server and get tokens."}
</p>
</div>
{/* OAuth Flow Progress */}
{showGuidedFlow && authSettings.serverUrl && (
<OAuthFlowProgressSimple
serverUrl={authSettings.serverUrl}
flowState={oauthFlowState}
updateFlowState={updateOAuthFlowState}
proceedToNextStep={proceedToNextStep}
/>
)}
{/* Exit Guided Flow Button */}
{showGuidedFlow && (
<div className="mt-4">
<Button variant="outline" onClick={exitGuidedFlow}>
Exit Guided Flow
</Button>
</div>
)}
</div>
</div>
</div>
</div>
</div>
);
};