Strict Content Security Policy (CSP) settings can conflict with essential functionalities. Recently, we at 51Degrees assisted a client in overcoming CSP issues that affected their device detection capabilities.
The client’s restrictive CSP settings triggered this error in the Chrome browser on a page that had 51degrees client side device detection solution integrated:
“Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source…”
This prevented the execution of our client side device detection script, which requires dynamic JavaScript execution for accurate functionality.
Why ‘unsafe-eval’ is Needed
Our solution relies on the Function()
API to execute minimal, dynamically loaded code snippets that adapt to detected software and hardware. This ensures that only essential operations are performed for efficient and accurate detection. Function()
API similarly to eval() converts string snippets loaded from the server into the executable javascript code. This functionality is restricted by CSP, unless ‘unsafe-eval’ source expression is specified.
Explored Solutions: Initial Options That Fell Short
Several potential solutions were evaluated, but none met the client’s needs due to inherent limitations:
- Nonce-Based Approach: Seemed promising but was insufficient because the
Function()
API still requires ‘unsafe-eval’, even when using nonces. - Selective ‘unsafe-eval’ Application: We considered applying ‘unsafe-eval’ only to specific sources, but CSP does not support this—it’s applied globally across all scripts.
- Trusted Types API: This future-focused solution aims to add a 'trusted-types-eval' source expression that would allow to bypass the ‘unsafe-eval’, but even when it is implemented - the support will be not universal.
Recommendation: Enable ‘unsafe-eval’ Temporarily
We recommended enabling ‘unsafe-eval’ as a temporary measure to restore full functionality. We reassured the client:
"Allowing limited dynamic JavaScript already implies similar risks. Omitting ‘unsafe-eval’ doesn’t add protection."
Given that their existing CSP already imposed strict limits on cross-site requests, enabling ‘unsafe-eval’ was deemed a reasonable short-term compromise. At 51Degrees, we stay informed on evolving security standards and continue to support our clients with the latest solutions and guidance, but sometimes there is no way to overcome over-restricted security requirements.