Skip to content

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.

SecurityDecorator is built by composing 6 mixin classes onto BaseSecurityDecorator:

BaseSecurityDecorator
└── AccessControl
└── RateLimiting
└── Authentication
└── Behavioral
└── ContentFiltering
└── Advanced = SecurityDecorator

Each mixin adds methods to the class. The final SecurityDecorator has all 20 methods available.

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>.

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;
}
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 });

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' });
})
)
);
MethodDescription
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
MethodDescription
requireHttps()Require HTTPS for this route
requireAuth(type?)Require authorization header
apiKeyAuth(headerName?)Require API key header
requireHeaders(headers)Require specific headers
MethodDescription
rateLimit(requests, window?)Per-route rate limit
geoRateLimit(limits)Country-based rate limits
MethodDescription
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
MethodDescription
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
MethodDescription
timeWindow(startTime, endTime)Restrict access to time windows
suspiciousDetection(enabled?)Toggle penetration detection
honeypotDetection(trapFields)Add honeypot form fields