teal-language / teal-playground

teal-language/tl playground
https://teal-playground.netlify.app/
19 stars 1 forks source link

fix(quoting) quote user input when feeding into Lua code #7

Closed hishamhm closed 4 years ago

hishamhm commented 4 years ago

JSON encoding seems compatible enough so that it produces a valid Lua string for the purposes of this playground.

I couldn't find a case where I could break out of the sandbox, which was possible before.

Fixes #3.

darrenjennings commented 4 years ago

:shipit:

pdesaulniers commented 4 years ago

Alternatively, it seems like we could've used Fengari's copy of the Lua C API to avoid this replace() call (although the resulting code is more verbose).

First, we define a global function for running tl (I called it tl_gen):

const tl = `
package.path = "https://raw.githubusercontent.com/teal-language/tl/master/?.lua"
os = { getenv = function (str) return '' end }
local tl = require('tl')

function tl_gen(input)
  local env = tl.init_env(false, true)
  local output, result = tl.gen(input, env)

  return { output, result.syntax_errors, result.type_errors }
end
`

We load that code:

const luaconf = fengari.luaconf
const lua = fengari.lua
const lauxlib = fengari.lauxlib
const lualib = fengari.lualib

const L = fengari.L

if (lauxlib.luaL_dostring(L, fengari.to_luastring(tl)) !== lua.LUA_OK) {
  console.log('Error message: ' + fengari.to_jsstring(lua.lua_tostring(L, -1)))
  lua.lua_pop(L, 1)
}

Finally, we call the function with the Teal code as argument:

lua.lua_getglobal(L, 'tl_gen')
lua.lua_pushstring(L, newValue)

/* do the call (1 argument, 1 result) */
if (lua.lua_pcall(L, 1, 1, 0) !== 0) {
   console.log('Error message: ' + fengari.to_jsstring(lua.lua_tostring(L, -1)))
   lua.lua_pop(L, 1)
   return
}

/* retrieve result */
const out: LuaTableJs = fengari.interop.tojs(L, -1)
lua.lua_pop(L, 1)