统一推送前Python代码格式

This commit is contained in:
yml2213
2026-09-02 18:11:41 +08:00
parent aaaa568916
commit 95ad900ef0
6 changed files with 265 additions and 124 deletions
+129 -56
View File
@@ -14,6 +14,7 @@
无第三方依赖:标准库 + websockets(直接走 CDP 协议)。
"""
from __future__ import annotations
import argparse
@@ -29,8 +30,7 @@ from pathlib import Path
import websockets
CHROME = (
Path.home()
/ "Library/Caches/ms-playwright/chromium-1234/chrome-mac-arm64/"
Path.home() / "Library/Caches/ms-playwright/chromium-1234/chrome-mac-arm64/"
"Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
)
@@ -41,8 +41,13 @@ PAGES = [
# 与 core/huya/app_login.py::WEB_DEVICE_COOKIE_KEYS 一致
WEB_DEVICE_KEYS = (
"guid", "udb_guiddata", "udb_deviceid", "game_did",
"_qimei_uuid42", "udb_anobiztoken", "__yamid_new",
"guid",
"udb_guiddata",
"udb_deviceid",
"game_did",
"_qimei_uuid42",
"udb_anobiztoken",
"__yamid_new",
)
OUT_DIR = Path("evidence/browser_cookie_harvest")
@@ -83,20 +88,29 @@ class Cdp:
self._id += 1
fut = asyncio.get_running_loop().create_future()
self._pending[self._id] = fut
await self.ws.send(json.dumps({"id": self._id, "method": method, "params": params or {}}))
await self.ws.send(
json.dumps({"id": self._id, "method": method, "params": params or {}})
)
resp = await fut
if "error" in resp:
raise RuntimeError(f"{method}: {resp['error']}")
return resp.get("result", {})
async def eval_js(self, expr):
r = await self.call("Runtime.evaluate", {
"expression": expr, "returnByValue": True, "awaitPromise": True,
})
r = await self.call(
"Runtime.evaluate",
{
"expression": expr,
"returnByValue": True,
"awaitPromise": True,
},
)
return r.get("result", {}).get("value")
def launch(profile: Path, port: int, headless: bool = True) -> tuple[subprocess.Popen, str]:
def launch(
profile: Path, port: int, headless: bool = True
) -> tuple[subprocess.Popen, str]:
"""启动用于 CDP 抓取的 Chrome。
默认使用无头模式,避免登录/抓取流程弹出窗口;传入 ``headless=False``
@@ -104,9 +118,13 @@ def launch(profile: Path, port: int, headless: bool = True) -> tuple[subprocess.
"""
args = [
str(CHROME),
"--no-first-run", "--no-default-browser-check",
"--disable-background-networking", "--disable-component-update",
"--disable-sync", "--metrics-recording-only", "--disable-extensions",
"--no-first-run",
"--no-default-browser-check",
"--disable-background-networking",
"--disable-component-update",
"--disable-sync",
"--metrics-recording-only",
"--disable-extensions",
"--disable-features=OptimizationHints,MediaRouter",
f"--user-data-dir={profile}",
f"--remote-debugging-port={port}",
@@ -133,7 +151,11 @@ def launch(profile: Path, port: int, headless: bool = True) -> tuple[subprocess.
f"http://127.0.0.1:{port}/json/list", timeout=2
) as resp:
targets = json.load(resp)
pages = {t for t in targets if t.get("type") == "page" and t.get("webSocketDebuggerUrl")}
pages = {
t
for t in targets
if t.get("type") == "page" and t.get("webSocketDebuggerUrl")
}
if pages:
ws_url = pages[0]["webSocketDebuggerUrl"]
break
@@ -204,11 +226,13 @@ async def capture_round(profile: Path, tag: str, port: int, *, headless: bool =
else:
entry["seq"] = min(ack_order, req_seq)
req_seq += 1
entry.update({
"url": url,
"host": urllib.parse.urlparse(url).netloc,
"type": params.get("type", ""),
})
entry.update(
{
"url": url,
"host": urllib.parse.urlparse(url).netloc,
"type": params.get("type", ""),
}
)
# 部分请求的 Cookie 头在 requestWillBeSent 就直接可见
seen = set(entry.get("cookie_names", []))
for name in cookie_names_from_header(req.get("headers", {})):
@@ -249,12 +273,16 @@ async def capture_round(profile: Path, tag: str, port: int, *, headless: bool =
entry = requests.setdefault(rid, {"url": "?"})
url = entry.get("url", "?")
headers = params.get("headers", {})
set_cookie = headers.get("Set-Cookie") or headers.get("set-cookie") or []
set_cookie = (
headers.get("Set-Cookie") or headers.get("set-cookie") or []
)
if isinstance(set_cookie, str):
set_cookie = [set_cookie]
for sc in set_cookie:
name = sc.split("=", 1)[0].strip()
resp_extra.append({"cookie": name, "url": url, "meta": sc[:160]})
resp_extra.append(
{"cookie": name, "url": url, "meta": sc[:160]}
)
cdp.listeners.append(on_resp_extra)
@@ -268,10 +296,19 @@ async def capture_round(profile: Path, tag: str, port: int, *, headless: bool =
}
await navigate(cdp, url)
doc_cookies[name]["after"] = await cdp.eval_js("document.cookie")
snapshots.append({"page": name, "url": url, "time": ts,
"cookies": await cdp.call("Network.getAllCookies")})
print(f"[harvest] {tag}/{name} done: {url} doc_cookie_len="
f"{len(doc_cookies[name]['after'] or '')}", flush=True)
snapshots.append(
{
"page": name,
"url": url,
"time": ts,
"cookies": await cdp.call("Network.getAllCookies"),
}
)
print(
f"[harvest] {tag}/{name} done: {url} doc_cookie_len="
f"{len(doc_cookies[name]['after'] or '')}",
flush=True,
)
# 按事件到达次序输出请求列表
req_list = sorted(requests.values(), key=lambda r: r.get("seq", 10**9))
@@ -330,14 +367,21 @@ async def probe_anon(profile: Path, port: int, *, headless: bool = True):
"url": url,
"method": req.get("method", ""),
"postData": req.get("postData", ""),
"headers": {k: v for k, v in req.get("headers", {}).items()
if k.lower() in ("cookie", "content-type", "referer", "origin")},
"headers": {
k: v
for k, v in req.get("headers", {}).items()
if k.lower()
in ("cookie", "content-type", "referer", "origin")
},
"body": None,
"status": None,
}
rid_map[params.get("requestId", "")] = entry
anon.append(entry)
print(f"[probe] 抓到匿名请求: {req.get('method')} {url[:120]}", flush=True)
print(
f"[probe] 抓到匿名请求: {req.get('method')} {url[:120]}",
flush=True,
)
cdp.listeners.append(on_anon_req)
@@ -357,10 +401,14 @@ async def probe_anon(profile: Path, port: int, *, headless: bool = True):
# 抓响应体
for rid, entry in rid_map.items():
try:
body = await cdp.call("Network.getResponseBody", {"requestId": rid})
body = await cdp.call(
"Network.getResponseBody", {"requestId": rid}
)
entry["body"] = body.get("body", "")
print(f"[probe] 响应体 {len(entry['body'])}B status={entry['status']}",
flush=True)
print(
f"[probe] 响应体 {len(entry['body'])}B status={entry['status']}",
flush=True,
)
except Exception as exc: # noqa: BLE001
print(f"[probe] 响应体获取失败: {exc}", flush=True)
@@ -389,16 +437,20 @@ async def probe_anon(profile: Path, port: int, *, headless: bool = True):
replay = []
for entry in anon:
host = urllib.parse.urlparse(entry["url"]).netloc
headers = {"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/149.0.0.0 Safari/537.36"
)}
headers = {
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/149.0.0.0 Safari/537.36"
)
}
ck = cookie_header(host)
if ck:
headers["Cookie"] = ck
if entry["postData"]:
headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
headers.setdefault(
"Content-Type", "application/x-www-form-urlencoded"
)
try:
resp = await asyncio.to_thread(
pyrequests.request,
@@ -409,18 +461,22 @@ async def probe_anon(profile: Path, port: int, *, headless: bool = True):
timeout=15,
allow_redirects=False,
)
replay.append({
"url": entry["url"][:160],
"method": entry["method"],
"status": resp.status_code,
"set_cookie": resp.headers.get("Set-Cookie", ""),
"location": resp.headers.get("Location", ""),
"body_head": resp.text[:600],
"body_len": len(resp.content),
})
print(f"[probe] 重放 {entry['method']} {entry['url'][:90]} "
f"-> {resp.status_code} setcookie={bool(resp.headers.get('Set-Cookie'))}",
flush=True)
replay.append(
{
"url": entry["url"][:160],
"method": entry["method"],
"status": resp.status_code,
"set_cookie": resp.headers.get("Set-Cookie", ""),
"location": resp.headers.get("Location", ""),
"body_head": resp.text[:600],
"body_len": len(resp.content),
}
)
print(
f"[probe] 重放 {entry['method']} {entry['url'][:90]} "
f"-> {resp.status_code} setcookie={bool(resp.headers.get('Set-Cookie'))}",
flush=True,
)
except Exception as exc: # noqa: BLE001
replay.append({"url": entry["url"][:160], "error": str(exc)})
print(f"[probe] 重放失败: {exc}", flush=True)
@@ -449,9 +505,17 @@ def build_report():
sys.exit(2)
req1 = json.loads((r1 / "requests.json").read_text())
req2 = json.loads((r2 / "requests.json").read_text()) if (r2 / "requests.json").exists() else []
req2 = (
json.loads((r2 / "requests.json").read_text())
if (r2 / "requests.json").exists()
else []
)
setc1 = json.loads((r1 / "set_cookies.json").read_text())
snap2 = json.loads((r2 / "snapshots.json").read_text()) if (r2 / "snapshots.json").exists() else []
snap2 = (
json.loads((r2 / "snapshots.json").read_text())
if (r2 / "snapshots.json").exists()
else []
)
doc1 = json.loads((r1 / "doc_cookies.json").read_text())
# 每个 cookie 名在 round1 的首次出现位置(按请求顺序)
@@ -459,7 +523,12 @@ def build_report():
for i, req in enumerate(req1):
for name in req.get("cookie_names", []):
if name not in first_seen:
first_seen[name] = {"idx": i, "host": req["host"], "url": req["url"], "type": req["type"]}
first_seen[name] = {
"idx": i,
"host": req["host"],
"url": req["url"],
"type": req["type"],
}
# Set-Cookie 写入的 cookie
set_from: dict[str, str] = {}
@@ -483,7 +552,7 @@ def build_report():
def fmt_first(info: dict | None):
if not info:
return "未见来源"
return f'#{info["idx"]} {info["host"]} ({info["type"]})'
return f"#{info['idx']} {info['host']} ({info['type']})"
lines = [
"# 浏览器 Cookie 字段来源分析(真实 Chrome 抓包,未登录)",
@@ -515,7 +584,7 @@ def build_report():
for i, req in enumerate(req1[:60]):
names = ", ".join(req.get("cookie_names", [])[:12])
names_all = req.get("cookie_names", [])
extra = f" +{len(names_all)-12}" if len(names_all) > 12 else ""
extra = f" +{len(names_all) - 12}" if len(names_all) > 12 else ""
lines.append(f"| {i} | {req['host']} | {req['type']} | {names}{extra} |")
lines += [
@@ -537,8 +606,10 @@ def build_report():
names = [p.split("=", 1)[0].strip() for p in after.split(";") if p.strip()]
diff = [n for n in names if n not in seen]
seen.update(names)
lines.append(f"- {page}: before={bool(v.get('before'))} after={len(names)} 字段"
f" 新增={', '.join(diff) if diff else '无'}")
lines.append(
f"- {page}: before={bool(v.get('before'))} after={len(names)} 字段"
f" 新增={', '.join(diff) if diff else '无'}"
)
lines += ["", "## round2 重启后首请求即携带的字段(浏览器持久态)", ""]
if req2:
pk = []
@@ -582,7 +653,9 @@ def main():
if args.mode == "round2" and not (profile / "Default").exists():
print("round2 需要先运行 round1(同一 profile)")
sys.exit(2)
asyncio.run(capture_round(profile, args.mode, args.port, headless=not args.headed))
asyncio.run(
capture_round(profile, args.mode, args.port, headless=not args.headed)
)
elif args.mode == "probe":
# 匿名流程只在"无 udb_deviceid 持久态"的全新 profile 触发;
# probe 模式内部使用临时全新 profile,跑完自动清理。