dpmcl 26.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dpmcl/__init__.py +64 -0
- dpmcl/__main__.py +6 -0
- dpmcl/_internal/__init__.py +24 -0
- dpmcl/_internal/accounts.py +601 -0
- dpmcl/_internal/assets.py +286 -0
- dpmcl/_internal/config.py +586 -0
- dpmcl/_internal/install.py +1116 -0
- dpmcl/_internal/java.py +673 -0
- dpmcl/_internal/launch.py +745 -0
- dpmcl/_internal/libraries.py +309 -0
- dpmcl/_internal/mods.py +312 -0
- dpmcl/_internal/net.py +407 -0
- dpmcl/_internal/options.py +137 -0
- dpmcl/_internal/progress.py +202 -0
- dpmcl/_internal/rules.py +131 -0
- dpmcl/_internal/util.py +352 -0
- dpmcl/_internal/version.py +331 -0
- dpmcl/accounts.py +25 -0
- dpmcl/api.py +613 -0
- dpmcl/cli.py +2198 -0
- dpmcl/config.py +74 -0
- dpmcl/constants.py +23 -0
- dpmcl/engine.py +27 -0
- dpmcl/errors.py +33 -0
- dpmcl/i18n.py +178 -0
- dpmcl-26.1.dist-info/METADATA +307 -0
- dpmcl-26.1.dist-info/RECORD +31 -0
- dpmcl-26.1.dist-info/WHEEL +5 -0
- dpmcl-26.1.dist-info/entry_points.txt +2 -0
- dpmcl-26.1.dist-info/licenses/LICENSE +21 -0
- dpmcl-26.1.dist-info/top_level.txt +1 -0
dpmcl/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""DPMCL 公共库。
|
|
2
|
+
|
|
3
|
+
安装、启动、Java、模组等逻辑都可以直接调用这里的 API;进度通过
|
|
4
|
+
``progress`` 回调接收结构化的 :class:`ProgressEvent`,事件字段为常量,
|
|
5
|
+
不包含本地化文案。CLI 文案映射在 :mod:`dpmcl.i18n`。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "26.1"
|
|
9
|
+
|
|
10
|
+
from .api import (
|
|
11
|
+
DoctorSummary,
|
|
12
|
+
GameProfile,
|
|
13
|
+
InstallIssue,
|
|
14
|
+
InstallResult,
|
|
15
|
+
JavaInfo,
|
|
16
|
+
Launcher,
|
|
17
|
+
LaunchHandle,
|
|
18
|
+
ModInfo,
|
|
19
|
+
PartitionInfo,
|
|
20
|
+
install,
|
|
21
|
+
launch,
|
|
22
|
+
list_partitions,
|
|
23
|
+
offline_profile,
|
|
24
|
+
)
|
|
25
|
+
from .config import Config, MinecraftSet, default_config_path, load_config
|
|
26
|
+
from .constants import (
|
|
27
|
+
Code,
|
|
28
|
+
Operation,
|
|
29
|
+
ProgressCallback,
|
|
30
|
+
ProgressEvent,
|
|
31
|
+
ProgressReporter,
|
|
32
|
+
Stage,
|
|
33
|
+
Status,
|
|
34
|
+
)
|
|
35
|
+
from .errors import DpmclError
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"__version__",
|
|
39
|
+
"Code",
|
|
40
|
+
"Operation",
|
|
41
|
+
"ProgressCallback",
|
|
42
|
+
"ProgressEvent",
|
|
43
|
+
"ProgressReporter",
|
|
44
|
+
"Stage",
|
|
45
|
+
"Status",
|
|
46
|
+
"DpmclError",
|
|
47
|
+
"Config",
|
|
48
|
+
"MinecraftSet",
|
|
49
|
+
"default_config_path",
|
|
50
|
+
"load_config",
|
|
51
|
+
"Launcher",
|
|
52
|
+
"PartitionInfo",
|
|
53
|
+
"InstallIssue",
|
|
54
|
+
"InstallResult",
|
|
55
|
+
"LaunchHandle",
|
|
56
|
+
"DoctorSummary",
|
|
57
|
+
"JavaInfo",
|
|
58
|
+
"ModInfo",
|
|
59
|
+
"GameProfile",
|
|
60
|
+
"offline_profile",
|
|
61
|
+
"install",
|
|
62
|
+
"launch",
|
|
63
|
+
"list_partitions",
|
|
64
|
+
]
|
dpmcl/__main__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""DPMCL 核心包。
|
|
2
|
+
|
|
3
|
+
模块划分:
|
|
4
|
+
config 配置与路径
|
|
5
|
+
util 通用工具
|
|
6
|
+
rules 版本 JSON 规则判定
|
|
7
|
+
libraries Maven 坐标、natives、classpath
|
|
8
|
+
version 版本 JSON 继承合并
|
|
9
|
+
java Java 探测与选择
|
|
10
|
+
net 下载(重试/镜像/校验)
|
|
11
|
+
assets 资源文件
|
|
12
|
+
install 原版与各加载器安装
|
|
13
|
+
launch 启动参数拼装与进程启动
|
|
14
|
+
accounts 账号与登录
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import warnings
|
|
18
|
+
|
|
19
|
+
# requests 与其依赖版本不匹配时会往 stderr 打警告,命令行里没有意义
|
|
20
|
+
warnings.filterwarnings("ignore", message=".*doesn't match a supported version.*")
|
|
21
|
+
warnings.filterwarnings("ignore", module="requests")
|
|
22
|
+
|
|
23
|
+
__version__ = "1.0.0"
|
|
24
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
"""账号管理:离线账号、微软正版登录、LittleSkin(Yggdrasil)登录与刷新。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
import uuid as uuidlib
|
|
9
|
+
import webbrowser
|
|
10
|
+
from hashlib import md5, sha256
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from . import net
|
|
15
|
+
from .config import accounts_path, config
|
|
16
|
+
from .util import atomic_write_bytes, atomic_write_text, read_json, write_json
|
|
17
|
+
|
|
18
|
+
LITTLESKIN_SERVER = "https://littleskin.cn/api/yggdrasil"
|
|
19
|
+
CLIENT_ID = "55e6afef-05d2-4a13-ab74-6a526a17016c"
|
|
20
|
+
DEVICE_CODE_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode"
|
|
21
|
+
TOKEN_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"
|
|
22
|
+
AUTHLIB_INJECTOR_LATEST = "https://authlib-injector.yushi.moe/artifact/latest.json"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def authlib_injector_jar() -> Path:
|
|
26
|
+
"""与配置文件放在一起,避免安装包目录不可写。"""
|
|
27
|
+
return config.path.parent / "authlib-injector.jar"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class AccountError(RuntimeError):
|
|
31
|
+
"""账号相关错误(登录失败、令牌过期等)。"""
|
|
32
|
+
|
|
33
|
+
code = "account_error"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------- 存储
|
|
37
|
+
|
|
38
|
+
def load_accounts() -> dict[str, dict]:
|
|
39
|
+
path = accounts_path()
|
|
40
|
+
if not path.exists():
|
|
41
|
+
return {}
|
|
42
|
+
try:
|
|
43
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
44
|
+
except (OSError, ValueError) as exc:
|
|
45
|
+
raise AccountError(f"accounts.json 无法读取({exc}),请检查或备份后删除该文件") from exc
|
|
46
|
+
if not isinstance(data, dict):
|
|
47
|
+
return {}
|
|
48
|
+
return {str(k): v for k, v in data.items() if isinstance(v, dict)}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def save_accounts(accounts: dict) -> None:
|
|
52
|
+
path = accounts_path()
|
|
53
|
+
# 备份上一次的内容,避免写坏
|
|
54
|
+
if path.exists():
|
|
55
|
+
try:
|
|
56
|
+
backup = path.with_suffix(".json.bak")
|
|
57
|
+
backup.write_bytes(path.read_bytes())
|
|
58
|
+
except OSError:
|
|
59
|
+
pass
|
|
60
|
+
write_json(path, accounts)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def add_account_save(account: dict) -> None:
|
|
64
|
+
accounts = load_accounts()
|
|
65
|
+
accounts[account["uuid"]] = account
|
|
66
|
+
save_accounts(accounts)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def update_account_save(uuid: str, account: dict) -> None:
|
|
70
|
+
"""按 uuid 更新账号;如果账号 uuid 变了,会迁移键名。
|
|
71
|
+
|
|
72
|
+
新数据里没带 alias 时保留旧别号,避免刷新令牌后序列号丢失。
|
|
73
|
+
"""
|
|
74
|
+
accounts = load_accounts()
|
|
75
|
+
previous = accounts.get(uuid) or accounts.get(str(account.get("uuid") or ""))
|
|
76
|
+
if previous and previous.get("alias") and not account.get("alias"):
|
|
77
|
+
account = dict(account)
|
|
78
|
+
account["alias"] = previous["alias"]
|
|
79
|
+
if uuid in accounts:
|
|
80
|
+
del accounts[uuid]
|
|
81
|
+
accounts[account["uuid"]] = account
|
|
82
|
+
save_accounts(accounts)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def remove_account(uuid: str) -> bool:
|
|
86
|
+
accounts = load_accounts()
|
|
87
|
+
if uuid in accounts:
|
|
88
|
+
del accounts[uuid]
|
|
89
|
+
save_accounts(accounts)
|
|
90
|
+
return True
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def get_account(uuid: str) -> dict | None:
|
|
95
|
+
return load_accounts().get(uuid)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def find_account(name: str) -> tuple[str, dict] | None:
|
|
99
|
+
"""按用户名 / 单字母别名 / uuid 查找账号。"""
|
|
100
|
+
name = str(name or "").strip()
|
|
101
|
+
if not name:
|
|
102
|
+
return None
|
|
103
|
+
accounts = load_accounts()
|
|
104
|
+
lowered = name.lower()
|
|
105
|
+
for uuid, info in accounts.items():
|
|
106
|
+
if str(info.get("username", "")).lower() == lowered:
|
|
107
|
+
return uuid, info
|
|
108
|
+
for uuid, info in accounts.items():
|
|
109
|
+
if str(info.get("alias", "")).lower() == lowered:
|
|
110
|
+
return uuid, info
|
|
111
|
+
if name in accounts:
|
|
112
|
+
return name, accounts[name]
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def alias_owner(alias: str, exclude_uuid: str | None = None) -> str | None:
|
|
117
|
+
alias = alias.lower()
|
|
118
|
+
for uuid, info in load_accounts().items():
|
|
119
|
+
if uuid != exclude_uuid and str(info.get("alias", "")).lower() == alias:
|
|
120
|
+
return str(info.get("username"))
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def set_alias(uuid: str, alias: str | None) -> None:
|
|
125
|
+
accounts = load_accounts()
|
|
126
|
+
if uuid not in accounts:
|
|
127
|
+
raise AccountError("账号不存在")
|
|
128
|
+
if alias:
|
|
129
|
+
owner = alias_owner(alias, exclude_uuid=uuid)
|
|
130
|
+
if owner:
|
|
131
|
+
raise AccountError(f"序列号 {alias} 已被用户 {owner} 使用")
|
|
132
|
+
accounts[uuid]["alias"] = alias.lower()
|
|
133
|
+
else:
|
|
134
|
+
accounts[uuid].pop("alias", None)
|
|
135
|
+
save_accounts(accounts)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def check_username_conflict(new_account: dict, excluding_uuid: str | None = None) -> None:
|
|
139
|
+
for uuid, info in load_accounts().items():
|
|
140
|
+
if uuid == excluding_uuid:
|
|
141
|
+
continue
|
|
142
|
+
if str(info.get("username", "")).lower() == str(new_account["username"]).lower():
|
|
143
|
+
raise AccountError(
|
|
144
|
+
f"用户名 {new_account['username']} 已被账号 {info['username']}({uuid})占用"
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---------------------------------------------------------------- 离线账号
|
|
149
|
+
|
|
150
|
+
def offline_uuid(username: str) -> str:
|
|
151
|
+
"""与官方离线模式一致的 UUID(md5("OfflinePlayer:"+name),版本 3)。"""
|
|
152
|
+
digest = bytearray(md5(("OfflinePlayer:" + username).encode("utf-8")).digest())
|
|
153
|
+
digest[6] = (digest[6] & 0x0F) | 0x30
|
|
154
|
+
digest[8] = (digest[8] & 0x3F) | 0x80
|
|
155
|
+
return str(uuidlib.UUID(bytes=bytes(digest)))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def create_offline_account(username: str) -> dict:
|
|
159
|
+
username = str(username).strip()
|
|
160
|
+
if not username:
|
|
161
|
+
raise AccountError("离线用户名不能为空")
|
|
162
|
+
return {
|
|
163
|
+
"type": "offline",
|
|
164
|
+
"uuid": offline_uuid(username),
|
|
165
|
+
"username": username,
|
|
166
|
+
"minecraft_access_token": "0" * 32,
|
|
167
|
+
"ms_access_token": None,
|
|
168
|
+
"ms_refresh_token": None,
|
|
169
|
+
"expires_at": 9999999999,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# ---------------------------------------------------------------- JWT 辅助
|
|
174
|
+
|
|
175
|
+
def _jwt_exp(token: str) -> int | None:
|
|
176
|
+
try:
|
|
177
|
+
payload = token.split(".")[1]
|
|
178
|
+
payload += "=" * (-len(payload) % 4)
|
|
179
|
+
data = json.loads(base64.urlsafe_b64decode(payload))
|
|
180
|
+
exp = data.get("exp")
|
|
181
|
+
return int(exp) if exp else None
|
|
182
|
+
except (IndexError, ValueError, TypeError):
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# ---------------------------------------------------------------- 微软登录
|
|
187
|
+
|
|
188
|
+
def _post_json(
|
|
189
|
+
url: str,
|
|
190
|
+
payload: dict,
|
|
191
|
+
bearer: str | None = None,
|
|
192
|
+
timeout: float = 30,
|
|
193
|
+
form: bool = False,
|
|
194
|
+
) -> dict:
|
|
195
|
+
"""POST 并解析 JSON 响应。
|
|
196
|
+
|
|
197
|
+
微软的 OAuth 端点(devicecode / token)只接受
|
|
198
|
+
``application/x-www-form-urlencoded``,用 JSON body 会报
|
|
199
|
+
AADSTS900144(缺少 grant_type);Xbox / Minecraft API 则用 JSON。
|
|
200
|
+
"""
|
|
201
|
+
session = net._session()
|
|
202
|
+
headers = {"Accept": "application/json"}
|
|
203
|
+
if bearer:
|
|
204
|
+
headers["Authorization"] = f"Bearer {bearer}"
|
|
205
|
+
if form:
|
|
206
|
+
response = session.post(url, data=payload, headers=headers, timeout=timeout)
|
|
207
|
+
else:
|
|
208
|
+
response = session.post(url, json=payload, headers=headers, timeout=timeout)
|
|
209
|
+
try:
|
|
210
|
+
data = response.json()
|
|
211
|
+
except ValueError:
|
|
212
|
+
data = {}
|
|
213
|
+
if response.status_code >= 400:
|
|
214
|
+
error = data.get("error") or f"HTTP {response.status_code}"
|
|
215
|
+
message = data.get("error_description") or data.get("message") or response.text[:200]
|
|
216
|
+
raise AccountError(f"{error}: {message}")
|
|
217
|
+
return data
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def device_login() -> tuple[str, str, int]:
|
|
221
|
+
"""微软设备码登录,返回 (access_token, refresh_token, expires_in)。"""
|
|
222
|
+
data = _post_json(
|
|
223
|
+
DEVICE_CODE_URL,
|
|
224
|
+
{"client_id": CLIENT_ID, "scope": "XboxLive.signin offline_access"},
|
|
225
|
+
form=True,
|
|
226
|
+
)
|
|
227
|
+
user_code = data.get("user_code")
|
|
228
|
+
device_code = data.get("device_code")
|
|
229
|
+
verification_uri = data.get("verification_uri") or "https://microsoft.com/link"
|
|
230
|
+
interval = int(data.get("interval") or 5)
|
|
231
|
+
expires_in = int(data.get("expires_in") or 900)
|
|
232
|
+
|
|
233
|
+
print(f" 请在浏览器中打开:{verification_uri}")
|
|
234
|
+
print(f" 并输入代码:{user_code}")
|
|
235
|
+
try:
|
|
236
|
+
import pyperclip
|
|
237
|
+
|
|
238
|
+
pyperclip.copy(user_code)
|
|
239
|
+
print(" (代码已复制到剪贴板)")
|
|
240
|
+
except Exception: # noqa: BLE001 - 剪贴板不可用不影响登录
|
|
241
|
+
pass
|
|
242
|
+
try:
|
|
243
|
+
webbrowser.open(verification_uri)
|
|
244
|
+
except Exception: # noqa: BLE001
|
|
245
|
+
pass
|
|
246
|
+
print(" 等待授权 …")
|
|
247
|
+
|
|
248
|
+
deadline = time.time() + expires_in
|
|
249
|
+
while time.time() < deadline:
|
|
250
|
+
time.sleep(interval)
|
|
251
|
+
try:
|
|
252
|
+
token = _post_json(
|
|
253
|
+
TOKEN_URL,
|
|
254
|
+
{
|
|
255
|
+
"client_id": CLIENT_ID,
|
|
256
|
+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
|
257
|
+
"device_code": device_code,
|
|
258
|
+
},
|
|
259
|
+
form=True,
|
|
260
|
+
)
|
|
261
|
+
except AccountError as exc:
|
|
262
|
+
text = str(exc)
|
|
263
|
+
if "authorization_pending" in text:
|
|
264
|
+
continue
|
|
265
|
+
if "slow_down" in text:
|
|
266
|
+
interval += 2
|
|
267
|
+
continue
|
|
268
|
+
if "expired_token" in text:
|
|
269
|
+
raise AccountError("设备码已过期,请重新登录") from exc
|
|
270
|
+
if "authorization_declined" in text:
|
|
271
|
+
raise AccountError("授权被拒绝") from exc
|
|
272
|
+
raise
|
|
273
|
+
return token["access_token"], token["refresh_token"], int(token.get("expires_in") or 3600)
|
|
274
|
+
raise AccountError("登录等待超时,请重试")
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
_XSTS_ERRORS = {
|
|
278
|
+
"2148916233": "该微软账号没有 Xbox 账户,请先到 xbox.com 创建",
|
|
279
|
+
"2148916235": "该账号所在地区不支持 Xbox Live",
|
|
280
|
+
"2148916238": "该账号是未成年人账号,需要加入家庭组",
|
|
281
|
+
"2148916236": "该账号需要完成年龄验证",
|
|
282
|
+
"2148916237": "该账号需要完成年龄验证",
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def minecraft_token(ms_access_token: str) -> tuple[str, str, str]:
|
|
287
|
+
"""微软令牌 -> (minecraft access_token, uuid, username)。"""
|
|
288
|
+
xbl = _post_json(
|
|
289
|
+
"https://user.auth.xboxlive.com/user/authenticate",
|
|
290
|
+
{
|
|
291
|
+
"Properties": {
|
|
292
|
+
"AuthMethod": "RPS",
|
|
293
|
+
"SiteName": "user.auth.xboxlive.com",
|
|
294
|
+
"RpsTicket": f"d={ms_access_token}",
|
|
295
|
+
},
|
|
296
|
+
"RelyingParty": "http://auth.xboxlive.com",
|
|
297
|
+
"TokenType": "JWT",
|
|
298
|
+
},
|
|
299
|
+
)
|
|
300
|
+
xbl_token = xbl["Token"]
|
|
301
|
+
userhash = xbl["DisplayClaims"]["xui"][0]["uhs"]
|
|
302
|
+
|
|
303
|
+
try:
|
|
304
|
+
xsts = _post_json(
|
|
305
|
+
"https://xsts.auth.xboxlive.com/xsts/authorize",
|
|
306
|
+
{
|
|
307
|
+
"Properties": {"SandboxId": "RETAIL", "UserTokens": [xbl_token]},
|
|
308
|
+
"RelyingParty": "rp://api.minecraftservices.com/",
|
|
309
|
+
"TokenType": "JWT",
|
|
310
|
+
},
|
|
311
|
+
)
|
|
312
|
+
except AccountError as exc:
|
|
313
|
+
text = str(exc)
|
|
314
|
+
for code, message in _XSTS_ERRORS.items():
|
|
315
|
+
if code in text:
|
|
316
|
+
raise AccountError(message) from exc
|
|
317
|
+
raise
|
|
318
|
+
|
|
319
|
+
mc = _post_json(
|
|
320
|
+
"https://api.minecraftservices.com/authentication/login_with_xbox",
|
|
321
|
+
{"identityToken": f"XBL3.0 x={userhash};{xsts['Token']}"},
|
|
322
|
+
)
|
|
323
|
+
access_token = mc["access_token"]
|
|
324
|
+
|
|
325
|
+
session = net._session()
|
|
326
|
+
response = session.get(
|
|
327
|
+
"https://api.minecraftservices.com/minecraft/profile",
|
|
328
|
+
headers={"Authorization": f"Bearer {access_token}"},
|
|
329
|
+
timeout=30,
|
|
330
|
+
)
|
|
331
|
+
if response.status_code == 404:
|
|
332
|
+
raise AccountError("该微软账号没有购买 Minecraft: Java 版")
|
|
333
|
+
response.raise_for_status()
|
|
334
|
+
profile = response.json()
|
|
335
|
+
return access_token, profile["id"], profile["name"]
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def login_mojang_account() -> dict:
|
|
339
|
+
ms_access, ms_refresh, expires_in = device_login()
|
|
340
|
+
mc_token, user_uuid, username = minecraft_token(ms_access)
|
|
341
|
+
expires_at = _jwt_exp(mc_token) or (int(time.time()) + max(expires_in, 86400))
|
|
342
|
+
return {
|
|
343
|
+
"type": "mojang",
|
|
344
|
+
"uuid": user_uuid,
|
|
345
|
+
"username": username,
|
|
346
|
+
"ms_access_token": ms_access,
|
|
347
|
+
"ms_refresh_token": ms_refresh,
|
|
348
|
+
"minecraft_access_token": mc_token,
|
|
349
|
+
"expires_at": expires_at,
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def refresh_mojang_account(uuid: str) -> dict:
|
|
354
|
+
accounts = load_accounts()
|
|
355
|
+
account = accounts.get(uuid)
|
|
356
|
+
if not account:
|
|
357
|
+
raise AccountError("账号不存在")
|
|
358
|
+
refresh_token = account.get("ms_refresh_token")
|
|
359
|
+
if not refresh_token:
|
|
360
|
+
raise AccountError("缺少微软 refresh_token,请重新登录")
|
|
361
|
+
try:
|
|
362
|
+
token = _post_json(
|
|
363
|
+
TOKEN_URL,
|
|
364
|
+
{
|
|
365
|
+
"client_id": CLIENT_ID,
|
|
366
|
+
"grant_type": "refresh_token",
|
|
367
|
+
"refresh_token": refresh_token,
|
|
368
|
+
},
|
|
369
|
+
form=True,
|
|
370
|
+
)
|
|
371
|
+
except AccountError as exc:
|
|
372
|
+
raise AccountError(f"微软令牌刷新失败,请重新登录:{exc}") from exc
|
|
373
|
+
|
|
374
|
+
ms_access = token["access_token"]
|
|
375
|
+
ms_refresh = token.get("refresh_token", refresh_token)
|
|
376
|
+
mc_token, new_uuid, username = minecraft_token(ms_access)
|
|
377
|
+
|
|
378
|
+
updated = dict(account)
|
|
379
|
+
updated.update(
|
|
380
|
+
{
|
|
381
|
+
"ms_access_token": ms_access,
|
|
382
|
+
"ms_refresh_token": ms_refresh,
|
|
383
|
+
"minecraft_access_token": mc_token,
|
|
384
|
+
"uuid": new_uuid,
|
|
385
|
+
"username": username,
|
|
386
|
+
"expires_at": _jwt_exp(mc_token) or (int(time.time()) + 86400),
|
|
387
|
+
}
|
|
388
|
+
)
|
|
389
|
+
update_account_save(uuid, updated)
|
|
390
|
+
return updated
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
# ---------------------------------------------------------------- LittleSkin
|
|
394
|
+
|
|
395
|
+
def _little_skin_error(response, action: str) -> AccountError:
|
|
396
|
+
message = ""
|
|
397
|
+
try:
|
|
398
|
+
data = response.json()
|
|
399
|
+
message = data.get("errorMessage") or data.get("error") or ""
|
|
400
|
+
except ValueError:
|
|
401
|
+
message = response.text[:200]
|
|
402
|
+
mapping = {
|
|
403
|
+
"ForbiddenOperationException": "账号或密码错误",
|
|
404
|
+
"InvalidCredentialsException": "凭据无效",
|
|
405
|
+
"IllegalArgumentException": "请求参数不合法",
|
|
406
|
+
}
|
|
407
|
+
for key, text in mapping.items():
|
|
408
|
+
if key in message:
|
|
409
|
+
message = text
|
|
410
|
+
return AccountError(f"LittleSkin {action}失败(HTTP {response.status_code}):{message}")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def little_skin_login(server_url: str, username: str, password: str) -> dict:
|
|
414
|
+
url = f"{server_url.rstrip('/')}/authserver/authenticate"
|
|
415
|
+
client_token = str(uuidlib.uuid4())
|
|
416
|
+
response = net._session().post(
|
|
417
|
+
url,
|
|
418
|
+
json={
|
|
419
|
+
"agent": {"name": "Minecraft", "version": 1},
|
|
420
|
+
"username": username,
|
|
421
|
+
"password": password,
|
|
422
|
+
"clientToken": client_token,
|
|
423
|
+
"requestUser": True,
|
|
424
|
+
},
|
|
425
|
+
timeout=30,
|
|
426
|
+
)
|
|
427
|
+
if response.status_code != 200:
|
|
428
|
+
raise _little_skin_error(response, "登录")
|
|
429
|
+
data = response.json()
|
|
430
|
+
profiles = data.get("availableProfiles") or []
|
|
431
|
+
selected = data.get("selectedProfile") or (profiles[0] if profiles else None)
|
|
432
|
+
if not selected:
|
|
433
|
+
raise AccountError("该账号没有可用角色,请先在 LittleSkin 创建角色")
|
|
434
|
+
|
|
435
|
+
raw_uuid = str(selected["id"])
|
|
436
|
+
if len(raw_uuid) == 32 and "-" not in raw_uuid:
|
|
437
|
+
raw_uuid = f"{raw_uuid[:8]}-{raw_uuid[8:12]}-{raw_uuid[12:16]}-{raw_uuid[16:20]}-{raw_uuid[20:]}"
|
|
438
|
+
return {
|
|
439
|
+
"type": "littleskin",
|
|
440
|
+
"uuid": raw_uuid,
|
|
441
|
+
"username": selected["name"],
|
|
442
|
+
"minecraft_access_token": data["accessToken"],
|
|
443
|
+
"client_token": data.get("clientToken", client_token),
|
|
444
|
+
"expires_at": _jwt_exp(data["accessToken"]) or (int(time.time()) + 86400),
|
|
445
|
+
"available_profiles": profiles,
|
|
446
|
+
"authlib_server": server_url,
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def refresh_little_skin_account(uuid: str, profile_id: str | None = None) -> dict:
|
|
451
|
+
accounts = load_accounts()
|
|
452
|
+
account = accounts.get(uuid)
|
|
453
|
+
if not account:
|
|
454
|
+
raise AccountError("账号不存在")
|
|
455
|
+
server_url = account.get("authlib_server") or LITTLESKIN_SERVER
|
|
456
|
+
payload: dict[str, Any] = {
|
|
457
|
+
"accessToken": account.get("minecraft_access_token"),
|
|
458
|
+
"clientToken": account.get("client_token"),
|
|
459
|
+
"requestUser": True,
|
|
460
|
+
}
|
|
461
|
+
if profile_id:
|
|
462
|
+
payload["selectedProfile"] = {"id": profile_id}
|
|
463
|
+
response = net._session().post(
|
|
464
|
+
f"{server_url.rstrip('/')}/authserver/refresh", json=payload, timeout=30
|
|
465
|
+
)
|
|
466
|
+
if response.status_code != 200:
|
|
467
|
+
raise AccountError("LittleSkin 登录已过期,请重新 login")
|
|
468
|
+
data = response.json()
|
|
469
|
+
selected = data.get("selectedProfile")
|
|
470
|
+
updated = dict(account)
|
|
471
|
+
updated["minecraft_access_token"] = data["accessToken"]
|
|
472
|
+
updated["client_token"] = data.get("clientToken", account.get("client_token"))
|
|
473
|
+
updated["expires_at"] = _jwt_exp(data["accessToken"]) or (int(time.time()) + 86400)
|
|
474
|
+
if selected:
|
|
475
|
+
raw_uuid = str(selected["id"])
|
|
476
|
+
if len(raw_uuid) == 32 and "-" not in raw_uuid:
|
|
477
|
+
raw_uuid = (
|
|
478
|
+
f"{raw_uuid[:8]}-{raw_uuid[8:12]}-{raw_uuid[12:16]}-"
|
|
479
|
+
f"{raw_uuid[16:20]}-{raw_uuid[20:]}"
|
|
480
|
+
)
|
|
481
|
+
updated["uuid"] = raw_uuid
|
|
482
|
+
updated["username"] = selected["name"]
|
|
483
|
+
if data.get("availableProfiles"):
|
|
484
|
+
updated["available_profiles"] = data["availableProfiles"]
|
|
485
|
+
update_account_save(uuid, updated)
|
|
486
|
+
return updated
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def switch_little_skin_profile(uuid: str, profile: str) -> dict:
|
|
490
|
+
"""切换 LittleSkin 角色(按角色名或角色 ID)。"""
|
|
491
|
+
account = get_account(uuid)
|
|
492
|
+
if not account:
|
|
493
|
+
raise AccountError("账号不存在")
|
|
494
|
+
if account.get("type") != "littleskin":
|
|
495
|
+
raise AccountError("只有 LittleSkin 账号支持切换角色")
|
|
496
|
+
profiles = account.get("available_profiles") or []
|
|
497
|
+
if not profiles:
|
|
498
|
+
# 没有缓存就刷新一次拿列表
|
|
499
|
+
account = refresh_little_skin_account(uuid)
|
|
500
|
+
profiles = account.get("available_profiles") or []
|
|
501
|
+
target = None
|
|
502
|
+
lowered = str(profile).lower()
|
|
503
|
+
for item in profiles:
|
|
504
|
+
if str(item.get("name", "")).lower() == lowered or str(item.get("id", "")).lower() == lowered:
|
|
505
|
+
target = item
|
|
506
|
+
break
|
|
507
|
+
if not target:
|
|
508
|
+
names = "、".join(str(p.get("name")) for p in profiles) or "(无)"
|
|
509
|
+
raise AccountError(f"找不到角色 {profile},可用角色:{names}")
|
|
510
|
+
return refresh_little_skin_profile(uuid, target["id"], target["name"])
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def refresh_little_skin_profile(uuid: str, profile_id: str, profile_name: str) -> dict:
|
|
514
|
+
account = get_account(uuid)
|
|
515
|
+
if not account:
|
|
516
|
+
raise AccountError("账号不存在")
|
|
517
|
+
server_url = account.get("authlib_server") or LITTLESKIN_SERVER
|
|
518
|
+
response = net._session().post(
|
|
519
|
+
f"{server_url.rstrip('/')}/authserver/refresh",
|
|
520
|
+
json={
|
|
521
|
+
"accessToken": account.get("minecraft_access_token"),
|
|
522
|
+
"clientToken": account.get("client_token"),
|
|
523
|
+
"selectedProfile": {"id": profile_id, "name": profile_name},
|
|
524
|
+
"requestUser": True,
|
|
525
|
+
},
|
|
526
|
+
timeout=30,
|
|
527
|
+
)
|
|
528
|
+
if response.status_code != 200:
|
|
529
|
+
raise AccountError("LittleSkin 角色切换失败,请重新 login")
|
|
530
|
+
data = response.json()
|
|
531
|
+
updated = dict(account)
|
|
532
|
+
updated["minecraft_access_token"] = data["accessToken"]
|
|
533
|
+
updated["client_token"] = data.get("clientToken", account.get("client_token"))
|
|
534
|
+
updated["expires_at"] = _jwt_exp(data["accessToken"]) or (int(time.time()) + 86400)
|
|
535
|
+
selected = data.get("selectedProfile") or {"id": profile_id, "name": profile_name}
|
|
536
|
+
raw_uuid = str(selected["id"])
|
|
537
|
+
if len(raw_uuid) == 32 and "-" not in raw_uuid:
|
|
538
|
+
raw_uuid = (
|
|
539
|
+
f"{raw_uuid[:8]}-{raw_uuid[8:12]}-{raw_uuid[12:16]}-"
|
|
540
|
+
f"{raw_uuid[16:20]}-{raw_uuid[20:]}"
|
|
541
|
+
)
|
|
542
|
+
updated["uuid"] = raw_uuid
|
|
543
|
+
updated["username"] = selected["name"]
|
|
544
|
+
update_account_save(uuid, updated)
|
|
545
|
+
return updated
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
# ---------------------------------------------------------------- 令牌维护
|
|
549
|
+
|
|
550
|
+
def ensure_valid_account(uuid: str) -> dict:
|
|
551
|
+
"""返回可用的账号信息,必要时自动刷新令牌。"""
|
|
552
|
+
account = get_account(uuid)
|
|
553
|
+
if not account:
|
|
554
|
+
raise AccountError(f"账号 {uuid} 不存在")
|
|
555
|
+
account_type = str(account.get("type") or "offline")
|
|
556
|
+
if account_type == "offline":
|
|
557
|
+
return account
|
|
558
|
+
expires_at = int(account.get("expires_at") or 0)
|
|
559
|
+
if time.time() < expires_at - 60:
|
|
560
|
+
return account
|
|
561
|
+
if account_type == "littleskin":
|
|
562
|
+
return refresh_little_skin_account(uuid)
|
|
563
|
+
return refresh_mojang_account(uuid)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
# ---------------------------------------------------------------- authlib-injector
|
|
567
|
+
|
|
568
|
+
_prefetch_cache: dict[str, str] = {}
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def ensure_authlib_injector() -> Path:
|
|
572
|
+
"""下载/校验 authlib-injector.jar,返回路径。"""
|
|
573
|
+
jar = authlib_injector_jar()
|
|
574
|
+
if jar.is_file() and jar.stat().st_size > 0:
|
|
575
|
+
return jar
|
|
576
|
+
info = net.fetch_json(AUTHLIB_INJECTOR_LATEST)
|
|
577
|
+
url = info.get("download_url")
|
|
578
|
+
expected = (info.get("checksums") or {}).get("sha256")
|
|
579
|
+
if not url:
|
|
580
|
+
raise AccountError("无法获取 authlib-injector 下载地址")
|
|
581
|
+
data = net.fetch_bytes(url)
|
|
582
|
+
actual = sha256(data).hexdigest()
|
|
583
|
+
if expected and actual.lower() != str(expected).lower():
|
|
584
|
+
raise AccountError(f"authlib-injector 校验失败(期望 {expected},实际 {actual})")
|
|
585
|
+
jar = authlib_injector_jar()
|
|
586
|
+
atomic_write_bytes(jar, data)
|
|
587
|
+
return jar
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def prefetch_authlib_meta(server_url: str) -> str:
|
|
591
|
+
"""把认证服务器根响应做 base64,供 -Dauthlibinjector.yggdrasil.prefetched 使用。"""
|
|
592
|
+
key = server_url.rstrip("/")
|
|
593
|
+
if key in _prefetch_cache:
|
|
594
|
+
return _prefetch_cache[key]
|
|
595
|
+
try:
|
|
596
|
+
text = net.fetch_text(key + "/", timeout=15, attempts=1)
|
|
597
|
+
encoded = base64.b64encode(text.encode("utf-8")).decode("ascii")
|
|
598
|
+
except Exception: # noqa: BLE001 - 预取失败不影响启动
|
|
599
|
+
encoded = ""
|
|
600
|
+
_prefetch_cache[key] = encoded
|
|
601
|
+
return encoded
|