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

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,121 @@
1
+ // Request compatibility is based on AUTO-MAS (AGPL-3.0-or-later), Kuro-autosignin,
2
+ // Kuro-API-Collection, Kuro_login and Yunzai-Kuro-Plugin. See AUTO-MAS's provider attribution.
3
+ import { createHash } from 'node:crypto';
4
+ import { ProviderError, providerObject, readProviderJson } from './provider.js';
5
+ const api = 'https://api.kurobbs.com';
6
+ const platform = '库街区';
7
+ const games = [{ id: '2', profile: 'kuro-punishing', title: '战双帕弥什' }, { id: '3', profile: 'kuro-wuthering', title: '鸣潮' }];
8
+ const field = (value) => typeof value === 'string' || typeof value === 'number' ? String(value).trim() : '';
9
+ const visible = /^[\x21-\x7e]{1,4096}$/u;
10
+ function stableDevice(label, token) {
11
+ const digest = createHash('md5').update(Buffer.from('6ba7b8119dad11d180b400c04fd430c8', 'hex')).update(`auto-mas:kuro:${label}:${token}`).digest();
12
+ digest[6] = (digest[6] & 0x0f) | 0x30;
13
+ digest[8] = (digest[8] & 0x3f) | 0x80;
14
+ const value = digest.toString('hex');
15
+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
16
+ }
17
+ function credential(input) {
18
+ let data;
19
+ const raw = input.trim();
20
+ try {
21
+ data = raw.startsWith('{') ? providerObject(JSON.parse(raw)) : { token: raw };
22
+ }
23
+ catch {
24
+ throw new ProviderError('库街区凭据 JSON 格式无效');
25
+ }
26
+ const token = field(data.token);
27
+ if (!visible.test(token))
28
+ throw new ProviderError('请输入已授权的库街区 Token');
29
+ const devCode = field(data.devCode) || stableDevice('devcode', token);
30
+ const distinctId = field(data.distinctId) || stableDevice('distinct', token);
31
+ if (!visible.test(devCode) || !visible.test(distinctId))
32
+ throw new ProviderError('库街区设备标识格式无效');
33
+ return { token, devCode, distinctId };
34
+ }
35
+ export function validateKuroCredential(input) { return JSON.stringify(credential(input)); }
36
+ async function call(raw, path, form, context, allowSigned = false) {
37
+ const { token, devCode, distinctId } = credential(raw);
38
+ const result = await readProviderJson(context, `${api}${path}`, { method: 'POST', body: new URLSearchParams(form), headers: {
39
+ Accept: 'application/json', 'User-Agent': 'okhttp/3.11.0', source: 'android', osversion: 'Android', version: '2.2.0',
40
+ versioncode: '2200', channelid: '1', lang: 'zh-Hans', countrycode: 'CN', token, devcode: devCode, distinct_id: distinctId,
41
+ ...(path.startsWith('/encourage/') ? { Origin: 'https://web-static.kurobbs.com', 'X-Requested-With': 'com.kurogame.kjq' } : {}),
42
+ } });
43
+ const code = field(result.code);
44
+ const message = field(result.msg ?? result.message);
45
+ if ([401, 403, 429].includes(Number(code)) || /安全验证|风控|captcha|challenge|geetest/iu.test(message)) {
46
+ throw new ProviderError('库街区要求安全验证或限制访问,请在官方客户端检查', 'verification');
47
+ }
48
+ if (code === '220' || code === '1513')
49
+ throw new ProviderError('库街区凭据已失效,请重新配置', 'unavailable');
50
+ if (allowSigned && code === '1511')
51
+ return { ...result, already: true };
52
+ if (code !== '200' || result.success === false)
53
+ throw new ProviderError('库街区拒绝了请求,请在官方客户端核对账号状态');
54
+ return { ...result, already: false };
55
+ }
56
+ async function identity(raw, context) {
57
+ const result = await call(raw, '/user/mineV2', {}, context);
58
+ const data = providerObject(result.data);
59
+ const mine = providerObject(data.mine);
60
+ const userId = field(mine.userId ?? data.userId);
61
+ if (!userId)
62
+ throw new ProviderError('库街区未返回有效的用户信息');
63
+ return { userId, name: field(mine.nickName ?? data.nickName) };
64
+ }
65
+ function roleRows(value) {
66
+ if (Array.isArray(value))
67
+ return value.flatMap(roleRows);
68
+ const data = providerObject(value);
69
+ if (field(data.roleId ?? data.role_id ?? data.roleID))
70
+ return [data];
71
+ for (const key of ['roles', 'roleList', 'role_list', 'list', 'data', 'roleInfo', 'role']) {
72
+ if (Object.hasOwn(data, key))
73
+ return roleRows(data[key]);
74
+ }
75
+ return [];
76
+ }
77
+ export async function discoverKuroRoles(raw, context) {
78
+ const { userId, name } = await identity(raw, context);
79
+ const roles = [{ profileId: 'kuro-community', roleUid: '', server: '', name: name ? `${name} · 社区打卡` : '库街区社区打卡' }];
80
+ for (const game of games) {
81
+ const result = await call(raw, '/user/role/findRoleList', { userId, gameId: game.id }, context);
82
+ for (const row of roleRows(result.data)) {
83
+ const reportedGame = field(row.gameId ?? row.game_id ?? row.gameID);
84
+ const roleUid = field(row.roleId ?? row.role_id ?? row.roleID);
85
+ const server = field(row.serverId ?? row.server_id);
86
+ if ((reportedGame && reportedGame !== game.id) || !roleUid || !server)
87
+ continue;
88
+ roles.push({ profileId: game.profile, roleUid, server, name: field(row.roleName ?? row.role_name) || game.title });
89
+ }
90
+ }
91
+ return { roles };
92
+ }
93
+ const credentialHint = '填写本人已授权的库街区 Token,或含 token、devCode、distinctId 的凭据 JSON。';
94
+ const base = { platform, credentialHint, validateCredential: validateKuroCredential };
95
+ const gameMonth = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Shanghai', month: '2-digit' });
96
+ function outcome(result) {
97
+ const data = providerObject(result.data);
98
+ const name = field(data.rewardName);
99
+ const reward = name ? `${name} × ${field(data.rewardCnt) || '1'}` : '';
100
+ return { status: result.already ? 'already' : 'success', message: [result.already ? '今天已签到' : '签到成功', reward].filter(Boolean).join(' · ') };
101
+ }
102
+ export const kuroProviders = [
103
+ { ...base, id: 'kuro-community', title: '库街区社区打卡', async sign(target, context) {
104
+ const result = await call(target.credential, '/user/signIn', { gameId: '2' }, context, true);
105
+ const data = providerObject(result.data);
106
+ const gains = Array.isArray(data.gainVoList) ? data.gainVoList.map(providerObject) : [];
107
+ const coins = gains.filter(item => field(item.gainTyp) === '2').map(item => Number(item.gainValue)).filter(Number.isSafeInteger)
108
+ .reduce((total, amount) => total + amount, 0);
109
+ const status = outcome(result);
110
+ return coins ? { ...status, message: `${status.message} · 库洛币 × ${coins}` } : status;
111
+ } },
112
+ ...games.map(game => ({ ...base, id: game.profile, title: game.title, roleRequired: true, serverRequired: true,
113
+ serverHint: '填写库街区角色的区服 ID,或一键同步绑定角色。', async sign(target, context) {
114
+ const { userId } = await identity(target.credential, context);
115
+ const result = await call(target.credential, '/encourage/signIn/v2', {
116
+ userId, gameId: game.id, roleId: target.roleUid ?? '', serverId: target.server ?? '', reqMonth: gameMonth.format(context.now),
117
+ }, context, true);
118
+ return outcome(result);
119
+ },
120
+ })),
121
+ ];
@@ -0,0 +1,108 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { providerObject, readProviderJson } from './provider.js';
3
+ const deviceFpUrl = 'https://public-data-api.mihoyo.com/device-fp/api/getFp';
4
+ const deviceLoginUrl = 'https://bbs-api.mihoyo.com/apihub/api/deviceLogin';
5
+ const deviceSaveUrl = 'https://bbs-api.mihoyo.com/apihub/api/saveDevice';
6
+ 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';
7
+ const signSalt = 't0qEgfub6cvueAPgR5m9aQWWVciEer7v';
8
+ const deviceModel = 'MI 8 SE';
9
+ const deviceName = 'Xiaomi MI 8 SE';
10
+ function stringField(value) {
11
+ return typeof value === 'string' ? value.trim() : typeof value === 'number' && Number.isFinite(value) ? String(value) : '';
12
+ }
13
+ function isZeroRetcode(value) {
14
+ return value === 0 || value === '0';
15
+ }
16
+ export function deterministicDeviceId(seed) {
17
+ const hash = createHash('sha256').update(`auto-masc:miyoushe:device:${seed}`, 'utf8').digest('hex');
18
+ return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-4${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`.toUpperCase();
19
+ }
20
+ export async function fetchMiyousheDeviceFp(context, deviceId, cookie) {
21
+ const seedId = randomBytes(8).toString('hex');
22
+ const seedFp = randomBytes(7).toString('hex').slice(0, 13);
23
+ const extFields = {
24
+ userAgent: bbsUserAgent,
25
+ browserScreenSize: 243750,
26
+ maxTouchPoints: 5,
27
+ isTouchSupported: true,
28
+ browserLanguage: 'zh-CN',
29
+ browserPlat: 'Linux armv8l',
30
+ browserTimeZone: 'Asia/Shanghai',
31
+ webGlRender: 'Adreno (TM) 640',
32
+ webGlVendor: 'Qualcomm',
33
+ numOfPlugins: 0,
34
+ listOfPlugins: 'unknown',
35
+ screenRatio: 3,
36
+ deviceMemory: '4',
37
+ hardwareConcurrency: '8',
38
+ cpuClass: 'unknown',
39
+ ifNotTrack: 'unknown',
40
+ ifAdBlock: 0,
41
+ hasLiedResolution: 1,
42
+ hasLiedOs: 0,
43
+ hasLiedBrowser: 0,
44
+ };
45
+ const body = JSON.stringify({
46
+ seed_id: seedId,
47
+ device_id: deviceId.toLowerCase(),
48
+ platform: '5',
49
+ seed_time: String(context.now.getTime()),
50
+ ext_fields: JSON.stringify(extFields),
51
+ app_name: 'account_cn',
52
+ device_fp: seedFp,
53
+ });
54
+ try {
55
+ const headers = { 'content-type': 'application/json', 'user-agent': bbsUserAgent };
56
+ if (cookie)
57
+ headers.cookie = cookie;
58
+ const payload = await readProviderJson(context, deviceFpUrl, { method: 'POST', headers, body });
59
+ if (!isZeroRetcode(payload.retcode))
60
+ return;
61
+ const fp = stringField(providerObject(payload.data).device_fp);
62
+ if (fp && /^[A-Za-z0-9_-]{6,128}$/.test(fp))
63
+ return fp;
64
+ }
65
+ catch {
66
+ context.signal.throwIfAborted();
67
+ }
68
+ }
69
+ export async function registerMiyousheDevice(context, deviceId, deviceFp, cookie) {
70
+ const baseData = {
71
+ app_version: '2.99.1',
72
+ device_id: deviceId,
73
+ device_name: deviceName,
74
+ os_version: '30',
75
+ platform: 'Android',
76
+ };
77
+ const baseHeaders = {
78
+ cookie,
79
+ 'x-rpc-client_type': '2',
80
+ 'x-rpc-app_version': '2.99.1',
81
+ 'x-rpc-sys_version': '12',
82
+ 'x-rpc-channel': 'miyousheluodi',
83
+ 'x-rpc-device_id': deviceId,
84
+ 'x-rpc-device_name': deviceName,
85
+ 'x-rpc-device_model': deviceModel,
86
+ 'x-rpc-device_fp': deviceFp,
87
+ referer: 'https://app.mihoyo.com',
88
+ 'content-type': 'application/json; charset=UTF-8',
89
+ 'user-agent': 'okhttp/4.9.3',
90
+ };
91
+ for (const url of [deviceLoginUrl, deviceSaveUrl]) {
92
+ try {
93
+ const registrationId = randomBytes(10).toString('hex').slice(0, 19);
94
+ const body = JSON.stringify({ ...baseData, registration_id: registrationId });
95
+ const timestamp = Math.floor(context.now.getTime() / 1000);
96
+ const nonce = randomBytes(3).toString('hex');
97
+ const digest = createHash('md5').update(`salt=${signSalt}&t=${timestamp}&r=${nonce}&b=${body}&q=`).digest('hex');
98
+ await readProviderJson(context, url, {
99
+ method: 'POST',
100
+ headers: { ...baseHeaders, DS: `${timestamp},${nonce},${digest}` },
101
+ body,
102
+ });
103
+ }
104
+ catch {
105
+ context.signal.throwIfAborted();
106
+ }
107
+ }
108
+ }