-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathcredential_tool.py
More file actions
3205 lines (2754 loc) · 107 KB
/
credential_tool.py
File metadata and controls
3205 lines (2754 loc) · 107 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
# src/rotator_library/credential_tool.py
import asyncio
import json
import os
import re
import time
from pathlib import Path
from dotenv import set_key, get_key
# NOTE: Heavy imports (provider_factory, PROVIDER_PLUGINS) are deferred
# to avoid 6-7 second delay before showing loading screen
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt, Confirm
from rich.table import Table
from rich.text import Text
from .utils.paths import get_oauth_dir, get_data_file
def _get_oauth_base_dir() -> Path:
"""Get the OAuth base directory (lazy, respects EXE vs script mode)."""
oauth_dir = get_oauth_dir()
oauth_dir.mkdir(parents=True, exist_ok=True)
return oauth_dir
def _get_env_file() -> Path:
"""Get the .env file path (lazy, respects EXE vs script mode)."""
return get_data_file(".env")
console = Console()
# Global variables for lazily loaded modules
_provider_factory = None
_provider_plugins = None
def _ensure_providers_loaded():
"""Lazy load provider modules only when needed"""
global _provider_factory, _provider_plugins
if _provider_factory is None:
from . import provider_factory as pf
from .providers import PROVIDER_PLUGINS as pp
_provider_factory = pf
_provider_plugins = pp
return _provider_factory, _provider_plugins
# OAuth provider display names mapping (no "(OAuth)" suffix - context makes it clear)
OAUTH_FRIENDLY_NAMES = {
"gemini_cli": "Gemini CLI",
"qwen_code": "Qwen Code",
"iflow": "iFlow",
"antigravity": "Antigravity",
"codex": "OpenAI Codex",
}
def _extract_key_number(key_name: str) -> int:
"""Extract the numeric suffix from a key name for proper sorting.
Examples:
GEMINI_API_KEY_1 -> 1
GEMINI_API_KEY_10 -> 10
GEMINI_API_KEY -> 0
"""
match = re.search(r"_(\d+)$", key_name)
return int(match.group(1)) if match else 0
def _normalize_tier_name(tier: str) -> str:
"""Normalize tier names for consistent display.
Examples:
"free-tier" -> "free"
"FREE_TIER" -> "free"
"PAID" -> "paid"
"standard" -> "standard"
None -> "unknown"
"""
if not tier:
return "unknown"
# Lowercase and remove common suffixes/prefixes
normalized = tier.lower().strip()
normalized = normalized.replace("-tier", "").replace("_tier", "")
normalized = normalized.replace("-", "").replace("_", "")
return normalized
def _count_tiers(credentials: list) -> dict:
"""Count credentials by tier.
Args:
credentials: List of credential info dicts with optional 'tier' key
Returns:
Dict mapping normalized tier names to counts, e.g. {"free": 15, "paid": 2}
"""
tier_counts = {}
for cred in credentials:
tier = cred.get("tier")
if tier:
normalized = _normalize_tier_name(tier)
tier_counts[normalized] = tier_counts.get(normalized, 0) + 1
return tier_counts
def _format_tier_counts(tier_counts: dict) -> str:
"""Format tier counts as a compact string.
Examples:
{"free": 15, "paid": 2} -> "(15 free, 2 paid)"
{"free": 5} -> "(5 free)"
{} -> ""
"""
if not tier_counts:
return ""
# Sort by count descending, then alphabetically
sorted_tiers = sorted(tier_counts.items(), key=lambda x: (-x[1], x[0]))
parts = [f"{count} {tier}" for tier, count in sorted_tiers]
return f"({', '.join(parts)})"
def _get_api_keys_from_env() -> dict:
"""
Parse the .env file and return a dictionary of API keys grouped by provider.
Keys are sorted numerically within each provider.
Returns:
Dict mapping provider names to lists of (key_name, key_value) tuples.
Example: {"GEMINI": [("GEMINI_API_KEY_1", "abc123"), ("GEMINI_API_KEY_2", "def456")]}
"""
api_keys = {}
env_file = _get_env_file()
if not env_file.is_file():
return api_keys
try:
with open(env_file, "r") as f:
for line in f:
line = line.strip()
# Skip comments and empty lines
if not line or line.startswith("#"):
continue
# Look for lines with API_KEY pattern
if "_API_KEY" in line and "=" in line:
key_name, _, key_value = line.partition("=")
key_name = key_name.strip()
key_value = key_value.strip().strip('"').strip("'")
# Skip PROXY_API_KEY and empty values
if key_name == "PROXY_API_KEY" or not key_value:
continue
# Skip placeholder values
if key_value.startswith("YOUR_") or key_value == "":
continue
# Extract provider name (everything before _API_KEY)
# Handle cases like GEMINI_API_KEY_1 -> GEMINI
parts = key_name.split("_API_KEY")
if parts:
provider_name = parts[0]
if provider_name not in api_keys:
api_keys[provider_name] = []
api_keys[provider_name].append((key_name, key_value))
# Sort keys numerically within each provider
for provider_name in api_keys:
api_keys[provider_name].sort(key=lambda x: _extract_key_number(x[0]))
except Exception as e:
console.print(f"[bold red]Error reading .env file: {e}[/bold red]")
return api_keys
def _delete_api_key_from_env(key_name: str) -> bool:
"""
Delete an API key from the .env file with safety backup and comparison.
This function creates a backup of all API keys before deletion,
performs the deletion, and then verifies no unintended keys were lost.
Args:
key_name: The exact key name to delete (e.g., "GEMINI_API_KEY_2")
Returns:
True if deletion was successful and verified, False otherwise
"""
env_file = _get_env_file()
if not env_file.is_file():
console.print("[bold red]Error: .env file not found[/bold red]")
return False
try:
# Step 1: Read all lines and backup all API keys
with open(env_file, "r") as f:
original_lines = f.readlines()
# Create backup of all API keys before modification
api_keys_before = _get_api_keys_from_env()
all_keys_before = set()
for provider_keys in api_keys_before.values():
for kn, kv in provider_keys:
all_keys_before.add((kn, kv))
# Step 2: Find and remove the target key
new_lines = []
key_found = False
deleted_key_value = None
for line in original_lines:
stripped = line.strip()
# Check if this line contains our target key
if stripped.startswith(f"{key_name}="):
key_found = True
# Store the value being deleted for verification
_, _, deleted_key_value = stripped.partition("=")
deleted_key_value = deleted_key_value.strip().strip('"').strip("'")
continue # Skip this line (delete it)
new_lines.append(line)
if not key_found:
console.print(
f"[bold red]Error: Key '{key_name}' not found in .env file[/bold red]"
)
return False
# Step 3: Write the modified content
with open(env_file, "w") as f:
f.writelines(new_lines)
# Step 4: Verify the deletion - compare before and after
api_keys_after = _get_api_keys_from_env()
all_keys_after = set()
for provider_keys in api_keys_after.values():
for kn, kv in provider_keys:
all_keys_after.add((kn, kv))
# Check that only the intended key was removed
expected_remaining = all_keys_before - {(key_name, deleted_key_value)}
if all_keys_after != expected_remaining:
# Something went wrong - restore from backup
console.print(
"[bold red]Error: Unexpected keys were affected during deletion![/bold red]"
)
console.print("[bold yellow]Restoring original file...[/bold yellow]")
with open(env_file, "w") as f:
f.writelines(original_lines)
return False
return True
except Exception as e:
console.print(f"[bold red]Error during API key deletion: {e}[/bold red]")
return False
def _get_oauth_credentials_summary() -> dict:
"""
Get a summary of all OAuth credentials for all providers.
Returns:
Dict mapping provider names to lists of credential info dicts.
Example: {"gemini_cli": [{"email": "user@example.com", "tier": "free-tier", ...}, ...]}
"""
provider_factory, _ = _ensure_providers_loaded()
oauth_providers = ["gemini_cli", "qwen_code", "iflow", "antigravity"]
oauth_summary = {}
for provider_name in oauth_providers:
try:
auth_class = provider_factory.get_provider_auth_class(provider_name)
auth_instance = auth_class()
credentials = auth_instance.list_credentials(_get_oauth_base_dir())
oauth_summary[provider_name] = credentials
except Exception:
oauth_summary[provider_name] = []
return oauth_summary
def _get_all_credentials_summary() -> dict:
"""
Get a complete summary of all credentials (API keys and OAuth).
Returns:
Dict with "api_keys" and "oauth" sections containing credential summaries.
"""
return {
"api_keys": _get_api_keys_from_env(),
"oauth": _get_oauth_credentials_summary(),
}
def _get_existing_custom_providers() -> list:
"""
Scan the .env file for existing custom OpenAI-compatible providers.
Custom providers are identified by *_CUSTOM_API_BASE entries.
Returns:
List of dicts with provider info:
[{"name": "myserver", "api_base": "http://...", "has_key": True}, ...]
"""
custom_providers = []
env_file = _get_env_file()
if not env_file.is_file():
return custom_providers
try:
# First pass: collect all CUSTOM_API_BASE entries
api_bases = {}
api_keys = set()
with open(env_file, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
key_name, _, value = line.partition("=")
key_name = key_name.strip()
value = value.strip().strip('"').strip("'")
if key_name.endswith("_CUSTOM_API_BASE") and value:
provider_name = key_name[:-16].lower() # Remove _CUSTOM_API_BASE
api_bases[provider_name] = value
elif "_API_KEY" in key_name and value:
# Extract provider name from API key
provider_prefix = key_name.split("_API_KEY")[0].lower()
api_keys.add(provider_prefix)
# Build result list
for provider_name, api_base in sorted(api_bases.items()):
custom_providers.append(
{
"name": provider_name,
"api_base": api_base,
"has_key": provider_name in api_keys,
}
)
except Exception as e:
console.print(f"[bold red]Error reading .env file: {e}[/bold red]")
return custom_providers
def _display_custom_providers_summary():
"""
Display a summary of existing custom OpenAI-compatible providers.
"""
custom_providers = _get_existing_custom_providers()
if not custom_providers:
console.print(
"[dim]No custom OpenAI-compatible providers configured yet.[/dim]\n"
)
return
table = Table(
title="Existing Custom Providers",
box=None,
padding=(0, 2),
title_style="bold cyan",
)
table.add_column("Provider", style="yellow", no_wrap=True)
table.add_column("API Base", style="dim")
table.add_column("API Key", style="green", justify="center")
for provider in custom_providers:
name = provider["name"].upper()
api_base = provider["api_base"]
# Truncate long URLs
if len(api_base) > 40:
api_base = api_base[:37] + "..."
has_key = "✓" if provider["has_key"] else "✗"
key_style = "green" if provider["has_key"] else "red"
table.add_row(name, api_base, Text(has_key, style=key_style))
console.print(table)
console.print()
def _display_credentials_summary():
"""
Display a compact 2-column summary of all configured credentials.
API Keys on the left, OAuth credentials on the right.
Handles cases where only one type exists or neither.
"""
from rich.columns import Columns
summary = _get_all_credentials_summary()
api_keys = summary["api_keys"]
oauth_creds = summary["oauth"]
# Calculate totals
total_api_keys = sum(len(keys) for keys in api_keys.values())
total_oauth = sum(len(creds) for creds in oauth_creds.values() if creds)
# Handle empty case
if total_api_keys == 0 and total_oauth == 0:
console.print("[dim]No credentials configured yet.[/dim]\n")
return
# Build API Keys table (left column)
api_table = None
if total_api_keys > 0:
api_table = Table(
title="API Keys", box=None, padding=(0, 1), title_style="bold cyan"
)
api_table.add_column("Provider", style="yellow", no_wrap=True)
api_table.add_column("Count", style="green", justify="right")
for provider, keys in sorted(api_keys.items()):
api_table.add_row(provider, str(len(keys)))
# Add total row
api_table.add_row("─" * 12, "─" * 5, style="dim")
api_table.add_row("Total", str(total_api_keys), style="bold")
# Build OAuth table (right column)
oauth_table = None
if total_oauth > 0:
oauth_table = Table(
title="OAuth Credentials", box=None, padding=(0, 1), title_style="bold cyan"
)
oauth_table.add_column("Provider", style="yellow", no_wrap=True)
oauth_table.add_column("Count", style="green", justify="right")
oauth_table.add_column("Tiers", style="dim", no_wrap=True)
for provider, creds in sorted(oauth_creds.items()):
if not creds:
continue
display_name = OAUTH_FRIENDLY_NAMES.get(provider, provider.title())
count = len(creds)
# Count and format tiers for providers that have tier info
tier_counts = _count_tiers(creds)
tier_str = _format_tier_counts(tier_counts)
oauth_table.add_row(display_name, str(count), tier_str)
# Add total row
oauth_table.add_row("─" * 12, "─" * 5, "", style="dim")
oauth_table.add_row("Total", str(total_oauth), "", style="bold")
# Display based on what's available
if api_table and oauth_table:
# Both columns - use Columns for side-by-side layout
console.print(Columns([api_table, oauth_table], padding=(0, 4), expand=False))
elif api_table:
# Only API keys
console.print(api_table)
elif oauth_table:
# Only OAuth
console.print(oauth_table)
console.print("") # Blank line after summary
def _display_oauth_providers_summary():
"""
Display a compact summary of OAuth providers only (used when adding OAuth credentials).
"""
oauth_summary = _get_oauth_credentials_summary()
total = sum(len(creds) for creds in oauth_summary.values())
# Build compact table
table = Table(
title="Current OAuth Credentials",
box=None,
padding=(0, 1),
title_style="bold cyan",
)
table.add_column("Provider", style="yellow", no_wrap=True)
table.add_column("Count", style="green", justify="right")
for provider, creds in sorted(oauth_summary.items()):
display_name = OAUTH_FRIENDLY_NAMES.get(provider, provider.title())
table.add_row(display_name, str(len(creds)))
if total > 0:
table.add_row("─" * 12, "─" * 5, style="dim")
table.add_row("Total", str(total), style="bold")
console.print(table)
console.print("")
def _display_provider_credentials(provider_name: str):
"""
Display all credentials for a specific OAuth provider.
Args:
provider_name: The provider key (e.g., "gemini_cli", "qwen_code")
"""
provider_factory, _ = _ensure_providers_loaded()
try:
auth_class = provider_factory.get_provider_auth_class(provider_name)
auth_instance = auth_class()
credentials = auth_instance.list_credentials(_get_oauth_base_dir())
except Exception:
credentials = []
display_name = OAUTH_FRIENDLY_NAMES.get(provider_name, provider_name.title())
if not credentials:
console.print(f"\n[dim]No existing credentials for {display_name}[/dim]\n")
return
console.print(f"\n[bold cyan]Existing {display_name} Credentials:[/bold cyan]")
table = Table(box=None, padding=(0, 2))
table.add_column("#", style="dim", width=3)
table.add_column("File", style="yellow")
table.add_column("Email/Identifier", style="cyan")
# Add tier/project columns for Google OAuth providers
if provider_name in ["gemini_cli", "antigravity"]:
table.add_column("Tier", style="green")
table.add_column("Project", style="dim")
for i, cred in enumerate(credentials, 1):
file_name = Path(cred["file_path"]).name
email = cred.get("email", "unknown")
if provider_name in ["gemini_cli", "antigravity"]:
tier = cred.get("tier", "-")
project = cred.get("project_id", "-")
if project and len(project) > 20:
project = project[:17] + "..."
table.add_row(str(i), file_name, email, tier or "-", project or "-")
else:
table.add_row(str(i), file_name, email)
console.print(table)
console.print("")
async def _edit_oauth_credential_email(provider_name: str):
"""
Edit the email field of an OAuth credential.
Args:
provider_name: The provider key (e.g., "qwen_code")
"""
provider_factory, _ = _ensure_providers_loaded()
try:
auth_class = provider_factory.get_provider_auth_class(provider_name)
auth_instance = auth_class()
credentials = auth_instance.list_credentials(_get_oauth_base_dir())
except Exception as e:
console.print(f"[bold red]Error loading credentials: {e}[/bold red]")
return
display_name = OAUTH_FRIENDLY_NAMES.get(provider_name, provider_name.title())
if not credentials:
console.print(
f"[bold yellow]No {display_name} credentials found.[/bold yellow]"
)
return
# Display credentials for selection
_display_provider_credentials(provider_name)
choice = Prompt.ask(
Text.from_markup(
"[bold]Select credential to edit or type [red]'b'[/red] to go back[/bold]"
),
choices=[str(i) for i in range(1, len(credentials) + 1)] + ["b"],
show_choices=False,
)
if choice.lower() == "b":
return
try:
idx = int(choice) - 1
cred_info = credentials[idx]
cred_path = cred_info["file_path"]
current_email = cred_info.get("email", "unknown")
console.print(f"\nCurrent email: [cyan]{current_email}[/cyan]")
new_email = Prompt.ask("Enter new email/identifier")
if not new_email.strip():
console.print("[bold yellow]No changes made (empty input).[/bold yellow]")
return
# Load and update the credential file
with open(cred_path, "r") as f:
creds = json.load(f)
if "_proxy_metadata" not in creds:
creds["_proxy_metadata"] = {}
old_email = creds["_proxy_metadata"].get("email")
creds["_proxy_metadata"]["email"] = new_email.strip()
# Save the updated credentials
with open(cred_path, "w") as f:
json.dump(creds, f, indent=2)
console.print(
Panel(
f"Email updated from [yellow]'{old_email}'[/yellow] to [green]'{new_email.strip()}'[/green]",
style="bold green",
title="Success",
expand=False,
)
)
except Exception as e:
console.print(f"[bold red]Error editing credential: {e}[/bold red]")
async def view_credentials_menu():
"""
Menu for viewing credentials. Shows summary first, then allows drilling
down to view detailed credentials for a specific provider.
"""
while True:
clear_screen("View Credentials")
# Display summary
_display_credentials_summary()
# Build list of all providers with credentials
api_keys = _get_api_keys_from_env()
oauth_creds = _get_oauth_credentials_summary()
all_providers = []
# Add API key providers
for provider in sorted(api_keys.keys()):
count = len(api_keys[provider])
all_providers.append(("api", provider, count))
# Add OAuth providers with credentials
for provider in sorted(oauth_creds.keys()):
if oauth_creds[provider]:
count = len(oauth_creds[provider])
display_name = OAUTH_FRIENDLY_NAMES.get(provider, provider.title())
all_providers.append(("oauth", provider, count, display_name))
if not all_providers:
console.print("[bold yellow]No credentials configured.[/bold yellow]")
console.print("\n[dim]Press Enter to return to main menu...[/dim]")
input()
break
# Display provider selection menu
console.print(
Panel(
Text.from_markup("[bold]Select a provider to view details:[/bold]"),
title="View Provider Credentials",
style="bold blue",
)
)
for i, provider_info in enumerate(all_providers, 1):
if provider_info[0] == "api":
_, provider, count = provider_info
console.print(f" {i}. [cyan]API:[/cyan] {provider} ({count} key(s))")
else:
_, provider, count, display_name = provider_info
console.print(
f" {i}. [cyan]OAuth:[/cyan] {display_name} ({count} credential(s))"
)
choice = Prompt.ask(
Text.from_markup(
"\n[bold]Select provider or type [red]'b'[/red] to go back[/bold]"
),
choices=[str(i) for i in range(1, len(all_providers) + 1)] + ["b"],
show_choices=False,
)
if choice.lower() == "b":
break
try:
idx = int(choice) - 1
provider_info = all_providers[idx]
if provider_info[0] == "api":
_, provider, _ = provider_info
await _view_api_keys_detail(provider)
else:
_, provider, _, _ = provider_info
await _view_oauth_credentials_detail(provider)
except (ValueError, IndexError):
console.print("[bold red]Invalid choice.[/bold red]")
await asyncio.sleep(1)
async def _view_api_keys_detail(provider_name: str):
"""Display detailed view of API keys for a specific provider."""
clear_screen(f"View {provider_name} API Keys")
api_keys = _get_api_keys_from_env()
keys = api_keys.get(provider_name, [])
if not keys:
console.print(
f"[bold yellow]No API keys found for {provider_name}.[/bold yellow]"
)
console.print("\n[dim]Press Enter to go back...[/dim]")
input()
return
# Display detailed table
table = Table(title=f"{provider_name} API Keys", box=None, padding=(0, 2))
table.add_column("#", style="dim", width=4)
table.add_column("Key Name", style="yellow")
table.add_column("Value (masked)", style="dim")
for i, (key_name, key_value) in enumerate(keys, 1):
masked = f"****{key_value[-4:]}" if len(key_value) > 4 else "****"
table.add_row(str(i), key_name, masked)
console.print(table)
console.print(f"\n[dim]Total: {len(keys)} key(s)[/dim]")
console.print("\n[dim]Press Enter to go back...[/dim]")
input()
async def _view_oauth_credentials_detail(provider_name: str):
"""Display detailed view of OAuth credentials for a specific provider."""
display_name = OAUTH_FRIENDLY_NAMES.get(provider_name, provider_name.title())
clear_screen(f"View {display_name} Credentials")
provider_factory, _ = _ensure_providers_loaded()
try:
auth_class = provider_factory.get_provider_auth_class(provider_name)
auth_instance = auth_class()
credentials = auth_instance.list_credentials(_get_oauth_base_dir())
except Exception:
credentials = []
if not credentials:
console.print(
f"[bold yellow]No credentials found for {display_name}.[/bold yellow]"
)
console.print("\n[dim]Press Enter to go back...[/dim]")
input()
return
# Display detailed table
table = Table(title=f"{display_name} Credentials", box=None, padding=(0, 2))
table.add_column("#", style="dim", width=4)
table.add_column("File", style="yellow")
table.add_column("Email/Identifier", style="cyan")
# Add tier/project columns for Google OAuth providers
if provider_name in ["gemini_cli", "antigravity"]:
table.add_column("Tier", style="green")
table.add_column("Project", style="dim")
for i, cred in enumerate(credentials, 1):
file_name = Path(cred["file_path"]).name
email = cred.get("email", "unknown")
if provider_name in ["gemini_cli", "antigravity"]:
tier = _normalize_tier_name(cred.get("tier")) if cred.get("tier") else "-"
project = cred.get("project_id", "-")
if project and len(project) > 25:
project = project[:22] + "..."
table.add_row(str(i), file_name, email, tier, project or "-")
else:
table.add_row(str(i), file_name, email)
console.print(table)
console.print(f"\n[dim]Total: {len(credentials)} credential(s)[/dim]")
console.print("\n[dim]Press Enter to go back...[/dim]")
input()
async def manage_credentials_submenu():
"""
Submenu for viewing and managing all credentials (API keys and OAuth).
Allows deletion of any credential and editing email for OAuth credentials.
"""
while True:
clear_screen("Manage Credentials")
# Display full summary
_display_credentials_summary()
console.print(
Panel(
Text.from_markup(
"[bold]Actions:[/bold]\n"
"1. Delete an API Key\n"
"2. Delete an OAuth Credential\n"
"3. Edit OAuth Credential Email [dim](Qwen Code recommended)[/dim]"
),
title="Choose action",
style="bold blue",
)
)
action = Prompt.ask(
Text.from_markup(
"[bold]Select an option or type [red]'b'[/red] to go back[/bold]"
),
choices=["1", "2", "3", "b"],
show_choices=False,
)
if action.lower() == "b":
break
if action == "1":
# Delete API Key
await _delete_api_key_menu()
console.print("\n[dim]Press Enter to continue...[/dim]")
input()
elif action == "2":
# Delete OAuth Credential
await _delete_oauth_credential_menu()
console.print("\n[dim]Press Enter to continue...[/dim]")
input()
elif action == "3":
# Edit OAuth Credential Email
await _edit_oauth_credential_menu()
console.print("\n[dim]Press Enter to continue...[/dim]")
input()
async def _delete_api_key_menu():
"""Menu for deleting an API key from the .env file."""
clear_screen("Delete API Key")
api_keys = _get_api_keys_from_env()
if not api_keys:
console.print("[bold yellow]No API keys configured.[/bold yellow]")
return
# Build a flat list of all keys for selection
all_keys = []
console.print("\n[bold cyan]Configured API Keys:[/bold cyan]")
table = Table(box=None, padding=(0, 2))
table.add_column("#", style="dim", width=3)
table.add_column("Key Name", style="yellow")
table.add_column("Provider", style="cyan")
table.add_column("Value", style="dim")
idx = 1
for provider, keys in sorted(api_keys.items()):
for key_name, key_value in keys:
masked = f"****{key_value[-4:]}" if len(key_value) > 4 else "****"
table.add_row(str(idx), key_name, provider, masked)
all_keys.append((key_name, key_value, provider))
idx += 1
console.print(table)
choice = Prompt.ask(
Text.from_markup(
"\n[bold]Select API key to delete or type [red]'b'[/red] to go back[/bold]"
),
choices=[str(i) for i in range(1, len(all_keys) + 1)] + ["b"],
show_choices=False,
)
if choice.lower() == "b":
return
try:
idx = int(choice) - 1
key_name, key_value, provider = all_keys[idx]
# Confirmation prompt
masked = f"****{key_value[-4:]}" if len(key_value) > 4 else "****"
confirmed = Confirm.ask(
f"[bold red]Delete[/bold red] [yellow]{key_name}[/yellow] ({masked})?"
)
if not confirmed:
console.print("[dim]Deletion cancelled.[/dim]")
return
if _delete_api_key_from_env(key_name):
console.print(
Panel(
f"Successfully deleted [yellow]{key_name}[/yellow]",
style="bold green",
title="Success",
expand=False,
)
)
else:
console.print(
Panel(
f"Failed to delete [yellow]{key_name}[/yellow]",
style="bold red",
title="Error",
expand=False,
)
)
except Exception as e:
console.print(f"[bold red]Error: {e}[/bold red]")
async def _delete_oauth_credential_menu():
"""Menu for deleting an OAuth credential file."""
clear_screen("Delete OAuth Credential")
oauth_summary = _get_oauth_credentials_summary()
# Check if there are any credentials
total = sum(len(creds) for creds in oauth_summary.values())
if total == 0:
console.print("[bold yellow]No OAuth credentials configured.[/bold yellow]")
return
# First, select provider
console.print("\n[bold cyan]Select OAuth Provider:[/bold cyan]")
providers_with_creds = [(p, c) for p, c in oauth_summary.items() if c]
for i, (provider, creds) in enumerate(providers_with_creds, 1):
display_name = OAUTH_FRIENDLY_NAMES.get(provider, provider.title())
console.print(f" {i}. {display_name} ({len(creds)} credential(s))")
provider_choice = Prompt.ask(
Text.from_markup(
"\n[bold]Select provider or type [red]'b'[/red] to go back[/bold]"
),
choices=[str(i) for i in range(1, len(providers_with_creds) + 1)] + ["b"],
show_choices=False,
)
if provider_choice.lower() == "b":
return
try:
provider_idx = int(provider_choice) - 1
provider_name, credentials = providers_with_creds[provider_idx]
display_name = OAUTH_FRIENDLY_NAMES.get(provider_name, provider_name.title())
# Now select credential
_display_provider_credentials(provider_name)
cred_choice = Prompt.ask(
Text.from_markup(
"[bold]Select credential to delete or type [red]'b'[/red] to go back[/bold]"
),
choices=[str(i) for i in range(1, len(credentials) + 1)] + ["b"],
show_choices=False,
)
if cred_choice.lower() == "b":
return
cred_idx = int(cred_choice) - 1
cred_info = credentials[cred_idx]
cred_path = cred_info["file_path"]
email = cred_info.get("email", "unknown")
# Confirmation prompt
confirmed = Confirm.ask(
f"[bold red]Delete[/bold red] credential for [cyan]{email}[/cyan] from {display_name}?"
)
if not confirmed:
console.print("[dim]Deletion cancelled.[/dim]")
return
# Use the auth class's delete method
provider_factory, _ = _ensure_providers_loaded()
auth_class = provider_factory.get_provider_auth_class(provider_name)
auth_instance = auth_class()