Skip to content

Commit

Permalink
Introduce user based rate limiting per type and entity
Browse files Browse the repository at this point in the history
  • Loading branch information
ikprk committed Jul 9, 2024
1 parent 9f345b1 commit e13c03f
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 2 deletions.
53 changes: 53 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"p-limit": "3.1.0",
"patch-package": "^6.5.0",
"pg": "8.8.0",
"rolling-rate-limiter": "^0.4.2",
"swagger-ui-express": "^4.6.2",
"tinyld": "^1.3.4",
"type-graphql": "^1.2.0-rc.1",
Expand Down
15 changes: 14 additions & 1 deletion src/auth-server/handlers/registerUserInteraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ import express from 'express'
import { AuthContext } from '../../utils/auth'
import { globalEm } from '../../utils/globalEm'
import { components } from '../generated/api-types'
import { UnauthorizedError } from '../errors'
import { TooManyRequestsError, UnauthorizedError } from '../errors'
import { UserInteractionCount } from '../../model'

import { InMemoryRateLimiter } from 'rolling-rate-limiter'

export const interactionLimiter = new InMemoryRateLimiter({
interval: 1000 * 60 * 5, // 5 minutes
maxInInterval: 1,
})

type ReqParams = Record<string, string>
type ResBody =
| components['schemas']['GenericOkResponseData']
Expand All @@ -26,6 +33,12 @@ export const registerUserInteraction: (
throw new UnauthorizedError('Cannot register interactions for empty session')
}

const isBlocked = await interactionLimiter.limit(`${type}-${entityId}-${session.userId}`)

if (isBlocked) {
throw new TooManyRequestsError('Too many requests for single entity')
}

const em = await globalEm

await em.transaction(async (em) => {
Expand Down
2 changes: 1 addition & 1 deletion src/auth-server/rateLimits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const rateLimitsPerRoute: RateLimitsPerRoute = {
'/register-user-interaction': {
post: {
windowMinutes: 5,
limit: 1,
limit: 30,
},
},
'/anonymous-auth': {
Expand Down

0 comments on commit e13c03f

Please sign in to comment.