How to Configure Strict Content Security Policy (CSP) with Trusted Types eval() Restrictions in Google Chrome

Dynamic string evaluation via eval(), new Function(), and asynchronous timers (setTimeout("string")) represents a notorious vector for client-side code execution. While traditional Content Security Policy (CSP) headers can ban dynamic code execution using 'unsafe-eval', complex enterprise web applications frequently rely on templating engines, WebAssembly runtimes, or mathematical parsers that legitimately require runtime code synthesis. Trusted Types bridges this gap in Google Chrome: it permits runtime evaluation only when arguments are wrapped in cryptographically verified or sanitized TrustedScript objects.

Understanding eval() Restrictions Under Trusted Types

When Trusted Types is enforced alongside CSP, Google Chrome alters its treatment of script evaluation sinks:

  • Passing a raw string to eval(untrustedString) immediately throws a runtime TypeError: Failed to execute 'eval': This document requires 'TrustedScript' assignment.
  • Applications must generate dynamic script snippets through an authorized policy that yields a verified TrustedScript object.
  • The CSP directive trusted-types acts as an allowlist, restricting policy creation to named factories registered by core application bundles.

Configuring Web Server Headers for Eval Lockdown

Configure your production web server to enforce Trusted Types while managing eval permissions:

# Nginx server block configuration
add_header Content-Security-Policy "require-trusted-types-for 'script'; trusted-types default template-engine-policy;" always;

# Apache HTTP Server (.htaccess / virtual host)
Header always set Content-Security-Policy "require-trusted-types-for 'script'; trusted-types default template-engine-policy;"

Authoring an Authorized TrustedScript Factory in JavaScript

Implement an application-level policy to safely validate and wrap mathematical expressions or dynamic templates:

// Register verified policy with the browser's Trusted Types runtime
if (window.trustedTypes && window.trustedTypes.createPolicy) {
    const scriptPolicy = window.trustedTypes.createPolicy('template-engine-policy', {
        createScript: (sourceCode) => {
            // Strictly validate that source contains only safe mathematical expressions
            const mathRegex = /^[ds+-*/().]+$/;
            if (mathRegex.test(sourceCode)) {
                return sourceCode;
            }
            throw new TypeError('Dynamic eval execution rejected: Invalid script syntax');
        }
    });

    // Invoke dynamic evaluation safely using the typed object
    function calculateFormula(rawExpression) {
        const safeScript = scriptPolicy.createScript(rawExpression);
        return window.eval(safeScript); // Allowed by Google Chrome
    }
}

Auditing Eval Blocking in Chrome DevTools

To inspect and troubleshoot script evaluation violations in Google Chrome:

  1. Open Google Chrome and navigate to your application.
  2. Open Chrome DevTools by pressing Ctrl + Shift + I (or Option + Command + I on macOS).
  3. Select the Sources tab, navigate to the Breakpoints pane, and expand Trusted Type Violations.
  4. Check Sink Violations. Chrome automatically pauses execution directly on the line of code attempting to pass unvetted strings into eval() or Function().
  5. Inspect the Console tab to view detailed stack traces and identify legacy dependencies attempting string evaluation without typed wrappers.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.