diff --git a/README.md b/README.md index a1f2192..7d941df 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 移动账户 -给自己的中国移动号码看话费余额、当月消费和套餐余量。页面只读,登录后按设定间隔自动刷新。登录方式是手机号、图形验证码和短信验证码。扫码登录没有做。 +给自己的中国移动号码看话费余额、当月消费和套餐余量。页面只读,登录后按设定间隔自动刷新。登录可以用短信验证码,也可以用中国移动 App 扫页面上的二维码。 页面没有访问口令,只放在自己的机器上。 @@ -28,7 +28,7 @@ 间隔和随机分钟在页面里保存后,以 `data/state.json` 为准。 -登录页先填手机号和图形验证码,再获取短信。这个号码上次的会话还在时,点登录会直接进入主页。退出只回到登录页,不向移动注销,也不再自动刷新。 +短信登录先填手机号和图形验证码,再获取短信。扫码登录点「扫码」,用中国移动 App 扫二维码。这个号码上次的会话还在时,点登录会直接进入主页。退出只回到登录页,不向移动注销,也不再自动刷新。 ## 编译 diff --git a/go.mod b/go.mod index cffc67f..0a0aa0e 100644 --- a/go.mod +++ b/go.mod @@ -2,11 +2,18 @@ module cmnetsmsinfo go 1.26.0 -require github.com/dop251/goja v0.0.0-20261011204819-0c9fae1b959d +require ( + github.com/dop251/goja v0.0.0-20261011204819-0c9fae1b959d + github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e + github.com/tuotoo/qrcode v0.0.0-20220425170535-52ccc2bebf5d +) require ( github.com/dlclark/regexp2/v2 v2.8.1 // indirect github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/maruel/rs v1.1.0 // indirect golang.org/x/text v0.43.0 // indirect + rsc.io/qr v0.2.0 // indirect ) diff --git a/go.sum b/go.sum index b3ccb95..88797f5 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/bits-and-blooms/bitset v1.2.1 h1:M+/hrU9xlMp7t4TyTDQW97d3tRPVuKFC6zBEK16QnXY= +github.com/bits-and-blooms/bitset v1.2.1/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= github.com/dlclark/regexp2/v2 v2.8.1 h1:I1jbaCbXeOxdVN8z3fb55Mvtgb94/6+Dh0zjmXjKV/0= github.com/dlclark/regexp2/v2 v2.8.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= github.com/dop251/goja v0.0.0-20261011204819-0c9fae1b959d h1:ONwCIvg9kcijZYa0B9SN/Fo/v7K0UW92HE5oyt3pFvo= @@ -10,5 +12,15 @@ github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/google/pprof v0.0.0-20230207041349-798e818bf904 h1:4/hN5RUoecvl+RmJRE2YxKWtnnQls6rQjjW5oV7qg2U= github.com/google/pprof v0.0.0-20230207041349-798e818bf904/go.mod h1:uglQLonpP8qtYCYyzA+8c/9qtqgA3qsXGYqCPKARAFg= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/maruel/rs v1.1.0 h1:dh4OceAF5yD06EASOrb+DS358LI4g0B90YApSdjCP6U= +github.com/maruel/rs v1.1.0/go.mod h1:vzwMjzSJJxLIXmU62qHj6O5QRn5kvCKxFrfaFCxBcUY= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= +github.com/tuotoo/qrcode v0.0.0-20220425170535-52ccc2bebf5d h1:4x1FeGJRB00cvxnKXnRJDT89fvG/Lzm2ecm0vlr/qDs= +github.com/tuotoo/qrcode v0.0.0-20220425170535-52ccc2bebf5d/go.mod h1:uSELzeIcTceNCgzbKdJuJa0ouCqqtkyzL+6bnA3rM+M= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY= +rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs= diff --git a/internal/cmnet/client.go b/internal/cmnet/client.go index 3e148ce..5ca2605 100644 --- a/internal/cmnet/client.go +++ b/internal/cmnet/client.go @@ -1,6 +1,7 @@ package cmnet import ( + "bytes" "context" "encoding/json" "errors" @@ -49,6 +50,11 @@ type Client struct { crypto pageCrypto channelID string provinces map[string]string + qrToken string + qrChannel string + hosts []string + portal string + scanBase string } func New() *Client { @@ -123,6 +129,7 @@ func (c *Client) SendSMS(ctx context.Context, phone, imageCode string) (string, if err := c.ensureKeys(ctx); err != nil { return "", err } + c.dropAccountSession() encPhone, err := c.crypto.encryptLogin(phone) if err != nil { return "", err @@ -183,6 +190,7 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID if err := c.ensureKeys(ctx); err != nil { return LoginResult{}, err } + c.dropAccountSession() encPhone, err := c.crypto.encryptLogin(phone) if err != nil { return LoginResult{}, err @@ -217,33 +225,36 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID return LoginResult{}, err } var loginRes struct { - Code string `json:"code"` - Desc string `json:"desc"` - Artifact string `json:"artifact"` - Type string `json:"type"` + Code string `json:"code"` + Desc string `json:"desc"` + Artifact string `json:"artifact"` + Type string `json:"type"` + ResultCode string `json:"resultCode"` + ResultDesc string `json:"resultDesc"` } if err := json.Unmarshal(body, &loginRes); err != nil { return LoginResult{}, errors.New("登录结果无法解析") } + if loginRes.Code == "" { + loginRes.Code = loginRes.ResultCode + } + if loginRes.Desc == "" { + loginRes.Desc = loginRes.ResultDesc + } if loginRes.Code != "0000" || loginRes.Artifact == "" { if loginRes.Desc != "" { return LoginResult{}, errors.New(loginRes.Desc) } + if loginRes.Code != "" { + return LoginResult{}, fmt.Errorf("登录失败 %s", loginRes.Code) + } return LoginResult{}, errors.New("登录失败") } - art, err := url.Parse(shopOrigin + "/i/v1/auth/getArtifact") - if err != nil { - return LoginResult{}, err + typ := loginRes.Type + if typ == "" { + typ = "00" } - q := art.Query() - q.Set("backUrl", backURL) - q.Set("artifact", loginRes.Artifact) - if loginRes.Type == "" { - loginRes.Type = "00" - } - q.Set("type", loginRes.Type) - art.RawQuery = q.Encode() - if _, _, err := c.get(ctx, art.String(), c.loginPage()); err != nil { + if err := c.exchangeArtifact(ctx, loginRes.Artifact, typ); err != nil { return LoginResult{}, err } info, err := c.loginfo(ctx) @@ -257,6 +268,275 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID return LoginResult{Phone: phone, ProvCode: prov, ProvName: c.provinceNameLocked(prov)}, nil } +type QRStatus struct { + Waiting bool + Expired bool + Result LoginResult +} + +func (c *Client) QRCode(ctx context.Context) ([]byte, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureKeys(ctx); err != nil { + return nil, err + } + if _, _, err := c.get(ctx, c.loginPage(), c.loginPage()); err != nil { + return nil, err + } + c.clearLoginCookies() + body, ctype, err := c.get(ctx, loginOrigin+"/genqr.htm?timestamp="+milli(), c.loginPage()) + if err != nil { + return nil, err + } + if !strings.Contains(ctype, "image") && !(len(body) > 4 && body[0] == 0x89) { + return nil, errors.New("没有拿到登录二维码") + } + if c.qrToken == "" { + c.qrToken = c.cookieNamed("lgToken") + } + if c.qrToken == "" { + return nil, errors.New("没有拿到扫码凭证") + } + _, _ = c.postForm(ctx, loginOrigin+"/checkBackUrl", url.Values{ + "backUrl": {backURL}, + "channelID": {c.channelID}, + }) + _, _ = c.postForm(ctx, loginOrigin+"/checkUidAvailable.action", url.Values{}) + return c.usableQR(ctx, body), nil +} + +func (c *Client) PollQR(ctx context.Context) (QRStatus, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.qrToken == "" { + c.qrToken = c.cookieNamed("lgToken") + } + if c.qrToken == "" { + return QRStatus{}, errors.New("请先获取二维码") + } + if err := c.ensureKeys(ctx); err != nil { + return QRStatus{}, err + } + status, artifact, err := c.pollChannels(ctx) + if err != nil { + return QRStatus{}, err + } + if status.Expired || status.Waiting || artifact == "" { + return status, nil + } + if err := c.exchangeArtifact(ctx, artifact, ""); err != nil { + return QRStatus{}, err + } + info, err := c.loginfo(ctx) + if err != nil { + return QRStatus{}, err + } + phone, err := restorePhone(asString(info["loginValue"]), asString(info["safeCode"])) + if err != nil { + return QRStatus{}, err + } + prov := asString(info["provice"]) + if prov == "" { + prov = asString(info["province"]) + } + status.Result = LoginResult{Phone: phone, ProvCode: prov, ProvName: c.provinceNameLocked(prov)} + c.qrToken = "" + return status, nil +} + +func (c *Client) exchangeArtifact(ctx context.Context, artifact, typ string) error { + art, err := url.Parse(shopOrigin + "/i/v1/auth/getArtifact") + if err != nil { + return err + } + q := art.Query() + q.Set("backUrl", backURL) + q.Set("artifact", artifact) + if typ != "" { + q.Set("type", typ) + } + art.RawQuery = q.Encode() + _, _, err = c.get(ctx, art.String(), c.loginPage()) + return err +} + +func (c *Client) pollChannels(ctx context.Context) (QRStatus, string, error) { + channels := []string{} + if c.qrChannel != "" { + channels = append(channels, c.qrChannel) + } + if c.channelID != "" && c.channelID != c.qrChannel { + channels = append(channels, c.channelID) + } + if len(channels) == 0 { + channels = []string{""} + } + sawWait := false + var lastErr error + for _, channel := range channels { + body, err := c.postForm(ctx, loginOrigin+"/chkqr.htm", url.Values{ + "lgToken": {c.qrToken}, + "targetChannelID": {channel}, + "backUrl": {url.QueryEscape(backURL)}, + }) + if err != nil { + lastErr = err + continue + } + status, artifact, err := parseQRPoll(bytes.TrimSpace(body)) + if err != nil { + return QRStatus{}, "", err + } + if artifact != "" { + return status, artifact, nil + } + if status.Expired { + continue + } + sawWait = true + } + if sawWait { + return QRStatus{Waiting: true}, "", nil + } + if lastErr != nil { + return QRStatus{}, "", lastErr + } + return QRStatus{Expired: true}, "", nil +} + +func parseQRPoll(body []byte) (QRStatus, string, error) { + if len(body) == 0 { + return QRStatus{Waiting: true}, "", nil + } + var res struct { + ResultCode string `json:"resultCode"` + ResultDesc string `json:"resultDesc"` + Artifact string `json:"artifact"` + } + if err := json.Unmarshal(body, &res); err != nil { + return QRStatus{Waiting: true}, "", nil + } + switch res.ResultCode { + case "": + return QRStatus{Waiting: true}, "", nil + case "0000": + if res.Artifact == "" { + return QRStatus{}, "", errors.New("登录结果缺少凭证") + } + return QRStatus{}, res.Artifact, nil + case "8020": + return QRStatus{Expired: true}, "", nil + default: + if res.ResultDesc != "" { + return QRStatus{}, "", errors.New(res.ResultDesc) + } + return QRStatus{Waiting: true}, "", nil + } +} + +func restorePhone(masked, code string) (string, error) { + masked = strings.TrimSpace(masked) + code = strings.TrimSpace(code) + if strings.Contains(masked, "******") && len(code) == 6 { + phone := strings.Replace(masked, "******", code, 1) + if phoneOK(phone) { + return phone, nil + } + } + if phoneOK(masked) { + return masked, nil + } + return "", errors.New("没有拿到手机号") +} + +func phoneOK(s string) bool { + if len(s) != 11 || s[0] != '1' { + return false + } + for _, c := range s { + if c < '0' || c > '9' { + return false + } + } + return true +} + +func (c *Client) dropAccountSession() { + hosts := []string{loginOrigin + "/", shopOrigin + "/", "https://10086.cn/", "https://www.10086.cn/"} + for _, raw := range hosts { + u, err := url.Parse(raw) + if err != nil { + continue + } + var drop []*http.Cookie + for _, ck := range c.jar.Cookies(u) { + if !accountSessionCookie(ck.Name) { + continue + } + path := ck.Path + if path == "" { + path = "/" + } + drop = append(drop, &http.Cookie{Name: ck.Name, Path: path, MaxAge: -1}) + drop = append(drop, &http.Cookie{Name: ck.Name, Domain: "10086.cn", Path: path, MaxAge: -1}) + } + if len(drop) > 0 { + c.jar.SetCookies(u, drop) + } + } +} + +func accountSessionCookie(name string) bool { + switch name { + case "cmccssotoken", "is_login", "ssologinprovince": + return true + default: + return false + } +} + +func (c *Client) clearLoginCookies() { + c.qrToken = "" + u, err := url.Parse(loginOrigin + "/") + if err != nil { + return + } + var drop []*http.Cookie + for _, ck := range c.jar.Cookies(u) { + if !loginHandshakeCookie(ck.Name) { + continue + } + drop = append(drop, &http.Cookie{Name: ck.Name, Path: ck.Path, MaxAge: -1}) + } + if len(drop) > 0 { + c.jar.SetCookies(u, drop) + } +} + +func loginHandshakeCookie(name string) bool { + switch name { + case "lgToken", "cvToken", "CaptchaCode", "jsessionid-cmcc", "rdmdmd5", "sendflag": + return true + default: + return false + } +} + +func (c *Client) cookieNamed(name string) string { + for _, raw := range []string{loginOrigin + "/", "https://10086.cn/", shopOrigin + "/"} { + u, err := url.Parse(raw) + if err != nil { + continue + } + for _, ck := range c.jar.Cookies(u) { + if ck.Name == name && ck.Value != "" { + return ck.Value + } + } + } + return "" +} + func (c *Client) Query(ctx context.Context, phone, prov string) (json.RawMessage, json.RawMessage, error) { c.mu.Lock() defer c.mu.Unlock() @@ -394,6 +674,7 @@ func (c *Client) fetchShopScript(ctx context.Context) error { if err != nil { return err } + c.noteLinks(string(page)) var cryptoJS, bundle string err = c.readScripts(ctx, string(page), shopOrigin, shopOrigin+"/i/?f=packremainqry", func(src string) bool { if cryptoJS == "" && isCryptoJSLib(src) { @@ -421,6 +702,7 @@ func (c *Client) fetchShopScript(ctx context.Context) error { if err != nil { return err } + c.noteLinks(bundle) c.provinces = provinces c.channelID = channel c.crypto.cryptoJS = cryptoJS @@ -541,6 +823,13 @@ func (c *Client) do(req *http.Request) ([]byte, string, error) { if err != nil { return nil, "", err } + if req.URL != nil && req.URL.Hostname() == "login.10086.cn" { + for _, ck := range resp.Cookies() { + if ck.Name == "lgToken" && ck.Value != "" { + c.qrToken = ck.Value + } + } + } if resp.StatusCode >= 400 && !strings.Contains(resp.Header.Get("Content-Type"), "json") { return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode) } diff --git a/internal/cmnet/crypto_test.go b/internal/cmnet/crypto_test.go index 2285016..d125962 100644 --- a/internal/cmnet/crypto_test.go +++ b/internal/cmnet/crypto_test.go @@ -287,6 +287,83 @@ func TestCalibrateUsesNativeWhenScriptAgrees(t *testing.T) { } } +func TestDecryptQRLoginfo(t *testing.T) { + z, err := zip.OpenReader("../../cmnet-qcode.chlz") + if err != nil { + t.Skip(err) + } + defer z.Close() + raw := map[string][]byte{} + for _, f := range z.File { + r, err := f.Open() + if err != nil { + t.Fatal(err) + } + b, err := io.ReadAll(r) + r.Close() + if err != nil { + t.Fatal(err) + } + raw[f.Name] = b + } + var outParam string + for name, body := range raw { + if !strings.HasSuffix(name, "-meta.json") { + continue + } + var meta struct { + Path string `json:"path"` + } + if json.Unmarshal(body, &meta) != nil || !strings.Contains(meta.Path, "loginfo") { + continue + } + id := strings.TrimSuffix(name, "-meta.json") + res := raw[id+"-res.json"] + var wrap struct { + RetCode string `json:"retCode"` + Data struct { + OutParam string `json:"outParam"` + } `json:"data"` + } + if json.Unmarshal(res, &wrap) != nil || wrap.RetCode != "000000" || wrap.Data.OutParam == "" { + continue + } + outParam = wrap.Data.OutParam + break + } + if outParam == "" { + t.Fatal("no loginfo payload") + } + shopFiles := readCapture(t, "81-res.js", "123-res.js") + enc, dec, keyExpr, err := extractAES(string(shopFiles["81-res.js"])) + if err != nil { + t.Fatal(err) + } + crypto := pageCrypto{cryptoJS: string(shopFiles["123-res.js"]), aesEnc: enc, aesDec: dec, keyExpr: keyExpr} + crypto.calibrateAES() + plain, err := crypto.decryptOutParam(outParam) + if err != nil { + t.Fatal(err) + } + var info map[string]any + if err := json.Unmarshal(plain, &info); err != nil { + t.Fatalf("plain json %v len %d", err, len(plain)) + } + _, hasLogin := info["loginValue"] + _, hasSafe := info["safeCode"] + if !hasLogin || !hasSafe { + t.Fatalf("keys %v", keysOf(info)) + } +} + +func keysOf(m map[string]any) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + return out +} + func TestParseShopScriptRequiresPageData(t *testing.T) { src := `b=["aaaa","xxxx","bbbb","aaaa","cccc","bbbb","dddd","cccc"]` if _, _, err := parseShopScript(src); err == nil { diff --git a/internal/cmnet/js.go b/internal/cmnet/js.go index 08eb814..ba7fa6e 100644 --- a/internal/cmnet/js.go +++ b/internal/cmnet/js.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "encoding/json" "errors" + "fmt" "net/url" "strings" "time" @@ -103,10 +104,10 @@ func (p *pageCrypto) callAES(decrypt bool, text string) (string, error) { return "", err } if err := runJS(vm, p.cryptoJS); err != nil { - return "", errors.New("个人中心脚本无法执行") + return "", fmt.Errorf("个人中心脚本无法执行: %w", err) } if err := runJS(vm, "var __enc = "+p.aesEnc+"; var __dec = "+p.aesDec+"; var __key = "+p.keyExpr+";"); err != nil { - return "", errors.New("个人中心脚本无法执行") + return "", fmt.Errorf("个人中心脚本无法执行: %w", err) } name := "__enc" if decrypt { @@ -118,7 +119,7 @@ func (p *pageCrypto) callAES(decrypt bool, text string) (string, error) { } out, err := fn(goja.Undefined(), vm.ToValue(text), vm.Get("__key"), vm.Get("__key")) if err != nil { - return "", errors.New("个人中心脚本无法执行") + return "", fmt.Errorf("个人中心脚本无法执行: %w", err) } got := strings.TrimSpace(out.String()) if got == "" || got == "undefined" || got == "null" { @@ -573,7 +574,8 @@ func isLoginEncryptCaller(src string) bool { } func isCryptoJSLib(src string) bool { - return strings.Contains(src, "CryptoJS=CryptoJS") || strings.Contains(src, "var CryptoJS=") + marked := strings.Contains(src, "CryptoJS=CryptoJS") || strings.Contains(src, "var CryptoJS=") + return marked && strings.Contains(src, ".AES=") } func isShopCryptoBundle(src string) bool { diff --git a/internal/cmnet/qr_test.go b/internal/cmnet/qr_test.go new file mode 100644 index 0000000..92748cf --- /dev/null +++ b/internal/cmnet/qr_test.go @@ -0,0 +1,28 @@ +package cmnet + +import "testing" + +func TestRestorePhone(t *testing.T) { + phone, err := restorePhone("138******00", "000000") + if err != nil || phone != "13800000000" { + t.Fatalf("phone %s %v", phone, err) + } + if _, err := restorePhone("138****0000", "0000"); err == nil { + t.Fatal("short code should fail") + } +} + +func TestParseQRPoll(t *testing.T) { + waiting, artifact, err := parseQRPoll(nil) + if err != nil || !waiting.Waiting || artifact != "" { + t.Fatalf("empty %+v %s %v", waiting, artifact, err) + } + expired, artifact, err := parseQRPoll([]byte(`{"resultCode":"8020"}`)) + if err != nil || !expired.Expired { + t.Fatalf("expired %+v %v", expired, err) + } + ok, artifact, err := parseQRPoll([]byte(`{"resultCode":"0000","artifact":"abc","resultDesc":"登录成功"}`)) + if err != nil || artifact != "abc" || ok.Waiting || ok.Expired { + t.Fatalf("ok %+v %s %v", ok, artifact, err) + } +} diff --git a/internal/cmnet/qrpage.go b/internal/cmnet/qrpage.go new file mode 100644 index 0000000..5ef439a --- /dev/null +++ b/internal/cmnet/qrpage.go @@ -0,0 +1,380 @@ +package cmnet + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strings" + "time" + + skipqr "github.com/skip2/go-qrcode" + tqr "github.com/tuotoo/qrcode" +) + +const scanProbeTimeout = 8 * time.Second + +var ( + httpURLRE = regexp.MustCompile(`https?://[a-zA-Z0-9.-]+(?::\d+)?(?:/[^\s"'<>\\]*)?`) + provCodeRE = regexp.MustCompile(`\{"code":(\d+),"name":"[^"]*"(?:,"[A-Za-z]+":"[^"]*")*,"abbr":"([a-z]+)"\}`) + indexExprRE = regexp.MustCompile(`["'](\./index_)["']\s*\+\s*[A-Za-z0-9_]+\s*\+\s*["'](_)["']\s*\+\s*[A-Za-z0-9_]+\s*\+\s*["'](\.html)["']`) + indexLinkRE = regexp.MustCompile(`https?://[a-zA-Z0-9.-]+/index/[a-z]{2,3}`) + submitChannelRE = regexp.MustCompile(`submitqr\.htm[\s\S]{0,400}?channelID['"]\s*:\s*['"](\d+)['"]`) +) + +func (c *Client) noteLinks(text string) { + for _, host := range carrierHosts(text) { + if !hasString(c.hosts, host) { + c.hosts = append(c.hosts, host) + } + } + if c.portal == "" { + c.portal = portalRoot(text) + } +} + +func (c *Client) usableQR(ctx context.Context, png []byte) []byte { + token := c.qrToken + defer func() { c.qrToken = token }() + text, err := decodeQRText(png) + if err != nil || text == "" { + return png + } + target, err := url.Parse(text) + if err != nil || target.Scheme == "" || target.Host == "" { + return png + } + if c.scanBase != "" { + return redrawQR(applyBase(c.scanBase, target), png) + } + if c.isScanPage(ctx, target.String()) { + c.scanBase = baseOf(target) + return png + } + base := c.findScanBase(ctx, target) + if base == "" { + return png + } + c.scanBase = base + return redrawQR(applyBase(base, target), png) +} + +func (c *Client) findScanBase(ctx context.Context, orig *url.URL) string { + if base := c.probeHosts(ctx, orig, c.hosts, true); base != "" { + return base + } + if c.portal == "" { + return "" + } + body, err := fetchPublic(ctx, c.portal) + if err != nil { + return "" + } + text := string(body) + pageURL := c.portal + for i := 0; i < 3; i++ { + if base := c.probeHosts(ctx, orig, carrierHosts(text), true); base != "" { + return base + } + next := nextPortalPage(pageURL, text) + if next == "" || samePage(next, pageURL) { + return c.probeHosts(ctx, orig, carrierHosts(text), false) + } + body, err = fetchPublic(ctx, next) + if err != nil { + return "" + } + text = string(body) + pageURL = next + } + return c.probeHosts(ctx, orig, carrierHosts(text), false) +} + +func (c *Client) probeHosts(ctx context.Context, orig *url.URL, hosts []string, appOnly bool) string { + list := orderedHosts(hosts, orig.Hostname()) + if appOnly { + var kept []string + for _, host := range list { + if strings.Contains(host, "app") { + kept = append(kept, host) + } + } + list = kept + } else if len(list) > 8 { + list = list[:8] + } + for _, host := range list { + cand := cloneURL(orig, host) + if !c.isScanPage(ctx, cand) { + continue + } + u, err := url.Parse(cand) + if err != nil { + continue + } + return baseOf(u) + } + return "" +} + +func (c *Client) isScanPage(ctx context.Context, rawURL string) bool { + body, err := fetchPublic(ctx, rawURL) + if err != nil || !isScanLoginPage(body) { + return false + } + c.learnScanChannel(ctx, rawURL, body) + return true +} + +func (c *Client) learnScanChannel(ctx context.Context, pageURL string, html []byte) { + if c.qrChannel != "" { + return + } + for _, ref := range scriptSrcs(string(html)) { + low := strings.ToLower(ref) + if !strings.Contains(low, "scancode") && !strings.Contains(low, "/transit/js/") { + continue + } + body, err := fetchPublic(ctx, absURL(pageURL, ref)) + if err != nil { + continue + } + if channel := submitChannel(string(body)); channel != "" { + c.qrChannel = channel + return + } + } +} + +func submitChannel(src string) string { + item := submitChannelRE.FindStringSubmatch(src) + if item == nil { + return "" + } + return item[1] +} + +var publicHTTP = &http.Client{Timeout: scanProbeTimeout} + +func fetchPublic(ctx context.Context, rawURL string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", userAgent) + req.Header.Set("Accept", "*/*") + resp, err := publicHTTP.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + buf, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return nil, err + } + if resp.StatusCode >= 400 { + return nil, fmt.Errorf("网站返回 %d", resp.StatusCode) + } + return buf, nil +} + +func isScanLoginPage(body []byte) bool { + return bytes.Contains(body, []byte("scancode")) && bytes.Contains(body, []byte("扫码登录")) +} + +func redrawQR(text string, fallback []byte) []byte { + png, err := encodeQR(text) + if err != nil || len(png) == 0 { + return fallback + } + return png +} + +func encodeQR(text string) ([]byte, error) { + return skipqr.Encode(text, skipqr.Medium, 336) +} + +func decodeQRText(png []byte) (string, error) { + mx, err := tqr.Decode(bytes.NewReader(png)) + if err != nil { + return "", err + } + return strings.TrimSpace(mx.Content), nil +} + +func chooseScanTarget(original string, hosts []string, page func(string) []byte) string { + if isScanLoginPage(page(original)) { + return original + } + target, err := url.Parse(original) + if err != nil || target.Host == "" { + return "" + } + for _, host := range orderedHosts(hosts, target.Hostname()) { + cand := cloneURL(target, host) + if isScanLoginPage(page(cand)) { + return cand + } + } + return "" +} + +func nextPortalPage(pageURL, body string) string { + u, err := url.Parse(pageURL) + if err != nil { + return "" + } + if abbr := pathAbbr(u.Path); abbr != "" { + if code := codeForAbbr(body, abbr); code != "" { + if file := buildIndexFile(body, code); file != "" { + ref, err := url.Parse(file) + if err == nil { + if !strings.HasSuffix(u.Path, "/") { + u.Path += "/" + } + return u.ResolveReference(ref).String() + } + } + } + } + link := indexLinkRE.FindString(body) + if link == "" || samePage(link, pageURL) { + return "" + } + return link +} + +func codeForAbbr(body, abbr string) string { + for _, item := range provCodeRE.FindAllStringSubmatch(body, -1) { + if item[2] == abbr { + return item[1] + } + } + return "" +} + +func buildIndexFile(body, code string) string { + item := indexExprRE.FindStringSubmatch(body) + if item == nil || code == "" { + return "" + } + return item[1] + code + item[2] + code + item[3] +} + +func portalRoot(text string) string { + for _, raw := range httpURLs(text) { + u, err := url.Parse(raw) + if err != nil || u.Hostname() != "www.10086.cn" { + continue + } + if u.Path != "" && u.Path != "/" { + continue + } + return "https://www.10086.cn/" + } + return "" +} + +func carrierHosts(text string) []string { + var out []string + seen := map[string]bool{} + for _, raw := range httpURLs(text) { + u, err := url.Parse(raw) + if err != nil { + continue + } + host := u.Hostname() + if host == "" || seen[host] || !strings.HasSuffix(host, "10086.cn") { + continue + } + seen[host] = true + out = append(out, host) + } + return out +} + +func httpURLs(text string) []string { + found := httpURLRE.FindAllString(text, -1) + out := make([]string, 0, len(found)) + for _, raw := range found { + out = append(out, strings.TrimRight(raw, ".,);")) + } + return out +} + +func orderedHosts(hosts []string, skip string) []string { + var app, rest []string + seen := map[string]bool{} + for _, host := range hosts { + host = strings.TrimSpace(host) + if host == "" || host == skip || seen[host] { + continue + } + seen[host] = true + if strings.Contains(host, "app") { + app = append(app, host) + } else { + rest = append(rest, host) + } + } + return append(app, rest...) +} + +func cloneURL(orig *url.URL, host string) string { + u := *orig + u.Scheme = "https" + u.Host = host + return u.String() +} + +func baseOf(u *url.URL) string { + return u.Scheme + "://" + u.Host + u.EscapedPath() +} + +func applyBase(base string, orig *url.URL) string { + u, err := url.Parse(base) + if err != nil { + return orig.String() + } + u.RawQuery = orig.RawQuery + return u.String() +} + +func pathAbbr(path string) string { + path = strings.Trim(path, "/") + if path == "" { + return "" + } + parts := strings.Split(path, "/") + last := parts[len(parts)-1] + if len(last) < 2 || len(last) > 3 { + return "" + } + for _, r := range last { + if r < 'a' || r > 'z' { + return "" + } + } + return last +} + +func samePage(a, b string) bool { + ua, errA := url.Parse(a) + ub, errB := url.Parse(b) + if errA != nil || errB != nil { + return a == b + } + return strings.EqualFold(ua.Hostname(), ub.Hostname()) && strings.TrimRight(ua.Path, "/") == strings.TrimRight(ub.Path, "/") +} + +func hasString(list []string, item string) bool { + for _, cur := range list { + if cur == item { + return true + } + } + return false +} diff --git a/internal/cmnet/qrpage_test.go b/internal/cmnet/qrpage_test.go new file mode 100644 index 0000000..ce13fc2 --- /dev/null +++ b/internal/cmnet/qrpage_test.go @@ -0,0 +1,310 @@ +package cmnet + +import ( + "context" + "encoding/json" + "net/http" + "net/url" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +func TestScanPageRecognition(t *testing.T) { + page := []byte(`
请使用中国移动客户端扫码登录
`)) { + t.Fatal("login hint without the scan script should not match") + } +} + +func TestChooseScanTarget(t *testing.T) { + orig := "https://app.10086.cn/activity/transit/scancode.html?lgToken=abc" + live := "https://h.app.coc.10086.cn/activity/transit/scancode.html?lgToken=abc" + pages := map[string][]byte{ + orig: []byte(`404 Not Found`), + live: []byte(`