This repository has been archived on 2026-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MetaLab/internal/middleware/csrf_token.go
Victor_Jay 55c408d86c 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 过清理→过期清理
2026-05-31 11:13:32 +08:00

45 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"crypto/rand"
"encoding/hex"
"net/http"
"metazone.cc/metalab/internal/config"
"github.com/gin-gonic/gin"
)
const csrfTokenLen = 32
// SetCSRFToken 在首次页面访问时下发 CSRF Cookie由页面路由中间件调用
func SetCSRFToken(c *gin.Context, cfg *config.Config) string {
secure := cfg.Server.Mode != "debug"
if existing, err := c.Cookie(csrfCookieName); err == nil && existing != "" {
c.Set(csrfMetaName, existing)
return existing
}
token, err := generateCSRFToken()
if err != nil {
token = "fallback-" + hex.EncodeToString([]byte("metazone"))
}
c.SetSameSite(http.SameSiteStrictMode)
maxAge := cfg.Session.RememberTimeout * 60
c.SetCookie(csrfCookieName, token, maxAge, "/", "", secure, false)
c.Set(csrfMetaName, token)
return token
}
// generateCSRFToken 生成 64 字符十六进制随机 CSRF token
func generateCSRFToken() (string, error) {
b := make([]byte, csrfTokenLen)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}