starmusic-mobile
1package main
2
3// ============================================================================
4// Web 公共工具:JSON 响应 / CORS / 客户端 IP / 校验 / 密码哈希 / 会话
5// ============================================================================
6
7import (
8 "bytes"
9 "crypto/rand"
10 "crypto/subtle"
11 "encoding/hex"
12 "encoding/json"
13 "fmt"
14 mrand "math/rand/v2"
15 "net"
16 "net/http"
17 "path"
18 "path/filepath"
19 "regexp"
20 "strconv"
21 "strings"
22 "sync"
23 "time"
24 "unicode/utf8"
25
26 "golang.org/x/crypto/bcrypt"
27)
28
29// ---------------------------------------------------------------------------
30// JSON 响应(与 PHP jsonOut 完全同构:{code, msg, data},中文不转义)
31// ---------------------------------------------------------------------------
32
33type apiResp struct {
34 Code int `json:"code"`
35 Msg string `json:"msg"`
36 Data any `json:"data"`
37}
38
39func writeJSON(w http.ResponseWriter, v any) {
40 w.Header().Set("Content-Type", "application/json; charset=utf-8")
41 enc := json.NewEncoder(w)
42 enc.SetEscapeHTML(false)
43 _ = enc.Encode(v)
44}
45
46func outJSON(w http.ResponseWriter, code int, msg string, data any) {
47 writeJSON(w, apiResp{Code: code, Msg: msg, Data: data})
48}
49
50// marshalNoEscape 等价 PHP json_encode(..., JSON_UNESCAPED_UNICODE)
51func marshalNoEscape(v any) ([]byte, error) {
52 var buf bytes.Buffer
53 enc := json.NewEncoder(&buf)
54 enc.SetEscapeHTML(false)
55 if err := enc.Encode(v); err != nil {
56 return nil, err
57 }
58 return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil
59}
60
61// setAccountCORS 与 PHP account.php 头部一致(H5 端跨域访问)
62func setAccountCORS(w http.ResponseWriter) {
63 w.Header().Set("Access-Control-Allow-Origin", "*")
64 w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
65 w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
66 w.Header().Set("Cache-Control", "no-store")
67}
68
69// ---------------------------------------------------------------------------
70// 客户端 IP(等价 PHP sm_client_ip:直连公网地址直接采信;
71// 内网/反代时才依次采信 CF-Connecting-IP / X-Real-IP / X-Forwarded-For)
72// ---------------------------------------------------------------------------
73
74func clientIP(r *http.Request) string {
75 remote := r.RemoteAddr
76 if h, _, err := net.SplitHostPort(remote); err == nil {
77 remote = h
78 }
79 if isPublicIP(remote) {
80 return remote
81 }
82 for _, key := range []string{"Cf-Connecting-Ip", "X-Real-Ip", "X-Forwarded-For"} {
83 v := strings.TrimSpace(r.Header.Get(key))
84 if v == "" {
85 continue
86 }
87 ip := strings.TrimSpace(strings.Split(v, ",")[0])
88 if net.ParseIP(ip) != nil {
89 return ip
90 }
91 }
92 if remote != "" {
93 return remote
94 }
95 return "unknown"
96}
97
98func isPublicIP(s string) bool {
99 ip := net.ParseIP(s)
100 if ip == nil {
101 return false
102 }
103 if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
104 ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() {
105 return false
106 }
107 return ip.IsGlobalUnicast()
108}
109
110// ---------------------------------------------------------------------------
111// 随机数 / 校验
112// ---------------------------------------------------------------------------
113
114func randHex(nBytes int) string {
115 b := make([]byte, nBytes)
116 if _, err := rand.Read(b); err != nil {
117 panic(err) // 系统熵源不可用属于致命错误
118 }
119 return hex.EncodeToString(b)
120}
121
122func randIntn(n int) int {
123 if n <= 0 {
124 return 0
125 }
126 return mrand.IntN(n)
127}
128
129// 用户名:2-16 位中文、字母、数字或下划线(等价 PHP /u 正则,Go 正则按 rune 匹配)
130var usernameRe = regexp.MustCompile(`^[\x{4e00}-\x{9fa5}A-Za-z0-9_]{2,16}$`)
131
132// 管理员用户名:3-24 位(admin.php 安装向导)
133var adminUsernameRe = regexp.MustCompile(`^[\x{4e00}-\x{9fa5}A-Za-z0-9_]{3,24}$`)
134
135// 版本号(api.php 发布):数字、字母、点、横线、下划线,1-32 位
136var versionRe = regexp.MustCompile(`^[0-9A-Za-z.\-_]{1,32}$`)
137
138// firstN 等价 PHP mb_substr($s, 0, $n)(按字符截取)
139func firstN(s string, n int) string {
140 r := []rune(s)
141 if utf8.RuneCountInString(s) <= n {
142 return s
143 }
144 return string(r[:n])
145}
146
147func runeLen(s string) int { return utf8.RuneCountInString(s) }
148
149func constantTimeEqual(a, b string) bool {
150 return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
151}
152
153// asString 等价 PHP (string) 强转(客户端字段均为字符串,防御性兜底)
154func asString(v any) string {
155 switch t := v.(type) {
156 case nil:
157 return ""
158 case string:
159 return t
160 case json.Number:
161 return t.String()
162 case bool:
163 if t {
164 return "1"
165 }
166 return ""
167 default:
168 return fmt.Sprint(t)
169 }
170}
171
172// leadingIntRe 模拟 PHP (int) 强转对字符串的前缀取整语义
173var leadingIntRe = regexp.MustCompile(`^\s*[+-]?[0-9]+`)
174
175// asInt 等价 PHP (int) 强转
176func asInt(v any) int64 {
177 switch t := v.(type) {
178 case nil:
179 return 0
180 case json.Number:
181 if n, err := t.Int64(); err == nil {
182 return n
183 }
184 if f, err := t.Float64(); err == nil {
185 return int64(f)
186 }
187 return 0
188 case int:
189 return int64(t)
190 case int64:
191 return t
192 case bool:
193 if t {
194 return 1
195 }
196 return 0
197 case string:
198 m := leadingIntRe.FindString(t)
199 if m == "" {
200 return 0
201 }
202 n, err := strconv.ParseInt(strings.TrimSpace(m), 10, 64)
203 if err != nil {
204 return 0
205 }
206 return n
207 default:
208 return 0
209 }
210}
211
212// ---------------------------------------------------------------------------
213// 密码哈希:与 PHP password_hash / password_verify(bcrypt)完全互通
214// - PHP 生成 $2y$ 前缀;Go 的 bcrypt 校验前归一化为 $2a$(算法完全相同)
215// - 新哈希用 bcrypt cost=10,与 PHP PASSWORD_DEFAULT 一致
216// ---------------------------------------------------------------------------
217
218func hashPassword(pw string) (string, error) {
219 b, err := bcrypt.GenerateFromPassword([]byte(pw), 10)
220 if err != nil {
221 return "", err
222 }
223 return string(b), nil
224}
225
226func verifyPassword(pw, hash string) bool {
227 if strings.HasPrefix(hash, "$2y$") {
228 hash = "$2a$" + hash[4:]
229 }
230 return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pw)) == nil
231}
232
233// ---------------------------------------------------------------------------
234// 会话(替代 PHP session:api.php 发版后台与 admin.php 管理后台共用,
235// 服务端内存存储 + HttpOnly Cookie;客户端 API 完全不依赖会话)
236// ---------------------------------------------------------------------------
237
238type Session struct {
239 id string
240 mu sync.Mutex
241 vals map[string]any
242}
243
244func (s *Session) Get(key string) any {
245 s.mu.Lock()
246 defer s.mu.Unlock()
247 return s.vals[key]
248}
249
250func (s *Session) Set(key string, v any) {
251 s.mu.Lock()
252 defer s.mu.Unlock()
253 s.vals[key] = v
254}
255
256type sessionRecord struct {
257 sess *Session
258 expires time.Time
259}
260
261type SessionStore struct {
262 mu sync.Mutex
263 cookie string
264 ttl time.Duration
265 sessions map[string]*sessionRecord
266}
267
268func NewSessionStore() *SessionStore {
269 st := &SessionStore{
270 cookie: "SM_SESSION",
271 ttl: 24 * time.Hour,
272 sessions: map[string]*sessionRecord{},
273 }
274 go func() {
275 for {
276 time.Sleep(10 * time.Minute)
277 st.cleanup()
278 }
279 }()
280 return st
281}
282
283func (st *SessionStore) cleanup() {
284 now := time.Now()
285 st.mu.Lock()
286 defer st.mu.Unlock()
287 for id, rec := range st.sessions {
288 if now.After(rec.expires) {
289 delete(st.sessions, id)
290 }
291 }
292}
293
294func (st *SessionStore) setCookie(w http.ResponseWriter, id string, maxAge int) {
295 http.SetCookie(w, &http.Cookie{
296 Name: st.cookie,
297 Value: id,
298 Path: "/",
299 HttpOnly: true,
300 SameSite: http.SameSiteLaxMode,
301 MaxAge: maxAge,
302 })
303}
304
305// Get 读取会话(滑动续期;不存在/已过期返回 nil)
306func (st *SessionStore) Get(r *http.Request) *Session {
307 c, err := r.Cookie(st.cookie)
308 if err != nil || c.Value == "" {
309 return nil
310 }
311 st.mu.Lock()
312 defer st.mu.Unlock()
313 rec, ok := st.sessions[c.Value]
314 if !ok {
315 return nil
316 }
317 if time.Now().After(rec.expires) {
318 delete(st.sessions, c.Value)
319 return nil
320 }
321 rec.expires = time.Now().Add(st.ttl)
322 return rec.sess
323}
324
325func (st *SessionStore) create() *Session {
326 s := &Session{id: randHex(32), vals: map[string]any{}}
327 st.sessions[s.id] = &sessionRecord{s, time.Now().Add(st.ttl)}
328 return s
329}
330
331// Ensure 读取或创建会话
332func (st *SessionStore) Ensure(w http.ResponseWriter, r *http.Request) *Session {
333 if s := st.Get(r); s != nil {
334 return s
335 }
336 st.mu.Lock()
337 s := st.create()
338 st.mu.Unlock()
339 st.setCookie(w, s.id, 0)
340 return s
341}
342
343// Regenerate 等价 PHP session_regenerate_id(true):换新 id 并迁移数据(登录后防会话固定)
344func (st *SessionStore) Regenerate(w http.ResponseWriter, r *http.Request) *Session {
345 old := st.Get(r)
346 st.mu.Lock()
347 s := st.create()
348 if old != nil {
349 old.mu.Lock()
350 for k, v := range old.vals {
351 s.vals[k] = v
352 }
353 old.mu.Unlock()
354 delete(st.sessions, old.id)
355 }
356 st.mu.Unlock()
357 st.setCookie(w, s.id, 0)
358 return s
359}
360
361func (st *SessionStore) Destroy(w http.ResponseWriter, r *http.Request) {
362 if c, err := r.Cookie(st.cookie); err == nil && c.Value != "" {
363 st.mu.Lock()
364 delete(st.sessions, c.Value)
365 st.mu.Unlock()
366 }
367 st.setCookie(w, "", -1)
368}
369
370// sessVal 空会话安全的取值
371func sessVal(s *Session, key string) any {
372 if s == nil {
373 return nil
374 }
375 return s.Get(key)
376}
377
378// ---------------------------------------------------------------------------
379// 站点根地址(等价 PHP getBaseUrl:HTTPS/反代识别;baseOverride 支持 -base-url)
380// ---------------------------------------------------------------------------
381
382func baseURL(r *http.Request, baseOverride string) string {
383 if baseOverride != "" {
384 return strings.TrimRight(baseOverride, "/")
385 }
386 scheme := "http"
387 if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
388 scheme = "https"
389 }
390 base := scheme + "://" + r.Host
391 if pfx := strings.TrimSpace(r.Header.Get("X-Forwarded-Prefix")); pfx != "" {
392 base += "/" + strings.Trim(pfx, "/")
393 }
394 return base
395}
396
397// safeJoin 把 update.json 里记录的相对路径安全地解析到 root 下(防目录穿越)
398func safeJoin(root, rel string) (string, error) {
399 clean := path.Clean("/" + strings.ReplaceAll(rel, "\\", "/"))
400 if clean == "/" || strings.HasSuffix(clean, "/..") {
401 return "", fmt.Errorf("非法路径: %s", rel)
402 }
403 return filepath.Join(root, filepath.FromSlash(clean)), nil
404}