Skip to content

Instantly share code, notes, and snippets.

@jmonteiro
Created November 20, 2025 13:57
Show Gist options
  • Select an option

  • Save jmonteiro/5dcb6f66ba9d538ca73132f28875a383 to your computer and use it in GitHub Desktop.

Select an option

Save jmonteiro/5dcb6f66ba9d538ca73132f28875a383 to your computer and use it in GitHub Desktop.
/**
* Vite plugin to fix CSP violations caused by singular-sdk
*
* ## Problem:
* The singular-sdk package (v1.4.8), contains code that uses `new Function("return this")()` to access the global object. This pattern requires 'unsafe-eval' in the Content Security Policy, which violates our CSP restrictions.
*
* ## Root Cause:
* - singular-sdk is a webpack-bundled UMD module
* - It uses `new Function("return this")()` as a cross-environment way to get
* the global object (works in browsers, Node.js, workers, etc.)
* - This pattern appears in the bundled code at module index 9
* - When Vite pre-bundles dependencies, this code gets included in the
* .vite/deps bundle, causing CSP violations in the browser
*
* ## Solution:
* This plugin intercepts the code during Vite's transform phase and replaces
* `new Function("return this")()` with `globalThis`, which is:
* - Supported in all modern browsers (our target environment)
* - CSP-safe (doesn't require 'unsafe-eval')
* - Functionally equivalent for our use case
*/
export default function fixSingularSdkCSP() {
return {
name: 'fix-singular-sdk-csp',
transform(code, id) {
// Target singular-sdk directly and Vite's pre-bundled deps that include it
if (id.includes('singular-sdk') || id.includes('.vite/deps')) {
let fixedCode = code;
let hasChanges = false;
// Replace new Function("return this")() with globalThis
// This pattern appears in singular-sdk's UMD wrapper for global object access
const pattern = /new Function\(["']return this["']\)\(\)/g;
if (pattern.test(code)) {
fixedCode = fixedCode.replace(pattern, 'globalThis');
hasChanges = true;
}
if (hasChanges) {
console.log(`[fix-singular-sdk-csp] Fixed CSP violation in: ${id.split('node_modules/').pop()}`);
return {
code: fixedCode,
map: null
};
}
}
return null;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment