sandbox_preamble.lua

 1---@diagnostic disable: undefined-global
 2
 3-- Create a sandbox environment
 4local sandbox = {}
 5
 6-- For now, add all globals to `sandbox` (so there effectively is no sandbox).
 7-- We still need the logic below so that we can do things like overriding print() to write
 8-- to our in-memory log rather than to stdout, we will delete this loop (and re-enable
 9-- the I/O module being sandboxed below) to have things be sandboxed again.
10for k, v in pairs(_G) do
11  if sandbox[k] == nil then
12    sandbox[k] = v
13  end
14end
15
16-- Allow access to standard libraries (safe subset)
17sandbox.string = string
18sandbox.table = table
19sandbox.math = math
20sandbox.print = sb_print
21sandbox.type = type
22sandbox.tostring = tostring
23sandbox.tonumber = tonumber
24sandbox.pairs = pairs
25sandbox.ipairs = ipairs
26
27-- Access to custom functions
28sandbox.search = search
29sandbox.outline = outline
30
31-- Create a sandboxed version of LuaFileIO
32local io = {}
33
34-- File functions
35io.open = sb_io_open
36
37-- Add the sandboxed io library to the sandbox environment
38-- sandbox.io = io -- Uncomment this line to re-enable sandboxed file I/O.
39
40-- Load the script with the sandbox environment
41local user_script_fn, err = load(user_script, nil, "t", sandbox)
42
43if not user_script_fn then
44  error("Failed to load user script: " .. tostring(err))
45end
46
47-- Execute the user script within the sandbox
48local success, result = pcall(user_script_fn)
49
50if not success then
51  error("Error executing user script: " .. tostring(result))
52end