function test_run_extension_again() { var window = createExtensionGlobal(); telemetryScript.runInNewContext(window); telemetryScript.runInNewContext(window); // Only one request should be sent because of rate-limiting. assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); // Simulate that quite some hours passed, but it's still rate-limited. window.Date.test_now_value += 11 * 36E5; telemetryScript.runInNewContext(window); // Only one request should be sent because of rate-limiting. assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); // Another hour passes and the request should not be rate-limited any more. window.Date.test_now_value += 1 * 36E5; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }, { 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
function test_browser_update() { var window = createExtensionGlobal(); telemetryScript.runInNewContext(window); updateBrowser(window); telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }, { // Generate a new ID for better privacy. 'Deduplication-Id': '4343434343', 'Extension-Version': '1.0.0', }]); },
function test_network_offline() { var window = createExtensionGlobal(); // Simulate that the network is down for sure. window.navigator.onLine = false; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, []); // Simulate that the network might be up. window.navigator.onLine = true; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
fs.readFile(configPath, 'utf8', function(err, configCode) { if (err || !configCode) { next(err || 'config.js has no content', { jspmConfig: null, jspmConfigPath: configPath }) return } var sandbox = { System: { config: function(cfg) { return cfg } }, config: null } var script = new vm.Script('config = ' + configCode) script.runInNewContext(sandbox) var jspmConfig = sandbox.config if (jspmConfig) assetInfo.bundles = jspmConfig && jspmConfig.bundles next(null, { jspmConfig: jspmConfig, jspmConfigPath: configPath }) })
function test_running_for_a_while() { var window = createExtensionGlobal(); telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); // Simulate that the timer fired 11 hours since the last ping. The request // should still be rate-limited. window.Date.test_now_value += 11 * 36E5; window.test_fireTimers(); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); // Another hour passes and the request should not be rate-limited any more. window.Date.test_now_value += 1 * 36E5; window.test_fireTimers(); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }, { 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
app.all('*', (req, res) => { res.header('Access-Control-Allow-Origin', '*'); if (req.method === 'OPTIONS') { // CORS preflight support (Allow any method or header requested) res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']); res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']); res.end(); } else { const label = funcLabel(req); const end = timeHistogram.labels(label).startTimer(); callsCounter.labels(label).inc(); const sandbox = Object.assign({}, global, { __filename: modPath, __dirname: modRootPath, module: new Module(modPath, null), require: (p) => modRequire(p, req, res, end), }); try { script.runInNewContext(sandbox, { timeout : timeout * 1000 }); } catch (err) { if (err.toString().match('Error: Script execution timed out')) { res.status(408).send(err); // We cannot stop the spawned process (https://github.com/nodejs/node/issues/3020) // we need to abruptly stop this process console.error('CRITICAL: Unable to stop spawned process. Exiting'); process.exit(1); } else { handleError(err, res, funcLabel, end); } } } });
return new Promise(function(resolve, reject) { sandbox.done = function(value) { log("hub script done", script_path); sandbox.fail = B.type.func_noop; sandbox.done = B.type.func_noop; resolve(value); }; sandbox.fail = function(value) { log.warn("hub script fail", script_path); sandbox.done = B.type.func_noop; sandbox.fail = B.type.func_noop; reject(value); }; sandbox.throwEXC = function(value) { log.warn("hub script throw exception", value); sandbox.fail(value); }; try { var f = func_script.runInNewContext(sandbox); f(); } catch(e) { log.warn("hub script catch exception", e); sandbox.fail(e); } });
function _eval(input, context) { var lines = EVAL_INSTANCE.lines; var isCompletion = !/\n$/.test(input); var undo = appendEval(input); var output; try { output = service.compile(EVAL_INSTANCE.input, EVAL_PATH, -lines); } catch (err) { undo(); throw err; } var changes = diff_1.diffLines(EVAL_INSTANCE.output, output); if (isCompletion) { undo(); } else { EVAL_INSTANCE.output = output; } var result; for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) { var change = changes_1[_i]; if (change.added) { var script = new vm_1.Script(change.value, EVAL_FILENAME); result = script.runInNewContext(context); } } return result; }
function test_first_run_incognito() { // The extension should not send any requests when in incognito mode. var window = createExtensionGlobal(); window.chrome.extension.inIncognitoContext = true; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, []); },
function initTest(body) { var script = new vm.Script(body); var LevelDao = script.runInNewContext(context); LevelDao.init(true, levelDir); LevelDao.fetch("level001").then(runTests); }
var read = function(thing) { say_invoked = false; console.log('thing we want to execute:',thing); var script = new vm.Script(thing, 'myfile.vm'); var result = script.runInNewContext(context); if (result) process.send({data: who+''+result}); }
function test_local_pref() { var window = createExtensionGlobal(); window.chrome.storage.local.mock_data = { disableTelemetry: true, }; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, []); },
function test_extension_update() { var window = createExtensionGlobal(); telemetryScript.runInNewContext(window); window.chrome.runtime.getManifest = function() { return { version: '1.0.1', }; }; window.Date.test_now_value += 12 * 36E5; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }, { // The ID did not change because the browser version did not change. 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.1', }]); },
function test_storage_managed_unavailable() { var window = createExtensionGlobal(); delete window.chrome.storage.managed; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
function test_first_run() { // Default settings, run extension for the first time. var window = createExtensionGlobal(); telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
function test_fetch_not_supported() { var window = createExtensionGlobal(); delete window.fetch; delete window.Request; delete window.Headers; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
function test_fetch_is_supported() { var window = createExtensionGlobal(); // XMLHttpRequest should not be called when fetch is available. So removing // the XMLHttpRequest API should not change behavior. delete window.XMLHttpRequest; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
process.on('message', function (message) { if (message === 'EXIT') { process.exit(0); } else if (message !== '') { const program = new vm.Script(message); program.runInNewContext({ console: console, process: process, require: vmRequire, }); } });
function test_fetch_mode_not_supported() { var window = createExtensionGlobal(); delete window.Request.prototype.mode; window.fetch = function() { throw new Error('Unexpected call to fetch!'); }; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
function test_unofficial_build() { var window = createExtensionGlobal(); var didWarn = false; window.console = {}; window.console.warn = function() { didWarn = true; }; window.chrome.runtime.id = 'abcdefghijklmnopabcdefghijklmnop'; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, []); assert.ok(didWarn); },
function runScript(filePath, context) { var scriptContent = fs.readFileSync(filePath, 'utf8'); var script = new vm.Script(scriptContent); context = globals(context || {}); context.window = context; script.runInNewContext(context); return context; };
it('setTimeout throws error', function (done) { var str = '"use strict";var module = {exports:{}};'; str += process; str += 'try {process.nextTick(function () {})} catch (e){this.works = e;}'; var script = new vm.Script(str); var context = { works: false }; script.runInNewContext(context); assert.ok(context.works); done(); });
it('should parse', function (done) { var str = '"use strict";var module = {exports:{}};'; str += process; str += 'this.works = process.browser;'; var script = new vm.Script(str); var context = { works: false }; script.runInNewContext(context); assert.ok(context.works); done(); });
function test_browser_update_between_pref_toggle() { var window = createExtensionGlobal(); telemetryScript.runInNewContext(window); window.chrome.storage.local.mock_data = { disableTelemetry: true, }; updateBrowser(window); telemetryScript.runInNewContext(window); window.chrome.storage.local.mock_data = { disableTelemetry: false, }; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }, { // Generate a new ID for better privacy, even if the update happened // while telemetry was disabled. 'Deduplication-Id': '4343434343', 'Extension-Version': '1.0.0', }]); },
/** * Executes the given CommonJS module in a fake context to get the exported string. The given module is expected to * just return a string without requiring further modules. * * @throws Error * @param {string} src * @param {string} filename * @param {string} [publicPath] * @returns {string} */ function runModule(src, filename, publicPath = "") { const script = new vm.Script(src, { filename, displayErrors: true }); const sandbox = { module: {}, __webpack_public_path__: publicPath // eslint-disable-line camelcase }; script.runInNewContext(sandbox); return sandbox.module.exports.toString(); }
async.eachSeries(events, (event, done) => { const script = new vm.Script(event.script, { timeout: 60000 }); script.runInNewContext({ require: () => { throw new Error("Not supported"); }, done, Data, Email, Property, Package, user, query, data, console }, { timeout: 60000 }); }, (error) => {
function test_managed_pref_is_overridden() { var window = createExtensionGlobal(); window.chrome.storage.managed.mock_data = { disableTelemetry: true, }; window.chrome.storage.sync.mock_data = { disableTelemetry: false, }; telemetryScript.runInNewContext(window); assert.deepEqual(window.test_requests, [{ 'Deduplication-Id': '4242424242', 'Extension-Version': '1.0.0', }]); },
const _eval = (content) => { const sandbox = {}, exports = {}; sandbox.exports = exports; sandbox.module = { exports: exports, filename: module.filename, id: module.filename, parent: module, }; sandbox.global = sandbox; const options = { displayErrors: false }; const stringScript = String(content).replace(/^\#\!.*/, ''); const script = new vm.Script(stringScript, options); script.runInNewContext(sandbox, options); return sandbox.module.exports; };
exports.sandbox = function (files, /*optional*/sandbox) { var source, script, result; if (!(files instanceof Array)) { files = [files]; } source = files.map(function (file) { return fs.readFileSync(file, 'utf8'); }).join(''); if (!sandbox) { sandbox = {}; } script = new Script(source); result = script.runInNewContext(sandbox); return sandbox; };
/** * Executes the given module's src in a fake context in order to get the resulting string. * * @this LoaderContext * @throws Error * @param {string} content the module's src */ function extractLoader(content) { const callback = this.async(); const dependencies = []; const script = new vm.Script(content, { filename: this.resourcePath, displayErrors: true }); const sandbox = { require: (resourcePath) => { const absPath = path.resolve(path.dirname(this.resourcePath), resourcePath); // Mark the file as dependency so webpack's watcher is working this.addDependency(absPath); // If the required file is a JS-file, we just evaluate it with node's require // This is necessary because of the css-loader which uses a helper module (css-base.js) to export stuff if (/css-base\.js$/i.test(resourcePath)) { return require(absPath); } dependencies.push(resourcePath); return rndPlaceholder; }, module: {}, exports: {} }; this.cacheable(); sandbox.module.exports = sandbox.exports; script.runInNewContext(sandbox); Promise.all(dependencies.map(loadModule, this)) .then(sources => sources.map( // runModule may throw an error, so it's important that our promise is rejected in this case (src, i) => runModule(src, dependencies[i], this.options.output.publicPath) )) .then(results => sandbox.module.exports.toString() .replace(new RegExp(rndPlaceholder, "g"), () => results.shift()) ) .then(content => callback(null, content)) .catch(callback); }