httpShield
Official sources are open to Staxis GitLab group members: how to join and view the code.
Repository:
httpShield development
Versions:
tags
and releases
Description
httpShield is the HTTP request-policy layer mounted on serverApp. Its label and typology are both httpShield. It groups traffic monitoring, IP bans, rate limiting, CORS, security headers, charset checks, declared payload-size checks, and path-denial rules. It uses the native Node.js middleware surface as the standard path, with adapters for optional frameworks.
Read before flight
We suggest reviewing the following settings against your application's traffic and deployment.
-
β Traffic and bans: we suggest monitoring the size of the .ipbans file and the growth of in-memory IP and route records. Set rate limits and ban durations to suit your traffic and storage budget, accounting for users who share an IP address. Counters are local to each layer instance.
-
β Headers: we suggest inspecting real response headers for the policy you selected. In native mode, Helmet is skipped by default when its dependency is missing. Install it when you want that header-hardening layer.
-
β CORS and proxies: we suggest checking preflight and ordinary responses from your intended frontend origins. Enable forwarded-client IP handling only behind a trusted proxy that replaces untrusted forwarded headers.
-
β Payloads: we suggest enforcing streamed-body limits in the component that reads the request. Shield's rawlimit checks the declared Content-Length rather than counting bytes consumed from a stream.
-
β Paths: we suggest replacing the supplied denyaccess array when defining denials. Its !/* entry allows every path and takes precedence over deny rules added alongside it.
Files Map
| File | Purpose |
|---|---|
| manifest.json | Declares httpShield and its serverApp requirement |
| configs.js | Provides policy defaults and Guardian dependency and file-access rules |
| main.js | Mounts request checks, maintains state, and publishes diagnostic assets |
| helmet.native.js, helmet.express.js, helmet.fastify.js, helmet.koa.js | Wire security-header dependencies to the chosen HTTP runtime |
| README.md, readme.details.md, readme.why.md | Pack overview, internal reference, and design rationale |
Requirements and Installation
Install through the Manager. The declared pack dependency is serverApp. Its provider manifest must permit httpShield's pack label; the supplied serverApp manifest already does. Prepare the project keys and review integrity records.
manager -> install -> httpShield
Header hardening uses an external dependency even in native Node.js mode. Ensure the dependency for your chosen runtime is installed; inspect what the selected installation profile supplies. The monolithic profile currently declares helmet for this entry.
| Runtime | Header dependency |
|---|---|
| Native Node.js or Express | helmet |
| Fastify | @fastify/helmet |
| Koa | koa-helmet |
// Standard native Node.js path, when not already provisioned
npm install helmet
The pack enables the global Guardian allowBareDeps option and declares these dependency names for httpShield. It also supplies allowedFileAccess with roots=true for its ban file operations. Review that broad pack-level file permission and narrow it to your selected storage location when preparing deployment policy. Existing project rules still need to be preserved.
Stack Order and Automatic Use
Normal application code does not call Shield methods. Configure the pack and let it attach. Put it after serverApp and before routes, static serving, downloads, and other request handlers that should receive its checks. Start httpListener after the application has been prepared.
// config.js -> config.stack (pack labels)
stack: [
'serverApp',
'httpShield',
'someOtherLayer',
'httpListener'
]
These are pack labels in the project's stack; someOtherLayer represents your own consumer pack's manifest.label. The same spelling for httpShield's label and typology does not make these slot names. Its internal Vault request uses httpShield as the requester's label and serverApp as the provider's label, then selects serverApp's typology to obtain the application instance.
Checks are registered in this order: RPS monitoring, IP denial, rate limiting, CORS, Helmet, charset checks, declared payload size, then path denial. An earlier rejection ends the chain. For example, an IP ban or rate-limit response does not reach the later Helmet middleware. Mounting Shield after a handler that already ends the response does not protect that handler.
Configuration
In the project's config.js, settings live under config.serveropt.httpShield. The example below replaces that policy with explicit choices; it is a starting configuration to tune, not a traffic-capacity guarantee. The supplied defaults use rateReqLimit=10, perUrlRules=false, rateBanSteps=false, and denyaccess=['!/*'] instead. Check the final merged denyaccess array so that an inherited !/* does not remain active.
// config.js -> config (merge into the exported object)
serveropt: {
httpShield: {
requireUTF8: true,
helmet: true,
csp: true,
cors: true,
corsMethods: true,
corslist: ['https://frontend.example.test'],
rateWhitelist: [],
rateReqLimit: 20,
rateReqRange: 1000,
perUrlRules: [
{ match: '^POST /api/login$', limit: 5 }
],
rateBanSteps: [10000, 60000, 300000, 900000, 3600000],
resetBan: true,
rpsRangeSec: 10,
rpsThreshold: 300,
uniqueIPsThreshold: 100,
attackHoldFor: 120000,
ipbansFile: false,
ipBanned: [],
rawlimit: 10485760,
denyaccess: ['/private', '/.env$', '/.git']
}
}
Keep positive numeric limits in the documented units. The example deliberately limits login requests below the global per-IP allowance. Check CORS responses and ban storage as part of deployment validation. Restart with reviewed configuration changes; some settings and patterns are captured during attach, while others are read for each request.
RPS Monitoring and Attack Mode
| Setting | Supplied default | Meaning |
|---|---|---|
| rpsRangeSec | 10 seconds | Rolling request-count window; accepts integers from 1 to 60 |
| rpsThreshold | 300 requests/second | Average over the configured window |
| uniqueIPsThreshold | 100 | Distinct observed IPs in the current one-second bucket |
| attackHoldFor | 120000 milliseconds | Minimum hold from the alarm timestamp before a qualifying cooldown |
Attack mode starts only when both the average request rate and the unique-IP count exceed their thresholds. It clears on a subsequent request after both counts have cooled down and the hold interval has elapsed. This monitor observes requests; it does not reject them directly. Attack mode tightens the global per-IP allowance to one quarter, rounded down with a minimum of one, and raises the initial rate-ban escalation level. It does not automatically disable expensive endpoints or change listener timeouts.
Per-IP and Per-URL Rate Limits
rateReqLimit is the per-IP allowance in the sliding interval rateReqRange, expressed in milliseconds. Exceeding an allowance returns 429. A temporary ban can include Retry-After; it is not guaranteed on every escalation response. IPs in rateWhitelist bypass this limiter, but remain subject to the separate IP deny policy and are still counted by the RPS monitor.
perUrlRules contains regular-expression strings matched against METHOD followed by a space and the normalized pathname, without query parameters. The first matching rule applies. Each concrete method/path has its own counter, even if several paths match the same rule. A per-URL rule adds a restriction; it does not increase the global per-IP allowance or combine an entire route group into one shared counter. Use simple, bounded patterns and test them against your actual routes.
rateBanSteps accepts exactly five nonnegative durations in milliseconds. false selects the built-in schedule. resetBan requests escalation cleanup when an expired temporary ban is revisited; it is not a periodic reset or a general command to clear permanent bans.
Client IPs and Ban Storage
The normal IP source is the connection's remote address. When serverApp.trustProxy is truthy, Shield instead accepts the first X-Forwarded-For entry. It does not itself verify the immediate proxy against a trusted-hop list. Enable that mode only behind infrastructure that restricts direct access and replaces untrusted forwarded headers. Shared NAT or proxy addresses can cause multiple users to share the same quota.
ipBanned supplies an exact-address deny list. Shield normalizes common forms, including IPv4-mapped IPv6 and loopback. Configured and loaded permanent bans are checked before rate limiting and return 403. CIDR ranges are not implemented by this list.
ipbansFile=false selects ./.ipbans through engine.fileaccess. In the standard layout, that path resolves beside httpShield's main.js, not at the project root. A custom path is also resolved relative to the calling file and must satisfy Guardian policy. The file is loaded during instance creation; editing it does not automatically reload the running deny set.
Persistence uses synchronous file I/O and a colon-separated address/timestamp format. We suggest keeping a recoverable copy before changing ban data and monitoring file growth. Separate processes do not share live counters or coordinate file updates.
CORS Policy
The current matcher allows the request's own host, localhost, configured serveropt.hostname and serveropt.port values, and entries in corslist. Exact entries without a port match the hostname across ports. Wildcard entries such as *.example.test match subdomains, not the bare domain. Matching is host-based and does not enforce an HTTP-versus-HTTPS distinction. Keep origins narrow; corslist is also reused when building CSP source lists.
Rejected origins receive 403. An accepted OPTIONS request receives 204, echoes the accepted origin, and reports allowed methods and headers with a 600-second preflight cache. The current implementation reflects requested header names. We suggest checking both preflight and ordinary response headers when validating a frontend integration. The current preflight code reads corsMethods and corsHeaders directly from serveropt.
The separate nocors=true branch deliberately uses Access-Control-Allow-Origin: * and bypasses the normal origin and preflight handling. It is a broad policy choice, not an authentication mechanism. CORS controls browser access to responses; routes still need their own authorization. See the CORS reference for the browser-side protocol.
Helmet, CSP, and Nonces
helmet=true asks the selected adapter to mount its header-hardening dependency. csp=true selects the custom CSP profile; csp=false retains the adapter's basic header profile without CSP. helmet=false deliberately omits that header layer. Actual headers also depend on the installed package version and whether the request reaches its middleware.
The custom CSP uses self, blob:, data:, configured host values, and corslist for several resource directives. This does not give every listed host permission to supply scripts: native, Express, and Koa script directives use self plus the nonce, or unsafe-inline when deliberately enabled. Fastify's script-source construction differs. Validate each required resource type in a browser.
In native mode, the adapter generates a per-request nonce and exposes it as res.locals.nonce. A renderer can use that value for deliberately allowed inline scripts. The layer does not rewrite HTML to insert nonce attributes. unsafescripts=true deliberately permits inline scripts instead; choose that relaxation explicitly. Fastify's current adapter does not use the generated nonce in its script directives.
Inspect Content-Security-Policy, X-Content-Type-Options, and the other required headers on actual responses, including early rejections. For header semantics, consult the Helmet documentation.
Charset and Declared Payload Size
requireUTF8=true rejects explicit non-UTF-8 charsets for application/json and text/plain with 415. Missing charsets are accepted, and multipart/form-data passes this check. It checks the Content-Type declaration; it does not validate the actual bytes or sanitize application data. Other media types, including vendor-specific JSON types, are not covered by this charset test.
rawlimit is a numeric byte threshold, supplied as 10485760 bytes (10 MiB). The Shield rejects a larger declared Content-Length with 413. Use a number, not a string such as 10mb. rawlimit=false deliberately disables this declared-length check. Chunked or otherwise uncounted bodies still need a streaming limit in their reader. Framework parsers and httpRestParser have their own limits and execution timing; configure those components as well.
Path Denial Rules
denyaccess matches URL paths, not filesystem locations. Before matching, Shield strips the query, percent-decodes up to twice, changes backslashes to slashes, and applies POSIX path normalization. It compares the resulting path without rewriting req.url for later middleware. Your route and file handlers must apply compatible path handling and their own filesystem boundaries.
| Rule | Meaning |
|---|---|
| /private | Deny that path and its descendants |
| /private/* | Equivalent subtree shorthand |
| /.env$ | Deny exactly /.env |
| !/public | Allow that subtree before evaluating all deny rules |
| /* | Deny all paths unless an allow override matches |
| !/* | Allow all paths, overriding every deny rule |
These are literal path rules with the documented prefix and suffix markers, not arbitrary regular expressions. Allow overrides always win regardless of list order. There is no implicit deny for every dotfile or traversal-looking input: the canonical destination must match a deny rule. For example, the configuration above blocks /public/%2e%2e/private/file after normalization, but only blocks /.git because that path is explicitly listed.
Status and Logs
The published assets contain diagnostics such as DDosRPSWarning and RPSSDdos, which reference RPS state, plus ipBanned, runtimeDeny, runtimeBanned, rateLimiter, cors, helmet, rUTF8, rawlimit, and denyaccess. These diagnostics include snapshots, configuration values, and registration flags; we suggest using request tests and response headers to verify the effective policy.
The supplied httpShield manifest has no permits declaration for consumer access. Normal use requires no Vault request to Shield itself. Adding an authorized diagnostics consumer is a separate manifest-policy decision; there is no public runtime administration API for changing limits or bans. engineopt.audit.logDeeply enables setup and selected decision logs, while alarms and some warnings are logged independently. Logging choices should not be used to determine whether protection is active.
We suggest applying reviewed policy changes through a controlled application restart.
Documentation
This page is the HTML adaptation of the pack's README.md, with practical clarifications checked against the implementation. Complete Staxis onboarding to request GitLab access to the official sources.