626 lines
25 KiB
Python
626 lines
25 KiB
Python
import os
|
||
import json
|
||
import requests
|
||
import logging
|
||
import subprocess
|
||
import uuid
|
||
import hashlib
|
||
import sys
|
||
import time
|
||
from typing import Optional, Dict, Tuple
|
||
from pathlib import Path
|
||
from utils.config import Config
|
||
from utils.cursor_registry import CursorRegistry
|
||
from cursor_auth_manager import CursorAuthManager
|
||
|
||
def get_hardware_id() -> str:
|
||
"""获取硬件唯一标识"""
|
||
try:
|
||
# 创建startupinfo对象来隐藏命令行窗口
|
||
startupinfo = None
|
||
if sys.platform == "win32":
|
||
startupinfo = subprocess.STARTUPINFO()
|
||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||
startupinfo.wShowWindow = subprocess.SW_HIDE
|
||
|
||
# 获取CPU信息
|
||
cpu_info = subprocess.check_output('wmic cpu get ProcessorId', startupinfo=startupinfo).decode()
|
||
cpu_id = cpu_info.split('\n')[1].strip()
|
||
|
||
# 获取主板序列号
|
||
board_info = subprocess.check_output('wmic baseboard get SerialNumber', startupinfo=startupinfo).decode()
|
||
board_id = board_info.split('\n')[1].strip()
|
||
|
||
# 获取BIOS序列号
|
||
bios_info = subprocess.check_output('wmic bios get SerialNumber', startupinfo=startupinfo).decode()
|
||
bios_id = bios_info.split('\n')[1].strip()
|
||
|
||
# 组合信息并生成哈希
|
||
combined = f"{cpu_id}:{board_id}:{bios_id}"
|
||
return hashlib.md5(combined.encode()).hexdigest()
|
||
except Exception as e:
|
||
logging.error(f"获取硬件ID失败: {str(e)}")
|
||
# 如果获取失败,使用UUID作为备选方案
|
||
return str(uuid.uuid4())
|
||
|
||
class AccountSwitcher:
|
||
def __init__(self):
|
||
self.cursor_path = Path(os.path.expanduser("~")) / "AppData" / "Local" / "Programs" / "Cursor"
|
||
self.app_path = self.cursor_path / "resources" / "app"
|
||
self.package_json = self.app_path / "package.json"
|
||
self.auth_manager = CursorAuthManager()
|
||
self.config = Config()
|
||
self.hardware_id = self.get_hardware_id() # 先获取硬件ID
|
||
self.registry = CursorRegistry() # 添加注册表操作工具类
|
||
|
||
logging.info(f"初始化硬件ID: {self.hardware_id}")
|
||
|
||
def get_hardware_id(self) -> str:
|
||
"""获取硬件唯一标识"""
|
||
try:
|
||
# 创建startupinfo对象来隐藏命令行窗口
|
||
startupinfo = None
|
||
if sys.platform == "win32":
|
||
startupinfo = subprocess.STARTUPINFO()
|
||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||
startupinfo.wShowWindow = subprocess.SW_HIDE
|
||
|
||
# 获取CPU信息
|
||
cpu_info = subprocess.check_output('wmic cpu get ProcessorId', startupinfo=startupinfo).decode()
|
||
cpu_id = cpu_info.split('\n')[1].strip()
|
||
|
||
# 获取主板序列号
|
||
board_info = subprocess.check_output('wmic baseboard get SerialNumber', startupinfo=startupinfo).decode()
|
||
board_id = board_info.split('\n')[1].strip()
|
||
|
||
# 获取BIOS序列号
|
||
bios_info = subprocess.check_output('wmic bios get SerialNumber', startupinfo=startupinfo).decode()
|
||
bios_id = bios_info.split('\n')[1].strip()
|
||
|
||
# 组合信息并生成哈希
|
||
combined = f"{cpu_id}:{board_id}:{bios_id}"
|
||
return hashlib.md5(combined.encode()).hexdigest()
|
||
except Exception as e:
|
||
logging.error(f"获取硬件ID失败: {str(e)}")
|
||
# 如果获取失败,使用UUID作为备选方案
|
||
return str(uuid.uuid4())
|
||
|
||
def get_cursor_version(self) -> str:
|
||
"""获取Cursor版本号"""
|
||
try:
|
||
if self.package_json.exists():
|
||
with open(self.package_json, "r", encoding="utf-8") as f:
|
||
data = json.load(f)
|
||
return data.get("version", "未知")
|
||
return "未知"
|
||
except Exception as e:
|
||
logging.error(f"获取Cursor版本失败: {str(e)}")
|
||
return "未知"
|
||
|
||
def get_device_info(self) -> dict:
|
||
"""获取设备信息"""
|
||
try:
|
||
import platform
|
||
import socket
|
||
import requests
|
||
import subprocess
|
||
|
||
# 获取操作系统信息
|
||
os_info = f"{platform.system()} {platform.release()}"
|
||
|
||
# 获取设备名称
|
||
try:
|
||
# 在Windows上使用wmic获取更详细的计算机名称
|
||
if platform.system() == "Windows":
|
||
startupinfo = subprocess.STARTUPINFO()
|
||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||
computer_info = subprocess.check_output('wmic computersystem get model', startupinfo=startupinfo).decode()
|
||
device_name = computer_info.split('\n')[1].strip()
|
||
else:
|
||
device_name = platform.node()
|
||
except:
|
||
device_name = platform.node()
|
||
|
||
# 获取IP地址
|
||
try:
|
||
ip_response = requests.get('https://api.ipify.org?format=json', timeout=5)
|
||
ip_address = ip_response.json()['ip']
|
||
except:
|
||
ip_address = "未知"
|
||
|
||
# 获取地理位置
|
||
try:
|
||
ip_info = requests.get(f'https://ipapi.co/{ip_address}/json/', timeout=5).json()
|
||
location = f"{ip_info.get('country_name', '')}-{ip_info.get('region', '')}-{ip_info.get('city', '')}"
|
||
except:
|
||
location = "未知"
|
||
|
||
return {
|
||
"os": os_info,
|
||
"device_name": device_name,
|
||
"ip": ip_address,
|
||
"location": location
|
||
}
|
||
except Exception as e:
|
||
logging.error(f"获取设备信息失败: {str(e)}")
|
||
return {
|
||
"os": "Windows",
|
||
"device_name": "未知设备",
|
||
"ip": "未知",
|
||
"location": "未知"
|
||
}
|
||
|
||
def check_activation_code(self, code: str) -> tuple:
|
||
"""检查激活码
|
||
|
||
Args:
|
||
code: 激活码
|
||
|
||
Returns:
|
||
tuple: (成功标志, 消息, 账号信息)
|
||
"""
|
||
try:
|
||
data = {
|
||
"machine_id": self.hardware_id,
|
||
"code": code
|
||
}
|
||
|
||
# 禁用SSL警告
|
||
import urllib3
|
||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||
|
||
# 设置请求参数
|
||
request_kwargs = {
|
||
"json": data,
|
||
"headers": {"Content-Type": "application/json"},
|
||
"timeout": 5, # 减少超时时间从10秒到5秒
|
||
"verify": False # 禁用SSL验证
|
||
}
|
||
|
||
# 尝试发送请求
|
||
try:
|
||
response = requests.post(
|
||
self.config.get_api_url("activate"),
|
||
**request_kwargs
|
||
)
|
||
except requests.exceptions.SSLError:
|
||
# 如果发生SSL错误,创建自定义SSL上下文
|
||
import ssl
|
||
ssl_context = ssl.create_default_context()
|
||
ssl_context.check_hostname = False
|
||
ssl_context.verify_mode = ssl.CERT_NONE
|
||
|
||
# 使用自定义SSL上下文重试请求
|
||
session = requests.Session()
|
||
session.verify = False
|
||
response = session.post(
|
||
self.config.get_api_url("activate"),
|
||
**request_kwargs
|
||
)
|
||
|
||
result = response.json()
|
||
# 激活成功
|
||
if result["code"] == 200:
|
||
api_data = result["data"]
|
||
# 构造标准的返回数据结构
|
||
account_info = {
|
||
"status": "active",
|
||
"expire_time": api_data.get("expire_time", ""),
|
||
"total_days": api_data.get("total_days", 0),
|
||
"days_left": api_data.get("days_left", 0),
|
||
"device_info": self.get_device_info()
|
||
}
|
||
return True, result["msg"], account_info
|
||
# 激活码无效或已被使用
|
||
elif result["code"] == 400:
|
||
logging.warning(f"激活码无效或已被使用: {result.get('msg', '未知错误')}")
|
||
return False, result.get("msg", "激活码无效或已被使用"), None
|
||
# 其他错误情况
|
||
else:
|
||
logging.error(f"激活失败: {result.get('msg', '未知错误')}")
|
||
return False, result["msg"], None # 返回 None 而不是空的账号信息
|
||
|
||
except Exception as e:
|
||
logging.error(f"激活失败: {str(e)}")
|
||
return False, f"激活失败: {str(e)}", None # 返回 None 而不是空的账号信息
|
||
|
||
def reset_machine_id(self) -> bool:
|
||
"""重置机器码"""
|
||
try:
|
||
# 1. 先关闭所有Cursor进程
|
||
if sys.platform == "win32":
|
||
os.system("taskkill /f /im Cursor.exe >nul 2>&1")
|
||
time.sleep(2)
|
||
|
||
# 2. 清理注册表(包括更新系统 MachineGuid)
|
||
if not self.registry.clean_registry():
|
||
logging.warning("注册表清理失败")
|
||
|
||
# 3. 清理文件(包括备份 storage.json)
|
||
if not self.registry.clean_cursor_files():
|
||
logging.warning("文件清理失败")
|
||
|
||
# 4. 修改 package.json 中的 machineId
|
||
if self.package_json.exists():
|
||
with open(self.package_json, "r", encoding="utf-8") as f:
|
||
data = json.load(f)
|
||
|
||
if "machineId" in data:
|
||
del data["machineId"]
|
||
|
||
with open(self.package_json, "w", encoding="utf-8") as f:
|
||
json.dump(data, f, indent=2)
|
||
|
||
# 5. 修改 storage.json 中的遥测 ID
|
||
storage_path = Path(os.getenv('APPDATA')) / "Cursor" / "User" / "globalStorage" / "storage.json"
|
||
if storage_path.exists():
|
||
with open(storage_path, "r", encoding="utf-8") as f:
|
||
storage_data = json.load(f)
|
||
|
||
# 只修改 machineId,保持其他遥测 ID 不变
|
||
if "telemetry.machineId" in storage_data:
|
||
# 生成新的 machineId(使用与 GitHub 脚本类似的格式)
|
||
new_machine_id = hashlib.sha256(str(uuid.uuid4()).encode()).hexdigest()
|
||
storage_data["telemetry.machineId"] = new_machine_id
|
||
|
||
with open(storage_path, "w", encoding="utf-8") as f:
|
||
json.dump(storage_data, f, indent=2)
|
||
|
||
# 6. 重启Cursor
|
||
cursor_exe = self.cursor_path / "Cursor.exe"
|
||
if cursor_exe.exists():
|
||
os.startfile(str(cursor_exe))
|
||
logging.info("Cursor重启成功")
|
||
|
||
logging.info("机器码重置完成")
|
||
return True
|
||
|
||
except Exception as e:
|
||
logging.error(f"重置机器码失败: {str(e)}")
|
||
return False
|
||
|
||
def bypass_version_limit(self) -> Tuple[bool, str]:
|
||
"""突破Cursor版本限制"""
|
||
try:
|
||
# 1. 先关闭所有Cursor进程
|
||
if sys.platform == "win32":
|
||
os.system("taskkill /f /im Cursor.exe >nul 2>&1")
|
||
time.sleep(2)
|
||
|
||
# 2. 重置机器码
|
||
if not self.reset_machine_id():
|
||
return False, "重置机器码失败"
|
||
|
||
# 3. 等待Cursor启动
|
||
time.sleep(3)
|
||
|
||
return True, "突破版本限制成功,Cursor已重启"
|
||
|
||
except Exception as e:
|
||
logging.error(f"突破版本限制失败: {str(e)}")
|
||
return False, f"突破失败: {str(e)}"
|
||
|
||
def activate_and_switch(self, activation_code: str) -> Tuple[bool, str]:
|
||
"""激活并切换账号
|
||
|
||
Returns:
|
||
Tuple[bool, str]: (是否成功, 提示消息)
|
||
"""
|
||
try:
|
||
# 验证激活码
|
||
success, message, account_info = self.check_activation_code(activation_code)
|
||
return success, message
|
||
|
||
except Exception as e:
|
||
logging.error(f"激活过程出错: {str(e)}")
|
||
return False, f"激活失败: {str(e)}"
|
||
|
||
def get_member_status(self) -> dict:
|
||
"""获取会员状态
|
||
|
||
Returns:
|
||
dict: 会员状态信息,包含:
|
||
- status: 状态(active/inactive/expired)
|
||
- expire_time: 到期时间
|
||
- total_days: 总天数
|
||
- days_left: 剩余天数
|
||
- device_info: 设备信息
|
||
"""
|
||
try:
|
||
data = {
|
||
"machine_id": self.hardware_id
|
||
}
|
||
|
||
api_url = self.config.get_api_url("status")
|
||
logging.info(f"正在检查会员状态...")
|
||
|
||
# 设置请求参数
|
||
request_kwargs = {
|
||
"json": data,
|
||
"headers": {"Content-Type": "application/json"},
|
||
"timeout": 2, # 减少超时时间到2秒
|
||
"verify": False
|
||
}
|
||
|
||
# 使用session来复用连接
|
||
session = requests.Session()
|
||
session.verify = False
|
||
|
||
# 尝试发送请求
|
||
try:
|
||
response = session.post(api_url, **request_kwargs)
|
||
except requests.exceptions.Timeout:
|
||
# 超时后快速重试一次
|
||
logging.warning("首次请求超时,正在重试...")
|
||
response = session.post(api_url, **request_kwargs)
|
||
|
||
result = response.json()
|
||
logging.info(f"状态检查响应: {result}")
|
||
|
||
if result.get("code") in [1, 200]:
|
||
api_data = result.get("data", {})
|
||
return {
|
||
"status": api_data.get("status", "inactive"),
|
||
"expire_time": api_data.get("expire_time", ""),
|
||
"total_days": api_data.get("total_days", 0),
|
||
"days_left": api_data.get("days_left", 0),
|
||
"device_info": self.get_device_info()
|
||
}
|
||
else:
|
||
error_msg = result.get("msg", "未知错误")
|
||
logging.error(f"获取状态失败: {error_msg}")
|
||
return {
|
||
"status": "inactive",
|
||
"expire_time": "",
|
||
"total_days": 0,
|
||
"days_left": 0,
|
||
"device_info": self.get_device_info()
|
||
}
|
||
|
||
except requests.exceptions.RequestException as e:
|
||
logging.error(f"API请求失败: {str(e)}")
|
||
return {
|
||
"status": "inactive",
|
||
"expire_time": "",
|
||
"total_days": 0,
|
||
"days_left": 0,
|
||
"device_info": self.get_device_info()
|
||
}
|
||
except Exception as e:
|
||
logging.error(f"获取会员状态失败: {str(e)}")
|
||
return {
|
||
"status": "inactive",
|
||
"expire_time": "",
|
||
"total_days": 0,
|
||
"days_left": 0,
|
||
"device_info": self.get_device_info()
|
||
}
|
||
|
||
def restart_cursor(self) -> bool:
|
||
"""重启Cursor编辑器
|
||
|
||
Returns:
|
||
bool: 是否成功重启
|
||
"""
|
||
try:
|
||
logging.info("正在重启Cursor...")
|
||
if sys.platform == "win32":
|
||
# Windows系统
|
||
# 关闭Cursor
|
||
os.system("taskkill /f /im Cursor.exe 2>nul")
|
||
time.sleep(2)
|
||
# 获取Cursor安装路径
|
||
cursor_exe = self.cursor_path / "Cursor.exe"
|
||
if cursor_exe.exists():
|
||
# 启动Cursor
|
||
os.startfile(str(cursor_exe))
|
||
logging.info("Cursor重启成功")
|
||
return True
|
||
else:
|
||
logging.error(f"未找到Cursor程序: {cursor_exe}")
|
||
return False
|
||
elif sys.platform == "darwin":
|
||
# macOS系统
|
||
os.system("killall Cursor 2>/dev/null")
|
||
time.sleep(2)
|
||
os.system("open -a Cursor")
|
||
logging.info("Cursor重启成功")
|
||
return True
|
||
elif sys.platform == "linux":
|
||
# Linux系统
|
||
os.system("pkill -f cursor")
|
||
time.sleep(2)
|
||
os.system("cursor &")
|
||
logging.info("Cursor重启成功")
|
||
return True
|
||
else:
|
||
logging.error(f"不支持的操作系统: {sys.platform}")
|
||
return False
|
||
except Exception as e:
|
||
logging.error(f"重启Cursor时发生错误: {str(e)}")
|
||
return False
|
||
|
||
def refresh_cursor_auth(self) -> Tuple[bool, str]:
|
||
"""刷新Cursor授权
|
||
|
||
Returns:
|
||
Tuple[bool, str]: (是否成功, 提示消息)
|
||
"""
|
||
try:
|
||
# 1. 先关闭所有Cursor进程
|
||
if sys.platform == "win32":
|
||
os.system("taskkill /f /im Cursor.exe >nul 2>&1")
|
||
time.sleep(2)
|
||
|
||
# 2. 获取未使用的账号
|
||
endpoint = "https://cursorapi.nosqli.com/admin/api.account/getUnused"
|
||
data = {
|
||
"machine_id": self.hardware_id
|
||
}
|
||
headers = {
|
||
"Content-Type": "application/json"
|
||
}
|
||
|
||
# 禁用SSL警告
|
||
import urllib3
|
||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||
|
||
# 设置请求参数
|
||
request_kwargs = {
|
||
"json": data,
|
||
"headers": headers,
|
||
"timeout": 30, # 增加超时时间
|
||
"verify": False # 禁用SSL验证
|
||
}
|
||
|
||
try:
|
||
# 尝试发送请求
|
||
try:
|
||
response = requests.post(endpoint, **request_kwargs)
|
||
except requests.exceptions.SSLError:
|
||
# 如果发生SSL错误,创建自定义SSL上下文
|
||
import ssl
|
||
ssl_context = ssl.create_default_context()
|
||
ssl_context.check_hostname = False
|
||
ssl_context.verify_mode = ssl.CERT_NONE
|
||
|
||
# 使用自定义SSL上下文重试请求
|
||
session = requests.Session()
|
||
session.verify = False
|
||
response = session.post(endpoint, **request_kwargs)
|
||
|
||
response_data = response.json()
|
||
|
||
if response_data.get("code") == 200:
|
||
account_data = response_data.get("data", {})
|
||
|
||
# 获取账号信息
|
||
email = account_data.get("email", "")
|
||
access_token = account_data.get("access_token", "")
|
||
refresh_token = account_data.get("refresh_token", "")
|
||
expire_time = account_data.get("expire_time", "")
|
||
days_left = account_data.get("days_left", 0)
|
||
|
||
if not all([email, access_token, refresh_token]):
|
||
return False, "获取账号信息不完整"
|
||
|
||
# 3. 更新Cursor认证信息
|
||
if not self.auth_manager.update_auth(email, access_token, refresh_token):
|
||
return False, "更新Cursor认证信息失败"
|
||
|
||
# 4. 重置机器码(包含了清理注册表、文件和重启操作)
|
||
if not self.reset_machine_id():
|
||
return False, "重置机器码失败"
|
||
|
||
return True, f"授权刷新成功,Cursor编辑器已重启\n邮箱: {email}\n"
|
||
|
||
elif response_data.get("code") == 404:
|
||
return False, "没有可用的未使用账号"
|
||
else:
|
||
error_msg = response_data.get("msg", "未知错误")
|
||
logging.error(f"获取未使用账号失败: {error_msg}")
|
||
return False, f"获取账号失败: {error_msg}"
|
||
|
||
except requests.exceptions.SSLError as e:
|
||
logging.error(f"SSL验证失败: {str(e)}")
|
||
return False, "SSL验证失败,请检查网络设置"
|
||
except requests.exceptions.ConnectionError as e:
|
||
logging.error(f"网络连接错误: {str(e)}")
|
||
return False, "网络连接失败,请检查网络设置"
|
||
except requests.exceptions.Timeout as e:
|
||
logging.error(f"请求超时: {str(e)}")
|
||
return False, "请求超时,请稍后重试"
|
||
except requests.RequestException as e:
|
||
logging.error(f"请求失败: {str(e)}")
|
||
return False, f"网络请求失败: {str(e)}"
|
||
except Exception as e:
|
||
logging.error(f"未知错误: {str(e)}")
|
||
return False, f"发生未知错误: {str(e)}"
|
||
|
||
except Exception as e:
|
||
logging.error(f"刷新授权过程出错: {str(e)}")
|
||
return False, f"刷新失败: {str(e)}"
|
||
|
||
def disable_cursor_update(self) -> Tuple[bool, str]:
|
||
"""禁用Cursor更新"""
|
||
try:
|
||
# 1. 先关闭所有Cursor进程
|
||
if sys.platform == "win32":
|
||
os.system("taskkill /f /im Cursor.exe >nul 2>&1")
|
||
time.sleep(2)
|
||
|
||
# 2. 删除updater目录并创建同名文件以阻止更新
|
||
updater_path = Path(os.getenv('LOCALAPPDATA')) / "cursor-updater"
|
||
|
||
try:
|
||
# 如果是目录,则删除
|
||
if updater_path.is_dir():
|
||
import shutil
|
||
shutil.rmtree(str(updater_path))
|
||
logging.info("删除updater目录成功")
|
||
|
||
# 如果是文件,则删除
|
||
if updater_path.is_file():
|
||
os.remove(str(updater_path))
|
||
logging.info("删除updater文件成功")
|
||
|
||
# 创建同名空文件
|
||
updater_path.touch()
|
||
logging.info("创建updater空文件成功")
|
||
|
||
# 3. 重启Cursor
|
||
cursor_exe = self.cursor_path / "Cursor.exe"
|
||
if cursor_exe.exists():
|
||
os.startfile(str(cursor_exe))
|
||
logging.info("Cursor重启成功")
|
||
|
||
return True, "Cursor更新已禁用,程序已重启"
|
||
|
||
except Exception as e:
|
||
logging.error(f"操作updater文件失败: {str(e)}")
|
||
return False, f"禁用更新失败: {str(e)}"
|
||
|
||
except Exception as e:
|
||
logging.error(f"禁用Cursor更新失败: {str(e)}")
|
||
return False, f"禁用更新失败: {str(e)}"
|
||
|
||
def main():
|
||
"""主函数"""
|
||
try:
|
||
switcher = AccountSwitcher()
|
||
|
||
print("\n=== Cursor账号切换工具 ===")
|
||
print("1. 激活并切换账号")
|
||
print("2. 仅重置机器码")
|
||
|
||
while True:
|
||
try:
|
||
choice = int(input("\n请选择操作 (1 或 2): ").strip())
|
||
if choice in [1, 2]:
|
||
break
|
||
else:
|
||
print("无效的选项,请重新输入")
|
||
except ValueError:
|
||
print("请输入有效的数字")
|
||
|
||
if choice == 1:
|
||
activation_code = input("请输入激活码: ").strip()
|
||
if switcher.activate_and_switch(activation_code):
|
||
print("\n账号激活成功!")
|
||
else:
|
||
print("\n账号激活失败,请查看日志了解详细信息")
|
||
else:
|
||
if switcher.reset_machine_id():
|
||
print("\n机器码重置成功!")
|
||
else:
|
||
print("\n机器码重置失败,请查看日志了解详细信息")
|
||
|
||
except Exception as e:
|
||
logging.error(f"程序执行出错: {str(e)}")
|
||
print("\n程序执行出错,请查看日志了解详细信息")
|
||
|
||
finally:
|
||
input("\n按回车键退出...")
|
||
|
||
if __name__ == "__main__":
|
||
main() |