From b88e31d8d6c6685f30eab3df5b9644c9d31eece4 Mon Sep 17 00:00:00 2001 From: Eugene Stativka Date: Wed, 20 Nov 2024 14:00:36 +0100 Subject: [PATCH] fix: replace eval with globalThis to comply with CSP policies **Issue:** Sandpack currently uses `eval` to obtain the global object, which triggers CSP `unsafe-eval` violations. This poses security risks and limits the ability to use Sandpack in environments with strict CSP policies. **Solution:** Replaced the `eval`-based approach with an IIFE that sequentially checks for `globalThis`, `self`, `window`, and `global` to securely access the global object without violating CSP policies. **Testing:** - Tested in a local development environment with CSP enforced to ensure no violations occur. **Related Issue:** - [1221](https://github.com/codesandbox/sandpack/issues/1221) --- .../src/components/Console/utils/transformers.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/sandpack-react/src/components/Console/utils/transformers.ts b/sandpack-react/src/components/Console/utils/transformers.ts index d20bdc78a..f5addc2ec 100644 --- a/sandpack-react/src/components/Console/utils/transformers.ts +++ b/sandpack-react/src/components/Console/utils/transformers.ts @@ -3,11 +3,17 @@ /* eslint-disable @typescript-eslint/explicit-function-return-type */ /* eslint-disable @typescript-eslint/no-explicit-any */ // Const -const GLOBAL = (function getGlobal() { - // NOTE: see http://www.ecma-international.org/ecma-262/6.0/index.html#sec-performeval step 10 - const savedEval = eval; +const GLOBAL = (function getGlobal(): any { + if (typeof globalThis !== "undefined") return globalThis; // modern standard - return savedEval("this"); + if (typeof window !== "undefined") return window; // browser + + if (typeof global !== "undefined") return global; // Node.js + + // eslint-disable-next-line no-restricted-globals + if (typeof self !== "undefined") return self; // Web Worker + + throw Error("Unable to locate global object"); })(); const ARRAY_BUFFER_SUPPORTED = typeof ArrayBuffer === "function";