// Package captcha 提供访客提交议题所需的 5 位数字图片验证码。 // // 设计要点: // - 零第三方依赖:数字用 7 段码笔画绘制(随机旋转 + 抖动 + 干扰线噪点), // 标准库 image/png 直接编码,不引入字体文件; // - 验证码一次性:验证通过或过期即销毁,内存存储(gitcat 单实例部署), // 防止同一份验证码被反复重放。 package captcha import ( "bytes" "crypto/rand" "encoding/hex" "errors" "image" "image/color" "image/png" "math" "strings" "sync" "time" ) // Store 是验证码的内存存储:id -> 一次性验证码。 type Store struct { mu sync.Mutex items map[string]captchaItem ttl time.Duration last time.Time } type captchaItem struct { code string expires time.Time } // NewStore 创建验证码存储,ttl 为验证码有效期。 func NewStore(ttl time.Duration) *Store { return &Store{items: map[string]captchaItem{}, ttl: ttl, last: time.Now()} } // New 生成一条新验证码,返回存储 id(调用方应把 id 写入 Cookie, // 让用户提交时带上)。旧的同 id 记录自然过期,无需显式清理。 func (s *Store) New() (id string, err error) { b := make([]byte, 16) if _, err = rand.Read(b); err != nil { return "", err } id = hex.EncodeToString(b) s.mu.Lock() defer s.mu.Unlock() if time.Since(s.last) > time.Minute { s.sweep(time.Now()) } s.items[id] = captchaItem{code: randomDigits(5), expires: time.Now().Add(s.ttl)} return id, nil } // Verify 校验用户输入(输入中的空白会被忽略)。无论对错,验证码都立即销毁(一次性)。 func (s *Store) Verify(id, input string) bool { if id == "" || len(input) > 16 { return false } input = NormalizeInput(input) s.mu.Lock() defer s.mu.Unlock() item, ok := s.items[id] if !ok { return false } delete(s.items, id) // 一次性:不管对错都作废 if time.Now().After(item.expires) { return false } return input == item.code } // PNG 渲染指定 id 的验证码图片;不存在或已过期时返回错误。 // 与 Verify 不同,渲染不会销毁验证码(图片可能被浏览器重新加载)。 func (s *Store) PNG(id string) ([]byte, error) { s.mu.Lock() item, ok := s.items[id] s.mu.Unlock() if !ok || time.Now().After(item.expires) { return nil, errCaptchaNotFound } return PNG(item.code) } // errCaptchaNotFound 表示验证码 id 不存在或已过期。 var errCaptchaNotFound = errors.New("验证码不存在或已过期") // Code 返回 id 对应的验证码明文。id 由 HttpOnly Cookie 持有、只有发起请求的 // 浏览器自己能看到,因此暴露它不会帮助第三方绕过验证;主要供测试与排障使用。 func (s *Store) Code(id string) (string, bool) { if id == "" { return "", false } s.mu.Lock() defer s.mu.Unlock() item, ok := s.items[id] if !ok || time.Now().After(item.expires) { return "", false } return item.code, true } // sweep 清掉过期项。调用方需持有锁。 func (s *Store) sweep(now time.Time) { for id, item := range s.items { if now.After(item.expires) { delete(s.items, id) } } s.last = now } func randomDigits(n int) string { b := make([]byte, n) _, _ = rand.Read(b) for i := range b { b[i] = '0' + b[i]%10 } return string(b) } // ---------------------------------------------------------------- 图片渲染 // 画布与字形尺寸(像素)。 const ( digitW = 18 // 单个数字笔画区域的宽 digitH = 30 // 单个数字笔画区域的高 cellW = 26 // 数字单元(含间距) cellH = 40 padX = 10 canvasW = padX*2 + cellW*5 canvasH = cellH + 12 strokeR = 2 // 笔画半径(线宽 = strokeR*2+1) rotateRange = 0.35 ) // segDigits 是数字 0-9 的 7 段码段定义,坐标基于 digitW×digitH 字形框。 var segDigits = map[byte][][][2]int{ '0': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}, {{-1, 17}, {-1, 28}}, {{-1, 2}, {-1, 13}}}, '1': {{{7, 4}, {13, 0}}, {{13, 0}, {13, 30}}}, '2': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{-1, 17}, {-1, 28}}, {{1, 30}, {17, 30}}}, '3': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}}, '4': {{{-1, 2}, {-1, 13}}, {{1, 15}, {17, 15}}, {{19, 2}, {19, 30}}}, '5': {{{1, 0}, {17, 0}}, {{-1, 2}, {-1, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}}, '6': {{{1, 0}, {17, 0}}, {{-1, 2}, {-1, 28}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}}, '7': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 30}}}, '8': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}, {{-1, 17}, {-1, 28}}, {{-1, 2}, {-1, 13}}}, '9': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{-1, 2}, {-1, 13}}, {{1, 30}, {17, 30}}}, } // PNG 把 5 位验证码渲染成带干扰的 PNG 图片。 func PNG(code string) ([]byte, error) { img := image.NewRGBA(image.Rect(0, 0, canvasW, canvasH)) bg := color.RGBA{244, 249, 247, 255} ink := color.RGBA{35, 64, 82, 255} noise := color.RGBA{148, 178, 196, 255} drawRect(img, img.Rect, bg) // 干扰曲线:几条跨画布的折线 for i := 0; i < 4; i++ { x := float64(randRange(0, canvasW/3)) y := float64(randRange(4, canvasH-4)) for x < float64(canvasW) { nx := x + float64(randRange(8, 22)) ny := clamp(y+float64(randRange(-14, 14)), 3, canvasH-4) drawThickLine(img, pt(x, y), pt(nx, ny), 1, noise) x, y = nx, ny } } // 噪点 for i := 0; i < 90; i++ { x, y := randRange(0, canvasW-1), randRange(0, canvasH-1) img.Set(x, y, noise) } // 数字:逐位随机旋转 + 抖动 for i := 0; i < len(code) && i < 5; i++ { ang := (float64(randRange(0, 100))/100 - 0.5) * 2 * rotateRange jx := randRange(0, 5) jy := randRange(0, 5) cx := float64(padX + i*cellW + cellW/2) cy := float64(canvasH/2 - 2) rot := func(p [2]float64) [2]float64 { dx, dy := p[0]-cx, p[1]-cy c, s := math.Cos(ang), math.Sin(ang) return [2]float64{cx + dx*c - dy*s, cy + dx*s + dy*c} } segs := segDigits[code[i]] ox := float64(padX + i*cellW + jx) oy := float64(6 + jy) for _, seg := range segs { p0 := rot([2]float64{ox + float64(seg[0][0])*digitW/20, oy + float64(seg[0][1])*digitH/30}) p1 := rot([2]float64{ox + float64(seg[1][0])*digitW/20, oy + float64(seg[1][1])*digitH/30}) drawThickLine(img, p0, p1, strokeR, ink) } } var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { return nil, err } return buf.Bytes(), nil } func pt(x, y float64) [2]float64 { return [2]float64{x, y} } func randRange(lo, hi int) int { if hi <= lo { return lo } b := make([]byte, 1) _, _ = rand.Read(b) return lo + int(b[0])%int(hi-lo+1) } func clamp(v, lo, hi float64) float64 { if v < lo { return lo } if v > hi { return hi } return v } func drawRect(img *image.RGBA, r image.Rectangle, c color.RGBA) { for y := r.Min.Y; y < r.Max.Y; y++ { for x := r.Min.X; x < r.Max.X; x++ { img.Set(x, y, c) } } } // drawThickLine 用 Bresenham + 圆点笔画画粗线段。 func drawThickLine(img *image.RGBA, p0, p1 [2]float64, radius int, c color.RGBA) { x0, y0 := int(math.Round(p0[0])), int(math.Round(p0[1])) x1, y1 := int(math.Round(p1[0])), int(math.Round(p1[1])) dx, dy := abs(x1-x0), -abs(y1-y0) sx, sy := -1, -1 if x0 < x1 { sx = 1 } if y0 < y1 { sy = 1 } err := dx + dy for { fillCircle(img, x0, y0, radius, c) if x0 == x1 && y0 == y1 { break } e2 := 2 * err if e2 >= dy { err += dy x0 += sx } if e2 <= dx { err += dx y0 += sy } } } func fillCircle(img *image.RGBA, cx, cy, r int, c color.RGBA) { for y := cy - r; y <= cy+r; y++ { for x := cx - r; x <= cx+r; x++ { if (x-cx)*(x-cx)+(y-cy)*(y-cy) <= r*r { img.Set(x, y, c) } } } } func abs(v int) int { if v < 0 { return -v } return v } // NormalizeInput 去掉用户输入里的空白,便于宽容比较。 func NormalizeInput(s string) string { var b strings.Builder for _, r := range s { if r != ' ' && r != '\t' && r != '\n' && r != '\r' { b.WriteRune(r) } } return b.String() }