Decorators Overview
The SecurityDecorator provides per-route security configuration through 20 chainable methods. Each method returns a higher-order function that wraps a route handler and associates a RouteConfig with it.
How It Works
Section titled “How It Works”Mixin Composition
Section titled “Mixin Composition”SecurityDecorator is built by composing 6 mixin classes onto BaseSecurityDecorator:
BaseSecurityDecorator └── AccessControl └── RateLimiting └── Authentication └── Behavioral └── ContentFiltering └── Advanced = SecurityDecoratorEach mixin adds methods to the class. The final SecurityDecorator has all 20 methods available.
Route ID Assignment
Section titled “Route ID Assignment”Each decorated function gets a unique route ID stored in a WeakMap<Function, string>. This avoids polluting the function object and allows garbage collection. IDs follow the pattern guard_route_N.
When the middleware processes a request, it reads the route ID from request.state.guardRouteId and looks up the corresponding RouteConfig from the decorator’s internal Map<string, RouteConfig>.
RouteConfig
Section titled “RouteConfig”A RouteConfig object holds all per-route settings:
class RouteConfig { rateLimit: number | null = null; rateLimitWindow: number | null = null; ipWhitelist: string[] | null = null; ipBlacklist: string[] | null = null; blockedCountries: string[] | null = null; whitelistCountries: string[] | null = null; bypassedChecks: Set<string> = new Set(); requireHttps: boolean = false; authRequired: string | null = null; customValidators: Array<(request: GuardRequest) => Promise<GuardResponse | null>> = []; blockedUserAgents: string[] = []; requiredHeaders: Record<string, string> = {}; behaviorRules: BehaviorRule[] = []; blockCloudProviders: Set<string> = new Set(); maxRequestSize: number | null = null; allowedContentTypes: string[] | null = null; timeRestrictions: { start: string; end: string } | null = null; enableSuspiciousDetection: boolean = true; requireReferrer: string[] | null = null; apiKeyRequired: boolean = false; sessionLimits: Record<string, number> | null = null; geoRateLimits: Record<string, [number, number]> | null = null;}Creating an Instance
Section titled “Creating an Instance”import { SecurityDecorator, SecurityConfigSchema } from '@guardcore/core';
const config = SecurityConfigSchema.parse({ enableRedis: false, rateLimit: 100, rateLimitWindow: 60,});
const guard = new SecurityDecorator(config);Pass the guard instance to your adapter:
createSecurityMiddleware({ config, guardDecorator: guard });Applying to Handlers
Section titled “Applying to Handlers”Each decorator method returns a function that wraps a route handler:
const handler = guard.rateLimit(5, 60)(async (req, res) => { res.json({ data: 'limited' });});
app.get('/api/resource', handler);Decorators can be chained by nesting:
const handler = guard.rateLimit(5, 60)( guard.requireAuth('bearer')( guard.blockCountries(['CN', 'RU'])(async (req, res) => { res.json({ data: 'protected' }); }) ));All 20 Methods
Section titled “All 20 Methods”Access Control
Section titled “Access Control”| Method | Description |
|---|---|
requireIp(whitelist?, blacklist?) | IP whitelist/blacklist per route |
blockCountries(countries) | Block specific countries |
allowCountries(countries) | Allow only specific countries |
blockClouds(providers?) | Block cloud provider IPs |
bypass(checks) | Bypass specific security checks |
Authentication
Section titled “Authentication”| Method | Description |
|---|---|
requireHttps() | Require HTTPS for this route |
requireAuth(type?) | Require authorization header |
apiKeyAuth(headerName?) | Require API key header |
requireHeaders(headers) | Require specific headers |
Rate Limiting
Section titled “Rate Limiting”| Method | Description |
|---|---|
rateLimit(requests, window?) | Per-route rate limit |
geoRateLimit(limits) | Country-based rate limits |
Behavioral
Section titled “Behavioral”| Method | Description |
|---|---|
usageMonitor(maxCalls, window?, action?) | Monitor endpoint call frequency |
returnMonitor(pattern, maxOccurrences, window?, action?) | Monitor response patterns |
behaviorAnalysis(rules) | Custom behavior rules |
suspiciousFrequency(maxFrequency, window?, action?) | Flag suspicious request frequency |
Content Filtering
Section titled “Content Filtering”| Method | Description |
|---|---|
blockUserAgents(patterns) | Block specific user agents |
contentTypeFilter(allowedTypes) | Restrict content types |
maxRequestSize(sizeBytes) | Limit request body size |
requireReferrer(allowedDomains) | Require valid referrer |
customValidation(validator) | Custom validation function |
Advanced
Section titled “Advanced”| Method | Description |
|---|---|
timeWindow(startTime, endTime) | Restrict access to time windows |
suspiciousDetection(enabled?) | Toggle penetration detection |
honeypotDetection(trapFields) | Add honeypot form fields |