Architecture & Sandbox
This page explains how the OpenWA plugin runtime works: how a plugin reaches WhatsApp through a small set of permission-gated capabilities, how lifecycle hooks fit into message and session processing, how the ADMIN-only management API drives a plugin's state, and what the worker-thread sandbox does and does not protect against. It is the conceptual companion to Building a Plugin — read this to understand why the contract looks the way it does before you write code.
The core idea: capabilities, not access
A plugin never gets a reference to OpenWA's internals. It cannot call MessageService, touch the database, or reach the WhatsApp engine directly. Instead it receives a PluginContext exposing a small set of narrow capability namespaces, and every method on them is checked against the plugin's declared permissions before it runs.
This inverts the usual extension model. Rather than handing a plugin the keys and trusting it, OpenWA hands it a vending machine: it can request exactly the actions it declared up front, and nothing else. A call the plugin did not earn fails fast with a PluginCapabilityError.
Three things follow from this design, and the rest of the page expands each:
- A plugin declares capability permissions in its manifest. There are exactly seven.
- A plugin runs its logic inside lifecycle hooks, returning a result that the host threads into the next handler.
- An ADMIN-only API (and the dashboard on top of it) installs, enables, configures, and scopes the plugin — the plugin never controls its own lifecycle.
The capability permission model
A plugin reaches the outside world only through capability namespaces on the context: ctx.messages, ctx.engine, and ctx.net form the base outbound surface, and the Integration SDK v1 adds ctx.registerWebhook, ctx.conversations, ctx.handover, and ctx.mappings. Since v0.17.0 the per-plugin key-value store ctx.storage is gated the same way. Each namespace maps to a permission string, which the plugin lists in its manifest permissions array:
| Permission | Namespace | What it grants |
|---|---|---|
messages:send | ctx.messages | Send and reply to messages on a session. Routes through the host MessageService, so persistence and history are preserved. |
engine:read | ctx.engine | Read-only engine queries: group info, contacts, chats, chat history (clamped to 100 messages), number-existence checks, and @lid to canonical-id resolution (since v0.26.0 only through a lid/phone pair an engine has reported; any other @lid comes back as <lid>@lid). No writes. On Baileys, getContacts lists only contacts with a name saved on the phone (v0.23.6+); a peer known by pushname alone is no longer listed, but getContactById still resolves it, with isMyContact: false. Since v0.31.0 a Baileys contact held under its privacy id (@lid) whose only name is that id's own digits reports neither a pushName nor a saved name, so getContacts, which lists only saved names, no longer lists one whose saved name was those digits, and getChats lists a Baileys chat held under a privacy id (@lid) that has no saved, verified or push name with name set to "" (it used to be the id's own digits) and, when the session can map the id, a phone holding the number's digits: title such a chat by phone, else by its id. Every Baileys chat name is also trimmed, and a blank name of a Baileys chat not held under a privacy id lists the contact's name or the id's digits. whatsapp-web.js lists no phone. On whatsapp-web.js getChatHistory reports a message deleted for everyone (type: 'revoked') under the id the message had, not the id of the delete notice (v0.30.2), and under the id of its stored row when the delete notice names the chat, or in a group the author, in the other id form, phone or @lid, and the gateway knows the two to be one person (v0.30.3). |
net:fetch | ctx.net | Outbound HTTP via ctx.net.fetch, passed through the host's SSRF guard and scoped to a host allowlist. The request, response and limits are fixed by the host. |
webhook:ingress | ctx.registerWebhook | Integration SDK v1 — claim a verified inbound ingress route. The host authenticates every delivery before the plugin code runs. |
conversation:send | ctx.conversations, ctx.handover, ctx.mappings | Integration SDK v1 — send normalized replies into a chat, flip a conversation's bot/human handover state, and manage the WhatsApp-chat↔external-conversation map. |
search:provide | ctx.registerSearchProvider | Serve the gateway's GET /api/search queries. Since v0.12.2 this permission is required: under the default SEARCH_PROVIDER=auto a registered provider is also made active (superseding builtin-fts), so a plugin that declared no permission would otherwise see every query the gateway serves. A plugin without it is refused before the provider reaches the registry, and the host logs one warning per enable (sandbox_search_provider_denied). |
storage:use | ctx.storage | Read and write the plugin's own key-value store — get, set, delete, and list, each gated separately. Since v0.17.0 this permission is required: before it, the four storage verbs dispatched with no permission check at all, so a plugin whose manifest declared nothing still wrote to the host disk. A plugin without it is denied at its next storage call, not at load; one that stores during onEnable is left in ERROR. |
The first three are the base surface any plugin can declare; the next two are the Integration Fabric pair for bidirectional external integrations (helpdesk/CRM/chatbot handover) — see Integration Fabric; search:provide gates the search-provider capability (added in v0.12.2), so a search plugin must declare it explicitly; and storage:use gates the per-plugin key-value store (required since v0.17.0). A manifest that declares none gets no capability access at all — it can still register hooks and observe events, but it cannot act on them.
Enforcement does not live in a separate policy engine; it lives at the call boundary. Each capability method runs assertPermission(manifest, permission) before doing any work:
// Conceptual shape of the check the loader runs on every capability call.
private assertPermission(manifest, permission) {
if (!(manifest.permissions ?? []).includes(permission)) {
throw new PluginCapabilityError(
`Plugin ${manifest.id} is missing the '${permission}' permission required for this capability. ` +
`Add "${permission}" to the "permissions" array in the plugin's manifest.json, then reload the plugin.`,
);
}
}
Rendered, that reads: Plugin gsheets-logger is missing the 'storage:use' permission required for this capability. Add "storage:use" to the "permissions" array in the plugin's manifest.json, then reload the plugin.
storage:use is required from v0.17.0A plugin that calls ctx.storage needs one manifest line — "storage:use" inside its permissions array. There is no load-time check for it, so the refusal arrives at the next storage call, not at load: an upgraded gateway looks fine until a plugin tries to store. Every storage verb is async, so the denial arrives as a rejected promise. A plugin that stores during onEnable does not merely lose the write — the loader records the error, sets the plugin to ERROR, unregisters its hooks, and leaves it disabled.
Operators: upgrade the seven official plugins that need it (every official plugin that declares storage:use except rocketchat-adapter, which requires OpenWA 0.30.0 or later) before upgrading the gateway. The new plugin versions are safe on an older gateway (an unrecognised permission string is ignored); the old versions are not safe on v0.17.0. The version floors are in the plugin catalog.
Two checks stack on top of the permission
Holding messages:send is necessary but not sufficient. Two further gates apply per call:
- Session scope. Every
messagesandenginecall carries asessionId, supplied by the plugin. The host runsassertSessionAllowed(manifest, sessionId)against the manifestsessionslist (['*']means all). Because thesessionIdoriginates from the plugin, this is the real security boundary — and it is static: editing config can never widen which sessions a plugin may touch. - Network allowlist.
ctx.net.fetchadditionally requires the target host to be allowed, and the request always traverses the SSRF guard, which blocks internal IP ranges even for an allowlisted host. The effective allowlist ismanifest.net.allowplus the https origin of the URL configured under every config key named inmanifest.net.allowConfigHosts, taken across the base config, every per-session override and the config of every enabled integration instance of the plugin. A value that is not an https URL, or that carries credentials, adds nothing, and since v0.24.0 the grant covers that scheme and port only. That second half is what lets an adapter reach an operator-provisioned tenant host that no manifest could name in advance, so unlike the session scope this list does widen with config. Since v0.26.0 the same host key also binds the secrets saved beside it: an override or instance that moves it to another origin does not inherit the layer beneath's secrets and must bring its own (see Scope a plugin to specific sessions).
A capability call is only as trustworthy as the sessionId the plugin passes in. If an operator could widen sessions by editing config at runtime, a compromised or buggy plugin could escalate from one session to all of them. Pinning the scope in the manifest keeps the boundary fixed for the life of the install.
The ctx.net.fetch contract
ctx.net.fetch(url, init?) takes init as { method?, headers?, body?, timeoutMs? }: method defaults to GET, and body is a string or a Uint8Array. It resolves to { ok, status, statusText, headers, body }, where body is the whole response decoded as UTF-8 text. There is no streaming and no binary result, so a binary download does not come through intact.
- Timeout.
timeoutMsdefaults to 15 seconds and is clamped to between 1 millisecond and 30 seconds; a value that is not a finite number falls back to the default. A fractional value is cut to a whole number of milliseconds before the clamp (v0.26.0+); before, a fractional value above 1 and below 30,000 failed the call. - Size cap. A response body over 10 MiB rejects the call with
plugin net.fetch response exceeds the 10485760-byte cap, whether the size is declared incontent-lengthor counted while the body streams. - Redirects. A redirect is never followed: any
3xxanswer rejects the call withRefusing to follow redirect from <url>, so request the final URL. - Concurrency. At most 16 fetches run at once across all plugins. A seventeenth rejects at once with
too many concurrent plugin net.fetch calls (max 16); retry shortly.
These limits are fixed in the gateway. The call is also bounded by the capability timeout (PLUGIN_CAP_TIMEOUT_MS, 30 seconds by default). With a lower setting there, the call rejects with capability 'net.fetch' timed out after <n>ms before its own timeoutMs, while the request keeps running on the host, and keeps its place among the 16, until it finishes or its own timeout ends it.
The manifest and the IPlugin contract
Two artifacts define a plugin: a declarative manifest.json and a code entry point that default-exports a class implementing IPlugin.
The manifest is the source of truth for what a plugin may do. Its required fields are id, name, version, type, and main; everything else is optional. The capability-relevant fields are:
| Field | Purpose |
|---|---|
permissions | The capability permissions above. Absent or empty means no capability access. |
sessions | Session ids the plugin may act on, or ['*']. Absent defaults to ['*']. Static — config edits can't widen it. |
sessionScoped | Default true: the plugin only sees events for sessions an operator activated it for. false means it always runs. |
net.allow | Outbound-HTTP host allowlist for ctx.net.fetch. Absent means deny all; "*" means any public host, with the SSRF guard still blocking internal addresses. Treat a "*" on a plugin whose README names specific endpoints as a review flag. |
configSchema | A declarative schema the dashboard renders into a config form. |
hooks | The hook events the plugin listens to (informational). |
The loader validates the required fields and resolves main strictly inside the plugin directory, a main path that escapes the directory is rejected. Since v0.24.0, an optional minOpenWAVersion must be a MAJOR.MINOR.PATCH version no newer than the host: an incompatible or malformed value refuses installation with 400, and the plugin is skipped at boot with a plugin_load_failed log. A declared ingress is checked against the Integration Fabric rules when the plugin loads and, since v0.31.0, when a package is installed or updated: a manifest the host would refuse at load answers 400 before anything is written and, for an update, before the running plugin is stopped (see Author an Integration Fabric adapter). testedOpenWAVersion records the plugin publisher's compatibility check and is not the gateway version.
The entry point is the behavior. Its module default-exports a class whose lifecycle methods are all optional. onLoad, onEnable, onDisable and onUnload receive only the PluginContext; onConfigChange also receives newConfig, the plugin's base config as it stands after the change, without any per-session override (and since v0.27.0 is also called immediately after onEnable if the base config was updated while onLoad/onEnable was running). In a hook handler, read config from ctx.config, which resolves to the firing session's slice:
// plugins/my-plugin/index.ts — shape only; implement IPlugin directly.
export default class MyPlugin {
async onLoad(ctx) {
ctx.registerHook('message:received', async hookCtx => {
const cfg = ctx.config; // per-session-merged config for this event
const { sessionId, data } = hookCtx;
const message = data;
if (message.body?.toLowerCase() === 'help' && sessionId) {
// Requires 'messages:send' + an in-scope, live session.
await ctx.messages.sendText(sessionId, message.from, cfg.greeting ?? 'How can I help you?');
return { continue: false }; // stop the chain
}
return { continue: true };
});
}
}
The context deliberately omits things a plugin might expect from other ecosystems. There is no ctx.api, ctx.router, or ctx.events: plugins do not mount HTTP routes and do not get an event emitter. They observe and act only through hooks and the permission-gated capability namespaces above. Storage is one of those namespaces: ctx.storage is a per-plugin key-value store whose values must survive a structured clone, bounded per plugin by PLUGIN_STORAGE_MAX_BYTES (default 50 MiB), and since v0.17.0 each of its four verbs requires storage:use. Since v0.26.0 list() returns only keys that get, set and delete accept, and a legacy key spelled like another key's encoded filename (key-Zm9v for foo) no longer reads or deletes that other key's value; since v0.28.0 set also rejects a key longer than 184 UTF-8 bytes so the base64url filename fits inside a 255-byte filesystem name limit (get answers null and delete does nothing for such a key). Since v0.31.0 a key that holds a lone UTF-16 surrogate (half of an emoji, left by cutting text with slice) is refused as an unsafe key too: set and delete reject it and get answers null, while a record an earlier version wrote under one stays reachable through the key spelled with U+FFFD. Also since v0.31.0 the keys ./manifest and ./package, or a spelling the filesystem folds to them, no longer reach the plugin's own manifest.json and package.json: get no longer reads the file, so it answers null unless the plugin itself stored a value under that key, and delete leaves the file.
Plugins implement the IPlugin interface directly today. An @openwa/plugin-sdk npm package is planned; until it ships, the live runtime interfaces are the contract. Importing the package name in examples is for type shape only.
Payload fields that are easy to miss
Plugins in the marketplace repository compile against a vendored types/openwa.d.ts rather than a published package. Six fields the host contract carries were absent from that file until recently — none of them a deliberate narrowing, so nothing marked them as missing. A field the vendored type does not name is a field an author has no way to discover, which is the whole cost of the omission:
| Type | Field | What it carries |
|---|---|---|
IncomingMessage | ephemeralDuration?: number | The chat's disappearing-messages timer in seconds, carried on every message. 0 or absent means no timer; WhatsApp's values are 86400 (24 h), 604800 (7 d) and 7776000 (90 d). |
IncomingMessage | call?: { video: boolean; missed: boolean } | Set on call (call-log) messages: video versus voice, and whether an incoming call went unanswered. |
IncomingMessage | backgroundColor?: string | Text status/story styling — the background as #RRGGBB. Only set by engines that expose it. |
IncomingMessage | font?: number | Text status/story styling — the WhatsApp font index. Only set by engines that expose it. |
ChatSummary | kind: ChatKind | The full chat discriminator: individual, group, channel, status, broadcast, or unknown. Required, as in core. isGroup is retained for back-compat but collapses six kinds into two. |
ConversationSendEnvelope | linkPreview?: boolean | Ask the engine for a link preview on a plain text send. Baileys generates one only when this is true, so a plugin relaying a URL otherwise delivers a bare link; whatsapp-web.js previews by default and takes false to suppress. Left out, or given as anything but a boolean, the send takes the session's linkPreview config default when one is set (v0.30.3), and so does a plain ctx.messages.sendText. Ignored on media, location, and quoted sends, which route through engine paths that take no preview option. |
The marketplace package ships separately from the gateway and cannot import from core, so "verified field-by-field against OpenWA core" in that file's header means someone diffed it by hand. Nothing enforces it, and it has been wrong before — five of the six fields above had been on the host for several minor versions by the time the alignment that missed them was written. When you re-align the file for a newer host, diff member by member and annotate anything you leave out, so the next reader can tell an omission from a decision.
Two more IncomingMessage fields arrived in v0.23.6, set on Baileys sessions only, so a vendored file aligned against an earlier host does not name them. button?: { id: string; text?: string } is set when the sender tapped a business button, template quick-reply, list row or native-flow control and the reply carries the choice's id; id is the handle the business defined. A reply without an id leaves button unset. A button, template or list reply still carries its label in body. A native-flow reply whose label sits only in its parameters carries that label in body when the parameters also carry the button's id, and arrives with an empty body when they do not. buttons?: Array<{ id: string; text: string }> is set on an inbound business prompt and lists up to 20 of the choices it offers that can be answered with a reply, leaving out URL and call buttons and every native-flow control not named quick_reply or button_click. A choice's id is the one the business defined, or its visible label when the prompt defines none; a choice whose id is longer than 256 characters is left out, and a label is cut to 256 characters. The same release reports Baileys button, template and list replies, and list prompts, as type: "text" with their text in body, where earlier releases reported unknown. Since v0.29.1 IncomingMessage on message:received and message:sent (both engines) and on ctx.engine.getChatHistory (whatsapp-web.js) also carries isForwarded?: boolean (true when the sender forwarded the message, absent otherwise) and forwardingScore?: number (set when isForwarded is true and the engine reports a positive count; both are stripped when a message arrives already deleted as type: 'revoked').
Lifecycle hooks
A plugin's real work happens in hook handlers it registers during onLoad via ctx.registerHook(event, handler, priority?). The host fires hooks at well-defined points across four lifecycles:
- Session:
session:created,session:starting,session:ready,session:qr,session:disconnected,session:error,session:deleted. - Message:
message:received,message:sending,message:sent,message:failed,message:ack(fires only for messages the account sent since v0.27.0),message:persisted,message:deleted. - Webhook:
webhook:before,webhook:queued,webhook:delivered,webhook:after,webhook:error. - Ingress:
ingress:error, fired once an inbound provider webhook's dispatch to the plugin has failed with every retry exhausted.
Since v0.24.0 POST /api/sessions/{sessionId}/messages/send-product also runs message:sending, with type product and { chatId, productId, body } as the input. A handler that returns { continue: false } blocks the send and the call answers 400; a rewritten productId or body is validated, and an invalid one answers 400 as well; a rewritten chatId is ignored. Since v0.27.0 a bulk audio item with ptt: true reports type: 'voice' on message:sending and message:failed, matching single voice-note sends (type: 'audio' before). Since v0.30.3 a handler that rewrites a send-text so that it carries both linkPreview: false and customLinkPreview gets the 400 the same request answers when sent directly.
session:created carries the new session in the shape the REST API returns it: id, name, status, phone, pushName, connectedAt, lastActive, createdAt, updatedAt, lastError, restriction and engineLoaded. It never carries the stored proxyUrl or config (v0.23.6+). Before v0.23.6 it carried the stored session row, so a plugin that read proxyUrl, config, lastActiveAt or another raw column from it no longer finds that field. session:deleted carries { id, name, phone, pushName }.
Since v0.23.6 a Baileys session that reconnects after being offline (a gateway restart included) replays what WhatsApp queued in the meantime: inbound messages from that window reach message:received, and messages the account sent from its phone reach message:sent. Earlier releases dropped both. A bot that should not answer a backlog can compare the message's timestamp (Unix seconds) with the current time. The same release keeps a re-delivered message the session has already recorded from reaching the message hooks a second time. If the message store cannot be read, that check lets the message through, so at worst a handler sees it twice.
message:persisted re-fires on every persisted transition as an upsert keyed by the row id — SENT with the engine id, FAILED on send failure, the surviving row after an echo-won merge, and (since v0.27.0) when an edit updates a stored message's text (carrying the same row id, the new body, and metadata.edited: true) — and message:deleted fires for the row that merge drops. Payloads are shallow snapshots taken at emission time, so fire-and-forget delivery sees the state as emitted. A search provider indexing these hooks therefore always sees the finalized state (and edited message text) rather than a ghost PENDING row it cannot correlate. Since v0.27.0 ctx.registerSearchProvider also receives match ('word' or 'contains') on the query object regardless of SEARCH_CONTAINS_ENABLED. Search-provider responses are validated at the host boundary: malformed hits or totals now fail with 502 (previously a bogus 200/500) — a breaking change for plugins that returned loose shapes. A provider that does not answer at all fails with 503 instead: its worker is not running, the query passed the 10-second search timeout, or the handler threw. GET /api/search declares both statuses in the OpenAPI contract from v0.23.3; the behaviour predates that.
Handlers for a given event run in priority order (lower priority first; default 100). Since v0.23.6 a priority that is not a finite number runs at 100, and a plugin's handlers for one event run together at the lowest priority any of them asked for, in their own priority order among themselves; before, they ran at the priority of the plugin's first handler for that event, so a later handler with a lower priority could still run after another plugin's. The host walks the chain, threading each handler's result into the next:
A handler controls the chain through its return value:
| Return | Effect |
|---|---|
{ continue: true } | Let the next handler (and the host) proceed unchanged. |
{ continue: true, data: x } | Replace the event payload — the next handler and the host see x. On message:received and message:sent, x must still be a message (an object with a string id and chatId), and on webhook:before an object whose payload is a plain object. Since v0.23.6 any other x (null, a primitive, {}) is skipped, and the chain keeps the last usable value, an earlier handler's rewrite included. The host logs a warning for a skipped result from a built-in plugin; a sandboxed plugin's result is skipped inside its worker, which writes no log line. Before, such a result on a message event erased the message from history, webhooks and the websocket, and on webhook:before an array payload was sent as the whole body without the event's identity fields, a payload of any other type except null and undefined (a string or number, for instance) failed the delivery, and any other such result sent the original payload, dropping a replacement an earlier handler had returned. |
{ continue: false } | Stop the chain immediately. |
{ error: e } | Not a way to fail the operation. A built-in plugin treats it exactly like throwing: the host logs it, the chain continues with the previous data, the handler's data mutation is discarded, and it is skipped entirely when paired with { continue: false }, which returns first. A sandboxed plugin, which is every plugin installed from a package, is treated the same way since v0.26.0, the first error per hook being reported as described below; before v0.26.0 the returned error was ignored there: the result was read as if it were absent, so its data was applied and nothing was logged, and a failure had to be thrown. |
The hook manager is built to keep one plugin from breaking the system:
- A handler that throws is logged, and the chain continues with the previous data. One bad plugin cannot break the chain. Inside the sandbox, the first handler error per hook also surfaces as a rate-limited structured host log and in the plugin's health check — sandboxed handler errors are no longer swallowed wholesale.
- Same-event re-entrancy is blocked. A handler that re-fires the event it is handling is short-circuited (this guards synchronous re-entry). For a sandboxed plugin the host carries the chain across the worker boundary, and since v0.23.6 only a capability call made by a hook handler, or by async work it started, while that dispatch is still pending counts as re-entrant: a send from an ingress handler, from a timer started outside a hook handler, or from one that fires after the dispatch has settled runs every plugin's hooks even while one of the plugin's own hooks is pending. Before, such a send could skip other plugins'
message:sendingvetoes and theirmessage:sentandmessage:failedhooks. A sandboxed handler that outlives the 5-second hook budget stays inside the guard until the worker answers it or exits (v0.26.0+; the host holds at most 32 such timed-out dispatches per worker and gives the oldest back beyond that), so a send it makes late no longer re-fires the event and dispatches the slow handler again; before, the guard let go at the timeout. For a built-in plugin, whose handlers run in the host process, the guard ends with the call that opened it (v0.26.0+): a send that a handler schedules from a timer or a detached promise after that call has settled runs every handler, a moderation veto included, where before it was skipped as re-entrant. - Plugins never call the hook manager directly.
ctx.registerHookwraps the handler with the per-session activation gate, so a session-scoped plugin only runs for the sessions an operator activated it for.
The ADMIN-only management API
A plugin does not enable or configure itself. Its entire lifecycle is driven by PluginsController, mounted at plugins, where every route requires the ADMIN role, not a bare API-key guard. The role alone is not enough: a key restricted with allowedChats is refused with 403 on every plugin route (v0.23.6+), and one restricted with allowedSessions on every route except PUT /plugins/:id/config/:sessionId for a session inside its scope (a session outside it is refused there with 403). The dashboard is a client of this API; an operator (or your automation) is always the one in control.
| Method & path | Purpose |
|---|---|
GET /plugins | List all plugins. |
GET /plugins/catalog | List the remote catalog, annotated with install state. |
GET /plugins/:id | Get a single plugin. |
POST /plugins/install | Install from an uploaded .zip (multipart/form-data, field file, ≤ 5 MB). |
POST /plugins/install-url | Install by downloading a .zip from a URL (SSRF-guarded; https://, or http:// with a required #sha256= integrity pin; in production the pin is required on every URL install, v0.20.0+). |
POST /plugins/:id/update | Update an installed plugin in place from a URL (preserves config + enabled state). |
POST /plugins/:id/enable | Enable a plugin. |
POST /plugins/:id/disable | Disable a plugin. For the engine ENGINE_TYPE selects, the call answers success: false (v0.23.6+); switching engines takes a config change and a restart. |
PUT /plugins/:id/config | Update the plugin's base config. |
PUT /plugins/:id/config/:sessionId | Set (or clear) a per-session config override. |
PUT /plugins/:id/sessions | Set which sessions a session-scoped plugin is activated for. |
GET /plugins/:id/config-ui | Serve the plugin's sandboxed config-editor HTML (see the callout below). |
GET /plugins/:id/health | Run the plugin's healthCheck. A sandboxed plugin with no running worker (disabled, never enabled, or failed) answers 200 with healthy: false and a message (v0.23.7+). |
DELETE /plugins/:id | Uninstall a plugin and remove its files (built-ins are protected). |
Installation is always a .zip package — by upload, by URL, or from the catalog — never an npm or GitHub source descriptor. Two state rules matter conceptually:
- Loading is not enabling. On startup the loader discovers every plugin on disk, reads and validates its manifest, and records it as
INSTALLEDwithout running any plugin code. A plugin directory that is a symbolic link to a directory is not followed: since v0.31.0 the scan skips it with aplugin_symlink_skippedwarning, where it used to skip it without a log line, so the package has to sit in that directory itself, as a copy or a bind mount. Once the rest of the gateway is up, the loader re-enables every plugin an operator had enabled, since the enable decision is stored apart from the runtime status (v0.10.5+); a plugin that fails to come back is logged (plugin_restore_failed) and left inERROR. The gateway waits at most 60 seconds for this restore before it opens its HTTP port (v0.26.0+; before, it waited for every plugin): it then logsplugin_restore_deferred, and the plugins not yet restored keep coming up in order in the background. Until a plugin is up its hooks do not run, so a request that arrives meanwhile is not seen by them;enable,disable,update,DELETEand an install of the same id answer409; and a delivery to its ingress routes is refused with503or held (see Author an Integration Fabric adapter). A plugin whose load fails at boot has its registry entry reconciled toERRORinstead of reportinginstalled/enabled; the operator config is preserved, and a later successful load restores the status. - Enabling is always explicit. Running a plugin's
onLoad/onEnableand wiring its capabilities is an ADMIN action. Two enables happen at boot without that action: the gateway enables the built-in engine thatENGINE_TYPEselects, and it restores each plugin an operator had already enabled. Disabling a plugin withdraws the operator's decision.
GET /plugins/:id/config-ui returns the plugin's config editor with Content-Security-Policy: sandbox and X-Content-Type-Options: nosniff. The dashboard fetches it with the API key but injects the body as an iframe srcdoc on an opaque origin, exchanging config over a postMessage bridge — so the API key never reaches the plugin's UI code.
The worker-thread sandbox
OpenWA splits plugins into two trust tiers, and the loader routes each automatically:
| Tier | What runs here | Where it runs | How it reaches capabilities |
|---|---|---|---|
| Built-in (trusted) | The two engine adapters (whatsapp-web.js, baileys), registered programmatically | In-process | Direct, full speed |
| Untrusted | Anything loaded from the plugins/ directory | In a Node worker_thread | Only through the host-validated bridge |
There is no vm2. An untrusted plugin runs in its own V8 context inside a worker thread, and every capability call and hook dispatch round-trips to the host over a MessagePort. The host applies the same permission and session-scope checks it would for an in-process plugin — the sandbox cannot be used to bypass them.
What the sandbox guarantees
- No host-object access. The worker holds no reference to the loader, the engine, the database, or any host singleton. Its only channel out is the
MessagePort, and the host's verbs are allowlisted — a worker cannot invoke an arbitrary host method. - Mediated capabilities. WhatsApp, the engine, and storage are reachable only through
ctx.messages/ctx.engine/ctx.storage, each re-checked against permissions and session scope on the host side. A sandboxed plugin can never exceed its declared manifest permissions. - Hook safety. A sandboxed hook handler has a 5-second budget (fixed:
SANDBOX_HOOK_TIMEOUT_MSis a module constant, not an environment variable; queued ingress webhook dispatches withQUEUE_ENABLED=truegetSIMULATE_TYPING_MAX_MS+ 5 seconds, capped at 25 seconds, since v0.28.0). On timeout the host resolves{ continue: true }(fail-open), so a wedged handler never stalls the chain; the same value drains in-flight hooks if the worker crashes. When a hook handler triggers an outbound send and does not need the send result, start it withvoid ctx.messages.sendText(...)withoutawaitso typing simulation does not consume the 5-second hook budget. A timeout alone cannot tell a slow async handler from a synchronous loop that never yields, so after a hook, ingress or search dispatch times out the host pings the worker. Since v0.24.0 a worker that stays silent for a further 5 seconds is terminated and its plugin is set toERRORwith its hooks unregistered, instead of making every later event wait out the budget again (about 10 seconds after a stalled hook or inline ingress dispatch, 15 seconds after a stalled search). A worker that answers is left running. The plugin is not restarted automatically:GET /api/plugins/{id}reportserror, the gateway logssandbox_worker_unresponsive, and an enable after the cause is fixed starts a fresh worker. - Fault and resource containment. Each worker has a heap cap (
maxOldGenerationSizeMb, fixed at 256 MB) — an OOM kills the worker, not the host. A runaway, even an infinite synchronous loop, can be force-terminated, and a crash rejects only its in-flight calls. A worker that crashes, or that is terminated for not answering, leaves its plugin inERROR, logged assandbox_worker_exitorsandbox_worker_unresponsive. Lifecycle methods are bounded by a 30-second timeout andhealthCheckby 5 seconds, so a wedged plugin can't hang an ADMIN enable/disable. Capability calls time out afterPLUGIN_CAP_TIMEOUT_MS(default 30 seconds), except the three whose host-side work is an outbound send (messages.sendText,messages.reply,conversation.send), which get four times that budget so a media download and upload cannot trip the timeout mid-send; timing out frees the in-flight slot — a hung plugin could previously pin all 32 capability slots forever — and a call that settles late is logged as a warning; work already running in the worker is not cancelled, by design. The log relay truncates lines, caps throughput per plugin, and flushes its dropped-line count on worker exit, so a plugin that goes quiet still reports what it dropped. Since v0.26.0 it relays a non-string log message as[non-string log message], and replaces a meta of more than 8192 values and characters (counted without building its text), or whose text as the logger writes it (a credential value as[REDACTED]) passes 8192 characters, with ametaTruncatedmarker. A meta that is a string, array, Map, Date or Error is written as onemetafield, andctx.logger.errorcalled without an error no longer writes the traceundefined. The worker also gets a minimal allowlisted environment (NODE_ENV,NODE_EXTRA_CA_CERTS,TZ); host secrets such as the master key and database credentials are withheld. - Bounded worker output. A loop that never yields posts to the host faster than the host's one thread can read, so since v0.31.0 the worker limits what it sends. It posts at most 198
ctx.loggerlines per 10 seconds, of any level, and drops the rest inside the worker, with a note at the first drop and a count with the first line after the window ends. It leaves at most 64 capability calls unanswered at once: a call made while 64 are waiting is held in the worker and posted, in order, as each reply frees a slot, and the worker refuses a call with a thrownErroronly when 10,000 are already held, so aPromise.allover a long list of quick calls, such as storage reads, is answered in full. A send (ctx.messages.sendText,ctx.messages.reply,ctx.conversations.send) that was held and is still held when the hook handler that made it returns is refused with a thrownErroras well, since posting it then would fire the hooks of the send outside the re-entrancy guard. The host's own bound of 32 concurrent calls is unchanged: a call that reaches the host while 32 are still running, as a burst of slow calls such as sends can, is refused there with a thrownError. A plugin that awaits its calls one after another never has a call held.
What the sandbox does NOT guarantee
A worker_thread is a separate V8 context in the same OS process, under the same user. The worker still has access to Node built-ins — require('fs'), process, network sockets — and runs as the same uid as OpenWA.
The sandbox protects the integrity of the host: no host-object compromise, contained faults, mediated capabilities. It does not, on its own, protect the confidentiality of the host filesystem against a plugin that deliberately abuses Node built-ins. Such a plugin could read files the OpenWA process can read or open outbound sockets directly, outside the capability model.
For genuinely untrusted, third-party plugins, combine the sandbox with OS-level containment: the shipped Docker image already runs a read-only rootfs, as non-root, with cap_drop: ALL, which bounds what any plugin's fs and network access can reach. The standing guidance is to install only plugins you trust.
What this means for plugin authors
The trust tier is invisible in your code — a sandboxed plugin keeps the same IPlugin shape. Three rules follow from the boundary being real:
- Capability calls genuinely cross a thread. They were always
async; nothing changes in how you call them. - Only serializable data crosses. Hook payloads, capability arguments, and results must be structured-clone-safe: plain objects, arrays, primitives,
Date, typed arrays. No functions, no class instances with methods, no live references. - Declare every permission you use. A capability call is denied unless the manifest declares the matching permission. Treat Node built-ins inside the worker as off-limits — anything you legitimately need should be a declared capability, and OS containment may block direct access anyway.
Next steps
- Building a Plugin — apply this model: write the manifest, implement
IPlugin, register hooks, and install. - Plugins overview — where plugins fit in OpenWA.
- Plugin catalog — the official plugins and what each one declares.
- Publishing — package and ship a plugin.