Content-Security-Policy
このコンテンツはまだ日本語訳がありません。
contentSecurityPolicy() builds a CSP header from a typed directive map.
camelCase keys serialise to their kebab-case directive names, and your
directives merge over a helmet-parity baseline.
import { contentSecurityPolicy, CspOptions, withMiddleware } from 'actor-ts/http';
const csp = contentSecurityPolicy( CspOptions.create().withDirectives({ scriptSrc: ["'self'", 'https://cdn.example'], imgSrc: ["'self'", 'data:', 'https:'], }),);
const routes = withMiddleware(csp, appRoutes);The baseline (useDefaults, on by default) is default-src 'self',
object-src 'none', base-uri 'self', frame-ancestors 'self',
script-src 'self', and friends. Your directives override per-directive;
set a directive to [] to remove it, or call withoutDefaults() to emit
only what you specify.
The header rides on a short-circuit that throws as well — an
HttpError from a layer below carries the policy out with it. That matters
more here than for the rest of the header bundle: a policy is far too
app-specific to sit in the server-wide withSecurityHeaders(...), so this
middleware is the only seam that emits one, and a response raised outside
its subtree (the backend’s own 404, the generic 500) carries none.
Configuration
Section titled “Configuration”| Builder method | Purpose |
|---|---|
withDirectives(map) | The directive map (merged over the baseline). |
withoutDefaults() | Emit only the given directives — skip the baseline. |
withReportOnly(flag?) | Send Content-Security-Policy-Report-Only instead of enforcing. |
upgradeInsecureRequests: true renders the valueless directive; reportUri
and reportTo are supported. A source token containing ;, ,, or
whitespace throws at construction — no silent header injection.
Where to next
Section titled “Where to next”- Security headers — the rest of the response headers.
- HTML & XSS — escaping is your first line; CSP is defence in depth.
- Security — the recommended stack.
