codesandbox / sandpack

A component toolkit for creating live-running code editing experiences, using the power of CodeSandbox.
https://sandpack.codesandbox.io
Apache License 2.0
4.93k stars 355 forks source link

Unnecessary usage of eval requires unsafe-eval in CSP #1221

Open arcticmatt opened 1 month ago

arcticmatt commented 1 month ago

Bug report

Packages affected

Description of the problem

This code uses eval("this"). AFAICT this is unnecessary, and we could instead do something like:

function getGlobalObject() {
  if (typeof globalThis !== "undefined") {
    // Modern standard
    return globalThis;
  } else if (typeof window !== "undefined") {
    // Browsers
    return window;
  } else if (typeof global !== "undefined") {
    // Node.js
    return global;
  } else if (typeof self !== "undefined") {
    // Web Workers
    return self;
  }
  throw new Error("Unable to locate global object.");
}

const GLOBAL = getGlobalObject();

With the current approach, if you use SandpackPreview, it will raise an error unless unsafe-eval is included in your CSP. It would be better if SandpackPreview was usable without making the CSP less safe.

@danilowoz I saw you introduced this code, curious for your thoughts here—I might be missing something about why eval("this") is used.

Dari4sho commented 2 weeks ago

I'm currently having this problem trying to implement a library (mdx-editor - that is using this package as a dependency) inside a chrome-extension - unsafe-eval is not allowed there.

Thanks to your suggestion @arcticmatt, I monkey patched the library accordingly for my project - it works perfectly fine! I created this gist with the patch for anyone interested in a quick access: https://gist.github.com/Dari4sho/71d5ea6eae4d50352d4244e61ebe4c6e

jonastreub commented 6 days ago

We at Framer are also running into this and now thinking of maybe forking for this reason