@@ -7,33 +7,24 @@ import {
7
7
useRuntimeConfig ,
8
8
useStorage ,
9
9
} from '#imports'
10
+ import type { RateLimit } from '../types/RateLimit'
10
11
11
12
export default defineEventHandler ( async ( event ) => {
12
13
const config = useRuntimeConfig ( ) . public . nuxtApiShield
13
14
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 ) ) ) ) {
19
17
return
20
18
}
21
19
22
20
const shieldStorage = useStorage ( 'shield' )
23
21
const requestIP = getRequestIP ( event , { xForwardedFor : true } ) || 'unKnownIP'
24
22
const banKey = `ban:${ requestIP } `
25
23
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 )
30
25
31
26
// 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 ) {
37
28
if ( config . retryAfterHeader ) {
38
29
const retryAfter = Math . ceil ( ( bannedUntil - Date . now ( ) ) / 1e3 )
39
30
event . node . res . setHeader ( 'Retry-After' , retryAfter )
@@ -44,20 +35,16 @@ export default defineEventHandler(async (event) => {
44
35
} )
45
36
}
46
37
// 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 ) {
52
39
await shieldStorage . removeItem ( banKey )
53
40
}
54
41
55
42
const ipKey = `ip:${ requestIP } `
56
- const req = await shieldStorage . getItem ( ipKey )
43
+ const req = await shieldStorage . getItem ( ipKey ) as RateLimit
57
44
const now = Date . now ( )
58
45
59
46
// 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 ) {
61
48
// If no record exists, or the duration has expired, reset the counter and timestamp
62
49
await shieldStorage . setItem ( ipKey , {
63
50
count : 1 ,
0 commit comments