feat: 提交广电个人中心只读面板
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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, "<script")
|
||||
if i < 0 {
|
||||
break
|
||||
}
|
||||
rest = rest[i:]
|
||||
j := strings.Index(rest, ">")
|
||||
k := strings.Index(rest, "</script>")
|
||||
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:], "</textarea>")
|
||||
if gt < 0 || end < 0 || end < gt {
|
||||
return ""
|
||||
}
|
||||
return html[i+gt+1 : i+end]
|
||||
}
|
||||
Reference in New Issue
Block a user