feat(限流): 登录、注册、比赛密码防爆破
三处原来都不限次数。学生初始密码弱,/classes/:name/usernames 又能公开列出整班
用户名,等于现成的撞库名单。
services/throttling.ts 加固定窗口计数(INCR + EXPIRE NX,锁定时长就是剩余 TTL),
何时计数由调用方决定:
- 登录按用户名 15 分钟 10 次失败,成功清零;按 IP 15 分钟 100 次失败,成功不清零
(否则拿自己的号登一次就能重置)。机房一个班共用出口 IP,所以 IP 那道放得宽
- 注册按 IP 每小时 100 个成功注册
- 比赛密码按「人 × 比赛」10 分钟 10 次失败
- IP 取 X-Real-IP:api 端口不对外,Caddy 用 {client_ip} 覆盖写入,可信
前端登录、注册、比赛密码三处按新错误码给中文提示。
本机实跑核过:第 11 次错误登录被拦、成功清零(用户名大小写不敏感)、同 IP 换
100 个用户名被拦且别的 IP 不受影响、比赛密码第 11 次被拦。
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5813981bb1
commit
fb240d4254
8 files changed
+156
-19
No files matched your search
@@ -38,6 +38,11 @@ import {
|
||||
requireContestAccess,
|
||||
type ContestEnv,
|
||||
} from "../services/contest"
|
||||
import {
|
||||
countAttempt,
|
||||
lockoutRemaining,
|
||||
type AttemptRule,
|
||||
} from "../services/throttling"
|
||||
import {
|
||||
objectValue,
|
||||
publicTemplates,
|
||||
@@ -149,6 +154,8 @@ contestRoutes.get("/contests/:id", optionalAuth, async (c) => {
|
||||
)
|
||||
})
|
||||
|
||||
const CONTEST_PASSWORD_RULE: AttemptRule = { limit: 10, windowSeconds: 10 * 60 }
|
||||
|
||||
contestRoutes.post("/contests/:id/access", requireAuth, async (c) => {
|
||||
const contest = await findAccessibleContest(
|
||||
c.get("user"),
|
||||
@@ -161,7 +168,20 @@ contestRoutes.post("/contests/:id/access", requireAuth, async (c) => {
|
||||
)
|
||||
if (!parsed.success)
|
||||
return failure(c, 400, "invalid-request", "Password is required")
|
||||
// 比赛密码往往就是几位数字,不限的话一个脚本几分钟就能扫完。
|
||||
// 按「人 × 比赛」计失败次数:猜错的是自己,锁的也只是自己进这一场。
|
||||
const attemptKey = `contest-password:${contest.id}:${c.get("user")!.id}`
|
||||
const wait = await lockoutRemaining(attemptKey, CONTEST_PASSWORD_RULE)
|
||||
if (wait !== null) {
|
||||
return failure(
|
||||
c,
|
||||
429,
|
||||
"too-many-password-attempts",
|
||||
`Too many wrong passwords, please wait ${wait} seconds`,
|
||||
)
|
||||
}
|
||||
if (!checkContestPassword(parsed.data.password, contest.password)) {
|
||||
await countAttempt(attemptKey, CONTEST_PASSWORD_RULE)
|
||||
return failure(
|
||||
c,
|
||||
403,
|
||||
|
||||
Reference in new issue
Block a user