diff --git a/internal/unicom/client.go b/internal/unicom/client.go index d1af590..fcc7f44 100644 --- a/internal/unicom/client.go +++ b/internal/unicom/client.go @@ -7,10 +7,12 @@ import ( "errors" "fmt" "io" + "math/rand" "net/http" "net/http/cookiejar" "net/url" "sort" + "strconv" "strings" "sync" "time" @@ -50,6 +52,15 @@ type Client struct { checkURL string qrSec string loginReady bool + notUnicom bool + pageJSONP pageJSONP +} + +// pageJSONP 复现页面里 jQuery 的 JSONP:回调名在请求之间复用,_ 用页面加载时开始的计数。 +type pageJSONP struct { + expando string + guid int64 + pool []string } func New() (*Client, error) { @@ -89,6 +100,8 @@ func (c *Client) Reset() { c.http.Jar = jar c.qrSec = "" c.loginReady = false + c.notUnicom = false + c.pageJSONP = pageJSONP{} } func (c *Client) SendSMS(ctx context.Context, phone, ticket, randstr string) (string, error) { @@ -98,13 +111,19 @@ func (c *Client) SendSMS(ctx context.Context, phone, ticket, randstr string) (st return "", err } c.dropAccount() + c.primeSMS(ctx, phone) debugf("发送短信 phone=%s randstr=%s ticket=%s", phone, randstr, ticket) - body, err := c.get(ctx, c.loginURL(c.spec.sendPath, url.Values{ + query := url.Values{ "req_time": {milli()}, "mobile": {phone}, "uvc": {ticket}, "verifyCode": {randstr}, - }), c.loginReferer) + } + if c.notUnicom { + query.Set("unicom_number", "0") + } + debugf("发短信前 Cookie %s", strings.Join(c.cookieNames("uac.10010.com"), ",")) + body, err := c.getLogin(ctx, c.spec.sendPath, query) if err != nil { return "", err } @@ -135,7 +154,7 @@ func (c *Client) Login(ctx context.Context, phone, smsCode, ticket, randstr stri "redirectType": {c.spec.redirectType}, "rememberMe": {"1"}, } - body, err := c.get(ctx, c.loginURL(c.spec.loginPath, q), c.loginReferer) + body, err := c.getLogin(ctx, c.spec.loginPath, q) if err != nil { return LoginResult{}, err } @@ -191,9 +210,9 @@ func (c *Client) PollQR(ctx context.Context) (QRStatus, error) { if c.qrSec == "" || c.spec.heartPath == "" { return QRStatus{}, errors.New("请先获取二维码") } - body, err := c.get(ctx, c.loginURL(c.spec.heartPath, url.Values{ + body, err := c.getLogin(ctx, c.spec.heartPath, url.Values{ "secsnid": {c.qrSec}, - }), c.loginReferer) + }) if err != nil { return QRStatus{}, err } @@ -250,9 +269,9 @@ func (c *Client) Query(ctx context.Context, phone string) (Snapshot, error) { } func (c *Client) finishQR(ctx context.Context) (QRStatus, error) { - body, err := c.get(ctx, c.loginURL(c.spec.logonPath, url.Values{ + body, err := c.getLogin(ctx, c.spec.logonPath, url.Values{ "secsnid": {c.qrSec}, - }), c.loginReferer) + }) if err != nil { return QRStatus{}, err } @@ -285,19 +304,18 @@ func (c *Client) prepareLogin(ctx context.Context) error { return err } next := findQuotedContaining(html, "homeLoginNew") + var scripts []string if next == "" { for _, src := range scriptSrcs(html) { js, err := c.getText(ctx, absURL(page, src), page) if err != nil { continue } + scripts = append(scripts, js) if path := findQuotedContaining(js, "homeLoginNew"); path != "" { next = path break } - if strings.Contains(js, "getKeyPair") { - return c.useBundle(html, js) - } } } html2 := "" @@ -314,6 +332,7 @@ func (c *Client) prepareLogin(ctx context.Context) error { if err != nil { continue } + scripts = append(scripts, js) if strings.Contains(js, "RSAUtils.getKeyPair") { bundle = js break @@ -322,7 +341,7 @@ func (c *Client) prepareLogin(ctx context.Context) error { if bundle == "" { return errors.New("登录脚本无法识别") } - return c.useBundle(combined, bundle) + return c.useBundle(combined, strings.Join(append([]string{bundle}, scripts...), "\n")) } func (c *Client) useBundle(html, bundle string) error { @@ -346,7 +365,8 @@ func (c *Client) useBundle(html, bundle string) error { c.spec = spec c.captchaScript = absURL(c.loginReferer, script) c.loginReady = true - debugf("登录脚本已识别 captcha=%s app=%s", c.captchaScript, spec.captchaAppID) + c.pageJSONP = newPageJSONP(spec.jqueryVer) + debugf("登录脚本已识别 captcha=%s app=%s jquery=%s", c.captchaScript, spec.captchaAppID, spec.jqueryVer) return nil } @@ -526,11 +546,18 @@ func (c *Client) land(ctx context.Context, raw string) error { return err } -func (c *Client) loginURL(path string, q url.Values) string { - q.Set("callback", jsonpCallback()) +func (c *Client) getLogin(ctx context.Context, path string, q url.Values) ([]byte, error) { + callback, under := c.takeCallback() + defer c.recycleCallback(callback) + q.Set("callback", callback) + return c.get(ctx, c.loginURL(path, q, under), c.loginReferer) +} + +func (c *Client) loginURL(path string, q url.Values, under string) string { order := []string{ "callback", "req_time", "redirectURL", "mobile", "userName", "password", "pwdType", "productType", "uvc", "verifyCode", "redirectType", "rememberMe", + "userId", "userType", } seen := map[string]bool{} parts := make([]string, 0, len(q)+1) @@ -556,10 +583,97 @@ func (c *Client) loginURL(path string, q url.Values) string { for _, key := range rest { add(key) } - parts = append(parts, "_="+jsEscape(milli())) + parts = append(parts, "_="+jsEscape(under)) return uacOrigin + path + "?" + strings.Join(parts, "&") } +func newPageJSONP(version string) pageJSONP { + if version == "" { + return pageJSONP{} + } + return pageJSONP{expando: jqueryExpando(version), guid: time.Now().UnixMilli()} +} + +func jqueryExpando(version string) string { + raw := version + strconv.FormatFloat(rand.Float64(), 'f', -1, 64) + var b strings.Builder + for _, r := range raw { + if r >= '0' && r <= '9' { + b.WriteRune(r) + } + } + return "jQuery" + b.String() +} + +func (c *Client) takeCallback() (string, string) { + if c.pageJSONP.expando == "" { + c.pageJSONP = newPageJSONP(c.spec.jqueryVer) + } + if c.pageJSONP.expando == "" { + c.pageJSONP.expando = "jQuery" + c.pageJSONP.guid = time.Now().UnixMilli() + } + var name string + if n := len(c.pageJSONP.pool); n > 0 { + name = c.pageJSONP.pool[n-1] + c.pageJSONP.pool = c.pageJSONP.pool[:n-1] + } else { + name = fmt.Sprintf("%s_%d", c.pageJSONP.expando, c.pageJSONP.guid) + c.pageJSONP.guid++ + } + under := strconv.FormatInt(c.pageJSONP.guid, 10) + c.pageJSONP.guid++ + return name, under +} + +func (c *Client) recycleCallback(name string) { + if name == "" { + return + } + c.pageJSONP.pool = append(c.pageJSONP.pool, name) +} + +func (c *Client) primeSMS(ctx context.Context, phone string) { + if c.spec.releasePath != "" { + if _, err := c.getLogin(ctx, c.spec.releasePath, url.Values{}); err != nil { + debugf("发布检查 %v", err) + } + } + if c.spec.checkFirst != "" { + if _, err := c.postForm(ctx, uacOrigin+c.spec.checkFirst, c.loginReferer, url.Values{"qry_from": {"01"}}); err != nil { + debugf("省份检查 %v", err) + } + } + need := url.Values{"userName": {phone}, "pwdType": {c.spec.pwdType}} + if c.spec.needPath != "" { + if _, err := c.getLogin(ctx, c.spec.needPath, need); err != nil { + debugf("验证码检查 %v", err) + } + } + c.notUnicom = false + if c.spec.userNoPath != "" { + body, err := c.postForm(ctx, uacOrigin+c.spec.userNoPath, c.loginReferer, url.Values{"user_id": {phone}}) + if err != nil { + debugf("号码检查 %v", err) + } else { + var data map[string]any + if json.Unmarshal(body, &data) == nil && asString(data["resultCode"]) == "1000" { + c.notUnicom = true + } + } + } + if c.spec.needPath != "" { + if _, err := c.getLogin(ctx, c.spec.needPath, need); err != nil { + debugf("验证码检查 %v", err) + } + } + if c.spec.agreePath != "" { + if _, err := c.getLogin(ctx, c.spec.agreePath, url.Values{"userId": {phone}, "userType": {c.spec.userType}}); err != nil { + debugf("协议检查 %v", err) + } + } +} + // jsEscape 与页面 jQuery.param / encodeURIComponent 一致。票据里的 * 必须原样保留。 func jsEscape(s string) string { var b strings.Builder @@ -575,10 +689,6 @@ func jsEscape(s string) string { return b.String() } -func jsonpCallback() string { - return fmt.Sprintf("jQuery%d_%d", time.Now().UnixNano(), time.Now().UnixMilli()) -} - func (c *Client) get(ctx context.Context, rawURL, referer string) ([]byte, error) { body, _, err := c.do(ctx, http.MethodGet, rawURL, referer, nil, nil) return body, err @@ -660,11 +770,36 @@ func (c *Client) decorate(req *http.Request, referer string) { } } if req.URL != nil && strings.Contains(req.URL.Host, "uac.10010.com") { - req.Header.Set("Origin", uacOrigin) req.Header.Set("X-Requested-With", "XMLHttpRequest") + req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6") + req.Header.Set("Sec-CH-UA", `"Microsoft Edge";v="155", "Chromium";v="155", "Not(A:Brand";v="24"`) + req.Header.Set("Sec-CH-UA-Mobile", "?0") + req.Header.Set("Sec-CH-UA-Platform", `"Windows"`) + if req.Method == http.MethodGet { + req.Header.Set("Accept", "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01") + req.Header.Set("Sec-Fetch-Site", "same-origin") + req.Header.Set("Sec-Fetch-Mode", "cors") + req.Header.Set("Sec-Fetch-Dest", "empty") + } else { + req.Header.Set("Origin", uacOrigin) + } } } +func (c *Client) cookieNames(host string) []string { + u, err := url.Parse("https://" + host + "/") + if err != nil { + return nil + } + cookies := c.jar.Cookies(u) + names := make([]string, 0, len(cookies)) + for _, ck := range cookies { + names = append(names, ck.Name) + } + sort.Strings(names) + return names +} + func (c *Client) cookie(host, name string) string { if name == "" { return "" diff --git a/internal/unicom/script.go b/internal/unicom/script.go index a10027d..6ad4d9a 100644 --- a/internal/unicom/script.go +++ b/internal/unicom/script.go @@ -21,6 +21,12 @@ type loginScript struct { pwdType string userType string redirectType string + jqueryVer string + releasePath string + checkFirst string + needPath string + agreePath string + userNoPath string } type billAPI struct { @@ -44,6 +50,12 @@ var ( piwCookieRE = regexp.MustCompile(`setCookie\(\s*["']([A-Za-z0-9_]+)["']\s*,\s*data\.piw`) pwdTypeRE = regexp.MustCompile(`PWD_TYPE_RND\s*=\s*["'](\d+)["']`) userTypeRE = regexp.MustCompile(`USER_TYPE_MOBILE\s*=\s*["'](\d+)["']`) + jqueryVerRE = regexp.MustCompile(`(?:jquery:"|jQuery v)(\d+\.\d+\.\d+)`) + releaseRE = regexp.MustCompile(`(/portal/Service/checkRelease)`) + checkFirstRE = regexp.MustCompile(`(/portal/Service/alogin_checkFirst)`) + needVerifyRE = regexp.MustCompile(`(/portal/Service/CheckNeedVerify)`) + agreementRE = regexp.MustCompile(`(/portal/Service/CheckAgreement)`) + userNumberRE = regexp.MustCompile(`(/portal/Service/CheckUsernumber)`) loginFromRE = regexp.MustCompile(`(?is)]*id=["']loginFrom["'][^>]*>`) inputValueRE = regexp.MustCompile(`value=["']([^"']*)["']`) scriptSrcRE = regexp.MustCompile(`(?i)]*?\ssrc=["']?([^"'\s>]+)`) @@ -85,6 +97,14 @@ func parseLoginBundle(js string) (loginScript, error) { if m := userTypeRE.FindStringSubmatch(js); m != nil { out.userType = m[1] } + if m := jqueryVerRE.FindStringSubmatch(js); m != nil { + out.jqueryVer = m[1] + } + out.releasePath = first(releaseRE, js) + out.checkFirst = first(checkFirstRE, js) + out.needPath = first(needVerifyRE, js) + out.agreePath = first(agreementRE, js) + out.userNoPath = first(userNumberRE, js) if out.sendPath == "" || out.loginPath == "" || out.captchaAppID == "" { return out, errors.New("登录脚本不完整") } diff --git a/internal/unicom/script_test.go b/internal/unicom/script_test.go index c07e343..023eb68 100644 --- a/internal/unicom/script_test.go +++ b/internal/unicom/script_test.go @@ -2,6 +2,7 @@ package unicom import ( "net/url" + "strconv" "strings" "testing" ) @@ -13,10 +14,25 @@ func TestPhoneFromPIW(t *testing.T) { } } -func TestJSONPCallbackName(t *testing.T) { - name := jsonpCallback() - if !strings.HasPrefix(name, "jQuery") || !strings.Contains(name, "_") { - t.Fatal(name) +func TestCallbackReusedLikePage(t *testing.T) { + c := &Client{spec: loginScript{jqueryVer: "3.5.1"}} + first, under1 := c.takeCallback() + c.recycleCallback(first) + second, under2 := c.takeCallback() + if first != second { + t.Fatalf("callback %s %s", first, second) + } + if !strings.HasPrefix(first, "jQuery351") { + t.Fatal(first) + } + suffix, err := strconv.ParseInt(strings.Split(first, "_")[1], 10, 64) + if err != nil { + t.Fatal(err) + } + u1, _ := strconv.ParseInt(under1, 10, 64) + u2, _ := strconv.ParseInt(under2, 10, 64) + if u1 != suffix+1 || u2 != u1+1 { + t.Fatalf("counter %d %d %d", suffix, u1, u2) } } @@ -41,11 +57,12 @@ func TestParseJSONP(t *testing.T) { func TestLoginQueryKeepsTicketStar(t *testing.T) { raw := (&Client{}).loginURL("/portal/Service/SendMSG", url.Values{ + "callback": {"jQuery35106785579090009984_1792133693942"}, "req_time": {"1792133860486"}, "mobile": {"10000000000"}, "uvc": {"ab*cd"}, "verifyCode": {"@abc"}, - }) + }, "1792133693944") if !strings.Contains(raw, "uvc=ab*cd") || !strings.Contains(raw, "verifyCode=%40abc") { t.Fatal(raw) } @@ -71,6 +88,8 @@ func TestParseLoginBundle(t *testing.T) { setCookie("piw", data.piw); CommonConstants.PWD_TYPE_RND = "02"; CommonConstants.USER_TYPE_MOBILE = "01"; + jquery:"3.5.1" + CommonConstants.CHECK_SHOW_VERIFY_URL = UacPrefix.PRXFIX + "/portal/Service/CheckNeedVerify?callback=?"; ` got, err := parseLoginBundle(js) if err != nil { @@ -88,6 +107,9 @@ func TestParseLoginBundle(t *testing.T) { if got.secCookie != "unisecid" || got.piwCookie != "piw" || got.pwdType != "02" || got.userType != "01" { t.Fatalf("names %#v", got) } + if got.jqueryVer != "3.5.1" || got.needPath != "/portal/Service/CheckNeedVerify" { + t.Fatalf("jquery %#v", got) + } html := ` ` if parseLoginFrom(html) != "01" {