diff --git a/src/client/widgets/common/widget.js b/src/client/widgets/common/widget.js index be2614c0..191c5e14 100644 --- a/src/client/widgets/common/widget.js +++ b/src/client/widgets/common/widget.js @@ -2,7 +2,9 @@ var EventEmitter = require('../../events/event-emitter'), osc = require('../../osc'), nanoid = require('nanoid/generate'), widgetManager = require('../../managers/widgets'), - {math, evaljs, urlParser} = require('../utils'), + {urlParser} = require('../utils'), + Vm = require('../vm'), + vm = new Vm(), scopeCss = require('scope-css'), {iconify} = require('../../ui/utils'), resize = require('../../events/resize'), @@ -166,7 +168,6 @@ class Widget extends EventEmitter { this.widget = options.html this.props = options.props this.errors = {} - this.parsers = {} this.parent = options.root ? widgetManager : options.parent this.parentNode = options.parentNode this.hash = nanoid('abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZ', 10) @@ -176,6 +177,9 @@ class Widget extends EventEmitter { this.mounted = false this.visible = true + this.parsers = {} + this.parsersLocalScope = {} + this.createPropsCache() if (this.getProp('id') == 'root' && !options.root) { @@ -183,8 +187,6 @@ class Widget extends EventEmitter { this.errors.id = 'There can only be one root' } - // this.mathjsDeprecationWarned = false - // cache decimals if (this.props.decimals !== undefined) { this.decimals = Math.min(20, Math.max(this.getProp('decimals'), 0)) @@ -609,9 +611,9 @@ class Widget extends EventEmitter { var code = m.substr(2, m.length - 3).trim() - if (!this.parsers[code]) this.parsers[code] = evaljs('return ' + code, defaultScope) + if (!this.parsers[code]) this.parsers[code] = vm.compile('return ' + code, defaultScope) - let r = this.parsers[code](jsScope) + let r = this.parsers[code](jsScope, this.parsersLocalScope) if (r === undefined) r = '' @@ -627,9 +629,9 @@ class Widget extends EventEmitter { try { propValue = propValue.replace(/JS\{\{([\s\S]*)\}\}/g, (m, code)=>{ - if (!this.parsers[code]) this.parsers[code] = evaljs(code, defaultScope) + if (!this.parsers[code]) this.parsers[code] = vm.compile(code, defaultScope) - let r = this.parsers[code](jsScope) + let r = this.parsers[code](jsScope, this.parsersLocalScope) if (r === undefined) r = '' diff --git a/src/client/widgets/containers/panel.js b/src/client/widgets/containers/panel.js index 46009e79..5954a4b0 100644 --- a/src/client/widgets/containers/panel.js +++ b/src/client/widgets/containers/panel.js @@ -130,7 +130,7 @@ class Panel extends Container() { } else if (this.getProp('widgets') && this.getProp('widgets').length) { this.value = -1 - + this.childrenType = 'widget' this.children = options.children || new Array(this.getProp('widgets').length) diff --git a/src/client/widgets/graphs/plot.js b/src/client/widgets/graphs/plot.js index 35c1b470..a1fb402f 100644 --- a/src/client/widgets/graphs/plot.js +++ b/src/client/widgets/graphs/plot.js @@ -125,7 +125,7 @@ module.exports = class Plot extends StaticProperties(Canvas, {bypass: true, inte points.push(mapToScale(this.value[i][1], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], 0, this.logScaleY, true)) } else { let nx = mapToScale(i, [0, this.value.length - 1], [padding, this.width - padding], 0, this.logScaleX, true), - ny = mapToScale(this.value[i], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], 0, this. logScaleY, true) + ny = mapToScale(this.value[i], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], 0, this.logScaleY, true) if (x !== nx || y !== ny) { points.push(nx) points.push(ny) diff --git a/src/client/widgets/indicators/led.js b/src/client/widgets/indicators/led.js index f6e3ce12..e22fca21 100644 --- a/src/client/widgets/indicators/led.js +++ b/src/client/widgets/indicators/led.js @@ -64,7 +64,7 @@ module.exports = class Led extends StaticProperties(Widget, {bypass: true, inter if (typeof v != 'number') return false this.value = v - this.container.style.setProperty('--opacity', mapToScale(v,[this.getProp('range').min,this.getProp('range').max],[0,1],false,this.getProp('logScale'),true)) + this.container.style.setProperty('--opacity', mapToScale(v, [this.getProp('range').min, this.getProp('range').max], [0, 1], -1, this.getProp('logScale'), true)) } diff --git a/src/client/widgets/pads/rgb.js b/src/client/widgets/pads/rgb.js index 3f725f59..a7e0d34e 100644 --- a/src/client/widgets/pads/rgb.js +++ b/src/client/widgets/pads/rgb.js @@ -142,7 +142,7 @@ module.exports = class Rgb extends Widget { var rgb = hsbToRgb(this.hsb) for (var k in rgb) { - rgb[k] = mapToScale(rgb[k], [0, 255], [this.getProp('range').min, this.getProp('range').max], false) + rgb[k] = mapToScale(rgb[k], [0, 255], [this.getProp('range').min, this.getProp('range').max], -1) } if (rgb.r != this.value[0] || rgb.g != this.value[1] || rgb.b != this.value[2]) { @@ -188,9 +188,9 @@ module.exports = class Rgb extends Widget { } var hsb = rgbToHsb({ - r: mapToScale(value[0], [this.getProp('range').min, this.getProp('range').max], [0, 255], false), - g: mapToScale(value[1], [this.getProp('range').min, this.getProp('range').max], [0, 255], false), - b: mapToScale(value[2], [this.getProp('range').min, this.getProp('range').max], [0, 255], false) + r: mapToScale(value[0], [this.getProp('range').min, this.getProp('range').max], [0, 255], -1), + g: mapToScale(value[1], [this.getProp('range').min, this.getProp('range').max], [0, 255], -1), + b: mapToScale(value[2], [this.getProp('range').min, this.getProp('range').max], [0, 255], -1) }) if (!options.dragged) { diff --git a/src/client/widgets/sliders/slider.js b/src/client/widgets/sliders/slider.js index 27b6172b..ffd5d1f5 100644 --- a/src/client/widgets/sliders/slider.js +++ b/src/client/widgets/sliders/slider.js @@ -66,9 +66,9 @@ class Slider extends Canvas { this.widget.addEventListener('mousewheel',this.mousewheelHandleProxy.bind(this)) - this.on('draginit', this.draginitHandleProxy.bind(this), {element:this.container, multitouch: options.multitouch}) - this.on('drag', this.dragHandleProxy.bind(this), {element:this.container, multitouch: options.multitouch}) - this.on('dragend', this.dragendHandleProxy.bind(this), {element:this.container, multitouch: options.multitouch}) + this.on('draginit', this.draginitHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch}) + this.on('drag', this.dragHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch}) + this.on('dragend', this.dragendHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch}) touchstate(this, {element: this.widget, multitouch: options.multitouch}) @@ -162,7 +162,7 @@ class Slider extends Canvas { var h = clip(percent,[0,100]) for (var i=0;i= this.rangeKeys[i]) { - return mapToScale(h,[this.rangeKeys[i],this.rangeKeys[i+1]],[this.rangeVals[i],this.rangeVals[i+1]],false,this.getProp('logScale')) + return mapToScale(h, [this.rangeKeys[i], this.rangeKeys[i + 1]], [this.rangeVals[i], this.rangeVals[i + 1]], -1, this.getProp('logScale')) } } @@ -175,7 +175,7 @@ class Slider extends Canvas { (this.rangeVals[i+1] > this.rangeVals[i] && value <= this.rangeVals[i+1] && value >= this.rangeVals[i]) || (this.rangeVals[i+1] < this.rangeVals[i] && value >= this.rangeVals[i+1] && value <= this.rangeVals[i]) ) { - return mapToScale(value,[this.rangeVals[i],this.rangeVals[i+1]],[this.rangeKeys[i],this.rangeKeys[i+1]],false,this.getProp('logScale'),true) + return mapToScale(value, [this.rangeVals[i], this.rangeVals[i + 1]], [this.rangeKeys[i], this.rangeKeys[i + 1]], -1, this.getProp('logScale'), true) } } diff --git a/src/client/widgets/switchers/crossfader.js b/src/client/widgets/switchers/crossfader.js index 07d32305..ee7cb1cf 100644 --- a/src/client/widgets/switchers/crossfader.js +++ b/src/client/widgets/switchers/crossfader.js @@ -116,7 +116,7 @@ module.exports = class Crossfader extends Switcher { if (!isNaN(s['A'][i][k])) { - a[i][k] = mapToScale(v, [0,1], [s['A'][i][k], s['B'][i][k]], false) + a[i][k] = mapToScale(v, [0,1], [s['A'][i][k], s['B'][i][k]], -1) } @@ -124,7 +124,7 @@ module.exports = class Crossfader extends Switcher { } else if (!isNaN(s['A'][i])) { - a[i] = mapToScale(v, [0,1], [s['A'][i], s['B'][i]], false) + a[i] = mapToScale(v, [0,1], [s['A'][i], s['B'][i]], -1) } } diff --git a/src/client/widgets/utils.js b/src/client/widgets/utils.js index f42853ec..ffb827e7 100644 --- a/src/client/widgets/utils.js +++ b/src/client/widgets/utils.js @@ -7,15 +7,22 @@ module.exports = { value = parseFloat(value) if (isNaN(value)) value = range[0] - return Math.max(Math.min(range[0],range[1]),Math.min(value,Math.max(range[0],range[1]))) + + return Math.max(Math.min(range[0], range[1]), Math.min(value, Math.max(range[0], range[1]))) }, - // map a value from a scale to another input and output must be range arrays - mapToScale: function(value,rangeIn,rangeOut,decimals,log,revertlog) { + // map a value from a scale to another + // value: number + // rangeIn: [number, number] + // rangeOut: [number, number] + // decimals: number (-1 to bypass) + // log: boolean + // revertLog: boolean + mapToScale: function(value, rangeIn, rangeOut, decimals, log, revertlog) { // clip in - value = module.exports.clip(value,[rangeIn[0],rangeIn[1]]) + value = module.exports.clip(value,[rangeIn[0], rangeIn[1]]) // normalize value = (value - rangeIn[0]) / (rangeIn[1] - rangeIn[0]) @@ -32,10 +39,10 @@ module.exports = { value = value * (rangeOut[1] - rangeOut[0]) + rangeOut[0] // clip out - value = module.exports.clip(value,[rangeOut[0],rangeOut[1]]) + value = module.exports.clip(value, [rangeOut[0], rangeOut[1]]) // decimals - if (decimals !== false) value = parseFloat(value.toFixed(decimals)) + if (decimals !== -1) value = parseFloat(value.toFixed(decimals)) return value @@ -97,120 +104,6 @@ module.exports = { return parser } - })(), - - evaljs: (function(){ - - var sandbox = document.createElement('iframe'), - loopProtect = require('loop-protect') - - sandbox.style.display = 'none' - sandbox.sandbox = 'allow-same-origin' - document.documentElement.appendChild(sandbox) - - // block requests - sandbox.contentWindow.document.open() - sandbox.contentWindow.document.write('') - sandbox.contentWindow.document.close() - - // init infinite loop guard - loopProtect.alias = '__protect' - loopProtect.hit = function(line){ - throw 'Potential infinite loop found on line ' + line - } - sandbox.contentWindow.__protect = loopProtect - - - var _Function = sandbox.contentWindow.Function, - parsers = {} - - sandbox.contentWindow.console = console - sandbox.contentWindow.setTimeout = - sandbox.contentWindow.setInterval = ()=>{ - throw 'setTimeout and setInterval can\'t be used in the JS sandbox' - } - sandbox.contentWindow.global = {} - - function nuke(o) { - // non-primitives created outside the sandbox context can leak - // the host window object... let's nuke that ! - // (we only nuke function and objects/arrays because we don't pass anything else) - var t = typeof o - if (t === 'function' || (t === 'object' && o !== null)) { - if (o.__proto__) { - if (t === 'function') { - o.__proto__.constructor = _Function - } else { - o.__proto__.constructor.constructor = _Function - } - } - for (var k in o) { - nuke(o[k]) - } - } - } - - for (var imports of ['__protect', 'console', 'setTimeout', 'setInterval', 'global']) { - nuke(sandbox.contentWindow[imports]) - } - - document.documentElement.removeChild(sandbox) - - function evaljs(code, defaultContext) { - - var contextInit = '', - contextKeys = ['__VARS'], - contextValues = [{}] - - if (defaultContext) { - for (var k in defaultContext) { - contextInit += `var ${k} = ${k} || ${JSON.stringify(defaultContext[k])};` - contextKeys.push(k) - contextValues.push(defaultContext[k]) - } - } - - parsers[code] = new _Function( - ...contextKeys, - loopProtect('"use strict";' + contextInit + code) - .replace(/;\n(if \(__protect.*break;)\n/g, ';$1') // prevent loop protect from breaking stack linenumber - .replace(/(VAR_[0-9]+)/g, '__VARS.$1') - ) - - return (context)=>{ - - var ret, err, k - - var __contextValues = deepCopy(contextValues) - var __VARS = __contextValues[0] - for (k in context) { - var index = contextKeys.indexOf(k) - if (index !== -1) { - __contextValues[index] = context[k] - } else { - __VARS[k] = context[k] - } - } - - nuke(contextValues) - - // evaluate - try { - ret = parsers[code].apply(null, __contextValues) - } catch(e) { - err = e - } - - if (err) throw err - - return ret - - } - - } - - return evaljs - })() } diff --git a/src/client/widgets/vm.js b/src/client/widgets/vm.js new file mode 100644 index 00000000..9689063d --- /dev/null +++ b/src/client/widgets/vm.js @@ -0,0 +1,118 @@ +var loopProtect = require('loop-protect'), + {deepCopy} = require('../utils') + +class Vm { + + constructor() { + + this.sandbox = document.createElement('iframe') + this.sandbox.style.display = 'none' + this.sandbox.sandbox = 'allow-same-origin' + + // attach sandbox + document.documentElement.appendChild(this.sandbox) + + // sandboxed function prototype + this.safeFunctionProto = this.sandbox.contentWindow.Function + + // block requests + this.sandbox.contentWindow.document.open() + this.sandbox.contentWindow.document.write('') + this.sandbox.contentWindow.document.close() + + // init infinite loop guard + loopProtect.alias = '__protect' + loopProtect.hit = function(line){ + throw 'Potential infinite loop found on line ' + line + } + this.sandbox.contentWindow.__protect = loopProtect + + // global context + this.sandbox.contentWindow.console = console + this.sandbox.contentWindow.setTimeout = + this.sandbox.contentWindow.setInterval = ()=>{ + throw 'setTimeout and setInterval can\'t be used in the JS sandbox' + } + this.sandbox.contentWindow.globals = {} + + + // sanitize globals + for (var imports of ['__protect', 'console', 'setTimeout', 'setInterval', 'globals']) { + this.sanitize(this.sandbox.contentWindow[imports]) + } + + // detach sandbox + document.documentElement.appendChild(this.sandbox) + + } + + sanitize(object) { + + // non-primitives created outside the sandbox context can leak + // the host window object... let's nuke that ! + // (we only nuke functions and objects/arrays because we don't pass anything else) + var t = typeof o + if (t === 'function' || (t === 'object' && o !== null)) { + if (o.__proto__) { + if (t === 'function') { + o.__proto__.constructor = this.safeFunctionProto + } else { + o.__proto__.constructor.constructor = this.safeFunctionProto + } + } + for (var k in o) { + this.sanitize(o[k]) + } + } + + } + + compile(code, defaultContext) { + + // var contextInit = 'var locals = locals;', + var contextInit = '', + contextKeys = ['__VARS'], + contextValues = [{}] + + if (defaultContext) { + for (var k in defaultContext) { + contextInit += `var ${k} = ${k} === undefined ? ${JSON.stringify(defaultContext[k])} : ${k};` + contextKeys.push(k) + contextValues.push(defaultContext[k]) + } + } + + var compiledCode = new this.safeFunctionProto( + ...contextKeys, 'locals', + loopProtect('"use strict";' + contextInit + code) + .replace(/;\n(if \(__protect.*break;)\n/g, ';$1') // prevent loop protect from breaking stack linenumber + .replace(/(VAR_[0-9]+)/g, '__VARS.$1') + ) + + + return (context, locals)=>{ + + var __contextValues = deepCopy(contextValues) + var __VARS = __contextValues[0] + for (var k in context) { + var index = contextKeys.indexOf(k) + if (index !== -1) { + __contextValues[index] = context[k] + } else { + __VARS[k] = context[k] + } + } + + __contextValues.push(locals) + + this.sanitize(__contextValues) + + return compiledCode.apply(null, __contextValues) + + } + + } + +} + +module.exports = Vm