Javascript

Writing a JavaScript Framework - Sandbox Code Evaluation




En este capítulo, explicaré las diferentes formas de evaluar el código en el browserUn navegador (además: browser) es una herramienta informática que te permite ver documentos y datos y navegar por la red. Los navegadores pueden mostrar distintos tipos de recursos de información; principalmente documentos HTML, a pesar de todo, además son posibles otros tipos de archivos y contenido multimedia, como PDF, JPEG, MPEG, GIF o el lenguaje de meta marcado. A través el uso de complementos especiales y la configuración respectivo, los plus y los problemas que causan. También introduciré un método, que se basa en algunas características nuevas o menos conocidas de JavaScriptJavaScript es un lenguaje de programación que funciona en el lado del cliente y con el que las webs pueden ser más funcionales. Incorporación en código HTML El código JavaScript puede ser incrustado en las páginas HTML, para que adquieran funcionalidad. Existen varias opciones. Puede estar entre las etiquetas <SCRIPT> y </SCRIPT>, puede estar contenido en un archivo externo, puede ser un parámetro de las etiquetas HTML, y puede estar plus.

The misused eval

The function eval () evaluates the JavaScript code represented as a string.

A common solution for code evaluation is the function eval (). The code evaluated with eval () you have access to closures and global reach, which leads to a security problem called code injection; and makes eval () be one of the most noticeable features of JavaScript.

Despite being frowned upon, eval () it is very useful in some situations. Most frames front-end Modern ones require their functionality, but don't dare to use them due to the problem we mentioned above. As a result, many workarounds for evaluating strings in a sandbox rather than global reach. The sandboxConcepto de Sandbox¿Qué es el Google Sandbox?El Sandbox es más que una definición usado dentro del sector de los videojuegos. Se trata del periodo de tiempo en el que Google pone a prueba todas aquellas páginas web que se han creado recientemente. Muchos lo definen como un periodo de cuarentena en el que el portal en cuestión pasa por un profundo análisis con el que el buscador determina su validez plus prevents code from accessing secure data. Usually it is a simple JavaScript object, which overrides the global object for the evaluated code.

The common way

The alternative to eval () más común es la reimplementación completa: un proceso de dos pasos, que consiste en analizar e interpretar la cadena pasada. Primero, el analizador crea un árbol de sintaxis abstracta, luego el intérpreteLos intérpretes son programas que, a diferencia de un compilador, no leen todo el código primero como un todo, sino que leen cada línea del programa fuente de forma separada y la ejecutan de forma directa en la plataforma sin traducir primero el código. Por ende, cada análisis se produce durante la ejecución del programa. Java, por ejemplo, usa intérpretes. Antecedentes El valor de los intérpretes es que un programa plus recorre el árbol y lo interpreta como un código dentro de una sandbox (caja de arena).

This is a widely used solution, but arguably too heavy for something so simple. Rewrite everything from scratch instead of applying patches eval () presents many opportunities for errors and requires frequent modifications to follow even the latest language updates.

An alternative way

NX tries to avoid the redeployment of native code. The evaluation is handled by a small library that uses some new or less known JavaScript features.

This section will progressively introduce these features and use them to explain the code evaluation library. nx-compile. The library has a function called compileCode (), which works as follows:

const code = compileCode ('return num1 + num2') // this logs 17 in console console.log (code ({num1: 10, num2: 7})) const globalNum = 12 const otherCode = compileCode ('return globalNum' ) // global scope access is prevented, this record is not defined in the console console.log (otherCode ({num1: 2, num2: 3}))

At the end of this article, we will implement the function compileCode () in less than 20 lines.

new Function ()

The builder Function create a new object Function. In JavaScript, each function is actually a function object.

The Function constructor is an alternative to eval (). new Function (… args, 'funcBody') evaluate the string 'funcBody' passed as code and returns a new function that executes that code. It differs from eval () in two main ways.

  • Evaluate passed code only once. Calling the returned function will execute the code without re-evaluating it.
  • You do not have access to the local closing variables, however you can still access the global scope.
function compileCode (src) {return new Function (src)}

new Function (), is a better alternative for eval () in our use case. It has superior performance and security, but global reach access must still be avoided to be viable.

The keywordPor definición, una palabra clave, (keyword en inglés), es una palabra informativa utilizada en un sistema de recuperación de información para indicar el contenido de un documento con la expectativa de un resultado de búsqueda coincidente. Herramientas de palabras clave La búsqueda de palabras clave para proyectos web individuales se ve enormemente facilitada por útiles herramientas. Al mismo tiempo, las herramientas de palabras clave ayudan mucho en la optimización del plus ‘with’

The instruction with extends the scope string of a statement.

with is a lesser known keyword in JavaScript. It allows a semi-sandblasted execution. The code inside a block with It tries to retrieve the variables from the sandbox object passed first, but if it can't find it there, it looks for the variable in the closure and in the global scope. Access to the closing scope is prevented by new Function () what we only have to worry about in the global sphere.

function compileCode (src) {src = 'with (sandbox) {' + src + '}' return new Function ('sandbox', src)}

with, uses the inoperator internally. For each variable access within the block, evaluate the variable in the condition sandbox. If the condition is true, retrieve the variable from the sandbox. Otherwise, it looks for the variable in the global scope. If we use with to always evaluate the variable in the sandbox as true, We could prevent it from accessing the global scope.

ES6 proxies

The object Proxy It is used to define custom behavior for fundamental operations such as searching or mapping properties.

A ES6 Proxy wraps an object and defines catch functions, which can intercept fundamental operations on that object. Capture functions are invoked when an operation occurs. By wrapping the test area object in a trap Proxy we can override the default behavior of the inoperator.

function compileCode (src) {src = 'with (sandbox) {' + src + '}' const code = new Function ('sandbox', src) return function (sandbox) {const sandboxProxy = new Proxy (sandbox, {has} ) return code (sandboxProxy)}} // this trap intercepts 'in' operations on the sandbox proxy. function has (target, key) {return true}

The above code tricks the with block already the variable in at sandbox since it will always evaluate to true because the trap have you always returns true. The code inside the with block it will never try to access the global object.

Code evaluation in the sandbox: 'with' statement and proxies

Symbol.unscopables

A symbol is a unique, immutable data type and can be used as an identifier for object properties.

Symbol.unscopables, it is a well-known symbol. A well-known symbol is a built-in JavaScript Symbol, que representa el comportamiento del idioma interno. Se pueden utilizar símbolos conocidos para agregar o sobrescribir iteraciones o comportamiento de conversionConversión es una acción precisa que lleva a cabo un usuario al visitar un portal web. Algunas formas clásica de conversión son, por ejemplo, una compra, una descarga o una suscripción a la newsletter. Un parte del SEO o del Marketing Online es la Optimización de Ratio de Conversión (CRO). En el Marketing de afiliación se usa para la conversión de los editores. Información general Hay diferentes indicadores para medir plus primitivo, por ejemplo:

The well-known symbol Symbol.unscopables used to specify an object value whose own and inherited property names are excluded from environment bindings 'with'.

Symbol.unscopables defines the non-openable properties of an object. Properties that cannot be captured are never retrieved from the sandbox object in declarations with, instead they are retrieved directly from the closure or global scope. Symbol.unscopables it is a very rarely used feature.

We can solve the above problem by defining a trap get at sandbox Proxy, which intercepts the recovery of Symbol.unscopables and it always returns undefined. This will fool the block with so that he thinks that our object of sandbox it has no properties that cannot be repaired.



function compileCode (src) {
src = 'with (sandbox) {' + src + '}'
const code = new Function('sandbox', src)

return function (sandbox) {
const sandboxProxy = new Proxy(sandbox, {has, get})
return code(sandboxProxy)
}
}

function has (target, key) {
return true
}

function get (target, key) {
if (key === Symbol.unscopables) return undefined
return target[key]
}


WeakMaps para el almacenamiento en cacheUn caché es un tipo de memoria auxiliar de la que se puede recuperar a alta velocidad con una capacidad de almacenamiento relativamente pequeña. Se encuentra entre la unidad central de procesamiento (CPU) y la memoria principal. Ayuda a evitar el acceso al disco duro o los recálculos complejos almacenando temporalmente ciertos datos y haciéndolos disponibles rápidamente cuando sea necesario. El caché almacena una copia de la petición actual y plus

The code is now safe, but its performance can still be updated as it creates a new Proxy on each invocation of the return function. This can be avoided by caching and using the same Proxy for each function call with the same sandbox object.

A proxy belongs to a sandbox object, so we could simply add the proxy to the sandbox object as a property. However, this would expose our deployment details to the public, and would not work in the case of a frozen sandbox stationary object Object.freeze (). Use a WeakMap ands a better alternative in this case.

The object WeakMap is a collection of key / value pairs in which the keys are weakly referenced. Keys must be objects, and values can be arbitrary values.

The WeakMap can be used to attach data to an object without directly extending it with properties. We can use WeakMaps to indirectly add the cache of Proxies to objects in the sandbox.



const sandboxProxies = new WeakMap()

function compileCode (src) {
src = 'with (sandbox) {' + src + '}'
const code = new Function('sandbox', src)

return function (sandbox) {
if (!sandboxProxies.has(sandbox)) {
const sandboxProxy = new Proxy(sandbox, {has, get})
sandboxProxies.set(sandbox, sandboxProxy)
}
return code(sandboxProxies.get(sandbox))
}
}

function has (target, key) {
return true
}

function get (target, key) {
if (key === Symbol.unscopables) return undefined
return target[key]
}


This way only one Proxy will be created per sandbox object.

The compileCode () the example above is a workspace code evaluator that works on just 19 lines of code.

Además de explicar la evaluación del código, el target¿Qué es un objetivo?En marketing, un objetivo es el resultado que se pretende alcanzar en un periodo de tiempo, a través el uso de los recursos disponibles. Por tanto, se debe formular de una forma clara y hace falta que sea accesible y medible. plus de este capítulo fue mostrar cómo se pueden usar las nuevas características de ES6 para alterar las existentes, en lugar de reinventarlas.