@lwrjs/security
HTTP security headers guard your site against malicious code injections and cross-site scripting (XSS) attacks. You can implement security headers for your LWR site on a route-by-route basis using the @lwrjs/security package.
@lwrjs/security exposes a default route handler and a security wrapper, both of which apply a set of default security headers. To customize these headers, modify the corresponding header configuration objects.
Usage
To add this package to your project, run npm install @lwrjs/security on the command line. Implement this package for a route via the default handler or a security wrapper.
Default Route Handler
The @lwrjs/security route handler matches the RouteHandlerFunction interface.
1type RouteHandler = (ViewRequest, HandlerContext) => Promise<ViewResponse>;It’s exposed as the default export.
1export { default } from '@lwrjs/security';To use the default handler for a route, set @lwrjs/security as the route handler in lwr.config.json.
1{
2 "routes": [
3 {
4 "id": "home",
5 "path": "/",
6 "rootComponent": "examples/example",
7 "routeHandler": "@lwrjs/security",
8 },
9 ]
10}To modify a security header in the default route handler, set the corresponding header configuration object in the routeHandler section. You can disable a header by setting its configuration object to false. For more information about default headers and header configuration, skip ahead to Headers.
1"routeHandler": ["@lwrjs/security", {
2 "contentSecurityPolicy": "default-src 'self';base-uri 'self'; script-src 'self'",
3 "referrerPolicy": false,
4 "xXSSProtection": false
5 }]Security Wrappers
The @lwrjs/security route handler wrapper secure() applies security headers to an existing route handler. The wrapper is exposed as a named export. It takes a route handler as an argument and returns a promise.
1type RouteHandlerWrapper = (RouteHandlerFunction) => Promise<RouteHandlerReturnType>;RouteHandlerReturnType can be a ViewResponse or ViewDefinitionResponse. Each type of promise applies headers as follows:
- ViewDefinitionResponse - applies the default security headers with inline resource hashing.
- ViewResponse (HTML content) - applies the default security headers without resource hashing.
- ViewResponse (non-HTML content) - doesn’t apply headers.
For example, this routeHandler.ts file passes the routeHandler into secure(). Since the headers section is empty, only the default headers are used.
1import type { ViewDefinitionResponse } from '@lwrjs/types';
2import { secure } from '@lwrjs/security';
3
4function routeHandler(): ViewDefinitionResponse {
5 return {
6 // programmatically define the view configuration
7 view: {
8 rootComponent: 'example/home'
9 },
10 // set response headers
11 headers: {},
12 };
13}
14
15export default secure(routeHandler);To modify a header for the default handler, configure the corresponding header configuration object in the route handler file. You can disable a header by setting its configuration object to false.
1headers: {
2 "contentSecurityPolicy": "default-src 'self';base-uri 'self'; script-src 'self'",
3 "referrerPolicy": false,
4 "xXSSProtection": false
5},Headers
The default route handler and security wrapper automatically enable the following security headers.
Content-Security-Policy
The Content-Security-Policy header directs your site to load content from only approved sources. For a list of acceptable formats for source values, see CSP Source Values.
These are the default directives for the Content-Security-Policy header.
| Directive | Description | Default Source Value |
|---|---|---|
default-src | Set the default source value for all directives that don’t have a value. | 'self' |
base-uri | Set approved sources that load content in the page’s <base> element. | 'self' |
font-src | Set approved sources that provide fonts. | 'self' https: data:; |
form-action | Set approved sources that a form can send information to. | 'self' |
frame-ancestors | Set approved sources that can embed your page (the current frame) into a container like <frame> on their site. | 'self' |
img-src | Set approved sources of images and icons. | 'self' data:; |
object-src | Set approved sources of <object> and <embed> elements. | 'none' |
script-src | Set approved sources of JavaScript code for elements like <script>. You can set the value of this directive to a hash, like 'sha256-hash_value'. | 'self' |
script-src-attr | Set approved sources of only JavaScript inline event handlers. | 'none' |
style-src | Set approved sources of stylesheets. | 'self' https: 'unsafe-inline' |
upgrade-insecure-requests | When this directive is declared in a Content-Security-Policy header, it upgrades HTTP requests (insecure) to HTTPS requests (secure). If an HTTP request is not available as an HTTPS request, the request fails. |
Customize the Content-Security-Policy Header
There are two ways to modify the Content-Security-Policy header.
1contentSecurityPolicy?: ContentSecurityPolicy | string | boolean;You can set contentSecurityPolicy to a ContentSecurityPolicy configuration object that contains your custom directives and options for the header. This object overwrites the default values, so you set the directives from scratch.
Alternatively, you can conveniently set contentSecurityPolicy to a string of directive-value pairs. When your input is a string, useDefault is automatically set to false and resourceHashing is automatically set to true. This overwrites the default values, so you set the directives from scratch.
1// The string:
2"contentSecurityPolicy": "default-src 'self';base-uri 'self'; script-src 'self'"
3
4// is parsed into this ContentSecurityPolicy object:
5"contentSecurityPolicy":
6 {
7 "useDefault": false,
8 "resourceHashing": true,
9 "directives": "default-src 'self';base-uri 'self'; script-src 'self'"
10 }Cross-Origin-Embedder-Policy
The Cross-Origin-Embedder-Policy header controls how a page loads cross-origin resources.
The default policy is require-corp. To configure this header, set the crossOriginEmbedderPolicy object to one of the following values in string format.
unsafe-nonerequire-corpcredentialless
For information about these directives, see MDN Web Docs: Cross-Origin-Embedder-Policy Directives.
Cross-Origin-Opener-Policy
The Cross-Origin-Opener-Policy header separates a top-level browser instance of a page (like a window) from different page contexts, like pop-ups and other browser tabs.
The default policy is same-origin. To configure this header, set the crossOriginOpenerPolicy object to one of the following values in string format.
same-originsame-origin-allow-popupsunsafe-none
For information about these directives, see MDN Web Docs: Cross-Origin-Opener-Policy Directives
1"crossOriginOpenerPolicy": "unsafe-none"Cross-Origin-Resource-Policy
The Cross-Origin-Resource-Policy header controls whether external websites can access and load content from your site.
The default policy is same-origin. To configure this header, set the crossOriginResourcePolicy object to one of the following values in string format.
same-originsame-origin-allow-popupsunsafe-none
For information about these directives, see MDN Web Docs: Cross-Origin-Resource-Policy Directives
1"crossOriginResourcePolicy": "unsafe-none"Origin-Agent-Cluster
The Origin-Agent-Cluster header controls whether or not the browser creates same-origin groups of pages. For more information about same-origin versus cross-origin pages, see Understanding “same-site” and “same-origin”.
The default value for the originAgentCluster object is the boolean ?1.
1"originAgentCluster": "?1"For more information about this header and accepted values, see MDN Web Docs: Origin-Agent-Cluster.
Strict-Transport-Security
The Strict-Transport-Security header forces the browser to access a site with HTTPS. Attempts to access the site with HTTP are automatically converted to HTTPS requests. If an HTTP request is not available as an HTTPS request, the request fails.
These are the default directives for this header.
| Directive | Directive Description | Default Value |
|---|---|---|
max-age | Duration (in seconds) that the browser should only load the site with HTTPS. | 15552000 |
includeSubDomains | Applies header settings to all subdomains. |
Customize the Strict-Transport-Security Header
There are two ways to modify the Strict-Transport-Security header.
1strictTransportSecurity?: StrictTransportSecurity | string | boolean;You can set strictTransportSecurity to a StrictTransportSecurity configuration object that contains your custom directives and options for the header. This object overwrites the default values, so you set the directives from scratch.
Alternatively, you can conveniently set strictTransportSecurity to a string of directive-value pairs. When your input is a string, it overwrites the default values and only uses your input.
1// The string:
2"strictTransportSecurity": "max-age=15552000; preload"
3
4// is parsed into this StrictTransportSecurity object:
5"strictTransportSecurity":
6 {
7 "maxAge": 15552000,
8 "preload": true
9 }Referrer-Policy
The Referrer-Policy header controls what information is shared with different types of browser requests.
The default policy is no-referrer. To configure this header, set the referrerPolicy object to one of the following values in string format.
no-referrerno-referrer-when-downgradeoriginorigin-when-cross-originsame-originstrict-originstrict-origin-when-cross-originunsafe-url
For information about these directives, see MDN Web Docs: Referrer-Policy Directives
1"referrerPolicy": "same-origin"X-Content-Type-Options
The X-Content-Type-Options header controls browser requests based on the request destination type and the MIME type.
The default policy is no-sniff. You can either disable this header or keep the no-sniff configuration.
X-DNS-Prefetch-Control
The X-DNS-Prefetch-Control header controls DNS prefetching.
The default policy is off, which disables prefetching. To configure this header, set the xDNSPrefetchControl object to one of the following values in string format.
offon
For information about these directives, see MDN Web Docs: X-DNS-Prefetch-Control Directives.
X-Download-Options
The X-Download-Options header controls whether content is executed in the browser or downloaded onto a local machine.
The default policy is "noopen", which prevents content from executing in the browser. You can either disable this header or keep the noopen configuration.
X-Frame-Options
The X-Frame-Options header determines whether or not the browser can load the page in a frame.
The default value is sameorigin. To configure this header, set the xFrameOptions object to one of the following values in string format.
sameorigindeny
For information about these directives, see MDN Web Docs: X-Frame-Options Directives.
X-Permitted-Cross-Domain-Policies
The X-Permitted-Cross-Domain-Policies header controls how resources are shared with cross-domain sites.
The default value is none. To configure this header, set the xPermittedCrossDomainPolicies object to one of the following values in string format.
nonemasteronlybycontenttypebyftpfilenameall
X-XSS-Protection
The X-XSS-Protection header controls XSS filtering.
The default value is 0. To configure this header, set the xXssProtection object to one of the following boolean values.
01
For information about these directives, see MDN Web Docs: X-XSS-Protection.
See Also
Developer Preview Feature