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

type RouteHandler = (ViewRequest, HandlerContext) => Promise<ViewResponse>;

It's exposed as the default export.

export { default } from '@lwrjs/security';

To use the default handler for a route, set @lwrjs/security as the route handler in lwr.config.json.

{
    "routes": [
        {
            "id": "home",
            "path": "/",
            "rootComponent": "examples/example",
            "routeHandler": "@lwrjs/security",
        },
    ]
}

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.

"routeHandler": ["@lwrjs/security", {
    "contentSecurityPolicy": "default-src 'self'&semi;base-uri 'self'&semi; script-src 'self'",
    "referrerPolicy": false,
    "xXSSProtection": false
    }]

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.

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

import type { ViewDefinitionResponse } from '@lwrjs/types';
import { secure } from '@lwrjs/security';

function routeHandler(): ViewDefinitionResponse {
    return {
        // programmatically define the view configuration
        view: {
            rootComponent: 'example/home'
        },
        // set response headers
        headers: {},
    };
}

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

headers: {
    "contentSecurityPolicy": "default-src 'self'&semi;base-uri 'self'&semi; script-src 'self'",
    "referrerPolicy": false,
    "xXSSProtection": false
},

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.

contentSecurityPolicy?: 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.

// The string:
"contentSecurityPolicy": "default-src 'self';base-uri 'self'; script-src 'self'"

// is parsed into this ContentSecurityPolicy object:
"contentSecurityPolicy":
    {
        "useDefault": false,
        "resourceHashing": true,
        "directives": "default-src 'self';base-uri 'self'; script-src 'self'"
    }

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-none
  • require-corp
  • credentialless

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-origin
  • same-origin-allow-popups
  • unsafe-none

For information about these directives, see MDN Web Docs: Cross-Origin-Opener-Policy Directives

"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-origin
  • same-origin-allow-popups
  • unsafe-none

For information about these directives, see MDN Web Docs: Cross-Origin-Resource-Policy Directives

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

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

strictTransportSecurity?: 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.

// The string:
"strictTransportSecurity": "max-age=15552000&semi; preload"

// is parsed into this StrictTransportSecurity object:
"strictTransportSecurity":
    {
        "maxAge": 15552000,
        "preload": true
    }

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-referrer
  • no-referrer-when-downgrade
  • origin
  • origin-when-cross-origin
  • same-origin
  • strict-origin
  • strict-origin-when-cross-origin
  • unsafe-url

For information about these directives, see MDN Web Docs: Referrer-Policy Directives

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

  • off
  • on

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.

  • sameorigin
  • deny

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.

  • none
  • masteronly
  • bycontenttype
  • byftpfilename
  • all

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.

  • 0
  • 1

For information about these directives, see MDN Web Docs: X-XSS-Protection.

See Also