feat: 移动增加扫码登录并支持换号短信登录
This commit is contained in:
+305
-16
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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(`<title>扫码登录</title><script src="/activity/transit/js/scancode.js"></script><div id="btn_land">登录</div>`)
|
||||
if !isScanLoginPage(page) {
|
||||
t.Fatal("scan page should match")
|
||||
}
|
||||
if isScanLoginPage([]byte(`<html><h1>404 Not Found</h1></html>`)) {
|
||||
t.Fatal("404 should not match")
|
||||
}
|
||||
if isScanLoginPage([]byte(`<p>请使用中国移动客户端扫码登录</p>`)) {
|
||||
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(`<html>404 Not Found</html>`),
|
||||
live: []byte(`<title>扫码登录</title><script src="scancode.js"></script>`),
|
||||
}
|
||||
got := chooseScanTarget(orig, []string{"touch.10086.cn", "h.app.coc.10086.cn"}, func(raw string) []byte {
|
||||
return pages[raw]
|
||||
})
|
||||
if got != live {
|
||||
t.Fatalf("target %s", got)
|
||||
}
|
||||
if chooseScanTarget(live, nil, func(raw string) []byte { return pages[raw] }) != live {
|
||||
t.Fatal("working url should stay")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPortalHop(t *testing.T) {
|
||||
root := `<a href="http://www.10086.cn/">首页</a>`
|
||||
if portalRoot(root) != "https://www.10086.cn/" {
|
||||
t.Fatalf("portal %s", portalRoot(root))
|
||||
}
|
||||
chooser := `{"code":100,"name":"北京","href":"http://www.10086.cn/index/bj","url":"http://shop.10086.cn/mall_100_100.html","abbr":"bj"}`
|
||||
next := nextPortalPage("https://www.10086.cn/", chooser)
|
||||
if next != "http://www.10086.cn/index/bj" {
|
||||
t.Fatalf("index link %s", next)
|
||||
}
|
||||
redirector := `{"code":100,"name":"北京","abbr":"bj"}
|
||||
gourl = "./index_" + CmProvNum + "_" + CmCityid + ".html";`
|
||||
file := nextPortalPage(next, redirector)
|
||||
if file != "http://www.10086.cn/index/bj/index_100_100.html" {
|
||||
t.Fatalf("index file %s", file)
|
||||
}
|
||||
hosts := carrierHosts(`<a href="https://h.app.coc.10086.cn/cmcc-app/pc-pages/tariffZonePers.html?prov=100">资费</a>`)
|
||||
if len(hosts) != 1 || hosts[0] != "h.app.coc.10086.cn" {
|
||||
t.Fatalf("hosts %v", hosts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveScanPage(t *testing.T) {
|
||||
if os.Getenv("CMNET_LIVE") == "" {
|
||||
t.Skip()
|
||||
}
|
||||
c := New()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||
defer cancel()
|
||||
c.portal = "https://www.10086.cn/"
|
||||
orig, err := url.Parse("https://app.10086.cn/activity/transit/scancode.html?lgToken=probe")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := c.findScanBase(ctx, orig)
|
||||
if base == "" || !c.isScanPage(ctx, base) {
|
||||
t.Fatalf("scan page %s", base)
|
||||
}
|
||||
t.Log(base)
|
||||
}
|
||||
|
||||
func TestLiveQRPoll(t *testing.T) {
|
||||
if os.Getenv("CMNET_LIVE") == "" {
|
||||
t.Skip()
|
||||
}
|
||||
c := New()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
if err := c.ensureKeys(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := c.get(ctx, c.loginPage(), c.loginPage()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _, err := c.get(ctx, loginOrigin+"/genqr.htm?timestamp="+milli(), c.loginPage())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text, err := decodeQRText(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(text)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := u.Query().Get("lgToken")
|
||||
firstMatch := q == c.qrToken
|
||||
body2, _, err := c.get(ctx, loginOrigin+"/genqr.htm?timestamp="+milli(), c.loginPage())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text2, err := decodeQRText(body2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u2, err := url.Parse(text2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q2 := u2.Query().Get("lgToken")
|
||||
secondMatch := q2 == c.qrToken
|
||||
_, _ = c.postForm(ctx, loginOrigin+"/checkBackUrl", url.Values{"backUrl": {backURL}, "channelID": {c.channelID}})
|
||||
_, _ = c.postForm(ctx, loginOrigin+"/checkUidAvailable.action", url.Values{})
|
||||
_ = c.usableQR(ctx, body2)
|
||||
st, err := c.PollQR(ctx)
|
||||
t.Logf("first %v second %v same %v after %v waiting %v expired %v err %v", firstMatch, secondMatch, q == q2, q2 == c.qrToken, st.Waiting, st.Expired, err)
|
||||
}
|
||||
|
||||
func TestLiveImageToken(t *testing.T) {
|
||||
if os.Getenv("CMNET_LIVE") == "" {
|
||||
t.Skip()
|
||||
}
|
||||
c := New()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
png, err := c.QRCode(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
pngPath := dir + "/qr.png"
|
||||
tokenPath := dir + "/token.txt"
|
||||
if err := os.WriteFile(pngPath, png, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(tokenPath, []byte(c.qrToken), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := `
|
||||
const fs = require("fs");
|
||||
const { PNG } = require("./Temp/node_modules/pngjs");
|
||||
const jsQR = require("./Temp/node_modules/jsqr");
|
||||
const png = PNG.sync.read(fs.readFileSync(process.argv[1]));
|
||||
const code = jsQR(new Uint8ClampedArray(png.data), png.width, png.height);
|
||||
const token = fs.readFileSync(process.argv[2], "utf8");
|
||||
if (!code) { console.log("decode-failed"); process.exit(0); }
|
||||
const u = new URL(code.data);
|
||||
console.log(u.searchParams.get("lgToken") === token ? "match" : "mismatch");
|
||||
console.log("host " + u.host);
|
||||
`
|
||||
cmd := exec.Command("node", "-e", script, pngPath, tokenPath)
|
||||
cmd.Dir = "../.."
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatal(err, string(out))
|
||||
}
|
||||
t.Log(strings.TrimSpace(string(out)))
|
||||
t.Logf("scanChannel %s pageChannel %s", c.qrChannel, c.channelID)
|
||||
st, err := c.PollQR(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("waiting %v expired %v", st.Waiting, st.Expired)
|
||||
}
|
||||
|
||||
func TestLiveSavedCookie(t *testing.T) {
|
||||
if os.Getenv("CMNET_LIVE") == "" {
|
||||
t.Skip()
|
||||
}
|
||||
raw, err := os.ReadFile("../../data/state.json")
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
var st struct {
|
||||
Cookies []Cookie `json:"cookies"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := New()
|
||||
c.ImportCookies(st.Cookies)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
if err := c.ensureKeys(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := c.get(ctx, c.loginPage(), c.loginPage()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.clearLoginCookies()
|
||||
body, _, err := c.get(ctx, loginOrigin+"/genqr.htm?timestamp="+milli(), c.loginPage())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text, err := decodeQRText(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(text)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := u.Query().Get("lgToken")
|
||||
if q == "" || q != c.qrToken {
|
||||
t.Fatal("image token was not kept")
|
||||
}
|
||||
stPoll, err := c.PollQR(ctx)
|
||||
if err != nil || !stPoll.Waiting || stPoll.Expired {
|
||||
t.Fatalf("waiting %v expired %v err %v", stPoll.Waiting, stPoll.Expired, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveShopCrypto(t *testing.T) {
|
||||
if os.Getenv("CMNET_LIVE") == "" {
|
||||
t.Skip()
|
||||
}
|
||||
c := New()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||
defer cancel()
|
||||
if err := c.ensureKeys(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm, err := newBrowserVM()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := runJS(vm, c.crypto.cryptoJS); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := vm.RunString(`(typeof CryptoJS)+" aes="+(CryptoJS&&CryptoJS.AES?"yes":"no")`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(got.String(), "aes=yes") {
|
||||
t.Fatalf("library %s bytes %d", got.String(), len(c.crypto.cryptoJS))
|
||||
}
|
||||
if !c.crypto.useNativeAES {
|
||||
t.Fatal("shop AES should match the native implementation")
|
||||
}
|
||||
token, err := c.crypto.encryptAES("probe")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
back, err := c.crypto.decryptAES(token)
|
||||
if err != nil || back != "probe" {
|
||||
t.Fatalf("roundtrip %q %v", back, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropAccountSession(t *testing.T) {
|
||||
c := New()
|
||||
u, err := url.Parse("https://login.10086.cn/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.jar.SetCookies(u, []*http.Cookie{
|
||||
{Name: "cmccssotoken", Value: "tok", Domain: "10086.cn", Path: "/"},
|
||||
{Name: "is_login", Value: "true", Domain: "10086.cn", Path: "/"},
|
||||
{Name: "CaptchaCode", Value: "ab", Path: "/"},
|
||||
})
|
||||
c.dropAccountSession()
|
||||
var left []string
|
||||
for _, ck := range c.jar.Cookies(u) {
|
||||
left = append(left, ck.Name)
|
||||
}
|
||||
if len(left) != 1 || left[0] != "CaptchaCode" {
|
||||
t.Fatalf("cookies %v", left)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitChannel(t *testing.T) {
|
||||
src := `$.ajax({url:'https://login.10086.cn/submitqr.htm',data:{'UID':uid,'lgToken':q,'channelID':'12008'}})`
|
||||
if submitChannel(src) != "12008" {
|
||||
t.Fatalf("channel %s", submitChannel(src))
|
||||
}
|
||||
if submitChannel("no submit here") != "" {
|
||||
t.Fatal("missing call should not match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQREncode(t *testing.T) {
|
||||
text := "https://example.com/activity/transit/scancode.html?lgToken=abc"
|
||||
png, err := encodeQR(text)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(png) < 8 || string(png[:8]) != "\x89PNG\r\n\x1a\n" {
|
||||
t.Fatal("encode should return a png")
|
||||
}
|
||||
again := redrawQR(text, []byte("nope"))
|
||||
if string(again[:8]) != "\x89PNG\r\n\x1a\n" {
|
||||
t.Fatal("redraw should be a png")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user