-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcursor_token_manager.py
More file actions
executable file
·991 lines (788 loc) · 40.6 KB
/
cursor_token_manager.py
File metadata and controls
executable file
·991 lines (788 loc) · 40.6 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
#!/usr/bin/env python3
"""
Cursor Token Manager - 命令行工具
功能:导入、保存、查询、刷新 Cursor Token
带图形化命令行交互界面
开发者: hihi
"""
import os
import sys
import json
import sqlite3
import requests
import uuid
import hashlib
from pathlib import Path
from datetime import datetime, timedelta
from typing import Optional, Dict
import base64
try:
from colorama import Fore, Style, Back, init
init(autoreset=True)
except ImportError:
print("请先安装依赖: pip install colorama")
sys.exit(1)
class CursorTokenManager:
"""Cursor Token 管理器"""
def __init__(self):
self.config_dir = Path(__file__).parent / "Token"
self.config_dir.mkdir(parents=True, exist_ok=True)
self.token_file = self.config_dir / "hihi.json"
# Cursor 官方路径
if sys.platform == "darwin": # macOS
self.cursor_storage = Path.home() / "Library/Application Support/Cursor/User/globalStorage"
elif sys.platform == "win32": # Windows
self.cursor_storage = Path(os.getenv("APPDATA")) / "Cursor/User/globalStorage"
else: # Linux
self.cursor_storage = Path.home() / ".config/Cursor/User/globalStorage"
self.storage_json = self.cursor_storage / "storage.json"
self.storage_db = self.cursor_storage / "state.vscdb"
def print_header(self, title):
"""打印标题"""
print(f"\n{Fore.CYAN}{'─' * 60}{Style.RESET_ALL}")
print(f"{Fore.CYAN}{title}{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'─' * 60}{Style.RESET_ALL}\n")
def print_hihi_logo(self):
"""打印 HIHI Logo"""
logo = f"""{Fore.CYAN}
╔═══════════════════════════════════════════════════════════════╗
║ ║
║ {Fore.YELLOW}██ ██ ██ ██ ██ ██{Fore.CYAN} ║
║ {Fore.YELLOW}██ ██ ██ ██ ██ ██{Fore.CYAN} {Fore.MAGENTA}Cursor Token Manager{Fore.CYAN} ║
║ {Fore.YELLOW}███████ ██ ███████ ██{Fore.CYAN} ║
║ {Fore.YELLOW}██ ██ ██ ██ ██ ██{Fore.CYAN} {Fore.GREEN}━━━━━━━━━━━━━━━━━━━━{Fore.CYAN} ║
║ {Fore.YELLOW}██ ██ ██ ██ ██ ██{Fore.CYAN} ║
║ ║
║ {Fore.YELLOW}✨ Developed by {Fore.RED}hihi{Fore.YELLOW} ✨{Fore.CYAN} ║
║ ║
╚═══════════════════════════════════════════════════════════════╝
{Style.RESET_ALL}"""
print(logo)
def print_box(self, content, color=Fore.WHITE):
"""打印带边框的内容"""
lines = content.split('\n')
for line in lines:
print(f"{color}{line}{Style.RESET_ALL}")
def print_menu(self):
"""打印主菜单"""
self.print_hihi_logo()
self.print_header("Cursor Token Manager")
print("1. 导入 Token")
print("2. 保存 Token")
print("3. Token 状态查询")
print("4. 刷新 Token")
print("5. 查看保存的 Token")
print("6. 登录 Cursor")
print("0. 退出")
print(f"\n{Fore.CYAN}Developed by hihi{Style.RESET_ALL}")
print()
def decode_jwt(self, token: str) -> Optional[Dict]:
"""解码 JWT Token"""
try:
# JWT 格式: header.payload.signature
parts = token.split('.')
if len(parts) != 3:
return None
# 解码 payload (需要补齐 padding)
payload = parts[1]
padding = 4 - len(payload) % 4
if padding != 4:
payload += '=' * padding
decoded = base64.urlsafe_b64decode(payload)
return json.loads(decoded)
except Exception as e:
print(f"{Fore.RED}❌ 解码 Token 失败: {e}{Style.RESET_ALL}")
return None
def get_token_expiry(self, token: str) -> Optional[datetime]:
"""获取 Token 过期时间"""
payload = self.decode_jwt(token)
if payload and 'exp' in payload:
return datetime.fromtimestamp(payload['exp'])
return None
def import_from_cursor(self):
"""从 Cursor 客户端导入 Token"""
self.print_header("从 Cursor 导入 Token")
# 检查数据库文件
if not self.storage_db.exists():
print(f"{Fore.RED}未找到 Cursor 数据库{Style.RESET_ALL}")
print(f"路径: {self.storage_db}")
print(f"{Fore.YELLOW}请确保已安装并登录 Cursor{Style.RESET_ALL}")
return
try:
# 从 SQLite 数据库读取 Token
conn = sqlite3.connect(str(self.storage_db))
cursor = conn.cursor()
# 读取 Access Token
cursor.execute("SELECT value FROM ItemTable WHERE key = ?", ("cursorAuth/accessToken",))
access_result = cursor.fetchone()
access_token = access_result[0] if access_result else None
# 读取 Refresh Token
cursor.execute("SELECT value FROM ItemTable WHERE key = ?", ("cursorAuth/refreshToken",))
refresh_result = cursor.fetchone()
refresh_token = refresh_result[0] if refresh_result else None
# 读取邮箱
cursor.execute("SELECT value FROM ItemTable WHERE key = ?", ("cursorAuth/cachedEmail",))
email_result = cursor.fetchone()
email = email_result[0] if email_result else 'unknown'
conn.close()
if not access_token or not refresh_token:
print(f"{Fore.RED}未找到有效的 Token{Style.RESET_ALL}")
print(f"{Fore.YELLOW}请先在 Cursor 中登录{Style.RESET_ALL}")
return
# 保存 Token
token_data = {
'access_token': access_token,
'refresh_token': refresh_token,
'email': email,
'imported_at': datetime.now().isoformat(),
'source': 'cursor_client'
}
self.save_token_to_file(token_data)
print(f"{Fore.GREEN}导入成功{Style.RESET_ALL}")
print(f"邮箱: {email}")
print(f"导入时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# 显示 Token 信息
self.show_token_info(token_data)
except Exception as e:
print(f"{Fore.RED}导入失败: {e}{Style.RESET_ALL}")
def save_token_manually(self):
"""手动输入并保存 Token"""
self.print_header("手动保存 Token")
print(f"{Fore.YELLOW}请选择 Token 类型:{Style.RESET_ALL}\n")
print("1. 客户端 Token (长期有效)")
print("2. 网页版 Cookie Token (短期,将自动转换)")
print()
token_type = input("请选择 [1-2]: ").strip()
if token_type == '1':
# 客户端 Token
print(f"\n{Fore.YELLOW}请输入以下信息(直接回车跳过可选项){Style.RESET_ALL}\n")
email = input("邮箱: ").strip()
access_token = input("Access Token: ").strip()
refresh_token = input("Refresh Token (可选): ").strip()
if not access_token:
print(f"{Fore.RED}Access Token 不能为空{Style.RESET_ALL}")
return
token_data = {
'access_token': access_token,
'refresh_token': refresh_token if refresh_token else None,
'email': email if email else 'manually_added',
'imported_at': datetime.now().isoformat(),
'source': 'manual_input'
}
self.save_token_to_file(token_data)
print(f"\n{Fore.GREEN}保存成功{Style.RESET_ALL}")
self.show_token_info(token_data)
elif token_type == '2':
# 网页版 Cookie Token 转换
self.convert_web_cookie_to_session_token()
else:
print(f"{Fore.RED}无效选择{Style.RESET_ALL}")
def save_token_to_file(self, token_data: Dict):
"""保存 Token 到文件(自动去重)"""
try:
# 读取现有数据
if self.token_file.exists():
with open(self.token_file, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
else:
existing_data = {'tokens': []}
# 去重检查:同一个 access_token 或邮箱只保存一次
new_access_token = token_data.get('access_token')
new_email = token_data.get('email')
# 检查是否已存在
for existing_token in existing_data['tokens']:
if existing_token.get('access_token') == new_access_token:
print(f"{Fore.YELLOW}该 Token 已存在,跳过保存{Style.RESET_ALL}")
return
if new_email != 'unknown' and new_email != 'manually_added' and existing_token.get('email') == new_email:
print(f"{Fore.YELLOW}该邮箱 ({new_email}) 的 Token 已存在,将更新为最新 Token{Style.RESET_ALL}")
# 移除旧的同邮箱 Token
existing_data['tokens'].remove(existing_token)
break
# 添加新 Token
existing_data['tokens'].append(token_data)
existing_data['last_updated'] = datetime.now().isoformat()
# 保存
with open(self.token_file, 'w', encoding='utf-8') as f:
json.dump(existing_data, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"{Fore.RED}保存失败: {e}{Style.RESET_ALL}")
def show_token_info(self, token_data: Dict):
"""显示 Token 信息"""
print()
# 优先显示邮箱信息
email = token_data.get('email', 'unknown')
print(f"{Fore.CYAN}账号邮箱: {email}{Style.RESET_ALL}")
print()
access_token = token_data.get('access_token')
refresh_token = token_data.get('refresh_token')
# 解析 Access Token
if access_token:
payload = self.decode_jwt(access_token)
if payload:
print(f"{Fore.GREEN}Access Token:{Style.RESET_ALL}")
print(f"Token: {access_token[:50]}...")
if 'exp' in payload:
exp_time = datetime.fromtimestamp(payload['exp'])
now = datetime.now()
remaining = exp_time - now
if remaining.total_seconds() > 0:
print(f"过期时间: {exp_time.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"{Fore.GREEN}剩余: {self.format_timedelta(remaining)}{Style.RESET_ALL}")
else:
print(f"{Fore.RED}已过期{Style.RESET_ALL}")
# 解析 Refresh Token
if refresh_token:
print(f"\n{Fore.MAGENTA}Refresh Token:{Style.RESET_ALL}")
print(f"Token: {refresh_token[:50]}...")
payload = self.decode_jwt(refresh_token)
if payload and 'exp' in payload:
exp_time = datetime.fromtimestamp(payload['exp'])
now = datetime.now()
remaining = exp_time - now
if remaining.total_seconds() > 0:
print(f"过期时间: {exp_time.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"{Fore.GREEN}剩余: {self.format_timedelta(remaining)}{Style.RESET_ALL}")
else:
print(f"{Fore.RED}已过期{Style.RESET_ALL}")
print()
def format_timedelta(self, td: timedelta) -> str:
"""格式化时间差"""
days = td.days
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
parts = []
if days > 0:
parts.append(f"{days}天")
if hours > 0:
parts.append(f"{hours}小时")
if minutes > 0:
parts.append(f"{minutes}分钟")
if seconds > 0 or not parts:
parts.append(f"{seconds}秒")
return " ".join(parts)
def check_token_status(self):
"""查询所有保存的 Token 状态"""
self.print_header("Token 状态查询")
# 读取所有保存的 Token
if not self.token_file.exists():
print(f"{Fore.YELLOW}未找到保存的 Token{Style.RESET_ALL}")
print("请先导入或保存 Token")
return
try:
with open(self.token_file, 'r', encoding='utf-8') as f:
data = json.load(f)
if not data.get('tokens'):
print(f"{Fore.YELLOW}没有保存的 Token{Style.RESET_ALL}")
return
tokens = data['tokens']
total = len(tokens)
print(f"{Fore.CYAN}共找到 {total} 个保存的 Token{Style.RESET_ALL}\n")
print("=" * 60)
# 遍历所有 Token 并验证
for idx, token_data in enumerate(tokens, 1):
print(f"\n{Fore.CYAN}[{idx}/{total}] 验证 Token...{Style.RESET_ALL}")
email = token_data.get('email', 'N/A')
access_token = token_data.get('access_token')
source = token_data.get('source', 'unknown')
imported_at = token_data.get('imported_at', 'N/A')
print(f"邮箱: {email}")
print(f"来源: {source}")
print(f"导入时间: {imported_at}")
if not access_token:
print(f"{Fore.RED}✗ 未找到有效的 Access Token{Style.RESET_ALL}")
print("-" * 60)
continue
# 测试 Token 有效性
headers = {
'Authorization': f'Bearer {access_token}',
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json'
}
try:
response = requests.get(
'https://api2.cursor.sh/auth/full_stripe_profile',
headers=headers,
timeout=10
)
if response.status_code == 200:
profile = response.json()
print(f"\n{Fore.GREEN}✓ Token 有效{Style.RESET_ALL}")
print(f"订阅类型: {profile.get('membershipType', 'N/A')}")
print(f"订阅状态: {profile.get('subscriptionStatus', 'N/A')}")
days_remaining = profile.get('daysRemainingOnTrial')
if days_remaining is not None:
print(f"剩余试用天数: {days_remaining} 天")
# 显示过期时间
try:
payload = jwt.decode(access_token, options={"verify_signature": False})
exp_timestamp = payload.get('exp')
if exp_timestamp:
exp_time = datetime.fromtimestamp(exp_timestamp)
now = datetime.now()
if exp_time > now:
remaining = exp_time - now
days = remaining.days
hours = remaining.seconds // 3600
print(f"Token 过期时间: {exp_time.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"剩余有效期: {days}天 {hours}小时")
else:
print(f"{Fore.YELLOW}Token 已过期{Style.RESET_ALL}")
except:
pass
elif response.status_code == 401:
print(f"{Fore.RED}✗ Token 已失效 (401){Style.RESET_ALL}")
else:
print(f"{Fore.YELLOW}✗ 验证失败: HTTP {response.status_code}{Style.RESET_ALL}")
except requests.RequestException as e:
print(f"{Fore.RED}✗ 网络请求失败: {e}{Style.RESET_ALL}")
print("-" * 60)
print(f"\n{Fore.CYAN}查询完成!{Style.RESET_ALL}")
except Exception as e:
print(f"{Fore.RED}查询失败: {e}{Style.RESET_ALL}")
def refresh_token(self):
"""刷新 Token - 从 Cursor 客户端重新导入最新 Token"""
self.print_header("刷新 Token")
print(f"{Fore.CYAN}提示: Cursor 官方刷新 API 已失效{Style.RESET_ALL}")
print(f"{Fore.CYAN}将从 Cursor 客户端重新导入最新 Token{Style.RESET_ALL}\n")
try:
# 读取 Cursor 客户端的最新 Token
db_path = self.get_cursor_db_path()
if not db_path or not Path(db_path).exists():
print(f"{Fore.RED}未找到 Cursor 客户端数据库{Style.RESET_ALL}")
print(f"{Fore.YELLOW}请确保 Cursor 已安装且已登录{Style.RESET_ALL}")
return
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 获取 access_token 和 refresh_token
cursor.execute("SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken'")
access_token_row = cursor.fetchone()
cursor.execute("SELECT value FROM ItemTable WHERE key = 'cursorAuth/refreshToken'")
refresh_token_row = cursor.fetchone()
cursor.execute("SELECT value FROM ItemTable WHERE key = 'cursorAuth/cachedEmail'")
email_row = cursor.fetchone()
conn.close()
if not access_token_row or not refresh_token_row:
print(f"{Fore.RED}Cursor 客户端未登录或 Token 信息不完整{Style.RESET_ALL}")
print(f"{Fore.YELLOW}请先在 Cursor 中登录账号{Style.RESET_ALL}")
return
# 解析 Token
access_token = access_token_row[0].strip('"') if access_token_row[0] else None
refresh_token = refresh_token_row[0].strip('"') if refresh_token_row[0] else None
email = email_row[0].strip('"') if email_row and email_row[0] else "unknown"
if not access_token or not refresh_token:
print(f"{Fore.RED}Token 信息不完整{Style.RESET_ALL}")
return
# 保存更新后的 Token
token_data = {
'access_token': access_token,
'refresh_token': refresh_token,
'email': email,
'imported_at': datetime.now().isoformat(),
'source': 'cursor_client_refresh'
}
self.save_token_to_file(token_data)
print(f"{Fore.GREEN}刷新成功 - 已从 Cursor 客户端导入最新 Token{Style.RESET_ALL}\n")
self.show_token_info(token_data)
except Exception as e:
print(f"{Fore.RED}刷新失败: {e}{Style.RESET_ALL}")
def delete_token(self):
"""删除指定的 Token"""
self.print_header("删除 Token")
if not self.token_file.exists():
print(f"{Fore.YELLOW}未找到保存的 Token{Style.RESET_ALL}")
return
try:
with open(self.token_file, 'r', encoding='utf-8') as f:
data = json.load(f)
tokens = data.get('tokens', [])
if not tokens:
print(f"{Fore.YELLOW}没有保存的 Token{Style.RESET_ALL}")
return
# 显示所有 Token
print(f"共有 {len(tokens)} 个 Token\n")
for i, token_data in enumerate(tokens, 1):
email = token_data.get('email', 'N/A')
source = token_data.get('source', 'N/A')
imported_at = token_data.get('imported_at', 'N/A')
access_token = token_data.get('access_token')
status = "未知"
if access_token:
exp_time = self.get_token_expiry(access_token)
if exp_time:
remaining = exp_time - datetime.now()
if remaining.total_seconds() > 0:
status = f"{Fore.GREEN}有效{Style.RESET_ALL}"
else:
status = f"{Fore.RED}已过期{Style.RESET_ALL}"
print(f"[{i}] 邮箱: {email} | 来源: {source} | 状态: {status}")
print(f"\n[0] 返回主菜单")
# 选择要删除的 Token
choice = input(f"\n请输入要删除的 Token 编号 [0-{len(tokens)}]: ").strip()
if choice == '0':
return
try:
index = int(choice) - 1
if 0 <= index < len(tokens):
deleted_token = tokens[index]
email = deleted_token.get('email', 'N/A')
# 确认删除
confirm = input(f"\n确认删除邮箱 {email} 的 Token? (y/N): ").strip().lower()
if confirm == 'y':
tokens.pop(index)
data['tokens'] = tokens
data['last_updated'] = datetime.now().isoformat()
# 保存
with open(self.token_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"\n{Fore.GREEN}删除成功{Style.RESET_ALL}")
else:
print(f"\n{Fore.YELLOW}已取消删除{Style.RESET_ALL}")
else:
print(f"{Fore.RED}无效的编号{Style.RESET_ALL}")
except ValueError:
print(f"{Fore.RED}请输入有效的数字{Style.RESET_ALL}")
except Exception as e:
print(f"{Fore.RED}删除失败: {e}{Style.RESET_ALL}")
def view_saved_tokens(self):
"""查看保存的 Token"""
self.print_header("已保存的 Token")
if not self.token_file.exists():
print(f"{Fore.YELLOW}未找到保存的 Token{Style.RESET_ALL}")
return
try:
with open(self.token_file, 'r', encoding='utf-8') as f:
data = json.load(f)
tokens = data.get('tokens', [])
if not tokens:
print(f"{Fore.YELLOW}没有保存的 Token{Style.RESET_ALL}")
return
print(f"共找到 {len(tokens)} 个 Token\n")
for i, token_data in enumerate(tokens, 1):
print(f"{'─' * 60}")
print(f"Token #{i}")
print(f"邮箱: {token_data.get('email', 'N/A')}")
print(f"来源: {token_data.get('source', 'N/A')}")
print(f"导入时间: {token_data.get('imported_at', 'N/A')}")
access_token = token_data.get('access_token')
if access_token:
print(f"Access Token: {access_token[:50]}...")
exp_time = self.get_token_expiry(access_token)
if exp_time:
remaining = exp_time - datetime.now()
if remaining.total_seconds() > 0:
print(f"{Fore.GREEN}状态: 有效 (剩余 {self.format_timedelta(remaining)}){Style.RESET_ALL}")
else:
print(f"{Fore.RED}状态: 已过期{Style.RESET_ALL}")
print()
print(f"{'─' * 60}")
print(f"\nToken 保存位置: {self.token_file}")
# 添加删除选项
print(f"\n按 'd' 删除 Token,按其他键返回")
action = input("请选择: ").strip().lower()
if action == 'd':
self.delete_token()
except Exception as e:
print(f"{Fore.RED}读取失败: {e}{Style.RESET_ALL}")
def login_cursor(self):
"""使用保存的 Token 登录 Cursor"""
self.print_header("登录 Cursor")
if not self.token_file.exists():
print(f"{Fore.YELLOW}未找到保存的 Token{Style.RESET_ALL}")
return
try:
with open(self.token_file, 'r', encoding='utf-8') as f:
data = json.load(f)
tokens = data.get('tokens', [])
if not tokens:
print(f"{Fore.YELLOW}没有保存的 Token{Style.RESET_ALL}")
return
print(f"共有 {len(tokens)} 个 Token\n")
# 显示所有 Token 并验证状态
valid_tokens = []
for i, token_data in enumerate(tokens, 1):
email = token_data.get('email', 'N/A')
access_token = token_data.get('access_token')
if not access_token:
print(f"[{i}] 邮箱: {email} | 状态: {Fore.RED}无效 Token{Style.RESET_ALL}")
continue
# 验证 Token 状态
try:
headers = {
'Authorization': f'Bearer {access_token}',
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json'
}
response = requests.get(
'https://api2.cursor.sh/auth/full_stripe_profile',
headers=headers,
timeout=5
)
if response.status_code == 200:
profile = response.json()
membership_type = profile.get('membershipType', 'N/A')
subscription_status = profile.get('subscriptionStatus', 'N/A')
days_remaining = profile.get('daysRemainingOnTrial', 'N/A')
status = f"{Fore.GREEN}Token 有效{Style.RESET_ALL}"
print(f"[{i}] 邮箱: {email} | 状态: {status}")
print(f" 账户信息:")
print(f" 邮箱: {email}")
print(f" 订阅类型: {membership_type}")
print(f" 订阅状态: {subscription_status}")
if days_remaining != 'N/A':
print(f" 剩余试用天数: {days_remaining} 天")
valid_tokens.append((i, token_data))
else:
print(f"[{i}] 邮箱: {email} | 状态: {Fore.RED}Token 已失效{Style.RESET_ALL}")
except requests.RequestException:
print(f"[{i}] 邮箱: {email} | 状态: {Fore.YELLOW}网络错误{Style.RESET_ALL}")
print()
if not valid_tokens:
print(f"{Fore.RED}没有可用的有效 Token{Style.RESET_ALL}")
return
print(f"[0] 返回主菜单")
# 选择要登录的 Token
choice = input(f"\n请选择要登录的 Token 编号 [0-{len(tokens)}]: ").strip()
if choice == '0':
return
try:
index = int(choice) - 1
if 0 <= index < len(tokens):
selected_token = tokens[index]
email = selected_token.get('email', 'N/A')
access_token = selected_token.get('access_token')
refresh_token = selected_token.get('refresh_token')
if not access_token:
print(f"{Fore.RED}选择的 Token 无效{Style.RESET_ALL}")
return
# 先重置机器码
print(f"\n{Fore.CYAN}正在重置机器码...{Style.RESET_ALL}")
reset_success = self.reset_machine_ids()
if not reset_success:
print(f"{Fore.RED}机器码重置失败,登录中止{Style.RESET_ALL}")
return
# 更新 Cursor 数据库
print(f"\n{Fore.CYAN}正在更新认证信息...{Style.RESET_ALL}")
success = self.update_cursor_auth(
email=email,
access_token=access_token,
refresh_token=refresh_token
)
if success:
print(f"\n{Fore.GREEN}登录成功{Style.RESET_ALL}")
print(f"已使用邮箱 {email} 的 Token 登录 Cursor")
print(f"机器码已重置,获得新的设备标识")
print(f"{Fore.YELLOW}请重启 Cursor 客户端以应用更改{Style.RESET_ALL}")
else:
print(f"\n{Fore.RED}登录失败{Style.RESET_ALL}")
else:
print(f"{Fore.RED}无效的编号{Style.RESET_ALL}")
except ValueError:
print(f"{Fore.RED}请输入有效的数字{Style.RESET_ALL}")
except Exception as e:
print(f"{Fore.RED}登录失败: {e}{Style.RESET_ALL}")
def reset_machine_ids(self):
"""重置机器码标识"""
try:
print(f"{Fore.CYAN}正在重置机器码...{Style.RESET_ALL}")
# 生成新的机器码
new_ids = self.generate_new_machine_ids()
# 更新 SQLite 数据库
success = self.update_machine_ids_in_db(new_ids)
if success:
print(f"{Fore.GREEN}机器码重置成功{Style.RESET_ALL}")
return True
else:
print(f"{Fore.RED}机器码重置失败{Style.RESET_ALL}")
return False
except Exception as e:
print(f"{Fore.RED}重置机器码失败: {e}{Style.RESET_ALL}")
return False
def generate_new_machine_ids(self):
"""生成新的机器码标识"""
# 生成新的 UUID
dev_device_id = str(uuid.uuid4())
# 生成新的 machineId (64 字符十六进制)
machine_id = hashlib.sha256(os.urandom(32)).hexdigest()
# 生成新的 macMachineId (128 字符十六进制)
mac_machine_id = hashlib.sha512(os.urandom(64)).hexdigest()
# 生成新的 sqmId
sqm_id = "{" + str(uuid.uuid4()).upper() + "}"
return {
"telemetry.devDeviceId": dev_device_id,
"telemetry.macMachineId": mac_machine_id,
"telemetry.machineId": machine_id,
"telemetry.sqmId": sqm_id,
"storage.serviceMachineId": dev_device_id,
}
def update_machine_ids_in_db(self, new_ids):
"""更新数据库中的机器码"""
try:
conn = sqlite3.connect(str(self.storage_db))
cursor = conn.cursor()
# 确保表存在
cursor.execute("""
CREATE TABLE IF NOT EXISTS ItemTable (
key TEXT PRIMARY KEY,
value TEXT
)
""")
# 更新机器码
for key, value in new_ids.items():
cursor.execute("""
INSERT OR REPLACE INTO ItemTable (key, value)
VALUES (?, ?)
""", (key, value))
print(f" ✓ 更新 {key}")
conn.commit()
conn.close()
return True
except Exception as e:
print(f"{Fore.RED}更新机器码失败: {e}{Style.RESET_ALL}")
return False
def convert_web_cookie_to_session_token(self):
"""将网页版 Cookie Token 转换为客户端 Session Token"""
print(f"\n{Fore.YELLOW}请输入网页版 Cookie Token 信息{Style.RESET_ALL}\n")
print(f"{Fore.CYAN}提示: 从浏览器开发者工具 (F12) → Application → Cookies 中获取{Style.RESET_ALL}")
print()
# 输入 Cookie Token
cookie_token = input("Cookie Token (WorkosCursorSessionToken): ").strip()
if not cookie_token:
print(f"{Fore.RED}Cookie Token 不能为空{Style.RESET_ALL}")
return
print(f"\n{Fore.CYAN}正在转换 Cookie Token 为 Session Token...{Style.RESET_ALL}")
try:
# 调用 Cursor API 获取 Session Token
response = requests.post(
'https://api2.cursor.sh/auth/exchange',
json={'cookieToken': cookie_token},
headers={
'User-Agent': 'Mozilla/5.0',
'Content-Type': 'application/json',
'Origin': 'https://cursor.com'
},
timeout=10
)
if response.status_code == 200:
result = response.json()
access_token = result.get('accessToken')
refresh_token = result.get('refreshToken')
if access_token:
# 解析 Token 获取邮箱
payload = self.decode_jwt(access_token)
email = payload.get('email') if payload else 'unknown'
token_data = {
'access_token': access_token,
'refresh_token': refresh_token,
'email': email,
'imported_at': datetime.now().isoformat(),
'source': 'web_cookie_converted'
}
self.save_token_to_file(token_data)
print(f"\n{Fore.GREEN}转换成功!{Style.RESET_ALL}")
print(f"已将网页版 Cookie Token 转换为客户端 Session Token")
self.show_token_info(token_data)
else:
print(f"{Fore.RED}转换失败: 未获取到有效 Token{Style.RESET_ALL}")
elif response.status_code == 401:
print(f"{Fore.RED}Cookie Token 已失效或无效{Style.RESET_ALL}")
print(f"{Fore.YELLOW}请从浏览器获取最新的 Cookie Token{Style.RESET_ALL}")
elif response.status_code == 404:
# API 端点可能不存在,尝试直接使用 Cookie
print(f"{Fore.YELLOW}API 转换不可用,尝试直接验证 Cookie...{Style.RESET_ALL}")
self.try_validate_cookie_directly(cookie_token)
else:
print(f"{Fore.RED}转换失败: HTTP {response.status_code}{Style.RESET_ALL}")
print(f"响应: {response.text}")
except requests.RequestException as e:
print(f"{Fore.RED}网络请求失败: {e}{Style.RESET_ALL}")
except Exception as e:
print(f"{Fore.RED}转换失败: {e}{Style.RESET_ALL}")
def try_validate_cookie_directly(self, cookie_token):
"""尝试直接使用 Cookie 验证并获取信息"""
try:
# 使用 Cookie 调用 API
response = requests.get(
'https://api2.cursor.sh/auth/full_stripe_profile',
headers={
'Cookie': f'WorkosCursorSessionToken={cookie_token}',
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json'
},
timeout=10
)
if response.status_code == 200:
profile = response.json()
print(f"\n{Fore.YELLOW}注意: Cookie Token 为短期有效{Style.RESET_ALL}")
print(f"账户信息:")
print(f" 订阅类型: {profile.get('membershipType', 'N/A')}")
print(f" 订阅状态: {profile.get('subscriptionStatus', 'N/A')}")
print(f"\n{Fore.RED}无法转换为长期 Token{Style.RESET_ALL}")
print(f"{Fore.YELLOW}建议使用客户端导入功能获取长期 Token{Style.RESET_ALL}")
else:
print(f"{Fore.RED}Cookie 验证失败{Style.RESET_ALL}")
except Exception as e:
print(f"{Fore.RED}验证失败: {e}{Style.RESET_ALL}")
def update_cursor_auth(self, email, access_token, refresh_token):
"""更新 Cursor 数据库中的认证信息"""
try:
import sqlite3
# 连接数据库
conn = sqlite3.connect(str(self.storage_db))
cursor = conn.cursor()
# 更新认证信息
updates = [
("cursorAuth/cachedSignUpType", "Auth_0"),
("cursorAuth/cachedEmail", email),
("cursorAuth/accessToken", access_token),
("cursorAuth/refreshToken", refresh_token)
]
for key, value in updates:
# 检查是否存在
cursor.execute("SELECT COUNT(*) FROM ItemTable WHERE key = ?", (key,))
if cursor.fetchone()[0] == 0:
# 插入
cursor.execute("INSERT INTO ItemTable (key, value) VALUES (?, ?)", (key, value))
else:
# 更新
cursor.execute("UPDATE ItemTable SET value = ? WHERE key = ?", (value, key))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"{Fore.RED}更新数据库失败: {e}{Style.RESET_ALL}")
return False
def run(self):
"""运行主程序"""
while True:
self.print_menu()
choice = input("请选择操作 [0-6]: ").strip()
if choice == '1':
self.import_from_cursor()
elif choice == '2':
self.save_token_manually()
elif choice == '3':
self.check_token_status()
elif choice == '4':
self.refresh_token()
elif choice == '5':
self.view_saved_tokens()
elif choice == '6':
self.login_cursor()
elif choice == '0':
print(f"\n{Fore.GREEN}再见{Style.RESET_ALL}\n")
break
else:
print(f"\n{Fore.RED}无效选择,请重新输入{Style.RESET_ALL}")
input("\n按回车键继续...")
def main():
"""主函数"""
try:
manager = CursorTokenManager()
manager.run()
except KeyboardInterrupt:
print(f"\n\n{Fore.YELLOW}程序已中断{Style.RESET_ALL}\n")
except Exception as e:
print(f"\n{Fore.RED}程序错误: {e}{Style.RESET_ALL}\n")
if __name__ == "__main__":
main()