@stacksjs/bun-router 0.0.17 → 0.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/container/service-provider.d.ts +3 -3
- package/dist/development/performance-profiler.d.ts +3 -3
- package/dist/development/route-debugger.d.ts +1 -1
- package/dist/development/route-inspector.d.ts +2 -2
- package/dist/observability/integration.d.ts +1 -1
- package/dist/response/macros.d.ts +1 -1
- package/dist/router/index.d.ts +7 -7
- package/dist/router/router.d.ts +0 -32
- package/dist/testing/performance-testing.d.ts +2 -2
- package/dist/testing/test-client.d.ts +1 -1
- package/dist/testing/websocket-testing.d.ts +1 -1
- package/package.json +2 -3
- package/src/auth.ts +0 -489
- package/src/cache/lru-cache.ts +0 -457
- package/src/cache/middleware-memoization.ts +0 -531
- package/src/cache/route-cache-warmer.ts +0 -486
- package/src/cache/sqlite-cache.ts +0 -783
- package/src/cache/streaming-cache.ts +0 -572
- package/src/cli/colors.ts +0 -29
- package/src/cli/index.ts +0 -287
- package/src/cli/middleware.ts +0 -291
- package/src/cli/openapi.ts +0 -407
- package/src/cli/router.ts +0 -188
- package/src/cli/routes.ts +0 -265
- package/src/cli/utils.ts +0 -531
- package/src/cli.ts +0 -5
- package/src/config.ts +0 -322
- package/src/container/container.ts +0 -786
- package/src/container/contextual-binding.ts +0 -606
- package/src/container/decorators.ts +0 -368
- package/src/container/index.ts +0 -49
- package/src/container/service-provider.ts +0 -596
- package/src/development/hot-reload.ts +0 -673
- package/src/development/index.ts +0 -499
- package/src/development/performance-profiler.ts +0 -717
- package/src/development/route-debugger.ts +0 -527
- package/src/development/route-inspector.ts +0 -749
- package/src/development/typescript-utilities.ts +0 -682
- package/src/docs.ts +0 -397
- package/src/errors/circuit-breaker.ts +0 -733
- package/src/errors/error-handler.ts +0 -569
- package/src/errors/error-reporting.ts +0 -672
- package/src/errors/exceptions.ts +0 -536
- package/src/errors/graceful-degradation.ts +0 -623
- package/src/errors/index.ts +0 -21
- package/src/errors/router-errors.ts +0 -632
- package/src/file-serving/static-files.ts +0 -718
- package/src/index.ts +0 -66
- package/src/middleware/auth.ts +0 -220
- package/src/middleware/content_security_policy.ts +0 -215
- package/src/middleware/cors.ts +0 -142
- package/src/middleware/csrf.ts +0 -166
- package/src/middleware/ddos_protection.ts +0 -279
- package/src/middleware/file_security.ts +0 -191
- package/src/middleware/file_upload.ts +0 -275
- package/src/middleware/helmet.ts +0 -268
- package/src/middleware/index.ts +0 -117
- package/src/middleware/input_validation.ts +0 -453
- package/src/middleware/json_body.ts +0 -37
- package/src/middleware/performance_alerting.ts +0 -540
- package/src/middleware/performance_dashboard.ts +0 -661
- package/src/middleware/performance_monitor.ts +0 -945
- package/src/middleware/pipeline.ts +0 -489
- package/src/middleware/rate_limit.ts +0 -251
- package/src/middleware/request_id.ts +0 -36
- package/src/middleware/request_signing.ts +0 -638
- package/src/middleware/request_tracer.ts +0 -653
- package/src/middleware/response_cache.ts +0 -778
- package/src/middleware/security.ts +0 -482
- package/src/middleware/security_suite.ts +0 -257
- package/src/middleware/session.ts +0 -91
- package/src/model-binding/index.ts +0 -18
- package/src/model-binding/model-middleware.ts +0 -425
- package/src/model-binding/model-registry.ts +0 -550
- package/src/model-binding.ts +0 -370
- package/src/model-resolver-factory.ts +0 -106
- package/src/observability/correlation.ts +0 -691
- package/src/observability/health-checks.ts +0 -729
- package/src/observability/index.ts +0 -184
- package/src/observability/integration.ts +0 -548
- package/src/observability/metrics.ts +0 -753
- package/src/observability/tracing.ts +0 -638
- package/src/optimization/bun-utilities.ts +0 -778
- package/src/query-builder-integration.ts +0 -137
- package/src/request/context.ts +0 -109
- package/src/request/enhanced-request.ts +0 -876
- package/src/request/macros.ts +0 -822
- package/src/response/macros.ts +0 -665
- package/src/response/response-factory.ts +0 -596
- package/src/router/api-routes.ts +0 -243
- package/src/router/file-based-routing.ts +0 -697
- package/src/router/file-streaming.ts +0 -383
- package/src/router/fluent-routing.ts +0 -866
- package/src/router/group-organization.ts +0 -229
- package/src/router/handler-resolver.ts +0 -327
- package/src/router/http-methods.ts +0 -407
- package/src/router/index.ts +0 -193
- package/src/router/middleware-groups.ts +0 -222
- package/src/router/middleware-integration.ts +0 -399
- package/src/router/middleware.ts +0 -234
- package/src/router/model-binding.ts +0 -215
- package/src/router/optimized-route-matching.ts +0 -302
- package/src/router/route-building.ts +0 -221
- package/src/router/route-compiler.ts +0 -691
- package/src/router/route-matching.ts +0 -368
- package/src/router/route-trie.ts +0 -450
- package/src/router/router.ts +0 -1616
- package/src/router/server.ts +0 -684
- package/src/router/validation-integration.ts +0 -449
- package/src/router/view-rendering.ts +0 -233
- package/src/router/websocket.ts +0 -100
- package/src/routing/route-caching.ts +0 -402
- package/src/routing/route-throttling.ts +0 -469
- package/src/routing/subdomain-routing.ts +0 -492
- package/src/session/database-store.ts +0 -109
- package/src/session/file-store.ts +0 -148
- package/src/session/index.ts +0 -244
- package/src/session/memory-store.ts +0 -88
- package/src/session/redis-store.ts +0 -93
- package/src/streaming/index.ts +0 -17
- package/src/streaming/sse-handler.ts +0 -482
- package/src/streaming/stream-handler.ts +0 -552
- package/src/testing/auth-testing.ts +0 -448
- package/src/testing/file-upload-testing.ts +0 -543
- package/src/testing/index.ts +0 -10
- package/src/testing/middleware-testing.ts +0 -322
- package/src/testing/model-binding-testing.ts +0 -645
- package/src/testing/performance-testing.ts +0 -738
- package/src/testing/test-client.ts +0 -310
- package/src/testing/test-request.ts +0 -315
- package/src/testing/test-response.ts +0 -332
- package/src/testing/types.ts +0 -224
- package/src/testing/websocket-testing.ts +0 -590
- package/src/types/controller-types.ts +0 -385
- package/src/types/core.ts +0 -683
- package/src/types/middleware-types.ts +0 -422
- package/src/types/request-response-augmentation.ts +0 -489
- package/src/types/route-inference.ts +0 -372
- package/src/types.ts +0 -2123
- package/src/url.ts +0 -131
- package/src/utils/index.ts +0 -1
- package/src/utils/query-preservation.ts +0 -201
- package/src/utils.ts +0 -395
- package/src/validation/validator.ts +0 -688
- package/src/websocket/clustering.ts +0 -769
package/src/middleware/csrf.ts
DELETED
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
import type { EnhancedRequest, NextFunction, SecurityConfig } from '../types'
|
|
2
|
-
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
|
|
3
|
-
import { config } from '../config'
|
|
4
|
-
|
|
5
|
-
/** Maximum number of issued tokens kept for verification (oldest evicted first). */
|
|
6
|
-
const MAX_TOKENS = 10_000
|
|
7
|
-
|
|
8
|
-
/** Token lifetime in milliseconds. */
|
|
9
|
-
const TOKEN_TTL_MS = 2 * 60 * 60 * 1000 // 2 hours
|
|
10
|
-
|
|
11
|
-
export default class Csrf {
|
|
12
|
-
// Issued tokens with their issue timestamp. Bounded (LRU by insertion
|
|
13
|
-
// order) and TTL'd — the previous implementation grew without limit.
|
|
14
|
-
private static tokens = new Map<string, number>()
|
|
15
|
-
|
|
16
|
-
async handle(req: EnhancedRequest, next: NextFunction): Promise<Response> {
|
|
17
|
-
const csrfConfig: Partial<SecurityConfig['csrf']> = config.server?.security?.csrf ?? {}
|
|
18
|
-
|
|
19
|
-
const method = req.method.toUpperCase()
|
|
20
|
-
const ignoredMethods = ['GET', 'HEAD', 'OPTIONS', ...(csrfConfig?.ignoreMethods || [])]
|
|
21
|
-
|
|
22
|
-
if (ignoredMethods.includes(method)) {
|
|
23
|
-
// Safe methods don't need verification, but the response carries a
|
|
24
|
-
// fresh token cookie so the client has something to submit later
|
|
25
|
-
const token = this.generateToken(csrfConfig?.secret || 'csrf-secret')
|
|
26
|
-
|
|
27
|
-
// Continue to next middleware
|
|
28
|
-
const response = await next()
|
|
29
|
-
if (!response) {
|
|
30
|
-
return new Response('Not Found', { status: 404 })
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// Add CSRF token cookie to response
|
|
34
|
-
const cookieName = csrfConfig?.cookie?.name || 'csrf-token'
|
|
35
|
-
const cookieOptions = []
|
|
36
|
-
|
|
37
|
-
cookieOptions.push(`${cookieName}=${token}`)
|
|
38
|
-
cookieOptions.push('Path=/')
|
|
39
|
-
|
|
40
|
-
if (csrfConfig?.cookie?.options?.httpOnly) {
|
|
41
|
-
cookieOptions.push('HttpOnly')
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
if (csrfConfig?.cookie?.options?.secure) {
|
|
45
|
-
cookieOptions.push('Secure')
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
if (csrfConfig?.cookie?.options?.sameSite) {
|
|
49
|
-
cookieOptions.push(`SameSite=${csrfConfig.cookie.options.sameSite}`)
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const newHeaders = new Headers(response.headers)
|
|
53
|
-
newHeaders.append('Set-Cookie', cookieOptions.join('; '))
|
|
54
|
-
|
|
55
|
-
// Store token for verification (bounded + TTL)
|
|
56
|
-
Csrf.storeToken(token)
|
|
57
|
-
|
|
58
|
-
return new Response(response.body, {
|
|
59
|
-
status: response.status,
|
|
60
|
-
statusText: response.statusText,
|
|
61
|
-
headers: newHeaders,
|
|
62
|
-
})
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// Bearer-authed requests can't be CSRF'd — the token doesn't
|
|
66
|
-
// ride on cookies, so a hostile origin can't trick a browser into
|
|
67
|
-
// sending it. Mirrors Laravel Sanctum / Django REST framework /
|
|
68
|
-
// express-csurf semantics. Filed against stacksjs/stacks#1922.
|
|
69
|
-
const authHeader = req.headers.get('authorization') ?? req.headers.get('Authorization')
|
|
70
|
-
if (authHeader && /^Bearer\s+\S/i.test(authHeader)) {
|
|
71
|
-
const response = await next()
|
|
72
|
-
return response || new Response('Not Found', { status: 404 })
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// For unsafe methods, verify the CSRF token
|
|
76
|
-
// Check for token in headers or in the request body
|
|
77
|
-
const rawToken = req.headers.get('X-CSRF-TOKEN')
|
|
78
|
-
|| req.jsonBody?.csrf_token
|
|
79
|
-
|| req.jsonBody?._token
|
|
80
|
-
|| null
|
|
81
|
-
const token = typeof rawToken === 'string' ? rawToken : null
|
|
82
|
-
|
|
83
|
-
// Get token from cookies for comparison
|
|
84
|
-
const cookies = this.parseCookies(req)
|
|
85
|
-
const cookieToken = cookies[csrfConfig?.cookie?.name || 'csrf-token']
|
|
86
|
-
|
|
87
|
-
// Verify the token: double-submit value must match the cookie
|
|
88
|
-
// (constant-time comparison) and must have been issued by us
|
|
89
|
-
if (!token || !cookieToken
|
|
90
|
-
|| !Csrf.safeCompare(token, cookieToken)
|
|
91
|
-
|| !Csrf.isTokenValid(token)) {
|
|
92
|
-
return new Response(
|
|
93
|
-
JSON.stringify({ error: 'CSRF token validation failed' }),
|
|
94
|
-
{
|
|
95
|
-
status: 403,
|
|
96
|
-
headers: { 'Content-Type': 'application/json' },
|
|
97
|
-
},
|
|
98
|
-
)
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Continue to next middleware if token is valid
|
|
102
|
-
const response = await next()
|
|
103
|
-
return response || new Response('Not Found', { status: 404 })
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Constant-time string comparison — a plain `!==` leaks how many leading
|
|
108
|
-
* characters of the token were correct through response timing.
|
|
109
|
-
*/
|
|
110
|
-
private static safeCompare(a: string, b: string): boolean {
|
|
111
|
-
const bufA = Buffer.from(a)
|
|
112
|
-
const bufB = Buffer.from(b)
|
|
113
|
-
if (bufA.length !== bufB.length) {
|
|
114
|
-
return false
|
|
115
|
-
}
|
|
116
|
-
return timingSafeEqual(bufA, bufB)
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
private static storeToken(token: string): void {
|
|
120
|
-
if (Csrf.tokens.size >= MAX_TOKENS) {
|
|
121
|
-
// Evict the oldest issued token (Map preserves insertion order)
|
|
122
|
-
const oldest = Csrf.tokens.keys().next().value
|
|
123
|
-
if (oldest !== undefined) {
|
|
124
|
-
Csrf.tokens.delete(oldest)
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
Csrf.tokens.set(token, Date.now())
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
private static isTokenValid(token: string): boolean {
|
|
131
|
-
const issuedAt = Csrf.tokens.get(token)
|
|
132
|
-
if (issuedAt === undefined) {
|
|
133
|
-
return false
|
|
134
|
-
}
|
|
135
|
-
if (Date.now() - issuedAt > TOKEN_TTL_MS) {
|
|
136
|
-
Csrf.tokens.delete(token)
|
|
137
|
-
return false
|
|
138
|
-
}
|
|
139
|
-
return true
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
private generateToken(secret: string): string {
|
|
143
|
-
const randomString = randomBytes(16).toString('hex')
|
|
144
|
-
return createHash('sha256')
|
|
145
|
-
.update(`${randomString}${secret}`)
|
|
146
|
-
.digest('hex')
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
private parseCookies(req: Request): Record<string, string> {
|
|
150
|
-
const cookieHeader = req.headers.get('cookie')
|
|
151
|
-
if (!cookieHeader)
|
|
152
|
-
return {}
|
|
153
|
-
|
|
154
|
-
const cookies: Record<string, string> = {}
|
|
155
|
-
for (const cookie of cookieHeader.split(';')) {
|
|
156
|
-
const eqIndex = cookie.indexOf('=')
|
|
157
|
-
if (eqIndex === -1)
|
|
158
|
-
continue
|
|
159
|
-
const name = cookie.slice(0, eqIndex).trim()
|
|
160
|
-
if (!name)
|
|
161
|
-
continue
|
|
162
|
-
cookies[name] = cookie.slice(eqIndex + 1).trim()
|
|
163
|
-
}
|
|
164
|
-
return cookies
|
|
165
|
-
}
|
|
166
|
-
}
|
|
@@ -1,279 +0,0 @@
|
|
|
1
|
-
import type { EnhancedRequest, NextFunction } from '../types'
|
|
2
|
-
import { config } from '../config'
|
|
3
|
-
|
|
4
|
-
export interface DDoSProtectionOptions {
|
|
5
|
-
enabled?: boolean
|
|
6
|
-
maxRequestsPerSecond?: number
|
|
7
|
-
maxRequestsPerMinute?: number
|
|
8
|
-
maxRequestsPerHour?: number
|
|
9
|
-
burstLimit?: number
|
|
10
|
-
windowSize?: number
|
|
11
|
-
blockDuration?: number
|
|
12
|
-
whitelistedIPs?: string[]
|
|
13
|
-
blacklistedIPs?: string[]
|
|
14
|
-
trustProxy?: boolean
|
|
15
|
-
skipSuccessfulRequests?: boolean
|
|
16
|
-
skipFailedRequests?: boolean
|
|
17
|
-
keyGenerator?: (req: EnhancedRequest) => string
|
|
18
|
-
onLimitReached?: (req: EnhancedRequest, rateLimitInfo: DDoSRateLimitInfo) => Response | Promise<Response>
|
|
19
|
-
store?: 'memory' | 'redis'
|
|
20
|
-
redis?: {
|
|
21
|
-
url: string
|
|
22
|
-
prefix?: string
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
interface RequestInfo {
|
|
27
|
-
count: number
|
|
28
|
-
firstRequest: number
|
|
29
|
-
lastRequest: number
|
|
30
|
-
blocked: boolean
|
|
31
|
-
blockExpires?: number
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Rate-limit details passed to `onLimitReached` when a client is blocked.
|
|
36
|
-
*/
|
|
37
|
-
export interface DDoSRateLimitInfo extends RequestInfo {
|
|
38
|
-
/** Seconds until the block lifts (mirrors the Retry-After header) */
|
|
39
|
-
retryAfter: number
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export default class DDoSProtection {
|
|
43
|
-
private options: DDoSProtectionOptions
|
|
44
|
-
private requestStore: Map<string, RequestInfo> = new Map()
|
|
45
|
-
private cleanupInterval: ReturnType<typeof setInterval> | null = null
|
|
46
|
-
|
|
47
|
-
constructor(options: DDoSProtectionOptions = {}) {
|
|
48
|
-
const ddosConfig = config.server?.security?.ddos || {}
|
|
49
|
-
|
|
50
|
-
this.options = {
|
|
51
|
-
enabled: options.enabled ?? ddosConfig.enabled ?? true,
|
|
52
|
-
maxRequestsPerSecond: options.maxRequestsPerSecond ?? ddosConfig.maxRequestsPerSecond ?? 10,
|
|
53
|
-
maxRequestsPerMinute: options.maxRequestsPerMinute ?? ddosConfig.maxRequestsPerMinute ?? 100,
|
|
54
|
-
maxRequestsPerHour: options.maxRequestsPerHour ?? ddosConfig.maxRequestsPerHour ?? 1000,
|
|
55
|
-
burstLimit: options.burstLimit ?? ddosConfig.burstLimit ?? 20,
|
|
56
|
-
windowSize: options.windowSize ?? ddosConfig.windowSize ?? 60000, // 1 minute
|
|
57
|
-
blockDuration: options.blockDuration ?? ddosConfig.blockDuration ?? 300000, // 5 minutes
|
|
58
|
-
whitelistedIPs: options.whitelistedIPs ?? ddosConfig.whitelistedIPs ?? [],
|
|
59
|
-
blacklistedIPs: options.blacklistedIPs ?? ddosConfig.blacklistedIPs ?? [],
|
|
60
|
-
trustProxy: options.trustProxy ?? ddosConfig.trustProxy ?? true,
|
|
61
|
-
skipSuccessfulRequests: options.skipSuccessfulRequests ?? ddosConfig.skipSuccessfulRequests ?? false,
|
|
62
|
-
skipFailedRequests: options.skipFailedRequests ?? ddosConfig.skipFailedRequests ?? false,
|
|
63
|
-
keyGenerator: options.keyGenerator ?? this.defaultKeyGenerator.bind(this),
|
|
64
|
-
onLimitReached: options.onLimitReached,
|
|
65
|
-
store: options.store ?? ddosConfig.store ?? 'memory',
|
|
66
|
-
redis: options.redis ?? ddosConfig.redis,
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// Start cleanup interval for memory store
|
|
70
|
-
if (this.options.store === 'memory') {
|
|
71
|
-
this.startCleanupInterval()
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
private defaultKeyGenerator(req: EnhancedRequest): string {
|
|
76
|
-
const forwarded = req.headers.get('x-forwarded-for')
|
|
77
|
-
const realIP = req.headers.get('x-real-ip')
|
|
78
|
-
const cfIP = req.headers.get('cf-connecting-ip')
|
|
79
|
-
|
|
80
|
-
if (this.options.trustProxy && forwarded) {
|
|
81
|
-
return forwarded.split(',')[0].trim()
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
return realIP || cfIP || 'unknown'
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
private startCleanupInterval(): void {
|
|
88
|
-
this.cleanupInterval = setInterval(() => {
|
|
89
|
-
const now = Date.now()
|
|
90
|
-
for (const [key, info] of this.requestStore.entries()) {
|
|
91
|
-
// Remove expired entries
|
|
92
|
-
if (now - info.lastRequest > this.options.windowSize! * 2) {
|
|
93
|
-
this.requestStore.delete(key)
|
|
94
|
-
}
|
|
95
|
-
// Remove expired blocks
|
|
96
|
-
if (info.blocked && info.blockExpires && now > info.blockExpires) {
|
|
97
|
-
info.blocked = false
|
|
98
|
-
info.blockExpires = undefined
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
}, this.options.windowSize! / 2) // Cleanup every half window
|
|
102
|
-
// Background housekeeping must not keep the process alive
|
|
103
|
-
this.cleanupInterval.unref?.()
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
private isWhitelisted(ip: string): boolean {
|
|
107
|
-
return this.options.whitelistedIPs?.includes(ip) ?? false
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
private isBlacklisted(ip: string): boolean {
|
|
111
|
-
return this.options.blacklistedIPs?.includes(ip) ?? false
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
private getRateLimitInfo(key: string, now: number): RequestInfo {
|
|
115
|
-
let info = this.requestStore.get(key)
|
|
116
|
-
|
|
117
|
-
if (!info) {
|
|
118
|
-
// Hard cap on tracked clients: a spoofed-IP flood would otherwise
|
|
119
|
-
// grow the store faster than the interval cleanup can drain it.
|
|
120
|
-
// Evicting the oldest entries (Map insertion order) only resets
|
|
121
|
-
// counters for long-idle clients.
|
|
122
|
-
if (this.requestStore.size >= 100_000) {
|
|
123
|
-
let toEvict = Math.ceil(this.requestStore.size / 10)
|
|
124
|
-
for (const oldestKey of this.requestStore.keys()) {
|
|
125
|
-
this.requestStore.delete(oldestKey)
|
|
126
|
-
if (--toEvict <= 0) {
|
|
127
|
-
break
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
info = {
|
|
133
|
-
count: 0,
|
|
134
|
-
firstRequest: now,
|
|
135
|
-
lastRequest: now,
|
|
136
|
-
blocked: false,
|
|
137
|
-
}
|
|
138
|
-
this.requestStore.set(key, info)
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// Reset count if window has passed
|
|
142
|
-
if (now - info.firstRequest > this.options.windowSize!) {
|
|
143
|
-
info.count = 0
|
|
144
|
-
info.firstRequest = now
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
return info
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
private shouldBlock(info: RequestInfo, now: number): boolean {
|
|
151
|
-
// Check if already blocked and block hasn't expired
|
|
152
|
-
if (info.blocked && info.blockExpires && now < info.blockExpires) {
|
|
153
|
-
return true
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// Check burst limit (requests per second)
|
|
157
|
-
const _secondWindow = 1000
|
|
158
|
-
const recentRequests = info.count // Simplified for this implementation
|
|
159
|
-
if (recentRequests > this.options.burstLimit!) {
|
|
160
|
-
return true
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// Check requests per minute
|
|
164
|
-
if (info.count > this.options.maxRequestsPerMinute!) {
|
|
165
|
-
return true
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
return false
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
private blockIP(info: RequestInfo, now: number): void {
|
|
172
|
-
info.blocked = true
|
|
173
|
-
info.blockExpires = now + this.options.blockDuration!
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
private createBlockedResponse(req: EnhancedRequest, info: RequestInfo): Response | Promise<Response> {
|
|
177
|
-
const retryAfter = Math.ceil((info.blockExpires! - Date.now()) / 1000)
|
|
178
|
-
|
|
179
|
-
const headers = {
|
|
180
|
-
'Retry-After': retryAfter.toString(),
|
|
181
|
-
'X-RateLimit-Limit': this.options.maxRequestsPerMinute!.toString(),
|
|
182
|
-
'X-RateLimit-Remaining': '0',
|
|
183
|
-
'X-RateLimit-Reset': Math.ceil(info.blockExpires! / 1000).toString(),
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
if (this.options.onLimitReached) {
|
|
187
|
-
return this.options.onLimitReached(req, { ...info, retryAfter })
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
return new Response(JSON.stringify({
|
|
191
|
-
error: 'Too Many Requests',
|
|
192
|
-
message: 'Rate limit exceeded. Please try again later.',
|
|
193
|
-
retryAfter,
|
|
194
|
-
}), {
|
|
195
|
-
status: 429,
|
|
196
|
-
headers: {
|
|
197
|
-
'Content-Type': 'application/json',
|
|
198
|
-
...headers,
|
|
199
|
-
},
|
|
200
|
-
})
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
async handle(req: EnhancedRequest, next: NextFunction): Promise<Response> {
|
|
204
|
-
// Skip if DDoS protection is disabled
|
|
205
|
-
if (!this.options.enabled) {
|
|
206
|
-
const response = await next()
|
|
207
|
-
return response || new Response('Not Found', { status: 404 })
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
const now = Date.now()
|
|
211
|
-
const key = this.options.keyGenerator!(req)
|
|
212
|
-
|
|
213
|
-
// Check if IP is whitelisted
|
|
214
|
-
if (this.isWhitelisted(key)) {
|
|
215
|
-
const response = await next()
|
|
216
|
-
return response || new Response('Not Found', { status: 404 })
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// Check if IP is blacklisted
|
|
220
|
-
if (this.isBlacklisted(key)) {
|
|
221
|
-
return new Response('Access Denied', { status: 403 })
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// Get rate limit info
|
|
225
|
-
const info = this.getRateLimitInfo(key, now)
|
|
226
|
-
|
|
227
|
-
// Check if should block
|
|
228
|
-
if (this.shouldBlock(info, now)) {
|
|
229
|
-
this.blockIP(info, now)
|
|
230
|
-
return this.createBlockedResponse(req, info)
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// Increment request count
|
|
234
|
-
info.count++
|
|
235
|
-
info.lastRequest = now
|
|
236
|
-
|
|
237
|
-
// Process request
|
|
238
|
-
const response = await next()
|
|
239
|
-
|
|
240
|
-
if (!response) {
|
|
241
|
-
return new Response('Not Found', { status: 404 })
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// Skip counting based on response status if configured
|
|
245
|
-
if (this.options.skipSuccessfulRequests && response.status < 400) {
|
|
246
|
-
info.count--
|
|
247
|
-
}
|
|
248
|
-
if (this.options.skipFailedRequests && response.status >= 400) {
|
|
249
|
-
info.count--
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
// Add rate limit headers
|
|
253
|
-
const headers = new Headers(response.headers)
|
|
254
|
-
headers.set('X-RateLimit-Limit', this.options.maxRequestsPerMinute!.toString())
|
|
255
|
-
headers.set('X-RateLimit-Remaining', Math.max(0, this.options.maxRequestsPerMinute! - info.count).toString())
|
|
256
|
-
headers.set('X-RateLimit-Reset', Math.ceil((info.firstRequest + this.options.windowSize!) / 1000).toString())
|
|
257
|
-
|
|
258
|
-
return new Response(response.body, {
|
|
259
|
-
status: response.status,
|
|
260
|
-
statusText: response.statusText,
|
|
261
|
-
headers,
|
|
262
|
-
})
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// Cleanup method
|
|
266
|
-
destroy(): void {
|
|
267
|
-
if (this.cleanupInterval) {
|
|
268
|
-
clearInterval(this.cleanupInterval)
|
|
269
|
-
this.cleanupInterval = null
|
|
270
|
-
}
|
|
271
|
-
this.requestStore.clear()
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// Factory function for easy use
|
|
276
|
-
export function ddosProtection(options: DDoSProtectionOptions = {}): (req: EnhancedRequest, next: NextFunction) => Promise<Response> {
|
|
277
|
-
const instance = new DDoSProtection(options)
|
|
278
|
-
return async (req: EnhancedRequest, next: NextFunction) => instance.handle(req, next)
|
|
279
|
-
}
|
|
@@ -1,191 +0,0 @@
|
|
|
1
|
-
import type { UploadedFile } from './file_upload'
|
|
2
|
-
|
|
3
|
-
export interface FileSecurityConfig {
|
|
4
|
-
scanForMalware?: boolean
|
|
5
|
-
checkMagicNumbers?: boolean
|
|
6
|
-
sanitizeFilenames?: boolean
|
|
7
|
-
preventExecutableUploads?: boolean
|
|
8
|
-
maxFilenameLength?: number
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export default class FileSecurity {
|
|
12
|
-
private config: Required<FileSecurityConfig>
|
|
13
|
-
|
|
14
|
-
// Common file signatures (magic numbers)
|
|
15
|
-
private readonly FILE_SIGNATURES: Record<string, Uint8Array[]> = {
|
|
16
|
-
'image/jpeg': [
|
|
17
|
-
new Uint8Array([0xFF, 0xD8, 0xFF]),
|
|
18
|
-
],
|
|
19
|
-
'image/png': [
|
|
20
|
-
new Uint8Array([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]),
|
|
21
|
-
],
|
|
22
|
-
'image/gif': [
|
|
23
|
-
new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x37, 0x61]),
|
|
24
|
-
new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61]),
|
|
25
|
-
],
|
|
26
|
-
'application/pdf': [
|
|
27
|
-
new Uint8Array([0x25, 0x50, 0x44, 0x46]),
|
|
28
|
-
],
|
|
29
|
-
'application/zip': [
|
|
30
|
-
new Uint8Array([0x50, 0x4B, 0x03, 0x04]),
|
|
31
|
-
new Uint8Array([0x50, 0x4B, 0x05, 0x06]),
|
|
32
|
-
new Uint8Array([0x50, 0x4B, 0x07, 0x08]),
|
|
33
|
-
],
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// Dangerous file extensions
|
|
37
|
-
private readonly EXECUTABLE_EXTENSIONS = [
|
|
38
|
-
'.exe',
|
|
39
|
-
'.bat',
|
|
40
|
-
'.cmd',
|
|
41
|
-
'.com',
|
|
42
|
-
'.pif',
|
|
43
|
-
'.scr',
|
|
44
|
-
'.vbs',
|
|
45
|
-
'.js',
|
|
46
|
-
'.jar',
|
|
47
|
-
'.app',
|
|
48
|
-
'.deb',
|
|
49
|
-
'.pkg',
|
|
50
|
-
'.dmg',
|
|
51
|
-
'.sh',
|
|
52
|
-
'.ps1',
|
|
53
|
-
'.msi',
|
|
54
|
-
'.dll',
|
|
55
|
-
]
|
|
56
|
-
|
|
57
|
-
constructor(config: FileSecurityConfig = {}) {
|
|
58
|
-
this.config = {
|
|
59
|
-
scanForMalware: config.scanForMalware ?? false,
|
|
60
|
-
checkMagicNumbers: config.checkMagicNumbers ?? true,
|
|
61
|
-
sanitizeFilenames: config.sanitizeFilenames ?? true,
|
|
62
|
-
preventExecutableUploads: config.preventExecutableUploads ?? true,
|
|
63
|
-
maxFilenameLength: config.maxFilenameLength ?? 255,
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
validateFile(file: UploadedFile): { isValid: boolean, errors: string[] } {
|
|
68
|
-
const errors: string[] = []
|
|
69
|
-
|
|
70
|
-
// Check filename length
|
|
71
|
-
if (file.originalName.length > this.config.maxFilenameLength) {
|
|
72
|
-
errors.push(`Filename too long (max ${this.config.maxFilenameLength} characters)`)
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// Check for dangerous filename patterns (but don't reject if we're sanitizing)
|
|
76
|
-
if (this.config.sanitizeFilenames) {
|
|
77
|
-
const sanitizedName = this.sanitizeFilename(file.originalName)
|
|
78
|
-
// Only error if sanitization results in empty filename
|
|
79
|
-
if (!sanitizedName || sanitizedName.length === 0) {
|
|
80
|
-
errors.push('Filename is invalid or empty after sanitization')
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Check for executable files
|
|
85
|
-
if (this.config.preventExecutableUploads) {
|
|
86
|
-
const extension = this.getFileExtension(file.originalName).toLowerCase()
|
|
87
|
-
if (this.EXECUTABLE_EXTENSIONS.includes(extension)) {
|
|
88
|
-
errors.push('Executable files are not allowed')
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// Validate file signature (magic numbers)
|
|
93
|
-
if (this.config.checkMagicNumbers) {
|
|
94
|
-
const isValidSignature = this.validateFileSignature(file)
|
|
95
|
-
if (!isValidSignature) {
|
|
96
|
-
errors.push('File signature does not match declared MIME type')
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// Basic malware scan (simple heuristics)
|
|
101
|
-
if (this.config.scanForMalware) {
|
|
102
|
-
const malwareDetected = this.basicMalwareScan(file)
|
|
103
|
-
if (malwareDetected) {
|
|
104
|
-
errors.push('Potential malware detected')
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
return {
|
|
109
|
-
isValid: errors.length === 0,
|
|
110
|
-
errors,
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
private validateFileSignature(file: UploadedFile): boolean {
|
|
115
|
-
const signatures = this.FILE_SIGNATURES[file.mimetype]
|
|
116
|
-
if (!signatures) {
|
|
117
|
-
// If we don't have signatures for this MIME type, allow it
|
|
118
|
-
return true
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const fileBuffer = new Uint8Array(file.buffer.slice(0, 16)) // Check first 16 bytes
|
|
122
|
-
|
|
123
|
-
return signatures.some((signature) => {
|
|
124
|
-
if (fileBuffer.length < signature.length)
|
|
125
|
-
return false
|
|
126
|
-
|
|
127
|
-
for (let i = 0; i < signature.length; i++) {
|
|
128
|
-
if (fileBuffer[i] !== signature[i])
|
|
129
|
-
return false
|
|
130
|
-
}
|
|
131
|
-
return true
|
|
132
|
-
})
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
private sanitizeFilename(filename: string): string {
|
|
136
|
-
// Remove or replace dangerous characters
|
|
137
|
-
return filename
|
|
138
|
-
// eslint-disable-next-line no-control-regex
|
|
139
|
-
.replace(/[<>:"/\\|?*\u0000-\u001F]/u, '_') // Replace dangerous chars with underscore
|
|
140
|
-
.replace(/^\.+/, '') // Remove leading dots
|
|
141
|
-
.replace(/\.+$/, '') // Remove trailing dots
|
|
142
|
-
.replace(/\s+/g, '_') // Replace spaces with underscores
|
|
143
|
-
.substring(0, this.config.maxFilenameLength) // Truncate if too long
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
private getFileExtension(filename: string): string {
|
|
147
|
-
const lastDotIndex = filename.lastIndexOf('.')
|
|
148
|
-
return lastDotIndex === -1 ? '' : filename.substring(lastDotIndex)
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
private basicMalwareScan(file: UploadedFile): boolean {
|
|
152
|
-
// Simple heuristic-based malware detection
|
|
153
|
-
const buffer = new Uint8Array(file.buffer)
|
|
154
|
-
const content = new TextDecoder('utf-8', { fatal: false }).decode(buffer)
|
|
155
|
-
|
|
156
|
-
// Check for common malware patterns (very basic)
|
|
157
|
-
const malwarePatterns = [
|
|
158
|
-
/eval\s*\(/gi,
|
|
159
|
-
/document\.write/gi,
|
|
160
|
-
/window\.location/gi,
|
|
161
|
-
/<script[^>]*>/gi,
|
|
162
|
-
/javascript:/gi,
|
|
163
|
-
/vbscript:/gi,
|
|
164
|
-
/onload\s*=/gi,
|
|
165
|
-
/onerror\s*=/gi,
|
|
166
|
-
]
|
|
167
|
-
|
|
168
|
-
return malwarePatterns.some(pattern => pattern.test(content))
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// Utility method to get safe filename
|
|
172
|
-
getSafeFilename(originalName: string): string {
|
|
173
|
-
return this.sanitizeFilename(originalName)
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// Check if file type is allowed based on whitelist
|
|
177
|
-
isAllowedFileType(mimetype: string, allowedTypes: string[]): boolean {
|
|
178
|
-
if (allowedTypes.length === 0)
|
|
179
|
-
return true
|
|
180
|
-
return allowedTypes.includes(mimetype)
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// Check file size limits
|
|
184
|
-
isWithinSizeLimit(fileSize: number, maxSize: number): boolean {
|
|
185
|
-
return fileSize <= maxSize
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
export function createFileSecurity(config: FileSecurityConfig = {}): FileSecurity {
|
|
190
|
-
return new FileSecurity(config)
|
|
191
|
-
}
|