代码管理

conn_browser_worker.py

← 返回编辑
"""conn_browser 的浏览器子进程(2026-11-23)。

由 conn_browser._run 通过 subprocess 调用,跑在独立进程里,避开
「playwright sync API 在 daemon 线程里 Event loop 关闭」的问题。

协议(都用临时文件传递,避免 stdout 解析):
  入参:argv[1]=sid, argv[2]=login_url
  输出:
    /gr_browser_.qr    —— 二维码 PNG 的 base64(一出现即被父进程推送)
    /gr_browser_.token —— 登录成功后写 sc_token(父进程读后落库)
    /gr_browser_.err   —— 出错信息
"""
import base64
import hashlib
import json
import os
import re
import sys
import tempfile
import threading
import time


def _is_hex32(v):
    """亿客 sc_token 是 32 位十六进制裸串;其它形态(base64 0.xxx== 等)都是假的。"""
    return bool(re.fullmatch(r"[0-9a-fA-F]{32}", v))


def _extract_token_from_text(text):
    """从登录响应文本里智能提取 token。

    优先级:32位hex > JWT(三段 base64) > 其它 16~400 长的无空白串。
    返回提取到的字符串,找不到返回 ""。
    """
    if not text:
        return ""
    # 1) 找 32 位 hex
    m = re.search(r"[^0-9a-zA-Z]([0-9a-fA-F]{32})[^0-9a-zA-Z]|^([0-9a-fA-F]{32})$", text)
    if m:
        return m.group(1) or m.group(2) or ""
    # 2) 找 JWT(eyJ 开头,三段)
    m = re.search(r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", text)
    if m:
        return m.group(0)
    # 3) 找带 "token" 字段的值
    m = re.search(r'"(?:sc_token|scToken|token|access_token|accessToken|authorization)"\s*:\s*"([^"]{16,400})"', text)
    if m:
        return m.group(1)
    return ""


def main():
    sid = sys.argv[1]
    login_url = sys.argv[2]
    iid = sys.argv[3] if len(sys.argv) > 3 else "unknown"
    brand = sys.argv[4] if len(sys.argv) > 4 else ""
    tmp = tempfile.gettempdir()
    qr_path = os.path.join(tmp, "gr_browser_%s.qr" % sid)
    token_path = os.path.join(tmp, "gr_browser_%s.token" % sid)
    err_path = os.path.join(tmp, "gr_browser_%s.err" % sid)
    diag_path = os.path.join(tmp, "gr_browser_%s.diag" % sid)
    for p in (qr_path, token_path, err_path, diag_path):
        try:
            if os.path.exists(p):
                os.remove(p)
        except Exception:                              # noqa: BLE001
            pass

    def _diag_write(line):
        try:
            with open(diag_path, "a") as f:
                f.write(line + "\n")
        except Exception:                              # noqa: BLE001
            pass

    def fail(msg):
        try:
            open(err_path, "w").write(str(msg)[:200])
        except Exception:                              # noqa: BLE001
            pass
        raise SystemExit(1)

    try:
        from playwright.sync_api import sync_playwright
    except Exception as e:                             # noqa: BLE001
        fail("缺 playwright:%s" % str(e)[:80])

    try:
        # 优先用系统 chromium(云容器 apt 装的那个);playwright 内核是次选。
        import shutil as _sh
        _exe = ""
        for _n in ("chromium", "chromium-browser", "google-chrome",
                   "google-chrome-stable", "chrome"):
            _p = _sh.which(_n)
            if _p:
                _exe = _p
                break
        if not _exe:
            for _p in ("/usr/bin/chromium", "/usr/bin/chromium-browser",
                       "/usr/local/bin/chrome"):
                if os.path.exists(_p):
                    _exe = _p
                    break

        with sync_playwright() as p:
            _kw = {"args": ["--no-sandbox", "--disable-dev-shm-usage",
                            "--disable-blink-features=AutomationControlled"]}
            if _exe:
                _kw["executable_path"] = _exe
            browser = p.chromium.launch(**_kw)
            # 用系统 chromium 的**真实 UA**(不伪造)。之前伪造 Chrome 159 + 随机
            # viewport 反而可能触发 digi 反爬、导致登录跳转后 token 不落库。
            # "多店同时在线"靠各自独立的 context 天然隔离,不需要伪造指纹。
            ctx = browser.new_context(
                viewport={"width": 1280, "height": 900}, device_scale_factor=2,
                locale="zh-CN", timezone_id="Asia/Shanghai")
            ctx.add_init_script(
                "Object.defineProperty(navigator,'webdriver',{get:()=>undefined});")
            page = ctx.new_page()
            captured_tokens = []

            def _on_req(req):
                try:
                    h = {k.lower(): v for k, v in (req.headers or {}).items()}
                except Exception:                      # noqa: BLE001
                    return
                for name in ("sc_token", "x-token", "authorization"):
                    v = h.get(name) or ""
                    if v.lower().startswith("bearer "):
                        v = v[7:]
                    v = v.strip()
                    # 真 sc_token 是 32 位十六进制裸串(如 98b7a125...32b4)。
                    # 上次抓到 0.xxx...== 这种 base64 串是错的,这里只收 hex 形态。
                    if name == "sc_token" and v:
                        if _is_hex32(v) and v not in captured_tokens:
                            captured_tokens.append(("sc_token", v))
                        continue
                    if v and 16 <= len(v) <= 400 and not any(c.isspace() for c in v):
                        if not _is_hex32(v):
                            continue
                        if v not in [x[1] for x in captured_tokens]:
                            captured_tokens.append((name, v))

            diag = []          # 诊断信息:扫码后每一步都记,最终写进 err 文件供排查

            def _on_resp(resp):
                # ★ 关键改造(2026-11-24):queryLogin 响应里必然带 token,
                #   直接从这里抓,不再依赖"跳转后读 localStorage"(后者偶发拿不到)。
                try:
                    if "queryLogin" in resp.url:
                        body = ""
                        try:
                            body = resp.text()
                        except Exception:              # noqa: BLE001
                            body = ""
                        _diag_write("QUERYLOGIN RESP 状态=%s 长度=%d" % (resp.status, len(body)))
                        # 只 dump 顶层结构 + 店铺/erp 关键字段(完整 body 太大)
                        try:
                            import json as _json
                            _obj = _json.loads(body)
                            _keys = list(_obj.keys()) if isinstance(_obj, dict) else "(非对象)"
                            _diag_write("QUERYLOGIN 顶层字段 -> %s" % _keys)
                            if isinstance(_obj, dict):
                                _data = _obj.get("data")
                                if isinstance(_data, list):
                                    _diag_write("  data 数组长度 = %d" % len(_data))
                                    for _di, _dv in enumerate(_data):
                                        if isinstance(_dv, dict):
                                            _diag_write("  data[%d] 字段 -> %s" % (_di, list(_dv.keys())))
                                            for _k, _v in _dv.items():
                                                if not isinstance(_v, (list, dict)):
                                                    _diag_write("    data[%d].%s = %s" % (_di, _k, str(_v)[:100]))
                                # data 数组第一个元素的字段(可能是账号信息)
                                if isinstance(_data, list) and _data:
                                    _d0 = _data[0]
                                    if isinstance(_d0, dict):
                                        _diag_write("  data[0] 字段 -> %s" % list(_d0.keys()))
                                        for _k, _v in _d0.items():
                                            if not isinstance(_v, (list, dict)):
                                                _diag_write("    data[0].%s = %s" % (_k, str(_v)[:120]))
                        except Exception as _e:        # noqa: BLE001
                            _diag_write("QUERYLOGIN 解析失败: %s" % str(_e)[:60])
                        # ★ 多门店账号(捷途+山海)修复(2026-11-24 用户确认根因):
                        #   纵横单门店登录后直接跳转;捷途/山海双门店账号登录后会弹
                        #   "选门店"框,云端卡在这。这里:解析候选门店列表,自动选第一个,
                        #   调 /login 换真正的 sc_token。
                        try:
                            _cands = (_obj.get("data") or []) if isinstance(_obj, dict) else []
                            if isinstance(_cands, list) and len(_cands) >= 1:
                                # ★ 根据品牌选候选:捷途→tenantId 0(第一个),山海→tenantId 1(第二个)
                                _target_tid = 1 if (brand and "山海" in brand) else 0
                                _c0 = _cands[0]
                                for _cc in _cands:
                                    if isinstance(_cc, dict) and int(_cc.get("tenantId") or 0) == _target_tid:
                                        _c0 = _cc
                                        break
                                _login_id = (_c0.get("loginIdentifier") or "") if isinstance(_c0, dict) else ""
                                _tenant_id = (_c0.get("tenantId") if isinstance(_c0, dict) else None)
                                _diag_write("目标品牌=%s → 选 tenantId=%s(候选%d个)" % (
                                    brand or "(未指定)", _target_tid, len(_cands)))
                                if _login_id:
                                    _diag_write("自动选门店换token: loginIdentifier=%s tenantId=%s" % (
                                        _login_id[:12] + "...", _tenant_id))
                                    _login_body = {"clientType": 0, "loginType": 3,
                                                   "loginIdentifier": _login_id}
                                    try:
                                        import urllib.request as _ur2
                                        import json as _json2
                                        _lr = _ur2.Request(
                                            "https://digi.jetourauto.com/scrm-center-api/login",
                                            data=_json2.dumps(_login_body).encode(),
                                            method="POST",
                                            headers={"Content-Type": "application/json"})
                                        _lresp = _ur2.urlopen(_lr, timeout=15)
                                        _lobj = _json2.loads(_lresp.read())
                                        _diag_write("/login 换token 返回: %s" % str(_lobj)[:300])
                                        _ldata = _lobj.get("data") if isinstance(_lobj, dict) else None
                                        # 真 token 可能直接在 data 里,也可能是 32位hex
                                        _real_tok = ""
                                        if isinstance(_ldata, str) and 16 <= len(_ldata) <= 400:
                                            _real_tok = _ldata
                                        elif isinstance(_ldata, dict):
                                            for _k2 in ("scToken", "token", "sc_token", "accessToken"):
                                                _v2 = _ldata.get(_k2)
                                                if isinstance(_v2, str) and len(_v2) >= 16:
                                                    _real_tok = _v2
                                                    break
                                        if not _real_tok:
                                            _real_tok = _extract_token_from_text(
                                                _json2.dumps(_lobj, ensure_ascii=False))
                                        if _real_tok:
                                            tok = _real_tok
                                            _diag_write("换到真 token: %s" % (_real_tok[:12] + "..." + _real_tok[-4:]))
                                            captured_tokens.append(("login", _real_tok))
                                            try:
                                                open(token_path, "w").write(_real_tok)
                                            except Exception:          # noqa: BLE001
                                                pass
                                    except Exception as _le:        # noqa: BLE001
                                        _diag_write("/login 换token失败: %s" % str(_le)[:100])
                        except Exception as _ce:                     # noqa: BLE001
                            _diag_write("选门店解析失败: %s" % str(_ce)[:80])

                        # 智能提取 token:遍历 JSON 里所有字段,找长得像 token 的值
                        # ★ 只有前面"选门店换token"没成功(tok 仍为空)时才走这个兜底,
                        #   否则会把换到的真 token 覆盖成 queryLogin 里的假值(bug 根因)。
                        if not tok:
                            tok = _extract_token_from_text(body)
                        if tok:
                            captured_tokens.append(("queryLogin", tok))
                            _diag_write("从 queryLogin 响应提取到 token: %s" % (tok[:12] + "..." + tok[-4:]))
                            # 立即用这个 token 查线索接口,dump 它真实归属的 erp
                            try:
                                import urllib.request as _ur
                                import json as _json
                                _req = _ur.Request(
                                    "https://digi.jetourauto.com/scrm-clue-api/shop/clue/pool/shop/default/queryShopCluePoolList",
                                    data=_json.dumps({"phone": "", "name": "", "meFlag": 0,
                                                      "handleType": 1, "pageIndex": 1, "pageSize": 1}).encode(),
                                    method="POST",
                                    headers={"Content-Type": "application/json", "sc_token": tok,
                                             "scrm_permission": "ShopGeneralClueManage"})
                                _resp = _ur.urlopen(_req, timeout=15)
                                _obj = _json.loads(_resp.read())
                                _data = _obj.get("data")
                                if isinstance(_data, list) and _data:
                                    _diag_write("TOKEN 真实归属 erp=%s erpName=%s" % (
                                        _data[0].get("erpCode") or "-",
                                        _data[0].get("erpName") or "-"))
                                else:
                                    _diag_write("TOKEN 查线索无数据: %s" % str(_obj)[:200])
                            except Exception as _e:    # noqa: BLE001
                                _diag_write("TOKEN 查线索失败: %s" % str(_e)[:80])
                            try:
                                open(token_path, "w").write(tok)
                                _diag_write("已写 token 文件")
                            except Exception:          # noqa: BLE001
                                pass
                except Exception:                      # noqa: BLE001
                    pass

            def _on_nav(frame):
                # 页面跳转(登录成功会跳到 /home)→ 全量 dump 存储,找 token 去哪了
                try:
                    # 完整记录 URL(含 query,企微回调的 code/state 可能在这里)
                    _diag_write("NAV[%s] -> %s" % ("main" if frame == page.main_frame else "sub", frame.url[:300]))
                    if frame == page.main_frame and "/login" not in frame.url:
                        ls = frame.evaluate("""() => {
                            const o = {};
                            for (let i=0;i120 ? (v.slice(0,16)+'...len'+v.length+'...'+v.slice(-8)) : v;
                            }
                            return o;
                        }""")
                        _diag_write("LOCALSTORAGE 跳转后 -> %s" % json.dumps(ls, ensure_ascii=False))
                        # 延迟 3 秒再 dump 一次,看 token 是否延迟写入
                        def _dump2():
                            try:
                                ls2 = frame.evaluate("""() => {
                                    const o={}; for(let i=0;i120?(v.slice(0,16)+'...len'+v.length+'...'+v.slice(-8)):v;
                                    } return o;
                                }""")
                                _diag_write("LOCALSTORAGE +3s -> %s" % json.dumps(ls2, ensure_ascii=False))
                            except Exception:          # noqa: BLE001
                                pass
                        threading.Timer(3.0, _dump2).start()
                except Exception as e:                 # noqa: BLE001
                    _diag_write("NAV dump 失败: %s" % str(e)[:80])

            # 额外:记录登录成功后所有请求(找"换token"接口)
            def _on_req_all(req):
                try:
                    _u = req.url
                    if "/scrm-" in _u and not any(x in _u for x in (".js", ".css", ".png", ".jpg", ".woff")):
                        _diag_write("REQ %s" % _u[:140])
                except Exception:                      # noqa: BLE001
                    pass

            page.on("request", _on_req)
            page.on("request", _on_req_all)
            page.on("response", _on_resp)
            page.on("framenavigated", _on_nav)
            # 也记录任何带 code/qwPlatformUserCode 的请求
            def _on_req_code(req):
                try:
                    _u = req.url
                    if "code=" in _u or "qwPlatformUserCode" in _u or "state=" in _u:
                        _diag_write("CODE-REQ %s" % _u[:250])
                except Exception:                      # noqa: BLE001
                    pass
            page.on("request", _on_req_code)
            page.goto(login_url, wait_until="domcontentloaded", timeout=45000)
            el = page.wait_for_selector('iframe[src*="login.work.weixin.qq.com"]',
                                        timeout=30000)
            page.wait_for_timeout(2500)
            png = el.screenshot(type="png")
            open(qr_path, "w").write(base64.b64encode(png).decode())

            deadline = time.time() + 580            # 跟父进程 TTL(600) 对齐,留余量
            scanned = False
            _last_diag = time.time()
            while time.time() < deadline:
                page.wait_for_timeout(1200)
                # 检测"扫码成功 请确认"后不再刷新/换码(会取消登录)
                if not scanned:
                    try:
                        fr = next((f for f in page.frames
                                   if "login.work.weixin.qq.com" in f.url), None)
                        txt = fr.evaluate("() => document.body.innerText") if fr else ""
                        if txt and "扫码成功" in txt:
                            scanned = True
                    except Exception:                  # noqa: BLE001
                        pass
                # 真令牌优先取请求头 sc_token(11-23 实测:localStorage 未必有);
                # 其次 localStorage/sessionStorage 全扫。
                tok = captured_tokens[-1][1] if captured_tokens else ""
                # ★ 关键修复:一旦页面离开 login(登录成功跳转),token 可能稍后才写进
                #   localStorage(跳转 → 前端再调 queryLogin → 写 sc_token)。
                #   这里在跳转后主动、带重试地读,别因为页面重载抛异常就永远读不到。
                if tok:
                    pass
                elif "/login" not in page.url:
                    for _try in range(20):            # 最多等 ~24 秒
                        try:
                            _v = page.evaluate(
                                "() => localStorage.getItem('sc_token') || localStorage.getItem('token') || ''")
                        except Exception:              # noqa: BLE001
                            _v = ""
                            page.wait_for_timeout(1200)
                            continue
                        if _v and 16 <= len(_v) <= 400 and not any(c.isspace() for c in _v):
                            tok = _v
                            _diag_write("拿到 token(跳转后 localStorage):%s" % (_v[:12] + "..." + _v[-4:]))
                            break
                        if _try == 19:                  # 最后一次还没拿到,dump 完整 keys
                            try:
                                _keys = page.evaluate("""() => {
                                    const o={}; for(let i=0;i 8:
                    _last_diag = time.time()
                    try:
                        fr2 = next((f for f in page.frames
                                    if "login.work.weixin.qq.com" in f.url), None)
                        ftxt = fr2.evaluate("() => document.body.innerText.replace(/\\s+/g,' ').slice(0,60)") if fr2 else "(iframe没了)"
                        line = "POLL url=%s iframe=%s tokens=%d scanned=%s" % (
                            page.url[:60], ftxt, len(captured_tokens), scanned)
                        diag.append(line)
                        _diag_write(line)
                    except Exception as e:             # noqa: BLE001
                        _diag_write("POLL err=%s" % str(e)[:60])
                if not tok:
                    try:
                        tok = page.evaluate("""() => {
                            const s = [localStorage.getItem('sc_token'),
                                       localStorage.getItem('token'),
                                       sessionStorage.getItem('sc_token'),
                                       sessionStorage.getItem('token')];
                            for (let i=0;i