* Run the script in a VM. * @param eventParams - The driver script message event parameters * @returns Promise resolving to the run script result * @throws {TypeError}
(eventParams: DriverScriptMessageEvent)
| 22 | * @throws {TypeError} |
| 23 | */ |
| 24 | async function runScript(eventParams: DriverScriptMessageEvent): Promise<RunScriptResult> { |
| 25 | const {driverOpts, script, timeoutMs} = eventParams; |
| 26 | if (typeof timeoutMs !== 'number' || Number.isNaN(timeoutMs)) { |
| 27 | throw new TypeError('Timeout parameter must be a number'); |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * set up fake logger |
| 32 | */ |
| 33 | const logs: {error: any[]; warn: any[]; log: any[]} = { |
| 34 | error: [], |
| 35 | warn: [], |
| 36 | log: [], |
| 37 | }; |
| 38 | const consoleFns: { |
| 39 | error: (...args: any[]) => void; |
| 40 | warn: (...args: any[]) => void; |
| 41 | log: (...args: any[]) => void; |
| 42 | } = { |
| 43 | error: wrapHostBindingForVmContext((...logMsgs) => logs.error.push(...logMsgs)), |
| 44 | warn: wrapHostBindingForVmContext((...logMsgs) => logs.warn.push(...logMsgs)), |
| 45 | log: wrapHostBindingForVmContext((...logMsgs) => logs.log.push(...logMsgs)), |
| 46 | }; |
| 47 | |
| 48 | const {attach} = await import('webdriverio'); |
| 49 | |
| 50 | const driver = await attach(driverOpts); |
| 51 | const sandboxDriver = wrapHostBindingForVmContext(driver); |
| 52 | const sandboxConsole = wrapHostBindingForVmContext(consoleFns); |
| 53 | const sandboxSetTimeout = wrapHostBindingForVmContext(setTimeout); |
| 54 | const sandboxClearTimeout = wrapHostBindingForVmContext(clearTimeout); |
| 55 | |
| 56 | const fullScript = `(async () => {${script}})();`; |
| 57 | |
| 58 | log.info('Running driver script in Node vm'); |
| 59 | |
| 60 | // run the driver script, giving user access to the driver object, a fake console logger, |
| 61 | // and standard setTimeout/clearTimeout functions. Each host value is proxied so |
| 62 | // main-realm prototype metadata cannot be used to obtain the host `Function` (VM escape). |
| 63 | let result = await vm.runInNewContext( |
| 64 | fullScript, |
| 65 | { |
| 66 | driver: sandboxDriver, |
| 67 | console: sandboxConsole, |
| 68 | setTimeout: sandboxSetTimeout, |
| 69 | clearTimeout: sandboxClearTimeout, |
| 70 | }, |
| 71 | {timeout: timeoutMs, breakOnSigint: true}, |
| 72 | ); |
| 73 | |
| 74 | result = coerceScriptResult(result); |
| 75 | log.info('Successfully ensured driver script result is appropriate type for return'); |
| 76 | return {result, logs}; |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * We can get any manner of crazy thing back from a vm executing untrusted |
no test coverage detected