script_task.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. # This Python file uses the following encoding: utf-8
  2. import subprocess
  3. import tempfile
  4. import threading
  5. import lzma
  6. import os
  7. import sys
  8. import time
  9. import json
  10. import random
  11. # 直接运行本脚本时,需要先将项目根目录加入 Python 路径
  12. if __name__ == '__main__' and 'tasks' not in sys.modules:
  13. sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
  14. import requests
  15. import urllib3
  16. from tasks.base_task import BaseTask
  17. from module.logger import logger
  18. from module.exception import TaskEnd
  19. try:
  20. from oas_checkin_biggod import FRIDA_SERVER_XZ, ADB_PATH
  21. except ImportError:
  22. raise ImportError(
  23. "oas-checkin-biggod is not installed. "
  24. "Run: ./toolkit/python.exe -m pip install oas-checkin-biggod"
  25. )
  26. urllib3.disable_warnings()
  27. os.environ['MSYS_NO_PATHCONV'] = '1'
  28. WELFARE_BASE = "https://god-welfare.gameyw.netease.com"
  29. LOGIN_BASE = "https://god.gameyw.netease.com"
  30. GL_PACKAGE = "com.netease.gl"
  31. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  32. FRIDA_SERVER_LOCAL = os.path.join(SCRIPT_DIR, "frida-server-17.6.2-android-x86_64")
  33. FRIDA_SERVER_REMOTE = "/data/local/tmp/frida-server"
  34. APP_KEY = "g37"
  35. GL_VERSION = "4.12.0" # 默认值,运行时会从APP动态获取
  36. GL_CLIENTTYPE = "50"
  37. _NO_WINDOW = subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
  38. class ScriptTask(BaseTask):
  39. def run(self):
  40. self.gl_uid = ""
  41. self.gl_token = ""
  42. self.gl_deviceid = ""
  43. self.gl_source = "URS"
  44. self.gl_version = GL_VERSION
  45. self.role_id = ""
  46. self.server = ""
  47. self.app_key = APP_KEY
  48. self.frida_pid = None
  49. self._frida_session = None # 常驻 frida.exe 子进程
  50. self._frida_attached_pid = None # REPL 当前 attach 的 PID
  51. self.session = requests.Session()
  52. self.session.verify = False
  53. logger.hr('AutoCheckinBigGod', level=1)
  54. # [1/5] 检查运行环境
  55. logger.info('[1/5] 检查运行环境...')
  56. if not self._check_adb_connection():
  57. logger.error('未检测到ADB设备,请确保模拟器已启动并已连接ADB')
  58. self.set_next_run('AutoCheckinBigGod', success=False, finish=True)
  59. raise TaskEnd('AutoCheckinBigGod')
  60. logger.info('ADB已连接')
  61. if not self._ensure_frida_server_running():
  62. logger.error('Frida Server启动失败,请检查模拟器环境')
  63. self.set_next_run('AutoCheckinBigGod', success=False, finish=True)
  64. raise TaskEnd('AutoCheckinBigGod')
  65. logger.info('Frida Server运行中')
  66. # [2/5] 启动大神APP
  67. logger.info('[2/5] 启动大神APP...')
  68. pid = self._launch_app()
  69. if not pid:
  70. logger.error('无法启动大神APP,请确保模拟器中已安装大神APP')
  71. self.set_next_run('AutoCheckinBigGod', success=False, finish=True)
  72. raise TaskEnd('AutoCheckinBigGod')
  73. self.frida_pid = pid
  74. logger.info(f'大神APP已运行 (PID: {pid})')
  75. # [3/5] 获取Token
  76. logger.info('[3/5] 获取Token...')
  77. # 优先通过 ADB 读取 auth 数据库 + HTTP API 登录(速度快)
  78. token_data = None
  79. new_pid, login_token = self._auto_login(pid)
  80. if new_pid:
  81. pid = new_pid
  82. self.frida_pid = pid
  83. if login_token:
  84. token_data = login_token
  85. # 回退:从内存提取(数据库无数据时)
  86. if not token_data:
  87. logger.warning('自动登录失败,尝试从内存提取Token...')
  88. token_data = self._try_extract_token(pid)
  89. if not token_data:
  90. logger.error('无法获取Token,请确保已登录大神APP并绑定阴阳师角色')
  91. self.set_next_run('AutoCheckinBigGod', success=False, finish=True)
  92. raise TaskEnd('AutoCheckinBigGod')
  93. self.gl_uid = token_data.get('GL_UID', '')
  94. self.gl_token = token_data.get('GL_TOKEN', '')
  95. self.gl_deviceid = token_data.get('GL_DEVICEID', '')
  96. self.gl_source = token_data.get('GL_SOURCE', 'URS')
  97. if token_data.get('GL_VERSION'):
  98. self.gl_version = token_data['GL_VERSION']
  99. logger.info(f'APP版本: {self.gl_version}')
  100. logger.info(f'Token获取成功! 用户ID: {self.gl_uid[:16]}...')
  101. # Token已获取,将大神APP切到后台,减少对用户的干扰
  102. try:
  103. self._adb_shell(['input', 'keyevent', 'KEYCODE_HOME'])
  104. except Exception:
  105. pass
  106. # 通过API获取角色信息
  107. logger.info('通过API获取角色信息...')
  108. role_info = self._get_role_info()
  109. if role_info:
  110. self.role_id = role_info.get('roleId', '')
  111. self.server = role_info.get('server', '')
  112. logger.info(f'角色信息: {self.role_id} @ {self.server}')
  113. else:
  114. logger.warning('未能获取角色信息,请确保已在大神APP中绑定阴阳师角色')
  115. # [4/5] 获取礼包列表
  116. logger.info('[4/5] 获取礼包列表...')
  117. rewards = self._get_rewards()
  118. if not rewards:
  119. logger.info('没有可领取的礼包')
  120. self._cleanup(restore_game=True)
  121. self.set_next_run('AutoCheckinBigGod', success=True, finish=True)
  122. raise TaskEnd('AutoCheckinBigGod')
  123. # [5/5] 领取礼包
  124. logger.info(f'[5/5] 领取 {len(rewards)} 个礼包...')
  125. success_count = 0
  126. for r in rewards:
  127. if self._claim_reward(r['id'], r['title']):
  128. success_count += 1
  129. time.sleep(0.5)
  130. logger.info(f'完成! 成功领取 {success_count}/{len(rewards)} 个礼包')
  131. self._cleanup(restore_game=True)
  132. self.set_next_run('AutoCheckinBigGod', success=True, finish=True)
  133. raise TaskEnd('AutoCheckinBigGod')
  134. # ======================== 清理 ========================
  135. def _cleanup(self, restore_game=False):
  136. logger.info('清理:关闭大神APP和Frida Server...')
  137. try:
  138. if self._frida_session is not None:
  139. self._frida_session.kill()
  140. except Exception:
  141. pass
  142. self._frida_session = None
  143. self._frida_attached_pid = None
  144. try:
  145. self._adb_shell(['am', 'force-stop', GL_PACKAGE])
  146. except Exception:
  147. pass
  148. try:
  149. self._adb_shell(['su -c "killall frida-server"'])
  150. except Exception:
  151. pass
  152. if restore_game:
  153. try:
  154. self.device.app_start()
  155. logger.info('已返回阴阳师前台')
  156. except Exception as e:
  157. logger.warning(f'返回阴阳师失败: {e}')
  158. # ======================== ADB 操作 ========================
  159. def _adb_cmd(self, args, timeout=10):
  160. # 如果有设备序列号且命令不是 connect/devices,则添加 -s 参数指定设备
  161. cmd = [ADB_PATH]
  162. if hasattr(self, '_adb_serial') and self._adb_serial and args[0] not in ['connect', 'devices']:
  163. cmd.extend(['-s', self._adb_serial])
  164. cmd.extend(args)
  165. result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
  166. creationflags=_NO_WINDOW)
  167. return result.stdout.strip()
  168. def _adb_shell(self, cmd, timeout=15):
  169. return self._adb_cmd(['shell'] + cmd, timeout=timeout)
  170. def _get_app_pid(self):
  171. try:
  172. output = self._adb_shell(['pidof', GL_PACKAGE])
  173. if output:
  174. return int(output.split()[0])
  175. except Exception as e:
  176. logger.warning(f'获取PID失败: {e}')
  177. return None
  178. def _launch_app(self):
  179. """启动大神APP。如果已在运行则直接返回PID,不会force-stop。"""
  180. try:
  181. # 先检查是否已在运行
  182. pid = self._get_app_pid()
  183. if pid:
  184. logger.info('大神APP已在运行,无需重启')
  185. return pid
  186. # 优先通过 ContentProvider 后台启动(不显示UI,需要 su 权限)
  187. logger.info('后台启动大神APP进程...')
  188. try:
  189. subprocess.run(
  190. [ADB_PATH] + (['-s', self._adb_serial] if getattr(self, '_adb_serial', None) else []) +
  191. ['shell', 'su', '0', 'content', 'query', '--uri',
  192. f'content://{GL_PACKAGE}.utilcode.provider/'],
  193. capture_output=True, timeout=20, creationflags=_NO_WINDOW
  194. )
  195. except subprocess.TimeoutExpired:
  196. pass
  197. # 等待进程启动
  198. for _ in range(10):
  199. time.sleep(2)
  200. pid = self._get_app_pid()
  201. if pid:
  202. return pid
  203. # 后台启动失败,用 monkey 前台启动后立即按 HOME 切回后台
  204. logger.info('后台启动失败,前台启动后切回后台...')
  205. self._adb_shell([
  206. 'monkey', '-p', GL_PACKAGE,
  207. '-c', 'android.intent.category.LAUNCHER', '1'
  208. ])
  209. for _ in range(15):
  210. time.sleep(2)
  211. pid = self._get_app_pid()
  212. if pid:
  213. # 立即按 HOME 键切到后台
  214. try:
  215. self._adb_shell(['input', 'keyevent', 'KEYCODE_HOME'])
  216. except Exception:
  217. pass
  218. return pid
  219. return None
  220. except Exception as e:
  221. logger.warning(f'启动APP失败: {e}')
  222. return None
  223. # ======================== Frida Server 管理 ========================
  224. def _check_adb_connection(self):
  225. try:
  226. serial = str(self.config.script.device.serial)
  227. if serial and serial != 'auto':
  228. logger.info(f'专用ADB连接到 {serial}...')
  229. result = self._adb_cmd(['connect', serial], timeout=10)
  230. if 'connected' not in result.lower() and 'already connected' not in result.lower():
  231. logger.warning(f'ADB连接失败: {result}')
  232. return False
  233. # 保存设备序列号,用于后续命令指定设备
  234. # adb connect 不带端口时会自动补 :5555,需要从 devices 列表中获取实际名称
  235. # 因为 Frida -D 参数需要精确匹配 adb devices 中的设备名
  236. self._adb_serial = serial
  237. else:
  238. self._adb_serial = None
  239. output = self._adb_cmd(['devices'])
  240. lines = [l for l in output.strip().split('\n')[1:] if l.strip() and '\tdevice' in l]
  241. if len(lines) == 0:
  242. logger.warning('未检测到任何设备')
  243. return False
  244. # 从 adb devices 输出中获取实际的设备 serial(可能带端口号)
  245. # 例如用户配置 192.168.1.66,adb devices 中显示 192.168.1.66:5555
  246. if self._adb_serial:
  247. for l in lines:
  248. actual_serial = l.split('\t')[0].strip()
  249. if actual_serial.startswith(self._adb_serial):
  250. if actual_serial != self._adb_serial:
  251. logger.info(f'设备实际名称: {actual_serial}')
  252. self._adb_serial = actual_serial
  253. break
  254. # 如果没有指定 serial 且只有一个设备,自动使用该设备
  255. if not self._adb_serial and len(lines) == 1:
  256. device_line = lines[0].split('\t')[0]
  257. self._adb_serial = device_line.strip()
  258. logger.info(f'自动使用设备: {self._adb_serial}')
  259. return True
  260. except Exception as e:
  261. logger.warning(f'ADB连接检查失败: {e}')
  262. return False
  263. def _is_frida_server_running(self):
  264. try:
  265. output = self._adb_shell(['ps | grep frida-server'])
  266. if 'frida-server' not in output:
  267. return False
  268. # 确保是以 root 身份运行,否则无法 attach 进程
  269. for line in output.strip().split('\n'):
  270. if 'frida-server' in line and 'grep' not in line:
  271. if line.strip().startswith('root'):
  272. return True
  273. # frida-server 存在但不是 root 运行,杀掉重启
  274. logger.warning('Frida Server未以root运行,正在重启...')
  275. try:
  276. self._adb_shell(['killall', 'frida-server'])
  277. except Exception:
  278. pass
  279. return False
  280. except Exception:
  281. return False
  282. def _is_frida_server_installed(self):
  283. try:
  284. output = self._adb_shell(['ls', '-l', FRIDA_SERVER_REMOTE])
  285. return 'No such file' not in output and FRIDA_SERVER_REMOTE in output
  286. except Exception:
  287. return False
  288. def _ensure_frida_local(self):
  289. if os.path.exists(FRIDA_SERVER_LOCAL):
  290. return True
  291. if not os.path.exists(FRIDA_SERVER_XZ):
  292. logger.error(f'找不到Frida Server压缩文件: {FRIDA_SERVER_XZ}')
  293. return False
  294. logger.info('解压Frida Server...')
  295. try:
  296. with lzma.open(FRIDA_SERVER_XZ, 'rb') as f_in:
  297. with open(FRIDA_SERVER_LOCAL, 'wb') as f_out:
  298. f_out.write(f_in.read())
  299. logger.info('Frida Server解压完成')
  300. return True
  301. except Exception as e:
  302. logger.error(f'解压失败: {e}')
  303. return False
  304. def _push_frida_server(self):
  305. if not self._ensure_frida_local():
  306. return False
  307. logger.info('推送Frida Server到模拟器...')
  308. try:
  309. # 先删除旧文件(如果存在)
  310. try:
  311. self._adb_shell(['rm', '-f', FRIDA_SERVER_REMOTE])
  312. except:
  313. pass
  314. # 推送文件
  315. self._adb_cmd(['push', FRIDA_SERVER_LOCAL, FRIDA_SERVER_REMOTE], timeout=60)
  316. # 验证推送是否成功(检查文件大小)
  317. local_size = os.path.getsize(FRIDA_SERVER_LOCAL)
  318. remote_check = self._adb_shell(['ls', '-l', FRIDA_SERVER_REMOTE])
  319. if 'No such file' in remote_check:
  320. logger.error('推送失败: 文件未找到')
  321. return False
  322. # 从 ls -l 输出提取文件大小(格式如:-rwxr-xr-x 1 root root 105123456 ...)
  323. try:
  324. parts = remote_check.split()
  325. if len(parts) >= 5:
  326. remote_size = int(parts[4])
  327. if remote_size != local_size:
  328. logger.error(f'推送失败: 文件大小不匹配 (本地: {local_size}, 远程: {remote_size})')
  329. return False
  330. except:
  331. pass
  332. self._adb_shell(['chmod', '755', FRIDA_SERVER_REMOTE])
  333. logger.info('Frida Server推送完成')
  334. return True
  335. except subprocess.TimeoutExpired:
  336. logger.error('推送超时,请检查网络连接和模拟器状态')
  337. return False
  338. except Exception as e:
  339. logger.error(f'推送失败: {e}')
  340. return False
  341. def _start_frida_server(self):
  342. logger.info('启动Frida Server...')
  343. # 使用 su + nohup 以 root 身份后台启动,否则无权 attach 其他进程
  344. # 将 stdout/stderr 重定向到 /dev/null 避免阻塞
  345. start_cmd = f'su -c "nohup {FRIDA_SERVER_REMOTE} > /dev/null 2>&1 &"'
  346. try:
  347. self._adb_shell([start_cmd], timeout=5)
  348. except subprocess.TimeoutExpired:
  349. # su 启动可能超时,但进程已经在后台运行了
  350. pass
  351. except Exception:
  352. pass
  353. # 轮询检测启动状态,最多等10秒
  354. for _ in range(5):
  355. time.sleep(2)
  356. if self._is_frida_server_running():
  357. logger.info('Frida Server已启动')
  358. return True
  359. logger.error('Frida Server启动失败,请确保模拟器已开启Root模式')
  360. return False
  361. def _ensure_frida_server_running(self):
  362. if self._is_frida_server_running():
  363. return True
  364. if not self._is_frida_server_installed():
  365. if not self._push_frida_server():
  366. return False
  367. return self._start_frida_server()
  368. # ======================== Frida 脚本执行 ========================
  369. def _get_frida_exe(self):
  370. """获取 frida 可执行文件路径"""
  371. python_dir = os.path.dirname(sys.executable)
  372. frida_exe = os.path.join(python_dir, 'Scripts', 'frida.exe')
  373. if os.path.exists(frida_exe):
  374. return frida_exe
  375. # 回退:依赖 PATH
  376. return 'frida'
  377. def _ensure_frida_repl(self, pid):
  378. """确保有一个常驻的 frida REPL 进程 attach 到目标 PID。
  379. 首次调用启动进程(~3-5秒),后续调用直接复用。
  380. 如果 PID 变了(APP重启),则关闭旧进程并重新 attach。
  381. """
  382. if self._frida_session is not None:
  383. if self._frida_session.poll() is None:
  384. # PID 没变,直接复用
  385. if self._frida_attached_pid == pid:
  386. return self._frida_session
  387. # PID 变了,需要重新 attach
  388. logger.info(f'目标PID变更 ({self._frida_attached_pid} -> {pid}),重新attach...')
  389. try:
  390. self._frida_session.kill()
  391. except Exception:
  392. pass
  393. else:
  394. logger.warning('Frida REPL 进程已退出,重新启动...')
  395. self._frida_session = None
  396. self._frida_attached_pid = None
  397. frida_exe = self._get_frida_exe()
  398. if hasattr(self, '_adb_serial') and self._adb_serial:
  399. cmd = [frida_exe, '-D', self._adb_serial, '-p', str(pid)]
  400. else:
  401. cmd = [frida_exe, '-U', '-p', str(pid)]
  402. try:
  403. proc = subprocess.Popen(
  404. cmd,
  405. stdin=subprocess.PIPE,
  406. stdout=subprocess.PIPE,
  407. stderr=subprocess.STDOUT,
  408. creationflags=_NO_WINDOW,
  409. )
  410. self._frida_session = proc
  411. # 等待 frida attach 完成后再发 ping
  412. # frida.exe 启动到可接受 JS 输入通常需要 3-5 秒
  413. for wait_sec in (3, 3, 4):
  414. time.sleep(wait_sec)
  415. if proc.poll() is not None:
  416. out = proc.stdout.read().decode('utf-8', errors='ignore')
  417. logger.warning(f'Frida REPL 进程提前退出: {out[:300]}')
  418. self._frida_session = None
  419. return None
  420. # 直接向 stdin 写 ping,不走 _run_frida_script 避免副作用
  421. if self._ping_frida_repl(proc):
  422. self._frida_attached_pid = pid
  423. logger.info('Frida REPL 已就绪')
  424. return proc
  425. logger.info('Frida REPL 尚未就绪,继续等待...')
  426. # 所有重试都失败
  427. logger.warning('Frida REPL 启动超时')
  428. try:
  429. proc.kill()
  430. except Exception:
  431. pass
  432. self._frida_session = None
  433. return None
  434. except Exception as e:
  435. logger.warning(f'启动Frida REPL失败: {e}')
  436. self._frida_session = None
  437. return None
  438. def _ping_frida_repl(self, proc, timeout=8):
  439. """向 frida REPL 发送 ping 并等待回显,验证 REPL 已就绪。
  440. 直接操作 proc 的 stdin/stdout,不经过 _run_frida_script。
  441. 返回 True/False。
  442. """
  443. # 使用唯一标记避免多次重试时 reader 线程之间的竞争
  444. marker = f'__PING_{id(proc)}_{time.monotonic_ns()}__'
  445. ping_js = f'console.log("{marker}"); console.log("__DONE__");\n'
  446. try:
  447. proc.stdin.write(ping_js.encode('utf-8'))
  448. proc.stdin.flush()
  449. except (BrokenPipeError, OSError):
  450. return False
  451. got_ready = False
  452. def _read():
  453. nonlocal got_ready
  454. try:
  455. while True:
  456. raw = proc.stdout.readline()
  457. if not raw:
  458. break
  459. line = raw.decode('utf-8', errors='ignore').strip()
  460. # 跳过 REPL 回显行(包含 ]-> ),避免 JS 代码中的标记被误判
  461. if ']->' in line:
  462. continue
  463. if marker in line:
  464. got_ready = True
  465. if '__DONE__' in line:
  466. break
  467. except Exception:
  468. pass
  469. reader = threading.Thread(target=_read, daemon=True)
  470. reader.start()
  471. reader.join(timeout=timeout)
  472. return got_ready
  473. def _run_frida_script(self, pid, script_content, timeout=10):
  474. """通过常驻 frida.exe REPL 子进程执行 JS 脚本,返回 console.log 输出。
  475. 首次调用自动启动 REPL(~3-5秒),后续调用复用同一进程(~毫秒级)。
  476. 脚本必须在最后一步打印 __DONE__ 来标记执行完成。
  477. """
  478. # 确保 REPL 进程存活
  479. if self._frida_session is None or self._frida_session.poll() is not None:
  480. if not self._ensure_frida_repl(pid):
  481. logger.warning('无法建立Frida REPL连接,回退到单次执行模式')
  482. return self._run_frida_script_oneshot(pid, script_content, timeout)
  483. proc = self._frida_session
  484. try:
  485. # 写入 stdin — 将多行 JS 压成单行(frida REPL 按行执行)
  486. line = script_content.replace('\n', ' ').replace('\r', '') + '\n'
  487. proc.stdin.write(line.encode('utf-8'))
  488. proc.stdin.flush()
  489. except (BrokenPipeError, OSError) as e:
  490. logger.warning(f'Frida REPL stdin写入失败: {e}')
  491. self._frida_session = None
  492. return self._run_frida_script_oneshot(pid, script_content, timeout)
  493. # 从 stdout 读取直到看到 __DONE__ 标记或超时
  494. output_lines = []
  495. timed_out = threading.Event()
  496. def _read_until_done():
  497. try:
  498. while True:
  499. if timed_out.is_set():
  500. break
  501. raw = proc.stdout.readline()
  502. if not raw:
  503. break
  504. line_decoded = raw.decode('utf-8', errors='ignore').rstrip('\n').rstrip('\r')
  505. # 先过滤 REPL 回显行(包含 ]-> ),避免 JS 代码中的标记被误判
  506. if ']->' in line_decoded:
  507. continue
  508. if '__DONE__' in line_decoded:
  509. break
  510. if line_decoded.strip():
  511. output_lines.append(line_decoded)
  512. except Exception:
  513. pass
  514. reader = threading.Thread(target=_read_until_done, daemon=True)
  515. reader.start()
  516. reader.join(timeout=timeout)
  517. if reader.is_alive():
  518. timed_out.set()
  519. logger.warning(f'Frida REPL 读取超时 ({timeout}s)')
  520. return '\n'.join(output_lines) if output_lines else ''
  521. def _run_frida_script_oneshot(self, pid, script_content, timeout=10):
  522. """回退方案:每次启动新 frida.exe 进程执行单个脚本"""
  523. with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as f:
  524. f.write(script_content)
  525. script_path = f.name
  526. try:
  527. frida_exe = self._get_frida_exe()
  528. if hasattr(self, '_adb_serial') and self._adb_serial:
  529. frida_cmd = [frida_exe, '-D', self._adb_serial, '-p', str(pid), '-l', script_path, '-q']
  530. else:
  531. frida_cmd = [frida_exe, '-U', '-p', str(pid), '-l', script_path, '-q']
  532. process = subprocess.Popen(
  533. frida_cmd,
  534. stdin=subprocess.PIPE,
  535. stdout=subprocess.PIPE,
  536. stderr=subprocess.PIPE,
  537. creationflags=_NO_WINDOW,
  538. )
  539. time.sleep(2)
  540. process.stdin.close()
  541. try:
  542. stdout_bytes, stderr_bytes = process.communicate(timeout=timeout)
  543. except subprocess.TimeoutExpired:
  544. process.kill()
  545. stdout_bytes, stderr_bytes = process.communicate()
  546. stdout = stdout_bytes.decode('utf-8', errors='ignore') if stdout_bytes else ''
  547. stderr = stderr_bytes.decode('utf-8', errors='ignore') if stderr_bytes else ''
  548. return stdout + stderr
  549. except Exception as e:
  550. logger.warning(f'Frida脚本执行失败: {e}')
  551. return None
  552. finally:
  553. try:
  554. os.unlink(script_path)
  555. except:
  556. pass
  557. def _try_extract_token(self, pid):
  558. """尝试多次从内存提取 Token(GL_UID/GL_TOKEN/GL_DEVICEID),返回 dict 或 None。"""
  559. for attempt in range(1, 4):
  560. token_data = self._extract_token(pid)
  561. if token_data:
  562. return token_data
  563. logger.warning(f'第{attempt}次获取Token失败,等待3秒后重试...')
  564. if attempt < 3:
  565. time.sleep(3)
  566. new_pid = self._get_app_pid()
  567. if new_pid:
  568. pid = new_pid
  569. self.frida_pid = pid
  570. return None
  571. def _extract_token(self, pid):
  572. """通过 Frida 从内存中提取 GL 认证信息(UID/Token/DeviceId/Source)"""
  573. script = """
  574. Java.perform(function() {
  575. try {
  576. var YXFDeviceInfo = Java.use('com.netease.gl.glbase.build.YXFDeviceInfo');
  577. console.log('GL_DEVICEID:' + YXFDeviceInfo.getDeviceId());
  578. } catch(e) {}
  579. Java.choose('com.netease.gl.serviceaccount.proto.auth.GLAuth$Authed', {
  580. onMatch: function(instance) {
  581. var uid = instance.getUid();
  582. var token = instance.getToken();
  583. var source = instance.getSource();
  584. if (uid && token) {
  585. console.log('GL_UID:' + uid);
  586. console.log('GL_TOKEN:' + token);
  587. console.log('GL_SOURCE:' + source);
  588. }
  589. },
  590. onComplete: function() {
  591. console.log('__DONE__');
  592. }
  593. });
  594. });
  595. """
  596. output = self._run_frida_script(pid, script, timeout=15)
  597. if not output:
  598. logger.warning('Frida脚本无输出')
  599. return None
  600. data = {}
  601. for line in output.split('\n'):
  602. if 'GL_UID:' in line:
  603. data['GL_UID'] = line.split('GL_UID:')[1].strip()
  604. elif 'GL_TOKEN:' in line and 'GL_TOKEN' not in data:
  605. data['GL_TOKEN'] = line.split('GL_TOKEN:')[1].strip()
  606. elif 'GL_DEVICEID:' in line:
  607. data['GL_DEVICEID'] = line.split('GL_DEVICEID:')[1].strip()
  608. elif 'GL_SOURCE:' in line:
  609. data['GL_SOURCE'] = line.split('GL_SOURCE:')[1].strip()
  610. if data.get('GL_UID') and data.get('GL_TOKEN'):
  611. # 版本号通过 ADB 获取
  612. version = self._get_app_version()
  613. if version:
  614. data['GL_VERSION'] = version
  615. return data
  616. return None
  617. def _frida_sign(self, url, body, headers=None):
  618. if not self.frida_pid:
  619. self.frida_pid = self._get_app_pid()
  620. if not self.frida_pid:
  621. logger.error('无法获取APP PID,请确保大神APP已打开')
  622. return None
  623. headers_code = ""
  624. if headers:
  625. for k, v in headers.items():
  626. v = v.replace("'", "\\'")
  627. headers_code += f"map.put('{k}', '{v}');\n"
  628. body_escaped = body.replace("\\", "\\\\").replace("'", "\\'")
  629. script = f"""
  630. Java.perform(function() {{
  631. var Tools = Java.use('com.netease.nep.Tools');
  632. var HashMap = Java.use('java.util.HashMap');
  633. var map = HashMap.$new();
  634. {headers_code}
  635. var result = Tools.getPostMethodSignatures('{url}', '{body_escaped}', map);
  636. console.log('SIGNED_URL:' + result);
  637. console.log('__DONE__');
  638. }});
  639. """
  640. output = self._run_frida_script(self.frida_pid, script, timeout=15)
  641. if not output:
  642. return None
  643. for line in output.split('\n'):
  644. if 'SIGNED_URL:' in line:
  645. return line.split('SIGNED_URL:')[1].strip()
  646. return None
  647. # ======================== 自动登录(读取auth数据库 + HTTP API) ========================
  648. def _auto_login(self, pid):
  649. """
  650. 自动登录流程:
  651. 1. 通过 ADB + sqlite3 直接读取 APP 的 auth 数据库,获取缓存的 URS 凭据
  652. 2. 使用 URS 凭据调用 login-by-urs-token API 获取新的 GL Token
  653. 前提:用户至少手动登录过一次(数据库中有缓存账号)。
  654. 返回 (pid, token_data) 元组。token_data 为 dict 或 None。
  655. """
  656. # 第1步:从 auth 数据库读取 URS 凭据
  657. logger.info('从APP数据库读取URS凭据...')
  658. urs_creds = self._get_urs_credentials(pid)
  659. if not urs_creds:
  660. logger.error('无法读取URS凭据,请确保已手动登录过大神APP')
  661. return pid, None
  662. logger.info(f'获取到URS凭据,账号: {urs_creds.get("AUTH_ACCOUNT", "unknown")}')
  663. if urs_creds.get('GL_VERSION'):
  664. self.gl_version = urs_creds['GL_VERSION']
  665. logger.info(f'APP版本: {self.gl_version}')
  666. # 第2步:调用 login-by-urs-token API
  667. logger.info('调用登录API...')
  668. token_data = self._login_by_urs_token(pid, urs_creds)
  669. if token_data:
  670. logger.info('自动登录成功!')
  671. return self._get_app_pid(), token_data
  672. logger.warning('登录API调用失败')
  673. return self._get_app_pid(), None
  674. def _get_urs_credentials(self, pid):
  675. """通过 ADB 直接从 auth 数据库读取 URS 凭据(不需要 Frida)"""
  676. try:
  677. # 直接通过 ADB + su + sqlite3 读取 auth 数据库
  678. sql = 'SELECT uid, token, account, ursAuthedToken, ursAuhtedId, authType FROM userauths LIMIT 1'
  679. db_path = f'/data/data/{GL_PACKAGE}/databases/auth'
  680. # 用单条字符串传给 adb shell,避免参数拆分导致 SQL 断裂
  681. shell_cmd = f'su 0 sqlite3 {db_path} "{sql}"'
  682. result = subprocess.run(
  683. [ADB_PATH] + (['-s', self._adb_serial] if getattr(self, '_adb_serial', None) else []) +
  684. ['shell', shell_cmd],
  685. capture_output=True, text=True, timeout=10, creationflags=_NO_WINDOW
  686. )
  687. row = result.stdout.strip()
  688. if not row or '|' not in row:
  689. logger.warning('auth数据库为空或不可读')
  690. return None
  691. fields = row.split('|')
  692. if len(fields) < 6:
  693. logger.warning(f'auth数据库字段不足: {len(fields)}')
  694. return None
  695. data = {
  696. 'AUTH_UID': fields[0],
  697. 'AUTH_TOKEN': fields[1],
  698. 'AUTH_ACCOUNT': fields[2],
  699. 'AUTH_URS_TOKEN': fields[3],
  700. 'AUTH_URS_ID': fields[4],
  701. 'AUTH_TYPE': fields[5],
  702. }
  703. # 通过 ADB 获取 UDID (android_id)
  704. udid = self._adb_shell(['settings', 'get', 'secure', 'android_id'])
  705. if udid:
  706. data['UDID'] = udid
  707. # 通过 ADB 获取 APP 版本号
  708. version = self._get_app_version()
  709. if version:
  710. data['GL_VERSION'] = version
  711. # DeviceId 通过 Frida 获取
  712. device_id = self._get_device_id(pid)
  713. if device_id:
  714. data['GL_DEVICEID'] = device_id
  715. if data.get('AUTH_URS_TOKEN') and data.get('AUTH_URS_ID'):
  716. return data
  717. logger.warning('数据库中无有效的URS凭据')
  718. return None
  719. except Exception as e:
  720. logger.warning(f'读取URS凭据失败: {e}')
  721. return None
  722. def _get_app_version(self):
  723. """通过 ADB dumpsys 获取 APP 版本号"""
  724. try:
  725. output = self._adb_shell([
  726. f'dumpsys package {GL_PACKAGE} | grep versionName'
  727. ])
  728. for line in output.split('\n'):
  729. if 'versionName=' in line:
  730. return line.split('versionName=')[1].strip()
  731. except Exception:
  732. pass
  733. return None
  734. def _get_device_id(self, pid):
  735. """通过 Frida 获取 DeviceId"""
  736. script = """
  737. Java.perform(function() {
  738. try {
  739. var YXFDeviceInfo = Java.use('com.netease.gl.glbase.build.YXFDeviceInfo');
  740. console.log('GL_DEVICEID:' + YXFDeviceInfo.getDeviceId());
  741. } catch(e) {}
  742. console.log('__DONE__');
  743. });
  744. """
  745. output = self._run_frida_script(pid, script, timeout=10)
  746. if output:
  747. for line in output.split('\n'):
  748. if 'GL_DEVICEID:' in line:
  749. return line.split('GL_DEVICEID:')[1].strip()
  750. return None
  751. def _login_by_urs_token(self, pid, urs_creds):
  752. """使用 URS 凭据调用 login-by-urs-token API 获取新的 GL Token"""
  753. base_url = f"{LOGIN_BASE}/v1/app/base/user/login-by-urs-token"
  754. device_id = urs_creds.get('GL_DEVICEID', '')
  755. udid = urs_creds.get('UDID', '')
  756. payload = {
  757. "urs": {
  758. "id": urs_creds['AUTH_URS_ID'],
  759. "token": urs_creds['AUTH_URS_TOKEN'],
  760. "type": int(urs_creds.get('AUTH_TYPE', '30'))
  761. },
  762. "account": urs_creds['AUTH_ACCOUNT'],
  763. "clientType": int(GL_CLIENTTYPE),
  764. "deviceId": device_id,
  765. "os": "android",
  766. "version": self.gl_version,
  767. "osVersion": "12",
  768. "device": "SDY-AN00",
  769. "udid": udid,
  770. "unisdkDeviceId": udid,
  771. "autoLogin": False
  772. }
  773. body_str = json.dumps(payload)
  774. nonce = self._generate_nonce()
  775. sign_headers = {
  776. "GL-ClientType": GL_CLIENTTYPE,
  777. "GL-DeviceId": device_id,
  778. "GL-Nonce": nonce,
  779. }
  780. # 需要 Frida 签名
  781. self.frida_pid = pid
  782. signed_url = self._frida_sign(base_url, body_str, sign_headers)
  783. if not signed_url:
  784. logger.warning('登录请求签名失败')
  785. return None
  786. headers = {
  787. "Content-Type": "application/json; charset=utf-8",
  788. "User-Agent": "okhttp/4.9.1",
  789. "gl-clienttype": GL_CLIENTTYPE,
  790. "gl-deviceid": device_id,
  791. "gl-version": self.gl_version,
  792. "gl-nonce": nonce,
  793. "gl-curtime": str(int(time.time())),
  794. }
  795. try:
  796. resp = self.session.post(signed_url, json=payload, headers=headers, timeout=15)
  797. data = resp.json()
  798. if data.get('code') == 200:
  799. result = data.get('result', {})
  800. token = result.get('token', '')
  801. uid = result.get('userInfo', {}).get('user', {}).get('uid', '')
  802. source = result.get('source', 'URS')
  803. if uid and token:
  804. logger.info(f'登录成功! Token: {token[:16]}...')
  805. return {
  806. 'GL_UID': uid,
  807. 'GL_TOKEN': token,
  808. 'GL_SOURCE': source,
  809. 'GL_DEVICEID': device_id,
  810. }
  811. logger.warning('登录API返回200但缺少uid或token')
  812. return None
  813. else:
  814. logger.warning(f'登录失败: code={data.get("code")}, msg={data.get("errmsg")}')
  815. return None
  816. except Exception as e:
  817. logger.warning(f'登录请求异常: {e}')
  818. return None
  819. # ======================== HTTP API ========================
  820. def _get_role_info(self):
  821. """通过大神API获取绑定的阴阳师角色信息"""
  822. url = f"{LOGIN_BASE}/v1/app/gameRole/getBindList"
  823. payload = {"uid": self.gl_uid}
  824. try:
  825. resp = self.session.post(url, json=payload, headers=self._build_headers(), timeout=15)
  826. data = resp.json()
  827. if data.get('code') != 200:
  828. logger.warning(f'获取角色信息失败: {data.get("errmsg")}')
  829. return None
  830. roles = data.get('result', [])
  831. for role in roles:
  832. if role.get('appKey') == self.app_key:
  833. role_id = role.get('roleId', '')
  834. server = role.get('server', '')
  835. if role_id:
  836. logger.info(f'API获取角色成功: {role_id} @ {server}')
  837. return {'roleId': role_id, 'server': server}
  838. if roles:
  839. logger.warning(f'找到 {len(roles)} 个绑定角色,但无 appKey={self.app_key} 的角色')
  840. else:
  841. logger.warning('未找到任何绑定角色')
  842. return None
  843. except Exception as e:
  844. logger.warning(f'获取角色信息异常: {e}')
  845. return None
  846. def _is_token_expired(self, code, msg):
  847. """判断API返回是否表示Token已过期"""
  848. if code in [802, 805]:
  849. return True
  850. if msg and ('其他设备' in msg or '登录' in msg or '过期' in msg or '失效' in msg):
  851. return True
  852. return False
  853. def _relogin(self):
  854. """Token过期时重新登录,更新 self 上的凭据。返回是否成功。"""
  855. logger.warning('Token已失效,尝试重新登录...')
  856. pid = self.frida_pid or self._get_app_pid()
  857. if not pid:
  858. logger.error('重新登录失败:APP未运行')
  859. return False
  860. _, token_data = self._auto_login(pid)
  861. if not token_data:
  862. logger.error('重新登录失败')
  863. return False
  864. self.gl_uid = token_data.get('GL_UID', '')
  865. self.gl_token = token_data.get('GL_TOKEN', '')
  866. self.gl_deviceid = token_data.get('GL_DEVICEID', self.gl_deviceid)
  867. self.gl_source = token_data.get('GL_SOURCE', 'URS')
  868. logger.info(f'重新登录成功! 新Token: {self.gl_token[:16]}...')
  869. return True
  870. def _generate_nonce(self):
  871. return str(random.randint(-9000000000000000000, 9000000000000000000))
  872. def _build_headers(self, nonce=None):
  873. if not nonce:
  874. nonce = self._generate_nonce()
  875. return {
  876. "Content-Type": "application/json",
  877. "Accept": "application/json",
  878. "User-Agent": "okhttp/4.9.1",
  879. "gl-version": self.gl_version,
  880. "gl-source": self.gl_source,
  881. "gl-deviceid": self.gl_deviceid,
  882. "gl-token": self.gl_token,
  883. "gl-clienttype": GL_CLIENTTYPE,
  884. "gl-uid": self.gl_uid,
  885. "gl-nonce": nonce,
  886. "Origin": "https://act.ds.163.com",
  887. "Referer": "https://act.ds.163.com/",
  888. }
  889. def _get_rewards(self):
  890. url = f"{WELFARE_BASE}/v1/welfare/getAppInfos"
  891. payload = {
  892. "appKey": self.app_key,
  893. "roleId": self.role_id,
  894. "server": self.server,
  895. }
  896. try:
  897. resp = self.session.post(url, json=payload, headers=self._build_headers(), timeout=15)
  898. data = resp.json()
  899. code = data.get('code')
  900. msg = data.get('errmsg', '')
  901. # Token过期,重新登录后重试
  902. if code != 200 and self._is_token_expired(code, msg):
  903. if self._relogin():
  904. resp = self.session.post(url, json=payload, headers=self._build_headers(), timeout=15)
  905. data = resp.json()
  906. code = data.get('code')
  907. msg = data.get('errmsg', '')
  908. if code != 200:
  909. logger.warning(f'获取礼包失败: {msg}')
  910. return []
  911. rewards = []
  912. for app_info in data.get('result', []):
  913. for bag in app_info.get('rewardBags', []):
  914. bag_id = bag.get('id')
  915. title = bag.get('title', '')
  916. completed = bag.get('completed', False)
  917. has_apply = bag.get('hasApplay', False)
  918. desc = bag.get('fixedRewardDesc', '')
  919. if has_apply:
  920. logger.info(f' [已领取] {title}')
  921. elif completed:
  922. logger.info(f' [可领取] {title} - {desc}')
  923. rewards.append({'id': bag_id, 'title': title})
  924. else:
  925. logger.info(f' [未完成] {title}')
  926. return rewards
  927. except Exception as e:
  928. logger.error(f'获取礼包请求异常: {e}')
  929. return []
  930. def _claim_reward(self, bag_id, title):
  931. base_url = f"{WELFARE_BASE}/v1/welfare/applyRewardV2"
  932. payload = {
  933. "appKey": self.app_key,
  934. "rewardBagId": bag_id,
  935. "roleId": self.role_id,
  936. "server": self.server,
  937. }
  938. nonce = self._generate_nonce()
  939. sign_headers = {
  940. "GL-ClientType": GL_CLIENTTYPE,
  941. "GL-DeviceId": self.gl_deviceid,
  942. "GL-Nonce": nonce,
  943. "GL-Token": self.gl_token,
  944. "GL-Uid": self.gl_uid,
  945. }
  946. logger.info(f' 正在领取: {title}...')
  947. signed_url = self._frida_sign(base_url, json.dumps(payload), sign_headers)
  948. if not signed_url:
  949. logger.warning(f' 签名失败: {title}')
  950. return False
  951. try:
  952. headers = self._build_headers(nonce)
  953. resp = self.session.post(signed_url, json=payload, headers=headers, timeout=15)
  954. data = resp.json()
  955. code = data.get('code')
  956. msg = data.get('errmsg', '')
  957. if code == 200:
  958. logger.info(f' 领取成功: {title}')
  959. return True
  960. elif code == 801 or '已领取' in msg:
  961. logger.info(f' 已领取过: {title}')
  962. elif self._is_token_expired(code, msg):
  963. # Token过期,重新登录后重试
  964. if self._relogin():
  965. logger.info(f' 重试领取: {title}...')
  966. nonce = self._generate_nonce()
  967. sign_headers["GL-Token"] = self.gl_token
  968. sign_headers["GL-Nonce"] = nonce
  969. signed_url = self._frida_sign(base_url, json.dumps(payload), sign_headers)
  970. if signed_url:
  971. resp2 = self.session.post(signed_url, json=payload,
  972. headers=self._build_headers(nonce), timeout=15)
  973. data2 = resp2.json()
  974. if data2.get('code') == 200:
  975. logger.info(f' 领取成功: {title}')
  976. return True
  977. logger.warning(f' 重试失败: {title} - {data2.get("errmsg")}')
  978. else:
  979. logger.warning(f' 领取失败: {title} - {msg}')
  980. except Exception as e:
  981. logger.error(f' 领取异常: {title} - {e}')
  982. return False