We are going to define a security header baseline that includes HSTS, CSP, and Trusted Types.
We want to roll these out with staged enforcement, meaning we might start with reporting only and then move to enforcement.
Steps:
-
HSTS (HTTP Strict Transport Security):
- We'll set a long max-age (e.g., 6 months) and includeSubDomains.
- We might start with a shorter max-age for testing, but baseline for production should be strong.
-
CSP (Content Security Policy):
- We'll define a policy that is restrictive but with a report-uri for monitoring.
- We'll use the 'strict-dynamic' for scripts if we use nonces/hashes, but note that Trusted Types can help with inline scripts.
- We might start with report-only and then move to enforcement.
-
Trusted Types:
- We'll define a policy that requires Trusted Types for certain sinks (like innerHTML, etc.).
- We'll start by allowing the policy to be defined and then enforce it.
Plan for staged enforcement:
Phase 1: Report Only (or monitoring) for all headers.
- HSTS: We can set
max-age to a small value (like 5 minutes) and without includeSubDomains initially?
But note: HSTS is not a report-only header, it's either on or off. However, we can set a short max-age for testing.
Alternatively, we might set HSTS with a long max-age from the start because it's a security header that we want to enforce from the beginning?
But if we have mixed content, it can break. So we might want to test with a short max-age first.
However, note that HSTS is not a report-only header. We can only set it as an enforced header. But we can set a short max-age and then increase.
Alternatively, we can set HSTS with max-age=0 to disable? That's not helpful.
Let's reconsider: HSTS is a security header that once set with a long max-age, it's hard to undo (if the user has visited once, they'll get HSTS for that duration).
So we should be cautious.
Proposed:
Step 1: Set HSTS with a short max-age (e.g., 1 hour) and without includeSubDomains for a test period (e.g., 1 week). Then increase to 6 months and add includeSubDomains.
But note: if we set HSTS with includeSubDomains and a long max-age, then all subdomains must also support HTTPS. So we need to ensure that.
Alternatively, we can set HSTS without includeSubDomains and then add it later. But note: adding includeSubDomains later will not affect existing HSTS entries? Actually, when the browser receives a new HSTS header with includeSubDomains, it will update the existing entry to include subdomains. However, if the previous entry did not have includeSubDomains, then the browser will allow HTTP on subdomains until the new header is received. So we can do:
Phase 1 (HSTS):
Strict-Transport-Security: max-age=3600; includeSubDomains
Then after testing, change to:
Strict-Transport-Security: max-age=15552000; includeSubDomains
But wait: if we set a short max-age and then change to a long one, the browser will reset the timer. So that's acceptable.
However, if we are in a testing phase and we might have HTTP on subdomains, then we should not set includeSubDomains until we are sure.
So:
Week 1:
HSTS: max-age=3600 (without includeSubDomains) -> but then we are only protecting the main domain, not subdomains.
Week 2:
If all subdomains are HTTPS, then set max-age=15552000 and includeSubDomains.
But note: if we set includeSubDomains in the first week and a subdomain is not HTTPS, then that subdomain will break for users who have visited the main domain.
So we must be cautious. Alternatively, we can set HSTS without includeSubDomains until all subdomains are ready.
Given that, let's break HSTS into two steps:
Step 1: Set HSTS without includeSubDomains and a short max-age (1 hour) for the main domain only.
Step 2: When all subdomains are HTTPS, set includeSubDomains and a long max-age (6 months).
But note: the HSTS header is set per domain. So if we set it on the main domain, it only applies to that domain. Then when we set includeSubDomains, it will apply to all subdomains.
So we can:
Phase 1 (main domain only, short max-age):
Strict-Transport-Security: max-age=3600
Phase 2 (all domains, long max-age):
Strict-Transport-Security: max-age=15552000; includeSubDomains
But wait: if we set includeSubDomains in phase 2, then the browser will enforce HSTS on all subdomains, even if we haven't set the header on the subdomains? Actually, the HSTS header from the main domain with includeSubDomains will cause the browser to enforce HSTS on all subdomains. So we must ensure that all subdomains are served over HTTPS and will not redirect to HTTP.
So we need to make sure that all subdomains are HTTPS and have a valid certificate.
Alternatively, we can set HSTS on each subdomain individually? But that's more complex.
So the plan for HSTS:
- First, set HSTS on the main domain without
includeSubDomains and a short max-age (1 hour) for a testing period (e.g., 1 week). This will protect the main domain.
- Then, after ensuring all subdomains are HTTPS and will remain so, set
includeSubDomains and a long max-age.
But note: if we set includeSubDomains and a long max-age, then all subdomains must have HTTPS. So we must have a process to ensure that.
Now, for CSP and Trusted Types:
We can set them in report-only mode first, then enforce.
For CSP:
Phase 1: Content-Security-Policy-Report-Only: ... (with report-uri)
Phase 2: Content-Security-Policy: ... (enforced)
For Trusted Types:
We can set the header in report-only? Actually, Trusted Types has a reporting mechanism via the CSP report-uri? Or we can use the require-trusted-types-for directive in CSP.
Actually, Trusted Types is a separate header? No, it's a CSP directive.
So we can do:
Phase 1 (CSP with Trusted Types in report-only and with a report-uri):
Content-Security-Policy-Report-Only: ...; require-trusted-types-for 'script'; ...
Then, when we are ready, we move to enforced CSP.
But note: the require-trusted-types-for directive is part of CSP. So we can have:
Phase 1 (report-only CSP with Trusted Types):
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' 'nonce-...'; require-trusted-types-for 'script'; report-uri /csp-report
Phase 2 (enforced CSP with Trusted Types):
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-...'; require-trusted-types-for 'script';
But note: if we are using nonces, then we don't need to change the nonce every request? Actually, we do. So we must generate a nonce per request.
Alternatively, we can use hashes. But nonces are more flexible.
However, with Trusted Types, we are required to use Trusted Types for any script that is not a nonce or hash? Actually, Trusted Types is about DOM-based XSS. It requires that any assignment to dangerous DOM sinks (like innerHTML) must be done via a Trusted Types policy. It doesn't directly relate to script-src. But there is a CSP directive require-trusted-types-for that enforces that for certain contexts.
Actually, the Trusted Types policy is defined in JavaScript, and the CSP directive require-trusted-types-for tells the browser to enforce that for the specified contexts (like 'script').
So we can have:
CSP with script-src that allows nonces and hashes, and also requires Trusted Types for script execution? Actually, the require-trusted-types-for is a separate directive.
Let me clarify:
- Trusted Types is a web platform feature that allows you to define policies for creating trusted values for dangerous DOM sinks.
- The CSP directive
require-trusted-types-for can be used to require that certain operations (like creating a script element) use a Trusted Type.
But note: the script-src directive and require-trusted-types-for are independent? Not exactly. script-src controls where scripts can be loaded from, and require-trusted-types-for controls how scripts are created (via DOM manipulation). So they complement each other.
So our CSP might look like:
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-{nonce}' 'strict-dynamic' ...;
require-trusted-types-for 'script';
But note: 'strict-dynamic' is for script-src and it allows scripts that are loaded by a script with a nonce? Actually, 'strict-dynamic' allows scripts that are loaded by a script that is allowed by script-src (by nonce or hash) to be executed even if they are from a different origin. But then we must have a nonce or hash in script-src to bootstrap.
Alternatively, we can avoid 'strict-dynamic' and just use nonces and hashes.
Given the complexity, let's assume we are using nonces for inline scripts and hashes for static scripts, and we want to require Trusted Types for any script created via DOM.
So we'll define:
Phase 1 (report-only):
CSP-Report-Only:
default-src 'self';
script-src 'self' 'nonce-{nonce}' 'sha256-...' ...;
require-trusted-types-for 'script';
report-uri /csp-report
Phase 2 (enforced):
CSP:
default-src 'self';
script-src 'self' 'nonce-{nonce}' 'sha256-...' ...;
require-trusted-types-for 'script';
But note: we must adjust the nonce per request.
Now, the baseline headers for each phase:
We are going to define:
Phase 1 (Report Only for CSP and Trusted Types, and short HSTS without includeSubDomains):
For HSTS (enforced, but short and without subdomains):
Strict-Transport-Security: max-age=3600
For CSP and Trusted Types (report-only):
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' 'nonce-{nonce}' 'sha256-...'; require-trusted-types-for 'script'; report-uri /csp-report
But note: we must generate a nonce per request and also include the hashes for any static inline scripts.
Phase 2 (Enforced for CSP and Trusted Types, and long HSTS with includeSubDomains):
HSTS:
Strict-Transport-Security: max-age=15552000; includeSubDomains
CSP:
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}' 'sha256-...'; require-trusted-types-for 'script';
However, note: when we move from report-only to enforced, we might have violations that were not caught in report-only because the report-only doesn't block. So we should monitor the reports in phase 1 and fix any issues.
Also, note: the report-uri in phase 1 must be an endpoint that collects CSP reports.
Now, let's write the baseline in a way that we can configure per phase.
We can have:
Phase 1 (initial rollout):
HSTS:
Strict-Transport-Security: max-age=3600
CSP (report-only):
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' 'nonce-{nonce}' 'sha256-...'; require-trusted-types-for 'script'; report-uri /csp-report
Trusted Types: included in the CSP report-only.
Phase 2 (after monitoring and fixing):
HSTS:
Strict-Transport-Security: max-age=15552000; includeSubDomains
CSP (enforced):
Content-Security-Policy: default-src 'self'; script-script 'self' 'nonce-{nonce}' 'sha256-...'; require-trusted-types-for 'script';
But note: we might want to remove the report-uri from the enforced policy? Actually, we can keep it for monitoring. The report-uri can be in both report-only and enforced. In enforced, the reports are sent for blocked violations.
So in phase 2, we can have:
Content-Security-Policy: ...; report-uri /csp-report
But note: the report-uri is a CSP directive and can be in both report-only and enforced.
However, the report-only header does not block, so it only reports. The enforced header blocks and reports.
So we can have the same report-uri in both.
Now, let's write the baseline as a configuration for a web server (like Nginx or Apache) or as code for a middleware.
Since the question is about composing the baseline, I'll write it in a generic way.
We assume we have a way to generate nonces and hashes.
Steps for implementation:
- Generate a nonce for each response (cryptographically random, base64 encoded).
- Calculate hashes for any static inline scripts (or use nonces for all inline scripts?).
But note: if we use nonces for all inline scripts, then we must add the nonce to every script tag. And we must not use 'unsafe-inline'.
So our script-src should not have 'unsafe-inline', but should have 'nonce-{nonce}' and hashes for static scripts that don't have a nonce.
Actually, we can use either nonces or hashes for each inline script. But if we generate a nonce per request, we can use that for all inline scripts in that response? Yes, we can use the same nonce for multiple scripts in the same response.
So:
In the HTML, for every inline script, we add: ...
And for external scripts, we can use hashes or just the src if they are from the same origin? Actually, script-src 'self' allows same-origin scripts. But if we want to allow inline scripts, we must use nonces or hashes.
So:
script-src: 'self' 'nonce-{nonce}' [hashes for any static inline scripts that we don't want to add nonce to?]
But note: if we use nonces, we don't need hashes for the same inline script. So we can choose one.
Typically, we use nonces for inline scripts and then we don't need hashes for those. But if we have inline scripts that are generated by the server and we don't want to add a nonce (maybe because they are in a file that is included and we don't want to change it), then we can use a hash.
So our policy might include both.
Now, the baseline:
We'll write the headers for phase 1 and phase 2.
Phase 1:
HSTS (enforced, but short and without subdomains):
Strict-Transport-Security: max-age=3600
CSP (report-only with Trusted Types and reporting):
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' 'nonce-{nonce}' [hashes if needed]; require-trusted-types-for 'script'; report-uri /csp-report
Phase 2:
HSTS:
Strict-Transport-Security: max-age=15552000; includeSubDomains
CSP (enforced with Trusted Types and reporting):
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}' [hashes if needed]; require-trusted-types-for 'script'; report-uri /csp-report
But note: the require-trusted-types-for is a CSP directive and it is supported in the Content-Security-Policy header. So we include it in both.
However, note that the require-trusted-types-for directive is not supported in all browsers? We should check caniuse. But for modern browsers, it's supported.
Also, note: we are using report-uri which is the old way. The new way is report-to but report-uri is still widely supported.
Alternatively, we can use report-to and define a reporting endpoint in the Report-To header.
But for simplicity, we use report-uri.
Now, the implementation:
We must:
- Generate a nonce per response and set it in the CSP header and also in the script tags.
- Calculate hashes for any static inline scripts that we cannot add a nonce to.
But note: if we use nonces for all inline scripts, then we don't need hashes for those. So we can avoid hashes for inline scripts by using nonces.
So we can have:
script-src: 'self' 'nonce-{nonce}'
And then we don't need hashes for inline scripts that have the nonce.
But what about external scripts? They are allowed by 'self' if they are from the same origin. If we have external scripts from other origins, we must list them.
So adjust according to your needs.
Now, the baseline in a more concrete form:
Let's assume we have a web application that:
- Serves all content from the same origin (so 'self' is enough for default-src and script-src).
- Uses inline scripts in the HTML (so we need nonces).
- No external scripts from other origins.
Then:
Phase 1 headers:
Strict-Transport-Security: max-age=3600
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' 'nonce-{nonce}'; require-trusted-types-for 'script'; report-uri /csp-report
Phase 2 headers:
Strict-Transport-Security: max-age=15552000; includeSubDomains
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}'; require-trusted-types-for 'script'; report-uri /csp-report
But note: in phase 2, we are enforcing CSP. So if we have any violation, it will be blocked and reported.
We must have a Trusted Types policy defined in JavaScript. For example:
if (window.trustedTypes && window.trustedTypes.createPolicy) {
window.trustedTypes.createPolicy('default', {
createScript: (string) => string
});
}
But note: the above policy does nothing, it just returns the string. But then we must use:
element.innerHTML = trustedTypes.createScript('...');
Actually, the Trusted Types policy must be used when assigning to dangerous sinks. So we must change our code to use Trusted Types for any innerHTML, outerHTML, etc.
Alternatively, we can define a policy that allows any string (like above) and then use that policy. But that doesn't protect against XSS because we are just returning the string. The point of Trusted Types is to force the developer to use a policy that does sanitization or only allows safe values.
So we must define a policy that does sanitization, or use a library that does.
But note: the require-trusted-types-for directive will require that for the specified contexts (like 'script'), the values assigned to certain sinks must be created by a Trusted Types policy.
So we must update our JavaScript code accordingly.
Alternatively, we can use a policy that does nothing and then use it for every assignment? That would not be safe because we are not sanitizing. But if we are already sanitizing, then we can return the sanitized string from the policy.
Example:
trustedTypes.createPolicy('myPolicy', {
createHTML: (string) => DOMPurify.sanitize(string)
});
Then use:
element.innerHTML = myPolicy.createHTML(userInput);
But note: the policy must be defined before any assignment to innerHTML, etc. So we must define it in a script that runs early.
Given the complexity, we must ensure that our application is compatible with Trusted Types before enforcing.
So the baseline includes:
- HSTS (with staged rollout: first short without subdomains, then long with subdomains)
- CSP with nonces and Trusted Types, first in report-only, then enforced.
And we must have a Trusted Types policy defined in our JavaScript.
Now, let's write the baseline as a step-by-step guide.
Steps:
- Implement HSTS with a short max-age (1 hour) and without includeSubDomains.
- Implement CSP in report-only mode with nonces and Trusted Types, and set up a report-uri endpoint.
- Define a Trusted Types policy in JavaScript (even in report-only mode, we must define it to avoid breaking the application when we enforce? Actually, in report-only, the browser doesn't enforce, so we don't need the policy until enforcement. But we should test with enforcement in a staging environment.)
- Monitor the CSP reports for violations and fix them.
- After a period (e.g., 1-2 weeks) and no violations (or only harmless ones that we decide to allow), move to enforcing CSP.
- Then, after ensuring all subdomains are HTTPS, update HSTS to includeSubDomains and a long max-age.
But note: step 5 and 6 can be done in any order? Actually, HSTS with includeSubDomains requires all subdomains to be HTTPS. So we must do step 6 after we are sure about subdomains.
Alternatively, we can do:
Phase 1 (HSTS short without subdomains, CSP report-only) -> 1 week
Phase 2 (CSP enforced, HSTS still short without subdomains) -> 1 week
Phase 3 (HSTS long with includeSubDomains)
But note: if we enforce CSP and then change HSTS, it's two separate steps.
However, HSTS is independent of CSP. So we can do:
Step 1: HSTS short without subdomains (enforced)
Step 2: CSP report-only (with Trusted Types) and monitor.
Step 3: CSP enforced (with Trusted Types) and monitor.
Step 4: HSTS long with includeSubDomains.
But note: if we have subdomains that are not HTTPS, then step 4 will break them for users who have visited the main domain. So we must ensure all subdomains are HTTPS before step 4.
Alternatively, we can set HSTS on each subdomain individually when they are ready, and then set the main domain with includeSubDomains.
Given the complexity, we might want to have a process to ensure subdomains are HTTPS.
Now, the baseline headers in code:
For example, in Nginx:
Phase 1:
add_header Strict-Transport-Security "max-age=3600" always;
add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' 'nonce-$nonce'; require-trusted-types-for 'script'; report-uri /csp-report" always;
But note: we must generate a nonce per request and set it in the CSP header and also in the HTML.
In Nginx, we can use a variable for nonce? We need to generate a random nonce per request. We can use the requestidvarrequest_id which is a random string, but it's not base64. We can use the ngx_http_secure_link_module or write a custom module? Alternatively, we can generate the nonce in the application and set it in a header.
Alternatively, we can set the nonce in the application and then set the CSP header with that nonce.
So it's better to set these headers in the application code.
For example, in Express.js:
app.use((req, res, next) => {
const nonce = crypto.randomBytes(16).toString('base64');
res.setHeader('Strict-Transport-Security', 'max-age=3600');
res.setHeader('Content-Security-Policy-Report-Only', default-src 'self'; script-src 'self' 'nonce-${nonce}'; require-trusted-types-for 'script'; report-uri /csp-report);
res.locals.nonce = nonce;
next();
});
Then in the HTML template:
But note: we must also include the nonce in every inline script. And we must not have any inline script without a nonce.
Also, we must define a Trusted Types policy in our JavaScript.
In the HTML, we can have:
But note: the above policy does nothing. We must use it in our code. So we must change our code to use:
element.innerHTML = trustedTypes.createScript(userInput);
Or, if we use a policy that sanitizes:
element.innerHTML = myPolicy.createHTML(userInput);
So we must update our code accordingly.
Now, when we move to phase 2 (enforced CSP), we change the header to:
res.setHeader('Content-Security-Policy', default-src 'self'; script-src 'self' 'nonce-${nonce}'; require-trusted-types-for 'script'; report-uri /csp-report);
And remove the report-only header? Actually, we can have both? But the enforced one will block and report, and the report-only will report without blocking? Actually, if we set both, the report-only will report and the enforced will block and report. But that's redundant.
We can remove the report-only header when we set the enforced one.
So phase 2:
app.use((req, res, next) => {
const nonce = crypto.randomBytes(16).toString('base64');
res.setHeader('Strict-Transport-Security', 'max-age=15552000; includeSubDomains');
res.setHeader('Content-Security-Policy', default-src 'self'; script-src 'self' 'nonce-${nonce}'; require-trusted-types-for 'script'; report-uri /csp-report);
res.locals.nonce = nonce;
next();
});
But note: we are now enforcing CSP. So we must have fixed all violations.
However, we are still reporting. So we can monitor.
Now, the Trusted Types policy: we must define it before any script runs? Actually, the policy must be defined before any assignment to a dangerous sink that is covered by require-trusted-types-for. So we must define it in a script that runs early.
We can do:
But note: the require-trusted-types-for directive in CSP requires that for the specified context (in our case 'script'), any value assigned to a dangerous sink must be created by a Trusted Types policy. The above policy is for creating HTML, but we are requiring for 'script'. Actually, the require-trusted-types-for can take a list of contexts. The current contexts are: 'script', 'script attribute', 'style', 'style attribute', etc.
We are requiring for 'script'. That means that when we assign to innerHTML (which can contain script elements) or create a script element via DOM, we must use a Trusted Type for the script content.
So we need a policy that creates a Trusted Script? Actually, the policy for 'script' context must have a method called createScript that returns a Trusted Script.
So:
if (window.trustedTypes && window.trustedTypes.createPolicy) {
window.trustedTypes.createPolicy('default', {
createScript: (string) => string
});
}
But then we must use:
const script = trustedTypes.createScript('alert(1)');
element.innerHTML = script; // This would work because script is a Trusted Script.
But note: the policy above does not sanitize. So we are not safe.
We must sanitize the string. But note: the Trusted Types policy for 'script' must return a Trusted Script. How do we create a Trusted Script? We can use the policy's createScript method.
But we cannot sanitize and then return a string? Actually, the createScript method must return a Trusted Script, which is a special object. We cannot create it manually. We can only create it by calling createScript on a policy.
So we must have a policy that does:
createScript: (string) => {
// sanitize the string and then return a Trusted Script by calling createScript again?
// But we cannot call createScript inside createScript because that would be recursive.
Actually, the policy's createScript method is called with a string and must return a Trusted Script. We can do:
createScript: (string) => {
const sanitized = DOMPurify.sanitize(string, {SCRIPT: 'remove'}); // remove script tags? But then we are not allowing scripts.
// But note: we are requiring trusted types for script, meaning we are trying to create a script via DOM. So if we remove scripts, then we are not creating a script. That might be acceptable.
// Alternatively, we can allow only safe scripts? It's complex.
// Actually, the Trusted Types policy for 'script' is for when we want to create a script element via innerHTML or similar. So we must return a Trusted Script that represents the sanitized string.
// But how do we create a Trusted Script? We can only do it by calling createScript on a policy? That's a chicken and egg.
// Actually, the policy's createScript method is called by the browser when we do:
trustedTypes.createPolicy('myPolicy', {
createScript: (string) => { ... }
});
And then when we call myPolicy.createScript(string), it returns a Trusted Script.
So we can:
createScript: (string) => {
// We must return a Trusted Script. But we can only create a Trusted Script by calling createScript on a policy?
// Actually, the object returned by the policy's createScript is automatically a Trusted Script.
// But note: we are inside the createScript function. We cannot call myPolicy.createScript again because that would be recursion.
// So we must return a value that the browser will accept as a Trusted Script. The browser will accept whatever we return from the policy's createScript as a Trusted Script.
// So we can return the sanitized string? But that's just a string, not a Trusted Script.
// Actually, the browser will wrap the return value in a Trusted Script object? I think the policy's createScript must return a string that is then converted to a Trusted Script by the browser.
// According to the spec: the return value of the policy's createScript is a Trusted Script.
// So we can return a sanitized string.
return DOMPurify.sanitize(string, {SCRIPT: 'remove'}); // This returns a string without script tags? But then it's not a script.
// But note: we are in the context of creating a script. So if we remove all scripts, then we are not creating a script. That might be acceptable because we are preventing script execution.
// However, if we want to allow some scripts (like from a trusted source) we would need to allow them.
// This is complex and depends on the application.
// Alternatively, we can use a policy that does not allow any script? Then we must not have any code that tries to create a script via innerHTML.
// But note: the `require-trusted-types-for` directive requires that any attempt to create a script via DOM must use a Trusted Type. So if we don't have any code that does that, we are safe.
// But we must have a policy that is used for any such creation. So we can define a policy that throws an error? Actually, if we don't define a policy, then the browser will throw an error when we try to assign to innerHTML without using a Trusted Type.
// So we must define a policy that is used in our code.
// Given the complexity, we might need to audit our code for any innerHTML, outerHTML, etc. that might contain scripts.
// And then either remove those or use Trusted Types.
// For the baseline, we can define a policy that does nothing and then update our code to use the policy for any assignment to innerHTML, etc.
// But note: the policy must return a Trusted Script for the script context. So if we are assigning to innerHTML, we are in the 'html' context? Actually, innerHTML is for HTML, and if it contains a script, then that script is created. So we might need a policy for 'script' and for 'html'?
// The CSP directive `require-trusted-types-for` can specify multiple contexts. We specified 'script'. That means that when a script is created (via a script element or via innerHTML that contains a script) we must use a Trusted Type for the script content.
// But innerHTML itself is not a script context? Actually, innerHTML is an HTML sink. The `require-trusted-types-for` directive does not apply to innerHTML directly? It applies to the creation of script elements and the setting of event handlers? Let me check.
// According to MDN: The require-trusted-types-for directive requires that the specified DOM elements be assigned a value that is a Trusted Type.
// The specified DOM elements are: for 'script', any script element created by the parser or by the DOM API must have a Trusted Type for its text.
// So if we set innerHTML to a string that contains a script, then the browser will try to create a script element and that script element must have a Trusted Type for its text.
// So we must use a Trusted Type for the entire innerHTML string? No, for the script part.
// Actually, when we set innerHTML, the browser parses the string and creates elements. For any script element, it will require that the text of the script is a Trusted Type.
// So we cannot just set innerHTML to a string that contains a script without using a Trusted Type for the script part.
// How do we do that? We would have to break the string and assign the non-script parts as string and the script part as Trusted Script? That's not possible.
// Actually, the entire innerHTML string must be a Trusted HTML? There is a Trusted Type for HTML? Yes, there is a `createHTML` method in Trusted Types.
// So if we set innerHTML, we must use a Trusted HTML. So we need a policy for 'html'? But we only required for 'script'.
// Let me check: the `require-trusted-types-for` directive can take a list of context tokens. The tokens are: 'script', 'script attribute', 'style', 'style attribute'.
// It does not include 'html'. So innerHTML is not covered by `require-trusted-types-for`? Actually, innerHTML is covered by the 'script' context when it contains a script? I think not.
// According to the spec: the `require-trusted-types-for` directive controls the creation of script and style elements and attributes. It does not control innerHTML.
// So if we set innerHTML to a string that contains a script, the script element will be created and then the script element's text will be set. That text must be a Trusted Type if we have `require-trusted-types-for 'script'`.
// But how do we set the text of the script element? The browser does it when parsing the innerHTML string. So the string that is the content of the script tag in the innerHTML must be a Trusted Type? But we are setting innerHTML with a string, not a Trusted Type.
// This is confusing.
// Let me look at an example from the Trusted Types documentation:
// If we have:
// element.innerHTML = "<script>alert('xss')</script>";
// And we have CSP: require-trusted-types-for 'script';
// Then the browser will throw an error because the script element's text is not a Trusted Type.
// So we must do:
// const script = trustedTypes.createScript("alert('xss')");
// element.innerHTML = `<script>${script}</script>`;
// But that doesn't work because the script variable is an object and when we put it in a string, it becomes [object TrustedScript].
// Actually, we cannot use template literals with Trusted Scripts.
// The correct way is to create a script element and set its text:
// const script = trustedTypes.createScript("alert('xss')");
// const scriptEl = document.createElement('script');
// scriptEl.text = script; // or scriptEl.textContent = script; but that might not work because textContent expects a string.
// Actually, the Trusted Script is not a string. So we cannot set textContent to a Trusted Script.
// The proper way is to use the policy to create a script element? Or use the policy to create a script string that is safe?
// Wait, the policy's createScript returns a Trusted Script object. Then we can assign it to the text property of a script element? According to the spec, the text property of a script element is of type Trusted Script when required by CSP.
// So:
// const script = trustedTypes.createPolicy('default', { createScript: (s) => s })('alert(1)');
// const scriptEl = document.createElement('script');
// scriptEl.text = script; // This should work.
// But then we are not sanitizing.
// So the point is: we must change our code to not use innerHTML for scripts, and instead use the DOM API to create script elements and set their text to a Trusted Script.
// And for innerHTML that does not contain scripts, we don't need Trusted Types? But if we have `require-trusted-types-for 'script'`, then any script element created by the parser (from innerHTML) must have a Trusted Script as its text.
// So we cannot use innerHTML to set any HTML that contains a script tag without using Trusted Types for the script content.
// Therefore, we must avoid having script tags in innerHTML strings, or we must break the string and insert the script via DOM with a Trusted Script.
// This is a big change.
// Given the complexity, we might want to start by removing all inline scripts and use external scripts with nonces? Or use event handlers with nonces? But event handlers are also covered by `require-trusted-types-for` if we set 'script attribute'?
// We are only requiring for 'script'. So event handlers are not required? Actually, event handlers are set via attributes (like onclick) and that is a 'script attribute'. So if we set `require-trusted-types-for 'script'`, it does not cover event handlers. We would need to add 'script attribute' to the directive.
// But then we must use Trusted Types for event handlers too.
// So we might need:
// require-trusted-types-for 'script' 'script attribute'
// But then we must change all event handlers to use Trusted Types.
// This is very invasive.
// Alternatively, we can avoid using event handlers and use addEventListener? That doesn't require Trusted Types because it's not an attribute.
// So we might want to avoid inline event handlers.
// Given the complexity, we must audit our application and decide on a policy.
// For the baseline, we will assume we are using nonces for script-src and we are not using inline event handlers (or we are using addEventListener). And we are not using innerHTML to set scripts.
// Then we can set:
// require-trusted-types-for 'script'
// And then we must ensure that any script element created via the DOM (like document.createElement('script')) must have its text set via a Trusted Type.
// But if we are not creating any script elements via DOM, then we don't need to do anything.
// So we must audit.
// Given the time, we cannot cover all.
// So the baseline is:
// 1. Set HSTS and CSP with nonces and Trusted Types.
// 2. Define a Trusted Types policy that does nothing (or sanitizes) and update our code to use it for any script creation.
// But note: if we don't create any script elements via DOM, then we don't need to use Trusted Types? But the CSP requires that any script element created must have a Trusted Type. So if we have a script element in the HTML (with a nonce) that is created by the parser, does that require Trusted Types? No, because that script element is created by the parser and its text is already in the HTML. The `require-trusted-types-for` only applies to scripts created by the DOM API or by the parser from a string that is not trusted? Actually, the parser creates script elements from the HTML and the text is set as a string. That string must be a Trusted Type if we have `require-trusted-types-for`?
// According to the spec: when the parser creates a script element from an HTML file, the text is set as a string. That string must be a Trusted Type if `require-trusted-types-for` is set? I think not, because the HTML file is trusted by the server? But the server might have XSS.
// Actually, the purpose of Trusted Types is to prevent DOM-based XSS. So if the server sends a script tag in the HTML, that's not DOM-based XSS? It's reflected or stored XSS. So we don't need Trusted Types for that? But the CSP `require-trusted-types-for` applies to all script elements, regardless of how they are created.
// So if we have a script tag in the HTML, the browser will try to set the text of that script element and if we have `require-trusted-types-for 'script'`, then the text must be a Trusted Type. But the text is just a string from the HTML. So we get an error.
// Therefore, we must use nonces for inline scripts and also set the script content as a Trusted Type? But the nonce already allows the script to run. And the script content is set by the parser as a string. So we get an error.
// This means that we cannot have inline scripts with `require-trusted-types-for` unless we set the script content via a Trusted Type. But we cannot set it via a Trusted Type because the parser is doing it.
// So we must not have any inline scripts? Then we must move all inline scripts to external files and use nonces? But the nonce is for the script tag, not the content? Actually, the nonce is for the script tag, and the script content is still a string.
// Wait, the nonce in the script tag allows the script to run, but the script content is still a string. The `require-trusted-types-for` requires that the script content be a Trusted Type. So we have a conflict.
// Actually, the `require-trusted-types-for` directive does not affect the nonce. The nonce is for the script-src. The `require-trusted-types-for` is a separate requirement.
// So if we have:
// <script nonce="...">alert(1)</script>
// The nonce allows the script to be executed (because it's in script-src). But the `require-trusted-types-for` requires that the text of the script element (which is "alert(1)") must be a Trusted Type. But it's just a string. So we get an error.
// Therefore, we cannot have inline scripts at all if we use `require-trusted-types-for`? That doesn't make sense.
// Let me check the spec: the `require-trusted-types-for` directive requires that the specified DOM elements be assigned a value that is a Trusted Type. For a script element, the text content must be a Trusted Type.
// But when the parser parses the HTML and creates a script element, it sets the text content to the string inside the script tag. That string is not a Trusted Type. So it will fail.
// So we must not have any inline scripts? Then how do we include inline scripts? We must use the DOM API to create a script element and set its text to a Trusted Type.
// So we must move all inline scripts to external files? Or we must create them via JavaScript with a Trusted Type.
// But then we cannot have inline scripts in the HTML. That is a big change.
// Alternatively, we can set the CSP without `require-trusted-types-for` and rely on nonces and hashes for script-src? But then we are not protected against DOM-based XSS.
// Given the complexity, we might need to reconsider.
// Actually, the Trusted Types feature is designed to work with nonces? No, it's designed to work with policies.
// So the baseline might be:
// We set CSP with nonces and hashes for script-src, and we set `require-trusted-types-for` only if we have code that creates script elements via the DOM and we have updated that code to use Trusted Types.
// And we must remove all inline scripts from the HTML? Or we must create them via Trusted Types? But we cannot create them via Trusted Types because they are in the HTML.
// Wait, we can create a script element with a nonce and then set its content via a Trusted Type? But the nonce is for the script tag, and the content must be a Trusted Type.
// So we can have:
// <script nonce="..."></script>
// And then set the content via JavaScript:
// const script = document.querySelector('script[nonce="..."]');
// script.text = trustedTypes.createScript('alert(1)');
// But that's not inline, it's external? No, the script tag is in the HTML but empty, and we fill it with JavaScript. But then we are still using inline JavaScript to set the script? That's a chicken and egg.
// Given the complexity, I think we must avoid `require-trusted-types-for` until we have a plan to refactor our code.
// But the requirement is to roll out with staged enforcement. So we can start without `require-trusted-types-for` and then add it later when we are ready.
// So for the baseline, we might not include `require-trusted-types-for` in the first phase? But the requirement says to include Trusted Types.
// Alternatively, we can set `require-trusted-types-for` in report-only and then when we enforce, we must have fixed our code.
// But if we have inline scripts in the HTML, we will get violations even in report-only? Actually, the browser will report violations for any script element that does not have a Trusted Type as its text.
// So we will get a lot of reports for inline scripts.
// Then we must remove all inline scripts or create them via Trusted Types.
// Given the time, we might need to remove all inline scripts and use external scripts with nonces? But then we are not using Trusted Types for the script content? Actually, the external script content is set by the network, and the script element's text is set by the parser. So we get the same issue.
// So it seems that `require-trusted-types-for` will break all scripts that are not created with a Trusted Type, including those from external sources.
// Wait, external scripts are loaded via the src attribute, and the script element's text is set by the network. The network response is not a Trusted Type. So it will break.
// So we cannot use `require-trusted-types-for` with external scripts? Actually, the `require-trusted-types-for` applies to the script element's text. For an external script, the text is set by the network, which is not a Trusted Type. So it will fail.
// Therefore, `require-trusted-types-for` is only for inline scripts and scripts created via the DOM? And it will break external scripts.
// But wait, the spec says: when a script element is created by the parser or by the DOM, and the script element has a non-empty text content, then that text content must be a Trusted Type.
// For an external script, the script element has no text content (it's empty) and the src attribute is set. So it's not affected.
// So external scripts are okay because they don't have text content.
// Inline scripts have text content. So they are affected.
// So we must remove inline scripts or set them via Trusted Types.
// But we cannot set them via Trusted Types because they are in the HTML.
// So we must remove inline scripts and move them to external files? Then we don't have inline scripts, so we don't have script elements with text content.
// Then we can use `require-trusted-types-for` without breaking.
// So the plan:
// 1. Remove all inline scripts from the HTML and move them to external .js files.
// 2. Use nonces for those external scripts? Actually, the nonce is for the script tag, not the file. If we have an external script, we don't need a nonce because it's not inline. But we can add a nonce to the script tag? That doesn't make sense because the nonce is for inline scripts.
// Actually, the nonce is for inline scripts. For external scripts, we use the src and the script-src must allow that src.
// So if we remove all inline scripts, then our script-src can be:
// script-src 'self'
// and we don't need nonces.
// But then we lose the ability to have inline scripts. And we must move all JavaScript to external files.
// Given the requirement of Trusted Types, we must do that.
// So the baseline becomes:
// - No inline scripts.
// - All JavaScript in external files.
// - Use CSP with script-src 'self' and maybe a nonce for any inline script? But we don't have any.
// Then we can set `require-trusted-types-for 'script'` without breaking because we don't have any script elements with text content.
// But wait, what about event handlers? They are script attributes. So we must avoid inline event handlers (like onclick) and use addEventListener.
// So we must audit and remove all inline event handlers.
// This is a big refactor.
// Given the complexity, we might need to do this gradually.
// But the requirement is to roll out with staged enforcement. So we can:
// Phase 1: Remove inline scripts and inline event handlers, and set CSP without `require-trusted-types-for` and with nonces (but we don't have inline scripts, so we don't need nonces). So:
// script-src 'self'
// and no `require-trusted-types-for`.
// Then, after we have removed all inline scripts and event handlers, we can add `require-trusted-types-for` to protect against any future code that might create script elements via the DOM.
// But note: if we have no inline scripts, then we don't have script elements with text content. So `require-trusted-types-for` will not break anything.
// However, if we have code that creates a script element via the DOM and sets its text, then we must use Trusted Types.
// So we must update that code.
// So the baseline might be:
// Step 1: Remove all inline scripts and inline event handlers. Use external scripts and addEventListener.
// Step 2: Set CSP with script-src 'self' and without `require-trusted-types-for` (and report-only).
// Step 3: After monitoring, add `require-trusted-types-for` in report-only and fix any violations (by updating code that creates script elements via DOM to use Trusted Types).
// Step 4: Enforce `require-trusted-types-for`.
// But note: the requirement is to roll out HSTS, CSP, and Trusted Types with staged enforcement. So we might need to do:
// Phase 1: HSTS (short, without subdomains) and CSP (report-only, without Trusted Types) -> monitor.
// Phase 2: CSP (enforced, without Trusted Types) -> monitor.
// Phase 3: Add Trusted Types to CSP (report-only) and fix violations.
// Phase 4: Enforce Trusted Types.
// But then we have many phases.
// Given the complexity of Trusted Types, we might need to separate the rollout of Trusted Types from CSP.
// However, the baseline must include Trusted Types.
// So let's adjust:
// We are going to roll out:
// 1. HSTS in two phases (short without subdomains, then long with subdomains).
// 2. CSP in two phases (report-only, then enforced) and without Trusted Types initially? But the requirement says with Trusted Types.
// Alternatively, we can roll out Trusted Types separately.
// Given the time, I think we must provide a baseline that includes Trusted Types, but we must also provide guidance on how to prepare for Trusted Types.
// So the baseline headers:
// Phase 1 (HSTS short without subdomains, CSP report-only with Trusted Types in report-only and with reporting):
// Strict-Transport-Security: max-age=3600
// Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; require-trusted-types-for 'script'; report-uri /csp-report
// But note: we are not using nonces because we don't have inline scripts? But we might have inline scripts that we haven't removed. So we need to remove them first.
// So we must have already removed all inline scripts and event handlers before setting `require-trusted-types-for`.
// Therefore, the baseline assumes we have done that.
// So the steps:
// Step 0: Remove all inline scripts and inline event handlers. Use external scripts and addEventListener.
// Step 1: Set HSTS short without subdomains.
// Step 2: Set CSP in report-only with script-src 'self' and `require-trusted-types-for 'script'` and report-uri.
// Step 3: Monitor and fix any violations (which would be from code that creates script elements via DOM without Trusted Types).
// Step 4: Enforce CSP (with `require-trusted-types-for`).
// Step 5: Then, when all subdomains are HTTPS, set HSTS with includeSubDomains and long max-age.
// But note: in step 2, we are reporting on Trusted Types violations. We might have violations from our own code that creates script elements via DOM. We must fix them by using Trusted Types.
// How to use Trusted Types for creating a script element:
// const policy = trustedTypes.defaultPolicy; // or by name
// const script = policy.createScript('alert(1)');
// const scriptEl = document.createElement('script');
// scriptEl.text = script;
// document.head.appendChild(scriptEl);
// But note: the policy must be defined. We can define a policy that does nothing (or sanitizes) and then use it.
// So in our JavaScript, we define:
// if (window.trustedTypes) {
// window.trustedTypes.createPolicy('default', {
// createScript: (s) => s
// });
// }
// And then when we create a script element, we use:
// const script = trustedTypes.defaultPolicy.createScript('alert(1)');
// But note: the policy's createScript must return a Trusted Script. By returning the string, we are not sanitizing. So we must sanitize.
// So we must have a sanitization function.
// Given the complexity, we might use a library like DOMPurify for HTML, but for script, we might want to allow only certain scripts? It's tricky.
// Alternatively, we can avoid creating script elements via the DOM altogether.
// So the baseline is:
// - Remove all inline scripts and event handlers.
// - Use external scripts.
// - Do not create script elements via the DOM (unless absolutely necessary, and then use Trusted Types with a safe policy).
// Then we can set `require-trusted-types-for` without breaking.
// So the headers:
// Phase 1:
// Strict-Transport-Security: max-age=3600
// Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; require-trusted-types-for 'script'; report-uri /csp-report
// Phase 2:
// Strict-Transport-Security: max-age=15552000; includeSubDomains
// Content-Security-Policy: default-src 'self'; script-src 'self'; require-trusted-types-for 'script'; report-uri /csp-report
// But note: we are not using nonces because we don't have inline scripts. So script-src 'self' is enough for external scripts from the same origin.
// If we have inline scripts that we haven't removed, we will get violations. So we must remove them.
// Given the above, I think the baseline is:
// 1. HSTS with two phases.
// 2. CSP with two phases and with Trusted Types, but only after removing inline scripts and event handlers.
// So the answer:
// We will roll out:
// Phase 1 (Preparation):
// - Remove all inline scripts and inline event handlers.
// - Use external scripts and addEventListener.
// - Set HSTS with short max-age and without includeSubDomains.
// - Set CSP in report-only with script-src 'self' and `require-trusted-types-for 'script'` and a report-uri.
// Phase 2 (Enforce CSP):
// - Change CSP to enforced.
// Phase 3 (HSTS with subdomains):
// - Change HSTS to long max-age and includeSubDomains.
// And we must define a Trusted Types policy in our JavaScript (even if we don't use it, we must define it to avoid errors when we enforce? Actually, if we don't define a policy, then when we try to create a script element via DOM, it will throw. So we must define a policy that does nothing or sanitizes, and then use it in any code that creates script elements.
// But if we don't have any code that creates script elements, we don't need to define a policy? Actually, the browser will require a policy for any script element created via the DOM. So if we don't create any, we are safe.
// But we must define a policy to avoid errors? No, if we don't create any script element via the DOM, then we don't need to define a policy. The `require-trusted-types-for` will not cause any error because there is no attempt to create a script element.
// So we can skip defining a policy if we don't create script elements via the DOM.
// But to be safe, we can define an empty policy:
// if (window.trustedTypes) {
// window.trustedTypes.createPolicy('empty', { createScript: (s) => s });
// }
// And then use it if needed.
// Given the above, let's write the baseline headers.
// However, the original requirement says to roll out HSTS, CSP, and Trusted Types with staged enforcement. So we are doing:
// HSTS: two phases.
// CSP: two phases (report-only and enforced) and with Trusted Types included.
// So the final answer:
// Phase 1 (initial rollout):
// Strict-Transport-Security: max-age=3600
// Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; require-trusted-types-for 'script'; report-uri /csp-report
// Phase 2 (after monitoring and fixing, and after removing inline scripts and event handlers):
// Strict-Transport-Security: max-age=15552000; includeSubDomains
// Content-Security-Policy: default-src 'self'; script-src 'self'; require-trusted-types-for 'script'; report-uri /csp-report
// But note: in phase 1, we are not enforcing CSP, so we can have violations reported. We must fix them (remove inline scripts, etc.) before phase 2.
// And we must ensure that we don't have any inline scripts or event handlers.
// This is the baseline.
// However, if we have a need for inline scripts (like a nonce for a small piece of code), we cannot have them because we are requiring Trusted Types and we don't have a way to set the script content as a Trusted Type from the HTML.
// So we must avoid inline scripts entirely.
// Therefore, the baseline assumes no inline scripts.
// If we must have inline scripts, we must use a Trusted Type policy and then set the script content via JavaScript? But then the script tag is in the HTML and we cannot set its content via JavaScript because the parser has already set it as a string.
// So we cannot have inline scripts in the HTML if we use `require-trusted-types-for`.
// So the baseline is for applications that can remove all inline scripts.
// If we cannot remove all inline scripts, then we cannot use `require-trusted-types-for` and we must rely on nonces and hashes for script-src and hope that we don't have DOM-based XSS.
// Given the requirement, we are rolling out Trusted Types, so we must remove inline scripts.
// Final note: the baseline is for a modern web application that uses external scripts and no inline scripts or event handlers.
// If we have third-party scripts that are inline? We must move them to external files as well.
// So the answer:
// We will roll out the following headers in two phases:
// Phase 1 (Report Only for CSP, HSTS short without subdomains):
// Strict-Transport-Security: max-age=3600
// Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; require-trusted-types-for 'script'; report-uri /csp-report
// Phase 2 (Enforced for CSP, HSTS long with subdomains):
// Strict-Transport-Security: max-age=15552000; includeSubDomains
// Content-Security-Policy: default-src 'self'; script-src 'self'; require-trusted-types-for 'script'; report-uri /csp-report
// And we must ensure that:
// - All inline scripts and inline event handlers are removed.
// - All JavaScript is in external files.
// - We define a Trusted Types policy (even if empty) in our JavaScript to avoid errors if we ever create a script element via the DOM.
// But note: if we never create a script element via the DOM, we don't need to define a policy? Actually, the browser will throw an error only when we try to create a script element without a Trusted Type. So if we don't do that, we are safe.
// However, if we use a library that might create script elements (like some analytics scripts), then we must ensure they use Trusted Types.
// So we must audit all JavaScript code.
// Given the complexity, we might need to adjust the baseline for each application.
// But the above is the general idea.
// Let me write the answer accordingly.</think>
Security Header Baseline with Staged Enforcement
This baseline provides a phased rollout strategy for HSTS, CSP, and Trusted Types with monitoring before enforcement. All directives include reporting capabilities to monitor impact before activation.
Phase 1: Monitoring Only (Week 1-2)
Collect telemetry without blocking any traffic
Strict-Transport-Security:
max-age=300; # 5 minutes (short for testing)
includeSubDomains=false; # Test main domain first
Content-Security-Policy-Report-Only:
default-src 'self';
script-src 'self' 'nonce-{nonce}';
style-src 'self' 'nonce-{nonce}';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self';
frame-src 'none';
base-uri 'self';
require-trusted-types-for 'script';
report-uri https://yourdomain.com/csp-violations
report-to default-group;
Content-Security-Policy-Report-Only:
trusted-types default 'none'; # Monitor policy creation only
report-uri https://yourdomain.com/tt-violations;
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy:
geolocation=(),
microphone=(),
camera=()
Phase 2: Partial Enforcement (Week 3-4)
Enforce structural policies while keeping flexible directives in report-only
Strict-Transport-Security:
max-age=15552000; # 6 months
includeSubDomains; # Now enforce on all subdomains
preload; # Optional: Add after 30 days of stable operation
Content-Security-Policy:
default-src 'self';
style-src 'self' 'nonce-{nonce}';
img-src 'self' data:;
font-src 'self';
connect-src 'self';
frame-src 'none';
base-uri 'self';
require-trusted-types-for 'script';
report-uri https://yourdomain.com/csp-violations
report-to default-group;
Content-Security-Policy-Report-Only:
script-src 'self' 'nonce-{nonce}' 'strict-dynamic'
'sha256-{hash1}' 'sha256-{hash2}';
upgrade-insecure-requests; # Monitor mixed content
report-uri https://yourdomain.com/csp-violations;
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy:
geolocation=(),
microphone=(),
camera=()
Phase 3: Full Enforcement (Week 5+)
All policies enforced after monitoring period
Strict-Transport-Security:
max-age=15552000;
includeSubDomains;
preload;
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-{nonce}' 'strict-dynamic'
'sha256-{hash1}' 'sha256-{hash2}';
style-src 'self' 'nonce-{nonce}';
img-src 'self' data:;
font-src 'self';
connect-src 'self';
frame-src 'none';
base-uri 'self';
require-trusted-types-for 'script';
require-trusted-types-for 'script attribute';
report-uri https://yourdomain.com/csp-violations
report-to default-group;
upgrade-insecure-requests;
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy:
geolocation=(),
microphone=(),
camera=()
Implementation Checklist
Prerequisites
- ✅ HTTPS Everywhere: Ensure 100% HTTPS coverage across all subdomains
- ✅ Nonce Generation: Implement cryptographically random nonce per request
- ✅ Hash Calculation: Precompute hashes for all static inline scripts/styles
- ✅ Reporting Endpoint: Create
/csp-violations and /tt-violations endpoints (POST JSON)
Trusted Types Policy (JavaScript)
// Define policy BEFORE any DOM manipulation
if (window.trustedTypes && window.trustedTypes.createPolicy) {
window.trustedTypes.createPolicy('default', {
createHTML: (string) => DOMPurify.sanitize(string),
createScript: (string) => {
// Only allow specific patterns or use CSP nonces
if (string.includes('eval') || string.includes('Function')) {
throw new TypeError('Potentially unsafe script');
}
return string;
}
});
}
Monitoring Setup
// CSP/Trusted Types violation reporter
window.addEventListener('securitypolicyviolation', (e) => {
fetch('/csp-violations', {
method: 'POST',
body: JSON.stringify({
directive: e.violatedDirective,
blockedURI: e.blockedURI,
sourceFile: e.sourceFile,
lineNumber: e.lineNumber,
columnNumber: e.columnNumber,
status: e.statusCode
})
});
});
Validation Commands
# Test headers
curl -I https://yourdomain.com | grep -E "(Strict|Content|X-|Permissions)"
# Validate CSP
npm install -g csp-evaluator
csp-evaluator --json "default-src 'self'; ..."
# Check Trusted Types
# Open browser console and run:
trustedTypes.getPolicyNames()
Rollback Plan
- Immediate Rollback: Remove
Content-Security-Policy header → reverts to Content-Security-Policy-Report-Only
- HSTS Rollback: Set
max-age=0 on all subdomains
- Emergency Bypass: Add
unsafe-inline to script-src temporarily (NOT recommended for production)
Key Notes
- Nonce Management: Must rotate per request; store in template variable
- Subdomain Coverage:
includeSubDomains affects ALL subdomains—test thoroughly
- Third-Party Scripts: Add specific domains to
script-src if needed; avoid *
- Legacy Browsers: IE/old Android may break—consider polyfills or separate user-agent rules
- Preload List: After 30 days of stable Phase 3, submit to Chrome preload list: https://hstspreload.org/
Timeline Summary
Week 1-2: Phase 1 (monitoring only)
Week 3-4: Phase 2 (partial enforcement)
Week 5+: Phase 3 (full enforcement)
→ 30 days stable → Submit to HSTS preload list
This approach minimizes risk by:
- Monitoring first: See what would break without affecting users
- Strictest last: Build confidence with less restrictive policies
- Telemetry-driven: Use violation reports to prioritize fixes
- Reversible: Each phase can be rolled back independently
Remember to communicate with stakeholders about potential third-party integrations that may require updates (analytics, chat widgets, etc.).