fix: 审计问题全量修复 + RateLimiter 原子化重构 + CDN 本地化收紧

- 安全:移除 CSP 中 esm.sh/cdnjs.cloudflare.com,highlight.js 主题已本地化 73 个文件
- 安全:StatusBanned 分支补 dummy hash 防时序攻击
- 安全:手写 constantTimeEq 替换为 crypto/subtle.ConstantTimeCompare
- Bug:锁定操作消息已删除→已锁定
- YAGNI:删除 12 个空预留模板目录
- KISS:删除 common.CheckPassword 薄封装,统一用 bcrypt 调用
- KISS:删除 tokenCtrl 别名字段,api.go 统一用 authCtrl
- RateLimiter:check()+recordFail 闭包模式重构为 try() 原子操作,消除竞态
- RateLimiter:新增 ClearIP() 方法,注册成功时清除 IP 计数
- 文档:修正 audit_service.go 注释编号跳跃(3→5→4)
- 文档:修正 deps_core.go 过清理→过期清理
This commit is contained in:
2026-05-31 11:13:32 +08:00
parent e1fb28e8fb
commit 55c408d86c
19 changed files with 504 additions and 94 deletions

View File

@ -30,8 +30,10 @@ type windowState struct {
blockedUntil time.Time
}
// check 核心检查逻辑
func (rl *RateLimiter) check(m map[string]*windowState, key string, window, blockDur time.Duration, maxFails int, lowKey bool) (RateLimitResult, func()) {
// try 原子检查+递增:在持锁状态下判断是否被限流,若允许则递增计数。
// 检查与递增在同一临界区内完成,无竞态窗口。
// 调用方需在操作成功后调用 Clear/或 ClearIP 清除计数。
func (rl *RateLimiter) try(m map[string]*windowState, key string, window, blockDur time.Duration, maxFails int, lowKey bool) RateLimitResult {
rl.mu.Lock()
defer rl.mu.Unlock()
@ -44,38 +46,28 @@ func (rl *RateLimiter) check(m map[string]*windowState, key string, window, bloc
}
}
// 已被封禁中
if !state.blockedUntil.IsZero() && now.Before(state.blockedUntil) {
retry := int(state.blockedUntil.Sub(now).Seconds()) + 1
msg := "请求过于频繁,请稍后重试"
if lowKey {
msg = fmt.Sprintf("该账号登录尝试过于频繁,请 %d 秒后重试", retry)
}
return RateLimitResult{Blocked: true, RetryAfter: retry, Message: msg}, nil
return RateLimitResult{Blocked: true, RetryAfter: retry, Message: msg}
}
// 窗口过期 → 重置
if now.Sub(state.windowStart) > window {
state.count = 0
state.windowStart = now
state.blockedUntil = time.Time{}
}
recordFail := func() {
rl.mu.Lock()
defer rl.mu.Unlock()
s := m[key]
if s == nil {
return
}
if now.Sub(s.windowStart) > window {
s.count = 1
s.windowStart = now
return
}
s.count++
if s.count >= maxFails {
s.blockedUntil = now.Add(blockDur)
}
// 原子递增计数(本次尝试已记录)
state.count++
if state.count >= maxFails {
state.blockedUntil = now.Add(blockDur)
}
return RateLimitResult{Blocked: false}, recordFail
return RateLimitResult{Blocked: false}
}