@stevenleep/sandbox
Version:
A powerful JavaScript sandbox library that provides multiple sandbox implementation options for safely executing untrusted code in browser environments.
65 lines (52 loc) • 2.17 kB
text/typescript
// Demo of completely isolated sandbox usage
import { getBestSandboxType, createSandbox } from '@stevenleep/sandbox';
// Get the best available sandbox type for the current environment
const sandboxType = getBestSandboxType();
console.log(`Using sandbox type: ${sandboxType}`);
// Create a sandbox with maximum isolation
const sandbox = createSandbox(sandboxType, {
name: "isolated-sandbox",
// List properties that should be restricted from modification
blacklist: [
'localStorage',
'sessionStorage',
'indexedDB',
'openDatabase',
'WebSocket',
'XMLHttpRequest',
'fetch',
'document'
],
// Enforce strict mode for full isolation
strictMode: true,
});
console.log("Sandbox created:", sandbox.name);
// Define a global variable before activating the sandbox
(window as any).___outsideVar = "I'm defined outside the sandbox";
console.log("Global variable before sandbox:", (window as any).___outsideVar);
// Activate the sandbox before using it
sandbox.activate();
// Execute some test code in the sandbox
sandbox.execScript(`
// This should be contained within the sandbox
window.___testVariable = "I'm isolated in the sandbox";
console.log("Hello from the sandbox!");
// This shouldn't modify the real window's property
window.___outsideVar = "Modified inside sandbox";
console.log("Outside variable accessed inside sandbox:", window.___outsideVar);
`);
// Verify that variables defined in the sandbox are accessible within the sandbox
const sandboxResult = sandbox.execScript(`
console.log("Sandbox variable value:", window.___testVariable);
return {
insideVar: window.___testVariable,
outsideVarSandboxView: window.___outsideVar
};
`);
console.log("Result from sandbox execution:", sandboxResult);
// Verify complete isolation from the global window
console.log("Global ___testVariable (should be undefined):", (window as any).___testVariable);
console.log("Global ___outsideVar (should be unchanged):", (window as any).___outsideVar);
// Clean up when finished
sandbox.deactivate();
sandbox.destroy();