mirror of
https://github.com/linux-odyssey/linux-odyssey.git
synced 2026-11-05 19:20:12 +08:00
feat(rate-limiting): implement rate limiting for login attempts and enhance configuration
- Added environment variables for `RATE_LIMIT_MAX_FAILED_ATTEMPTS` and `RATE_LIMIT_LOCKOUT_TIME` - Integrated rate limiting into the login process with a maximum of 5 failed attempts - Refactored login attempt recording into the `authRouter` - Removed deprecated `recordLogin` middleware and adjusted related logic
This commit is contained in:
1 parent
bda68ad293
commit
ccbc4ff4b0
9 files changed
+47
-49
No files matched your search
+3
-3
@@ -24,6 +24,9 @@ ADMIN_PORT=3001
|
|||||||
# TRUSTED_PROXIES=1.2.3.4
|
# TRUSTED_PROXIES=1.2.3.4
|
||||||
# valid configurations see isIP & isIPRange in https://github.com/validatorjs/validator.js?tab=readme-ov-file#validators
|
# valid configurations see isIP & isIPRange in https://github.com/validatorjs/validator.js?tab=readme-ov-file#validators
|
||||||
|
|
||||||
|
# RATE_LIMIT_MAX_FAILED_ATTEMPTS=5
|
||||||
|
# RATE_LIMIT_LOCKOUT_TIME=10
|
||||||
|
|
||||||
# GOOGLE_CLIENT_ID=
|
# GOOGLE_CLIENT_ID=
|
||||||
# GOOGLE_CLIENT_SECRET=
|
# GOOGLE_CLIENT_SECRET=
|
||||||
# GITHUB_CLIENT_ID=
|
# GITHUB_CLIENT_ID=
|
||||||
@@ -31,9 +34,6 @@ ADMIN_PORT=3001
|
|||||||
# SURVEY_URL=
|
# SURVEY_URL=
|
||||||
# BUG_REPORT_URL=
|
# BUG_REPORT_URL=
|
||||||
|
|
||||||
# SURVEY_URL=
|
|
||||||
# BUG_REPORT_URL=
|
|
||||||
|
|
||||||
# Docker related config
|
# Docker related config
|
||||||
# DOCKER_NETWORK=host
|
# DOCKER_NETWORK=host
|
||||||
# QUEST_IMAGE=linuxodyssey/quest-base
|
# QUEST_IMAGE=linuxodyssey/quest-base
|
||||||
|
|||||||
+3
-3
@@ -12,6 +12,9 @@ DOCKER_NETWORK=linux-odyssey-players-dev
|
|||||||
# TRUSTED_PROXIES=1.2.3.4
|
# TRUSTED_PROXIES=1.2.3.4
|
||||||
# valid configurations see isIP & isIPRange in https://github.com/validatorjs/validator.js?tab=readme-ov-file#validators
|
# valid configurations see isIP & isIPRange in https://github.com/validatorjs/validator.js?tab=readme-ov-file#validators
|
||||||
|
|
||||||
|
# RATE_LIMIT_MAX_FAILED_ATTEMPTS=5
|
||||||
|
# RATE_LIMIT_LOCKOUT_TIME=10
|
||||||
|
|
||||||
# GOOGLE_CLIENT_ID=
|
# GOOGLE_CLIENT_ID=
|
||||||
# GOOGLE_CLIENT_SECRET=
|
# GOOGLE_CLIENT_SECRET=
|
||||||
# GITHUB_CLIENT_ID=
|
# GITHUB_CLIENT_ID=
|
||||||
@@ -19,9 +22,6 @@ DOCKER_NETWORK=linux-odyssey-players-dev
|
|||||||
# SURVEY_URL=
|
# SURVEY_URL=
|
||||||
# BUG_REPORT_URL=
|
# BUG_REPORT_URL=
|
||||||
|
|
||||||
# SURVEY_URL=
|
|
||||||
# BUG_REPORT_URL=
|
|
||||||
|
|
||||||
# Docker related config
|
# Docker related config
|
||||||
# DOCKER_NETWORK=host
|
# DOCKER_NETWORK=host
|
||||||
# QUEST_IMAGE=linuxodyssey/quest-base
|
# QUEST_IMAGE=linuxodyssey/quest-base
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ const LoginAttemptSchema = new Schema<LoginAttemptDocument>(
|
|||||||
userAgent: { type: String, required: true },
|
userAgent: { type: String, required: true },
|
||||||
time: { type: Date, default: Date.now, required: true },
|
time: { type: Date, default: Date.now, required: true },
|
||||||
success: { type: Boolean, required: true },
|
success: { type: Boolean, required: true },
|
||||||
message: {type: String}
|
message: { type: String },
|
||||||
},
|
},
|
||||||
{ timestamps: true }
|
{ timestamps: true }
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Router, Request, Response } from 'express'
|
import { Router, Request, Response, Express } from 'express'
|
||||||
import passport from 'passport'
|
import passport from 'passport'
|
||||||
import { recordLogin } from '../../middleware/recordLogin.js'
|
import { NextFunction } from 'express-serve-static-core'
|
||||||
|
import { LoginAttempt } from '../../../../packages/models'
|
||||||
import enabledMethods from '../../auth/passport.js'
|
import enabledMethods from '../../auth/passport.js'
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -17,15 +18,17 @@ import {
|
|||||||
registerFromSessionValidators,
|
registerFromSessionValidators,
|
||||||
registerValidators,
|
registerValidators,
|
||||||
} from '../validators/authValidator.js'
|
} from '../validators/authValidator.js'
|
||||||
import { authenticateRateLimit } from '../../middleware/rateLimiter.js'
|
import {
|
||||||
import { NextFunction } from 'express-serve-static-core'
|
authenticateRateLimit,
|
||||||
import { rateLimitByAccount } from '../../middleware/rateLimiter.js'
|
rateLimitByAccount,
|
||||||
|
} from '../../middleware/rateLimiter.js'
|
||||||
|
|
||||||
const router = Router()
|
const router = Router()
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
'/login',
|
'/login',
|
||||||
rateLimitByAccount,
|
|
||||||
authenticateRateLimit,
|
authenticateRateLimit,
|
||||||
|
rateLimitByAccount,
|
||||||
loginValidators,
|
loginValidators,
|
||||||
(req: Request, res: Response, next: NextFunction): void => {
|
(req: Request, res: Response, next: NextFunction): void => {
|
||||||
passport.authenticate(
|
passport.authenticate(
|
||||||
@@ -42,20 +45,32 @@ router.post(
|
|||||||
return res.status(401).json({ message: msg })
|
return res.status(401).json({ message: msg })
|
||||||
}
|
}
|
||||||
|
|
||||||
req.logIn(user, async (err: unknown) => {
|
req.logIn(user, async (loginErr: unknown) => {
|
||||||
if (err) {
|
if (loginErr) {
|
||||||
await recordLogin(req, false, 'login session failed')
|
await recordLogin(req, false, 'login session failed')
|
||||||
return next(err)
|
return next(loginErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
await recordLogin(req, true, 'login success')
|
await recordLogin(req, true, 'login success')
|
||||||
return res.json({ message: 'success' })
|
return res.json({ message: 'success' })
|
||||||
})
|
})
|
||||||
|
return null
|
||||||
}
|
}
|
||||||
)(req, res, next)
|
)(req, res, next)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async function recordLogin(req: Request, success: boolean, message: string) {
|
||||||
|
await LoginAttempt.create({
|
||||||
|
ip: req.ip,
|
||||||
|
userAgent: req.headers['user-agent'] || '',
|
||||||
|
success,
|
||||||
|
time: new Date(),
|
||||||
|
username: req.body.username,
|
||||||
|
message,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
router.post('/register', authenticateRateLimit, registerValidators, register)
|
router.post('/register', authenticateRateLimit, registerValidators, register)
|
||||||
|
|
||||||
router.post('/register-guest', authenticateRateLimit, registerGuest)
|
router.post('/register-guest', authenticateRateLimit, registerGuest)
|
||||||
|
|||||||
@@ -68,6 +68,13 @@ function createConfig() {
|
|||||||
trustedProxies: getTrustProxies('TRUSTED_PROXIES'),
|
trustedProxies: getTrustProxies('TRUSTED_PROXIES'),
|
||||||
surveyUrl: getUrl('SURVEY_URL'),
|
surveyUrl: getUrl('SURVEY_URL'),
|
||||||
bugReportUrl: getUrl('BUG_REPORT_URL'),
|
bugReportUrl: getUrl('BUG_REPORT_URL'),
|
||||||
|
rateLimit: {
|
||||||
|
maxFailedAttempts: Number(
|
||||||
|
process.env.RATE_LIMIT_MAX_FAILED_ATTEMPTS ?? 5
|
||||||
|
),
|
||||||
|
lockoutTime:
|
||||||
|
Number(process.env.RATE_LIMIT_LOCKOUT_TIME ?? 10) * 60 * 1000,
|
||||||
|
},
|
||||||
|
|
||||||
projectRoot,
|
projectRoot,
|
||||||
|
|
||||||
|
|||||||
@@ -85,7 +85,6 @@ async function main() {
|
|||||||
server.listen(config.port, '0.0.0.0', () => {
|
server.listen(config.port, '0.0.0.0', () => {
|
||||||
logger.info(`Server listening at ${config.baseUrl}`)
|
logger.info(`Server listening at ${config.baseUrl}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((err) => logger.error(err))
|
main().catch((err) => logger.error(err))
|
||||||
@@ -2,8 +2,8 @@ import rateLimit from 'express-rate-limit'
|
|||||||
import type { Options } from 'express-rate-limit'
|
import type { Options } from 'express-rate-limit'
|
||||||
import type { Request, Response, NextFunction } from 'express'
|
import type { Request, Response, NextFunction } from 'express'
|
||||||
import config from '../config.js'
|
import config from '../config.js'
|
||||||
import { recordLogin } from './recordLogin.js'
|
|
||||||
import { LoginAttempt } from '../../../packages/models'
|
import { LoginAttempt } from '../../../packages/models'
|
||||||
|
import logger from '../utils/logger.js'
|
||||||
|
|
||||||
function createRateLimiter(options: Partial<Options>) {
|
function createRateLimiter(options: Partial<Options>) {
|
||||||
if (config.testing.enabled) {
|
if (config.testing.enabled) {
|
||||||
@@ -16,17 +16,10 @@ export const globalRateLimit = createRateLimiter({
|
|||||||
windowMs: 60 * 1000,
|
windowMs: 60 * 1000,
|
||||||
max: 100,
|
max: 100,
|
||||||
})
|
})
|
||||||
export const authenticateRateLimit = config.testing.enabled
|
|
||||||
? (req: Request, res: Response, next: NextFunction) => next()
|
export const authenticateRateLimit = createRateLimiter({
|
||||||
: rateLimit({
|
windowMs: 10 * 1000,
|
||||||
windowMs: 1 * 1000,
|
|
||||||
max: 5,
|
max: 5,
|
||||||
handler: async (req: Request, res: Response, _next: NextFunction) => {
|
|
||||||
recordLogin(req, false, 'rate limit')
|
|
||||||
res.status(429).json({
|
|
||||||
error: 'Too many login attempts. Please try again later.',
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
export const sessionRateLimit = createRateLimiter({
|
export const sessionRateLimit = createRateLimiter({
|
||||||
@@ -52,10 +45,14 @@ export async function rateLimitByAccount(
|
|||||||
const recentFailedCount = await LoginAttempt.countDocuments({
|
const recentFailedCount = await LoginAttempt.countDocuments({
|
||||||
username,
|
username,
|
||||||
success: false,
|
success: false,
|
||||||
|
ip: req.ip,
|
||||||
time: { $gte: since },
|
time: { $gte: since },
|
||||||
})
|
})
|
||||||
|
|
||||||
if (recentFailedCount >= 10) {
|
if (recentFailedCount >= 5) {
|
||||||
|
logger.warn(
|
||||||
|
`Too many failed login attempts for "${username}" from ${req.ip}`
|
||||||
|
)
|
||||||
return res.status(429).json({
|
return res.status(429).json({
|
||||||
error: 'Too many failed login attempts. Please try again later.',
|
error: 'Too many failed login attempts. Please try again later.',
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
import { Request, Response, NextFunction } from 'express'
|
|
||||||
import { LoginAttempt } from '../../../packages/models'
|
|
||||||
|
|
||||||
export async function recordLogin(
|
|
||||||
req: Request,
|
|
||||||
success: boolean,
|
|
||||||
message: string
|
|
||||||
) {
|
|
||||||
await LoginAttempt.create({
|
|
||||||
ip: req.ip,
|
|
||||||
userAgent: req.headers['user-agent'] || '',
|
|
||||||
success,
|
|
||||||
time: new Date(),
|
|
||||||
username: req.body.username,
|
|
||||||
message,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
import { validationResult } from 'express-validator'
|
import { validationResult } from 'express-validator'
|
||||||
import type { Request, Response, NextFunction } from 'express'
|
import type { Request, Response, NextFunction } from 'express'
|
||||||
import { recordLogin } from './recordLogin.js'
|
|
||||||
|
|
||||||
|
|
||||||
export function noError(req: Request, res: Response, next: NextFunction) {
|
export function noError(req: Request, res: Response, next: NextFunction) {
|
||||||
const result = validationResult(req)
|
const result = validationResult(req)
|
||||||
@@ -9,7 +7,6 @@ export function noError(req: Request, res: Response, next: NextFunction) {
|
|||||||
next()
|
next()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
recordLogin(req, false, 'valid error');
|
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
message: 'Validation failed',
|
message: 'Validation failed',
|
||||||
errors: result.array(),
|
errors: result.array(),
|
||||||
|
|||||||
Reference in new issue
Block a user