script_task.py 43 KB

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