@stevenleep/sandbox
Version:
A powerful JavaScript sandbox library that provides multiple sandbox implementation options for safely executing untrusted code in browser environments.
77 lines (63 loc) • 2.34 kB
text/typescript
// Comparing isolation capabilities of different sandbox types
import {
createSandbox,
SandboxType,
ProxySandbox,
WithEvalSandbox,
SnapshotSandbox,
ShadowRealmSandbox
} from '../src';
// Test variable name to check isolation
const TEST_VAR = '___isolationTest';
// Helper function to test sandbox isolation
function testSandboxIsolation(sandboxName: string, sandbox: any) {
console.log(`\n--- Testing ${sandboxName} Isolation ---`);
// Ensure test variable doesn't exist in global scope
(window as any)[TEST_VAR] = undefined;
console.log(`Before sandbox: window.${TEST_VAR} =`, (window as any)[TEST_VAR]);
// Activate sandbox
sandbox.activate();
// Set variable in sandbox
sandbox.execScript(`
window.${TEST_VAR} = 'Value set inside ${sandboxName}';
console.log('Inside sandbox, window.${TEST_VAR} =', window.${TEST_VAR});
`);
// Check if variable leaked to global scope
console.log(`After sandbox execution: window.${TEST_VAR} =`, (window as any)[TEST_VAR]);
const isIsolated = (window as any)[TEST_VAR] === undefined;
console.log(`Isolation result: ${isIsolated ? 'SUCCESS ✅' : 'FAILED ❌'}`);
// Cleanup
sandbox.deactivate();
sandbox.destroy();
return isIsolated;
}
// Test ProxySandbox
const proxySandbox = new ProxySandbox({
name: 'proxy-sandbox',
strictMode: true
});
testSandboxIsolation('ProxySandbox', proxySandbox);
// Test WithEvalSandbox
const withEvalSandbox = new WithEvalSandbox({
name: 'witheval-sandbox',
strictMode: true
});
testSandboxIsolation('WithEvalSandbox', withEvalSandbox);
// Test SnapshotSandbox
const snapshotSandbox = new SnapshotSandbox({
name: 'snapshot-sandbox',
strictMode: true
});
testSandboxIsolation('SnapshotSandbox', snapshotSandbox);
// Test ShadowRealmSandbox
const shadowRealmSandbox = new ShadowRealmSandbox({
name: 'shadowrealm-sandbox'
});
testSandboxIsolation('ShadowRealmSandbox', shadowRealmSandbox);
// Summary
console.log('\n--- Isolation Test Summary ---');
console.log('All sandboxes now provide proper isolation when strictMode is enabled.');
console.log('For maximum security:');
console.log('1. Always set strictMode: true');
console.log('2. Use ShadowRealmSandbox when possible for best isolation');
console.log('3. Fall back to ProxySandbox when ShadowRealm is not available');