package main // ============================================================================ // Web 公共工具:JSON 响应 / CORS / 客户端 IP / 校验 / 密码哈希 / 会话 // ============================================================================ import ( "bytes" "crypto/rand" "crypto/subtle" "encoding/hex" "encoding/json" "fmt" mrand "math/rand/v2" "net" "net/http" "path" "path/filepath" "regexp" "strconv" "strings" "sync" "time" "unicode/utf8" "golang.org/x/crypto/bcrypt" ) // --------------------------------------------------------------------------- // JSON 响应(与 PHP jsonOut 完全同构:{code, msg, data},中文不转义) // --------------------------------------------------------------------------- type apiResp struct { Code int `json:"code"` Msg string `json:"msg"` Data any `json:"data"` } func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") enc := json.NewEncoder(w) enc.SetEscapeHTML(false) _ = enc.Encode(v) } func outJSON(w http.ResponseWriter, code int, msg string, data any) { writeJSON(w, apiResp{Code: code, Msg: msg, Data: data}) } // marshalNoEscape 等价 PHP json_encode(..., JSON_UNESCAPED_UNICODE) func marshalNoEscape(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.TrimSuffix(buf.Bytes(), []byte("\n")), nil } // setAccountCORS 与 PHP account.php 头部一致(H5 端跨域访问) func setAccountCORS(w http.ResponseWriter) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") w.Header().Set("Cache-Control", "no-store") } // --------------------------------------------------------------------------- // 客户端 IP(等价 PHP sm_client_ip:直连公网地址直接采信; // 内网/反代时才依次采信 CF-Connecting-IP / X-Real-IP / X-Forwarded-For) // --------------------------------------------------------------------------- func clientIP(r *http.Request) string { remote := r.RemoteAddr if h, _, err := net.SplitHostPort(remote); err == nil { remote = h } if isPublicIP(remote) { return remote } for _, key := range []string{"Cf-Connecting-Ip", "X-Real-Ip", "X-Forwarded-For"} { v := strings.TrimSpace(r.Header.Get(key)) if v == "" { continue } ip := strings.TrimSpace(strings.Split(v, ",")[0]) if net.ParseIP(ip) != nil { return ip } } if remote != "" { return remote } return "unknown" } func isPublicIP(s string) bool { ip := net.ParseIP(s) if ip == nil { return false } if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() { return false } return ip.IsGlobalUnicast() } // --------------------------------------------------------------------------- // 随机数 / 校验 // --------------------------------------------------------------------------- func randHex(nBytes int) string { b := make([]byte, nBytes) if _, err := rand.Read(b); err != nil { panic(err) // 系统熵源不可用属于致命错误 } return hex.EncodeToString(b) } func randIntn(n int) int { if n <= 0 { return 0 } return mrand.IntN(n) } // 用户名:2-16 位中文、字母、数字或下划线(等价 PHP /u 正则,Go 正则按 rune 匹配) var usernameRe = regexp.MustCompile(`^[\x{4e00}-\x{9fa5}A-Za-z0-9_]{2,16}$`) // 管理员用户名:3-24 位(admin.php 安装向导) var adminUsernameRe = regexp.MustCompile(`^[\x{4e00}-\x{9fa5}A-Za-z0-9_]{3,24}$`) // 版本号(api.php 发布):数字、字母、点、横线、下划线,1-32 位 var versionRe = regexp.MustCompile(`^[0-9A-Za-z.\-_]{1,32}$`) // firstN 等价 PHP mb_substr($s, 0, $n)(按字符截取) func firstN(s string, n int) string { r := []rune(s) if utf8.RuneCountInString(s) <= n { return s } return string(r[:n]) } func runeLen(s string) int { return utf8.RuneCountInString(s) } func constantTimeEqual(a, b string) bool { return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 } // asString 等价 PHP (string) 强转(客户端字段均为字符串,防御性兜底) func asString(v any) string { switch t := v.(type) { case nil: return "" case string: return t case json.Number: return t.String() case bool: if t { return "1" } return "" default: return fmt.Sprint(t) } } // leadingIntRe 模拟 PHP (int) 强转对字符串的前缀取整语义 var leadingIntRe = regexp.MustCompile(`^\s*[+-]?[0-9]+`) // asInt 等价 PHP (int) 强转 func asInt(v any) int64 { switch t := v.(type) { case nil: return 0 case json.Number: if n, err := t.Int64(); err == nil { return n } if f, err := t.Float64(); err == nil { return int64(f) } return 0 case int: return int64(t) case int64: return t case bool: if t { return 1 } return 0 case string: m := leadingIntRe.FindString(t) if m == "" { return 0 } n, err := strconv.ParseInt(strings.TrimSpace(m), 10, 64) if err != nil { return 0 } return n default: return 0 } } // --------------------------------------------------------------------------- // 密码哈希:与 PHP password_hash / password_verify(bcrypt)完全互通 // - PHP 生成 $2y$ 前缀;Go 的 bcrypt 校验前归一化为 $2a$(算法完全相同) // - 新哈希用 bcrypt cost=10,与 PHP PASSWORD_DEFAULT 一致 // --------------------------------------------------------------------------- func hashPassword(pw string) (string, error) { b, err := bcrypt.GenerateFromPassword([]byte(pw), 10) if err != nil { return "", err } return string(b), nil } func verifyPassword(pw, hash string) bool { if strings.HasPrefix(hash, "$2y$") { hash = "$2a$" + hash[4:] } return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pw)) == nil } // --------------------------------------------------------------------------- // 会话(替代 PHP session:api.php 发版后台与 admin.php 管理后台共用, // 服务端内存存储 + HttpOnly Cookie;客户端 API 完全不依赖会话) // --------------------------------------------------------------------------- type Session struct { id string mu sync.Mutex vals map[string]any } func (s *Session) Get(key string) any { s.mu.Lock() defer s.mu.Unlock() return s.vals[key] } func (s *Session) Set(key string, v any) { s.mu.Lock() defer s.mu.Unlock() s.vals[key] = v } type sessionRecord struct { sess *Session expires time.Time } type SessionStore struct { mu sync.Mutex cookie string ttl time.Duration sessions map[string]*sessionRecord } func NewSessionStore() *SessionStore { st := &SessionStore{ cookie: "SM_SESSION", ttl: 24 * time.Hour, sessions: map[string]*sessionRecord{}, } go func() { for { time.Sleep(10 * time.Minute) st.cleanup() } }() return st } func (st *SessionStore) cleanup() { now := time.Now() st.mu.Lock() defer st.mu.Unlock() for id, rec := range st.sessions { if now.After(rec.expires) { delete(st.sessions, id) } } } func (st *SessionStore) setCookie(w http.ResponseWriter, id string, maxAge int) { http.SetCookie(w, &http.Cookie{ Name: st.cookie, Value: id, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: maxAge, }) } // Get 读取会话(滑动续期;不存在/已过期返回 nil) func (st *SessionStore) Get(r *http.Request) *Session { c, err := r.Cookie(st.cookie) if err != nil || c.Value == "" { return nil } st.mu.Lock() defer st.mu.Unlock() rec, ok := st.sessions[c.Value] if !ok { return nil } if time.Now().After(rec.expires) { delete(st.sessions, c.Value) return nil } rec.expires = time.Now().Add(st.ttl) return rec.sess } func (st *SessionStore) create() *Session { s := &Session{id: randHex(32), vals: map[string]any{}} st.sessions[s.id] = &sessionRecord{s, time.Now().Add(st.ttl)} return s } // Ensure 读取或创建会话 func (st *SessionStore) Ensure(w http.ResponseWriter, r *http.Request) *Session { if s := st.Get(r); s != nil { return s } st.mu.Lock() s := st.create() st.mu.Unlock() st.setCookie(w, s.id, 0) return s } // Regenerate 等价 PHP session_regenerate_id(true):换新 id 并迁移数据(登录后防会话固定) func (st *SessionStore) Regenerate(w http.ResponseWriter, r *http.Request) *Session { old := st.Get(r) st.mu.Lock() s := st.create() if old != nil { old.mu.Lock() for k, v := range old.vals { s.vals[k] = v } old.mu.Unlock() delete(st.sessions, old.id) } st.mu.Unlock() st.setCookie(w, s.id, 0) return s } func (st *SessionStore) Destroy(w http.ResponseWriter, r *http.Request) { if c, err := r.Cookie(st.cookie); err == nil && c.Value != "" { st.mu.Lock() delete(st.sessions, c.Value) st.mu.Unlock() } st.setCookie(w, "", -1) } // sessVal 空会话安全的取值 func sessVal(s *Session, key string) any { if s == nil { return nil } return s.Get(key) } // --------------------------------------------------------------------------- // 站点根地址(等价 PHP getBaseUrl:HTTPS/反代识别;baseOverride 支持 -base-url) // --------------------------------------------------------------------------- func baseURL(r *http.Request, baseOverride string) string { if baseOverride != "" { return strings.TrimRight(baseOverride, "/") } scheme := "http" if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") { scheme = "https" } base := scheme + "://" + r.Host if pfx := strings.TrimSpace(r.Header.Get("X-Forwarded-Prefix")); pfx != "" { base += "/" + strings.Trim(pfx, "/") } return base } // safeJoin 把 update.json 里记录的相对路径安全地解析到 root 下(防目录穿越) func safeJoin(root, rel string) (string, error) { clean := path.Clean("/" + strings.ReplaceAll(rel, "\\", "/")) if clean == "/" || strings.HasSuffix(clean, "/..") { return "", fmt.Errorf("非法路径: %s", rel) } return filepath.Join(root, filepath.FromSlash(clean)), nil }