Files

336 lines
9.5 KiB
Go

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)
}
shop, err := url.Parse("https://shop.10086.cn/i/")
if err != nil {
t.Fatal(err)
}
c.jar.SetCookies(u, []*http.Cookie{
{Name: "cmccssotoken", Value: "old", Domain: "10086.cn", Path: "/"},
{Name: "is_login", Value: "true", Domain: "10086.cn", Path: "/"},
{Name: "CaptchaCode", Value: "ab", Path: "/"},
})
c.dropAccountSession()
c.jar.SetCookies(u, []*http.Cookie{
{Name: "cmccssotoken", Value: "new", Domain: "10086.cn", Path: "/"},
{Name: "ssologinprovince", Value: "200", Domain: "10086.cn", Path: "/"},
})
var names []string
for _, ck := range c.jar.Cookies(shop) {
names = append(names, ck.Name+"="+ck.Value)
}
joined := strings.Join(names, ",")
if !strings.Contains(joined, "cmccssotoken=new") || !strings.Contains(joined, "ssologinprovince=200") {
t.Fatalf("shop cookies %s", joined)
}
var loginNames []string
for _, ck := range c.jar.Cookies(u) {
loginNames = append(loginNames, ck.Name)
}
if !containsName(loginNames, "CaptchaCode") {
t.Fatalf("captcha cookie missing %v", loginNames)
}
}
func containsName(list []string, name string) bool {
for _, item := range list {
if item == name || strings.HasPrefix(item, name+"=") {
return true
}
}
return false
}
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")
}
}