-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
67 lines (57 loc) · 1.57 KB
/
worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
self.addEventListener('fetch', function(event) {
event.respondWith(
new Response('', {
headers: {
'Content-Security-Policy': "default-src 'none'; script-src 'self';"
}
})
);
});
function executeJavaScriptCode(jsCode, editorId) {
jsCode = sanitizeJavaScriptCode(jsCode);
const functionRegex = /function\s+([a-zA-Z_$][0-9a-zA-Z_$]*)\s*\(([^)]*)\)\s*{([^]*)}/g;
let match;
while ((match = functionRegex.exec(jsCode)) !== null) {
const functionName = match[1].trim();
const functionParameters = match[2].split(',').map(param => param.trim());
const functionBody = match[3];
try {
self[functionName] = new Function(...functionParameters, functionBody);
} catch (error) {
console.error(`Error creating function ${functionName}:`, error);
}
}
let result;
try {
result = new Function(jsCode)();
} catch (error) {
result = `Error: ${error.message}`;
}
self.postMessage(result);
}
self.onmessage = function(event) {
const { jsCode, editorId } = event.data;
executeJavaScriptCode(jsCode, editorId);
};
function sanitizeJavaScriptCode(jsCode) {
const dangerousPatterns = [
/eval\s*\(/g,
/importScripts\s*\(/g,
/document\s*\./g,
/window\s*\./g,
/self\s*\./g,
/XMLHttpRequest\s*\(/g,
/fetch\s*\(/g,
/WebSocket\s*\(/g,
/Worker\s*\(/g,
/navigator\s*\./g,
/localStorage\s*\./g,
/sessionStorage\s*\./g,
/IndexedDB\s*\./g,
/postMessage\s*\(/g
];
dangerousPatterns.forEach(pattern => {
jsCode = jsCode.replace(pattern, '');
});
return jsCode;
}