-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathisolated-vm.ts
More file actions
338 lines (298 loc) · 9.25 KB
/
isolated-vm.ts
File metadata and controls
338 lines (298 loc) · 9.25 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { type ChildProcess, execSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { validateProxyUrl } from '@/lib/core/security/input-validation'
import { createLogger } from '@/lib/logs/console/logger'
const logger = createLogger('IsolatedVMExecution')
let nodeAvailable: boolean | null = null
function checkNodeAvailable(): boolean {
if (nodeAvailable !== null) return nodeAvailable
try {
execSync('node --version', { stdio: 'ignore' })
nodeAvailable = true
} catch {
nodeAvailable = false
}
return nodeAvailable
}
export interface IsolatedVMExecutionRequest {
code: string
params: Record<string, unknown>
envVars: Record<string, string>
contextVariables: Record<string, unknown>
timeoutMs: number
requestId: string
}
export interface IsolatedVMExecutionResult {
result: unknown
stdout: string
error?: IsolatedVMError
}
export interface IsolatedVMError {
message: string
name: string
stack?: string
line?: number
column?: number
lineContent?: string
}
interface PendingExecution {
resolve: (result: IsolatedVMExecutionResult) => void
timeout: ReturnType<typeof setTimeout>
}
let worker: ChildProcess | null = null
let workerReady = false
let workerReadyPromise: Promise<void> | null = null
let workerIdleTimeout: ReturnType<typeof setTimeout> | null = null
const pendingExecutions = new Map<number, PendingExecution>()
let executionIdCounter = 0
const WORKER_IDLE_TIMEOUT_MS = 60000
function cleanupWorker() {
if (workerIdleTimeout) {
clearTimeout(workerIdleTimeout)
workerIdleTimeout = null
}
if (worker) {
worker.kill()
worker = null
}
workerReady = false
workerReadyPromise = null
}
function resetIdleTimeout() {
if (workerIdleTimeout) {
clearTimeout(workerIdleTimeout)
}
workerIdleTimeout = setTimeout(() => {
if (pendingExecutions.size === 0) {
logger.info('Cleaning up idle isolated-vm worker')
cleanupWorker()
}
}, WORKER_IDLE_TIMEOUT_MS)
}
/**
* Secure fetch wrapper that validates URLs to prevent SSRF attacks
*/
async function secureFetch(requestId: string, url: string, options?: RequestInit): Promise<string> {
const validation = validateProxyUrl(url)
if (!validation.isValid) {
logger.warn(`[${requestId}] Blocked fetch request due to SSRF validation`, {
url: url.substring(0, 100),
error: validation.error,
})
return JSON.stringify({ error: `Security Error: ${validation.error}` })
}
try {
const response = await fetch(url, options)
const body = await response.text()
const headers: Record<string, string> = {}
response.headers.forEach((value, key) => {
headers[key] = value
})
return JSON.stringify({
ok: response.ok,
status: response.status,
statusText: response.statusText,
body,
headers,
})
} catch (error: unknown) {
return JSON.stringify({ error: error instanceof Error ? error.message : 'Unknown fetch error' })
}
}
/**
* Handle IPC messages from the Node.js worker
*/
function handleWorkerMessage(message: unknown) {
if (typeof message !== 'object' || message === null) return
const msg = message as Record<string, unknown>
if (msg.type === 'result') {
const pending = pendingExecutions.get(msg.executionId as number)
if (pending) {
clearTimeout(pending.timeout)
pendingExecutions.delete(msg.executionId as number)
pending.resolve(msg.result as IsolatedVMExecutionResult)
}
return
}
if (msg.type === 'fetch') {
const { fetchId, requestId, url, optionsJson } = msg as {
fetchId: number
requestId: string
url: string
optionsJson?: string
}
let options: RequestInit | undefined
if (optionsJson) {
try {
options = JSON.parse(optionsJson)
} catch {
worker?.send({
type: 'fetchResponse',
fetchId,
response: JSON.stringify({ error: 'Invalid fetch options JSON' }),
})
return
}
}
secureFetch(requestId, url, options)
.then((response) => {
try {
worker?.send({ type: 'fetchResponse', fetchId, response })
} catch (err) {
logger.error('Failed to send fetch response to worker', { err, fetchId })
}
})
.catch((err) => {
try {
worker?.send({
type: 'fetchResponse',
fetchId,
response: JSON.stringify({
error: err instanceof Error ? err.message : 'Fetch failed',
}),
})
} catch (sendErr) {
logger.error('Failed to send fetch error to worker', { sendErr, fetchId })
}
})
}
}
/**
* Start the Node.js worker process
*/
async function ensureWorker(): Promise<void> {
if (workerReady && worker) return
if (workerReadyPromise) return workerReadyPromise
workerReadyPromise = new Promise<void>((resolve, reject) => {
if (!checkNodeAvailable()) {
reject(
new Error(
'Node.js is required for code execution but was not found. ' +
'Please install Node.js (v20+) from https://nodejs.org'
)
)
return
}
const currentDir = path.dirname(fileURLToPath(import.meta.url))
const workerPath = path.join(currentDir, 'isolated-vm-worker.cjs')
if (!fs.existsSync(workerPath)) {
reject(new Error(`Worker file not found at ${workerPath}`))
return
}
import('node:child_process').then(({ spawn }) => {
worker = spawn('node', [workerPath], {
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
serialization: 'json',
})
worker.on('message', handleWorkerMessage)
let stderrData = ''
worker.stderr?.on('data', (data: Buffer) => {
stderrData += data.toString()
})
const startTimeout = setTimeout(() => {
worker?.kill()
worker = null
workerReady = false
workerReadyPromise = null
reject(new Error('Worker failed to start within timeout'))
}, 10000)
const readyHandler = (message: unknown) => {
if (
typeof message === 'object' &&
message !== null &&
(message as { type?: string }).type === 'ready'
) {
workerReady = true
clearTimeout(startTimeout)
worker?.off('message', readyHandler)
resolve()
}
}
worker.on('message', readyHandler)
worker.on('exit', (code) => {
if (workerIdleTimeout) {
clearTimeout(workerIdleTimeout)
workerIdleTimeout = null
}
const wasStartupFailure = !workerReady && workerReadyPromise
worker = null
workerReady = false
workerReadyPromise = null
let errorMessage = 'Worker process exited unexpectedly'
if (stderrData.includes('isolated_vm') || stderrData.includes('MODULE_NOT_FOUND')) {
errorMessage =
'Code execution requires the isolated-vm native module which failed to load. ' +
'This usually means the module needs to be rebuilt for your Node.js version. ' +
'Please run: cd node_modules/isolated-vm && npm rebuild'
logger.error('isolated-vm module failed to load', { stderr: stderrData })
} else if (stderrData) {
errorMessage = `Worker process failed: ${stderrData.slice(0, 500)}`
logger.error('Worker process failed', { stderr: stderrData })
}
if (wasStartupFailure) {
clearTimeout(startTimeout)
reject(new Error(errorMessage))
return
}
for (const [id, pending] of pendingExecutions) {
clearTimeout(pending.timeout)
pending.resolve({
result: null,
stdout: '',
error: { message: errorMessage, name: 'WorkerError' },
})
pendingExecutions.delete(id)
}
})
})
})
return workerReadyPromise
}
/**
* Execute JavaScript code in an isolated V8 isolate via Node.js subprocess.
* The worker's V8 isolate enforces timeoutMs internally. The parent timeout
* (timeoutMs + 1000) is a safety buffer for IPC communication.
*/
export async function executeInIsolatedVM(
req: IsolatedVMExecutionRequest
): Promise<IsolatedVMExecutionResult> {
if (workerIdleTimeout) {
clearTimeout(workerIdleTimeout)
workerIdleTimeout = null
}
await ensureWorker()
if (!worker) {
return {
result: null,
stdout: '',
error: { message: 'Failed to start isolated-vm worker', name: 'WorkerError' },
}
}
const executionId = ++executionIdCounter
return new Promise((resolve) => {
const timeout = setTimeout(() => {
pendingExecutions.delete(executionId)
resolve({
result: null,
stdout: '',
error: { message: `Execution timed out after ${req.timeoutMs}ms`, name: 'TimeoutError' },
})
}, req.timeoutMs + 1000)
pendingExecutions.set(executionId, { resolve, timeout })
try {
worker!.send({ type: 'execute', executionId, request: req })
} catch {
clearTimeout(timeout)
pendingExecutions.delete(executionId)
resolve({
result: null,
stdout: '',
error: { message: 'Failed to send execution request to worker', name: 'WorkerError' },
})
return
}
resetIdleTimeout()
})
}