安全加固:增加后台登录 IP 限流并记录验证结果
This commit is contained in:
@@ -71,6 +71,31 @@ test('createRateLimitMiddleware supports custom limit responses', () => {
|
||||
assert.deepEqual(res.body, { code: 429, message: 'limited' })
|
||||
})
|
||||
|
||||
test('createRateLimitMiddleware can cap an IP across different accounts', () => {
|
||||
resetRateLimitBucketsForTest()
|
||||
|
||||
const limiter = createRateLimitMiddleware({
|
||||
scope: 'test:ip-wide',
|
||||
windowMs: 60_000,
|
||||
max: 2,
|
||||
})
|
||||
const first = createMockRequest()
|
||||
const second = createMockRequest()
|
||||
const third = createMockRequest()
|
||||
const response = createMockResponse()
|
||||
let nextCount = 0
|
||||
const next: NextFunction = () => {
|
||||
nextCount += 1
|
||||
}
|
||||
|
||||
limiter(first, response, next)
|
||||
limiter(second, response, next)
|
||||
limiter(third, response, next)
|
||||
|
||||
assert.equal(nextCount, 2)
|
||||
assert.equal(response.statusCode, 429)
|
||||
})
|
||||
|
||||
function createMockRequest(): Request {
|
||||
return {
|
||||
ip: '127.0.0.1',
|
||||
|
||||
@@ -15,14 +15,23 @@ import { createJsonHandler, extractBearerToken } from './session.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
const adminLoginIpRateLimit = createRateLimitMiddleware({
|
||||
scope: 'admin:login:ip',
|
||||
windowMs: 60_000,
|
||||
max: 20,
|
||||
})
|
||||
|
||||
const adminLoginAccountRateLimit = createRateLimitMiddleware({
|
||||
scope: 'admin:login:account',
|
||||
windowMs: 60_000,
|
||||
max: 10,
|
||||
key: getBodyFieldRateLimitKey('username'),
|
||||
})
|
||||
|
||||
router.post(
|
||||
'/auth/login',
|
||||
createRateLimitMiddleware({
|
||||
scope: 'admin:login',
|
||||
windowMs: 60_000,
|
||||
max: 10,
|
||||
key: getBodyFieldRateLimitKey('username'),
|
||||
}),
|
||||
adminLoginIpRateLimit,
|
||||
adminLoginAccountRateLimit,
|
||||
createJsonHandler(
|
||||
(req) =>
|
||||
loginAdmin(req.body?.username, req.body?.password, {
|
||||
|
||||
Reference in New Issue
Block a user