From 21e5dbe1799fd55233c8b7b0f6f888eea0478682 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Thu, 15 Oct 2026 18:09:50 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8F=90=E4=BA=A4=E7=A7=BB=E5=8A=A8?= =?UTF-8?q?=E4=B8=AA=E4=BA=BA=E4=B8=AD=E5=BF=83=E5=8F=AA=E8=AF=BB=E9=9D=A2?= =?UTF-8?q?=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 9 + README.md | 62 +++ config.example.json | 6 + go.mod | 3 + internal/cmnet/client.go | 570 +++++++++++++++++++++++ internal/cmnet/crypto.go | 127 ++++++ internal/cmnet/crypto_test.go | 76 ++++ internal/cmnet/format.go | 390 ++++++++++++++++ main.go | 723 +++++++++++++++++++++++++++++ web/favicon.ico | Bin 0 -> 1150 bytes web/index.html | 826 ++++++++++++++++++++++++++++++++++ 11 files changed, 2792 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 config.example.json create mode 100644 go.mod create mode 100644 internal/cmnet/client.go create mode 100644 internal/cmnet/crypto.go create mode 100644 internal/cmnet/crypto_test.go create mode 100644 internal/cmnet/format.go create mode 100644 main.go create mode 100644 web/favicon.ico create mode 100644 web/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f264856 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +data/ +config.json +*.exe +*.chlz +_*.py +_*.txt +_*.js +_*.json +Temp/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..a1f2192 --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +# 移动账户 + +给自己的中国移动号码看话费余额、当月消费和套餐余量。页面只读,登录后按设定间隔自动刷新。登录方式是手机号、图形验证码和短信验证码。扫码登录没有做。 + +页面没有访问口令,只放在自己的机器上。 + +## 使用 + +程序从当前工作目录读取 `config.json` 并写入 `data/`。先进入程序所在目录再启动,浏览器打开它监听的地址。 + +```json +{ + "listen": ":8788", + "pollInterval": "30m", + "jitterMinutes": 0, + "phone": "" +} +``` + +| 字段 | 作用 | +| --- | --- | +| `listen` | 监听地址,默认 `:8788` | +| `pollInterval` | 登录后的基础刷新间隔,最短 1 分钟 | +| `jitterMinutes` | 每次额外随机增加 0 到这个分钟数,精确到秒。0 表示不加 | +| `phone` | 可选。写上后登录页会预先填好号码 | + +环境变量 `CMNET_LISTEN`、`CMNET_POLL`、`CMNET_JITTER`、`CMNET_PHONE` 会覆盖同名字段。`CMNET_POLL` 和 `CMNET_JITTER` 用时长写法,例如 `30m`、`10m`。 + +间隔和随机分钟在页面里保存后,以 `data/state.json` 为准。 + +登录页先填手机号和图形验证码,再获取短信。这个号码上次的会话还在时,点登录会直接进入主页。退出只回到登录页,不向移动注销,也不再自动刷新。 + +## 编译 + +需要 Go 1.26 或更高。 + +```bash +go build -trimpath -ldflags="-s -w" -o cmnet-dashboard . +``` + +交叉编译到 Linux: + +```bash +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o cmnet-dashboard . +``` + +## 流程 + +```mermaid +flowchart TD + open[打开页面] --> saved{这个号码还有上次的会话?} + saved -->|有| pull[用该会话拉取余额和余量] + pull -->|成功| home[进入主页并按间隔刷新] + pull -->|会话已失效| code[填写图形验证码和短信验证码] + saved -->|没有| code + code --> home + home --> tick[倒计时结束] + tick -->|会话仍有效| home + tick -->|移动要求重新登录| code + home --> logout[退出] + logout --> hold[停在登录页且不再刷新] +``` diff --git a/config.example.json b/config.example.json new file mode 100644 index 0000000..03529ab --- /dev/null +++ b/config.example.json @@ -0,0 +1,6 @@ +{ + "listen": ":8788", + "pollInterval": "30m", + "jitterMinutes": 0, + "phone": "" +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..35caf19 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module cmnetsmsinfo + +go 1.26.0 diff --git a/internal/cmnet/client.go b/internal/cmnet/client.go new file mode 100644 index 0000000..39a03a8 --- /dev/null +++ b/internal/cmnet/client.go @@ -0,0 +1,570 @@ +package cmnet + +import ( + "context" + "crypto/rsa" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/cookiejar" + "net/url" + "regexp" + "strings" + "sync" + "time" +) + +const ( + loginOrigin = "https://login.10086.cn" + shopOrigin = "https://shop.10086.cn" + channelID = "12003" + backURL = "https://shop.10086.cn/i/?f=packremainqry" + loginPage = loginOrigin + "/login.html?channelID=" + channelID + "&backUrl=" + "https%3A%2F%2Fshop.10086.cn%2Fi%2F%3Ff%3Dpackremainqry" + loginScript = loginOrigin + "/platform/js/login_qr_fun.js" + userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36 Edg/155.0.0.0" + fallbackAES = "043AOQGK6ykklyZA" +) + +var ( + ErrNeedLogin = errors.New("会话已失效") + pubRE = regexp.MustCompile(`MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A[A-Za-z0-9+/=]+`) + pkgRE = regexp.MustCompile(`/i/pkg/requirepkg_[A-Za-z0-9]+\.js`) + keyRE = regexp.MustCompile(`\[(?:"[A-Za-z0-9]{4}",){7}"[A-Za-z0-9]{4}"\]`) + keyItemRE = regexp.MustCompile(`"([A-Za-z0-9]{4})"`) +) + +type Cookie struct { + Name string `json:"name"` + Value string `json:"value"` + Domain string `json:"domain"` + Path string `json:"path"` +} + +type LoginResult struct { + Phone string + ProvCode string + ProvName string +} + +type Client struct { + mu sync.Mutex + http *http.Client + jar *cookiejar.Jar + pub *rsa.PublicKey + pubB64 string + aesKey []byte +} + +func New() *Client { + jar, err := cookiejar.New(nil) + if err != nil { + panic(err) + } + return &Client{ + jar: jar, + http: &http.Client{ + Timeout: 30 * time.Second, + Jar: jar, + }, + aesKey: []byte(fallbackAES), + } +} + +func (c *Client) Prepare(ctx context.Context) error { + c.mu.Lock() + defer c.mu.Unlock() + return c.ensureKeys(ctx) +} + +func (c *Client) Captcha(ctx context.Context) ([]byte, string, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureKeys(ctx); err != nil { + return nil, "", err + } + if err := c.bootstrap(ctx); err != nil { + return nil, "", err + } + rawURL := loginOrigin + "/captchazh.htm?type=12×tamp=" + milli() + body, ctype, err := c.get(ctx, rawURL, loginPage) + if err != nil { + return nil, "", err + } + if !strings.Contains(ctype, "image") && !(len(body) > 4 && body[0] == 0x89) && !(len(body) > 2 && body[0] == 0xff) { + return nil, "", errors.New("没有拿到图形验证码") + } + if ctype == "" { + ctype = "image/png" + } + return body, ctype, nil +} + +func (c *Client) SendSMS(ctx context.Context, phone, imageCode string) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureKeys(ctx); err != nil { + return "", err + } + encPhone, err := rsaEncrypt(c.pub, phone) + if err != nil { + return "", err + } + encCode, err := rsaEncrypt(c.pub, imageCode) + if err != nil { + return "", err + } + vbody, err := c.postForm(ctx, loginOrigin+"/verifyCaptcha.htm", url.Values{"inputCode": {imageCode}}) + if err != nil { + return "", err + } + var captchaRes struct { + ResultCode string `json:"resultCode"` + } + _ = json.Unmarshal(vbody, &captchaRes) + if captchaRes.ResultCode != "" && captchaRes.ResultCode != "0" { + return "", errors.New("图形验证码不正确") + } + if _, err := c.postForm(ctx, loginOrigin+"/chkNumberAction.action", url.Values{ + "userName": {encPhone}, + "loginMode": {"01"}, + "channelID": {channelID}, + }); err != nil { + return "", err + } + tokenBody, err := c.postForm(ctx, loginOrigin+"/loadToken.action", url.Values{"userName": {encPhone}}) + if err != nil { + return "", err + } + var tokenRes struct { + RspCode string `json:"rspCode"` + RspDesc string `json:"rspDesc"` + Result string `json:"result"` + } + _ = json.Unmarshal(tokenBody, &tokenRes) + if tokenRes.Result == "" { + if tokenRes.RspDesc != "" { + return "", errors.New(tokenRes.RspDesc) + } + return "", errors.New("没有拿到短信发送凭证") + } + body, err := c.postFormHeader(ctx, loginOrigin+"/sendRandomCodeAction.action", url.Values{ + "userName": {encPhone}, + "inputCode": {encCode}, + "type": {"01"}, + "channelID": {channelID}, + }, map[string]string{"Xa-before": tokenRes.Result}) + if err != nil { + return "", err + } + return smsMessage(strings.TrimSpace(string(body))) +} + +func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID string) (LoginResult, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureKeys(ctx); err != nil { + return LoginResult{}, err + } + encPhone, err := rsaEncrypt(c.pub, phone) + if err != nil { + return LoginResult{}, err + } + encSMS, err := rsaEncrypt(c.pub, smsCode) + if err != nil { + return LoginResult{}, err + } + _, _ = c.postJSON(ctx, loginOrigin+"/fkRisk.action", map[string]string{ + "account": encPhone, + "const_id": deviceID, + "login_channel": channelID, + }) + body, err := c.postForm(ctx, loginOrigin+"/login.htm", url.Values{ + "accountType": {"01"}, + "account": {encPhone}, + "password": {encSMS}, + "pwdType": {"02"}, + "email_sms": {""}, + "smsPwd": {"false"}, + "inputCode": {imageCode}, + "backUrl": {backURL}, + "rememberMe": {"1"}, + "channelID": {channelID}, + "loginMode": {"01"}, + "protocol": {"https:"}, + "deviceId": {deviceID}, + "deviceIdSource": {"fingerprint"}, + "timestamp": {milli()}, + }) + if err != nil { + return LoginResult{}, err + } + var loginRes struct { + Code string `json:"code"` + Desc string `json:"desc"` + Artifact string `json:"artifact"` + Type string `json:"type"` + } + if err := json.Unmarshal(body, &loginRes); err != nil { + return LoginResult{}, errors.New("登录结果无法解析") + } + if loginRes.Code != "0000" || loginRes.Artifact == "" { + if loginRes.Desc != "" { + return LoginResult{}, errors.New(loginRes.Desc) + } + return LoginResult{}, errors.New("登录失败") + } + art, err := url.Parse(shopOrigin + "/i/v1/auth/getArtifact") + if err != nil { + return LoginResult{}, err + } + q := art.Query() + q.Set("backUrl", backURL) + q.Set("artifact", loginRes.Artifact) + if loginRes.Type == "" { + loginRes.Type = "00" + } + q.Set("type", loginRes.Type) + art.RawQuery = q.Encode() + if _, _, err := c.get(ctx, art.String(), loginPage); err != nil { + return LoginResult{}, err + } + info, err := c.loginfo(ctx) + if err != nil { + return LoginResult{}, err + } + prov := asString(info["provice"]) + if prov == "" { + prov = asString(info["province"]) + } + return LoginResult{Phone: phone, ProvCode: prov, ProvName: ProvinceName(prov)}, nil +} + +func (c *Client) Query(ctx context.Context, phone, prov string) (json.RawMessage, json.RawMessage, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureKeys(ctx); err != nil { + return nil, nil, err + } + token, err := phoneToken(c.aesKey, phone) + if err != nil { + return nil, nil, err + } + pay, err := payPhoneNo(c.aesKey, phone) + if err != nil { + return nil, nil, err + } + headers := map[string]string{"provcode": prov, "payphoneno": pay} + real, err := c.shopGet(ctx, "/i/v1/fee/real/"+token+"?_="+milli(), headers) + if err != nil { + return nil, nil, err + } + plan, err := c.shopGet(ctx, "/i/v1/fee/planbal/"+token+"?_="+milli(), headers) + if err != nil { + return real, nil, err + } + return real, plan, nil +} + +func (c *Client) shopGet(ctx context.Context, path string, extra map[string]string) (json.RawMessage, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, shopOrigin+path, nil) + if err != nil { + return nil, err + } + c.decorate(req, shopOrigin+"/i/?f=packremainqry") + for k, v := range extra { + req.Header.Set(k, v) + } + buf, _, err := c.do(req) + if err != nil { + return nil, err + } + return decodeShop(c.aesKey, buf) +} + +func (c *Client) loginfo(ctx context.Context) (map[string]any, error) { + raw, err := c.shopGet(ctx, "/i/v1/auth/loginfo?_="+milli(), nil) + if err != nil { + return nil, err + } + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil { + return nil, errors.New("登录状态无法解析") + } + return m, nil +} + +func decodeShop(key []byte, buf []byte) (json.RawMessage, error) { + var wrap struct { + RetCode string `json:"retCode"` + RetMsg string `json:"retMsg"` + Data struct { + OutParam string `json:"outParam"` + } `json:"data"` + } + if err := json.Unmarshal(buf, &wrap); err != nil { + return nil, errors.New("网站没有返回账户数据") + } + if wrap.RetCode == "500003" || strings.Contains(wrap.RetMsg, "not login") || strings.Contains(wrap.RetMsg, "未登录") { + return nil, ErrNeedLogin + } + if wrap.RetCode != "000000" { + if wrap.RetMsg != "" { + return nil, errors.New(wrap.RetMsg) + } + return nil, fmt.Errorf("查询失败 %s", wrap.RetCode) + } + if wrap.Data.OutParam == "" { + return buf, nil + } + plain, err := decryptOutParam(key, wrap.Data.OutParam) + if err != nil { + return nil, err + } + return json.RawMessage(plain), nil +} + +func (c *Client) ensureKeys(ctx context.Context) error { + if c.pub != nil && len(c.aesKey) == 16 { + return nil + } + script, _, err := c.get(ctx, loginScript, loginPage) + if err != nil { + return err + } + b64 := pubRE.FindString(string(script)) + if b64 == "" { + return errors.New("登录页没有找到加密公钥") + } + pub, err := parsePublicKey(b64) + if err != nil { + return err + } + c.pub = pub + c.pubB64 = b64 + if key := c.fetchAESKey(ctx); len(key) == 16 { + c.aesKey = key + } + return nil +} + +func (c *Client) fetchAESKey(ctx context.Context) []byte { + page, _, err := c.get(ctx, shopOrigin+"/i/?f=packremainqry", shopOrigin+"/") + if err != nil { + return nil + } + refs := pkgRE.FindAllString(string(page), -1) + for _, ref := range refs { + body, _, err := c.get(ctx, shopOrigin+ref, shopOrigin+"/i/?f=packremainqry") + if err != nil { + continue + } + if key := aesKeyFromJS(string(body)); len(key) == 16 { + return key + } + } + return nil +} + +func aesKeyFromJS(src string) []byte { + for _, raw := range keyRE.FindAllString(src, -1) { + parts := keyItemRE.FindAllStringSubmatch(raw, -1) + if len(parts) < 8 { + continue + } + var b strings.Builder + for i := 0; i < len(parts); i += 2 { + b.WriteString(parts[i][1]) + } + if b.Len() == 16 { + return []byte(b.String()) + } + } + return nil +} + +func (c *Client) postForm(ctx context.Context, rawURL string, form url.Values) ([]byte, error) { + return c.postFormHeader(ctx, rawURL, form, nil) +} + +func (c *Client) postFormHeader(ctx context.Context, rawURL string, form url.Values, extra map[string]string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, strings.NewReader(form.Encode())) + if err != nil { + return nil, err + } + c.decorate(req, loginPage) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") + req.Header.Set("X-Requested-With", "XMLHttpRequest") + for k, v := range extra { + req.Header.Set(k, v) + } + buf, _, err := c.do(req) + return buf, err +} + +func (c *Client) postJSON(ctx context.Context, rawURL string, payload any) ([]byte, error) { + b, err := json.Marshal(payload) + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, strings.NewReader(string(b))) + if err != nil { + return nil, err + } + c.decorate(req, loginPage) + req.Header.Set("Content-Type", "application/json") + buf, _, err := c.do(req) + return buf, err +} + +func (c *Client) get(ctx context.Context, rawURL, referer string) ([]byte, string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, "", err + } + c.decorate(req, referer) + return c.do(req) +} + +func (c *Client) do(req *http.Request) ([]byte, string, error) { + resp, err := c.http.Do(req) + if err != nil { + return nil, "", err + } + defer resp.Body.Close() + buf, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if err != nil { + return nil, "", err + } + if resp.StatusCode >= 400 && !strings.Contains(resp.Header.Get("Content-Type"), "json") { + return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode) + } + return buf, resp.Header.Get("Content-Type"), nil +} + +func (c *Client) decorate(req *http.Request, referer string) { + req.Header.Set("User-Agent", userAgent) + req.Header.Set("Accept", "*/*") + req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8") + req.Header.Set("Referer", referer) + if req.URL != nil && strings.Contains(req.URL.Host, "login.10086.cn") { + req.Header.Set("Origin", loginOrigin) + } +} + +func (c *Client) bootstrap(ctx context.Context) error { + if _, _, err := c.get(ctx, loginPage, loginPage); err != nil { + return err + } + if _, _, err := c.get(ctx, loginOrigin+"/loadSendflag.htm?timestamp="+milli(), loginPage); err != nil { + return err + } + if _, _, err := c.get(ctx, loginOrigin+"/genqr.htm", loginPage); err != nil { + return err + } + _, _, _ = c.get(ctx, shopOrigin+"/i/v1/auth/loginfo?_="+milli(), shopOrigin+"/i/?f=packremainqry") + return nil +} + +func (c *Client) ExportCookies() []Cookie { + c.mu.Lock() + defer c.mu.Unlock() + var out []Cookie + for _, raw := range []string{loginOrigin + "/", shopOrigin + "/", "https://10086.cn/"} { + u, _ := url.Parse(raw) + for _, ck := range c.jar.Cookies(u) { + out = append(out, Cookie{Name: ck.Name, Value: ck.Value, Domain: hostOf(u), Path: "/"}) + } + } + return dedupeCookies(out) +} + +func (c *Client) ImportCookies(list []Cookie) { + c.mu.Lock() + defer c.mu.Unlock() + grouped := map[string][]*http.Cookie{} + for _, item := range list { + if item.Name == "" { + continue + } + domain := item.Domain + if domain == "" { + domain = "shop.10086.cn" + } + path := item.Path + if path == "" { + path = "/" + } + grouped[domain] = append(grouped[domain], &http.Cookie{Name: item.Name, Value: item.Value, Path: path}) + } + for domain, cs := range grouped { + u, err := url.Parse("https://" + strings.TrimPrefix(domain, ".") + "/") + if err != nil { + continue + } + c.jar.SetCookies(u, cs) + } +} + +func (c *Client) Reset() { + c.mu.Lock() + defer c.mu.Unlock() + jar, err := cookiejar.New(nil) + if err != nil { + return + } + c.jar = jar + c.http.Jar = jar +} + +func dedupeCookies(list []Cookie) []Cookie { + seen := map[string]bool{} + out := make([]Cookie, 0, len(list)) + for _, item := range list { + k := item.Domain + "|" + item.Name + if seen[k] { + continue + } + seen[k] = true + out = append(out, item) + } + return out +} + +func hostOf(u *url.URL) string { + if u == nil { + return "" + } + return u.Hostname() +} + +func milli() string { + return fmt.Sprintf("%d", time.Now().UnixMilli()) +} + +func smsMessage(body string) (string, error) { + code := strings.Trim(strings.TrimSpace(body), `"`) + switch code { + case "0": + return "短信验证码已发送", nil + case "1": + return "", errors.New("短信暂时不能发送,请一分钟后再试") + case "2": + return "", errors.New("短信验证码获取已达上限") + case "3": + return "", errors.New("短信发送过于频繁") + case "4005": + return "", errors.New("手机号码有误") + default: + if code == "" { + return "", errors.New("短信接口没有返回结果") + } + return "", fmt.Errorf("发送短信验证码失败(%s)", code) + } +} + +func asString(v any) string { + s, _ := v.(string) + return s +} diff --git a/internal/cmnet/crypto.go b/internal/cmnet/crypto.go new file mode 100644 index 0000000..60bc582 --- /dev/null +++ b/internal/cmnet/crypto.go @@ -0,0 +1,127 @@ +package cmnet + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "errors" + "strings" +) + +func rsaEncrypt(pub *rsa.PublicKey, plain string) (string, error) { + if pub == nil { + return "", errors.New("缺少登录公钥") + } + ct, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(plain)) + if err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(ct), nil +} + +func parsePublicKey(b64 string) (*rsa.PublicKey, error) { + der, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + return nil, err + } + pub, err := x509.ParsePKIXPublicKey(der) + if err != nil { + return nil, err + } + rk, ok := pub.(*rsa.PublicKey) + if !ok { + return nil, errors.New("登录公钥不是 RSA") + } + return rk, nil +} + +func aesEncryptB64(key []byte, plain string) (string, error) { + block, err := aes.NewCipher(key) + if err != nil { + return "", err + } + src := pkcs7Pad([]byte(plain), aes.BlockSize) + dst := make([]byte, len(src)) + cipher.NewCBCEncrypter(block, key).CryptBlocks(dst, src) + return base64.StdEncoding.EncodeToString(dst), nil +} + +func aesDecryptB64(key []byte, b64 string) ([]byte, error) { + raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(b64)) + if err != nil { + return nil, err + } + if len(raw) == 0 || len(raw)%aes.BlockSize != 0 { + return nil, errors.New("余额数据无法解密") + } + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + dst := make([]byte, len(raw)) + cipher.NewCBCDecrypter(block, key).CryptBlocks(dst, raw) + return pkcs7Unpad(dst, aes.BlockSize) +} + +func phoneToken(key []byte, phone string) (string, error) { + inner, err := aesEncryptB64(key, phone) + if err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString([]byte(inner)), nil +} + +func payPhoneNo(key []byte, phone string) (string, error) { + token, err := phoneToken(key, phone) + if err != nil { + return "", err + } + tail := "" + if len(phone) >= 7 { + tail = phone[5:7] + } + return token + tail, nil +} + +func decryptOutParam(key []byte, outParam string) ([]byte, error) { + raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(outParam)) + if err != nil { + return nil, err + } + inner := strings.Map(func(r rune) rune { + if r == ' ' || r == '\n' || r == '\r' || r == '\t' { + return -1 + } + return r + }, string(raw)) + return aesDecryptB64(key, inner) +} + +func pkcs7Pad(b []byte, size int) []byte { + n := size - len(b)%size + out := make([]byte, len(b)+n) + copy(out, b) + for i := len(b); i < len(out); i++ { + out[i] = byte(n) + } + return out +} + +func pkcs7Unpad(b []byte, size int) ([]byte, error) { + if len(b) == 0 || len(b)%size != 0 { + return nil, errors.New("余额数据无法解密") + } + n := int(b[len(b)-1]) + if n == 0 || n > size || n > len(b) { + return nil, errors.New("余额数据无法解密") + } + for _, c := range b[len(b)-n:] { + if int(c) != n { + return nil, errors.New("余额数据无法解密") + } + } + return b[:len(b)-n], nil +} diff --git a/internal/cmnet/crypto_test.go b/internal/cmnet/crypto_test.go new file mode 100644 index 0000000..9665a2a --- /dev/null +++ b/internal/cmnet/crypto_test.go @@ -0,0 +1,76 @@ +package cmnet + +import ( + "archive/zip" + "encoding/json" + "testing" +) + +func TestAESKeyParse(t *testing.T) { + src := `b=["043A","lyZA","OQGK","043A","6ykk","OQGK","lyZA","6ykk"]` + if string(aesKeyFromJS(src)) != fallbackAES { + t.Fatalf("key %s", aesKeyFromJS(src)) + } +} + +func TestPhoneTokenMatchesCapture(t *testing.T) { + token, err := phoneToken([]byte(fallbackAES), "13800000000") + if err != nil || token == "" { + t.Fatal(err) + } + back, err := decryptOutParam([]byte(fallbackAES), token) + if err != nil || string(back) != "13800000000" { + t.Fatalf("roundtrip %q %v", back, err) + } +} + +func TestDecryptCapturedPlan(t *testing.T) { + z, err := zip.OpenReader("../../cmnet.chlz") + if err != nil { + t.Skip(err) + } + defer z.Close() + var op string + for _, f := range z.File { + if f.Name != "156-res.json" { + continue + } + r, err := f.Open() + if err != nil { + t.Fatal(err) + } + var wrap struct { + Data struct { + OutParam string `json:"outParam"` + } `json:"data"` + } + if err := json.NewDecoder(r).Decode(&wrap); err != nil { + r.Close() + t.Fatal(err) + } + r.Close() + op = wrap.Data.OutParam + } + if op == "" { + t.Fatal("missing plan response") + } + plain, err := decryptOutParam([]byte(fallbackAES), op) + if err != nil { + t.Fatal(err) + } + snap := BuildSnapshot("13800000000", "广东", nil, plain) + if len(snap.Resources) == 0 { + t.Fatal("no resources") + } + if snap.VoiceTotal != "100" || snap.VoiceRemain != "78" { + t.Fatalf("voice total %s remain %s", snap.VoiceTotal, snap.VoiceRemain) + } + if snap.DataTotal != "64.10" || snap.DataUsed != "31.39" || snap.DataRemain != "32.70" { + t.Fatalf("data total %s used %s remain %s", snap.DataTotal, snap.DataUsed, snap.DataRemain) + } + for _, item := range snap.Resources { + if item.Unit == "分钟" && item.Total == "1" { + t.Fatalf("voice row total was truncated: %+v", item) + } + } +} diff --git a/internal/cmnet/format.go b/internal/cmnet/format.go new file mode 100644 index 0000000..418b7e8 --- /dev/null +++ b/internal/cmnet/format.go @@ -0,0 +1,390 @@ +package cmnet + +import ( + "encoding/json" + "math" + "strconv" + "strings" +) + +type Snapshot struct { + Phone string `json:"phone,omitempty"` + PhoneMasked string `json:"phoneMasked,omitempty"` + Region string `json:"region,omitempty"` + PackageName string `json:"packageName,omitempty"` + OpenedAt string `json:"openedAt,omitempty"` + Cycle string `json:"cycle,omitempty"` + Balance string `json:"balance,omitempty"` + BalanceNegative bool `json:"balanceNegative,omitempty"` + MonthFee string `json:"monthFee,omitempty"` + DataTotal string `json:"dataTotal,omitempty"` + DataUsed string `json:"dataUsed,omitempty"` + DataRemain string `json:"dataRemain,omitempty"` + DataExtra string `json:"dataExtra,omitempty"` + VoiceTotal string `json:"voiceTotal,omitempty"` + VoiceRemain string `json:"voiceRemain,omitempty"` + Resources []Resource `json:"resources"` + Extras []Extra `json:"extras"` + Bills []Bill `json:"bills"` +} + +type Resource struct { + Name string `json:"name"` + Used string `json:"used"` + Remain string `json:"remain"` + Total string `json:"total"` + Unit string `json:"unit"` + Percent float64 `json:"percent"` +} + +type Extra struct { + Name string `json:"name"` + Used string `json:"used"` + Fee string `json:"fee"` +} + +type Bill struct { + Title string `json:"title"` + Items []BillItem `json:"items"` +} + +type BillItem struct { + Name string `json:"name"` + Value string `json:"value"` +} + +func BuildSnapshot(phone, provName string, realRaw, planRaw json.RawMessage) Snapshot { + snap := Snapshot{ + Phone: strings.TrimSpace(phone), + PhoneMasked: MaskPhone(phone), + Region: provName, + PackageName: "中国移动", + Resources: []Resource{}, + Extras: []Extra{}, + Bills: []Bill{}, + } + var real map[string]any + _ = json.Unmarshal(realRaw, &real) + if real != nil { + snap.Balance = text(real["realBalanceFee"]) + snap.MonthFee = text(real["realFee"]) + if owe := text(real["oweFee"]); owe != "" && owe != "0" && owe != "0.00" { + snap.Extras = append(snap.Extras, Extra{Name: "欠费", Used: owe, Fee: owe}) + } + snap.Bills = []Bill{{ + Title: "话费", + Items: []BillItem{ + {Name: "话费余额", Value: snap.Balance}, + {Name: "当月消费", Value: snap.MonthFee}, + {Name: "欠费", Value: text(real["oweFee"])}, + }, + }} + } + snap.Resources = resourcesFromPlan(planRaw) + snap.DataTotal, snap.DataUsed, snap.DataRemain, snap.DataExtra, snap.VoiceTotal, snap.VoiceRemain = officialTotals(planRaw) + return snap +} + +func resourcesFromPlan(raw json.RawMessage) []Resource { + var plans []struct { + Arr []struct { + MealName string `json:"mealName"` + ResInfos []struct { + SecResInfos []struct { + ResConName string `json:"resConName"` + ResConInfo struct { + TotalMeal string `json:"totalMeal"` + UseMeal string `json:"useMeal"` + BalMeal string `json:"balMeal"` + Unit string `json:"unit"` + } `json:"resConInfo"` + } `json:"secResInfos"` + } `json:"resInfos"` + } `json:"arr"` + } + if json.Unmarshal(raw, &plans) != nil { + return []Resource{} + } + out := []Resource{} + for _, plan := range plans { + for _, meal := range plan.Arr { + for _, res := range meal.ResInfos { + for _, sec := range res.SecResInfos { + info := sec.ResConInfo + name := sec.ResConName + if meal.MealName != "" { + name = meal.MealName + if sec.ResConName != "" { + name = meal.MealName + " · " + sec.ResConName + } + } + item := scaleResource(name, info.UseMeal, info.BalMeal, info.TotalMeal, info.Unit) + out = append(out, item) + } + } + } + } + return out +} + +func scaleResource(name, used, remain, total, unit string) Resource { + item := Resource{Name: name} + switch unit { + case "01": + item.Unit = "分钟" + item.Used, item.Remain, item.Total = num(used), num(remain), num(total) + case "02": + item.Unit = "条" + item.Used, item.Remain, item.Total = num(used), num(remain), num(total) + case "03": + item.Unit = "G" + item.Used, item.Remain, item.Total = kbToG(used), kbToG(remain), kbToG(total) + case "04": + item.Unit = "MB" + item.Used, item.Remain, item.Total = kbToMB(used), kbToMB(remain), kbToMB(total) + default: + item.Unit = unit + item.Used, item.Remain, item.Total = num(used), num(remain), num(total) + } + item.Percent = percent(item.Used, item.Total) + return item +} + +type planGroup struct { + Type any `json:"type"` + Arr []planMeal `json:"arr"` +} + +type planMeal struct { + ExpireFlag any `json:"expireFlag"` + ResInfos []planRes `json:"resInfos"` +} + +type planRes struct { + ResCode string `json:"resCode"` + SecResInfos []planSec `json:"secResInfos"` +} + +type planSec struct { + ResConName string `json:"resConName"` + ResConInfo planAmount `json:"resConInfo"` +} + +type planAmount struct { + TotalMeal string `json:"totalMeal"` + UseMeal string `json:"useMeal"` + BalMeal string `json:"balMeal"` + Unit string `json:"unit"` +} + +// officialTotals follows the shop homepage: voice is resCode 01, and general +// data is resCode 04 except items whose name starts with "10-" (定向流量). +// Only the current, unexpired group (type 1, expireFlag not 1) is included. +func officialTotals(raw json.RawMessage) (dataTotal, dataUsed, dataRemain, dataExtra, voiceTotal, voiceRemain string) { + var groups []planGroup + if json.Unmarshal(raw, &groups) != nil { + return + } + var current []planMeal + found := false + for _, group := range groups { + if isOne(group.Type) { + current = group.Arr + found = true + } + } + if !found { + return + } + var voiceT, voiceR float64 + var voiceHas bool + var dataT, dataU, dataR float64 + var dataHas bool + for _, meal := range current { + if isOne(meal.ExpireFlag) { + continue + } + for _, res := range meal.ResInfos { + switch res.ResCode { + case "01": + for _, sec := range res.SecResInfos { + voiceHas = true + voiceT += atof(sec.ResConInfo.TotalMeal) + voiceR += atof(sec.ResConInfo.BalMeal) + } + case "04": + for _, sec := range res.SecResInfos { + if strings.HasPrefix(sec.ResConName, "10-") || !numericMeal(sec.ResConInfo.TotalMeal) { + continue + } + kbT, okT := amountKB(sec.ResConInfo.TotalMeal, sec.ResConInfo.Unit) + kbU, okU := amountKB(sec.ResConInfo.UseMeal, sec.ResConInfo.Unit) + kbR, okR := amountKB(sec.ResConInfo.BalMeal, sec.ResConInfo.Unit) + if !okT && !okU && !okR { + continue + } + dataHas = true + dataT += kbT + dataU += kbU + dataR += kbR + } + } + } + } + if voiceHas { + voiceTotal = formatCount(voiceT) + voiceRemain = formatCount(voiceR) + } + if dataHas { + dataTotal = formatGB(dataT) + dataUsed = formatGB(dataU) + dataRemain = formatGB(dataR) + dataExtra = "0.00" + } + return +} + +func isOne(v any) bool { + switch t := v.(type) { + case string: + return t == "1" + case float64: + return t == 1 + default: + return false + } +} + +func numericMeal(s string) bool { + s = strings.TrimSpace(s) + if s == "" { + return true + } + _, err := strconv.ParseFloat(s, 64) + return err == nil +} + +func amountKB(amount, unit string) (float64, bool) { + s := strings.TrimSpace(amount) + if s == "" { + return 0, true + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return 0, false + } + switch unit { + case "04": + return f * 1024, true + case "05": + return f * 1024 * 1024, true + default: + return f, true + } +} + +func formatCount(f float64) string { + if f == math.Trunc(f) { + return strconv.FormatFloat(f, 'f', 0, 64) + } + return strconvFormat(f, 2) +} + +func formatGB(kb float64) string { + return strconv.FormatFloat(kb/1024/1024, 'f', 2, 64) +} + +func kbToG(s string) string { + return fixed(atof(s) / 1024 / 1024) +} + +func kbToMB(s string) string { + return fixed(atof(s) / 1024) +} + +func fixed(f float64) string { + return strconvFormat(f, 2) +} + +func num(s string) string { + f := atof(s) + if f == math.Trunc(f) { + return strconvFormat(f, 0) + } + return fixed(f) +} + +func strconvFormat(f float64, prec int) string { + s := strconvFormatRaw(f, prec) + if !strings.Contains(s, ".") { + return s + } + s = strings.TrimRight(strings.TrimRight(s, "0"), ".") + if s == "" || s == "-" { + return "0" + } + return s +} + +func strconvFormatRaw(f float64, prec int) string { + return strconv.FormatFloat(f, 'f', prec, 64) +} + +func atof(s string) float64 { + f, err := strconv.ParseFloat(strings.TrimSpace(s), 64) + if err != nil { + return 0 + } + return f +} + +func text(v any) string { + switch t := v.(type) { + case string: + return t + case float64: + return fixed(t) + default: + return "" + } +} + +func percent(used, total string) float64 { + t := atof(total) + if t <= 0 { + return 0 + } + p := atof(used) / t * 100 + if p < 0 { + return 0 + } + if p > 100 { + return 100 + } + return math.Round(p*10) / 10 +} + +func MaskPhone(phone string) string { + if len(phone) == 11 { + return phone[:3] + "****" + phone[7:] + } + return phone +} + +func ProvinceName(code string) string { + names := map[string]string{ + "100": "北京", "200": "广东", "210": "上海", "220": "天津", "230": "重庆", + "240": "辽宁", "250": "江苏", "270": "湖北", "280": "四川", "290": "陕西", + "311": "河北", "351": "山西", "371": "河南", "431": "吉林", "451": "黑龙江", + "471": "内蒙古", "531": "山东", "551": "安徽", "571": "浙江", "591": "福建", + "731": "湖南", "771": "广西", "791": "江西", "851": "贵州", "871": "云南", + "891": "西藏", "898": "海南", "931": "甘肃", "951": "宁夏", "971": "青海", "991": "新疆", + } + if name, ok := names[code]; ok { + return name + } + if code == "" { + return "中国移动" + } + return "中国移动 " + code +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..0f1d180 --- /dev/null +++ b/main.go @@ -0,0 +1,723 @@ +package main + +import ( + "context" + crand "crypto/rand" + _ "embed" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "math/rand/v2" + "net/http" + "os" + "os/signal" + "path/filepath" + "strings" + "sync" + "syscall" + "time" + _ "time/tzdata" + + "cmnetsmsinfo/internal/cmnet" +) + +//go:embed web/index.html +var indexPage []byte + +//go:embed web/favicon.ico +var favicon []byte + +const statePath = "data/state.json" + +type Config struct { + Listen string `json:"listen"` + PollInterval string `json:"pollInterval"` + JitterMinutes int `json:"jitterMinutes"` + Phone string `json:"phone"` +} + +type savedState struct { + Phone string `json:"phone"` + ProvCode string `json:"provCode"` + DeviceID string `json:"deviceId"` + LoggedIn bool `json:"loggedIn"` + SessionOK bool `json:"sessionOk"` + Cookies []cmnet.Cookie `json:"cookies"` + Snapshot cmnet.Snapshot `json:"snapshot"` + RealRaw json.RawMessage `json:"realRaw,omitempty"` + PlanRaw json.RawMessage `json:"planRaw,omitempty"` + RefreshedAt time.Time `json:"refreshedAt"` + LastError string `json:"lastError"` + Stale bool `json:"stale"` + PollMinutes int `json:"pollMinutes"` + JitterMinutes int `json:"jitterMinutes"` +} + +type overview struct { + LoggedIn bool `json:"loggedIn"` + NeedLogin bool `json:"needLogin"` + CanResume bool `json:"canResume"` + Refreshing bool `json:"refreshing"` + PollEvery string `json:"pollEvery"` + PollMinutes int `json:"pollMinutes"` + JitterMinutes int `json:"jitterMinutes"` + SecondsLeft int `json:"secondsLeft"` + RefreshedAt string `json:"refreshedAt,omitempty"` + Error string `json:"error,omitempty"` + Stale bool `json:"stale"` + HasData bool `json:"hasData"` + cmnet.Snapshot +} + +type App struct { + client *cmnet.Client + interval time.Duration + jitter time.Duration + pollText string + cfgPhone string + kick chan struct{} + saveMu sync.Mutex + + mu sync.Mutex + phone string + provCode string + deviceID string + loggedIn bool + sessionOK bool + snap cmnet.Snapshot + realRaw json.RawMessage + planRaw json.RawMessage + refreshedAt time.Time + nextAt time.Time + lastError string + stale bool + refreshing bool +} + +func main() { + log.SetFlags(log.LstdFlags) + cfg := loadConfig() + interval, err := time.ParseDuration(cfg.PollInterval) + if err != nil || interval < time.Minute { + log.Printf("轮询间隔无效,已改用 30 分钟") + interval = 30 * time.Minute + } + if cfg.JitterMinutes < 0 || cfg.JitterMinutes > 1440 { + cfg.JitterMinutes = 0 + } + app := newApp(cmnet.New(), strings.TrimSpace(cfg.Phone), interval, time.Duration(cfg.JitterMinutes)*time.Minute) + app.load() + prepCtx, prepCancel := context.WithTimeout(context.Background(), 45*time.Second) + if err := app.client.Prepare(prepCtx); err != nil { + log.Printf("登录参数暂未就绪,登录时会再试: %v", err) + } + prepCancel() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + go app.loop(ctx) + + mux := http.NewServeMux() + mux.HandleFunc("GET /{$}", app.page) + mux.HandleFunc("GET /favicon.ico", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "image/x-icon") + w.Header().Set("Cache-Control", "public, max-age=86400") + _, _ = w.Write(favicon) + }) + mux.HandleFunc("GET /api/overview", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, app.view()) + }) + mux.HandleFunc("POST /api/refresh", app.manualRefresh) + mux.HandleFunc("GET /api/captcha", app.captcha) + mux.HandleFunc("POST /api/sms", app.sms) + mux.HandleFunc("POST /api/login", app.login) + mux.HandleFunc("POST /api/logout", app.logout) + mux.HandleFunc("POST /api/resume", app.resume) + mux.HandleFunc("POST /api/interval", app.setInterval) + + srv := &http.Server{Addr: cfg.Listen, Handler: mux, ReadHeaderTimeout: 10 * time.Second} + go func() { + <-ctx.Done() + shut, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = srv.Shutdown(shut) + }() + log.Printf("已启动,浏览器打开 %s", listenURL(cfg.Listen)) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatal(err) + } +} + +func newApp(client *cmnet.Client, phone string, interval, jitter time.Duration) *App { + return &App{ + client: client, + interval: interval, + jitter: jitter, + pollText: humanInterval(interval), + cfgPhone: phone, + kick: make(chan struct{}, 1), + deviceID: newDeviceID(), + snap: cmnet.Snapshot{ + Resources: []cmnet.Resource{}, + Extras: []cmnet.Extra{}, + Bills: []cmnet.Bill{}, + }, + } +} + +func (a *App) loop(ctx context.Context) { + timer := time.NewTimer(time.Hour) + stopTimer(timer) + if a.isLoggedIn() { + a.stampNext() + timer.Reset(a.untilNext()) + go a.refresh() + } + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-a.kick: + stopTimer(timer) + if a.isLoggedIn() { + timer.Reset(a.untilNext()) + } + case <-timer.C: + if !a.isLoggedIn() { + continue + } + a.stampNext() + timer.Reset(a.untilNext()) + go a.refresh() + } + } +} + +func stopTimer(timer *time.Timer) { + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } +} + +func (a *App) wakeLoop() { + select { + case a.kick <- struct{}{}: + default: + } +} + +func (a *App) refresh() bool { + a.mu.Lock() + if !a.loggedIn || a.phone == "" { + a.mu.Unlock() + return true + } + if a.refreshing { + a.mu.Unlock() + return false + } + a.refreshing = true + phone, prov := a.phone, a.provCode + a.mu.Unlock() + + defer func() { + a.mu.Lock() + a.refreshing = false + a.mu.Unlock() + a.save() + }() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + real, plan, err := a.client.Query(ctx, phone, prov) + if errors.Is(err, cmnet.ErrNeedLogin) { + a.markLoggedOut("会话已失效,请重新登录") + return true + } + a.mu.Lock() + defer a.mu.Unlock() + if a.phone != phone || !a.loggedIn { + return true + } + if err != nil && real == nil && plan == nil { + a.stale = true + a.lastError = err.Error() + return true + } + if real != nil { + a.realRaw = real + } + if plan != nil { + a.planRaw = plan + } + a.snap = cmnet.BuildSnapshot(phone, cmnetProvince(prov), a.realRaw, a.planRaw) + a.stale = err != nil + if err != nil { + a.lastError = err.Error() + return true + } + a.lastError = "" + a.refreshedAt = time.Now() + log.Printf("同步完成 %s", a.snap.PhoneMasked) + return true +} + +func (a *App) markLoggedOut(msg string) { + a.client.Reset() + a.mu.Lock() + a.loggedIn = false + a.sessionOK = false + a.snap = emptySnap() + a.realRaw, a.planRaw = nil, nil + a.stale = false + a.refreshedAt = time.Time{} + a.lastError = msg + a.nextAt = time.Time{} + a.mu.Unlock() +} + +func (a *App) page(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + _, _ = w.Write(indexPage) +} + +func (a *App) manualRefresh(w http.ResponseWriter, r *http.Request) { + if a.isLoggedIn() && a.refresh() && a.isLoggedIn() { + a.stampNext() + a.wakeLoop() + a.save() + } + writeJSON(w, http.StatusOK, a.view()) +} + +func (a *App) captcha(w http.ResponseWriter, r *http.Request) { + body, ctype, err := a.client.Captcha(r.Context()) + if err != nil { + writeJSON(w, http.StatusBadGateway, map[string]any{"ok": false, "message": err.Error()}) + return + } + a.save() + w.Header().Set("Content-Type", ctype) + w.Header().Set("Cache-Control", "no-store") + _, _ = w.Write(body) +} + +func (a *App) sms(w http.ResponseWriter, r *http.Request) { + var req struct { + Phone string `json:"phone"` + ImageCode string `json:"imageCode"` + } + if err := decode(r, &req); err != nil { + writeErr(w, "请求格式不对") + return + } + phone := strings.TrimSpace(req.Phone) + image := strings.TrimSpace(req.ImageCode) + if !validPhone(phone) { + writeErr(w, "请输入正确的手机号码") + return + } + if image == "" { + writeErr(w, "请填写图形验证码") + return + } + msg, err := a.client.SendSMS(r.Context(), phone, image) + if err != nil { + writeErr(w, err.Error()) + return + } + a.mu.Lock() + a.phone = phone + a.mu.Unlock() + a.save() + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": msg}) +} + +func (a *App) login(w http.ResponseWriter, r *http.Request) { + var req struct { + Phone string `json:"phone"` + ImageCode string `json:"imageCode"` + SMSCode string `json:"smsCode"` + } + if err := decode(r, &req); err != nil { + writeErr(w, "请求格式不对") + return + } + phone := strings.TrimSpace(req.Phone) + image := strings.TrimSpace(req.ImageCode) + sms := strings.TrimSpace(req.SMSCode) + if !validPhone(phone) || image == "" || sms == "" { + writeErr(w, "请填写手机号、图形验证码和短信验证码") + return + } + a.mu.Lock() + deviceID := a.deviceID + a.mu.Unlock() + result, err := a.client.Login(r.Context(), phone, image, sms, deviceID) + if err != nil { + writeErr(w, err.Error()) + return + } + a.mu.Lock() + a.loggedIn = true + a.sessionOK = true + a.phone = result.Phone + a.provCode = result.ProvCode + a.lastError = "" + a.stale = false + a.mu.Unlock() + a.stampNext() + a.wakeLoop() + a.save() + a.refresh() + 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) { + a.mu.Lock() + a.loggedIn = false + a.lastError = "" + a.nextAt = time.Time{} + a.mu.Unlock() + a.wakeLoop() + a.save() + writeJSON(w, http.StatusOK, a.view()) +} + +func (a *App) resume(w http.ResponseWriter, r *http.Request) { + var req struct { + Phone string `json:"phone"` + } + if err := decode(r, &req); err != nil { + writeErr(w, "请求格式不对") + return + } + phone := strings.TrimSpace(req.Phone) + a.mu.Lock() + same := a.sessionOK && a.phone != "" && a.phone == phone + a.mu.Unlock() + if !same { + writeJSON(w, http.StatusOK, map[string]any{"ok": false, "needCode": true}) + return + } + a.mu.Lock() + a.loggedIn = true + a.lastError = "" + a.mu.Unlock() + a.stampNext() + a.wakeLoop() + a.refresh() + if !a.isLoggedIn() { + writeJSON(w, http.StatusOK, map[string]any{"ok": false, "expired": true, "message": "会话已过期"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (a *App) clientCookies() []cmnet.Cookie { + return a.client.ExportCookies() +} + +func (a *App) setInterval(w http.ResponseWriter, r *http.Request) { + var req struct { + Minutes int `json:"minutes"` + Jitter int `json:"jitter"` + } + if err := decode(r, &req); err != nil || req.Minutes < 1 || req.Minutes > 1440 { + writeErr(w, "间隔需在 1 到 1440 分钟之间") + return + } + if req.Jitter < 0 || req.Jitter > 1440 { + writeErr(w, "随机需在 0 到 1440 分钟之间") + return + } + a.mu.Lock() + a.interval = time.Duration(req.Minutes) * time.Minute + a.jitter = time.Duration(req.Jitter) * time.Minute + a.pollText = humanInterval(a.interval) + if a.loggedIn { + a.stampNextLocked() + } + a.mu.Unlock() + a.wakeLoop() + a.save() + writeJSON(w, http.StatusOK, a.view()) +} + +func (a *App) untilNext() time.Duration { + a.mu.Lock() + defer a.mu.Unlock() + if !a.nextAt.IsZero() { + if d := time.Until(a.nextAt); d > 0 { + return d + } + } + return time.Second +} + +func (a *App) view() overview { + a.mu.Lock() + defer a.mu.Unlock() + snap := a.snap + if snap.Resources == nil { + snap.Resources = []cmnet.Resource{} + } + if snap.Extras == nil { + snap.Extras = []cmnet.Extra{} + } + if snap.Bills == nil { + snap.Bills = []cmnet.Bill{} + } + if !a.loggedIn { + phone := a.phone + snap = emptySnap() + snap.Phone = phone + snap.PhoneMasked = cmnet.MaskPhone(phone) + } + out := overview{ + LoggedIn: a.loggedIn, + NeedLogin: !a.loggedIn, + CanResume: !a.loggedIn && a.sessionOK && a.phone != "", + Refreshing: a.refreshing, + PollEvery: a.pollText, + PollMinutes: int(a.interval / time.Minute), + JitterMinutes: int(a.jitter / time.Minute), + Error: a.lastError, + Stale: a.loggedIn && a.stale, + HasData: a.loggedIn && hasData(snap), + Snapshot: snap, + } + if a.loggedIn && !a.refreshedAt.IsZero() { + out.RefreshedAt = a.refreshedAt.In(shanghai()).Format("2006-01-02 15:04") + } + if a.loggedIn && !a.nextAt.IsZero() { + left := time.Until(a.nextAt) + if left < 0 { + left = 0 + } + out.SecondsLeft = int(left.Round(time.Second) / time.Second) + } + return out +} + +func emptySnap() cmnet.Snapshot { + return cmnet.Snapshot{Resources: []cmnet.Resource{}, Extras: []cmnet.Extra{}, Bills: []cmnet.Bill{}} +} + +func (a *App) load() { + b, err := os.ReadFile(statePath) + if err != nil { + a.phone = a.cfgPhone + return + } + var st savedState + if json.Unmarshal(b, &st) != nil { + a.phone = a.cfgPhone + return + } + a.phone = strings.TrimSpace(st.Phone) + if a.phone == "" { + a.phone = a.cfgPhone + } + a.provCode = st.ProvCode + if 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 { + a.interval = time.Duration(st.PollMinutes) * time.Minute + a.pollText = humanInterval(a.interval) + } + if st.JitterMinutes >= 0 && st.JitterMinutes <= 1440 { + a.jitter = time.Duration(st.JitterMinutes) * time.Minute + } + a.client.ImportCookies(st.Cookies) + if len(a.planRaw) > 0 || len(a.realRaw) > 0 { + a.snap = cmnet.BuildSnapshot(a.phone, cmnet.ProvinceName(a.provCode), a.realRaw, a.planRaw) + } + if a.loggedIn { + log.Printf("已恢复会话 %s", cmnet.MaskPhone(a.phone)) + } +} + +func (a *App) save() { + a.saveMu.Lock() + defer a.saveMu.Unlock() + a.mu.Lock() + st := savedState{ + Phone: a.phone, ProvCode: a.provCode, DeviceID: a.deviceID, LoggedIn: a.loggedIn, SessionOK: a.sessionOK, + Snapshot: a.snap, RealRaw: a.realRaw, PlanRaw: a.planRaw, RefreshedAt: a.refreshedAt, + LastError: a.lastError, Stale: a.stale, + PollMinutes: int(a.interval / time.Minute), JitterMinutes: int(a.jitter / time.Minute), + } + a.mu.Unlock() + st.Cookies = a.client.ExportCookies() + buf, err := json.MarshalIndent(st, "", " ") + if err != nil { + log.Printf("保存会话失败: %v", err) + return + } + if err := writeFileAtomic(statePath, buf); err != nil { + log.Printf("保存会话失败: %v", err) + } +} + +func (a *App) isLoggedIn() bool { + a.mu.Lock() + defer a.mu.Unlock() + return a.loggedIn +} + +func (a *App) stampNext() { + a.mu.Lock() + a.stampNextLocked() + a.mu.Unlock() +} + +func (a *App) stampNextLocked() { + a.nextAt = time.Now().Add(a.nextWaitLocked()) +} + +func (a *App) nextWaitLocked() time.Duration { + base := a.interval + if base < time.Minute { + base = 30 * time.Minute + } + maxSec := int64(a.jitter / time.Second) + if maxSec <= 0 { + return base + } + return base + time.Duration(rand.Int64N(maxSec+1))*time.Second +} + +func hasData(s cmnet.Snapshot) bool { + return s.Balance != "" || len(s.Resources) > 0 || s.MonthFee != "" +} + +func loadConfig() Config { + cfg := Config{Listen: ":8788", PollInterval: "30m"} + b, err := os.ReadFile("config.json") + if err != nil { + if os.IsNotExist(err) { + buf, _ := json.MarshalIndent(cfg, "", " ") + buf = append(buf, '\n') + _ = os.WriteFile("config.json", buf, 0644) + } + } else if json.Unmarshal(b, &cfg) != nil { + cfg = Config{Listen: ":8788", PollInterval: "30m"} + } + if strings.TrimSpace(cfg.Listen) == "" { + cfg.Listen = ":8788" + } + if strings.TrimSpace(cfg.PollInterval) == "" { + cfg.PollInterval = "30m" + } + if v := strings.TrimSpace(os.Getenv("CMNET_LISTEN")); v != "" { + cfg.Listen = v + } + if v := strings.TrimSpace(os.Getenv("CMNET_POLL")); v != "" { + cfg.PollInterval = v + } + if v := strings.TrimSpace(os.Getenv("CMNET_JITTER")); v != "" { + if n, err := time.ParseDuration(v); err == nil { + cfg.JitterMinutes = int(n / time.Minute) + } + } + if v := strings.TrimSpace(os.Getenv("CMNET_PHONE")); v != "" { + cfg.Phone = v + } + return cfg +} + +func writeFileAtomic(path string, b []byte) error { + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, b, 0600); err != nil { + return err + } + return os.Rename(tmp, path) +} + +func decode(r *http.Request, dest any) error { + defer r.Body.Close() + return json.NewDecoder(io.LimitReader(r.Body, 1<<16)).Decode(dest) +} + +func writeJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(code) + enc := json.NewEncoder(w) + enc.SetEscapeHTML(false) + _ = enc.Encode(v) +} + +func writeErr(w http.ResponseWriter, msg string) { + writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "message": msg}) +} + +func validPhone(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 humanInterval(d time.Duration) string { + if d >= time.Hour && d%time.Hour == 0 { + return fmt.Sprintf("%d 小时", int(d.Hours())) + } + if d >= time.Minute && d%time.Minute == 0 { + return fmt.Sprintf("%d 分钟", int(d.Minutes())) + } + return d.String() +} + +func listenURL(addr string) string { + if strings.HasPrefix(addr, ":") { + return "http://127.0.0.1" + addr + } + return "http://" + addr +} + +func shanghai() *time.Location { + loc, err := time.LoadLocation("Asia/Shanghai") + if err != nil { + return time.FixedZone("CST", 8*3600) + } + return loc +} + +func newDeviceID() string { + var a, b [16]byte + _, _ = crand.Read(a[:]) + _, _ = crand.Read(b[:]) + return hex.EncodeToString(a[:]) + "_" + hex.EncodeToString(b[:]) +} + +func cmnetProvince(code string) string { + return cmnet.ProvinceName(code) +} diff --git a/web/favicon.ico b/web/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..46a145f0c26029e7089c548fbe38cb7b222c800b GIT binary patch literal 1150 zcma))Jx;_h6okEEB?^ROQP6HmDzw~Sa|4bLI?5a&LV|+d3q%2YQH`e)(4hzLWVq1xT9+|HwHMIf zaS30jj~VQ3WuOzseE8evhofro@%SVRLMtrAlfil9#0=h~&_3(veYv;z@ZgQ;Rg(cW z8JsKLoxWY+_3OLCMm=69Sb^*`gBi%+eD=__@3#l^o*It5pjoOD!3^Yd0)EdM2Mu>0f0J4{504Yl47hP_ zW)J(V)<*Dfe5%v;jTv4%et@SF;PBFK{f^aVfk%&yIm%GeQ#)bDJ54dpfd}m%^a6KX z33xlL5m0P4}?9e AkpKVy literal 0 HcmV?d00001 diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..6cdfec3 --- /dev/null +++ b/web/index.html @@ -0,0 +1,826 @@ + + + + + + 移动账户 + + + + + +
+
+

移动账户

+ +
+ + + + +
+

登录

+
+ +
+ + +
+

+ +
+
+ + + + + + + +
+ + +