@auto-mas/auto-mas-plugin-community 0.0.0-stage → 0.2.1

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.
@@ -0,0 +1,484 @@
1
+ import { createHash, randomInt, randomUUID } from 'node:crypto';
2
+ import { fetchMiyousheDeviceFp, registerMiyousheDevice } from './miyoushe-device.js';
3
+ import { miyousheProviders } from './miyoushe.js';
4
+ import { ProviderError, providerObject, readProviderJson, readProviderJsonWithHeaders } from './provider.js';
5
+ const appCreateUrl = 'https://passport-api.mihoyo.com/account/ma-cn-passport/app/createQRLogin';
6
+ const appCheckUrl = 'https://passport-api.mihoyo.com/account/ma-cn-passport/app/queryQRLoginStatus';
7
+ const passportExchangeUrl = 'https://passport-api.mihoyo.com/account/ma-cn-session/app/exchange';
8
+ const webCreateUrl = 'https://passport-api.miyoushe.com/account/ma-cn-passport/web/createQRLogin';
9
+ const webCheckUrl = 'https://passport-api.miyoushe.com/account/ma-cn-passport/web/queryQRLoginStatus';
10
+ const ltokenUrl = 'https://passport-api.mihoyo.com/account/auth/api/getLTokenBySToken';
11
+ const cookieTokenUrls = [
12
+ 'https://api-takumi.mihoyo.com/auth/api/getCookieAccountInfoBySToken',
13
+ 'https://passport-api.mihoyo.com/account/auth/api/getCookieAccountInfoBySToken',
14
+ ];
15
+ const multiTokenUrl = 'https://api-takumi.mihoyo.com/auth/api/getMultiTokenByLoginTicket';
16
+ const appId = 'bll8iq97cem8';
17
+ const appVersion = '2.90.1';
18
+ const appUserAgent = 'Mozilla/5.0 miHoYoBBS/2.90.1 Capture/2.2.0';
19
+ const appSalt = 'xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs';
20
+ const defaultWebDeviceFp = '38d7fa104e5d7';
21
+ const cookieAliases = {
22
+ cookie_token_v2: 'cookie_token',
23
+ stoken_v2: 'stoken',
24
+ ltuid_v2: 'stuid',
25
+ stuid_v2: 'stuid',
26
+ account_id_v2: 'account_id',
27
+ mid_v2: 'mid',
28
+ ltmid_v2: 'mid',
29
+ account_mid_v2: 'mid',
30
+ ltoken_v2: 'ltoken',
31
+ };
32
+ const knownCookieFields = [
33
+ 'uni_web_token', 'cookie_token', 'cookie_token_v2', 'stoken', 'stoken_v2',
34
+ 'mid', 'mid_v2', 'ltmid_v2', 'account_mid_v2', 'ltoken', 'ltoken_v2',
35
+ 'stuid', 'stuid_v2', 'ltuid', 'ltuid_v2', 'account_id', 'account_id_v2', 'login_uid', 'login_ticket',
36
+ ];
37
+ const uidKeys = ['stuid', 'stuid_v2', 'ltuid', 'ltuid_v2', 'account_id', 'account_id_v2', 'login_uid'];
38
+ const midKeys = ['mid', 'mid_v2', 'ltmid_v2', 'account_mid_v2'];
39
+ function stringField(value) {
40
+ return typeof value === 'string' ? value.trim() : typeof value === 'number' && Number.isFinite(value) ? String(value) : '';
41
+ }
42
+ function isZeroRetcode(value) {
43
+ return value === 0 || value === '0';
44
+ }
45
+ function isExpiredMessage(message) {
46
+ const lower = message.toLowerCase();
47
+ return ['expired', 'expire', 'invalid qr', '二维码已过期', '二维码失效', '二维码无效'].some(marker => lower.includes(marker));
48
+ }
49
+ function appQrHeaders(context, device, body) {
50
+ const timestamp = String(Math.floor(context.now.getTime() / 1000));
51
+ const nonce = String(randomInt(100000, 200000));
52
+ const digest = createHash('md5').update(`salt=${appSalt}&t=${timestamp}&r=${nonce}&b=${body}&q=`).digest('hex');
53
+ return {
54
+ 'x-rpc-app_id': appId,
55
+ 'x-rpc-client_type': '3',
56
+ 'x-rpc-device_id': device,
57
+ 'x-rpc-app_version': appVersion,
58
+ 'x-rpc-sdk_version': appVersion,
59
+ 'x-rpc-account_version': appVersion,
60
+ 'x-rpc-game_biz': 'bbs_cn',
61
+ 'user-agent': appUserAgent,
62
+ 'content-type': 'application/json',
63
+ DS: `${timestamp},${nonce},${digest}`,
64
+ };
65
+ }
66
+ function webQrHeaders(device) {
67
+ return {
68
+ 'x-rpc-app_id': appId,
69
+ 'x-rpc-client_type': '4',
70
+ 'x-rpc-game_biz': 'bbs_cn',
71
+ 'x-rpc-device_fp': defaultWebDeviceFp,
72
+ 'x-rpc-device_id': device,
73
+ 'content-type': 'application/json',
74
+ };
75
+ }
76
+ function parseAppQrData(data) {
77
+ const qrUrl = stringField(data.url);
78
+ if (!qrUrl)
79
+ return;
80
+ let parsed;
81
+ try {
82
+ parsed = new URL(qrUrl);
83
+ }
84
+ catch {
85
+ return;
86
+ }
87
+ if (parsed.protocol !== 'https:' || parsed.hostname.toLowerCase() !== 'user.mihoyo.com' || parsed.pathname.toLowerCase() !== '/login-platform/mobile.html') {
88
+ return;
89
+ }
90
+ const ticket = stringField(data.ticket) || stringField(parsed.searchParams.get('tk'));
91
+ if (!ticket)
92
+ return;
93
+ return { qrUrl, ticket };
94
+ }
95
+ function parseCookieString(raw, out) {
96
+ for (const part of raw.split(';')) {
97
+ const separator = part.indexOf('=');
98
+ if (separator < 1)
99
+ continue;
100
+ const key = part.slice(0, separator).trim();
101
+ const value = part.slice(separator + 1).trim();
102
+ if (key && value && !out.has(key))
103
+ out.set(key, value);
104
+ }
105
+ }
106
+ function addAliases(cookies) {
107
+ for (const [legacy, v2] of [['cookie_token', 'cookie_token_v2'], ['stoken', 'stoken_v2'], ['ltoken', 'ltoken_v2']]) {
108
+ const value = cookies.get(legacy);
109
+ if (!cookies.has(v2) && value?.startsWith('v2_'))
110
+ cookies.set(v2, value);
111
+ }
112
+ for (const [source, target] of Object.entries(cookieAliases)) {
113
+ const value = cookies.get(source);
114
+ if (value && !cookies.has(target))
115
+ cookies.set(target, value);
116
+ }
117
+ const uid = uidKeys.map(key => cookies.get(key)).find(Boolean);
118
+ if (uid) {
119
+ for (const key of uidKeys)
120
+ if (!cookies.has(key))
121
+ cookies.set(key, uid);
122
+ }
123
+ const mid = midKeys.map(key => cookies.get(key)).find(Boolean);
124
+ if (mid) {
125
+ for (const key of midKeys)
126
+ if (!cookies.has(key))
127
+ cookies.set(key, mid);
128
+ }
129
+ }
130
+ function extractBodyCookies(payload, out, depth = 0) {
131
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
132
+ return;
133
+ const data = payload;
134
+ for (const key of knownCookieFields) {
135
+ const value = stringField(data[key]);
136
+ if (value && !out.has(key))
137
+ out.set(key, value);
138
+ }
139
+ const userInfo = providerObject(data.user_info);
140
+ const aid = stringField(userInfo.aid || userInfo.uid || userInfo.account_id);
141
+ const mid = stringField(userInfo.mid);
142
+ if (aid) {
143
+ if (!out.has('account_id_v2'))
144
+ out.set('account_id_v2', aid);
145
+ if (!out.has('ltuid_v2'))
146
+ out.set('ltuid_v2', aid);
147
+ }
148
+ if (mid && !out.has('mid'))
149
+ out.set('mid', mid);
150
+ if (Array.isArray(data.tokens)) {
151
+ for (const item of data.tokens) {
152
+ const tokenInfo = providerObject(item);
153
+ const token = stringField(tokenInfo.token);
154
+ if (!token)
155
+ continue;
156
+ const name = stringField(tokenInfo.name);
157
+ if (name && knownCookieFields.includes(name) && !out.has(name)) {
158
+ out.set(name, token);
159
+ }
160
+ else if (stringField(tokenInfo.token_type) === '1' && !out.has('stoken_v2')) {
161
+ out.set('stoken_v2', token);
162
+ if (!out.has('stoken'))
163
+ out.set('stoken', token);
164
+ }
165
+ }
166
+ }
167
+ else if (data.tokens && typeof data.tokens === 'object') {
168
+ const tokens = providerObject(data.tokens);
169
+ for (const key of knownCookieFields) {
170
+ const value = stringField(tokens[key]);
171
+ if (value && !out.has(key))
172
+ out.set(key, value);
173
+ }
174
+ }
175
+ for (const key of ['cookie', 'cookies', 'cookie_str', 'cookies_str']) {
176
+ const value = data[key];
177
+ if (typeof value === 'string')
178
+ parseCookieString(value, out);
179
+ else if (value && typeof value === 'object' && !Array.isArray(value)) {
180
+ for (const [k, v] of Object.entries(value)) {
181
+ const text = stringField(v);
182
+ if (k && text && !out.has(k))
183
+ out.set(k, text);
184
+ }
185
+ }
186
+ }
187
+ if (depth < 2) {
188
+ for (const key of ['data', 'result', 'payload', 'login_data']) {
189
+ let nested = data[key];
190
+ if (typeof nested === 'string') {
191
+ try {
192
+ nested = JSON.parse(nested);
193
+ }
194
+ catch {
195
+ nested = undefined;
196
+ }
197
+ }
198
+ if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
199
+ extractBodyCookies(nested, out, depth + 1);
200
+ }
201
+ }
202
+ }
203
+ }
204
+ function extractSetCookies(headers, out) {
205
+ const list = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];
206
+ for (const header of list) {
207
+ const first = header.split(';', 1)[0] ?? '';
208
+ const separator = first.indexOf('=');
209
+ if (separator < 1)
210
+ continue;
211
+ const key = first.slice(0, separator).trim();
212
+ const value = first.slice(separator + 1).trim();
213
+ if (key && value)
214
+ out.set(key, value);
215
+ }
216
+ }
217
+ async function supplementStokenFromTicket(context, cookies) {
218
+ const ticket = cookies.get('login_ticket');
219
+ const uid = uidKeys.map(key => cookies.get(key)).find(Boolean);
220
+ if (!ticket || !uid)
221
+ return;
222
+ try {
223
+ const url = new URL(multiTokenUrl);
224
+ url.search = new URLSearchParams({ login_ticket: ticket, token_types: '3', uid }).toString();
225
+ const payload = await readProviderJson(context, url, { method: 'GET' });
226
+ if (!isZeroRetcode(payload.retcode))
227
+ return;
228
+ const list = providerObject(payload.data).list;
229
+ if (!Array.isArray(list))
230
+ return;
231
+ for (const entry of list) {
232
+ const info = providerObject(entry);
233
+ const name = stringField(info.name);
234
+ const token = stringField(info.token);
235
+ if (!token)
236
+ continue;
237
+ if (name === 'stoken' || name === 'stoken_v2') {
238
+ if (!cookies.has('stoken'))
239
+ cookies.set('stoken', token);
240
+ if (name === 'stoken_v2' || token.startsWith('v2_')) {
241
+ if (!cookies.has('stoken_v2'))
242
+ cookies.set('stoken_v2', token);
243
+ const mid = stringField(info.mid);
244
+ if (mid && !cookies.has('mid'))
245
+ cookies.set('mid', mid);
246
+ }
247
+ }
248
+ else if (name === 'ltoken' || name === 'ltoken_v2') {
249
+ if (!cookies.has('ltoken'))
250
+ cookies.set('ltoken', token);
251
+ if (name === 'ltoken_v2' && !cookies.has('ltoken_v2'))
252
+ cookies.set('ltoken_v2', token);
253
+ }
254
+ }
255
+ }
256
+ catch {
257
+ context.signal.throwIfAborted();
258
+ }
259
+ }
260
+ async function supplementTokensByStoken(context, cookies, device) {
261
+ addAliases(cookies);
262
+ const stoken = cookies.get('stoken_v2') ?? cookies.get('stoken');
263
+ const mid = cookies.get('mid');
264
+ const uid = uidKeys.map(key => cookies.get(key)).find(Boolean);
265
+ if (!stoken || !mid || !uid)
266
+ return;
267
+ const pending = [];
268
+ if (!cookies.has('ltoken'))
269
+ pending.push(['ltoken', [ltokenUrl]]);
270
+ if (!cookies.has('cookie_token'))
271
+ pending.push(['cookie_token', cookieTokenUrls]);
272
+ if (!pending.length)
273
+ return;
274
+ const androidHeaders = {
275
+ cookie: `stoken=${stoken}; mid=${mid}; stuid=${uid}`,
276
+ accept: 'application/json, text/plain, */*',
277
+ origin: 'https://webstatic.mihoyo.com',
278
+ referer: 'https://act.mihoyo.com/',
279
+ 'x-rpc-client_type': '5',
280
+ 'x-rpc-device_id': device,
281
+ 'x-rpc-game_biz': 'bbs_cn',
282
+ 'x-rpc-app_version': '2.99.1',
283
+ 'x-rpc-channel': 'miyousheluodi',
284
+ 'x-requested-with': 'com.mihoyo.hyperion',
285
+ 'user-agent': 'Mozilla/5.0 (Linux; Android 12; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/103.0.5060.129 Mobile Safari/537.36 miHoYoBBS/2.99.1',
286
+ };
287
+ const iosHeaders = {
288
+ cookie: `stoken=${stoken}; mid=${mid}; stuid=${uid}`,
289
+ 'x-rpc-client_type': '1',
290
+ 'x-rpc-device_id': device,
291
+ 'x-rpc-game_biz': 'bbs_cn',
292
+ 'x-rpc-app_version': '2.63.1',
293
+ 'user-agent': 'Hyperion/275 CFNetwork/1402.0.8 Darwin/22.2.0',
294
+ };
295
+ for (const [field, urls] of pending) {
296
+ let resolved = false;
297
+ const dstTokenType = field === 'cookie_token' ? 4 : 2;
298
+ const exchangeBody = JSON.stringify({
299
+ dst_token_type: dstTokenType,
300
+ src_token: { token: stoken, token_type: 1 },
301
+ mid,
302
+ });
303
+ for (const headers of [
304
+ appQrHeaders(context, device, exchangeBody),
305
+ {
306
+ ...appQrHeaders(context, device, exchangeBody),
307
+ 'x-rpc-client_type': '2',
308
+ 'x-rpc-app_version': '2.119.0',
309
+ 'user-agent': 'okhttp/4.9.3',
310
+ },
311
+ ]) {
312
+ try {
313
+ const payload = await readProviderJson(context, passportExchangeUrl, {
314
+ method: 'POST',
315
+ headers,
316
+ body: exchangeBody,
317
+ });
318
+ if (!isZeroRetcode(payload.retcode))
319
+ continue;
320
+ const data = providerObject(payload.data);
321
+ const tokenObj = providerObject(data.token);
322
+ const value = stringField(tokenObj.token) || stringField(data[field]);
323
+ if (!value)
324
+ continue;
325
+ cookies.set(field, value);
326
+ resolved = true;
327
+ break;
328
+ }
329
+ catch {
330
+ context.signal.throwIfAborted();
331
+ }
332
+ }
333
+ if (resolved)
334
+ continue;
335
+ const candidates = field === 'cookie_token' ? [androidHeaders, iosHeaders] : [iosHeaders, androidHeaders];
336
+ for (const url of urls) {
337
+ if (resolved)
338
+ break;
339
+ for (const headers of candidates) {
340
+ try {
341
+ const { payload, headers: responseHeaders } = await readProviderJsonWithHeaders(context, url, { method: 'GET', headers });
342
+ if (!isZeroRetcode(payload.retcode))
343
+ continue;
344
+ const data = providerObject(payload.data);
345
+ const setCookies = new Map();
346
+ extractSetCookies(responseHeaders, setCookies);
347
+ const value = stringField(data[field]) || (field === 'cookie_token' ? stringField(data.cookie_token_v2) || stringField(setCookies.get('cookie_token')) || stringField(setCookies.get('cookie_token_v2')) : '');
348
+ if (!value)
349
+ continue;
350
+ if (field === 'cookie_token' && stringField(data.uid) && stringField(data.uid) !== uid)
351
+ continue;
352
+ cookies.set(field, value);
353
+ resolved = true;
354
+ break;
355
+ }
356
+ catch {
357
+ context.signal.throwIfAborted();
358
+ }
359
+ }
360
+ }
361
+ }
362
+ addAliases(cookies);
363
+ }
364
+ async function finalizeMiyousheCookies(context, cookies, device) {
365
+ cookies.delete('login_ticket');
366
+ addAliases(cookies);
367
+ if (!cookies.has('stoken_v2') || !cookies.has('mid')) {
368
+ throw new ProviderError('扫码确认成功但缺少 stoken_v2 或配套 mid,请重新扫码');
369
+ }
370
+ await supplementTokensByStoken(context, cookies, device);
371
+ const cookie = [...cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
372
+ const deviceFp = await fetchMiyousheDeviceFp(context, device, cookie);
373
+ if (deviceFp) {
374
+ const stoken = cookies.get('stoken_v2') ?? cookies.get('stoken') ?? '';
375
+ const mid = cookies.get('mid') ?? '';
376
+ const uid = uidKeys.map(key => cookies.get(key)).find(Boolean) ?? '';
377
+ if (stoken && mid && uid) {
378
+ await registerMiyousheDevice(context, device, deviceFp, `stoken=${stoken}; mid=${mid}; stuid=${uid}`);
379
+ }
380
+ }
381
+ const raw = deviceFp ? JSON.stringify({ cookie, deviceId: device, deviceFp }) : JSON.stringify({ cookie, deviceId: device });
382
+ return miyousheProviders[0].validateCredential(raw);
383
+ }
384
+ export async function createMiyousheQrLogin(context) {
385
+ const device = randomUUID().toUpperCase();
386
+ try {
387
+ const payload = await readProviderJson(context, appCreateUrl, {
388
+ method: 'POST',
389
+ headers: appQrHeaders(context, device, '{}'),
390
+ body: '{}',
391
+ });
392
+ if (isZeroRetcode(payload.retcode)) {
393
+ const parsed = parseAppQrData(providerObject(payload.data));
394
+ if (parsed)
395
+ return { mode: 'app', ticket: parsed.ticket, qrUrl: parsed.qrUrl, device };
396
+ }
397
+ }
398
+ catch {
399
+ context.signal.throwIfAborted();
400
+ }
401
+ const payload = await readProviderJson(context, webCreateUrl, {
402
+ method: 'POST',
403
+ headers: webQrHeaders(device),
404
+ body: '{}',
405
+ });
406
+ if (!isZeroRetcode(payload.retcode))
407
+ throw new ProviderError('创建米游社二维码失败,请稍后重试');
408
+ const data = providerObject(payload.data);
409
+ const qrUrl = stringField(data.url);
410
+ const ticket = stringField(data.ticket);
411
+ let parsedUrl;
412
+ try {
413
+ parsedUrl = new URL(qrUrl);
414
+ }
415
+ catch {
416
+ throw new ProviderError('米游社二维码响应格式无效');
417
+ }
418
+ if (parsedUrl.protocol !== 'https:' || !ticket)
419
+ throw new ProviderError('米游社二维码响应缺少必要字段');
420
+ return { mode: 'web', ticket, qrUrl, device };
421
+ }
422
+ export async function pollMiyousheQrLogin(context, challenge) {
423
+ if (challenge.mode === 'app') {
424
+ const body = JSON.stringify({ ticket: challenge.ticket });
425
+ const payload = await readProviderJson(context, appCheckUrl, {
426
+ method: 'POST',
427
+ headers: appQrHeaders(context, challenge.device, body),
428
+ body,
429
+ });
430
+ const message = stringField(payload.message);
431
+ if (!isZeroRetcode(payload.retcode)) {
432
+ if (String(payload.retcode) === '-106' || isExpiredMessage(message)) {
433
+ return { status: 'expired', message: '二维码已过期,请重新生成' };
434
+ }
435
+ throw new ProviderError('查询米游社扫码状态失败,请稍后重试');
436
+ }
437
+ const data = providerObject(payload.data);
438
+ const status = stringField(data.status);
439
+ if (status === 'Created' || status === 'Init')
440
+ return { status: 'waiting' };
441
+ if (status === 'Scanned')
442
+ return { status: 'scanned' };
443
+ if (status === 'Expired')
444
+ return { status: 'expired', message: '二维码已过期,请重新生成' };
445
+ if (status === 'Canceled')
446
+ return { status: 'canceled', message: '登录已取消' };
447
+ if (status !== 'Confirmed')
448
+ throw new ProviderError('收到未知的米游社扫码状态');
449
+ const cookies = new Map();
450
+ extractBodyCookies(data, cookies);
451
+ return { status: 'confirmed', credential: await finalizeMiyousheCookies(context, cookies, challenge.device) };
452
+ }
453
+ const { payload, headers } = await readProviderJsonWithHeaders(context, webCheckUrl, {
454
+ method: 'POST',
455
+ headers: webQrHeaders(challenge.device),
456
+ body: JSON.stringify({ ticket: challenge.ticket }),
457
+ });
458
+ const message = stringField(payload.message);
459
+ if (!isZeroRetcode(payload.retcode)) {
460
+ if (String(payload.retcode) === '-106' || isExpiredMessage(message)) {
461
+ return { status: 'expired', message: '二维码已过期,请重新生成' };
462
+ }
463
+ throw new ProviderError('查询米游社扫码状态失败,请稍后重试');
464
+ }
465
+ const data = providerObject(payload.data);
466
+ const status = stringField(data.status);
467
+ if (!status || status === 'Expired')
468
+ return { status: 'expired', message: '二维码已过期,请重新生成' };
469
+ if (status === 'Created' || status === 'Init')
470
+ return { status: 'waiting' };
471
+ if (status === 'Scanned')
472
+ return { status: 'scanned' };
473
+ if (status === 'Canceled')
474
+ return { status: 'canceled', message: '登录已取消' };
475
+ if (status !== 'Confirmed')
476
+ throw new ProviderError('收到未知的米游社扫码状态');
477
+ const cookies = new Map();
478
+ extractSetCookies(headers, cookies);
479
+ extractBodyCookies(data, cookies);
480
+ addAliases(cookies);
481
+ if (!cookies.has('stoken_v2'))
482
+ await supplementStokenFromTicket(context, cookies);
483
+ return { status: 'confirmed', credential: await finalizeMiyousheCookies(context, cookies, challenge.device) };
484
+ }