@pronghorn/shield
Shield
Shield is a lightweight, TypeScript-first security header middleware built as an external plugin for Pronghorn. It sets Content-Security-Policy, Strict-Transport-Security, X-Frame-Options, and other hardening headers with secure-by-default settings, filling the gap left by Pronghorn's built-in cors middleware, which only ever handled cross-origin headers.
Built as a standalone package (
@pronghorn/shield), the Pronghorn equivalent of Express'shelmet, pairs naturally withcorsin the global middleware chain.
Why Shield
Pronghorn ships cors for cross-origin headers, but nothing for the broader set of response headers that protect against clickjacking, MIME-sniffing, protocol downgrade attacks, and unsafe script/style injection. Shield closes that gap with secure defaults out of the box.
- Sets
Content-Security-Policywith adefault-src 'none'whitelist baseline, merged with any directives you provide. - Sets
Strict-Transport-Securityto force HTTPS on repeat visits, with configurablemax-age, subdomain inclusion, and preload support. - Sets
X-Frame-Options,X-Content-Type-Options,Referrer-Policy, andPermissions-Policy. - Strips
X-Powered-Byto avoid leaking framework fingerprints. - Every directive can be disabled individually by passing
false, nothing is forced on you. - Zero runtime dependencies,
pronghornis only a peer dependency for types.
Installation
bun add @pronghorn/shield
Requires Bun >=1.3.0 and pronghorn >=0.1.2 as a peer dependency (used for typing the middleware only).
Quick Start
import { createApp, cors } from 'pronghorn'
import { shield } from '@pronghorn/shield'
const app = createApp()
app.use(cors)
app.use(shield())
app.get('/', context => context.json({ message: 'Secured by Shield 🛡️' }))
await app.listen(4000)
Register shield alongside (and typically after) cors, since it rebuilds the response with merged headers, the same ordering pattern used by @pronghorn/cookie.
Core Concepts
Content Security Policy
Shield ships a restrictive default-src 'none' baseline. Pass directives to merge your own allowlists on top of it, only the keys you provide are overridden, the rest keep their secure defaults.
app.use(shield({
contentSecurityPolicy: {
directives: {
'script-src': ["'self'", 'https://cdn.example.com'],
'img-src': ["'self'", 'data:', 'https:'],
'connect-src': ["'self'", 'https://api.example.com']
}
}
}))
Set reportOnly: true to send Content-Security-Policy-Report-Only instead, useful for testing a policy without enforcing it yet.
app.use(shield({
contentSecurityPolicy: { reportOnly: true, directives: { 'script-src': ["'self'"] } }
}))
Disable CSP entirely by passing false.
app.use(shield({ contentSecurityPolicy: false }))
Strict Transport Security
Forces browsers to only connect over HTTPS for the configured duration. Defaults to one year with subdomains included.
app.use(shield({
strictTransportSecurity: { maxAge: 63_072_000, includeSubDomains: true, preload: true }
}))
Frame options
Prevents your app from being embedded in an <iframe> on another origin, mitigating clickjacking. Defaults to DENY.
app.use(shield({ frameOptions: 'SAMEORIGIN' }))
MIME sniffing protection
Sets X-Content-Type-Options: nosniff, stopping browsers from guessing a response's content type and executing it as something other than declared. Enabled by default.
app.use(shield({ noSniff: false })) // opt out if you have a specific reason to
Referrer policy
Controls how much referrer information is sent on outgoing requests/navigations. Defaults to strict-origin-when-cross-origin.
app.use(shield({ referrerPolicy: 'no-referrer' }))
Permissions policy
Restricts which browser features (camera, geolocation, etc.) your app is allowed to use, and whether embedded content can use them.
app.use(shield({
permissionsPolicy: {
geolocation: [],
camera: ["'self'"],
microphone: []
}
}))
Hiding the framework fingerprint
Strips any X-Powered-By header before the response leaves your server. Enabled by default.
app.use(shield({ hidePoweredBy: false }))
Middleware Options
| Option | Type | Default | Description |
|---|---|---|---|
contentSecurityPolicy |
ContentSecurityPolicyOptions | false |
{} (secure baseline) |
Content-Security-Policy configuration, or false to disable |
strictTransportSecurity |
StrictTransportSecurityOptions | false |
{} (1 year, subdomains) |
Strict-Transport-Security configuration, or false to disable |
frameOptions |
'DENY' | 'SAMEORIGIN' | false |
'DENY' |
X-Frame-Options value, or false to disable |
noSniff |
boolean |
true |
Sets X-Content-Type-Options: nosniff |
referrerPolicy |
ReferrerPolicy | false |
'strict-origin-when-cross-origin' |
Referrer-Policy value, or false to disable |
hidePoweredBy |
boolean |
true |
Removes the X-Powered-By header if present |
permissionsPolicy |
Record<string, string[]> | false |
undefined (not set) |
Permissions-Policy feature allowlist map |
ContentSecurityPolicyOptions
| Property | Type | Description |
|---|---|---|
directives |
Record<string, string[]> |
Directive-to-allowlist map, merged over the secure baseline |
reportOnly |
boolean |
Sends Content-Security-Policy-Report-Only instead of enforcing |
StrictTransportSecurityOptions
| Property | Type | Default | Description |
|---|---|---|---|
maxAge |
number |
31536000 (1 year) |
Duration in seconds browsers should remember to use HTTPS only |
includeSubDomains |
boolean |
true |
Applies the policy to all subdomains |
preload |
boolean |
false |
Opts into browser HSTS preload lists |
API Reference
shield(options?: ShieldOptions): Middleware — global middleware factory, register via app.use(shield(options)).
Lower-level header builders are also exported for advanced use outside the middleware:
import { buildCspHeader, buildHstsHeader, buildPermissionsPolicyHeader } from '@pronghorn/shield'
const csp = buildCspHeader({ directives: { 'script-src': ["'self'"] } })
const hsts = buildHstsHeader({ maxAge: 31_536_000, preload: true })
const permissions = buildPermissionsPolicyHeader({ camera: [] })
Architecture
Shield is split into two modules, each with a single responsibility.
| Module | Responsibility |
|---|---|
directives.ts |
Builds individual header value strings (CSP, HSTS, Permissions-Policy) from structured options |
middleware.ts |
Applies each enabled header to the response, rebuilding it with a merged Headers object since immutable responses (e.g. from Response.json()) can't have headers mutated directly |
Shield rebuilds the response the same way @pronghorn/cookie and Pronghorn's built-in cors middleware do, by constructing a new Response with the original body, status, and a merged Headers instance, rather than calling .set() on the original response's headers.
Security Notes
- Start with the default
default-src 'none'CSP baseline and add only the directives your app actually needs, an overly permissive CSP defeats its own purpose. - Use
reportOnly: truewhen rolling out a new CSP to production, to catch violations via browser reports before enforcing the policy. - Always enable
strictTransportSecurityin production once your app is fully served over HTTPS, enabling it prematurely on a mixed HTTP/HTTPS setup can lock out HTTP-only clients. preload: truesubmits your domain to browser HSTS preload lists, this is effectively permanent and hard to reverse, only enable it once you're certain HTTPS will never be removed.
License
WTFPL (Do What the Fuck You Want to Public License), see LICENSE for details.