sandpack icon indicating copy to clipboard operation
sandpack copied to clipboard

Unnecessary usage of eval requires unsafe-eval in CSP

Open arcticmatt opened this issue 1 year ago • 2 comments

Bug report

Packages affected

  • [ ] sandpack-client
  • [x] sandpack-react

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.

arcticmatt avatar Oct 25 '24 01:10 arcticmatt