@stevenleep/sandbox
Version:
A powerful JavaScript sandbox library that provides multiple sandbox implementation options for safely executing untrusted code in browser environments.
141 lines (125 loc) โข 4.24 kB
text/typescript
// Sample ShadowRealm Sandbox demo
import { ShadowRealmSandbox } from '../src';
/**
* This example demonstrates how to use the ShadowRealmSandbox
* featuring security controls, memory management, and resource limits
*/
async function shadowRealmDemo() {
console.log('๐ ShadowRealm Sandbox Demo');
console.log('------------------------------');
// Create a ShadowRealm sandbox with security and resource limits
const sandbox = new ShadowRealmSandbox({
name: 'demo-shadowrealm',
// Use iframe fallback for better compatibility
forceIframe: true,
// Set execution timeout
timeLimit: 3000,
// Enable strict mode
strictMode: true,
// Enable performance measurement
enablePerformanceMeasure: true,
// Security configuration
security: {
// Prevent access to sensitive APIs
preventSensitiveAPIs: true,
// Block network access
allowNetwork: false
},
// Custom error handler
errorHandler: (error, code) => {
console.error('๐ Sandbox execution error:', error.message);
console.log('Problematic code:', code);
}
});
// Activate the sandbox
sandbox.activate();
// Basic code execution
console.log('\n๐ Basic Execution:');
const result = sandbox.execScript(`
const a = 5;
const b = 7;
return a + b;
`);
console.log('Result:', result);
// Demonstrate isolation
console.log('\n๐ Demonstrating Isolation:');
sandbox.execScript(`window.isolationTest = 'This should be contained';`);
console.log('In sandbox:', sandbox.execScript(`return window.isolationTest;`));
console.log('In main context:', typeof (window as any).isolationTest);
// Demonstrate security features
console.log('\n๐ก๏ธ Demonstrating Security Features:');
try {
sandbox.execScript(`
try {
// Attempt to access fetch API (should be restricted)
return typeof fetch;
} catch (e) {
return e.message;
}
`);
} catch (error) {
console.log('Security restriction in action:', error);
}
// Demonstrate function export and import
console.log('\n๐ Demonstrating Function Export/Import:');
// Export a function from main context to sandbox
const multiplyFn = (a: number, b: number) => a * b;
sandbox.exportFunction('multiply', multiplyFn);
// Use the exported function in the sandbox
const multiplyResult = sandbox.execScript(`
return multiply(5, 7);
`);
console.log('Using exported function in sandbox:', multiplyResult);
// Define a function in the sandbox
sandbox.execScript(`
function add(a, b) {
return a + b;
}
`);
// Import the function from sandbox to main context
const addFn = sandbox.importFunction('add');
console.log('Using imported function in main context:', addFn(10, 20));
// Demonstrate async execution with timeout
console.log('\nโฑ๏ธ Demonstrating Async Execution with Timeout:');
try {
const asyncResult = await sandbox.execScriptAsync(`
return new Promise(resolve => {
setTimeout(() => {
resolve('Async operation completed');
}, 100);
});
`, 500);
console.log('Async result:', asyncResult);
} catch (error) {
console.error('Async execution error:', error);
}
// Demonstrate timeout for long-running operations
console.log('\nโฐ Demonstrating Timeout for Long-Running Operations:');
try {
await sandbox.execScriptAsync(`
// This should timeout after 1 second
return new Promise(resolve => {
let counter = 0;
const interval = setInterval(() => {
counter++;
if (counter >= 1000) {
clearInterval(interval);
resolve('This should never resolve');
}
}, 10);
});
`, 1000);
} catch (error) {
console.log('Timeout worked:', error.message);
}
// Clean up resources
console.log('\n๐งน Cleaning Up Resources:');
console.log('Deactivating and destroying sandbox...');
sandbox.deactivate();
sandbox.destroy();
console.log('Sandbox destroyed.');
console.log('\nโ
ShadowRealm Sandbox Demo Completed');
}
// Run the demo
shadowRealmDemo()
.catch(error => console.error('Demo failed:', error));