feat: add rate limit to session creation

This commit is contained in:
Justin Lin committed 2026-11-03 20:28:04 +11:00
1 parent 9ffcd9fa90
commit b510d18758
5 files changed
+36 -8

No files matched your search

+3
View File
@@ -133,6 +133,7 @@
"passport-google-oidc": "^0.1.0", "passport-google-oidc": "^0.1.0",
"passport-jwt": "^4.0.1", "passport-jwt": "^4.0.1",
"passport-local": "^1.0.0", "passport-local": "^1.0.0",
"rate-limiter-flexible": "^11.2.3",
"socket.io": "^4.7.1", "socket.io": "^4.7.1",
"swagger-ui-express": "^5.0.0", "swagger-ui-express": "^5.0.0",
"validator": "^13.15.22", "validator": "^13.15.22",
@@ -1604,6 +1605,8 @@
"range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="], "range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
"rate-limiter-flexible": ["rate-limiter-flexible@11.2.3", "", {}, "sha512-w4HX4toAsEbu1VksOauZwI9d6URb6/4WqJJ5Hg1bESihMt2KJfQ2iTwvDkhIg+y2HetLh65DGu/8xIkUz/xNPA=="],
"raw-body": ["raw-body@2.5.3", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "unpipe": "~1.0.0" } }, "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA=="], "raw-body": ["raw-body@2.5.3", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "unpipe": "~1.0.0" } }, "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA=="],
"react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="], "react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="],
+1
View File
@@ -38,6 +38,7 @@
"passport-google-oidc": "^0.1.0", "passport-google-oidc": "^0.1.0",
"passport-jwt": "^4.0.1", "passport-jwt": "^4.0.1",
"passport-local": "^1.0.0", "passport-local": "^1.0.0",
"rate-limiter-flexible": "^11.2.3",
"socket.io": "^4.7.1", "socket.io": "^4.7.1",
"swagger-ui-express": "^5.0.0", "swagger-ui-express": "^5.0.0",
"validator": "^13.15.22", "validator": "^13.15.22",
+29 -7
View File
@@ -1,9 +1,12 @@
import rateLimit from 'express-rate-limit' 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 { RateLimiterMemory } from 'rate-limiter-flexible'
import { TRPCError } from '@trpc/server'
import { LoginAttempt } from '@odyssey/models' import { LoginAttempt } from '@odyssey/models'
import config from '../config.js' import config from '../config.js'
import logger from '../utils/logger.js' import logger from '../utils/logger.js'
import { middleware } from '../trpc.js'
function createRateLimiter(options: Partial<Options>) { function createRateLimiter(options: Partial<Options>) {
if (config.testing.enabled) { if (config.testing.enabled) {
@@ -22,13 +25,32 @@ export const authenticateRateLimit = createRateLimiter({
max: 5, max: 5,
}) })
export const sessionRateLimit = createRateLimiter({ export function trpcRateLimit({
windowMs: 10 * 1000, points,
max: 1, duration,
keyGenerator: (req: Request) => { }: {
return req.user ? (req.user as any)._id : req.ip || '' points: number
}, duration: number
}) }) {
const limiter = new RateLimiterMemory({ points, duration })
return middleware(async (opts) => {
if (config.testing.enabled) {
return opts.next()
}
const key = opts.ctx.user?.id ?? opts.ctx.ip ?? ''
try {
await limiter.consume(key)
} catch {
throw new TRPCError({
code: 'TOO_MANY_REQUESTS',
message: 'Too many requests. Please try again later.',
})
}
return opts.next()
})
}
export const sessionRateLimit = trpcRateLimit({ points: 3, duration: 60 })
export async function rateLimitByAccount( export async function rateLimitByAccount(
req: Request, req: Request,
+2
View File
@@ -8,6 +8,7 @@ import config from '../config.js'
import { protectedProcedure, router } from '../trpc.js' import { protectedProcedure, router } from '../trpc.js'
import { questManager } from '../models/quest.js' import { questManager } from '../models/quest.js'
import { genJWT } from '../utils/auth' import { genJWT } from '../utils/auth'
import { sessionRateLimit } from '../middleware/rateLimiter.js'
export type SessionDetail = Awaited<ReturnType<typeof sessionDetail>> export type SessionDetail = Awaited<ReturnType<typeof sessionDetail>>
@@ -47,6 +48,7 @@ async function sessionDetail(session: ISession) {
export const sessionRouter = router({ export const sessionRouter = router({
createSession: protectedProcedure createSession: protectedProcedure
.use(sessionRateLimit)
.input( .input(
z.object({ z.object({
questId: z.string(), questId: z.string(),
+1 -1
View File
@@ -18,7 +18,7 @@ const t = initTRPC.context<AppContext>().create()
* Export reusable router and procedure helpers * Export reusable router and procedure helpers
* that can be used throughout the router * that can be used throughout the router
*/ */
export const { router, procedure: publicProcedure } = t export const { router, procedure: publicProcedure, middleware } = t
export const protectedProcedure = publicProcedure.use(async (opts) => { export const protectedProcedure = publicProcedure.use(async (opts) => {
if (opts.ctx.isAuthenticated() && !('newUser' in opts.ctx.user)) { if (opts.ctx.isAuthenticated() && !('newUser' in opts.ctx.user)) {