simplification
Download
102 lines 4.3 KiBMarkdownModified 2026-11-09 raw

Using Nomsu as a library

Nomsu can be embedded in a Lua program, so the program can run Nomsu code — including untrusted code, in a sandbox. Each runtime has its own environment, loaded modules, and random numbers, so runtimes don't affect each other or the host program.

local nomsu = require "nomsu"

local vm = nomsu.Runtime{}
vm:run[[ say "Hello" ]]
local ok, result = vm:run[[ return (2 + 2) ]]   -- ok == true, result == 4

Loading the library changes nothing in the host program: it adds no globals, runs nothing, and reads no files until you ask it to.

Running code

runtime:run(code) runs a chunk of Nomsu code (text, or a parsed tree) and returns:

  • true, value — the value the code returned (or nil).
  • false, message — a parse or runtime error, as a printable string.
  • false, signal — if the code called exit, a table with signal.exit (the exit code); if it ran out of a limit, a table with signal.limit ("instructions", "time", or "memory").

run never prints an error or exits the host program. Each run is a separate chunk, so a top-level definition in one call isn't visible in the next — use public: for definitions that should persist across calls in the same runtime.

Making a runtime

nomsu.Runtime(config) returns a runtime. Every field of config is optional:

Field Meaning
modules Where use finds modules, besides Nomsu's own library (default: {"."}). The list part holds directories; the other keys map module names to their Nomsu code, for modules held in memory.
print function(text) that say writes to (default: stdout).
input function() that ask reads a line from (default: stdin).
environment A table of extra values to put in the runtime's environment (added before the core library loads).
limits Resource limits for each run (see below).
local vm = nomsu.Runtime{
    modules = {"./game_lib", ["game/api"] = my_api_code},
}

A runtime exposes runtime.root (its root environment) and runtime.environment (the environment that run uses).

Sandboxing untrusted code

runtime:seal() turns a runtime into a sandbox, and can't be undone. Set the runtime up with full permissions first (load modules, define things), then seal it, then run untrusted code.

local vm = nomsu.Runtime{print = print, limits = {instructions = 1e7, seconds = 1, memory = 64 * 1024}}
vm:run[[ use "mygame/api" ]]     -- trusted setup
vm:seal()                        -- from here on, sandboxed
local ok, result = vm:run(untrusted_code)

Sandboxed code can use the core language (including say and ask, which go through the runtime's print and input) and whatever the host put in environment. It cannot use inline Lua, define compile rules, load new modules from disk, or reach Lua's libraries for files, the OS, and so on. Sealing again does nothing.

A sandbox can use a module that was loaded before sealing (the host can pre-load optional modules with runtime.root:Module("name")), bringing in its safe exports only. It can't load anything new.

A sealed runtime's run returns a deep copy of its result containing only plain data (strings, numbers, booleans, and plain tables); it refuses a result with a metatable or a function, since using those could run sandboxed code later in the host. Functions the host puts in environment get called with values from sandboxed code, so they should copy those values the same way before using them, with nomsu.plain_copy(value).

Limits

limits caps each run. Any of the keys may be left out:

  • instructions — the number of Lua instructions.
  • seconds — of CPU time.
  • memory — in kilobytes (approximate).

Code that goes over a limit is stopped; try, pcall, and coroutines can't catch it. Change the limits later with runtime.limits.

The memory limit and the guard against catastrophic pattern matches are best-effort: they're measured in-process, and a little code can run between checks. For a hard guarantee against hostile code, run it in a separate process and treat the in-process sandbox as defense in depth.

Example

examples/nomic.lua is a full game of Nomic: players submit Nomsu code that runs in per-player sandboxes, and the rules of the game are themselves Nomsu code that the players can change.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
# Using Nomsu as a library

Nomsu can be embedded in a Lua program, so the program can run Nomsu code — including
untrusted code, in a sandbox. Each *runtime* has its own environment, loaded modules,
and random numbers, so runtimes don't affect each other or the host program.

```lua
local nomsu = require "nomsu"

local vm = nomsu.Runtime{}
vm:run[[ say "Hello" ]]
local ok, result = vm:run[[ return (2 + 2) ]]   -- ok == true, result == 4
```

Loading the library changes nothing in the host program: it adds no globals, runs
nothing, and reads no files until you ask it to.

## Running code

`runtime:run(code)` runs a chunk of Nomsu code (text, or a parsed tree) and returns:

- `true, value` — the value the code returned (or `nil`).
- `false, message` — a parse or runtime error, as a printable string.
- `false, signal` — if the code called `exit`, a table with `signal.exit` (the exit code);
  if it ran out of a limit, a table with `signal.limit` (`"instructions"`, `"time"`, or
  `"memory"`).

`run` never prints an error or exits the host program. Each `run` is a separate chunk, so
a top-level definition in one call isn't visible in the next — use `public:` for
definitions that should persist across calls in the same runtime.

## Making a runtime

`nomsu.Runtime(config)` returns a runtime. Every field of `config` is optional:

| Field | Meaning |
|-------|---------|
| `modules` | Where `use` finds modules, besides Nomsu's own library (default: `{"."}`). The list part holds directories; the other keys map module names to their Nomsu code, for modules held in memory. |
| `print` | `function(text)` that `say` writes to (default: stdout). |
| `input` | `function()` that `ask` reads a line from (default: stdin). |
| `environment` | A table of extra values to put in the runtime's environment (added before the core library loads). |
| `limits` | Resource limits for each `run` (see below). |

```lua
local vm = nomsu.Runtime{
    modules = {"./game_lib", ["game/api"] = my_api_code},
}
```

A runtime exposes `runtime.root` (its root environment) and `runtime.environment` (the
environment that `run` uses).

## Sandboxing untrusted code

`runtime:seal()` turns a runtime into a sandbox, and can't be undone. Set the runtime up
with full permissions first (load modules, define things), then seal it, then run
untrusted code.

```lua
local vm = nomsu.Runtime{print = print, limits = {instructions = 1e7, seconds = 1, memory = 64 * 1024}}
vm:run[[ use "mygame/api" ]]     -- trusted setup
vm:seal()                        -- from here on, sandboxed
local ok, result = vm:run(untrusted_code)
```

Sandboxed code can use the core language (including `say` and `ask`, which go through the
runtime's `print` and `input`) and whatever the host put in `environment`. It **cannot**
use inline Lua, define compile rules, load new modules from disk, or reach Lua's libraries
for files, the OS, and so on. Sealing again does nothing.

A sandbox can `use` a module that was **loaded before sealing** (the host can pre-load
optional modules with `runtime.root:Module("name")`), bringing in its safe exports only.
It can't load anything new.

A sealed runtime's `run` returns a deep copy of its result containing only plain data
(strings, numbers, booleans, and plain tables); it refuses a result with a metatable or a
function, since using those could run sandboxed code later in the host.
Functions the host puts in `environment` get called with values from sandboxed code, so
they should copy those values the same way before using them, with
`nomsu.plain_copy(value)`.

### Limits

`limits` caps each `run`. Any of the keys may be left out:

- `instructions` — the number of Lua instructions.
- `seconds` — of CPU time.
- `memory` — in kilobytes (approximate).

Code that goes over a limit is stopped; `try`, `pcall`, and coroutines can't catch it.
Change the limits later with `runtime.limits`.

The memory limit and the guard against catastrophic pattern matches are **best-effort**:
they're measured in-process, and a little code can run between checks. For a hard
guarantee against hostile code, run it in a separate process and treat the in-process
sandbox as defense in depth.

## Example

[examples/nomic.lua](../examples/nomic.lua) is a full game of Nomic: players submit Nomsu
code that runs in per-player sandboxes, and the rules of the game are themselves Nomsu
code that the players can change.