feat: 移动增加扫码登录并支持换号短信登录
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
# 移动账户
|
# 移动账户
|
||||||
|
|
||||||
给自己的中国移动号码看话费余额、当月消费和套餐余量。页面只读,登录后按设定间隔自动刷新。登录方式是手机号、图形验证码和短信验证码。扫码登录没有做。
|
给自己的中国移动号码看话费余额、当月消费和套餐余量。页面只读,登录后按设定间隔自动刷新。登录可以用短信验证码,也可以用中国移动 App 扫页面上的二维码。
|
||||||
|
|
||||||
页面没有访问口令,只放在自己的机器上。
|
页面没有访问口令,只放在自己的机器上。
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@
|
|||||||
|
|
||||||
间隔和随机分钟在页面里保存后,以 `data/state.json` 为准。
|
间隔和随机分钟在页面里保存后,以 `data/state.json` 为准。
|
||||||
|
|
||||||
登录页先填手机号和图形验证码,再获取短信。这个号码上次的会话还在时,点登录会直接进入主页。退出只回到登录页,不向移动注销,也不再自动刷新。
|
短信登录先填手机号和图形验证码,再获取短信。扫码登录点「扫码」,用中国移动 App 扫二维码。这个号码上次的会话还在时,点登录会直接进入主页。退出只回到登录页,不向移动注销,也不再自动刷新。
|
||||||
|
|
||||||
## 编译
|
## 编译
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,18 @@ module cmnetsmsinfo
|
|||||||
|
|
||||||
go 1.26.0
|
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 (
|
require (
|
||||||
github.com/dlclark/regexp2/v2 v2.8.1 // indirect
|
github.com/dlclark/regexp2/v2 v2.8.1 // indirect
|
||||||
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
|
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
|
||||||
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // 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
|
golang.org/x/text v0.43.0 // indirect
|
||||||
|
rsc.io/qr v0.2.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
|
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/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 h1:I1jbaCbXeOxdVN8z3fb55Mvtgb94/6+Dh0zjmXjKV/0=
|
||||||
github.com/dlclark/regexp2/v2 v2.8.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
|
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=
|
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/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 h1:4/hN5RUoecvl+RmJRE2YxKWtnnQls6rQjjW5oV7qg2U=
|
||||||
github.com/google/pprof v0.0.0-20230207041349-798e818bf904/go.mod h1:uglQLonpP8qtYCYyzA+8c/9qtqgA3qsXGYqCPKARAFg=
|
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 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
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=
|
||||||
|
|||||||
+305
-16
@@ -1,6 +1,7 @@
|
|||||||
package cmnet
|
package cmnet
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
@@ -49,6 +50,11 @@ type Client struct {
|
|||||||
crypto pageCrypto
|
crypto pageCrypto
|
||||||
channelID string
|
channelID string
|
||||||
provinces map[string]string
|
provinces map[string]string
|
||||||
|
qrToken string
|
||||||
|
qrChannel string
|
||||||
|
hosts []string
|
||||||
|
portal string
|
||||||
|
scanBase string
|
||||||
}
|
}
|
||||||
|
|
||||||
func New() *Client {
|
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 {
|
if err := c.ensureKeys(ctx); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
c.dropAccountSession()
|
||||||
encPhone, err := c.crypto.encryptLogin(phone)
|
encPhone, err := c.crypto.encryptLogin(phone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -183,6 +190,7 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID
|
|||||||
if err := c.ensureKeys(ctx); err != nil {
|
if err := c.ensureKeys(ctx); err != nil {
|
||||||
return LoginResult{}, err
|
return LoginResult{}, err
|
||||||
}
|
}
|
||||||
|
c.dropAccountSession()
|
||||||
encPhone, err := c.crypto.encryptLogin(phone)
|
encPhone, err := c.crypto.encryptLogin(phone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return LoginResult{}, err
|
return LoginResult{}, err
|
||||||
@@ -217,33 +225,36 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID
|
|||||||
return LoginResult{}, err
|
return LoginResult{}, err
|
||||||
}
|
}
|
||||||
var loginRes struct {
|
var loginRes struct {
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
Desc string `json:"desc"`
|
Desc string `json:"desc"`
|
||||||
Artifact string `json:"artifact"`
|
Artifact string `json:"artifact"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
|
ResultCode string `json:"resultCode"`
|
||||||
|
ResultDesc string `json:"resultDesc"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(body, &loginRes); err != nil {
|
if err := json.Unmarshal(body, &loginRes); err != nil {
|
||||||
return LoginResult{}, errors.New("登录结果无法解析")
|
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.Code != "0000" || loginRes.Artifact == "" {
|
||||||
if loginRes.Desc != "" {
|
if loginRes.Desc != "" {
|
||||||
return LoginResult{}, errors.New(loginRes.Desc)
|
return LoginResult{}, errors.New(loginRes.Desc)
|
||||||
}
|
}
|
||||||
|
if loginRes.Code != "" {
|
||||||
|
return LoginResult{}, fmt.Errorf("登录失败 %s", loginRes.Code)
|
||||||
|
}
|
||||||
return LoginResult{}, errors.New("登录失败")
|
return LoginResult{}, errors.New("登录失败")
|
||||||
}
|
}
|
||||||
art, err := url.Parse(shopOrigin + "/i/v1/auth/getArtifact")
|
typ := loginRes.Type
|
||||||
if err != nil {
|
if typ == "" {
|
||||||
return LoginResult{}, err
|
typ = "00"
|
||||||
}
|
}
|
||||||
q := art.Query()
|
if err := c.exchangeArtifact(ctx, loginRes.Artifact, typ); err != nil {
|
||||||
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 {
|
|
||||||
return LoginResult{}, err
|
return LoginResult{}, err
|
||||||
}
|
}
|
||||||
info, err := c.loginfo(ctx)
|
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
|
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) {
|
func (c *Client) Query(ctx context.Context, phone, prov string) (json.RawMessage, json.RawMessage, error) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
@@ -394,6 +674,7 @@ func (c *Client) fetchShopScript(ctx context.Context) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
c.noteLinks(string(page))
|
||||||
var cryptoJS, bundle string
|
var cryptoJS, bundle string
|
||||||
err = c.readScripts(ctx, string(page), shopOrigin, shopOrigin+"/i/?f=packremainqry", func(src string) bool {
|
err = c.readScripts(ctx, string(page), shopOrigin, shopOrigin+"/i/?f=packremainqry", func(src string) bool {
|
||||||
if cryptoJS == "" && isCryptoJSLib(src) {
|
if cryptoJS == "" && isCryptoJSLib(src) {
|
||||||
@@ -421,6 +702,7 @@ func (c *Client) fetchShopScript(ctx context.Context) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
c.noteLinks(bundle)
|
||||||
c.provinces = provinces
|
c.provinces = provinces
|
||||||
c.channelID = channel
|
c.channelID = channel
|
||||||
c.crypto.cryptoJS = cryptoJS
|
c.crypto.cryptoJS = cryptoJS
|
||||||
@@ -541,6 +823,13 @@ func (c *Client) do(req *http.Request) ([]byte, string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
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") {
|
if resp.StatusCode >= 400 && !strings.Contains(resp.Header.Get("Content-Type"), "json") {
|
||||||
return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode)
|
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) {
|
func TestParseShopScriptRequiresPageData(t *testing.T) {
|
||||||
src := `b=["aaaa","xxxx","bbbb","aaaa","cccc","bbbb","dddd","cccc"]`
|
src := `b=["aaaa","xxxx","bbbb","aaaa","cccc","bbbb","dddd","cccc"]`
|
||||||
if _, _, err := parseShopScript(src); err == nil {
|
if _, _, err := parseShopScript(src); err == nil {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -103,10 +104,10 @@ func (p *pageCrypto) callAES(decrypt bool, text string) (string, error) {
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if err := runJS(vm, p.cryptoJS); err != nil {
|
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 {
|
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"
|
name := "__enc"
|
||||||
if decrypt {
|
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"))
|
out, err := fn(goja.Undefined(), vm.ToValue(text), vm.Get("__key"), vm.Get("__key"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.New("个人中心脚本无法执行")
|
return "", fmt.Errorf("个人中心脚本无法执行: %w", err)
|
||||||
}
|
}
|
||||||
got := strings.TrimSpace(out.String())
|
got := strings.TrimSpace(out.String())
|
||||||
if got == "" || got == "undefined" || got == "null" {
|
if got == "" || got == "undefined" || got == "null" {
|
||||||
@@ -573,7 +574,8 @@ func isLoginEncryptCaller(src string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func isCryptoJSLib(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 {
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -134,6 +134,8 @@ func main() {
|
|||||||
mux.HandleFunc("GET /api/captcha", app.captcha)
|
mux.HandleFunc("GET /api/captcha", app.captcha)
|
||||||
mux.HandleFunc("POST /api/sms", app.sms)
|
mux.HandleFunc("POST /api/sms", app.sms)
|
||||||
mux.HandleFunc("POST /api/login", app.login)
|
mux.HandleFunc("POST /api/login", app.login)
|
||||||
|
mux.HandleFunc("GET /api/qr", app.qrCode)
|
||||||
|
mux.HandleFunc("GET /api/qr/poll", app.qrPoll)
|
||||||
mux.HandleFunc("POST /api/logout", app.logout)
|
mux.HandleFunc("POST /api/logout", app.logout)
|
||||||
mux.HandleFunc("POST /api/resume", app.resume)
|
mux.HandleFunc("POST /api/resume", app.resume)
|
||||||
mux.HandleFunc("POST /api/interval", app.setInterval)
|
mux.HandleFunc("POST /api/interval", app.setInterval)
|
||||||
@@ -366,6 +368,40 @@ func (a *App) login(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeErr(w, err.Error())
|
writeErr(w, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
a.acceptLogin(result)
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "登录成功"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) qrCode(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body, err := a.client.QRCode(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusBadGateway, map[string]any{"ok": false, "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "image/png")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) qrPoll(w http.ResponseWriter, r *http.Request) {
|
||||||
|
status, err := a.client.PollQR(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeErr(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if status.Expired {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "expired": true, "message": "二维码已失效,请刷新"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if status.Waiting || status.Result.Phone == "" {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "waiting": true})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.acceptLogin(status.Result)
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "登录成功"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) acceptLogin(result cmnet.LoginResult) {
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
a.loggedIn = true
|
a.loggedIn = true
|
||||||
a.sessionOK = true
|
a.sessionOK = true
|
||||||
@@ -379,7 +415,6 @@ func (a *App) login(w http.ResponseWriter, r *http.Request) {
|
|||||||
a.save()
|
a.save()
|
||||||
a.refresh()
|
a.refresh()
|
||||||
log.Printf("登录成功 %s", cmnet.MaskPhone(result.Phone))
|
log.Printf("登录成功 %s", cmnet.MaskPhone(result.Phone))
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "登录成功"})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) logout(w http.ResponseWriter, r *http.Request) {
|
func (a *App) logout(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
+77
-2
@@ -161,7 +161,14 @@
|
|||||||
}
|
}
|
||||||
.card { background: var(--card); border-radius: 12px; box-shadow: var(--shadow); }
|
.card { background: var(--card); border-radius: 12px; box-shadow: var(--shadow); }
|
||||||
#login { width: min(340px, 100%); margin: 0 auto; padding: 16px 14px 14px; }
|
#login { width: min(340px, 100%); margin: 0 auto; padding: 16px 14px 14px; }
|
||||||
#login h2 { margin: 0 0 12px; font-size: 16px; font-weight: 650; }
|
#login h2 { margin: 0; font-size: 16px; font-weight: 650; }
|
||||||
|
.login-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 12px; }
|
||||||
|
.mode-switch { display: flex; gap: 4px; }
|
||||||
|
.mode-switch button { height: 28px; padding: 0 8px; }
|
||||||
|
.mode-switch button.on { color: var(--accent); border-color: var(--accent); }
|
||||||
|
#qrBox { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 4px 0 2px; }
|
||||||
|
#qrBox[hidden] { display: none; }
|
||||||
|
#qrImg { width: 168px; height: 168px; border: 1px solid var(--line); border-radius: 8px; background: #fff; cursor: pointer; }
|
||||||
.field { margin-bottom: 10px; }
|
.field { margin-bottom: 10px; }
|
||||||
label { display: block; margin-bottom: 4px; color: var(--muted); font-size: 12px; }
|
label { display: block; margin-bottom: 4px; color: var(--muted); font-size: 12px; }
|
||||||
.login-row {
|
.login-row {
|
||||||
@@ -300,7 +307,13 @@
|
|||||||
<div id="toast" class="toast" hidden></div>
|
<div id="toast" class="toast" hidden></div>
|
||||||
|
|
||||||
<section id="login" class="card">
|
<section id="login" class="card">
|
||||||
<h2>登录</h2>
|
<div class="login-head">
|
||||||
|
<h2>登录</h2>
|
||||||
|
<div class="mode-switch">
|
||||||
|
<button id="smsMode" class="on" type="button">短信</button>
|
||||||
|
<button id="qrMode" type="button">扫码</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<form id="form">
|
<form id="form">
|
||||||
<div class="login-row">
|
<div class="login-row">
|
||||||
<label for="phone">手机号</label>
|
<label for="phone">手机号</label>
|
||||||
@@ -327,6 +340,10 @@
|
|||||||
<p id="loginMsg"></p>
|
<p id="loginMsg"></p>
|
||||||
<button id="submit" class="primary" type="submit">登录</button>
|
<button id="submit" class="primary" type="submit">登录</button>
|
||||||
</form>
|
</form>
|
||||||
|
<div id="qrBox" hidden>
|
||||||
|
<img id="qrImg" alt="登录二维码" title="点击刷新">
|
||||||
|
<p id="qrHint">请用中国移动 App 扫码,打开后点登录</p>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section id="pending" class="card" hidden>读取中</section>
|
<section id="pending" class="card" hidden>读取中</section>
|
||||||
@@ -423,6 +440,8 @@
|
|||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
let lastKey = "";
|
let lastKey = "";
|
||||||
let captchaReady = false;
|
let captchaReady = false;
|
||||||
|
let qrTimer = 0;
|
||||||
|
let qrMode = false;
|
||||||
let smsLeft = 0;
|
let smsLeft = 0;
|
||||||
let smsTimer = 0;
|
let smsTimer = 0;
|
||||||
let deadline = 0;
|
let deadline = 0;
|
||||||
@@ -450,6 +469,7 @@
|
|||||||
lastKey = key;
|
lastKey = key;
|
||||||
|
|
||||||
loggedIn = !!data.loggedIn;
|
loggedIn = !!data.loggedIn;
|
||||||
|
if (loggedIn) stopQR();
|
||||||
$("menu").hidden = !data.loggedIn;
|
$("menu").hidden = !data.loggedIn;
|
||||||
$("countdown").hidden = !data.loggedIn;
|
$("countdown").hidden = !data.loggedIn;
|
||||||
$("refresh").disabled = !!data.refreshing;
|
$("refresh").disabled = !!data.refreshing;
|
||||||
@@ -661,6 +681,61 @@
|
|||||||
$("settingsSave").addEventListener("click", () => {
|
$("settingsSave").addEventListener("click", () => {
|
||||||
saveInterval().catch(() => { $("settingsMsg").textContent = "未保存"; });
|
saveInterval().catch(() => { $("settingsMsg").textContent = "未保存"; });
|
||||||
});
|
});
|
||||||
|
function stopQR() {
|
||||||
|
clearInterval(qrTimer);
|
||||||
|
qrTimer = 0;
|
||||||
|
}
|
||||||
|
function showSMS() {
|
||||||
|
qrMode = false;
|
||||||
|
stopQR();
|
||||||
|
$("form").hidden = false;
|
||||||
|
$("qrBox").hidden = true;
|
||||||
|
$("smsMode").classList.add("on");
|
||||||
|
$("qrMode").classList.remove("on");
|
||||||
|
}
|
||||||
|
async function startQR() {
|
||||||
|
qrMode = true;
|
||||||
|
stopQR();
|
||||||
|
$("form").hidden = true;
|
||||||
|
$("qrBox").hidden = false;
|
||||||
|
$("qrMode").classList.add("on");
|
||||||
|
$("smsMode").classList.remove("on");
|
||||||
|
setLoginMsg("");
|
||||||
|
$("qrHint").textContent = "请用中国移动 App 扫码,打开后点登录";
|
||||||
|
$("qrImg").src = "/api/qr?t=" + Date.now();
|
||||||
|
qrTimer = setInterval(async () => {
|
||||||
|
if (!qrMode) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/qr/poll", { cache: "no-store" });
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.expired) {
|
||||||
|
stopQR();
|
||||||
|
$("qrHint").textContent = data.message || "二维码已失效,点击图片刷新";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!data.waiting && data.ok === false) {
|
||||||
|
stopQR();
|
||||||
|
const message = data.message || "扫码登录失败";
|
||||||
|
$("qrHint").textContent = message;
|
||||||
|
setLoginMsg(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data.ok) {
|
||||||
|
stopQR();
|
||||||
|
lastKey = "";
|
||||||
|
await pull();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
stopQR();
|
||||||
|
setLoginMsg("扫码登录失败");
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
|
}
|
||||||
|
$("smsMode").addEventListener("click", () => showSMS());
|
||||||
|
$("qrMode").addEventListener("click", () => { startQR().catch(() => setLoginMsg("二维码加载失败")); });
|
||||||
|
$("qrImg").addEventListener("click", () => { if (qrMode) startQR().catch(() => setLoginMsg("二维码加载失败")); });
|
||||||
|
$("qrImg").addEventListener("error", () => { setLoginMsg("二维码加载失败"); });
|
||||||
|
|
||||||
$("captcha").addEventListener("click", () => { loadCaptcha(); captchaReady = true; });
|
$("captcha").addEventListener("click", () => { loadCaptcha(); captchaReady = true; });
|
||||||
$("captcha").addEventListener("error", () => { setLoginMsg("验证码加载失败"); });
|
$("captcha").addEventListener("error", () => { setLoginMsg("验证码加载失败"); });
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user