captcha.ts
8.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
/**
* 图形验证码(服务端签发 + 服务端校验)。
*
* 设计要点,逐条都对应一种真实攻击:
*
* 1. **码只存在服务端**。接口回给前端的是 `{ id, image }`,`image` 是服务端渲染好的
* SVG data URI。前端拿不到明文码,也就没法「本地比对」——那种写法(把答案塞进
* JS 变量再在浏览器里比)等于没做验证码,任何人看一眼源码就能绕。
* 2. **一次性 + 有 TTL**。验证成功即销毁;错满 MAX_TRIES 次也销毁。否则一张图可以被
* 无限次试(32^4 的空间,慢慢试总能中)。
* 3. **按 IP 限流签发**。防止有人写脚本狂拉 /api/captcha 把内存撑爆,也顺手把
* 自动化爆破的单 IP 吞吐压到没有意义。
* 4. **常量时间比较**。用 timingSafeEqual,避免按字节提前返回泄露信息(这里是 4 位码,
* 收益有限,但成本为零)。
*
* 注意:验证码不是密码的替代品。它挡的是「脚本批量撞库」,挡不住「针对单个账号的
* 人工社工」。登录失败计数(index.ts 里的 rateLimit)是另一层,两者都要有。
*/
/** 去掉易混字符:0/O、1/I/l、2/Z、5/S、8/B 在噪点图里会被看错 */
const ALPHABET = '346789ACDEFGHJKMNPQRTUVWXY';
const CODE_LENGTH = 4;
const TTL_MS = 2 * 60 * 1000;
/** 同一张图允许试错次数,超了必须换图 */
const MAX_TRIES = 3;
/** 内存里最多同时挂多少张未使用的图,超了淘汰最早的(Map 保持插入序) */
const MAX_PENDING = 3000;
/** 单 IP 每分钟签发上限 */
const ISSUE_LIMIT = 40;
interface Entry {
code: string;
expiresAt: number;
tries: number;
}
const store = new Map<string, Entry>();
const issueWindow = new Map<string, { count: number; resetAt: number }>();
export interface CaptchaChallenge {
id: string;
/** `data:image/svg+xml;base64,...`,可直接塞进 <img src> */
image: string;
/** 秒,给前端做倒计时提示用 */
expiresIn: number;
}
export type CaptchaVerdict = 'ok' | 'invalid' | 'expired' | 'missing';
export class CaptchaRateLimited extends Error {
constructor() {
super('captcha_rate_limited');
}
}
function issueAllowed(ip: string): boolean {
const now = Date.now();
const rec = issueWindow.get(ip);
if (!rec || now >= rec.resetAt) {
issueWindow.set(ip, { count: 1, resetAt: now + 60_000 });
return true;
}
if (rec.count >= ISSUE_LIMIT) return false;
rec.count += 1;
return true;
}
function sweep(now: number): void {
for (const [id, entry] of store) {
if (entry.expiresAt <= now) store.delete(id);
}
for (const [ip, rec] of issueWindow) {
if (rec.resetAt <= now) issueWindow.delete(ip);
}
}
/**
* 定时清理。`unref()` 很关键:不然这个 interval 会把 Node 进程钉死,
* 容器里 `docker stop` 要等到超时才退,本地 tsx 也会挂住终端。
*/
const sweeper = setInterval(() => sweep(Date.now()), 60_000);
sweeper.unref();
function pick<T>(arr: readonly T[]): T {
return arr[randomInt(0, arr.length)];
}
function rand(min: number, max: number): number {
return min + Math.random() * (max - min);
}
function buildCode(): string {
let out = '';
for (let i = 0; i < CODE_LENGTH; i += 1) out += ALPHABET[randomInt(0, ALPHABET.length)];
return out;
}
/** 噪点颜色都偏深偏灰蓝,保证在黑字与浅底之间有足够对比,不做成「一片糊」 */
const INK = ['#1f2a5e', '#2b3a7a', '#39406b', '#4653a2', '#243049', '#3c2f5e'];
const NOISE = ['#8f9bc4', '#a9b4d6', '#6f7bab', '#c0c8e0'];
function buildSvg(code: string): string {
const W = 132;
const H = 44;
const chars = [...code].map((ch, i) => {
// 字符故意轻微重叠(步长 26 < 字宽 ~27),配合旋转就断开了「逐字切分」这条路。
// 字号取 25~29:图在登录框里只显示 108×36,源图字号再小一档,缩放后 4 个字符就
// 挤成一条毛边(实测 23~27 时第 4 位最容易认错)。
const x = 15 + i * 26 + rand(-2.5, 2.5);
const y = 31 + rand(-2.5, 2.5);
const rot = rand(-24, 24);
const size = rand(25, 29);
return `<text x="${x.toFixed(1)}" y="${y.toFixed(1)}" font-size="${size.toFixed(
1,
)}" font-weight="700" fill="${pick(INK)}" transform="rotate(${rot.toFixed(
1,
)} ${x.toFixed(1)} ${y.toFixed(1)})">${ch}</text>`;
});
const curves = Array.from({ length: 3 }, () => {
const y1 = rand(6, H - 6);
const y2 = rand(6, H - 6);
return `<path d="M${rand(-8, 4).toFixed(1)} ${y1.toFixed(1)} C ${rand(24, 48).toFixed(
1,
)} ${rand(-4, H + 4).toFixed(1)}, ${rand(84, 108).toFixed(1)} ${rand(-4, H + 4).toFixed(
1,
)}, ${rand(W - 4, W + 8).toFixed(1)} ${y2.toFixed(
1,
)}" fill="none" stroke="${pick(NOISE)}" stroke-width="${rand(0.8, 1.5).toFixed(
2,
)}" stroke-linecap="round" opacity="${rand(0.5, 0.9).toFixed(2)}"/>`;
}).join('');
const dots = Array.from({ length: 34 }, () => {
return `<circle cx="${rand(0, W).toFixed(1)}" cy="${rand(0, H).toFixed(
1,
)}" r="${rand(0.5, 1.4).toFixed(2)}" fill="${pick(NOISE)}" opacity="${rand(
0.35,
0.8,
).toFixed(2)}"/>`;
}).join('');
// 中间横穿一条干扰线:专门打掉「按行投影切字符」的简单 OCR
const strikeY = rand(14, 30).toFixed(1);
return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" role="img">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#f6f8fd"/><stop offset="52%" stop-color="#eaeef9"/><stop offset="100%" stop-color="#dde4f4"/>
</linearGradient>
<filter id="warp" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.035" numOctaves="2" seed="${randomInt(
1,
99,
)}" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="1.6" xChannelSelector="R" yChannelSelector="G"/>
</filter>
</defs>
<rect width="${W}" height="${H}" fill="url(#bg)"/>
<g opacity="0.55">${dots}</g>
<g>${curves}</g>
<g filter="url(#warp)" font-family="'DejaVu Sans Mono','Liberation Mono',Consolas,'Courier New',monospace" letter-spacing="0.5">${chars}</g>
<line x1="${rand(4, 14).toFixed(1)}" y1="${strikeY}" x2="${rand(W - 14, W - 4).toFixed(
1,
)}" y2="${rand(14, 30).toFixed(1)}" stroke="${pick(NOISE)}" stroke-width="1.1" opacity="0.75"/>
</svg>`;
}
export function createCaptcha(ip: string): CaptchaChallenge {
if (!issueAllowed(ip)) throw new CaptchaRateLimited();
const now = Date.now();
if (store.size >= MAX_PENDING) sweep(now);
while (store.size >= MAX_PENDING) {
const oldest = store.keys().next();
if (oldest.done) break;
store.delete(oldest.value);
}
const id = randomBytes(16).toString('hex');
const code = buildCode();
store.set(id, { code, expiresAt: now + TTL_MS, tries: 0 });
return {
id,
image: `data:image/svg+xml;base64,${Buffer.from(buildSvg(code), 'utf-8').toString('base64')}`,
expiresIn: Math.floor(TTL_MS / 1000),
};
}
/**
* 校验并消耗。返回值刻意区分 expired / invalid:
* 前端据此决定提示语(「已过期,已换一张」vs「填错了」),但两者都不是安全信息,
* 攻击者本来就知道自己的码有没有过期。
*/
export function verifyCaptcha(id: string | undefined, input: string | undefined): CaptchaVerdict {
if (!id || !input) return 'missing';
const entry = store.get(id);
if (!entry) return 'expired';
if (entry.expiresAt <= Date.now()) {
store.delete(id);
return 'expired';
}
entry.tries += 1;
const normalized = input.trim().toUpperCase();
const expected = Buffer.from(entry.code, 'utf-8');
const actual = Buffer.from(normalized, 'utf-8');
const matched =
expected.length === actual.length && timingSafeEqual(expected, actual);
if (matched) {
store.delete(id);
return 'ok';
}
if (entry.tries >= MAX_TRIES) store.delete(id);
return 'invalid';
}
/** 仅测试用:清空所有未使用的挑战 */
export function __resetCaptchaStore(): void {
store.clear();
issueWindow.clear();
}