Guest User

Untitled

a guest
Apr 3rd, 2025
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.33 KB | None | 0 0
  1. import time
  2. import json
  3. import random
  4. import string
  5. import requests
  6. import threading
  7. import argparse
  8. import webbrowser
  9. import hashlib
  10. import base64
  11. import secrets
  12. from datetime import datetime
  13.  
  14. # 生成随机字符串的函数
  15. def generate_random_string(length=32):
  16. """生成指定长度的随机字符串,用于challenge和uuid参数"""
  17. chars = string.ascii_letters + string.digits + '-_'
  18. return ''.join(random.choice(chars) for _ in range(length))
  19.  
  20. # 生成UUID格式的函数
  21. def generate_uuid():
  22. """生成uuid格式的随机字符串"""
  23. parts = [
  24. generate_random_string(8),
  25. generate_random_string(4),
  26. generate_random_string(4),
  27. generate_random_string(4),
  28. generate_random_string(12)
  29. ]
  30. return '-'.join(parts)
  31.  
  32. # 生成challenge参数的函数
  33. def generate_challenge():
  34. """生成challenge参数"""
  35. return generate_random_string(24)
  36.  
  37. # 生成PKCE验证器和挑战码对
  38. def generate_pkce_pair():
  39. """生成PKCE验证器和挑战码对,用于OAuth 2.0 PKCE流程"""
  40. # 生成一个安全的随机码作为验证器
  41. code_verifier = secrets.token_urlsafe(43) # 43字符长度会产生一个足够长的verifier
  42.  
  43. # 计算挑战码 (code_challenge)
  44. code_challenge_digest = hashlib.sha256(code_verifier.encode('utf-8')).digest()
  45. code_challenge = base64.urlsafe_b64encode(code_challenge_digest).decode('utf-8').rstrip('=')
  46.  
  47. return code_verifier, code_challenge
  48.  
  49. # 轮询API获取cookie的函数
  50. def poll_for_cookie(uuid, verifier, stop_event):
  51. """持续轮询API获取cookie,直到获取成功或手动停止"""
  52. api_url = f"https://api2.cursor.sh/auth/poll?uuid={uuid}&verifier={verifier}"
  53. traceparent = f"00-{generate_random_string(32)}-{generate_random_string(16)}-00"
  54.  
  55. # OPTIONS预检请求的头部
  56. headers_options = {
  57. "Host": "api2.cursor.sh",
  58. "Connection": "keep-alive",
  59. "Accept": "*/*",
  60. "Access-Control-Request-Method": "GET",
  61. "Access-Control-Request-Headers": "traceparent,x-ghost-mode,x-new-onboarding-completed",
  62. "Origin": "vscode-file://vscode-app",
  63. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Cursor/0.48.6 Chrome/132.0.6834.210 Electron/34.3.4 Safari/537.36",
  64. "Sec-Fetch-Mode": "cors",
  65. "Sec-Fetch-Site": "cross-site",
  66. "Sec-Fetch-Dest": "empty",
  67. "Accept-Language": "zh-CN"
  68. }
  69.  
  70. # GET请求的头部
  71. headers_get = {
  72. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Cursor/0.48.6 Chrome/132.0.6834.210 Electron/34.3.4 Safari/537.36",
  73. "Accept": "*/*",
  74. "Origin": "vscode-file://vscode-app",
  75. "Sec-Fetch-Site": "cross-site",
  76. "Sec-Fetch-Mode": "cors",
  77. "Sec-Fetch-Dest": "empty",
  78. "traceparent": traceparent,
  79. "sec-ch-ua-platform": "Windows",
  80. "x-ghost-mode": "true",
  81. "x-new-onboarding-completed": "false",
  82. "sec-ch-ua": "\"Not A(Brand\";v=\"8\", \"Chromium\";v=\"132\"",
  83. "sec-ch-ua-mobile": "?0",
  84. "Accept-Language": "zh-CN",
  85. "Connection": "keep-alive"
  86. }
  87.  
  88. attempt = 0
  89. print("开始轮询API获取cookie...")
  90. print(f"请求接口:{api_url}")
  91.  
  92. while not stop_event.is_set():
  93. attempt += 1
  94. try:
  95. print(f"尝试 #{attempt}...")
  96.  
  97. # 先发送OPTIONS预检请求
  98. print(f"发送OPTIONS预检请求...")
  99. options_response = requests.options(api_url, headers=headers_options, timeout=5)
  100. print(f"OPTIONS预检响应状态码: {options_response.status_code}")
  101.  
  102. # 等待一小段时间再发送GET请求
  103. time.sleep(0.2)
  104.  
  105. # 发送GET请求获取cookie
  106. response = requests.get(api_url, headers=headers_get, timeout=5)
  107.  
  108. if response.status_code == 200:
  109. data = response.json()
  110. print(f"API响应: {data}")
  111.  
  112. if 'accessToken' in data:
  113. token = data['accessToken']
  114. print("\n============ 成功获取Cookie! ============")
  115. print(f"Token: {token}")
  116.  
  117. # 将token保存到文件
  118. current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
  119. with open(f"token_{current_time}.txt", "w") as f:
  120. f.write(token)
  121.  
  122. print(f"Token已保存到文件: token_{current_time}.txt")
  123. print("=======================================\n")
  124. return token
  125. else:
  126. print(f"尝试 #{attempt}: 请求失败,状态码: {response.status_code}")
  127. except requests.exceptions.Timeout:
  128. print(f"尝试 #{attempt}: 请求超时")
  129. except Exception as e:
  130. print(f"尝试 #{attempt}: 异常 - {e}")
  131.  
  132. time.sleep(1) # 每秒轮询一次
  133.  
  134. print("轮询已停止")
  135. return None
  136.  
  137. def main():
  138. parser = argparse.ArgumentParser(description='Cursor Cookie获取测试脚本')
  139. parser.add_argument('--no-browser', action='store_true', help='不自动打开浏览器')
  140. parser.add_argument('--uuid', type=str, help='使用指定的UUID,而不是生成随机UUID')
  141. parser.add_argument('--url', type=str, help='使用指定的完整确认页面URL,而不是生成新URL')
  142. args = parser.parse_args()
  143.  
  144. # 判断是否使用预设的URL
  145. if args.url:
  146. # 从URL中解析UUID和challenge
  147. import re
  148. url_match = re.search(r'uuid=([^&]+)', args.url)
  149. uuid = url_match.group(1) if url_match else generate_uuid()
  150. confirm_url = args.url
  151.  
  152. # 生成新的验证器
  153. verifier, _ = generate_pkce_pair()
  154. else:
  155. # 使用命令行参数或生成新的参数
  156. uuid = args.uuid if args.uuid else generate_uuid()
  157.  
  158. # 使用PKCE生成验证器和挑战码
  159. verifier, challenge = generate_pkce_pair()
  160.  
  161. # 生成确认页面URL
  162. confirm_url = f"https://www.cursor.com/cn/loginDeepControl?challenge={challenge}&uuid={uuid}&mode=login"
  163.  
  164. print("\n===== Cursor Cookie获取测试脚本 =====")
  165. print("此脚本会生成一个确认页面URL,并在后台不断轮询API尝试获取cookie")
  166. print("请按照以下步骤操作:")
  167. print("1. 打开确认页面URL")
  168. print("2. 如果需要登录,请先登录")
  169. print("3. 在确认页面点击 'Yes, Log In' 按钮")
  170. print("4. 脚本将自动检测并获取cookie")
  171. print("5. 按Ctrl+C可随时停止脚本")
  172. print("====================================\n")
  173.  
  174. print(f"确认页面URL: {confirm_url}")
  175. print(f"使用的UUID: {uuid}")
  176. print(f"使用的verifier: {verifier}")
  177.  
  178. # 如果不禁用浏览器,则自动打开URL
  179. if not args.no_browser:
  180. print("正在打开浏览器...")
  181. webbrowser.open(confirm_url)
  182.  
  183. # 创建停止事件
  184. stop_event = threading.Event()
  185.  
  186. try:
  187. # 在主线程中轮询
  188. poll_for_cookie(uuid, verifier, stop_event)
  189. except KeyboardInterrupt:
  190. print("\n用户中断,正在停止...")
  191. stop_event.set()
  192.  
  193. if __name__ == "__main__":
  194. main()
Add Comment
Please, Sign In to add comment