fix: 发短信前按页面完成预检查和回调计数

This commit is contained in:
Nixevol
2026-10-16 18:16:25 +08:00
parent ef33ed166c
commit d17d8c9778
3 changed files with 202 additions and 25 deletions
+155 -20
View File
@@ -7,10 +7,12 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"math/rand"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
"net/url" "net/url"
"sort" "sort"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -50,6 +52,15 @@ type Client struct {
checkURL string checkURL string
qrSec string qrSec string
loginReady bool loginReady bool
notUnicom bool
pageJSONP pageJSONP
}
// pageJSONP 复现页面里 jQuery 的 JSONP:回调名在请求之间复用,_ 用页面加载时开始的计数。
type pageJSONP struct {
expando string
guid int64
pool []string
} }
func New() (*Client, error) { func New() (*Client, error) {
@@ -89,6 +100,8 @@ func (c *Client) Reset() {
c.http.Jar = jar c.http.Jar = jar
c.qrSec = "" c.qrSec = ""
c.loginReady = false c.loginReady = false
c.notUnicom = false
c.pageJSONP = pageJSONP{}
} }
func (c *Client) SendSMS(ctx context.Context, phone, ticket, randstr string) (string, error) { 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 return "", err
} }
c.dropAccount() c.dropAccount()
c.primeSMS(ctx, phone)
debugf("发送短信 phone=%s randstr=%s ticket=%s", phone, randstr, ticket) 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()}, "req_time": {milli()},
"mobile": {phone}, "mobile": {phone},
"uvc": {ticket}, "uvc": {ticket},
"verifyCode": {randstr}, "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 { if err != nil {
return "", err return "", err
} }
@@ -135,7 +154,7 @@ func (c *Client) Login(ctx context.Context, phone, smsCode, ticket, randstr stri
"redirectType": {c.spec.redirectType}, "redirectType": {c.spec.redirectType},
"rememberMe": {"1"}, "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 { if err != nil {
return LoginResult{}, err return LoginResult{}, err
} }
@@ -191,9 +210,9 @@ func (c *Client) PollQR(ctx context.Context) (QRStatus, error) {
if c.qrSec == "" || c.spec.heartPath == "" { if c.qrSec == "" || c.spec.heartPath == "" {
return QRStatus{}, errors.New("请先获取二维码") 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}, "secsnid": {c.qrSec},
}), c.loginReferer) })
if err != nil { if err != nil {
return QRStatus{}, err 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) { 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}, "secsnid": {c.qrSec},
}), c.loginReferer) })
if err != nil { if err != nil {
return QRStatus{}, err return QRStatus{}, err
} }
@@ -285,19 +304,18 @@ func (c *Client) prepareLogin(ctx context.Context) error {
return err return err
} }
next := findQuotedContaining(html, "homeLoginNew") next := findQuotedContaining(html, "homeLoginNew")
var scripts []string
if next == "" { if next == "" {
for _, src := range scriptSrcs(html) { for _, src := range scriptSrcs(html) {
js, err := c.getText(ctx, absURL(page, src), page) js, err := c.getText(ctx, absURL(page, src), page)
if err != nil { if err != nil {
continue continue
} }
scripts = append(scripts, js)
if path := findQuotedContaining(js, "homeLoginNew"); path != "" { if path := findQuotedContaining(js, "homeLoginNew"); path != "" {
next = path next = path
break break
} }
if strings.Contains(js, "getKeyPair") {
return c.useBundle(html, js)
}
} }
} }
html2 := "" html2 := ""
@@ -314,6 +332,7 @@ func (c *Client) prepareLogin(ctx context.Context) error {
if err != nil { if err != nil {
continue continue
} }
scripts = append(scripts, js)
if strings.Contains(js, "RSAUtils.getKeyPair") { if strings.Contains(js, "RSAUtils.getKeyPair") {
bundle = js bundle = js
break break
@@ -322,7 +341,7 @@ func (c *Client) prepareLogin(ctx context.Context) error {
if bundle == "" { if bundle == "" {
return errors.New("登录脚本无法识别") 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 { func (c *Client) useBundle(html, bundle string) error {
@@ -346,7 +365,8 @@ func (c *Client) useBundle(html, bundle string) error {
c.spec = spec c.spec = spec
c.captchaScript = absURL(c.loginReferer, script) c.captchaScript = absURL(c.loginReferer, script)
c.loginReady = true 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 return nil
} }
@@ -526,11 +546,18 @@ func (c *Client) land(ctx context.Context, raw string) error {
return err return err
} }
func (c *Client) loginURL(path string, q url.Values) string { func (c *Client) getLogin(ctx context.Context, path string, q url.Values) ([]byte, error) {
q.Set("callback", jsonpCallback()) 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{ order := []string{
"callback", "req_time", "redirectURL", "mobile", "userName", "password", "callback", "req_time", "redirectURL", "mobile", "userName", "password",
"pwdType", "productType", "uvc", "verifyCode", "redirectType", "rememberMe", "pwdType", "productType", "uvc", "verifyCode", "redirectType", "rememberMe",
"userId", "userType",
} }
seen := map[string]bool{} seen := map[string]bool{}
parts := make([]string, 0, len(q)+1) 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 { for _, key := range rest {
add(key) add(key)
} }
parts = append(parts, "_="+jsEscape(milli())) parts = append(parts, "_="+jsEscape(under))
return uacOrigin + path + "?" + strings.Join(parts, "&") 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 一致。票据里的 * 必须原样保留。 // jsEscape 与页面 jQuery.param / encodeURIComponent 一致。票据里的 * 必须原样保留。
func jsEscape(s string) string { func jsEscape(s string) string {
var b strings.Builder var b strings.Builder
@@ -575,10 +689,6 @@ func jsEscape(s string) string {
return b.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) { func (c *Client) get(ctx context.Context, rawURL, referer string) ([]byte, error) {
body, _, err := c.do(ctx, http.MethodGet, rawURL, referer, nil, nil) body, _, err := c.do(ctx, http.MethodGet, rawURL, referer, nil, nil)
return body, err 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") { 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("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 { func (c *Client) cookie(host, name string) string {
if name == "" { if name == "" {
return "" return ""
+20
View File
@@ -21,6 +21,12 @@ type loginScript struct {
pwdType string pwdType string
userType string userType string
redirectType string redirectType string
jqueryVer string
releasePath string
checkFirst string
needPath string
agreePath string
userNoPath string
} }
type billAPI struct { type billAPI struct {
@@ -44,6 +50,12 @@ var (
piwCookieRE = regexp.MustCompile(`setCookie\(\s*["']([A-Za-z0-9_]+)["']\s*,\s*data\.piw`) piwCookieRE = regexp.MustCompile(`setCookie\(\s*["']([A-Za-z0-9_]+)["']\s*,\s*data\.piw`)
pwdTypeRE = regexp.MustCompile(`PWD_TYPE_RND\s*=\s*["'](\d+)["']`) pwdTypeRE = regexp.MustCompile(`PWD_TYPE_RND\s*=\s*["'](\d+)["']`)
userTypeRE = regexp.MustCompile(`USER_TYPE_MOBILE\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)<input[^>]*id=["']loginFrom["'][^>]*>`) loginFromRE = regexp.MustCompile(`(?is)<input[^>]*id=["']loginFrom["'][^>]*>`)
inputValueRE = regexp.MustCompile(`value=["']([^"']*)["']`) inputValueRE = regexp.MustCompile(`value=["']([^"']*)["']`)
scriptSrcRE = regexp.MustCompile(`(?i)<script[^>]*?\ssrc=["']?([^"'\s>]+)`) scriptSrcRE = regexp.MustCompile(`(?i)<script[^>]*?\ssrc=["']?([^"'\s>]+)`)
@@ -85,6 +97,14 @@ func parseLoginBundle(js string) (loginScript, error) {
if m := userTypeRE.FindStringSubmatch(js); m != nil { if m := userTypeRE.FindStringSubmatch(js); m != nil {
out.userType = m[1] 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 == "" { if out.sendPath == "" || out.loginPath == "" || out.captchaAppID == "" {
return out, errors.New("登录脚本不完整") return out, errors.New("登录脚本不完整")
} }
+27 -5
View File
@@ -2,6 +2,7 @@ package unicom
import ( import (
"net/url" "net/url"
"strconv"
"strings" "strings"
"testing" "testing"
) )
@@ -13,10 +14,25 @@ func TestPhoneFromPIW(t *testing.T) {
} }
} }
func TestJSONPCallbackName(t *testing.T) { func TestCallbackReusedLikePage(t *testing.T) {
name := jsonpCallback() c := &Client{spec: loginScript{jqueryVer: "3.5.1"}}
if !strings.HasPrefix(name, "jQuery") || !strings.Contains(name, "_") { first, under1 := c.takeCallback()
t.Fatal(name) 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) { func TestLoginQueryKeepsTicketStar(t *testing.T) {
raw := (&Client{}).loginURL("/portal/Service/SendMSG", url.Values{ raw := (&Client{}).loginURL("/portal/Service/SendMSG", url.Values{
"callback": {"jQuery35106785579090009984_1792133693942"},
"req_time": {"1792133860486"}, "req_time": {"1792133860486"},
"mobile": {"10000000000"}, "mobile": {"10000000000"},
"uvc": {"ab*cd"}, "uvc": {"ab*cd"},
"verifyCode": {"@abc"}, "verifyCode": {"@abc"},
}) }, "1792133693944")
if !strings.Contains(raw, "uvc=ab*cd") || !strings.Contains(raw, "verifyCode=%40abc") { if !strings.Contains(raw, "uvc=ab*cd") || !strings.Contains(raw, "verifyCode=%40abc") {
t.Fatal(raw) t.Fatal(raw)
} }
@@ -71,6 +88,8 @@ func TestParseLoginBundle(t *testing.T) {
setCookie("piw", data.piw); setCookie("piw", data.piw);
CommonConstants.PWD_TYPE_RND = "02"; CommonConstants.PWD_TYPE_RND = "02";
CommonConstants.USER_TYPE_MOBILE = "01"; CommonConstants.USER_TYPE_MOBILE = "01";
jquery:"3.5.1"
CommonConstants.CHECK_SHOW_VERIFY_URL = UacPrefix.PRXFIX + "/portal/Service/CheckNeedVerify?callback=?";
` `
got, err := parseLoginBundle(js) got, err := parseLoginBundle(js)
if err != nil { 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" { if got.secCookie != "unisecid" || got.piwCookie != "piw" || got.pwdType != "02" || got.userType != "01" {
t.Fatalf("names %#v", got) t.Fatalf("names %#v", got)
} }
if got.jqueryVer != "3.5.1" || got.needPath != "/portal/Service/CheckNeedVerify" {
t.Fatalf("jquery %#v", got)
}
html := `<input type="hidden" id="loginFrom" name="loginFrom" value='01' /> html := `<input type="hidden" id="loginFrom" name="loginFrom" value='01' />
<script src="https://turing.captcha.qcloud.com/TJCaptcha.js"></script>` <script src="https://turing.captcha.qcloud.com/TJCaptcha.js"></script>`
if parseLoginFrom(html) != "01" { if parseLoginFrom(html) != "01" {