diff --git a/lib/sandbox.js b/lib/sandbox.js index 087f0d9..2afe369 100644 --- a/lib/sandbox.js +++ b/lib/sandbox.js @@ -18,6 +18,8 @@ const vm = require("vm"); +const seedrandom = require("seedrandom"); + const common = require("./common"); const device = require("./device"); const extensions = require("./extensions"); @@ -38,6 +40,8 @@ const sandbox = { declarations: null, extensionsCache: null, extensions: null, + clear: null, + rng: null, context: vm.createContext() } @@ -54,6 +58,13 @@ class SandboxDate { } }; +function random() { + if (!sandbox.rng) + sandbox.rng = seedrandom(sandbox.timestamp); + + return sandbox.rng(); +} + class ParameterWrapper { constructor(path, attributes, unpacked, unpackedRevision) { @@ -203,6 +214,11 @@ Object.defineProperty(sandbox.context, 'clear', {value: clear}); Object.defineProperty(sandbox.context, 'commit', {value: commit}); Object.defineProperty(sandbox.context, 'ext', {value: ext}); +// Monkey-patch Math.random() to make it deterministic +sandbox.context.random = random; +vm.runInContext("Math.random = random;", sandbox.context); +delete sandbox.random; + function errorToFault(err) { if (!err) @@ -230,6 +246,7 @@ function run(script, globals, timestamp, deviceData, extensionsCache, startRevis sandbox.declarations = []; sandbox.extensions = {}; sandbox.clear = null; + sandbox.rng = null; for (let n in sandbox.context) delete sandbox.context[n]; diff --git a/package.json b/package.json index 5937aee..143813d 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,8 @@ "libxmljs": "^0.18.0", "redis": "^2.6.2", "hiredis": "^0.5.0", - "mongodb": "^2.2.4" + "mongodb": "^2.2.4", + "seedrandom": "^2.4.2" }, "devDependencies": { "coffee-script": "^1.10.0"