@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,633 @@
1
+ import { createHash, randomBytes, randomInt } from 'node:crypto';
2
+ import { deterministicDeviceId, fetchMiyousheDeviceFp, registerMiyousheDevice } from './miyoushe-device.js';
3
+ import { ProviderError, providerObject, readProviderJson, } from './provider.js';
4
+ const signBase = 'https://api-takumi.mihoyo.com/event/luna';
5
+ const zzzSignBase = 'https://act-nap-api.mihoyo.com/event/luna/zzz';
6
+ const rolesUrl = 'https://api-takumi.mihoyo.com/binding/api/getUserGameRolesByCookie';
7
+ const passportExchangeUrl = 'https://passport-api.mihoyo.com/account/ma-cn-session/app/exchange';
8
+ const passportCookieUrls = [
9
+ 'https://api-takumi.mihoyo.com/auth/api/getCookieAccountInfoBySToken',
10
+ 'https://passport-api.mihoyo.com/account/auth/api/getCookieAccountInfoBySToken',
11
+ ];
12
+ const passportAppId = 'bll8iq97cem8';
13
+ const recordHost = 'https://api-takumi-record.mihoyo.com';
14
+ // Public request-format constants from the legacy MAS CN web and record clients.
15
+ const webSalt = 'DlOUwIupfU6YespEUWDJmXtutuXV6owG';
16
+ const signSalt = 't0qEgfub6cvueAPgR5m9aQWWVciEer7v';
17
+ const noteSalt = 'xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs';
18
+ const widgetSalt = '9ttJY72HxbjwWRNHJvn0n2AYue47nYsK';
19
+ const bbsUserAgent = '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';
20
+ const zzzUserAgent = 'Mozilla/5.0 (Linux; Android 12; MI 8 SE Build/RQ3A.211001.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/111.0.5563.116 Mobile Safari/537.36 miHoYoBBS/2.73.1';
21
+ const verificationCodes = new Set([1034, 5003, 10035, 10041]);
22
+ const uidKeys = ['stuid', 'stuid_v2', 'ltuid', 'account_id', 'login_uid', 'ltuid_v2', 'account_id_v2'];
23
+ const legacyUidKeys = ['stuid', 'ltuid', 'account_id', 'login_uid'];
24
+ const cookieAliases = {
25
+ cookie_token_v2: 'cookie_token', stoken_v2: 'stoken', mid_v2: 'mid', ltmid_v2: 'mid', account_mid_v2: 'mid',
26
+ };
27
+ const authNames = new Set([...uidKeys, ...Object.keys(cookieAliases), ...Object.values(cookieAliases), 'ltoken', 'ltoken_v2']);
28
+ function session(input) {
29
+ const text = input.trim();
30
+ if (!text || text.length > 8192)
31
+ throw new ProviderError('请输入有效的米游社凭据');
32
+ const metadata = text.startsWith('{') ? sessionObject(text) : { cookie: text };
33
+ if (typeof metadata.cookie !== 'string' || /[^\x20-\x7e]/.test(metadata.cookie)) {
34
+ throw new ProviderError('米游社凭据的 Cookie 格式无效');
35
+ }
36
+ const cookies = new Map();
37
+ for (const field of metadata.cookie.split(';')) {
38
+ const separator = field.indexOf('=');
39
+ if (separator < 1)
40
+ continue;
41
+ const key = field.slice(0, separator).trim();
42
+ const value = field.slice(separator + 1).trim();
43
+ if (authNames.has(key) && /^[^\s;,"]+$/.test(value))
44
+ cookies.set(key, value);
45
+ }
46
+ const uid = uidKeys.map(key => cookies.get(key)).find(value => value && /^\d+$/.test(value));
47
+ if (!uid)
48
+ throw new ProviderError('米游社 Cookie 缺少登录账号 UID');
49
+ for (const key of legacyUidKeys) {
50
+ if (!cookies.has(key))
51
+ cookies.set(key, uid);
52
+ }
53
+ for (const [source, destination] of Object.entries(cookieAliases)) {
54
+ const value = cookies.get(source);
55
+ if (value && !cookies.has(destination))
56
+ cookies.set(destination, value);
57
+ }
58
+ const signReady = cookies.has('cookie_token');
59
+ const v2Stoken = cookies.get('stoken_v2') ?? (cookies.get('stoken')?.startsWith('v2_') ? cookies.get('stoken') : undefined);
60
+ const noteReady = Boolean(v2Stoken) && cookies.has('mid');
61
+ if (!signReady && !noteReady)
62
+ throw new ProviderError('米游社 Cookie 缺少 cookie_token 或便笺所需的 v2 stoken 与 mid');
63
+ const cookie = [...cookies.entries()].map(([key, value]) => `${key}=${value}`).join('; ');
64
+ const activityCookies = new Map(cookies);
65
+ if (v2Stoken) {
66
+ activityCookies.set('stoken', v2Stoken);
67
+ activityCookies.delete('stoken_v2');
68
+ }
69
+ const activityCookie = [...activityCookies.entries()].map(([key, value]) => `${key}=${value}`).join('; ');
70
+ const secretValues = [...cookies].filter(([key]) => !uidKeys.includes(key)).map(([, value]) => value);
71
+ return {
72
+ uid, cookies, v2Stoken, mid: cookies.get('mid'), cookie, activityCookie,
73
+ signReady, noteReady, secretValues, deviceId: deviceValue(metadata.deviceId), deviceFp: deviceValue(metadata.deviceFp),
74
+ };
75
+ }
76
+ function serializeSession(credentials, cookieOverrides) {
77
+ const merged = new Map(credentials.cookies);
78
+ for (const [key, value] of Object.entries(cookieOverrides)) {
79
+ if (value)
80
+ merged.set(key, value);
81
+ }
82
+ const cookie = [...merged.entries()].map(([key, value]) => `${key}=${value}`).join('; ');
83
+ return credentials.deviceId || credentials.deviceFp
84
+ ? JSON.stringify({ cookie, deviceId: credentials.deviceId, deviceFp: credentials.deviceFp })
85
+ : cookie;
86
+ }
87
+ async function deriveCookieTokenFromStoken(credentials, context) {
88
+ if (!credentials.v2Stoken || !credentials.mid || !credentials.uid) {
89
+ return { reason: '缺少 stoken_v2、mid 或 uid' };
90
+ }
91
+ const deviceId = credentials.deviceId ?? deterministicDeviceId(credentials.uid);
92
+ let exchangeReason;
93
+ let lastReason = '未返回 cookie_token';
94
+ const exchangeBody = JSON.stringify({
95
+ dst_token_type: 4,
96
+ src_token: { token: credentials.v2Stoken, token_type: 1 },
97
+ mid: credentials.mid,
98
+ });
99
+ const exchangeProfiles = [
100
+ { clientType: '3', version: '2.90.1', ua: 'Mozilla/5.0 miHoYoBBS/2.90.1 Capture/2.2.0' },
101
+ { clientType: '2', version: '2.119.0', ua: 'okhttp/4.9.3' },
102
+ ];
103
+ for (const profile of exchangeProfiles) {
104
+ try {
105
+ const headers = {
106
+ 'content-type': 'application/json',
107
+ 'x-rpc-app_id': passportAppId,
108
+ 'x-rpc-client_type': profile.clientType,
109
+ 'x-rpc-device_id': deviceId,
110
+ 'x-rpc-app_version': profile.version,
111
+ 'x-rpc-sdk_version': profile.version,
112
+ 'x-rpc-account_version': profile.version,
113
+ 'x-rpc-game_biz': 'bbs_cn',
114
+ 'user-agent': profile.ua,
115
+ DS: signature(context, noteSalt, String(randomInt(100000, 200000)), exchangeBody),
116
+ };
117
+ if (credentials.deviceFp)
118
+ headers['x-rpc-device_fp'] = credentials.deviceFp;
119
+ const response = await readProviderJson(context, passportExchangeUrl, {
120
+ method: 'POST',
121
+ headers,
122
+ body: exchangeBody,
123
+ });
124
+ if (businessState(response) !== 'success') {
125
+ const code = response.retcode !== undefined ? `retcode=${String(response.retcode)}` : 'retcode 异常';
126
+ const msg = typeof response.message === 'string' && response.message.trim()
127
+ && !credentials.secretValues.some(secret => response.message.toString().includes(secret))
128
+ ? response.message.trim().slice(0, 60)
129
+ : '';
130
+ exchangeReason = msg ? `exchange ${code} (${msg})` : `exchange ${code}`;
131
+ continue;
132
+ }
133
+ const data = providerObject(response.data);
134
+ const tokenObj = providerObject(data.token);
135
+ const raw = typeof tokenObj.token === 'string' ? tokenObj.token
136
+ : typeof data.cookie_token === 'string' ? data.cookie_token
137
+ : typeof data.cookie_token_v2 === 'string' ? data.cookie_token_v2 : '';
138
+ const token = raw.trim();
139
+ if (token && /^[^\s;,"]+$/.test(token))
140
+ return { token };
141
+ exchangeReason = 'exchange 接口返回成功但无 cookie_token';
142
+ }
143
+ catch (error) {
144
+ context.signal.throwIfAborted();
145
+ exchangeReason = error instanceof Error ? `exchange: ${error.message.slice(0, 60)}` : 'exchange 请求失败';
146
+ }
147
+ }
148
+ const stokenCookie = `stoken=${credentials.v2Stoken}; mid=${credentials.mid}; stuid=${credentials.uid}`;
149
+ const attempts = [
150
+ {
151
+ cookie: stokenCookie, accept: 'application/json, text/plain, */*', origin: 'https://webstatic.mihoyo.com',
152
+ referer: 'https://act.mihoyo.com/', 'x-rpc-client_type': '5', 'x-rpc-app_version': '2.99.1',
153
+ 'x-rpc-game_biz': 'bbs_cn', 'x-rpc-device_id': deviceId, 'x-rpc-channel': 'miyousheluodi',
154
+ 'x-requested-with': 'com.mihoyo.hyperion', 'user-agent': bbsUserAgent,
155
+ },
156
+ {
157
+ cookie: stokenCookie, 'x-rpc-client_type': '1', 'x-rpc-device_id': deviceId, 'x-rpc-game_biz': 'bbs_cn',
158
+ 'x-rpc-app_version': '2.63.1', 'user-agent': 'Hyperion/275 CFNetwork/1402.0.8 Darwin/22.2.0',
159
+ },
160
+ ];
161
+ for (const url of passportCookieUrls) {
162
+ for (const headers of attempts) {
163
+ try {
164
+ const response = await readProviderJson(context, url, { method: 'GET', headers });
165
+ if (businessState(response) !== 'success') {
166
+ const code = response.retcode !== undefined ? `retcode=${String(response.retcode)}` : 'retcode 异常';
167
+ const msg = typeof response.message === 'string' && response.message.trim()
168
+ && !credentials.secretValues.some(secret => response.message.toString().includes(secret))
169
+ ? response.message.trim().slice(0, 60)
170
+ : '';
171
+ lastReason = msg ? `${code} (${msg})` : code;
172
+ continue;
173
+ }
174
+ const data = providerObject(response.data);
175
+ const raw = typeof data.cookie_token === 'string' ? data.cookie_token : typeof data.cookie_token_v2 === 'string' ? data.cookie_token_v2 : '';
176
+ const token = raw.trim();
177
+ if (token && /^[^\s;,"]+$/.test(token))
178
+ return { token };
179
+ lastReason = '接口返回成功但无 cookie_token';
180
+ }
181
+ catch (error) {
182
+ context.signal.throwIfAborted();
183
+ lastReason = error instanceof Error ? error.message.slice(0, 60) : '请求失败';
184
+ }
185
+ }
186
+ }
187
+ return { reason: exchangeReason ?? lastReason };
188
+ }
189
+ function sessionObject(text) {
190
+ try {
191
+ return providerObject(JSON.parse(text));
192
+ }
193
+ catch {
194
+ throw new ProviderError('米游社凭据 JSON 格式无效');
195
+ }
196
+ }
197
+ function deviceValue(value) {
198
+ if (value === undefined)
199
+ return undefined;
200
+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(value))
201
+ throw new ProviderError('米游社凭据的设备标识格式无效');
202
+ return value;
203
+ }
204
+ function validateCredential(input) {
205
+ const { cookie, deviceId, deviceFp } = session(input);
206
+ return deviceId || deviceFp ? JSON.stringify({ cookie, deviceId, deviceFp }) : cookie;
207
+ }
208
+ function role(target) {
209
+ const { roleUid, server } = target;
210
+ if (!roleUid || !server || !/^[A-Za-z0-9_-]{1,80}$/.test(roleUid) || !/^[A-Za-z0-9_-]{1,80}$/.test(server)) {
211
+ throw new ProviderError('请输入米游社绑定的国服角色 UID 和区服代码');
212
+ }
213
+ return { roleUid, server };
214
+ }
215
+ function signature(context, salt, nonce, body = '', query = '') {
216
+ const time = Math.floor(context.now.getTime() / 1000);
217
+ const digest = createHash('md5').update(`salt=${salt}&t=${time}&r=${nonce}&b=${body}&q=${query}`).digest('hex');
218
+ return `${time},${nonce},${digest}`;
219
+ }
220
+ function simpleSignature(context, salt, nonce) {
221
+ const time = Math.floor(context.now.getTime() / 1000);
222
+ const digest = createHash('md5').update(`salt=${salt}&t=${time}&r=${nonce}`).digest('hex');
223
+ return `${time},${nonce},${digest}`;
224
+ }
225
+ function optionalDeviceHeaders(headers, deviceId, deviceFp) {
226
+ if (deviceId)
227
+ headers.set('x-rpc-device_id', deviceId);
228
+ if (deviceFp)
229
+ headers.set('x-rpc-device_fp', deviceFp);
230
+ }
231
+ function businessState(payload) {
232
+ const { retcode, data } = payload;
233
+ const code = typeof retcode === 'string' && /^-?\d+$/.test(retcode) ? Number(retcode) : retcode;
234
+ const details = providerObject(data);
235
+ if ((typeof code === 'number' && verificationCodes.has(code)) || payload.challenge || details.challenge || details.gt || details.is_risk === true)
236
+ return 'verification';
237
+ if (code === -100 || code === 10001)
238
+ return 'expired';
239
+ if (code === -5003)
240
+ return 'already';
241
+ return code === 0 ? 'success' : 'failed';
242
+ }
243
+ function awardMessage(data, credentials) {
244
+ const award = providerObject(providerObject(data).award);
245
+ const name = typeof award.name === 'string' ? award.name.trim() : '';
246
+ const count = numberValue(award.cnt);
247
+ if (name && /^[\p{L}\p{N} ·()()_-]{1,40}$/u.test(name) && count !== undefined && !credentials.secretValues.some(value => name.includes(value))) {
248
+ return `签到成功,${name} × ${count}`;
249
+ }
250
+ return '签到成功';
251
+ }
252
+ async function sign(game, target, context) {
253
+ let credentials = session(target.credential);
254
+ let deriveReason;
255
+ if (!credentials.signReady && credentials.noteReady) {
256
+ const derived = await deriveCookieTokenFromStoken(credentials, context);
257
+ if (derived.token)
258
+ credentials = session(validateCredential(serializeSession(credentials, { cookie_token: derived.token, cookie_token_v2: derived.token })));
259
+ else
260
+ deriveReason = derived.reason;
261
+ }
262
+ if (!credentials.signReady) {
263
+ return {
264
+ status: 'failed',
265
+ message: deriveReason ? `米游社签到需要有效的 cookie_token(自动换取失败:${deriveReason})` : '米游社签到需要有效的 cookie_token',
266
+ };
267
+ }
268
+ const { roleUid: uid, server: region } = role(target);
269
+ const base = game.base ?? signBase;
270
+ const params = new URLSearchParams({ lang: 'zh-cn', act_id: game.actId, region, uid });
271
+ params.sort();
272
+ const buildHeaders = (active) => {
273
+ const headers = new Headers({
274
+ accept: 'application/json', cookie: active.cookie, origin: 'https://act.mihoyo.com', referer: 'https://act.mihoyo.com/',
275
+ 'x-rpc-client_type': '5', 'x-rpc-app_version': '2.99.1',
276
+ });
277
+ optionalDeviceHeaders(headers, active.deviceId, active.deviceFp);
278
+ if (game.signgame)
279
+ headers.set('x-rpc-signgame', game.signgame);
280
+ headers.set('DS', signature(context, signSalt, randomBytes(3).toString('hex'), '', params.toString()));
281
+ return headers;
282
+ };
283
+ let headers = buildHeaders(credentials);
284
+ let info = await readProviderJson(context, `${base}/info?${params}`, { method: 'GET', headers });
285
+ let state = businessState(info);
286
+ if (state === 'expired' && credentials.noteReady) {
287
+ const derived = await deriveCookieTokenFromStoken(credentials, context);
288
+ if (derived.token) {
289
+ credentials = session(validateCredential(serializeSession(credentials, { cookie_token: derived.token, cookie_token_v2: derived.token })));
290
+ headers = buildHeaders(credentials);
291
+ info = await readProviderJson(context, `${base}/info?${params}`, { method: 'GET', headers });
292
+ state = businessState(info);
293
+ }
294
+ }
295
+ if (state === 'already' || state === 'success' && providerObject(info.data).is_sign === true) {
296
+ return { status: 'already', message: '今日已签到' };
297
+ }
298
+ if (state !== 'success')
299
+ return signFailure(state, '获取米游社签到状态失败');
300
+ const body = JSON.stringify({ act_id: game.actId, region, uid });
301
+ const postHeaders = new Headers(headers);
302
+ postHeaders.set('content-type', 'application/json;charset=utf-8');
303
+ postHeaders.set('DS', signature(context, signSalt, randomBytes(3).toString('hex'), body));
304
+ const response = await readProviderJson(context, `${base}/sign`, { method: 'POST', headers: postHeaders, body });
305
+ const outcome = businessState(response);
306
+ if (outcome === 'success')
307
+ return { status: 'success', message: awardMessage(response.data, credentials) };
308
+ if (outcome === 'already')
309
+ return { status: 'already', message: '今日已签到' };
310
+ return signFailure(outcome, '米游社未确认签到成功');
311
+ }
312
+ function signFailure(state, message) {
313
+ if (state === 'verification')
314
+ return { status: 'verification', message: '米游社要求验证,请在官方客户端完成后重试' };
315
+ return { status: 'failed', message: state === 'expired' ? '米游社凭据已失效,请重新配置' : message };
316
+ }
317
+ async function activity(note, target, context) {
318
+ const credentials = session(target.credential);
319
+ if (!credentials.noteReady)
320
+ throw new ProviderError('米游社便笺需要 v2 stoken 和 mid,请检查官方会话凭据', 'unavailable');
321
+ const { roleUid, server } = role(target);
322
+ const deviceId = credentials.deviceId ?? deterministicDeviceId(credentials.uid);
323
+ let deviceFp = credentials.deviceFp;
324
+ if (!deviceFp) {
325
+ deviceFp = await fetchMiyousheDeviceFp(context, deviceId, credentials.activityCookie);
326
+ if (deviceFp)
327
+ await registerMiyousheDevice(context, deviceId, deviceFp, credentials.activityCookie);
328
+ }
329
+ const query = new URLSearchParams({ role_id: roleUid, server }).toString();
330
+ const primaryHeaders = new Headers({
331
+ accept: 'application/json', cookie: credentials.activityCookie, ...note.headers,
332
+ DS: signature(context, noteSalt, String(randomInt(100000, 200000)), '', query),
333
+ });
334
+ optionalDeviceHeaders(primaryHeaders, deviceId, deviceFp);
335
+ let primaryError;
336
+ if (deviceFp) {
337
+ try {
338
+ const response = await readProviderJson(context, `${recordHost}${note.path}?${query}`, { method: 'GET', headers: primaryHeaders });
339
+ const state = businessState(response);
340
+ if (state === 'success') {
341
+ const metrics = note.parse(providerObject(response.data));
342
+ if (!metrics.length)
343
+ throw new ProviderError('米游社未返回可读取的便笺数据', 'unavailable');
344
+ return metrics;
345
+ }
346
+ primaryError = state === 'verification'
347
+ ? new ProviderError('米游社要求验证,请在官方客户端完成后重试', 'verification')
348
+ : new ProviderError('米游社便笺不可用,请检查授权与角色区服', 'unavailable');
349
+ }
350
+ catch (error) {
351
+ context.signal.throwIfAborted();
352
+ if (error instanceof ProviderError && error.message.includes('未返回可读取'))
353
+ throw error;
354
+ primaryError = error instanceof ProviderError ? error : new ProviderError('米游社便笺请求失败', 'failed');
355
+ }
356
+ }
357
+ else {
358
+ primaryError = new ProviderError('米游社便笺需要已授权设备的 ID 和指纹', 'unavailable');
359
+ }
360
+ if (note.widget) {
361
+ const widget = note.widget;
362
+ const widgetHeaders = new Headers({
363
+ accept: 'application/json', cookie: credentials.activityCookie, ...widget.headers,
364
+ });
365
+ if (widget.ds === 'ios-widget') {
366
+ widgetHeaders.set('DS', simpleSignature(context, widgetSalt, randomBytes(3).toString('hex')));
367
+ }
368
+ else if (widget.ds === 'data-empty') {
369
+ widgetHeaders.set('DS', signature(context, signSalt, String(randomInt(100000, 200000)), '', ''));
370
+ }
371
+ else {
372
+ widgetHeaders.set('DS', signature(context, noteSalt, String(randomInt(100000, 200000)), '', ''));
373
+ }
374
+ optionalDeviceHeaders(widgetHeaders, widget.includeDevice ? deviceId : undefined, widget.includeDeviceFp ? deviceFp : undefined);
375
+ try {
376
+ const response = await readProviderJson(context, `${recordHost}${widget.path}`, { method: 'GET', headers: widgetHeaders });
377
+ const state = businessState(response);
378
+ if (state === 'success') {
379
+ const metrics = note.parse(providerObject(response.data));
380
+ if (metrics.length)
381
+ return metrics;
382
+ }
383
+ }
384
+ catch {
385
+ context.signal.throwIfAborted();
386
+ }
387
+ }
388
+ throw primaryError;
389
+ }
390
+ function numberValue(value) {
391
+ const number = typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value) : value;
392
+ return typeof number === 'number' && Number.isSafeInteger(number) && number >= 0 ? number : undefined;
393
+ }
394
+ function metric(label, current, max, recovery) {
395
+ const value = numberValue(current);
396
+ const limit = numberValue(max);
397
+ if (value === undefined || limit === undefined || limit === 0)
398
+ return;
399
+ const seconds = numberValue(recovery);
400
+ const display = `${value} / ${limit}`;
401
+ if (value >= limit || seconds === undefined)
402
+ return { label, value: display };
403
+ return { label, value: `${display} · ${seconds === 0 ? '即将回满' : `约 ${Math.ceil(seconds / 60)} 分钟回满`}` };
404
+ }
405
+ const progressCurrent = ['current', 'cur', 'completed', 'finished', 'finish', 'done', 'currentValue', 'current_value'];
406
+ const progressLimit = ['total', 'target', 'max', 'maxProgress', 'totalCount', 'maxValue', 'max_value'];
407
+ function firstCount(data, keys) {
408
+ for (const key of keys) {
409
+ const value = numberValue(data[key]);
410
+ if (value !== undefined)
411
+ return value;
412
+ }
413
+ }
414
+ function nestedMetric(label, raw, recovery, depth = 0) {
415
+ if (typeof raw === 'string') {
416
+ const parts = raw.split('/');
417
+ if (parts.length === 2)
418
+ return metric(label, parts[0], parts[1], recovery);
419
+ return;
420
+ }
421
+ if (!raw || typeof raw !== 'object' || depth > 8)
422
+ return;
423
+ const data = providerObject(raw);
424
+ return metric(label, firstCount(data, progressCurrent), firstCount(data, progressLimit), recovery)
425
+ ?? nestedMetric(label, data.progress, recovery, depth + 1)
426
+ ?? nestedMetric(label, data.value, recovery, depth + 1);
427
+ }
428
+ function genshinDaily(fields) {
429
+ const label = '每日委托';
430
+ const data = providerObject(fields);
431
+ return nestedMetric(label, fields)
432
+ ?? metric(label, firstCount(data, ['finished_num', 'finished_task_num']), firstCount(data, ['total_num', 'total_task_num']));
433
+ }
434
+ function collect(...values) {
435
+ return values.filter(value => value !== undefined);
436
+ }
437
+ function noteHeaders(version, page) {
438
+ return {
439
+ origin: 'https://webstatic.mihoyo.com', referer: 'https://webstatic.mihoyo.com/', 'x-rpc-client_type': '5',
440
+ 'x-rpc-app_version': '2.99.1', 'x-rpc-tool_version': version, 'x-rpc-page': page,
441
+ 'x-rpc-device_model': 'MI 8 SE', 'x-rpc-device_name': 'Xiaomi MI 8 SE', 'user-agent': bbsUserAgent,
442
+ };
443
+ }
444
+ const games = [
445
+ {
446
+ id: 'genshin', biz: 'hk4e_cn', title: '原神', actId: 'e202311201442471', signgame: 'hk4e',
447
+ serverOptions: [
448
+ { label: '天空岛(官服)', value: 'cn_gf01' },
449
+ { label: '世界树(B服)', value: 'cn_qd01' },
450
+ ],
451
+ note: {
452
+ path: '/game_record/app/genshin/api/dailyNote',
453
+ headers: noteHeaders('v4.2.2-ys', 'v4.2.2-ys_#/ys/daily'),
454
+ widget: {
455
+ path: '/game_record/genshin/aapi/widget/v2',
456
+ ds: 'ios-widget',
457
+ includeDevice: true,
458
+ includeDeviceFp: true,
459
+ headers: {
460
+ referer: 'https://app.mihoyo.com', 'x-rpc-client_type': '1', 'x-rpc-channel': 'appstore',
461
+ 'x-rpc-app_version': '2.99.1', 'x-rpc-device_model': 'MI 8 SE', 'x-rpc-device_name': 'Xiaomi MI 8 SE',
462
+ 'user-agent': bbsUserAgent,
463
+ },
464
+ },
465
+ parse: data => collect(metric('原粹树脂', data.current_resin, data.max_resin, data.resin_recovery_time), genshinDaily(data.daily) ?? genshinDaily(data.daily_task) ?? metric('每日委托', data.finished_task_num, data.total_task_num), metric('洞天宝钱', data.current_home_coin, data.max_home_coin, data.home_coin_recovery_time)),
466
+ },
467
+ },
468
+ {
469
+ id: 'hsr', biz: 'hkrpg_cn', title: '星穹铁道', actId: 'e202304121516551',
470
+ serverOptions: [
471
+ { label: '星穹列车(官服)', value: 'prod_gf_cn' },
472
+ { label: '无名客(B服)', value: 'prod_qd_cn' },
473
+ ],
474
+ note: {
475
+ path: '/game_record/app/hkrpg/api/note',
476
+ headers: noteHeaders('v4.51.1', 'v4.51.1_#/rpg'),
477
+ widget: {
478
+ path: '/game_record/app/hkrpg/aapi/widget',
479
+ ds: 'data-empty',
480
+ headers: {
481
+ referer: 'https://app.mihoyo.com', 'x-rpc-client_type': '2', 'x-rpc-app_version': '2.63.1',
482
+ 'x-rpc-channel': 'appstore', 'x-rpc-device_model': 'iPhone10,2', 'x-rpc-device_name': 'iPhone',
483
+ 'x-rpc-sys_version': '16.2', 'user-agent': 'WidgetExtension/231 CFNetwork/1390 Darwin/22.0.0',
484
+ },
485
+ },
486
+ parse: data => collect(metric('开拓力', data.current_stamina, data.max_stamina, data.stamina_recover_time), nestedMetric('每日实训', data.daily) ?? nestedMetric('每日实训', data.daily_task)
487
+ ?? metric('每日实训', data.current_train_score ?? data.current_training_score, data.max_train_score ?? data.max_training_score), metric('储备开拓力', data.current_reserve_stamina, data.max_reserve_stamina)),
488
+ },
489
+ },
490
+ {
491
+ id: 'zzz', biz: 'nap_cn', title: '绝区零', actId: 'e202406242138391', signgame: 'zzz', base: zzzSignBase,
492
+ serverOptions: [
493
+ { label: '新艾利都(官服)', value: 'prod_gf_cn' },
494
+ { label: 'B服', value: 'prod_qd_cn' },
495
+ ],
496
+ note: {
497
+ path: '/event/game_record_zzz/api/zzz/note',
498
+ headers: {
499
+ origin: 'https://act.mihoyo.com', referer: 'https://act.mihoyo.com/', 'x-rpc-client_type': '2',
500
+ 'x-rpc-app_version': '2.73.1', 'x-rpc-channel': 'mihoyo', 'x-rpc-csm_source': 'myself',
501
+ 'x-rpc-sys_version': '12', 'x-requested-with': 'com.mihoyo.hyperion', 'user-agent': zzzUserAgent,
502
+ },
503
+ widget: {
504
+ path: '/event/game_record_zzz/api/zzz/widget',
505
+ ds: 'record-empty',
506
+ includeDevice: true,
507
+ headers: {
508
+ origin: 'https://webstatic.mihoyo.com', referer: 'https://webstatic.mihoyo.com',
509
+ 'x-rpc-app_version': '2.40.1', 'x-rpc-client_type': '5', 'x-rpc-page': '3.1.3_#/rpg',
510
+ 'x-rpc-language': 'zh-cn', 'x-requested-with': 'com.mihoyo.hyperion',
511
+ 'user-agent': 'WidgetExtension/434 CFNetwork/1492.0.1 Darwin/23.3.0',
512
+ },
513
+ },
514
+ parse: data => {
515
+ const energy = providerObject(data.energy);
516
+ const weekly = providerObject(data.weekly_task);
517
+ return collect(nestedMetric('电量', energy.progress, energy.restore), nestedMetric('今日活跃度', data.vitality), metric('丽都周纪积分', weekly.cur_point, weekly.max_point));
518
+ },
519
+ },
520
+ },
521
+ {
522
+ id: 'bh2', biz: 'bh2_cn', title: '崩坏学园2', actId: 'e202203291431091',
523
+ serverOptions: [
524
+ { label: '国服官服', value: 'gf01' },
525
+ { label: '国服 B 服', value: 'qd01' },
526
+ ],
527
+ },
528
+ {
529
+ id: 'bh3', biz: 'bh3_cn', title: '崩坏3', actId: 'e202306201626331',
530
+ serverOptions: [
531
+ { label: '安卓官服', value: 'android01' },
532
+ { label: 'iOS 官服', value: 'ios01' },
533
+ { label: '渠道服 / B 服', value: 'bb01' },
534
+ ],
535
+ },
536
+ {
537
+ id: 'tot', biz: 'nxx_cn', title: '未定事件簿', actId: 'e202202251749321',
538
+ serverOptions: [
539
+ { label: '国服官服', value: 'cn_prod_gf01' },
540
+ { label: '国服 B 服', value: 'cn_prod_qd01' },
541
+ ],
542
+ },
543
+ ];
544
+ const gamesByBiz = new Map(games.map(game => [game.biz, game]));
545
+ export async function discoverMiyousheRoles(credential, context) {
546
+ let currentCredential = credential;
547
+ let credentials = session(currentCredential);
548
+ let updatedCredential;
549
+ const refreshCookieToken = async () => {
550
+ const derived = await deriveCookieTokenFromStoken(credentials, context);
551
+ if (!derived.token)
552
+ return false;
553
+ currentCredential = validateCredential(serializeSession(credentials, { cookie_token: derived.token, cookie_token_v2: derived.token }));
554
+ credentials = session(currentCredential);
555
+ updatedCredential = currentCredential;
556
+ return true;
557
+ };
558
+ if (!credentials.signReady && credentials.noteReady) {
559
+ await refreshCookieToken();
560
+ }
561
+ const fetchRoles = async () => {
562
+ const headers = new Headers({
563
+ accept: 'application/json, text/plain, */*',
564
+ cookie: credentials.cookie,
565
+ origin: 'https://webstatic.mihoyo.com',
566
+ referer: 'https://act.mihoyo.com/',
567
+ 'x-rpc-client_type': '5',
568
+ 'x-rpc-app_version': '2.99.1',
569
+ 'x-rpc-channel': 'miyousheluodi',
570
+ 'x-requested-with': 'com.mihoyo.hyperion',
571
+ 'user-agent': bbsUserAgent,
572
+ DS: simpleSignature(context, webSalt, randomBytes(3).toString('hex')),
573
+ });
574
+ optionalDeviceHeaders(headers, credentials.deviceId ?? deterministicDeviceId(credentials.uid), credentials.deviceFp);
575
+ return readProviderJson(context, rolesUrl, { method: 'GET', headers });
576
+ };
577
+ let response = await fetchRoles();
578
+ let state = businessState(response);
579
+ if (state === 'expired' && credentials.noteReady && await refreshCookieToken()) {
580
+ response = await fetchRoles();
581
+ state = businessState(response);
582
+ }
583
+ if (state === 'verification')
584
+ throw new ProviderError('米游社角色查询触发风控验证,请在官方客户端检查后重试', 'verification');
585
+ if (state === 'expired')
586
+ throw new ProviderError('米游社凭据已失效,请重新扫码或更新凭据', 'unavailable');
587
+ if (state !== 'success')
588
+ throw new ProviderError('获取米游社绑定角色失败,请稍后重试');
589
+ const rawList = providerObject(response.data).list;
590
+ if (!Array.isArray(rawList))
591
+ return { roles: [], updatedCredential };
592
+ const entries = [];
593
+ for (const item of rawList) {
594
+ const record = providerObject(item);
595
+ if (Array.isArray(record.list)) {
596
+ for (const nested of record.list)
597
+ entries.push(providerObject(nested));
598
+ }
599
+ else {
600
+ entries.push(record);
601
+ }
602
+ }
603
+ const seen = new Set();
604
+ const roles = [];
605
+ for (const item of entries) {
606
+ const biz = typeof item.game_biz === 'string' ? item.game_biz.trim() : '';
607
+ const game = gamesByBiz.get(biz);
608
+ const roleUid = typeof item.game_uid === 'string' ? item.game_uid.trim() : typeof item.gameUid === 'string' ? item.gameUid.trim() : '';
609
+ const server = typeof item.region === 'string' ? item.region.trim() : typeof item.server === 'string' ? item.server.trim() : '';
610
+ if (!game || !roleUid || !server)
611
+ continue;
612
+ const key = `${game.id}:${roleUid}:${server}`;
613
+ if (seen.has(key))
614
+ continue;
615
+ seen.add(key);
616
+ const nickname = typeof item.nickname === 'string' && item.nickname.trim() ? item.nickname.trim() : `${game.title} (${roleUid})`;
617
+ roles.push({ profileId: `miyoushe-${game.id}`, roleUid, server, name: nickname.slice(0, 100) });
618
+ }
619
+ return { roles, updatedCredential };
620
+ }
621
+ export const miyousheProviders = games.map(game => {
622
+ const note = game.note;
623
+ return {
624
+ id: `miyoushe-${game.id}`, title: game.title, platform: '米游社', roleRequired: true, serverRequired: true,
625
+ serverOptions: game.serverOptions,
626
+ serverHint: '请选择该角色所在的国服大区。',
627
+ credentialHint: note
628
+ ? '填写已登录的米游社 Cookie(或直接扫码登录)。签到需要 UID 与 cookie_token;便笺需要 v2 stoken 与 mid。'
629
+ : '填写已登录的米游社 Cookie(或直接扫码登录),需包含登录账号 UID 与 cookie_token。',
630
+ validateCredential, sign: (target, context) => sign(game, target, context),
631
+ activity: note ? (target, context) => activity(note, target, context) : undefined,
632
+ };
633
+ });