fix: 退出后不保留登录状态,调试输出改为总开关

This commit is contained in:
Nixevol
2026-10-16 15:39:05 +08:00
parent 543fcce134
commit d5dcd7086d
7 changed files with 253 additions and 51 deletions
+1 -1
View File
@@ -28,7 +28,7 @@
间隔和随机分钟在页面里保存后,以 `data/state.json` 为准。 间隔和随机分钟在页面里保存后,以 `data/state.json` 为准。
短信登录先填手机号和图形验证码,再获取短信。扫码登录点「扫码」,用中国移动 App 扫二维码。这个号码上次的会话还在时,点登录会直接进入主页。退出只回到登录页,不向移动注销,也不再自动刷新。 短信登录先填手机号和图形验证码,再获取短信。扫码登录点「扫码」,用中国移动 App 扫二维码。退出后立即清除本次登录状态。重新打开程序不会恢复上次登录,需要重新登录。
## 编译 ## 编译
+94 -13
View File
@@ -11,6 +11,7 @@ import (
"net/http/cookiejar" "net/http/cookiejar"
"net/url" "net/url"
"regexp" "regexp"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -120,6 +121,7 @@ func (c *Client) Captcha(ctx context.Context) ([]byte, string, error) {
if ctype == "" { if ctype == "" {
ctype = "image/png" ctype = "image/png"
} }
debugf("图形验证码已获取 %d 字节", len(body))
return body, ctype, nil return body, ctype, nil
} }
@@ -130,6 +132,8 @@ func (c *Client) SendSMS(ctx context.Context, phone, imageCode string) (string,
return "", err return "", err
} }
c.dropAccountSession() c.dropAccountSession()
debugf("发送短信 phone=%s 图形验证码=%s", phone, imageCode)
c.debugCookies("发送短信前")
encPhone, err := c.crypto.encryptLogin(phone) encPhone, err := c.crypto.encryptLogin(phone)
if err != nil { if err != nil {
return "", err return "", err
@@ -146,6 +150,7 @@ func (c *Client) SendSMS(ctx context.Context, phone, imageCode string) (string,
ResultCode string `json:"resultCode"` ResultCode string `json:"resultCode"`
} }
_ = json.Unmarshal(vbody, &captchaRes) _ = json.Unmarshal(vbody, &captchaRes)
debugf("图形验证码校验 phone=%s 图形验证码=%s 原文=%s", phone, imageCode, string(vbody))
if captchaRes.ResultCode != "" && captchaRes.ResultCode != "0" { if captchaRes.ResultCode != "" && captchaRes.ResultCode != "0" {
return "", errors.New("图形验证码不正确") return "", errors.New("图形验证码不正确")
} }
@@ -181,7 +186,10 @@ func (c *Client) SendSMS(ctx context.Context, phone, imageCode string) (string,
if err != nil { if err != nil {
return "", err return "", err
} }
return smsMessage(strings.TrimSpace(string(body))) msg, err := smsMessage(strings.TrimSpace(string(body)))
debugf("短信发送结果 phone=%s 原文=%s", phone, string(body))
c.debugCookies("短信发送后")
return msg, err
} }
func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID string) (LoginResult, error) { func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID string) (LoginResult, error) {
@@ -191,6 +199,8 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID
return LoginResult{}, err return LoginResult{}, err
} }
c.dropAccountSession() c.dropAccountSession()
debugf("短信登录 phone=%s 图形验证码=%s 短信验证码=%s AES密钥=%s", phone, imageCode, smsCode, string(c.crypto.aesKey))
c.debugCookies("短信登录前")
encPhone, err := c.crypto.encryptLogin(phone) encPhone, err := c.crypto.encryptLogin(phone)
if err != nil { if err != nil {
return LoginResult{}, err return LoginResult{}, err
@@ -233,6 +243,7 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID
ResultDesc string `json:"resultDesc"` ResultDesc string `json:"resultDesc"`
} }
if err := json.Unmarshal(body, &loginRes); err != nil { if err := json.Unmarshal(body, &loginRes); err != nil {
debugf("短信登录结果无法解析 phone=%s 原文=%s", phone, string(body))
return LoginResult{}, errors.New("登录结果无法解析") return LoginResult{}, errors.New("登录结果无法解析")
} }
if loginRes.Code == "" { if loginRes.Code == "" {
@@ -242,6 +253,7 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID
loginRes.Desc = loginRes.ResultDesc loginRes.Desc = loginRes.ResultDesc
} }
if loginRes.Code != "0000" || loginRes.Artifact == "" { if loginRes.Code != "0000" || loginRes.Artifact == "" {
debugf("短信登录被拒绝 phone=%s code=%s desc=%s 原文=%s", phone, loginRes.Code, loginRes.Desc, string(body))
if loginRes.Desc != "" { if loginRes.Desc != "" {
return LoginResult{}, errors.New(loginRes.Desc) return LoginResult{}, errors.New(loginRes.Desc)
} }
@@ -254,13 +266,20 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID
if typ == "" { if typ == "" {
typ = "00" typ = "00"
} }
if err := c.exchangeArtifact(ctx, loginRes.Artifact, typ); err != nil { debugf("短信登录已通过 phone=%s type=%s artifact=%s", phone, typ, loginRes.Artifact)
if err := c.exchangeArtifact(ctx, loginRes.Artifact, "", typ); err != nil {
debugf("交换登录凭证失败 phone=%s %v", phone, err)
c.debugCookies("交换凭证失败")
return LoginResult{}, err return LoginResult{}, err
} }
c.debugCookies("交换凭证后")
info, err := c.loginfo(ctx) info, err := c.loginfo(ctx)
if err != nil { if err != nil {
debugf("读取登录资料失败 phone=%s %s", phone, err.Error())
c.debugCookies("读取资料失败")
return LoginResult{}, err return LoginResult{}, err
} }
debugf("登录资料 phone=%s loginValue=%s safeCode=%s provice=%s province=%s", phone, asString(info["loginValue"]), asString(info["safeCode"]), asString(info["provice"]), asString(info["province"]))
prov := asString(info["provice"]) prov := asString(info["provice"])
if prov == "" { if prov == "" {
prov = asString(info["province"]) prov = asString(info["province"])
@@ -271,6 +290,7 @@ func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID
type QRStatus struct { type QRStatus struct {
Waiting bool Waiting bool
Expired bool Expired bool
AssertURL string
Result LoginResult Result LoginResult
} }
@@ -297,6 +317,8 @@ func (c *Client) QRCode(ctx context.Context) ([]byte, error) {
if c.qrToken == "" { if c.qrToken == "" {
return nil, errors.New("没有拿到扫码凭证") return nil, errors.New("没有拿到扫码凭证")
} }
debugf("扫码凭证 lgToken=%s", c.qrToken)
c.debugCookies("二维码")
_, _ = c.postForm(ctx, loginOrigin+"/checkBackUrl", url.Values{ _, _ = c.postForm(ctx, loginOrigin+"/checkBackUrl", url.Values{
"backUrl": {backURL}, "backUrl": {backURL},
"channelID": {c.channelID}, "channelID": {c.channelID},
@@ -324,7 +346,7 @@ func (c *Client) PollQR(ctx context.Context) (QRStatus, error) {
if status.Expired || status.Waiting || artifact == "" { if status.Expired || status.Waiting || artifact == "" {
return status, nil return status, nil
} }
if err := c.exchangeArtifact(ctx, artifact, ""); err != nil { if err := c.exchangeArtifact(ctx, artifact, status.AssertURL, ""); err != nil {
return QRStatus{}, err return QRStatus{}, err
} }
info, err := c.loginfo(ctx) info, err := c.loginfo(ctx)
@@ -344,8 +366,11 @@ func (c *Client) PollQR(ctx context.Context) (QRStatus, error) {
return status, nil return status, nil
} }
func (c *Client) exchangeArtifact(ctx context.Context, artifact, typ string) error { func (c *Client) exchangeArtifact(ctx context.Context, artifact, assertURL, typ string) error {
art, err := url.Parse(shopOrigin + "/i/v1/auth/getArtifact") if assertURL == "" || !sameSite(shopOrigin, assertURL) {
assertURL = shopOrigin + "/i/v1/auth/getArtifact"
}
art, err := url.Parse(assertURL)
if err != nil { if err != nil {
return err return err
} }
@@ -362,39 +387,53 @@ func (c *Client) exchangeArtifact(ctx context.Context, artifact, typ string) err
func (c *Client) pollChannels(ctx context.Context) (QRStatus, string, error) { func (c *Client) pollChannels(ctx context.Context) (QRStatus, string, error) {
channels := []string{} channels := []string{}
if c.qrChannel != "" { if c.channelID != "" {
channels = append(channels, c.qrChannel)
}
if c.channelID != "" && c.channelID != c.qrChannel {
channels = append(channels, c.channelID) channels = append(channels, c.channelID)
} }
if c.qrChannel != "" && c.qrChannel != c.channelID {
channels = append(channels, c.qrChannel)
}
if len(channels) == 0 { if len(channels) == 0 {
channels = []string{""} channels = []string{""}
} }
sawWait := false sawWait := false
var lastErr error var lastErr error
var fallback QRStatus
fallbackArtifact := ""
for _, channel := range channels { for _, channel := range channels {
body, err := c.postForm(ctx, loginOrigin+"/chkqr.htm", url.Values{ body, err := c.postForm(ctx, loginOrigin+"/chkqr.htm", url.Values{
"lgToken": {c.qrToken}, "lgToken": {c.qrToken},
"targetChannelID": {channel}, "targetChannelID": {channel},
"backUrl": {url.QueryEscape(backURL)}, "backUrl": {url.QueryEscape(backURL)},
}) })
debugf("扫码轮询 channel=%s lgToken=%s err=%v 原文=%s", channel, c.qrToken, err, string(body))
if err != nil { if err != nil {
lastErr = err lastErr = err
continue continue
} }
status, artifact, err := parseQRPoll(bytes.TrimSpace(body)) status, artifact, err := parseQRPoll(bytes.TrimSpace(body))
if err != nil { if err != nil {
return QRStatus{}, "", err lastErr = err
continue
} }
if artifact != "" { if artifact != "" {
if shopArtifact(status.AssertURL) {
return status, artifact, nil return status, artifact, nil
} }
if fallbackArtifact == "" {
fallback = status
fallbackArtifact = artifact
}
continue
}
if status.Expired { if status.Expired {
continue continue
} }
sawWait = true sawWait = true
} }
if fallbackArtifact != "" && !sawWait {
return fallback, fallbackArtifact, nil
}
if sawWait { if sawWait {
return QRStatus{Waiting: true}, "", nil return QRStatus{Waiting: true}, "", nil
} }
@@ -404,6 +443,17 @@ func (c *Client) pollChannels(ctx context.Context) (QRStatus, string, error) {
return QRStatus{Expired: true}, "", nil return QRStatus{Expired: true}, "", nil
} }
func shopArtifact(rawURL string) bool {
if rawURL == "" {
return true
}
u, err := url.Parse(rawURL)
if err != nil {
return false
}
return u.Hostname() == "shop.10086.cn"
}
func parseQRPoll(body []byte) (QRStatus, string, error) { func parseQRPoll(body []byte) (QRStatus, string, error) {
if len(body) == 0 { if len(body) == 0 {
return QRStatus{Waiting: true}, "", nil return QRStatus{Waiting: true}, "", nil
@@ -412,6 +462,7 @@ func parseQRPoll(body []byte) (QRStatus, string, error) {
ResultCode string `json:"resultCode"` ResultCode string `json:"resultCode"`
ResultDesc string `json:"resultDesc"` ResultDesc string `json:"resultDesc"`
Artifact string `json:"artifact"` Artifact string `json:"artifact"`
AssertURL string `json:"assertUrl"`
} }
if err := json.Unmarshal(body, &res); err != nil { if err := json.Unmarshal(body, &res); err != nil {
return QRStatus{Waiting: true}, "", nil return QRStatus{Waiting: true}, "", nil
@@ -423,7 +474,7 @@ func parseQRPoll(body []byte) (QRStatus, string, error) {
if res.Artifact == "" { if res.Artifact == "" {
return QRStatus{}, "", errors.New("登录结果缺少凭证") return QRStatus{}, "", errors.New("登录结果缺少凭证")
} }
return QRStatus{}, res.Artifact, nil return QRStatus{AssertURL: res.AssertURL}, res.Artifact, nil
case "8020": case "8020":
return QRStatus{Expired: true}, "", nil return QRStatus{Expired: true}, "", nil
default: default:
@@ -537,6 +588,13 @@ func (c *Client) cookieNamed(name string) string {
return "" return ""
} }
func (c *Client) SessionAlive(ctx context.Context) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, err := c.loginfo(ctx)
return err == nil
}
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()
@@ -549,12 +607,15 @@ func (c *Client) Query(ctx context.Context, phone, prov string) (json.RawMessage
func (c *Client) queryOnce(ctx context.Context, phone, prov string) (json.RawMessage, json.RawMessage, error) { func (c *Client) queryOnce(ctx context.Context, phone, prov string) (json.RawMessage, json.RawMessage, error) {
token, err := c.crypto.phoneToken(phone) token, err := c.crypto.phoneToken(phone)
if err != nil { if err != nil {
debugf("生成号码令牌失败 phone=%s %v", phone, err)
return nil, nil, err return nil, nil, err
} }
pay, err := c.crypto.payPhoneNo(phone) pay, err := c.crypto.payPhoneNo(phone)
if err != nil { if err != nil {
debugf("生成缴费号码失败 phone=%s %v", phone, err)
return nil, nil, err return nil, nil, err
} }
debugf("查询账户 phone=%s prov=%s token=%s pay=%s", phone, prov, token, pay)
headers := map[string]string{"provcode": prov, "payphoneno": pay} headers := map[string]string{"provcode": prov, "payphoneno": pay}
real, err := c.shopGet(ctx, "/i/v1/fee/real/"+token+"?_="+milli(), headers) real, err := c.shopGet(ctx, "/i/v1/fee/real/"+token+"?_="+milli(), headers)
if err != nil { if err != nil {
@@ -607,9 +668,11 @@ func (c *Client) decodeShop(buf []byte) (json.RawMessage, error) {
return nil, errors.New("网站没有返回账户数据") return nil, errors.New("网站没有返回账户数据")
} }
if wrap.RetCode == "500003" || strings.Contains(wrap.RetMsg, "not login") || strings.Contains(wrap.RetMsg, "未登录") { if wrap.RetCode == "500003" || strings.Contains(wrap.RetMsg, "not login") || strings.Contains(wrap.RetMsg, "未登录") {
debugf("个人中心判定未登录 retCode=%s retMsg=%s 原文=%s", wrap.RetCode, wrap.RetMsg, string(buf))
return nil, ErrNeedLogin return nil, ErrNeedLogin
} }
if wrap.RetCode != "000000" { if wrap.RetCode != "000000" {
debugf("个人中心查询失败 retCode=%s retMsg=%s", wrap.RetCode, wrap.RetMsg)
if wrap.RetMsg != "" { if wrap.RetMsg != "" {
return nil, errors.New(wrap.RetMsg) return nil, errors.New(wrap.RetMsg)
} }
@@ -831,8 +894,17 @@ func (c *Client) do(req *http.Request) ([]byte, string, error) {
} }
} }
if resp.StatusCode >= 400 && !strings.Contains(resp.Header.Get("Content-Type"), "json") { if resp.StatusCode >= 400 && !strings.Contains(resp.Header.Get("Content-Type"), "json") {
if debugRequest(req) {
debugf("%s %s -> %d 失败", req.Method, req.URL.String(), resp.StatusCode)
}
return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode) return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode)
} }
if debugRequest(req) {
debugf("%s %s -> %d Set-Cookie [%s]", req.Method, req.URL.String(), resp.StatusCode, debugSetCookies(resp))
if !strings.Contains(resp.Header.Get("Content-Type"), "image") {
debugBody(req.URL.Path, buf)
}
}
return buf, resp.Header.Get("Content-Type"), nil return buf, resp.Header.Get("Content-Type"), nil
} }
@@ -909,6 +981,7 @@ func (c *Client) Reset() {
} }
c.jar = jar c.jar = jar
c.http.Jar = jar c.http.Jar = jar
c.qrToken = ""
} }
func dedupeCookies(list []Cookie) []Cookie { func dedupeCookies(list []Cookie) []Cookie {
@@ -958,6 +1031,14 @@ func smsMessage(body string) (string, error) {
} }
func asString(v any) string { func asString(v any) string {
s, _ := v.(string) switch t := v.(type) {
return s case string:
return t
case float64:
return strconv.FormatFloat(t, 'f', -1, 64)
case json.Number:
return t.String()
default:
return ""
}
} }
+88
View File
@@ -0,0 +1,88 @@
package cmnet
import (
"log"
"net/http"
"net/url"
"strings"
)
// debugEnabled 为调试总开关。关闭后所有 debugf 调用都不会输出。
const debugEnabled = false
func debugf(format string, args ...any) {
if !debugEnabled {
return
}
log.Printf("调试 "+format, args...)
}
func Debugf(format string, args ...any) {
debugf(format, args...)
}
func (c *Client) debugCookies(where string) {
if !debugEnabled {
return
}
var b strings.Builder
seen := map[string]bool{}
for _, raw := range []string{loginOrigin + "/", shopOrigin + "/", "https://10086.cn/", "https://www.10086.cn/"} {
u, err := url.Parse(raw)
if err != nil {
continue
}
for _, ck := range c.jar.Cookies(u) {
line := u.Hostname() + " " + ck.Name + "=" + ck.Value
if seen[line] {
continue
}
seen[line] = true
if b.Len() > 0 {
b.WriteString(" | ")
}
b.WriteString(line)
}
}
debugf("%s Cookie %s", where, b.String())
}
func debugSetCookies(resp *http.Response) string {
if resp == nil {
return ""
}
parts := make([]string, 0, len(resp.Cookies()))
for _, ck := range resp.Cookies() {
parts = append(parts, ck.Name+"="+ck.Value)
}
return strings.Join(parts, "; ")
}
func debugBody(tag string, buf []byte) {
if !debugEnabled {
return
}
if len(buf) == 0 {
debugf("%s 响应空", tag)
return
}
const limit = 2000
if len(buf) > limit {
debugf("%s 响应 %d 字节 %s", tag, len(buf), string(buf[:limit]))
return
}
debugf("%s 响应 %s", tag, string(buf))
}
func debugRequest(req *http.Request) bool {
if !debugEnabled || req == nil || req.URL == nil {
return false
}
switch req.URL.Path {
case "/login.htm", "/verifyCaptcha.htm", "/sendRandomCodeAction.action", "/loadToken.action",
"/chkNumberAction.action", "/chkqr.htm", "/i/v1/auth/getArtifact", "/i/v1/auth/loginfo", "/fkRisk.action":
return true
default:
return strings.Contains(req.URL.Path, "/fee/")
}
}
+3
View File
@@ -187,6 +187,7 @@ func (p *pageCrypto) calibrateAES() {
} }
key := []byte(v.String()) key := []byte(v.String())
p.aesKey = key p.aesKey = key
debugf("AES密钥 %s", string(key))
const probe = "probe" const probe = "probe"
jsText, err := p.callAES(false, probe) jsText, err := p.callAES(false, probe)
if err != nil { if err != nil {
@@ -201,6 +202,7 @@ func (p *pageCrypto) calibrateAES() {
return return
} }
p.useNativeAES = true p.useNativeAES = true
debugf("AES使用原生实现")
} }
// calibrateRSA 从登录脚本里取出公钥。官网密文长度等于该公钥块长时才走原生。 // calibrateRSA 从登录脚本里取出公钥。官网密文长度等于该公钥块长时才走原生。
@@ -224,6 +226,7 @@ func (p *pageCrypto) calibrateRSA() {
} }
p.rsaPub = pub p.rsaPub = pub
p.useNativeRSA = true p.useNativeRSA = true
debugf("RSA公钥位数 %d", pub.N.BitLen())
} }
func newBrowserVM() (*goja.Runtime, error) { func newBrowserVM() (*goja.Runtime, error) {
+30 -5
View File
@@ -269,21 +269,46 @@ func TestDropAccountSession(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
shop, err := url.Parse("https://shop.10086.cn/i/")
if err != nil {
t.Fatal(err)
}
c.jar.SetCookies(u, []*http.Cookie{ c.jar.SetCookies(u, []*http.Cookie{
{Name: "cmccssotoken", Value: "tok", Domain: "10086.cn", Path: "/"}, {Name: "cmccssotoken", Value: "old", Domain: "10086.cn", Path: "/"},
{Name: "is_login", Value: "true", Domain: "10086.cn", Path: "/"}, {Name: "is_login", Value: "true", Domain: "10086.cn", Path: "/"},
{Name: "CaptchaCode", Value: "ab", Path: "/"}, {Name: "CaptchaCode", Value: "ab", Path: "/"},
}) })
c.dropAccountSession() c.dropAccountSession()
var left []string 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) { for _, ck := range c.jar.Cookies(u) {
left = append(left, ck.Name) loginNames = append(loginNames, ck.Name)
} }
if len(left) != 1 || left[0] != "CaptchaCode" { if !containsName(loginNames, "CaptchaCode") {
t.Fatalf("cookies %v", left) 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) { func TestSubmitChannel(t *testing.T) {
src := `$.ajax({url:'https://login.10086.cn/submitqr.htm',data:{'UID':uid,'lgToken':q,'channelID':'12008'}})` src := `$.ajax({url:'https://login.10086.cn/submitqr.htm',data:{'UID':uid,'lgToken':q,'channelID':'12008'}})`
if submitChannel(src) != "12008" { if submitChannel(src) != "12008" {
+27 -27
View File
@@ -69,6 +69,7 @@ type overview struct {
Error string `json:"error,omitempty"` Error string `json:"error,omitempty"`
Stale bool `json:"stale"` Stale bool `json:"stale"`
HasData bool `json:"hasData"` HasData bool `json:"hasData"`
LoginEpoch int `json:"loginEpoch"`
cmnet.Snapshot cmnet.Snapshot
} }
@@ -95,6 +96,7 @@ type App struct {
lastError string lastError string
stale bool stale bool
refreshing bool refreshing bool
loginEpoch int
} }
func main() { func main() {
@@ -239,7 +241,15 @@ func (a *App) refresh() bool {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel() defer cancel()
real, plan, err := a.client.Query(ctx, phone, prov) real, plan, err := a.client.Query(ctx, phone, prov)
cmnet.Debugf("刷新 phone=%s prov=%s err=%v", phone, prov, err)
if errors.Is(err, cmnet.ErrNeedLogin) { if errors.Is(err, cmnet.ErrNeedLogin) {
if a.client.SessionAlive(ctx) {
a.mu.Lock()
a.stale = true
a.lastError = "账户数据暂时没有刷新"
a.mu.Unlock()
return true
}
a.markLoggedOut("会话已失效,请重新登录") a.markLoggedOut("会话已失效,请重新登录")
return true return true
} }
@@ -272,6 +282,7 @@ func (a *App) refresh() bool {
} }
func (a *App) markLoggedOut(msg string) { func (a *App) markLoggedOut(msg string) {
cmnet.Debugf("清除登录状态 %s", msg)
a.client.Reset() a.client.Reset()
a.mu.Lock() a.mu.Lock()
a.loggedIn = false a.loggedIn = false
@@ -282,7 +293,9 @@ func (a *App) markLoggedOut(msg string) {
a.refreshedAt = time.Time{} a.refreshedAt = time.Time{}
a.lastError = msg a.lastError = msg
a.nextAt = time.Time{} a.nextAt = time.Time{}
a.loginEpoch++
a.mu.Unlock() a.mu.Unlock()
a.save()
} }
func (a *App) page(w http.ResponseWriter, r *http.Request) { func (a *App) page(w http.ResponseWriter, r *http.Request) {
@@ -418,10 +431,18 @@ func (a *App) acceptLogin(result cmnet.LoginResult) {
} }
func (a *App) logout(w http.ResponseWriter, r *http.Request) { func (a *App) logout(w http.ResponseWriter, r *http.Request) {
cmnet.Debugf("用户退出,清除登录状态")
a.client.Reset()
a.mu.Lock() a.mu.Lock()
a.loggedIn = false a.loggedIn = false
a.sessionOK = false
a.snap = emptySnap()
a.realRaw, a.planRaw = nil, nil
a.stale = false
a.refreshedAt = time.Time{}
a.lastError = "" a.lastError = ""
a.nextAt = time.Time{} a.nextAt = time.Time{}
a.loginEpoch++
a.mu.Unlock() a.mu.Unlock()
a.wakeLoop() a.wakeLoop()
a.save() a.save()
@@ -532,6 +553,7 @@ func (a *App) view() overview {
Error: a.lastError, Error: a.lastError,
Stale: a.loggedIn && a.stale, Stale: a.loggedIn && a.stale,
HasData: a.loggedIn && hasData(snap), HasData: a.loggedIn && hasData(snap),
LoginEpoch: a.loginEpoch,
Snapshot: snap, Snapshot: snap,
} }
if a.loggedIn && !a.refreshedAt.IsZero() { if a.loggedIn && !a.refreshedAt.IsZero() {
@@ -552,32 +574,18 @@ func emptySnap() cmnet.Snapshot {
} }
func (a *App) load() { func (a *App) load() {
a.phone = a.cfgPhone
b, err := os.ReadFile(statePath) b, err := os.ReadFile(statePath)
if err != nil { if err != nil {
a.phone = a.cfgPhone
return return
} }
var st savedState var st savedState
if json.Unmarshal(b, &st) != nil { if json.Unmarshal(b, &st) != nil {
a.phone = a.cfgPhone
return return
} }
a.phone = strings.TrimSpace(st.Phone)
if a.phone == "" {
a.phone = a.cfgPhone
}
a.provCode = st.ProvCode
if st.DeviceID != "" { if st.DeviceID != "" {
a.deviceID = st.DeviceID a.deviceID = st.DeviceID
} }
a.sessionOK = st.SessionOK && a.phone != "" && len(st.Cookies) > 0
a.loggedIn = st.LoggedIn && a.sessionOK
a.snap = st.Snapshot
a.realRaw = st.RealRaw
a.planRaw = st.PlanRaw
a.refreshedAt = st.RefreshedAt
a.lastError = st.LastError
a.stale = st.Stale
if st.PollMinutes >= 1 && st.PollMinutes <= 1440 { if st.PollMinutes >= 1 && st.PollMinutes <= 1440 {
a.interval = time.Duration(st.PollMinutes) * time.Minute a.interval = time.Duration(st.PollMinutes) * time.Minute
a.pollText = humanInterval(a.interval) a.pollText = humanInterval(a.interval)
@@ -585,13 +593,7 @@ func (a *App) load() {
if st.JitterMinutes >= 0 && st.JitterMinutes <= 1440 { if st.JitterMinutes >= 0 && st.JitterMinutes <= 1440 {
a.jitter = time.Duration(st.JitterMinutes) * time.Minute a.jitter = time.Duration(st.JitterMinutes) * time.Minute
} }
a.client.ImportCookies(st.Cookies) a.save()
if len(a.planRaw) > 0 || len(a.realRaw) > 0 {
a.snap = cmnet.BuildSnapshot(a.phone, a.snap.Region, a.realRaw, a.planRaw)
}
if a.loggedIn {
log.Printf("已恢复会话 %s", cmnet.MaskPhone(a.phone))
}
} }
func (a *App) save() { func (a *App) save() {
@@ -599,13 +601,11 @@ func (a *App) save() {
defer a.saveMu.Unlock() defer a.saveMu.Unlock()
a.mu.Lock() a.mu.Lock()
st := savedState{ st := savedState{
Phone: a.phone, ProvCode: a.provCode, DeviceID: a.deviceID, LoggedIn: a.loggedIn, SessionOK: a.sessionOK, DeviceID: a.deviceID,
Snapshot: a.snap, RealRaw: a.realRaw, PlanRaw: a.planRaw, RefreshedAt: a.refreshedAt, PollMinutes: int(a.interval / time.Minute),
LastError: a.lastError, Stale: a.stale, JitterMinutes: int(a.jitter / time.Minute),
PollMinutes: int(a.interval / time.Minute), JitterMinutes: int(a.jitter / time.Minute),
} }
a.mu.Unlock() a.mu.Unlock()
st.Cookies = a.client.ExportCookies()
buf, err := json.MarshalIndent(st, "", " ") buf, err := json.MarshalIndent(st, "", " ")
if err != nil { if err != nil {
log.Printf("保存会话失败: %v", err) log.Printf("保存会话失败: %v", err)
+6 -1
View File
@@ -440,6 +440,7 @@
const $ = (id) => document.getElementById(id); const $ = (id) => document.getElementById(id);
let lastKey = ""; let lastKey = "";
let captchaReady = false; let captchaReady = false;
let loginEpoch = null;
let qrTimer = 0; let qrTimer = 0;
let qrMode = false; let qrMode = false;
let smsLeft = 0; let smsLeft = 0;
@@ -497,8 +498,12 @@
if (data.phone) savedPhone = data.phone; if (data.phone) savedPhone = data.phone;
if (!$("phone").value && data.phone) $("phone").value = data.phone; if (!$("phone").value && data.phone) $("phone").value = data.phone;
const reuse = canResume && $("phone").value.trim() === savedPhone; const reuse = canResume && $("phone").value.trim() === savedPhone;
const nextEpoch = Number.isInteger(data.loginEpoch) ? data.loginEpoch : 0;
const epochChanged = loginEpoch !== nextEpoch;
loginEpoch = nextEpoch;
$("verify").hidden = !data.needLogin || reuse; $("verify").hidden = !data.needLogin || reuse;
if (data.needLogin && !reuse && !captchaReady) { if (data.needLogin && !reuse && (epochChanged || !captchaReady)) {
if (epochChanged) $("imageCode").value = "";
loadCaptcha(); loadCaptcha();
captchaReady = true; captchaReady = true;
} }