@@ -7,33 +7,24 @@ import {
77 useRuntimeConfig ,
88 useStorage ,
99} from '#imports'
10+ import type { RateLimit } from '../types/RateLimit'
1011
1112export default defineEventHandler ( async ( event ) => {
1213 const config = useRuntimeConfig ( ) . public . nuxtApiShield
1314 const url = getRequestURL ( event )
14- if (
15- ! url ?. pathname ?. startsWith ( '/api/' )
16- || ( config . routes ?. length
17- && ! config . routes . some ( route => url . pathname ?. startsWith ( route ) ) )
18- ) {
15+ if ( ! url ?. pathname ?. startsWith ( '/api/' )
16+ || ( config . routes ?. length && ! config . routes . some ( route => url . pathname ?. startsWith ( route ) ) ) ) {
1917 return
2018 }
2119
2220 const shieldStorage = useStorage ( 'shield' )
2321 const requestIP = getRequestIP ( event , { xForwardedFor : true } ) || 'unKnownIP'
2422 const banKey = `ban:${ requestIP } `
2523 const bannedUntilRaw = await shieldStorage . getItem ( banKey )
26- const bannedUntil
27- = typeof bannedUntilRaw === 'number'
28- ? bannedUntilRaw
29- : Number ( bannedUntilRaw )
24+ const bannedUntil = typeof bannedUntilRaw === 'number' ? bannedUntilRaw : Number ( bannedUntilRaw )
3025
3126 // Check if the user is currently banned
32- if (
33- bannedUntilRaw
34- && ! Number . isNaN ( bannedUntil )
35- && Date . now ( ) < bannedUntil
36- ) {
27+ if ( bannedUntilRaw && ! Number . isNaN ( bannedUntil ) && Date . now ( ) < bannedUntil ) {
3728 if ( config . retryAfterHeader ) {
3829 const retryAfter = Math . ceil ( ( bannedUntil - Date . now ( ) ) / 1e3 )
3930 event . node . res . setHeader ( 'Retry-After' , retryAfter )
@@ -44,20 +35,16 @@ export default defineEventHandler(async (event) => {
4435 } )
4536 }
4637 // Unban the user if the ban has expired
47- else if (
48- bannedUntilRaw
49- && ! Number . isNaN ( bannedUntil )
50- && Date . now ( ) >= bannedUntil
51- ) {
38+ if ( bannedUntilRaw && ! Number . isNaN ( bannedUntil ) && Date . now ( ) >= bannedUntil ) {
5239 await shieldStorage . removeItem ( banKey )
5340 }
5441
5542 const ipKey = `ip:${ requestIP } `
56- const req = await shieldStorage . getItem ( ipKey )
43+ const req = await shieldStorage . getItem ( ipKey ) as RateLimit
5744 const now = Date . now ( )
5845
5946 // Check if a new request is outside the duration window
60- if ( ! req || ( now - req . time ) / 1e3 >= config . limit . duration ) {
47+ if ( ! req || ( now - req . time ) / 1000 >= config . limit . duration ) {
6148 // If no record exists, or the duration has expired, reset the counter and timestamp
6249 await shieldStorage . setItem ( ipKey , {
6350 count : 1 ,
0 commit comments