From 92b5621a51be7a726c62529e1975643802cab4bf Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 12 Oct 2026 18:20:48 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8F=90=E4=BA=A4=E5=B9=BF=E7=94=B5?= =?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 | 6 + README.md | 62 ++++ config.example.json | 5 + go.mod | 12 + go.sum | 10 + internal/cbn/client.go | 571 +++++++++++++++++++++++++++++++ internal/cbn/crypto.go | 184 ++++++++++ internal/cbn/format.go | 425 +++++++++++++++++++++++ internal/cbn/site.go | 162 +++++++++ internal/cbn/waf.go | 112 ++++++ main.go | 692 +++++++++++++++++++++++++++++++++++++ web/index.html | 757 +++++++++++++++++++++++++++++++++++++++++ 12 files changed, 2998 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 config.example.json create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/cbn/client.go create mode 100644 internal/cbn/crypto.go create mode 100644 internal/cbn/format.go create mode 100644 internal/cbn/site.go create mode 100644 internal/cbn/waf.go create mode 100644 main.go create mode 100644 web/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..19a316e --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +data/ +config.json +*.exe +*.chlz +*.zip +Temp/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..b8c977e --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +# 广电账户 + +给自己的中国广电号码看余额、当月话费、流量和语音。页面只读,登录后按设定间隔自动刷新。适合号码插在不能收短信的设备上:会话还在就直接看;过期后把卡插回手机收验证码,在这个页面完成登录。 + +页面没有访问口令,只放在自己的机器上。 + +## 使用 + +在程序目录放 `config.json`,然后运行编译好的程序,浏览器打开它监听的地址。 + +```json +{ + "listen": ":8787", + "pollInterval": "30m", + "phone": "" +} +``` + +| 字段 | 作用 | +| --- | --- | +| `listen` | 监听地址,默认 `:8787` | +| `pollInterval` | 登录后的刷新间隔,最短 1 分钟,例如 `30m`、`1h` | +| `phone` | 可选。写上后登录页会预先填好号码 | + +环境变量 `CBN_LISTEN`、`CBN_POLL`、`CBN_PHONE` 会覆盖同名字段。 + +登录页输入号码。如果这个号码上次的会话还在,点登录会直接进入主页并开始倒计时。会话失效后才出现图形验证码和短信验证码。主页右上角「更多」里可以改刷新间隔、立刻刷新,或退出。退出只回到登录页,不向运营商注销,也不再自动刷新,让会话自己过期。运营商判定会话失效后,页面会回到登录页并提示重新登录。 + +会话、Cookie 和站点参数写在程序目录的 `data/`。不要把这个目录交给别人。 + +## 编译 + +需要 Go 1.26 或更高。 + +```bash +go build -trimpath -ldflags="-s -w" -o cbn-dashboard . +``` + +交叉编译到 Linux: + +```bash +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o cbn-dashboard . +``` + +把二进制和 `config.json` 放在同一目录运行。程序会在该目录创建 `data/`。 + +## 流程 + +```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..c69ce2b --- /dev/null +++ b/config.example.json @@ -0,0 +1,5 @@ +{ + "listen": ":8787", + "pollInterval": "30m", + "phone": "" +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..444bd3c --- /dev/null +++ b/go.mod @@ -0,0 +1,12 @@ +module cbnsmsinfo + +go 1.26.0 + +require github.com/dop251/goja v0.0.0-20261011204819-0c9fae1b959d + +require ( + github.com/dlclark/regexp2/v2 v2.8.1 // indirect + github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect + github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect + golang.org/x/text v0.43.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..9b84086 --- /dev/null +++ b/go.sum @@ -0,0 +1,10 @@ +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/dop251/goja v0.0.0-20261011204819-0c9fae1b959d h1:ONwCIvg9kcijZYa0B9SN/Fo/v7K0UW92HE5oyt3pFvo= +github.com/dop251/goja v0.0.0-20261011204819-0c9fae1b959d/go.mod h1:Cp9NYOLrEKg/ypIRkUWYXWLuKAyyFGkDmGeJ95Sw0zI= +github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU= +github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= +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= +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= diff --git a/internal/cbn/client.go b/internal/cbn/client.go new file mode 100644 index 0000000..d6bb018 --- /dev/null +++ b/internal/cbn/client.go @@ -0,0 +1,571 @@ +package cbn + +import ( + "bytes" + "context" + "crypto/rsa" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/http/cookiejar" + "net/url" + "strings" + "sync" + "time" +) + +const ( + origin = "https://www.10099.com.cn" + basePath = "/contact-web" + loginReferer = origin + "/login.html" + homeReferer = origin + "/personal-center-number-order.html" + 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" + siteCachePath = "data/site.json" + + PathBalance = "/api/busi/qryBalanceFee" + PathBill = "/api/busi/qryBillInfo" + PathResource = "/api/busi/qryUserRes" + PathSubscribe = "/api/busi/qrySubscribeBusiness" +) + +var ErrNeedLogin = errors.New("会话已失效") + +type APIError struct { + Status string + Message string +} + +func (e *APIError) Error() string { + if e.Message != "" { + return e.Message + } + if e.Status != "" { + return e.Status + } + return "请求失败" +} + +type Result struct { + Status string + Message string + Data json.RawMessage +} + +type Cookie struct { + Name string `json:"name"` + Value string `json:"value"` +} + +type LoginResult struct { + SessionID string + Phone string + Prov string + City string +} + +type Client struct { + mu sync.Mutex + http *http.Client + jar *cookiejar.Jar + profile *siteProfile +} + +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, + }, + } +} + +func (c *Client) ExportCookies() []Cookie { + c.mu.Lock() + defer c.mu.Unlock() + return c.exportLocked() +} + +func (c *Client) ImportCookies(list []Cookie) { + c.mu.Lock() + defer c.mu.Unlock() + u, _ := url.Parse(origin + "/") + cs := make([]*http.Cookie, 0, len(list)) + for _, item := range list { + if item.Name == "" { + continue + } + cs = append(cs, &http.Cookie{Name: item.Name, Value: item.Value, Path: "/"}) + } + c.jar.SetCookies(u, cs) +} + +func (c *Client) Reset() { + c.mu.Lock() + defer c.mu.Unlock() + c.resetLocked() +} + +func (c *Client) Prepare(ctx context.Context) error { + c.mu.Lock() + defer c.mu.Unlock() + return c.ensureProfile(ctx, false) +} + +func (c *Client) Captcha(ctx context.Context) ([]byte, string, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureProfile(ctx, false); err != nil { + return nil, "", err + } + body, ctype, err := c.get(ctx, "/api/login/getImageCheckCode", loginReferer, "*/*") + if err != nil { + return nil, "", err + } + if !strings.Contains(strings.ToLower(ctype), "image/") && !isImage(body) { + snippet := strings.TrimSpace(string(body)) + if len(snippet) > 160 { + snippet = snippet[:160] + } + if ctype == "" { + ctype = "unknown" + } + return nil, "", fmt.Errorf("没有拿到图形验证码(%s)%s", ctype, snippet) + } + if ctype == "" || !strings.Contains(strings.ToLower(ctype), "image/") { + ctype = sniffImage(body) + } + return body, ctype, nil +} + +func isImage(body []byte) bool { + if len(body) >= 3 && body[0] == 0xff && body[1] == 0xd8 && body[2] == 0xff { + return true + } + if len(body) >= 8 && string(body[:8]) == "\x89PNG\r\n\x1a\n" { + return true + } + if len(body) >= 6 && (string(body[:6]) == "GIF87a" || string(body[:6]) == "GIF89a") { + return true + } + return false +} + +func sniffImage(body []byte) string { + if len(body) >= 8 && string(body[:8]) == "\x89PNG\r\n\x1a\n" { + return "image/png" + } + if len(body) >= 6 && (string(body[:6]) == "GIF87a" || string(body[:6]) == "GIF89a") { + return "image/gif" + } + return "image/jpeg" +} + +func (c *Client) SendSMS(ctx context.Context, phone string) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureProfile(ctx, false); err != nil { + return "", err + } + res, err := c.post(ctx, "/api/login/getVerifyCode", map[string]any{ + "recieveNum": phone, + "channelId": c.channelID(), + "type": 5, + }, loginReferer) + if err != nil { + return "", err + } + ok, desc := innerOK(res.Data) + if !ok { + return "", errors.New(desc) + } + if desc == "" { + desc = "短信验证码已发送" + } + return desc, nil +} + +func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode string) (LoginResult, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureProfile(ctx, false); err != nil { + return LoginResult{}, err + } + res, err := c.post(ctx, "/api/login/gwLogin", map[string]any{ + "channelId": c.channelID(), + "loginPhone": phone, + "loginPassWord": smsCode, + "loginType": "5", + "channelType": "1", + "imageCheckCode": imageCode, + }, loginReferer) + if err != nil { + return LoginResult{}, err + } + var data struct { + SessionID string `json:"sessionId"` + LoginPhone string `json:"loginPhone"` + PhoneInfo struct { + MgmtProvName string `json:"mgmtProvName"` + MgmtDistrictName string `json:"mgmtDistrictName"` + AccessNumber string `json:"accessNumber"` + } `json:"phoneInfo"` + } + if err := json.Unmarshal(res.Data, &data); err != nil { + return LoginResult{}, errors.New("登录结果无法解析") + } + if data.SessionID == "" { + return LoginResult{}, errors.New("登录未返回会话") + } + gotPhone := data.LoginPhone + if gotPhone == "" { + gotPhone = data.PhoneInfo.AccessNumber + } + if gotPhone == "" { + gotPhone = phone + } + return LoginResult{ + SessionID: data.SessionID, + Phone: gotPhone, + Prov: data.PhoneInfo.MgmtProvName, + City: data.PhoneInfo.MgmtDistrictName, + }, nil +} + +func (c *Client) Logout(ctx context.Context, sessionID string) { + c.mu.Lock() + defer c.mu.Unlock() + if sessionID != "" { + u := origin + basePath + "/api/login/logOut?sessionId=" + url.QueryEscape(sessionID) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err == nil { + c.decorate(req, loginReferer, "") + _, _, _ = c.send(req, nil) + } + } + c.resetLocked() +} + +func (c *Client) Query(ctx context.Context, path, phone, sessionID string) (json.RawMessage, error) { + c.mu.Lock() + defer c.mu.Unlock() + if err := c.ensureProfile(ctx, false); err != nil { + return nil, err + } + res, err := c.post(ctx, path, map[string]any{ + "sessionId": sessionID, + "channelId": c.profile.ChannelID, + "accessNum": phone, + }, homeReferer) + if err != nil { + return nil, err + } + return res.Data, nil +} + +func (c *Client) channelID() string { + if c.profile == nil { + return "" + } + return c.profile.ChannelID +} + +func (c *Client) post(ctx context.Context, path string, payload map[string]any, referer string) (*Result, error) { + if err := c.ensureProfile(ctx, false); err != nil { + return nil, err + } + res, err := c.postOnce(ctx, path, payload, referer) + if errors.Is(err, errDecrypt) { + if err2 := c.ensureProfile(ctx, true); err2 != nil { + return nil, err + } + return c.postOnce(ctx, path, payload, referer) + } + return res, err +} + +func (c *Client) postOnce(ctx context.Context, path string, payload map[string]any, referer string) (*Result, error) { + body := make(map[string]any, len(payload)+2) + for k, v := range payload { + body[k] = v + } + body["v"] = c.profile.Version + body["timestamp"] = time.Now().UnixMilli() + access := accessSign(body) + plain, err := marshalCompact(body) + if err != nil { + return nil, err + } + enc, err := encryptLong(c.profile.Public, encodeURIComponent(string(plain))) + if err != nil { + return nil, err + } + envelope, err := json.Marshal(struct { + Data string `json:"data"` + }{Data: enc}) + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+basePath+path, nil) + if err != nil { + return nil, err + } + c.decorate(req, referer, "application/json, text/javascript, */*; q=0.01") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Requested-With", "XMLHttpRequest") + req.Header.Set("Access", access) + buf, _, err := c.send(req, envelope) + if err != nil { + return nil, err + } + return parseBody(buf, c.profile.Private) +} + +func (c *Client) get(ctx context.Context, path, referer, accept string) ([]byte, string, error) { + return c.getURL(ctx, origin+basePath+path, referer, accept) +} + +func (c *Client) getURL(ctx context.Context, rawURL, referer, accept string) ([]byte, string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, "", err + } + c.decorate(req, referer, accept) + return c.send(req, nil) +} + +func (c *Client) send(req *http.Request, body []byte) ([]byte, string, error) { + var last []byte + var lastType string + for attempt := 0; attempt < 2; attempt++ { + r := req.Clone(req.Context()) + if body != nil { + r.Body = io.NopCloser(bytes.NewReader(body)) + r.ContentLength = int64(len(body)) + } + resp, err := c.http.Do(r) + if err != nil { + return nil, "", err + } + buf, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + resp.Body.Close() + if err != nil { + return nil, "", err + } + last, lastType = buf, resp.Header.Get("Content-Type") + if attempt == 0 && isWAF(buf) { + token, err := solveACW(string(buf)) + if err != nil { + return nil, "", err + } + c.setCookie("acw_sc__v2", token) + continue + } + if resp.StatusCode >= 400 && !bytes.Contains(buf, []byte(`"status"`)) && !isImage(buf) { + return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode) + } + return buf, lastType, nil + } + if isWAF(last) { + return nil, "", errors.New("网站校验没有通过") + } + return last, lastType, nil +} + +func (c *Client) ensureProfile(ctx context.Context, force bool) error { + if !force && c.profile != nil && time.Since(c.profile.FetchedAt) < siteCacheTTL { + return nil + } + p, err := c.fetchProfile(ctx) + if err != nil { + if c.profile != nil && !force { + return nil + } + if cached, err2 := loadSiteCache(siteCachePath); err2 == nil { + c.profile = cached + log.Printf("网页参数暂时拉不下来,继续用 %s 的缓存", cached.FetchedAt.Format("2006-01-02 15:04")) + return nil + } + return err + } + changed := c.profile == nil || c.profile.PublicB64 != p.PublicB64 || c.profile.Version != p.Version || c.profile.ChannelID != p.ChannelID + c.profile = p + if err := saveSiteCache(siteCachePath, p); err != nil { + log.Printf("页面参数已读取,但缓存没写成: %v", err) + } + if changed { + log.Printf("已同步页面参数 %s %s", p.ChannelID, p.Version) + } + return nil +} + +func (c *Client) fetchProfile(ctx context.Context) (*siteProfile, error) { + page, _, err := c.getURL(ctx, loginReferer, loginReferer, "text/html,application/xhtml+xml") + if err != nil { + return nil, err + } + if isWAF(page) { + return nil, errors.New("登录页被校验拦住了") + } + urls := scriptURLs(string(page)) + if len(urls) == 0 { + return nil, errors.New("登录页里没有脚本地址") + } + var last error + for _, ref := range urls { + body, _, err := c.getURL(ctx, resolveURL(ref), loginReferer, "*/*") + if err != nil { + last = err + continue + } + if isWAF(body) || !bytes.Contains(body, []byte("MII")) { + continue + } + p, err := parseSiteJS(string(body)) + if err == nil { + return p, nil + } + last = err + if strings.Contains(ref, "common-") { + break + } + } + if last != nil { + return nil, last + } + return nil, errors.New("没有在页面脚本里找到加密参数") +} + +func (c *Client) setCookie(name, value string) { + u, _ := url.Parse(origin + "/") + c.jar.SetCookies(u, []*http.Cookie{{Name: name, Value: value, Path: "/"}}) +} + +func isWAF(body []byte) bool { + return bytes.Contains(body, []byte("renderData")) && bytes.Contains(body, []byte("acw_sc__v2")) +} + +func (c *Client) decorate(req *http.Request, referer, accept string) { + req.Header.Set("User-Agent", userAgent) + req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8") + req.Header.Set("Referer", referer) + if accept != "" { + req.Header.Set("Accept", accept) + } + req.Header.Set("Sec-Fetch-Site", "same-origin") + req.Header.Set("Sec-Fetch-Mode", "cors") + req.Header.Set("Sec-Fetch-Dest", "empty") +} + +func (c *Client) exportLocked() []Cookie { + u, _ := url.Parse(origin + "/") + got := c.jar.Cookies(u) + out := make([]Cookie, 0, len(got)) + for _, ck := range got { + out = append(out, Cookie{Name: ck.Name, Value: ck.Value}) + } + return out +} + +func (c *Client) resetLocked() { + jar, err := cookiejar.New(nil) + if err != nil { + return + } + c.jar = jar + c.http.Jar = jar +} + +func parseBody(buf []byte, priv *rsa.PrivateKey) (*Result, error) { + buf = bytes.TrimSpace(buf) + if len(buf) == 0 { + return nil, errors.New("网站返回空内容") + } + if buf[0] != '{' { + return nil, errors.New("网站没有返回账户数据") + } + var probe map[string]json.RawMessage + if err := json.Unmarshal(buf, &probe); err != nil { + return nil, errors.New("无法解析网站响应") + } + if len(probe) == 1 { + if raw, ok := probe["data"]; ok { + var s string + if json.Unmarshal(raw, &s) == nil && s != "" { + plain, err := decryptLong(priv, s) + if err != nil { + return nil, errors.New("无法解密网站响应") + } + decoded, err := decodeURIComponent(plain) + if err != nil { + return nil, err + } + buf = bytes.TrimSpace([]byte(decoded)) + } + } + } + var wrap struct { + Status string `json:"status"` + Message string `json:"message"` + Data json.RawMessage `json:"data"` + } + if err := json.Unmarshal(buf, &wrap); err != nil { + return nil, errors.New("无法解析网站响应") + } + res := &Result{Status: wrap.Status, Message: wrap.Message, Data: wrap.Data} + if needLogin(wrap.Status, wrap.Message) { + if res.Message == "" { + res.Message = ErrNeedLogin.Error() + } + return res, ErrNeedLogin + } + if wrap.Status != "000000" { + return res, &APIError{Status: wrap.Status, Message: wrap.Message} + } + return res, nil +} + +func needLogin(status, message string) bool { + if status == "701" { + return true + } + for _, part := range []string{"未登录", "请重新登录", "请重新登陆", "会话失效", "登录超时", "登陆超时"} { + if strings.Contains(message, part) { + return true + } + } + return false +} + +func innerOK(data json.RawMessage) (bool, string) { + var m map[string]any + if err := json.Unmarshal(data, &m); err != nil { + return true, "" + } + code := asString(m["respCode"]) + desc := asString(m["respDesc"]) + if code == "" || code == "0000" || code == "000000" { + return true, desc + } + if desc == "" { + desc = "请求失败" + } + return false, desc +} + +func marshalCompact(v any) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return nil, err + } + return bytes.TrimRight(buf.Bytes(), "\n"), nil +} diff --git a/internal/cbn/crypto.go b/internal/cbn/crypto.go new file mode 100644 index 0000000..fdf6c71 --- /dev/null +++ b/internal/cbn/crypto.go @@ -0,0 +1,184 @@ +package cbn + +import ( + "crypto/md5" + "crypto/rand" + "crypto/rsa" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "math" + "net/url" + "sort" + "strconv" + "strings" +) + +var errDecrypt = errors.New("无法用当前密钥解密") + +func encryptLong(pub *rsa.PublicKey, plain string) (string, error) { + if pub == nil { + return "", errors.New("缺少加密公钥") + } + keyBytes := pub.Size() + maxChunk := keyBytes - 12 + runes := []rune(plain) + var blocks []byte + o, a, s, c := 0, 0, 0, 0 + for f, h := range runes { + add := 1 + switch { + case h > 65535: + add = 4 + case h > 2047: + add = 3 + case h > 127: + add = 2 + } + s += add + if maxChunk < s { + ct, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(string(runes[o:a]))) + if err != nil { + return "", err + } + blocks = append(blocks, ct...) + o = a + s -= c + } else { + a = f + c = s + } + } + ct, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(string(runes[o:]))) + if err != nil { + return "", err + } + blocks = append(blocks, ct...) + return base64.StdEncoding.EncodeToString(blocks), nil +} + +func decryptLong(priv *rsa.PrivateKey, b64 string) (string, error) { + if priv == nil { + return "", errDecrypt + } + raw, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + return "", err + } + k := priv.Size() + if k == 0 || len(raw)%k != 0 { + return "", errDecrypt + } + var out []byte + for i := 0; i < len(raw); i += k { + pt, err := rsa.DecryptPKCS1v15(rand.Reader, priv, raw[i:i+k]) + if err != nil { + return "", errDecrypt + } + out = append(out, pt...) + } + return string(out), nil +} + +func encodeURIComponent(s string) string { + var b strings.Builder + b.Grow(len(s)) + for i := 0; i < len(s); i++ { + c := s[i] + if isURIUnreserved(c) { + b.WriteByte(c) + continue + } + fmt.Fprintf(&b, "%%%02X", c) + } + return b.String() +} + +func isURIUnreserved(c byte) bool { + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') { + return true + } + switch c { + case '-', '_', '.', '!', '~', '*', '\'', '(', ')': + return true + default: + return false + } +} + +func decodeURIComponent(s string) (string, error) { + return url.PathUnescape(s) +} + +func accessSign(payload map[string]any) string { + sum := md5.Sum([]byte(canonical(payload, false))) + return hex.EncodeToString(sum[:]) +} + +func canonical(v any, nested bool) string { + m, ok := asMap(v) + if !ok { + return "" + } + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, k := range keys { + val := m[k] + if child, ok := asMap(val); ok && !nested { + parts = append(parts, k+"="+canonical(child, true)) + continue + } + if s, ok := primitive(val); ok { + parts = append(parts, k+"="+s) + } + } + return strings.Join(parts, "&") +} + +func asMap(v any) (map[string]any, bool) { + m, ok := v.(map[string]any) + return m, ok +} + +func primitive(v any) (string, bool) { + switch t := v.(type) { + case nil: + return "", false + case string: + if t == "" { + return "", false + } + return t, true + case bool: + if t { + return "true", true + } + return "false", true + case int: + return strconv.Itoa(t), true + case int64: + return strconv.FormatInt(t, 10), true + case float64: + if math.IsNaN(t) || math.IsInf(t, 0) { + return "", false + } + if t == math.Trunc(t) && math.Abs(t) < 1e16 { + return strconv.FormatInt(int64(t), 10), true + } + return strconv.FormatFloat(t, 'f', -1, 64), true + case json.Number: + s := t.String() + if s == "" { + return "", false + } + return s, true + default: + return "", false + } +} diff --git a/internal/cbn/format.go b/internal/cbn/format.go new file mode 100644 index 0000000..fb3bc1e --- /dev/null +++ b/internal/cbn/format.go @@ -0,0 +1,425 @@ +package cbn + +import ( + "encoding/json" + "fmt" + "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, prov, city string, balance, bill, resource, subscribe json.RawMessage) Snapshot { + snap := Snapshot{ + Resources: []Resource{}, + Extras: []Extra{}, + Bills: []Bill{}, + } + if sub := beanOf(subscribe); sub != nil { + if phone == "" { + phone = asString(sub["accessNum"]) + } + if opened := asString(sub["openDate"]); len(opened) >= 10 { + snap.OpenedAt = opened[:10] + } + if offers, ok := sub["offerList"].([]any); ok { + for _, item := range offers { + m, ok := item.(map[string]any) + if !ok { + continue + } + if asString(m["isMain"]) == "1" { + snap.PackageName = asString(m["offerName"]) + break + } + } + } + } + if res := beanOf(resource); res != nil { + if list, ok := res["userResList"].([]any); ok { + for _, item := range list { + m, ok := item.(map[string]any) + if !ok { + continue + } + snap.Resources = append(snap.Resources, formatResource(m)) + } + } + if list, ok := res["userExtResList"].([]any); ok { + for _, item := range list { + m, ok := item.(map[string]any) + if !ok { + continue + } + used := getFloatNumber(jsNumber(atof(asString(m["extTotalValue"])) / 1024 / 1024)) + fee := toFixed2(atof(asString(m["extDiscntFee"])) / 100) + snap.Extras = append(snap.Extras, Extra{Name: "套外国内流量", Used: used, Fee: fee}) + } + } + } + if bal := beanOf(balance); bal != nil { + snap.Cycle = formatCycle(asString(bal["curCycleId"])) + spay := asString(bal["spayFee"]) + if spay != "" && spay != "0" { + snap.Balance = "-" + fenToYuan(spay) + snap.BalanceNegative = true + } else if asString(bal["balance"]) != "" { + snap.Balance = fenToYuan(asString(bal["balance"])) + } + if asString(bal["currealFee"]) != "" { + snap.MonthFee = fenToYuan(asString(bal["currealFee"])) + } + } + snap.Bills = formatBills(bill) + snap.DataTotal, snap.DataUsed, snap.DataRemain, snap.DataExtra = SummarizeTraffic(snap.Resources, snap.Extras) + snap.VoiceTotal, snap.VoiceRemain = SummarizeVoice(snap.Resources) + snap.Phone = strings.TrimSpace(phone) + snap.PhoneMasked = MaskPhone(snap.Phone) + snap.Region = joinRegion(prov, city) + if snap.PackageName == "" { + for _, item := range snap.Resources { + if item.Name != "" { + snap.PackageName = item.Name + break + } + } + } + return snap +} + +func SummarizeTraffic(resources []Resource, extras []Extra) (total, used, remain, extra string) { + var totalN, usedN, remainN, extraN float64 + var hasData bool + for _, item := range resources { + if item.Unit != "G" { + continue + } + hasData = true + totalN += atof(item.Total) + usedN += atof(item.Used) + remainN += atof(item.Remain) + } + for _, item := range extras { + extraN += atof(item.Used) + } + if !hasData && len(extras) == 0 { + return "", "", "", "" + } + return getFloatNumber(toFixed2(totalN)), getFloatNumber(toFixed2(usedN)), getFloatNumber(toFixed2(remainN)), getFloatNumber(toFixed2(extraN)) +} + +func SummarizeVoice(resources []Resource) (total, remain string) { + var totalN, remainN float64 + var has bool + for _, item := range resources { + if item.Unit != "分钟" { + continue + } + has = true + totalN += atof(item.Total) + remainN += atof(item.Remain) + } + if !has { + return "", "" + } + return formatCount(totalN), formatCount(remainN) +} + +func formatCount(n float64) string { + if n == math.Trunc(n) { + return strconv.FormatInt(int64(n), 10) + } + return getFloatNumber(toFixed2(n)) +} + +func formatResource(m map[string]any) Resource { + busi := asString(m["busiType"]) + name := asString(m["discntName"]) + high := asString(m["highFee"]) + remainRaw := asString(m["balance"]) + addup := asString(m["addupValue"]) + if addup == "" { + addup = "0" + } + item := Resource{Name: name} + if busi == "5" { + item.Unit = "G" + item.Total = getFloatNumber(toFixed2(atof(high) / 1024 / 1024)) + item.Remain = getFloatNumber(toFixed2(atof(remainRaw) / 1024 / 1024)) + item.Used = subFloatToInt(item.Total, item.Remain) + } else { + if busi == "1" { + item.Unit = "分钟" + } else { + item.Unit = "条" + } + item.Total = zero(high) + item.Remain = zero(remainRaw) + item.Used = zero(addup) + } + item.Percent = percent(item.Used, item.Total) + return item +} + +func formatBills(raw json.RawMessage) []Bill { + root := object(raw) + if root == nil { + return []Bill{} + } + list, ok := root["contentList"].([]any) + if !ok { + if data, ok := root["data"].(map[string]any); ok { + list, _ = data["contentList"].([]any) + } + } + if len(list) == 0 { + return []Bill{} + } + out := make([]Bill, 0, len(list)) + for _, item := range list { + m, ok := item.(map[string]any) + if !ok { + continue + } + group := Bill{Title: asString(m["title"]), Items: []BillItem{}} + if rows, ok := m["list"].([]any); ok { + for _, row := range rows { + rm, ok := row.(map[string]any) + if !ok { + continue + } + group.Items = append(group.Items, BillItem{Name: asString(rm["name"]), Value: asString(rm["value"])}) + } + } + out = append(out, group) + } + return out +} + +func MaskPhone(phone string) string { + if len(phone) == 11 { + return phone[:3] + "****" + phone[7:] + } + return phone +} + +func joinRegion(prov, city string) string { + prov = strings.TrimSpace(prov) + city = strings.TrimSpace(city) + switch { + case prov != "" && city != "": + return prov + " " + city + case prov != "": + return prov + default: + return city + } +} + +func formatCycle(v string) string { + if len(v) == 6 { + return v[:4] + "-" + v[4:] + } + return v +} + +func fenToYuan(s string) string { + neg := strings.HasPrefix(s, "-") + if neg { + s = strings.TrimPrefix(s, "-") + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return getFloatNumber(toFixed2(atof(s) / 100)) + } + sign := "" + if neg { + sign = "-" + } + return fmt.Sprintf("%s%d.%02d", sign, n/100, n%100) +} + +func beanOf(raw json.RawMessage) map[string]any { + root := object(raw) + if root == nil { + return nil + } + if bean, ok := root["intfResultBean"].(map[string]any); ok { + return bean + } + if data, ok := root["data"].(map[string]any); ok { + if bean, ok := data["intfResultBean"].(map[string]any); ok { + return bean + } + } + return nil +} + +func object(raw json.RawMessage) map[string]any { + if len(bytesTrim(raw)) == 0 { + return nil + } + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil { + return nil + } + return m +} + +func bytesTrim(raw json.RawMessage) []byte { + return []byte(strings.TrimSpace(string(raw))) +} + +func asString(v any) string { + switch t := v.(type) { + case string: + return t + case float64: + if math.IsNaN(t) || math.IsInf(t, 0) { + return "" + } + if t == math.Trunc(t) && math.Abs(t) < 1e16 { + return strconv.FormatInt(int64(t), 10) + } + return strconv.FormatFloat(t, 'f', -1, 64) + case json.Number: + return t.String() + default: + return "" + } +} + +func atof(s string) float64 { + f, err := strconv.ParseFloat(strings.TrimSpace(s), 64) + if err != nil { + return 0 + } + return f +} + +func zero(s string) string { + if strings.TrimSpace(s) == "" { + return "0" + } + return s +} + +func jsNumber(f float64) string { + return strconv.FormatFloat(f, 'f', -1, 64) +} + +func toFixed2(f float64) string { + return strconv.FormatFloat(f, 'f', 2, 64) +} + +func getFloatNumber(v string) string { + var b strings.Builder + for _, r := range v { + if (r >= '0' && r <= '9') || r == '.' || r == '|' { + b.WriteRune(r) + } + } + t := strings.TrimLeft(b.String(), "0") + if !strings.Contains(t, ".") { + t += ".00" + } + if strings.HasPrefix(t, ".") { + t = "0" + t + } + t += "00" + for i := 0; i < len(t); i++ { + if t[i] != '.' || i+3 > len(t) { + continue + } + j := i + for j > 0 && t[j-1] >= '0' && t[j-1] <= '9' { + j-- + } + if j < i { + return t[j : i+3] + } + } + return "0.00" +} + +func subFloatToInt(a, b string) string { + ra := decimalPlaces(a) + rb := decimalPlaces(b) + r := ra + if rb > r { + r = rb + } + scale := math.Pow10(r) + af := atof(a) + bf := atof(b) + return strconv.FormatFloat((af*scale-bf*scale)/scale, 'f', r, 64) +} + +func decimalPlaces(s string) int { + i := strings.IndexByte(s, '.') + if i < 0 { + return 0 + } + return len(s) - i - 1 +} + +func percent(used, total string) float64 { + u := atof(used) + t := atof(total) + if t <= 0 { + return 0 + } + p := u / t * 100 + if p < 0 { + return 0 + } + if p > 100 { + return 100 + } + return math.Round(p*10) / 10 +} diff --git a/internal/cbn/site.go b/internal/cbn/site.go new file mode 100644 index 0000000..d7efeba --- /dev/null +++ b/internal/cbn/site.go @@ -0,0 +1,162 @@ +package cbn + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/json" + "errors" + "os" + "regexp" + "strings" + "time" +) + +const siteCacheTTL = 6 * time.Hour + +var ( + keyRE = regexp.MustCompile(`MII[A-Za-z0-9+/]{200,}={0,2}`) + versionRE = regexp.MustCompile(`\d+\.\d+\.\d+\.\d+_[A-Za-z0-9]+`) + channelRE = regexp.MustCompile(`channelId:"(cd_[0-9_]+)"`) + scriptRE = regexp.MustCompile(`(?i)src=["']([^"']+\.js)["']`) +) + +type siteProfile struct { + ChannelID string + Version string + PublicB64 string + PrivateB64 string + Public *rsa.PublicKey + Private *rsa.PrivateKey + FetchedAt time.Time +} + +type siteFile struct { + ChannelID string `json:"channelId"` + Version string `json:"version"` + PublicB64 string `json:"publicKey"` + PrivateB64 string `json:"privateKey"` + FetchedAt time.Time `json:"fetchedAt"` +} + +func parseSiteJS(src string) (*siteProfile, error) { + var pub *rsa.PublicKey + var priv *rsa.PrivateKey + var pubB64, privB64 string + for _, b64 := range keyRE.FindAllString(src, -1) { + der, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + continue + } + if pub == nil { + if parsed, err := x509.ParsePKIXPublicKey(der); err == nil { + if rk, ok := parsed.(*rsa.PublicKey); ok { + pub = rk + pubB64 = b64 + continue + } + } + } + if priv == nil { + if parsed, err := x509.ParsePKCS8PrivateKey(der); err == nil { + if rk, ok := parsed.(*rsa.PrivateKey); ok { + priv = rk + privB64 = b64 + continue + } + } + if rk, err := x509.ParsePKCS1PrivateKey(der); err == nil { + priv = rk + privB64 = b64 + } + } + } + if pub == nil || priv == nil { + return nil, errors.New("页面脚本里没有找到加密密钥") + } + ver := versionRE.FindString(src) + ch := channelRE.FindStringSubmatch(src) + if ver == "" || ch == nil { + return nil, errors.New("页面脚本里没有找到渠道或版本号") + } + return &siteProfile{ + ChannelID: ch[1], + Version: ver, + PublicB64: pubB64, + PrivateB64: privB64, + Public: pub, + Private: priv, + FetchedAt: time.Now(), + }, nil +} + +func scriptURLs(html string) []string { + matches := scriptRE.FindAllStringSubmatch(html, -1) + var common, rest []string + seen := map[string]bool{} + for _, m := range matches { + u := m[1] + if seen[u] { + continue + } + seen[u] = true + if strings.Contains(u, "common-") { + common = append(common, u) + continue + } + rest = append(rest, u) + } + return append(common, rest...) +} + +func resolveURL(ref string) string { + if strings.HasPrefix(ref, "https://") || strings.HasPrefix(ref, "http://") { + return ref + } + if strings.HasPrefix(ref, "//") { + return "https:" + ref + } + if strings.HasPrefix(ref, "/") { + return origin + ref + } + return origin + "/" + ref +} + +func loadSiteCache(path string) (*siteProfile, error) { + b, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var file siteFile + if err := json.Unmarshal(b, &file); err != nil { + return nil, err + } + p, err := parseSiteJS(`channelId:"` + file.ChannelID + `" v="` + file.Version + `" "` + file.PublicB64 + `" "` + file.PrivateB64 + `"`) + if err != nil { + return nil, err + } + p.FetchedAt = file.FetchedAt + return p, nil +} + +func saveSiteCache(path string, p *siteProfile) error { + buf, err := json.MarshalIndent(siteFile{ + ChannelID: p.ChannelID, + Version: p.Version, + PublicB64: p.PublicB64, + PrivateB64: p.PrivateB64, + FetchedAt: p.FetchedAt, + }, "", " ") + if err != nil { + return err + } + buf = append(buf, '\n') + if err := os.MkdirAll("data", 0755); err != nil { + return err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, buf, 0600); err != nil { + return err + } + return os.Rename(tmp, path) +} diff --git a/internal/cbn/waf.go b/internal/cbn/waf.go new file mode 100644 index 0000000..edd0004 --- /dev/null +++ b/internal/cbn/waf.go @@ -0,0 +1,112 @@ +package cbn + +import ( + "errors" + "strings" + "time" + + "github.com/dop251/goja" +) + +// 只在返回人机校验页时执行官网自己的脚本,平时的查询走 Go,不常驻解释器。 +func solveACW(html string) (string, error) { + parts := extractScripts(html) + if len(parts) < 2 { + return "", errors.New("校验脚本不完整") + } + render := extractTextarea(html, "renderData") + if render == "" { + return "", errors.New("校验页面缺少参数") + } + vm := goja.New() + timer := time.AfterFunc(3*time.Second, func() { vm.Interrupt("timeout") }) + defer timer.Stop() + if err := vm.Set("RENDER_HTML", render); err != nil { + return "", err + } + if err := vm.Set("UA", userAgent); err != nil { + return "", err + } + if _, err := vm.RunString(wafPrelude); err != nil { + return "", err + } + if _, err := vm.RunString(parts[0]); err != nil { + return "", errors.New("校验脚本无法执行") + } + if _, err := vm.RunString(`window.arg1 = arg1; var __old = reload; reload = function(v){ __token = String(v); try { __old(v); } catch (e) {} }; window.reload = reload;`); err != nil { + return "", errors.New("校验脚本无法执行") + } + if _, err := vm.RunString(parts[1]); err != nil { + return "", errors.New("校验计算失败") + } + v := vm.Get("__token") + if v == nil || goja.IsUndefined(v) || goja.IsNull(v) { + return "", errors.New("校验脚本没有给出凭证") + } + token := v.String() + if token == "" || token == "undefined" || !strings.Contains(token, "-") { + return "", errors.New("校验脚本没有给出凭证") + } + return token, nil +} + +const wafPrelude = ` +var __token = ""; +var document = { + referrer: "https://www.10099.com.cn/login.html", + getElementById: function() { return { innerHTML: RENDER_HTML }; }, + location: { href: "https://www.10099.com.cn/login.html", reload: function() {} } +}; +var location = document.location; +var navigator = { + userAgent: UA, + webdriver: false, + language: "zh-CN", + languages: ["zh-CN", "zh"], + platform: "Win32", + hardwareConcurrency: 8, + plugins: { length: 0 } +}; +var window = { document: document, location: location, navigator: navigator }; +` + +func extractScripts(html string) []string { + var out []string + rest := html + for { + i := strings.Index(rest, "") + k := strings.Index(rest, "") + if j < 0 || k < 0 || k < j { + break + } + body := strings.TrimSpace(rest[j+1 : k]) + if body != "" { + out = append(out, body) + } + rest = rest[k+9:] + } + return out +} + +func extractTextarea(html, id string) string { + marker := `id="` + id + `"` + i := strings.Index(html, marker) + if i < 0 { + marker = `id='` + id + `'` + i = strings.Index(html, marker) + } + if i < 0 { + return "" + } + gt := strings.Index(html[i:], ">") + end := strings.Index(html[i:], "") + if gt < 0 || end < 0 || end < gt { + return "" + } + return html[i+gt+1 : i+end] +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..86c168e --- /dev/null +++ b/main.go @@ -0,0 +1,692 @@ +package main + +import ( + "context" + _ "embed" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "os" + "os/signal" + "path/filepath" + "strings" + "sync" + "syscall" + "time" + _ "time/tzdata" + + "cbnsmsinfo/internal/cbn" +) + +//go:embed web/index.html +var indexPage []byte + +const statePath = "data/state.json" + +type Config struct { + Listen string `json:"listen"` + PollInterval string `json:"pollInterval"` + Phone string `json:"phone"` +} + +type savedState struct { + Phone string `json:"phone"` + SessionID string `json:"sessionId"` + Prov string `json:"prov"` + City string `json:"city"` + LoggedIn bool `json:"loggedIn"` + Cookies []cbn.Cookie `json:"cookies"` + Snapshot cbn.Snapshot `json:"snapshot"` + RefreshedAt time.Time `json:"refreshedAt"` + LastError string `json:"lastError"` + Stale bool `json:"stale"` + PollMinutes int `json:"pollMinutes"` +} + +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"` + SecondsLeft int `json:"secondsLeft"` + RefreshedAt string `json:"refreshedAt,omitempty"` + NextRefreshAt string `json:"nextRefreshAt,omitempty"` + Error string `json:"error,omitempty"` + Stale bool `json:"stale"` + HasData bool `json:"hasData"` + cbn.Snapshot +} + +type App struct { + client *cbn.Client + interval time.Duration + pollText string + cfgPhone string + kick chan struct{} + + mu sync.Mutex + phone string + sessionID string + prov string + city string + loggedIn bool + snap cbn.Snapshot + 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 + } + app := newApp(cbn.New(), strings.TrimSpace(cfg.Phone), interval) + 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 /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 *cbn.Client, phone string, interval time.Duration) *App { + return &App{ + client: client, + interval: interval, + pollText: humanInterval(interval), + cfgPhone: phone, + kick: make(chan struct{}, 1), + snap: cbn.Snapshot{ + Resources: []cbn.Resource{}, + Extras: []cbn.Extra{}, + Bills: []cbn.Bill{}, + }, + } +} + +func (a *App) loop(ctx context.Context) { + timer := time.NewTimer(a.currentInterval()) + stopTimer(timer) + if a.isLoggedIn() { + a.stampNext() + a.refresh() + timer.Reset(a.currentInterval()) + } + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-a.kick: + stopTimer(timer) + if a.isLoggedIn() { + timer.Reset(a.currentInterval()) + } + case <-timer.C: + if !a.isLoggedIn() { + continue + } + a.stampNext() + a.refresh() + if a.isLoggedIn() { + timer.Reset(a.currentInterval()) + } + } + } +} + +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() { + a.mu.Lock() + if !a.loggedIn || a.sessionID == "" || a.phone == "" { + a.mu.Unlock() + return + } + if a.refreshing { + a.mu.Unlock() + return + } + a.refreshing = true + phone, sid, prov, city := a.phone, a.sessionID, a.prov, a.city + 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() + + type call struct { + name string + path string + raw *json.RawMessage + } + var balance, bill, resource, subscribe json.RawMessage + calls := []call{ + {"余额", cbn.PathBalance, &balance}, + {"账单", cbn.PathBill, &bill}, + {"余量", cbn.PathResource, &resource}, + {"套餐", cbn.PathSubscribe, &subscribe}, + } + var errs []string + for _, item := range calls { + raw, err := a.client.Query(ctx, item.path, phone, sid) + if errors.Is(err, cbn.ErrNeedLogin) { + a.markLoggedOut("会话已失效,请重新登录") + return + } + if err != nil { + errs = append(errs, item.name+":"+err.Error()) + continue + } + *item.raw = raw + } + + a.mu.Lock() + defer a.mu.Unlock() + if len(errs) > 0 && hasData(a.snap) && balance == nil && bill == nil && resource == nil && subscribe == nil { + a.stale = true + a.lastError = strings.Join(errs, ";") + return + } + if len(errs) > 0 && hasData(a.snap) { + a.stale = true + a.lastError = strings.Join(errs, ";") + return + } + snap := cbn.BuildSnapshot(phone, prov, city, balance, bill, resource, subscribe) + a.snap = snap + a.stale = len(errs) > 0 + a.lastError = strings.Join(errs, ";") + if len(errs) == 0 { + a.refreshedAt = time.Now() + log.Printf("同步完成 %s", snap.PhoneMasked) + } +} + +func (a *App) markLoggedOut(msg string) { + a.client.Reset() + a.mu.Lock() + a.loggedIn = false + a.sessionID = "" + a.snap = emptySnap() + 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() + } + 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"` + } + if err := decode(r, &req); err != nil { + writeErr(w, "请求格式不对") + return + } + phone := strings.TrimSpace(req.Phone) + if !validPhone(phone) { + writeErr(w, "请输入正确的手机号码") + return + } + a.mu.Lock() + a.phone = phone + a.mu.Unlock() + msg, err := a.client.SendSMS(r.Context(), phone) + if err != nil { + writeErr(w, cleanErr(err)) + return + } + 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) { + writeErr(w, "请输入正确的手机号码") + return + } + if image == "" { + writeErr(w, "请输入图形验证码") + return + } + if sms == "" { + writeErr(w, "请输入短信验证码") + return + } + result, err := a.client.Login(r.Context(), phone, image, sms) + if err != nil { + writeErr(w, cleanErr(err)) + return + } + a.mu.Lock() + a.loggedIn = true + a.sessionID = result.SessionID + a.phone = result.Phone + a.prov = result.Prov + a.city = result.City + a.lastError = "" + a.stale = false + a.mu.Unlock() + a.stampNext() + a.wakeLoop() + a.save() + a.refresh() + log.Printf("登录成功 %s", cbn.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.sessionID != "" && 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) setInterval(w http.ResponseWriter, r *http.Request) { + var req struct { + Minutes int `json:"minutes"` + } + if err := decode(r, &req); err != nil || req.Minutes < 1 || req.Minutes > 1440 { + writeErr(w, "间隔需在 1 到 1440 分钟之间") + return + } + a.mu.Lock() + a.interval = time.Duration(req.Minutes) * time.Minute + a.pollText = humanInterval(a.interval) + if a.loggedIn { + a.nextAt = time.Now().Add(a.interval) + } + a.mu.Unlock() + select { + case a.kick <- struct{}{}: + default: + } + a.save() + writeJSON(w, http.StatusOK, a.view()) +} + +func (a *App) currentInterval() time.Duration { + a.mu.Lock() + defer a.mu.Unlock() + if a.interval < time.Minute { + return 30 * time.Minute + } + return a.interval +} + +func (a *App) view() overview { + a.mu.Lock() + defer a.mu.Unlock() + snap := a.snap + if snap.Resources == nil { + snap.Resources = []cbn.Resource{} + } + if snap.Extras == nil { + snap.Extras = []cbn.Extra{} + } + if snap.Bills == nil { + snap.Bills = []cbn.Bill{} + } + if len(snap.Resources) > 0 || len(snap.Extras) > 0 { + snap.DataTotal, snap.DataUsed, snap.DataRemain, snap.DataExtra = cbn.SummarizeTraffic(snap.Resources, snap.Extras) + snap.VoiceTotal, snap.VoiceRemain = cbn.SummarizeVoice(snap.Resources) + } + if !a.loggedIn { + phone := a.phone + snap = emptySnap() + snap.Phone = phone + snap.PhoneMasked = cbn.MaskPhone(phone) + } + out := overview{ + LoggedIn: a.loggedIn, + NeedLogin: !a.loggedIn, + CanResume: !a.loggedIn && a.sessionID != "" && a.phone != "", + Refreshing: a.refreshing, + PollEvery: a.pollText, + PollMinutes: int(a.interval / 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) + out.NextRefreshAt = a.nextAt.In(shanghai()).Format("15:04:05") + } + return out +} + +func emptySnap() cbn.Snapshot { + return cbn.Snapshot{ + Resources: []cbn.Resource{}, + Extras: []cbn.Extra{}, + Bills: []cbn.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.sessionID = st.SessionID + a.prov = st.Prov + a.city = st.City + a.loggedIn = st.LoggedIn && st.SessionID != "" + a.snap = st.Snapshot + 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) + } + a.client.ImportCookies(st.Cookies) + if a.loggedIn { + log.Printf("已恢复会话 %s", cbn.MaskPhone(a.phone)) + } +} + +func (a *App) save() { + a.mu.Lock() + st := savedState{ + Phone: a.phone, + SessionID: a.sessionID, + Prov: a.prov, + City: a.city, + LoggedIn: a.loggedIn, + Snapshot: a.snap, + RefreshedAt: a.refreshedAt, + LastError: a.lastError, + Stale: a.stale, + PollMinutes: int(a.interval / 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.nextAt = time.Now().Add(a.interval) + a.mu.Unlock() +} + +func hasData(s cbn.Snapshot) bool { + return s.Balance != "" || s.PackageName != "" || s.MonthFee != "" || len(s.Resources) > 0 || len(s.Bills) > 0 +} + +func loadConfig() Config { + cfg := Config{Listen: ":8787", PollInterval: "30m"} + b, err := os.ReadFile("config.json") + if err != nil { + if os.IsNotExist(err) { + buf, _ := json.MarshalIndent(cfg, "", " ") + buf = append(buf, '\n') + if werr := os.WriteFile("config.json", buf, 0644); werr != nil { + log.Printf("未写入 config.json: %v", werr) + } + } + } else if json.Unmarshal(b, &cfg) != nil { + cfg = Config{Listen: ":8787", PollInterval: "30m"} + } + if strings.TrimSpace(cfg.Listen) == "" { + cfg.Listen = ":8787" + } + if strings.TrimSpace(cfg.PollInterval) == "" { + cfg.PollInterval = "30m" + } + if v := strings.TrimSpace(os.Getenv("CBN_LISTEN")); v != "" { + cfg.Listen = v + } + if v := strings.TrimSpace(os.Getenv("CBN_POLL")); v != "" { + cfg.PollInterval = v + } + if v := strings.TrimSpace(os.Getenv("CBN_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 cleanErr(err error) string { + if err == nil { + return "请求失败" + } + msg := err.Error() + if msg == "" { + return "请求失败" + } + return 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 +} diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..10fbc1f --- /dev/null +++ b/web/index.html @@ -0,0 +1,757 @@ + + + + + + 广电账户 + + + +
+
+

广电账户

+ +
+ + + +
+

登录

+
+ +
+ + +
+

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