cdp_login_diag.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """Diagnose why the login didn't complete after geetest passed.
  2. Enables CDP Network domain, re-does the login flow (fill + click + slider),
  3. and captures:
  4. - the actual /auth/v3/login/safe/byPwd request + response
  5. - any console errors
  6. - page error messages
  7. """
  8. import asyncio
  9. import json
  10. import sys
  11. import httpx
  12. import websockets
  13. USERNAME = "longwu988"
  14. PASSWORD = "Longwu1988"
  15. CDP = "http://127.0.0.1:9222"
  16. async def get_targets():
  17. async with httpx.AsyncClient(timeout=5) as c:
  18. r = await c.get(f"{CDP}/json/list")
  19. return r.json()
  20. class Page:
  21. def __init__(self, ws):
  22. self.ws = ws
  23. self.mid = 0
  24. self.events = []
  25. async def call(self, method, params=None):
  26. self.mid += 1
  27. await self.ws.send(json.dumps({"id": self.mid, "method": method, "params": params or {}}))
  28. while True:
  29. msg = json.loads(await self.ws.recv())
  30. if msg.get("id") == self.mid:
  31. return msg.get("result", {})
  32. elif "method" in msg:
  33. self.events.append(msg)
  34. async def eval(self, expr):
  35. r = await self.call("Runtime.evaluate", {"expression": expr, "returnByValue": True})
  36. return r.get("result", {}).get("value")
  37. async def mouse(self, typ, x, y):
  38. params = {"type": typ, "x": x, "y": y, "button": "left"}
  39. if typ == "mousePressed":
  40. params["clickCount"] = 1
  41. params["buttons"] = 1
  42. if typ == "mouseReleased":
  43. params["clickCount"] = 1
  44. params["buttons"] = 0
  45. await self.call("Input.dispatchMouseEvent", params)
  46. def network_events(self, method_filter=None):
  47. out = []
  48. for e in self.events:
  49. if e.get("method", "").startswith("Network."):
  50. if method_filter is None or method_filter in e["method"]:
  51. out.append(e)
  52. return out
  53. async def main():
  54. targets = await get_targets()
  55. login = next((t for t in targets if "login" in t.get("url", "") and t["type"] == "page"), None)
  56. if not login:
  57. print("no login page")
  58. for t in targets:
  59. print(f" [{t['type']}] {t['url'][:70]}")
  60. return 1
  61. print(f"login page: {login['url'][:60]}")
  62. async with websockets.connect(login["webSocketDebuggerUrl"], max_size=10**7) as ws:
  63. page = Page(ws)
  64. # Enable network tracking FIRST
  65. await page.call("Network.enable")
  66. print("network tracking enabled")
  67. # 1. Check current page state — maybe already logged in / error showing?
  68. state = await page.eval("""
  69. (function() {
  70. const err = document.querySelector('.ant-message-error, [class*=error], .ant-form-item-explain-error');
  71. const msg = document.querySelector('.ant-message-notice, .ant-message');
  72. const u = document.querySelector('#username');
  73. const p = document.querySelector('#password');
  74. return JSON.stringify({
  75. errText: err ? err.innerText.slice(0,60) : '',
  76. msgText: msg ? msg.innerText.slice(0,60) : '',
  77. uLen: u ? (u.value||'').length : -1,
  78. pLen: p ? (p.value||'').length : -1,
  79. saveChecked: document.querySelector('#save') ? document.querySelector('#save').checked : null
  80. });
  81. })()
  82. """)
  83. print(f"page state: {state}")
  84. # 2. Fill if empty
  85. st = json.loads(state or "{}")
  86. if st.get("uLen", 0) < 3:
  87. await page.eval(f"""
  88. (function() {{
  89. const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
  90. const u = document.querySelector('#username');
  91. const p = document.querySelector('#password');
  92. set.call(u, '{USERNAME}');
  93. u.dispatchEvent(new Event('input', {{bubbles:true}}));
  94. set.call(p, '{PASSWORD}');
  95. p.dispatchEvent(new Event('input', {{bubbles:true}}));
  96. return 'filled';
  97. }})()
  98. """)
  99. print("credentials filled")
  100. # 3. Clear previous network events, click login
  101. page.events.clear()
  102. clicked = await page.eval("""
  103. (function() {
  104. const btn = document.querySelector('button.ant-btn.login-btn, button.login-btn, button.ant-btn');
  105. if (!btn) return 'no button';
  106. btn.click();
  107. return 'clicked: ' + btn.innerText.trim();
  108. })()
  109. """)
  110. print(f"login {clicked}")
  111. # 4. Wait for geetest, solve it
  112. await asyncio.sleep(2.5)
  113. for attempt in range(3):
  114. has_gt = await page.eval("!!document.querySelector('.geetest_box, [class*=geetest_btn]')")
  115. if not has_gt:
  116. print(f"attempt {attempt+1}: no geetest visible — checking network...")
  117. break
  118. print(f"attempt {attempt+1}: solving slider...")
  119. info = await page.eval("""
  120. (function() {
  121. const sel = ['.geetest_slider_button', '.geetest_btn_drag', '[class*=slider_button]', '.geetest_box .geetest_btn'];
  122. for (const s of sel) {
  123. const el = document.querySelector(s);
  124. if (el && el.offsetParent !== null) {
  125. const r = el.getBoundingClientRect();
  126. return JSON.stringify({x: r.x + r.width/2, y: r.y + r.height/2});
  127. }
  128. }
  129. return null;
  130. })()
  131. """)
  132. if not info:
  133. print(" slider not found")
  134. break
  135. d = json.loads(info)
  136. x, y = d["x"], d["y"]
  137. import math
  138. await page.mouse("mouseMoved", x, y)
  139. await asyncio.sleep(0.15)
  140. await page.mouse("mousePressed", x, y)
  141. await asyncio.sleep(0.1)
  142. dist = 280
  143. for i in range(1, 41):
  144. progress = i / 40
  145. eased = 1 - (1 - progress) ** 2.2
  146. await page.mouse("mouseMoved", x + dist * eased, y + math.sin(i * 0.7) * 2.5)
  147. await asyncio.sleep(0.028)
  148. await asyncio.sleep(0.12)
  149. await page.mouse("mouseReleased", x + dist, y)
  150. print(" drag done")
  151. await asyncio.sleep(3)
  152. # check page state after slide
  153. after = await page.eval("""
  154. JSON.stringify({
  155. url: location.href.slice(0,70),
  156. err: (document.querySelector('.ant-message-error, [class*=error]')||{}).innerText || ''
  157. })
  158. """)
  159. print(f" after: {after}")
  160. if "login" not in json.loads(after or '{"url":"login"}').get("url", ""):
  161. break
  162. # 5. Wait and collect network responses for byPwd
  163. print("\nwaiting 10s for responses...")
  164. await asyncio.sleep(10)
  165. # Find requestWillBeSent for byPwd, match to responseReceived
  166. reqs = {}
  167. for e in page.network_events():
  168. m = e["method"]
  169. p = e.get("params", {})
  170. if m == "Network.requestWillBeSent":
  171. url = p.get("request", {}).get("url", "")
  172. if "byPwd" in url or "login" in url.lower():
  173. reqs[p["requestId"]] = {"url": url, "method": p["request"].get("method")}
  174. elif m == "Network.responseReceived":
  175. rid = p.get("requestId")
  176. if rid in reqs:
  177. reqs[rid]["status"] = p["response"].get("status")
  178. reqs[rid]["respUrl"] = p["response"].get("url", "")[:80]
  179. print(f"\n=== login-related network requests: {len(reqs)} ===")
  180. for rid, r in reqs.items():
  181. print(f" [{r.get('method','?')}] {r.get('url','')[:75]}")
  182. print(f" -> status={r.get('status','?')}")
  183. # fetch response body via Network.getResponseBody
  184. try:
  185. body = await page.call("Network.getResponseBody", {"requestId": rid})
  186. txt = body.get("body", "")
  187. if body.get("base64Encoded"):
  188. import base64
  189. txt = base64.b64decode(txt).decode("utf-8", errors="replace")
  190. print(f" body: {txt[:300]}")
  191. except Exception as ex:
  192. print(f" body err: {type(ex).__name__}")
  193. # 6. Final page state
  194. final = await page.eval("location.href + ' | ' + document.title")
  195. print(f"\nfinal page: {final}")
  196. return 0
  197. sys.exit(asyncio.run(main()))