gitcat
1// Package captcha 提供访客提交议题所需的 5 位数字图片验证码。
2//
3// 设计要点:
4// - 零第三方依赖:数字用 7 段码笔画绘制(随机旋转 + 抖动 + 干扰线噪点),
5// 标准库 image/png 直接编码,不引入字体文件;
6// - 验证码一次性:验证通过或过期即销毁,内存存储(gitcat 单实例部署),
7// 防止同一份验证码被反复重放。
8package captcha
9
10import (
11 "bytes"
12 "crypto/rand"
13 "encoding/hex"
14 "errors"
15 "image"
16 "image/color"
17 "image/png"
18 "math"
19 "strings"
20 "sync"
21 "time"
22)
23
24// Store 是验证码的内存存储:id -> 一次性验证码。
25type Store struct {
26 mu sync.Mutex
27 items map[string]captchaItem
28 ttl time.Duration
29 last time.Time
30}
31
32type captchaItem struct {
33 code string
34 expires time.Time
35}
36
37// NewStore 创建验证码存储,ttl 为验证码有效期。
38func NewStore(ttl time.Duration) *Store {
39 return &Store{items: map[string]captchaItem{}, ttl: ttl, last: time.Now()}
40}
41
42// New 生成一条新验证码,返回存储 id(调用方应把 id 写入 Cookie,
43// 让用户提交时带上)。旧的同 id 记录自然过期,无需显式清理。
44func (s *Store) New() (id string, err error) {
45 b := make([]byte, 16)
46 if _, err = rand.Read(b); err != nil {
47 return "", err
48 }
49 id = hex.EncodeToString(b)
50 s.mu.Lock()
51 defer s.mu.Unlock()
52 if time.Since(s.last) > time.Minute {
53 s.sweep(time.Now())
54 }
55 s.items[id] = captchaItem{code: randomDigits(5), expires: time.Now().Add(s.ttl)}
56 return id, nil
57}
58
59// Verify 校验用户输入(输入中的空白会被忽略)。无论对错,验证码都立即销毁(一次性)。
60func (s *Store) Verify(id, input string) bool {
61 if id == "" || len(input) > 16 {
62 return false
63 }
64 input = NormalizeInput(input)
65 s.mu.Lock()
66 defer s.mu.Unlock()
67 item, ok := s.items[id]
68 if !ok {
69 return false
70 }
71 delete(s.items, id) // 一次性:不管对错都作废
72 if time.Now().After(item.expires) {
73 return false
74 }
75 return input == item.code
76}
77
78// PNG 渲染指定 id 的验证码图片;不存在或已过期时返回错误。
79// 与 Verify 不同,渲染不会销毁验证码(图片可能被浏览器重新加载)。
80func (s *Store) PNG(id string) ([]byte, error) {
81 s.mu.Lock()
82 item, ok := s.items[id]
83 s.mu.Unlock()
84 if !ok || time.Now().After(item.expires) {
85 return nil, errCaptchaNotFound
86 }
87 return PNG(item.code)
88}
89
90// errCaptchaNotFound 表示验证码 id 不存在或已过期。
91var errCaptchaNotFound = errors.New("验证码不存在或已过期")
92
93// Code 返回 id 对应的验证码明文。id 由 HttpOnly Cookie 持有、只有发起请求的
94// 浏览器自己能看到,因此暴露它不会帮助第三方绕过验证;主要供测试与排障使用。
95func (s *Store) Code(id string) (string, bool) {
96 if id == "" {
97 return "", false
98 }
99 s.mu.Lock()
100 defer s.mu.Unlock()
101 item, ok := s.items[id]
102 if !ok || time.Now().After(item.expires) {
103 return "", false
104 }
105 return item.code, true
106}
107
108// sweep 清掉过期项。调用方需持有锁。
109func (s *Store) sweep(now time.Time) {
110 for id, item := range s.items {
111 if now.After(item.expires) {
112 delete(s.items, id)
113 }
114 }
115 s.last = now
116}
117
118func randomDigits(n int) string {
119 b := make([]byte, n)
120 _, _ = rand.Read(b)
121 for i := range b {
122 b[i] = '0' + b[i]%10
123 }
124 return string(b)
125}
126
127// ---------------------------------------------------------------- 图片渲染
128
129// 画布与字形尺寸(像素)。
130const (
131 digitW = 18 // 单个数字笔画区域的宽
132 digitH = 30 // 单个数字笔画区域的高
133 cellW = 26 // 数字单元(含间距)
134 cellH = 40
135 padX = 10
136 canvasW = padX*2 + cellW*5
137 canvasH = cellH + 12
138 strokeR = 2 // 笔画半径(线宽 = strokeR*2+1)
139 rotateRange = 0.35
140)
141
142// segDigits 是数字 0-9 的 7 段码段定义,坐标基于 digitW×digitH 字形框。
143var segDigits = map[byte][][][2]int{
144 '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}}},
145 '1': {{{7, 4}, {13, 0}}, {{13, 0}, {13, 30}}},
146 '2': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{-1, 17}, {-1, 28}}, {{1, 30}, {17, 30}}},
147 '3': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}},
148 '4': {{{-1, 2}, {-1, 13}}, {{1, 15}, {17, 15}}, {{19, 2}, {19, 30}}},
149 '5': {{{1, 0}, {17, 0}}, {{-1, 2}, {-1, 13}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}},
150 '6': {{{1, 0}, {17, 0}}, {{-1, 2}, {-1, 28}}, {{1, 15}, {17, 15}}, {{19, 17}, {19, 28}}, {{1, 30}, {17, 30}}},
151 '7': {{{1, 0}, {17, 0}}, {{19, 2}, {19, 30}}},
152 '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}}},
153 '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}}},
154}
155
156// PNG 把 5 位验证码渲染成带干扰的 PNG 图片。
157func PNG(code string) ([]byte, error) {
158 img := image.NewRGBA(image.Rect(0, 0, canvasW, canvasH))
159 bg := color.RGBA{244, 249, 247, 255}
160 ink := color.RGBA{35, 64, 82, 255}
161 noise := color.RGBA{148, 178, 196, 255}
162 drawRect(img, img.Rect, bg)
163
164 // 干扰曲线:几条跨画布的折线
165 for i := 0; i < 4; i++ {
166 x := float64(randRange(0, canvasW/3))
167 y := float64(randRange(4, canvasH-4))
168 for x < float64(canvasW) {
169 nx := x + float64(randRange(8, 22))
170 ny := clamp(y+float64(randRange(-14, 14)), 3, canvasH-4)
171 drawThickLine(img, pt(x, y), pt(nx, ny), 1, noise)
172 x, y = nx, ny
173 }
174 }
175 // 噪点
176 for i := 0; i < 90; i++ {
177 x, y := randRange(0, canvasW-1), randRange(0, canvasH-1)
178 img.Set(x, y, noise)
179 }
180
181 // 数字:逐位随机旋转 + 抖动
182 for i := 0; i < len(code) && i < 5; i++ {
183 ang := (float64(randRange(0, 100))/100 - 0.5) * 2 * rotateRange
184 jx := randRange(0, 5)
185 jy := randRange(0, 5)
186 cx := float64(padX + i*cellW + cellW/2)
187 cy := float64(canvasH/2 - 2)
188 rot := func(p [2]float64) [2]float64 {
189 dx, dy := p[0]-cx, p[1]-cy
190 c, s := math.Cos(ang), math.Sin(ang)
191 return [2]float64{cx + dx*c - dy*s, cy + dx*s + dy*c}
192 }
193 segs := segDigits[code[i]]
194 ox := float64(padX + i*cellW + jx)
195 oy := float64(6 + jy)
196 for _, seg := range segs {
197 p0 := rot([2]float64{ox + float64(seg[0][0])*digitW/20, oy + float64(seg[0][1])*digitH/30})
198 p1 := rot([2]float64{ox + float64(seg[1][0])*digitW/20, oy + float64(seg[1][1])*digitH/30})
199 drawThickLine(img, p0, p1, strokeR, ink)
200 }
201 }
202
203 var buf bytes.Buffer
204 if err := png.Encode(&buf, img); err != nil {
205 return nil, err
206 }
207 return buf.Bytes(), nil
208}
209
210func pt(x, y float64) [2]float64 { return [2]float64{x, y} }
211
212func randRange(lo, hi int) int {
213 if hi <= lo {
214 return lo
215 }
216 b := make([]byte, 1)
217 _, _ = rand.Read(b)
218 return lo + int(b[0])%int(hi-lo+1)
219}
220
221func clamp(v, lo, hi float64) float64 {
222 if v < lo {
223 return lo
224 }
225 if v > hi {
226 return hi
227 }
228 return v
229}
230
231func drawRect(img *image.RGBA, r image.Rectangle, c color.RGBA) {
232 for y := r.Min.Y; y < r.Max.Y; y++ {
233 for x := r.Min.X; x < r.Max.X; x++ {
234 img.Set(x, y, c)
235 }
236 }
237}
238
239// drawThickLine 用 Bresenham + 圆点笔画画粗线段。
240func drawThickLine(img *image.RGBA, p0, p1 [2]float64, radius int, c color.RGBA) {
241 x0, y0 := int(math.Round(p0[0])), int(math.Round(p0[1]))
242 x1, y1 := int(math.Round(p1[0])), int(math.Round(p1[1]))
243 dx, dy := abs(x1-x0), -abs(y1-y0)
244 sx, sy := -1, -1
245 if x0 < x1 {
246 sx = 1
247 }
248 if y0 < y1 {
249 sy = 1
250 }
251 err := dx + dy
252 for {
253 fillCircle(img, x0, y0, radius, c)
254 if x0 == x1 && y0 == y1 {
255 break
256 }
257 e2 := 2 * err
258 if e2 >= dy {
259 err += dy
260 x0 += sx
261 }
262 if e2 <= dx {
263 err += dx
264 y0 += sy
265 }
266 }
267}
268
269func fillCircle(img *image.RGBA, cx, cy, r int, c color.RGBA) {
270 for y := cy - r; y <= cy+r; y++ {
271 for x := cx - r; x <= cx+r; x++ {
272 if (x-cx)*(x-cx)+(y-cy)*(y-cy) <= r*r {
273 img.Set(x, y, c)
274 }
275 }
276 }
277}
278
279func abs(v int) int {
280 if v < 0 {
281 return -v
282 }
283 return v
284}
285
286// NormalizeInput 去掉用户输入里的空白,便于宽容比较。
287func NormalizeInput(s string) string {
288 var b strings.Builder
289 for _, r := range s {
290 if r != ' ' && r != '\t' && r != '\n' && r != '\r' {
291 b.WriteRune(r)
292 }
293 }
294 return b.String()
295}