Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 38 ยท Patterns and Tooling

Plugin Systems with WebAssembly

Learn to design a plugin system on WebAssembly - host API as the only imports, allow-lists, LinkError rejection, fuel limits against infinite loops, versioning, data passing and lifecycle - with runnable code.

Almost every successful application grows a plugin system: editors, browsers, databases, game engines, build tools, e-commerce platforms. The hard part has always been trust. A native plugin runs with all the permissions of the host and can crash it. A script plugin is safer but is locked to one language and tends to be slow. WebAssembly offers a third option: plugins that are fast, language-neutral and sandboxed by construction, because a module can only do what its imports allow.

This lesson shows how to design a plugin host around that fact: the API you expose is the only way a plugin can affect the world, and you can enforce limits on top. All examples run for real, using two tiny plugin modules.

The core idea: imports are the whole API

A WebAssembly module has no ambient authority. It cannot read a file, open a socket or call the clock unless the host imports such a function into it. So designing the plugin API is the same task as designing the import object. A plugin that wants a function you did not provide simply fails to instantiate.

Anatomy of a Wasm plugin host

Contract Exports the host calls, imports it offers.
Allow-list Provide only the imports you choose.
Limits Fuel, memory and timeouts.
Isolation A crash stays inside the plugin.

The import object is your security policy.

1 / 2

Example: a minimal host

The first plugin exports run(n), which calls the host function host.log(i) for each i from 1 to n. It also imports host.tick, which we will use later for limits. The second plugin, evil, additionally asks for host.readFile, a capability our host never offers.

Node.js Host API as an allow-list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The LinkError is the sandbox working: the evil plugin could never run even one instruction. It is also a good audit tool: WebAssembly.Module.imports(module) lists a plugin's requested capabilities before you run anything, so you can show them to users ("this plugin wants network access") or reject plugins that ask for too much.

Limiting time with fuel

Limiting capabilities does not stop a plugin from burning your CPU with an infinite loop. Native Wasm runtimes solve this with fuel (a counter of executed instructions) or epoch interruption (a timer-driven check). Browsers and Node give you no built-in fuel, but you can build a cooperative version: a compiler pass (or the plugin author's SDK) inserts a call to an imported tick() at the start of each loop iteration, and the host's tick returns non-zero when the budget is used up. The plugin's spin() export below is exactly such a loop:

WAT
(func (export "spin")
  (loop $forever
    (if (i32.eqz (call $tick)) (then (br $forever)))))   ;; keep going until tick() says stop
Node.js Stopping a runaway plugin with a fuel budget

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This cooperative scheme only works if the plugin cooperates, because a hostile module could simply omit the tick call. For untrusted code you need a preemptive limit that the runtime enforces: Wasmtime fuel and epochs, Wasmer metering middleware, or running the plugin in a Worker that you can terminate() on timeout. Match the mechanism to your threat model.

Passing data to plugins

Real plugins need richer data than a single integer. The usual designs, from simplest to most capable:

  1. Numbers only. Great for small hooks (a score, a flag). No memory management at all.
  2. Pointer and length in the plugin's memory. The host calls the plugin's exported alloc, writes bytes in, then calls the plugin function. Use a stable serialization such as JSON, MessagePack or Protocol Buffers so plugin authors in any language can parse it. (See Passing Strings and Structs for the mechanics.)
  3. Typed interfaces with WIT. The component model generates bindings for the host and for every plugin language, so the contract is checked by tools (see The Component Model and WIT).

Whatever you pick, copy data into the plugin's memory instead of sharing the host's memory, and validate everything that comes out: a plugin's output is untrusted input.

Designing the host API

  • Small and stable. Every function you expose is a promise; add capabilities deliberately.
  • Capability-scoped. Instead of readFile(path), expose readConfig(key) or give a handle to one directory.
  • Versioned. Put a version in the import module name (host_v1) or an exported plugin_api_version() so you can evolve without breaking old plugins.
  • Idempotent and bounded. Enforce size limits on every argument and result.
  • Observable. Log which plugin called which host function; record fuel and memory usage per call.

Failure handling

Plugins will misbehave, so wrap every call:

JavaScript
function safeCall(plugin, fn, ...args) {
  try {
    return { ok: true, value: plugin[fn](...args) };
  } catch (err) {
    if (err instanceof WebAssembly.RuntimeError) {
      return { ok: false, error: 'plugin trapped' };            // reset or unload this plugin
    }
    return { ok: false, error: 'host error: ' + err.message };
  }
}

After a trap, the instance's memory may be in an odd state, so the safest policy is to discard the instance and create a fresh one for the next call. This is cheap (see WebAssembly on Servers and the Edge).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What determines what a Wasm plugin can do to the outside world?

    A module has no ambient authority. It can only call functions that the host places in its import object.
  2. 2. What happens if a plugin imports host.readFile and the host does not provide it?

    Linking checks every import. A missing one makes instantiation fail before any plugin code runs.
  3. 3. Why is a cooperative tick() fuel scheme not enough for hostile plugins?

    Cooperative checks rely on the plugin. Runtime-enforced fuel, epochs or worker termination do not.
  4. 4. After a plugin traps, what is the safest next step?

    A trap can leave memory and globals half-updated. A fresh instance gives a clean state.

Summary

  • In a Wasm plugin system the import object is the security policy: expose a small, capability-scoped, versioned host API.
  • WebAssembly.Module.imports lets you audit what a plugin requests before running it; missing imports cause a LinkError.
  • Limit time with runtime fuel, epochs or terminable workers; cooperative tick checks only protect against honest mistakes.
  • Pass data by copying serialized bytes into plugin memory or by using WIT-typed interfaces; validate all plugin output.
  • Wrap calls, treat traps as plugin failures, and discard instances after errors.

Next: The WebAssembly Security Model