From eb20136e2c2231a886e9aaff465bbe7343601359 Mon Sep 17 00:00:00 2001 From: Stephanie DiBenedetto Date: Wed, 13 Aug 2025 13:36:51 -0700 Subject: [PATCH] Limit global resolution to globalThis Historically we've supported old platforms with a variety of fallback options for determining a global object. However, our use of Function('return this') is essentially an eval, which causes issues for strict CSP. On consulation with other teams, we think we can just rely on globalThis at this point in time. --- generator/js_generator.cc | 21 +-------------------- internal_options.js | 3 +-- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/generator/js_generator.cc b/generator/js_generator.cc index d6a9e79..a1619fa 100644 --- a/generator/js_generator.cc +++ b/generator/js_generator.cc @@ -3641,26 +3641,7 @@ void Generator::GenerateFile(const GeneratorOptions& options, if (options.import_style == GeneratorOptions::kImportCommonJsStrict) { printer->Print("var proto = {};\n\n"); } else { - // To get the global object we call a function with .call(null), this will - // set "this" inside the function to the global object. This does not work - // if we are running in strict mode ("use strict"), so we fallback to the - // following things (in order from first to last): - // - globalThis: cross-platform standard, might not be defined in older - // versions of browsers - // - window: defined in browsers - // - global: defined in most server side environments like NodeJS - // - self: defined inside Web Workers (WorkerGlobalScope) - // - Function('return this')(): this will work on most platforms, but it - // may be blocked by things like CSP. - // Function('') is almost the same as eval('') - printer->Print( - "var global =\n" - " (typeof globalThis !== 'undefined' && globalThis) ||\n" - " (typeof window !== 'undefined' && window) ||\n" - " (typeof global !== 'undefined' && global) ||\n" - " (typeof self !== 'undefined' && self) ||\n" - " (function () { return this; }).call(null) ||\n" - " Function('return this')();\n\n"); + printer->Print("var global = globalThis;\n\n"); } for (int i = 0; i < file->dependency_count(); i++) { diff --git a/internal_options.js b/internal_options.js index ecdac9e..aff1018 100644 --- a/internal_options.js +++ b/internal_options.js @@ -28,14 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** - * @fileoverview Internal options for. + * @fileoverview Internal options. */ goog.module('jspb.internal_options'); /** * @return {boolean} True if BigInt is permitted for use and supported by the * platform. - * @nosideeffects */ function isBigIntAvailable() { return goog.FEATURESET_YEAR >= 2021 || (typeof BigInt === 'function');