Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat: plugin platform — sandboxed plugins + dashboard install/uninstall (v0.6.0) (#426)

Yudhi Armyndharis3337cd70da63
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 805f4eb52..d43d36eef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,9 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [0.6.0] - 2026-06-22
+
+The **plugin platform** release: untrusted plugins now run sandboxed, and you can install and uninstall them from the dashboard. One breaking change for plugin authors (the sandbox context), so this is a minor bump.
+
+### Added
+
+- **Install and uninstall plugins from the dashboard.** Upload a plugin packaged as a `.zip` (`POST /api/plugins/install`) and remove it (`DELETE /api/plugins/:id`). The Plugins page is redesigned into a status rail — the active engine + library version, enabled/installed counts, and the live list of active plugins — alongside a catalog with an Install button and a per-plugin Uninstall. Uploaded packages are validated (manifest, safe id, zip-slip + size guards), only `extension` plugins are installable (engines and other tiers stay built-in), and built-ins cannot be uninstalled.
+
+### Changed
+
+- ⚠️ **Breaking (plugin authors):** plugins loaded from the `plugins/` directory now run sandboxed in an isolated worker thread instead of in-process. Their context is curated to `messages`, `engine`, `storage`, `logger`, `config`, `pluginId`, and `registerHook`, with capability calls permission-checked on the host — a sandboxed plugin can no longer reach the host `hookManager` directly or share host objects. Bundled/built-in plugins (engines, auto-reply, translation) are unaffected and still run in-process. See `docs/23-plugin-sandboxing.md` for the trust model and the boundary's limits.
+- Engines are now single-active: enabling an engine other than the configured `engine.type` is rejected (switch engines in settings, then restart). The dashboard shows the active engine as **Active** and the others as **Available**, fixing the state where two engines could appear active at once.
+- Calmer plugin cards — the loud gradient, type-colored card headers are replaced with clean cards and a subtle type-tinted icon.
+
### Fixed
- Plugins page: the "Active" state and the Enable/Activate actions were all the same green and hard to tell apart. Actions are now a solid green button and the current state a neutral chip. (#417)
+- The dashboard reports each plugin's real built-in status (previously only the WhatsApp Web.js engine was flagged built-in).
+- The appearance/theme popover no longer spills outside the sidebar onto the page. (#424)
## [0.5.1] - 2026-06-22
diff --git a/dashboard/package.json b/dashboard/package.json
index 919d15460..63d73bc2a 100644
--- a/dashboard/package.json
+++ b/dashboard/package.json
@@ -1,7 +1,7 @@
{
"name": "dashboard",
"private": true,
- "version": "0.5.0",
+ "version": "0.6.0",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/dashboard/src/pages/Plugins.css b/dashboard/src/pages/Plugins.css
index f2ad41fa5..42c7b822e 100644
--- a/dashboard/src/pages/Plugins.css
+++ b/dashboard/src/pages/Plugins.css
@@ -105,74 +105,96 @@
}
.plugin-card-header {
- padding: 1rem 1.25rem;
+ padding: 1.25rem 1.25rem 1rem;
display: flex;
align-items: center;
justify-content: space-between;
-}
-
-.plugin-card-header.type-engine {
- background: linear-gradient(135deg, #22c55e 0%, #10b981 100%);
-}
-
-.plugin-card-header.type-storage {
- background: linear-gradient(135deg, #22c55e 0%, #10b981 100%);
-}
-
-.plugin-card-header.type-queue {
- background: linear-gradient(135deg, #f97316 0%, #f59e0b 100%);
-}
-
-.plugin-card-header.type-auth {
- background: linear-gradient(135deg, #a855f7 0%, #8b5cf6 100%);
-}
-
-.plugin-card-header.type-extension {
- background: linear-gradient(135deg, #ec4899 0%, #f43f5e 100%);
+ gap: 0.5rem;
}
.plugin-info {
display: flex;
align-items: center;
gap: 0.75rem;
+ min-width: 0;
}
.plugin-icon-wrapper {
- width: 40px;
- height: 40px;
- background: rgba(255, 255, 255, 0.2);
- border-radius: 8px;
+ width: 42px;
+ height: 42px;
+ background: var(--bg-light);
+ border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
+ flex-shrink: 0;
}
.plugin-icon-wrapper svg {
- color: #fff;
+ color: var(--text-secondary);
+}
+
+/* Calm, low-saturation type tints on the icon only — no loud gradient header, no alarming red. */
+.type-engine .plugin-icon-wrapper {
+ background: rgba(34, 197, 94, 0.12);
+}
+.type-engine .plugin-icon-wrapper svg {
+ color: #16a34a;
+}
+.type-extension .plugin-icon-wrapper {
+ background: rgba(99, 102, 241, 0.12);
+}
+.type-extension .plugin-icon-wrapper svg {
+ color: #6366f1;
+}
+.type-storage .plugin-icon-wrapper {
+ background: rgba(13, 148, 136, 0.12);
+}
+.type-storage .plugin-icon-wrapper svg {
+ color: #0d9488;
+}
+.type-queue .plugin-icon-wrapper {
+ background: rgba(217, 119, 6, 0.12);
+}
+.type-queue .plugin-icon-wrapper svg {
+ color: #d97706;
+}
+.type-auth .plugin-icon-wrapper {
+ background: rgba(147, 51, 234, 0.12);
+}
+.type-auth .plugin-icon-wrapper svg {
+ color: #9333ea;
}
.plugin-name {
- font-size: 1rem;
+ font-size: 0.9375rem;
font-weight: 600;
- color: #fff;
+ color: var(--text-primary);
margin: 0;
text-transform: none;
letter-spacing: normal;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
}
.plugin-version {
font-size: 0.75rem;
- color: rgba(255, 255, 255, 0.75);
+ color: var(--text-muted);
}
.plugin-builtin-badge {
- padding: 0.25rem 0.5rem;
- background: rgba(255, 255, 255, 0.2);
- color: #fff;
+ padding: 0.1875rem 0.5rem;
+ background: var(--bg-light);
+ color: var(--text-muted);
font-size: 0.625rem;
font-weight: 600;
- border-radius: 4px;
+ border-radius: 5px;
text-transform: uppercase;
+ letter-spacing: 0.04em;
+ border: 1px solid var(--border);
+ white-space: nowrap;
+ flex-shrink: 0;
}
.plugin-card-body {
@@ -582,3 +604,216 @@
gap: 1rem;
}
}
+
+/* ── Two-column control layout: status rail + plugin catalog ─────────────── */
+.plugins-layout {
+ display: flex;
+ gap: 1.5rem;
+ align-items: flex-start;
+}
+
+.plugins-rail {
+ flex: 0 0 280px;
+ position: sticky;
+ top: 1.5rem;
+ display: flex;
+ flex-direction: column;
+ gap: 1.25rem;
+ background: var(--bg-white);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ padding: 1.25rem;
+}
+
+.plugins-main {
+ flex: 1 1 auto;
+ min-width: 0;
+}
+
+.rail-label {
+ font-size: 0.6875rem;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--text-muted);
+ margin-bottom: 0.625rem;
+}
+
+.rail-engine {
+ display: flex;
+ align-items: center;
+ gap: 0.625rem;
+}
+
+.rail-engine-icon {
+ width: 34px;
+ height: 34px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(34, 197, 94, 0.12);
+ color: #16a34a;
+ border-radius: 8px;
+ flex-shrink: 0;
+}
+
+.rail-engine-meta {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ flex: 1;
+}
+
+.rail-engine-name {
+ font-weight: 600;
+ font-size: 0.875rem;
+ color: var(--text-primary);
+}
+
+.rail-engine-lib {
+ font-size: 0.75rem;
+ color: var(--text-muted);
+}
+
+.rail-stats {
+ display: flex;
+ gap: 0.75rem;
+}
+
+.rail-stat {
+ flex: 1;
+ background: var(--bg-light);
+ border-radius: 8px;
+ padding: 0.625rem 0.75rem;
+ text-align: center;
+}
+
+.rail-stat-num {
+ display: block;
+ font-size: 1.25rem;
+ font-weight: 700;
+ color: var(--text-primary);
+ line-height: 1.2;
+}
+
+.rail-stat-label {
+ font-size: 0.6875rem;
+ color: var(--text-muted);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+}
+
+.rail-active-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.rail-active-item {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.rail-active-name {
+ font-size: 0.8125rem;
+ color: var(--text-primary);
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.rail-active-type {
+ font-size: 0.625rem;
+ color: var(--text-muted);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+}
+
+.rail-empty {
+ font-size: 0.8125rem;
+ color: var(--text-muted);
+}
+
+/* Engine that isn't the active one — non-actionable (switch via Settings + restart) */
+.btn-available {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem;
+ padding: 0.625rem 1rem;
+ background: var(--bg-light);
+ border: 1px dashed var(--border);
+ color: var(--text-muted);
+ font-size: 0.875rem;
+ font-weight: 500;
+ border-radius: 8px;
+ cursor: default;
+}
+
+/* Uninstall icon button — neutral, red on hover */
+.btn-action-danger:hover {
+ background: rgba(239, 68, 68, 0.1);
+ border-color: rgba(239, 68, 68, 0.3);
+}
+
+.btn-action-danger:hover svg {
+ color: #ef4444;
+}
+
+/* Install modal */
+.install-hint {
+ font-size: 0.875rem;
+ color: var(--text-secondary);
+ line-height: 1.5;
+ margin-bottom: 1rem;
+}
+
+.install-drop {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 0.625rem;
+ padding: 2rem 1rem;
+ border: 2px dashed var(--border);
+ border-radius: 10px;
+ color: var(--text-muted);
+ cursor: pointer;
+ transition: all 0.15s;
+ text-align: center;
+}
+
+.install-drop:hover {
+ border-color: var(--primary, #25d366);
+ color: var(--text-secondary);
+}
+
+.install-drop.has-file {
+ border-style: solid;
+ border-color: var(--primary, #25d366);
+ color: var(--text-primary);
+ background: rgba(34, 197, 94, 0.05);
+}
+
+.install-drop-name {
+ font-size: 0.875rem;
+ word-break: break-all;
+}
+
+@media (max-width: 860px) {
+ .plugins-layout {
+ flex-direction: column;
+ }
+
+ .plugins-rail {
+ flex-basis: auto;
+ width: 100%;
+ position: static;
+ }
+}
diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsx
index bf0399664..9b1dd940b 100644
--- a/dashboard/src/pages/Plugins.tsx
+++ b/dashboard/src/pages/Plugins.tsx
@@ -16,6 +16,8 @@ import {
Shield,
Zap,
X,
+ Upload,
+ Trash2,
} from 'lucide-react';
import { pluginsApi, infraApi } from '../services/api';
import type { Plugin } from '../services/api';
@@ -73,6 +75,9 @@ export default function Plugins() {
const [savingConfig, setSavingConfig] = useState(false);
// Values for a schema-driven (non-engine) plugin's config form, keyed by configSchema property.
const [schemaConfig, setSchemaConfig] = useState<Record<string, unknown>>({});
+ const [showInstallModal, setShowInstallModal] = useState(false);
+ const [installFile, setInstallFile] = useState<File | null>(null);
+ const [installing, setInstalling] = useState(false);
const refetchAll = () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });
@@ -162,6 +167,43 @@ export default function Plugins() {
}
};
+ const handleInstall = async () => {
+ if (!installFile) return;
+ if (installFile.size > 5 * 1024 * 1024) {
+ toast.error(
+ t('plugins.toasts.installFailed', 'Install failed'),
+ t('plugins.installModal.tooLarge', 'The file exceeds the 5 MB limit.'),
+ );
+ return;
+ }
+ setInstalling(true);
+ try {
+ const installed = await pluginsApi.install(installFile);
+ refetchAll();
+ toast.success(t('plugins.toasts.installed', 'Plugin installed'), installed.name);
+ setShowInstallModal(false);
+ setInstallFile(null);
+ } catch (err) {
+ toast.error(t('plugins.toasts.installFailed', 'Install failed'), err instanceof Error ? err.message : '');
+ } finally {
+ setInstalling(false);
+ }
+ };
+
+ const handleUninstall = async (plugin: Plugin) => {
+ if (!window.confirm(t('plugins.uninstallConfirm', `Uninstall "${plugin.name}"? This deletes its files.`))) return;
+ setActionLoading(plugin.id);
+ try {
+ await pluginsApi.uninstall(plugin.id);
+ refetchAll();
+ toast.success(t('plugins.toasts.uninstalled', 'Plugin uninstalled'), plugin.name);
+ } catch (err) {
+ toast.error(t('plugins.toasts.uninstallFailed', 'Uninstall failed'), err instanceof Error ? err.message : '');
+ } finally {
+ setActionLoading(null);
+ }
+ };
+
if (loading) {
return (
<div
@@ -174,6 +216,8 @@ export default function Plugins() {
}
const activeEngine = engines.find(e => e.id === currentEngine);
+ const enabledCount = plugins.filter(p => p.status === 'enabled').length;
+ const activePlugins = plugins.filter(p => p.status === 'enabled');
return (
<div className="plugins-page">
@@ -181,10 +225,16 @@ export default function Plugins() {
title={t('plugins.title')}
subtitle={t('plugins.subtitle')}
actions={
- <button className="btn-secondary" onClick={refetchAll}>
- <RefreshCw size={16} />
- {t('plugins.refresh')}
- </button>
+ <>
+ <button className="btn-secondary" onClick={refetchAll}>
+ <RefreshCw size={16} />
+ {t('plugins.refresh')}
+ </button>
+ <button className="btn-primary" onClick={() => setShowInstallModal(true)}>
+ <Upload size={16} />
+ {t('plugins.install', 'Install plugin')}
+ </button>
+ </>
}
/>
@@ -195,38 +245,57 @@ export default function Plugins() {
</div>
)}
- <div className="engine-card">
- <div className="engine-header">
- <div className="engine-info">
- <div className="engine-icon-wrapper">
- <Cpu size={24} />
- </div>
- <div>
- <h3 className="engine-title">{t('plugins.engineCard')}</h3>
- <span className="engine-name">
- {currentEngine}
- {activeEngine?.library && ` · ${activeEngine.library.name} ${activeEngine.library.version}`}
- </span>
+ <div className="plugins-layout">
+ <aside className="plugins-rail">
+ <div className="rail-section">
+ <p className="rail-label">{t('plugins.rail.engine', 'Active engine')}</p>
+ <div className="rail-engine">
+ <div className="rail-engine-icon">
+ <Cpu size={18} />
+ </div>
+ <div className="rail-engine-meta">
+ <span className="rail-engine-name">{currentEngine || '—'}</span>
+ {activeEngine?.library && (
+ <span className="rail-engine-lib">
+ {activeEngine.library.name} {activeEngine.library.version}
+ </span>
+ )}
+ </div>
+ <span className="status-badge connected">{t('plugins.running')}</span>
</div>
</div>
- <span className="status-badge connected">{t('plugins.running')}</span>
- </div>
- {activeEngine && activeEngine.features.length > 0 && (
- <div className="engine-features">
- <p className="features-label">{t('plugins.supportedFeatures')}</p>
- <div className="features-list">
- {activeEngine.features.map(feature => (
- <span key={feature} className="feature-tag">
- {feature.replace(/-/g, ' ')}
- </span>
- ))}
+ <div className="rail-stats">
+ <div className="rail-stat">
+ <span className="rail-stat-num">{enabledCount}</span>
+ <span className="rail-stat-label">{t('plugins.rail.enabled', 'enabled')}</span>
+ </div>
+ <div className="rail-stat">
+ <span className="rail-stat-num">{plugins.length}</span>
+ <span className="rail-stat-label">{t('plugins.rail.installed', 'installed')}</span>
</div>
</div>
- )}
- </div>
- <div className="plugins-grid">
+ <div className="rail-section">
+ <p className="rail-label">{t('plugins.rail.active', 'Active plugins')}</p>
+ {activePlugins.length === 0 ? (
+ <p className="rail-empty">{t('plugins.rail.none', 'None enabled yet')}</p>
+ ) : (
+ <ul className="rail-active-list">
+ {activePlugins.map(p => (
+ <li key={p.id} className="rail-active-item">
+ <span className="status-dot enabled" />
+ <span className="rail-active-name">{p.name}</span>
+ <span className="rail-active-type">{p.type}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </aside>
+
+ <main className="plugins-main">
+ <div className="plugins-grid">
{plugins.map(plugin => {
const TypeIcon = pluginTypeIcons[plugin.type as PluginType] || Puzzle;
const isLoading = actionLoading === plugin.id;
@@ -295,21 +364,16 @@ export default function Plugins() {
</span>
);
} else {
+ // Engines are pinned to engine.type and switched via Settings + restart, not at
+ // runtime — show "available" instead of a misleading "Activate" that the API rejects.
return (
- <button
- onClick={() => handleToggle(plugin)}
- disabled={isLoading}
- className="btn-toggle enable"
+ <span
+ className="btn-available"
+ title={t('plugins.engineSwitchHint', 'Set as the active engine in Settings, then restart')}
>
- {isLoading ? (
- <Loader2 size={16} className="animate-spin" />
- ) : (
- <>
- <Power size={16} />
- {t('plugins.activate')}
- </>
- )}
- </button>
+ <Cpu size={16} />
+ {t('plugins.available', 'Available')}
+ </span>
);
}
})()
@@ -347,11 +411,24 @@ export default function Plugins() {
<button className="btn-action" title={t('plugins.configure')} onClick={() => handleOpenConfig(plugin)}>
<Settings size={16} />
</button>
+
+ {!plugin.builtIn && (
+ <button
+ className="btn-action btn-action-danger"
+ title={t('plugins.uninstall', 'Uninstall')}
+ onClick={() => void handleUninstall(plugin)}
+ disabled={isLoading}
+ >
+ <Trash2 size={16} />
+ </button>
+ )}
</div>
</div>
</div>
);
})}
+ </div>
+ </main>
</div>
{plugins.length === 0 && !loading && (
@@ -362,6 +439,45 @@ export default function Plugins() {
</div>
)}
+ {showInstallModal && (
+ <div className="modal-overlay" onClick={() => setShowInstallModal(false)}>
+ <div className="modal install-modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>{t('plugins.installModal.title', 'Install a plugin')}</h2>
+ <button className="btn-icon" onClick={() => setShowInstallModal(false)}>
+ <X size={20} />
+ </button>
+ </div>
+ <div className="modal-body">
+ <p className="install-hint">
+ {t('plugins.installModal.hint', 'Upload a plugin packaged as a .zip (with a manifest.json). It runs sandboxed once enabled.')}
+ </p>
+ <label className={`install-drop${installFile ? ' has-file' : ''}`}>
+ <input
+ type="file"
+ accept=".zip,application/zip"
+ hidden
+ onChange={e => setInstallFile(e.target.files?.[0] ?? null)}
+ />
+ <Upload size={28} />
+ <span className="install-drop-name">
+ {installFile ? installFile.name : t('plugins.installModal.choose', 'Choose a .zip file…')}
+ </span>
+ </label>
+ </div>
+ <div className="modal-footer">
+ <button className="btn-secondary" onClick={() => setShowInstallModal(false)} disabled={installing}>
+ {t('common.cancel', 'Cancel')}
+ </button>
+ <button className="btn-primary" onClick={() => void handleInstall()} disabled={!installFile || installing}>
+ {installing ? <Loader2 size={16} className="animate-spin" /> : <Upload size={16} />}
+ {t('plugins.install', 'Install plugin')}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
{showConfigModal && configPlugin && (
<div className="modal-overlay" onClick={() => setShowConfigModal(false)}>
<div className="modal config-modal" onClick={e => e.stopPropagation()}>
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 16623b55b..c2d22cea5 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -284,8 +284,10 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<
// Get API key from sessionStorage for authentication
const apiKey = sessionStorage.getItem('openwa_api_key');
+ // For FormData (file uploads) let the browser set multipart/form-data + boundary itself.
+ const isFormData = options.body instanceof FormData;
const headers: HeadersInit = {
- 'Content-Type': 'application/json',
+ ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
...(apiKey ? { 'X-API-Key': apiKey } : {}),
...options.headers,
};
@@ -639,6 +641,12 @@ export const pluginsApi = {
body: JSON.stringify({ config }),
}),
healthCheck: (id: string) => request<{ healthy: boolean; message?: string }>(`/plugins/${id}/health`),
+ install: (file: File) => {
+ const form = new FormData();
+ form.append('file', file);
+ return request<Plugin>('/plugins/install', { method: 'POST', body: form });
+ },
+ uninstall: (id: string) => request<{ success: boolean; message: string }>(`/plugins/${id}`, { method: 'DELETE' }),
getEngines: () => request<Engine[]>('/infra/engines'),
getCurrentEngine: () => request<{ engineType: string }>('/infra/engines/current'),
};
diff --git a/docs/23-plugin-sandboxing.md b/docs/23-plugin-sandboxing.md
new file mode 100644
index 000000000..ab4f2c64d
--- /dev/null
+++ b/docs/23-plugin-sandboxing.md
@@ -0,0 +1,80 @@
+# 23 — Plugin Sandboxing
+
+OpenWA runs **untrusted plugins** (anything loaded from the plugins directory) in an isolated worker
+thread, separate from first-party built-ins (engines, bundled extensions) which run in-process. This
+page describes the security model honestly — what the sandbox guarantees and, just as important, what
+it does not — and what changes for plugin authors.
+
+## Trust tiers
+
+| Tier | Examples | Runs | Capabilities |
+|------|----------|------|--------------|
+| **Built-in (trusted)** | engines (whatsapp-web.js, baileys), bundled extensions (auto-reply, translation) | in-process | direct, full speed |
+| **Untrusted** | anything in the plugins directory | in a `worker_thread` | only via the host-validated bridge |
+
+The loader routes by tier automatically: a plugin registered programmatically is built-in; one loaded
+from disk is untrusted and sandboxed.
+
+## What the sandbox guarantees
+
+- **No host-object access.** The worker runs in its own V8 context. It receives no reference to the
+ loader, the engine, the database, `MessageService`, or any host singleton. Its only channel out is
+ a `MessagePort`.
+- **Capability mediation.** A plugin can touch WhatsApp / the database **only** through
+ `ctx.messages.*` / `ctx.engine.*` / `ctx.storage.*`, which round-trip to the host. The host runs
+ each call through the same permission + session-scope checks an in-process plugin gets
+ (`assertPermission` / declared `sessions`), so a sandboxed plugin can never exceed its declared
+ manifest permissions. Verbs are allowlisted — a worker cannot invoke an arbitrary host method.
+- **Hook safety.** Hook handlers run in the worker and are dispatched with a **time budget**
+ (`SANDBOX_HOOK_TIMEOUT_MS`, default 5s). A slow or wedged handler is skipped (`continue: true`) so
+ it can never stall the host's hook chain.
+- **Resource & runaway containment.** Each worker has a heap cap (`maxOldGenerationSizeMb`, default
+ 256). An OOM terminates the worker, not the host. A runaway (even an infinite synchronous loop)
+ can be force-terminated; a crash rejects its in-flight calls and the host survives.
+
+## What the sandbox does NOT guarantee
+
+> A `worker_thread` is a separate V8 context **in the same OS process, under the same user**. It is
+> not an OS-level sandbox.
+
+A worker still has access to Node built-ins — `require('fs')`, `process`, network sockets — and runs
+as the same uid as OpenWA. The sandbox therefore does **not**, by itself, stop a malicious plugin
+from reading files the OpenWA process can read or making outbound network connections. It protects
+the *integrity* of the host (no host-object compromise, contained faults, mediated capabilities) — not
+the *confidentiality* of the host filesystem against deliberate Node-builtin abuse.
+
+For genuinely untrusted, third-party plugins, combine the sandbox with **OS-level containment**:
+
+- **Run OpenWA in its container** (the shipped Docker image already runs read-only rootfs, non-root,
+ and `cap_drop: ALL`), which bounds what any plugin's `fs`/network access can reach.
+- Until a marketplace exists, the standing guidance remains: **install only plugins you trust.**
+
+A stronger isolation variant (child process with Node's permission model, or an `isolated-vm`) is a
+possible future enhancement for maximum-hostility deployments; the transport is already abstracted
+behind a channel interface so it can slot in without touching plugin code.
+
+## What changes for plugin authors
+
+Sandboxed plugins keep the same `IPlugin` shape (`onLoad`/`onEnable`/`onDisable`/`onUnload`,
+`ctx.messages`, `ctx.engine`, `ctx.storage`, `ctx.registerHook`), with these rules:
+
+1. **Capability calls are remote.** They were already `async`; they now genuinely cross a thread
+ boundary. Nothing to change in usage.
+2. **Only serializable data crosses.** Hook payloads and capability args/results must be
+ structured-clone-safe — plain objects, arrays, primitives, `Date`, typed arrays. **No functions,
+ no class instances with methods, no live references.**
+3. **No ambient host access.** `require('fs')`/`process` etc. still exist in the worker but must not
+ be relied on as a capability — anything the plugin legitimately needs should be a declared
+ capability, and OS containment may block direct access.
+4. **Declare your permissions.** A capability call is denied unless the manifest declares it
+ (`messages:send`, `engine:read`). See [19 — Plugin Architecture](./19-plugin-architecture.md).
+
+This is a **breaking change for third-party plugin authoring** and ships in a minor release. Built-in
+plugins are unaffected (they remain in-process).
+
+## Configuration
+
+| Env / constant | Default | Purpose |
+|----------------|---------|---------|
+| `maxOldGenerationSizeMb` (worker) | 256 | per-plugin heap cap; OOM kills the worker, not the host |
+| hook handler timeout | 5000 ms | budget before a sandboxed hook handler is skipped |
diff --git a/package-lock.json b/package-lock.json
index 78f53af24..be81ff65d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -26,6 +26,7 @@
"@nestjs/throttler": "^6.5.0",
"@nestjs/typeorm": "^11.0.2",
"@whiskeysockets/baileys": "6.7.23",
+ "adm-zip": "^0.5.17",
"archiver": "^8.0.0",
"bullmq": "^5.79.1",
"class-transformer": "^0.5.1",
@@ -51,10 +52,12 @@
"@nestjs/cli": "^11.0.23",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.1.27",
+ "@types/adm-zip": "^0.5.8",
"@types/archiver": "^8.0.0",
"@types/dockerode": "^4.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
+ "@types/multer": "^2.1.0",
"@types/node": "^26.0.0",
"@types/qrcode": "^1.5.5",
"@types/supertest": "^6.0.2",
@@ -762,6 +765,7 @@
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.0",
"@babel/generator": "^7.29.0",
@@ -1267,6 +1271,7 @@
"resolved": "https://registry.npmjs.org/@bull-board/api/-/api-8.0.1.tgz",
"integrity": "sha512-7FELJHRQPtjH9+r/DUArr4pDVU8r1yeDS9azQUzFtIbsUT5xGjyg5R1RB0I/RfwFfK5bqho/4cpzxJ/UnQjSKA==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"redis-info": "^3.1.0"
},
@@ -1305,6 +1310,7 @@
"resolved": "https://registry.npmjs.org/@bull-board/ui/-/ui-8.0.1.tgz",
"integrity": "sha512-gKEGSD8dlUoWFGJJ4I4Q5bDtfB7yJwGfpgA2DVn1G1TzlUSN5n4fzzcGpLf5fS+QhR7tB/niydUiFRQ2zrjVrQ==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@bull-board/api": "8.0.1"
}
@@ -1342,6 +1348,7 @@
"resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz",
"integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@keyv/serialize": "^1.1.1"
}
@@ -1672,6 +1679,7 @@
"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz",
"integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==",
"license": "Apache-2.0",
+ "peer": true,
"dependencies": {
"@grpc/proto-loader": "^0.8.0",
"@js-sdsl/ordered-map": "^4.4.2"
@@ -1703,6 +1711,7 @@
"resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz",
"integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==",
"license": "Apache-2.0",
+ "peer": true,
"dependencies": {
"lodash.camelcase": "^4.3.0",
"long": "^5.0.0",
@@ -1802,7 +1811,6 @@
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=18"
}
@@ -1819,7 +1827,6 @@
"os": [
"darwin"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -1842,7 +1849,6 @@
"os": [
"darwin"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -1862,7 +1868,6 @@
"os": [
"freebsd"
],
- "peer": true,
"dependencies": {
"@img/sharp-wasm32": "0.35.1"
},
@@ -1885,7 +1890,6 @@
"os": [
"darwin"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1902,7 +1906,6 @@
"os": [
"darwin"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1919,7 +1922,6 @@
"os": [
"linux"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1936,7 +1938,6 @@
"os": [
"linux"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1953,7 +1954,6 @@
"os": [
"linux"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1970,7 +1970,6 @@
"os": [
"linux"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1987,7 +1986,6 @@
"os": [
"linux"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -2004,7 +2002,6 @@
"os": [
"linux"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -2021,7 +2018,6 @@
"os": [
"linux"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -2038,7 +2034,6 @@
"os": [
"linux"
],
- "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -2055,7 +2050,6 @@
"os": [
"linux"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2078,7 +2072,6 @@
"os": [
"linux"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2101,7 +2094,6 @@
"os": [
"linux"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2124,7 +2116,6 @@
"os": [
"linux"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2147,7 +2138,6 @@
"os": [
"linux"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2170,7 +2160,6 @@
"os": [
"linux"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2193,7 +2182,6 @@
"os": [
"linux"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2216,7 +2204,6 @@
"os": [
"linux"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2233,7 +2220,6 @@
"integrity": "sha512-PCQUoQdZyE8tp3HpbevuihfUmgSP4qWI0FGEPWoeXqaS+cUrFfemabHQiebUmUmlUhCuNnQMxGrQ+CPqK4hnxg==",
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
"optional": true,
- "peer": true,
"dependencies": {
"@emnapi/runtime": "^1.11.0"
},
@@ -2253,7 +2239,6 @@
],
"license": "Apache-2.0",
"optional": true,
- "peer": true,
"dependencies": {
"@img/sharp-wasm32": "0.35.1"
},
@@ -2276,7 +2261,6 @@
"os": [
"win32"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -2296,7 +2280,6 @@
"os": [
"win32"
],
- "peer": true,
"engines": {
"node": "^20.9.0"
},
@@ -2316,7 +2299,6 @@
"os": [
"win32"
],
- "peer": true,
"engines": {
"node": ">=20.9.0"
},
@@ -3518,6 +3500,7 @@
"resolved": "https://registry.npmjs.org/@nestjs/bull-shared/-/bull-shared-11.0.4.tgz",
"integrity": "sha512-VBJcDHSAzxQnpcDfA0kt9MTGUD1XZzfByV70su0W0eDCQ9aqIEBlzWRW21tv9FG9dIut22ysgDidshdjlnczLw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"tslib": "2.8.1"
},
@@ -3672,6 +3655,7 @@
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.27.tgz",
"integrity": "sha512-kEGSzqM2lWr4whh4Ubflw+oPZSEzxvRMu9WL+LveZploJWTjec5bBlCiRVlVzTPg2kIwBiLwWSvCCW7Wnin1gg==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"file-type": "21.3.4",
"iterare": "1.2.1",
@@ -3718,6 +3702,7 @@
"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.27.tgz",
"integrity": "sha512-K6DX7hcqmZdeXkv7tsPakKBRCgqL19a4mtbX4FluY0hWtFdtPKp6lbe+lb8gWPfvLdbOWr/CPScn7BSjBX+Ecg==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"fast-safe-stringify": "2.1.1",
"iterare": "1.2.1",
@@ -3777,6 +3762,7 @@
"resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.27.tgz",
"integrity": "sha512-0ZFhz6H6EdGh4xQVbUNwjoAwBuz73P7FvUAl67h9CTdMqQlJDaQYJApBv8pKfVZ1fGjMCbl0m9DcC6pXaZPWSQ==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"cors": "2.8.6",
"express": "5.2.1",
@@ -3798,6 +3784,7 @@
"resolved": "https://registry.npmjs.org/@nestjs/platform-socket.io/-/platform-socket.io-11.1.27.tgz",
"integrity": "sha512-xgpLzaIDGOCC6xOAtHnRAz8sqieFgGxxu3MN5ID026Jt6oeL3efp29N5QHhPr7UlqBfy/Jd02uj0POkZq6Au3Q==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"socket.io": "4.8.3",
"tslib": "2.8.1"
@@ -4010,6 +3997,7 @@
"resolved": "https://registry.npmjs.org/@nestjs/typeorm/-/typeorm-11.0.2.tgz",
"integrity": "sha512-KQsmOKqIbfq+I1fe88rDq8QNfTU3C4b8MA2qOImhvIbIDOStcC+m+z2itf7vnWGQK0LZBFjWlYdRBID12qgZeg==",
"license": "MIT",
+ "peer": true,
"peerDependencies": {
"@nestjs/common": "^10.0.0 || ^11.0.0",
"@nestjs/core": "^10.0.0 || ^11.0.0",
@@ -4468,6 +4456,16 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@types/adm-zip": {
+ "version": "0.5.8",
+ "resolved": "https://registry.npmjs.org/@types/adm-zip/-/adm-zip-0.5.8.tgz",
+ "integrity": "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/archiver": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/@types/archiver/-/archiver-8.0.0.tgz",
@@ -4590,6 +4588,7 @@
"integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@types/estree": "*",
"@types/json-schema": "*"
@@ -4704,11 +4703,22 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/multer": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/multer/-/multer-2.1.0.tgz",
+ "integrity": "sha512-zYZb0+nJhOHtPpGDb3vqPjwpdeGlGC157VpkqNQL+UU2qwoacoQ7MpsAmUptI/0Oa127X32JzWDqQVEXp2RcIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/express": "*"
+ }
+ },
"node_modules/@types/node": {
"version": "26.0.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.0.0.tgz",
"integrity": "sha512-vf2YFi1iY9lHGwNJMs01biZFbKJkrZR1T6/MlzjhJLPdntOHLhTrDSnSVcdtvjihi4VQNlrFRIxLsDBlQpAipA==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"undici-types": "~8.3.0"
}
@@ -4934,6 +4944,7 @@
"integrity": "sha512-PJ5vePq5/ognBbrIcoC5+SHO5dfpeLPzP9FpLkzWrguoYQEeeSjlJpVwOpo1JRSTEi7dRcwNy4h4dzV70PqHcg==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.61.1",
"@typescript-eslint/types": "8.61.1",
@@ -5685,6 +5696,7 @@
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"devOptional": true,
"license": "MIT",
+ "peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -5728,6 +5740,15 @@
"node": ">=0.4.0"
}
},
+ "node_modules/adm-zip": {
+ "version": "0.5.17",
+ "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.17.tgz",
+ "integrity": "sha512-+Ut8d9LLqwEvHHJl1+PIHqoyDxFgVN847JTVM3Izi3xHDWPE4UtzzXysMZQs64DMcrJfBeS/uoEP4AD3HQHnQQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0"
+ }
+ },
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@@ -5773,6 +5794,7 @@
"integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
@@ -6370,6 +6392,7 @@
"resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.8.2.tgz",
"integrity": "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ==",
"license": "Apache-2.0",
+ "peer": true,
"peerDependencies": {
"bare-abort-controller": "*"
},
@@ -6659,6 +6682,7 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.10.12",
"caniuse-lite": "^1.0.30001782",
@@ -6749,6 +6773,7 @@
"resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.79.1.tgz",
"integrity": "sha512-cteoHRr1FGOTUgzFrnMyBNGtQhNeVR8Ej6nImNSHQDJi4tj6GMD0p9ZG65ZsTnvR9RVf18dhRxWu4kFl634QGA==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"cron-parser": "4.9.0",
"ioredis": "5.10.1",
@@ -7066,6 +7091,7 @@
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"readdirp": "^4.0.1"
},
@@ -7135,13 +7161,15 @@
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/class-transformer/-/class-transformer-0.5.1.tgz",
"integrity": "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==",
- "license": "MIT"
+ "license": "MIT",
+ "peer": true
},
"node_modules/class-validator": {
"version": "0.15.1",
"resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.15.1.tgz",
"integrity": "sha512-LqoS80HBBSCVhz/3KloUly0ovokxpdOLR++Al3J3+dHXWt9sTKlKd4eYtoxhxyUjoe5+UcIM+5k9MIxyBWnRTw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@types/validator": "^13.15.3",
"libphonenumber-js": "^1.11.1",
@@ -7994,7 +8022,8 @@
"version": "0.0.1581282",
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1581282.tgz",
"integrity": "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ==",
- "license": "BSD-3-Clause"
+ "license": "BSD-3-Clause",
+ "peer": true
},
"node_modules/dezalgo": {
"version": "1.0.4",
@@ -8492,6 +8521,7 @@
"integrity": "sha512-1y+7C+vi12bUK1IpZeaV3gsH9fHLBmPvYmPx42pvT/E9yG0IC8g3PUZZgp0+JLJl7ZDK0flc2gc+Aw9dpCvIsQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"workspaces": [
"packages/*"
],
@@ -8551,6 +8581,7 @@
"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==",
"dev": true,
"license": "MIT",
+ "peer": true,
"bin": {
"eslint-config-prettier": "bin/cli.js"
},
@@ -10049,6 +10080,7 @@
"resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.11.1.tgz",
"integrity": "sha512-ehuGcf94bQXhfagULNXrJdfnWO38v070jxSx/qE87Kjzmu2fU7ro5EFAb+OPituLqgfyuQaym5DlrNydW2sJ9A==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@ioredis/commands": "1.10.0",
"cluster-key-slot": "1.1.1",
@@ -10321,6 +10353,7 @@
"integrity": "sha512-Yi1jqNC/Oq0N4hBgNH/YvBpP1P57QqundgytzYqy3yqAa7NZPNjSoi4SGbRAXDMdBzNE6xBCi5U7RgfrvMEUVQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@jest/core": "30.4.2",
"@jest/types": "30.4.1",
@@ -12285,7 +12318,6 @@
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz",
"integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">= 6"
}
@@ -12674,6 +12706,7 @@
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
"integrity": "sha512-8wih1vVIBMxoUM2oB4soJsD9tDnDpLv4OXBJ+EJzFsvycD+lfyIreC2gGHq78f8jbLLt+bvlPTFdFZfJkOuzAA==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"pg-connection-string": "^2.14.0",
"pg-pool": "^3.14.0",
@@ -13003,6 +13036,7 @@
"integrity": "sha512-N2MylSdi48+5N/6S5j+maeHbUSIzzZ5uOcX5Hm4QpV8Dkb1HFjfAKTKX6yNPJQD9AhcT3ifHNB66tWTTJDi11Q==",
"dev": true,
"license": "MIT",
+ "peer": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
@@ -13718,7 +13752,8 @@
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
- "license": "Apache-2.0"
+ "license": "Apache-2.0",
+ "peer": true
},
"node_modules/require-directory": {
"version": "2.1.1",
@@ -13868,6 +13903,7 @@
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"license": "Apache-2.0",
+ "peer": true,
"dependencies": {
"tslib": "^2.1.0"
}
@@ -14037,7 +14073,6 @@
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.1.tgz",
"integrity": "sha512-lW979AMi+ESidzMv/Lnv+F9bknzLyxLqFI05Sm433vOeRcltgxQmXpnfOOFIAlKtwXU/ksupm2srQoFCkR214g==",
"license": "Apache-2.0",
- "peer": true,
"dependencies": {
"@img/colour": "^1.1.0",
"detect-libc": "^2.1.2",
@@ -14082,7 +14117,6 @@
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz",
"integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==",
"license": "ISC",
- "peer": true,
"bin": {
"semver": "bin/semver.js"
},
@@ -14470,6 +14504,7 @@
"integrity": "sha512-GGIyOiFaG+TUra3JIfkI/zGP8yZYLPQ0pl1bH+ODjiX57sPhrLU5sQJn1y9bDKZUFYkX1crlrPfSYt0BKKdkog==",
"hasInstallScript": true,
"license": "BSD-3-Clause",
+ "peer": true,
"dependencies": {
"bindings": "^1.5.0",
"node-addon-api": "^7.0.0",
@@ -14995,6 +15030,7 @@
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
@@ -15348,6 +15384,7 @@
"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
"devOptional": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@cspotcode/source-map-support": "^0.8.0",
"@tsconfig/node10": "^1.0.7",
@@ -15532,6 +15569,7 @@
"resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.3.30.tgz",
"integrity": "sha512-8T35PzjefOdqc2ZR9mwLQj0pUGp6lQhMbK2EvVMwJVJWlaoHm0v/Q6dThNOZkFchD+0yMg8gwjKM28ePiLSXSQ==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@sqltools/formatter": "^1.2.5",
"ansis": "^4.2.0",
@@ -15751,6 +15789,7 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
+ "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -16091,6 +16130,7 @@
"integrity": "sha512-wGN3qcrBQIFmQ/c0AiOAQBvrZ5lmY8vbbMv4Mxfgzqd/B6+9pXtLo73WuS1dSGXM5QYY3hZnIbvx+K1xxe6FyA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@types/eslint-scope": "^3.7.7",
"@types/estree": "^1.0.8",
@@ -16159,6 +16199,7 @@
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
diff --git a/package.json b/package.json
index f5d691aca..4c9a27301 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "openwa",
- "version": "0.5.1",
+ "version": "0.6.0",
"description": "Open Source WhatsApp API Gateway - Free, Self-Hosted HTTP API for WhatsApp",
"author": "Yudhi Armyndharis & OpenWA Contributors",
"private": true,
@@ -63,6 +63,7 @@
"@nestjs/throttler": "^6.5.0",
"@nestjs/typeorm": "^11.0.2",
"@whiskeysockets/baileys": "6.7.23",
+ "adm-zip": "^0.5.17",
"archiver": "^8.0.0",
"bullmq": "^5.79.1",
"class-transformer": "^0.5.1",
@@ -88,10 +89,12 @@
"@nestjs/cli": "^11.0.23",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.1.27",
+ "@types/adm-zip": "^0.5.8",
"@types/archiver": "^8.0.0",
"@types/dockerode": "^4.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
+ "@types/multer": "^2.1.0",
"@types/node": "^26.0.0",
"@types/qrcode": "^1.5.5",
"@types/supertest": "^6.0.2",
diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
new file mode 100644
index 000000000..5395a5575
--- /dev/null
+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
@@ -0,0 +1,99 @@
+import { ConfigService } from '@nestjs/config';
+import { ModuleRef } from '@nestjs/core';
+import { PluginLoaderService } from './plugin-loader.service';
+import { PluginStorageService } from './plugin-storage.service';
+import { HookManager } from '../hooks';
+import { IPlugin, PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
+import { PluginWorkerHost } from './sandbox/plugin-worker-host';
+
+type FakeHost = { load: jest.Mock; runLifecycle: jest.Mock; terminate: jest.Mock };
+
+/** Loader that returns fake worker hosts so routing is testable without spawning a real OS thread. */
+class TestableLoader extends PluginLoaderService {
+ readonly hosts: FakeHost[] = [];
+ protected createSandboxHost(): PluginWorkerHost {
+ const host: FakeHost = {
+ load: jest.fn().mockResolvedValue(undefined),
+ runLifecycle: jest.fn().mockResolvedValue(undefined),
+ terminate: jest.fn().mockResolvedValue(undefined),
+ };
+ this.hosts.push(host);
+ return host as unknown as PluginWorkerHost;
+ }
+}
+
+function makeLoader(): TestableLoader {
+ const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
+ const pluginStorage = {
+ createPluginStorage: jest.fn().mockReturnValue({}),
+ getPluginConfig: jest.fn().mockReturnValue(undefined),
+ getPluginEntry: jest.fn().mockReturnValue(undefined),
+ setPluginEntry: jest.fn(),
+ setPluginStatus: jest.fn(),
+ } as unknown as PluginStorageService;
+ const moduleRef = { get: jest.fn() } as unknown as ModuleRef;
+ return new TestableLoader(configService, new HookManager(), pluginStorage, moduleRef);
+}
+
+const manifest = (): PluginManifest => ({
+ id: 'p1',
+ name: 'P1',
+ version: '1.0.0',
+ type: PluginType.EXTENSION,
+ main: 'index.js',
+});
+
+function seed(loader: TestableLoader, opts: { builtIn: boolean; instance: IPlugin | null }): void {
+ const plugin: PluginInstance = {
+ manifest: manifest(),
+ status: PluginStatus.INSTALLED,
+ config: {},
+ instance: opts.instance,
+ builtIn: opts.builtIn,
+ };
+ (loader as unknown as { plugins: Map<string, PluginInstance> }).plugins.set('p1', plugin);
+}
+
+const pluginOf = (loader: TestableLoader): PluginInstance =>
+ (loader as unknown as { plugins: Map<string, PluginInstance> }).plugins.get('p1') as PluginInstance;
+
+describe('PluginLoaderService — sandbox tier routing', () => {
+ it('enables an untrusted plugin in a sandbox worker, not in-process', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+
+ await loader.enablePlugin('p1');
+
+ expect(loader.hosts).toHaveLength(1);
+ expect(loader.hosts[0].load).toHaveBeenCalled();
+ expect(loader.hosts[0].runLifecycle).toHaveBeenCalledWith('onEnable');
+ const plugin = pluginOf(loader);
+ expect(plugin.status).toBe(PluginStatus.ENABLED);
+ expect(plugin.instance).toBeNull(); // the instance lives in the worker, never in-process
+ });
+
+ it('disables an untrusted plugin by running onDisable then terminating the worker', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ await loader.enablePlugin('p1');
+ const host = loader.hosts[0];
+
+ await loader.disablePlugin('p1');
+
+ expect(host.runLifecycle).toHaveBeenCalledWith('onDisable');
+ expect(host.terminate).toHaveBeenCalled();
+ expect(pluginOf(loader).status).toBe(PluginStatus.DISABLED);
+ });
+
+ it('enables a built-in plugin in-process (no sandbox worker spawned)', async () => {
+ const loader = makeLoader();
+ const onEnable = jest.fn().mockResolvedValue(undefined);
+ seed(loader, { builtIn: true, instance: { onEnable } });
+
+ await loader.enablePlugin('p1');
+
+ expect(loader.hosts).toHaveLength(0);
+ expect(onEnable).toHaveBeenCalled();
+ expect(pluginOf(loader).status).toBe(PluginStatus.ENABLED);
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index a625aebde..5450a4010 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -151,3 +151,98 @@ describe('PluginLoaderService — enable/config persistence', () => {
expect(loader2.getPlugin('persist-test')?.config).toEqual({ apiKey: 'operator-secret' });
});
});
+
+describe('PluginLoaderService — engine mutual exclusion', () => {
+ let tmpDir: string;
+ let storage: PluginStorageService;
+
+ const engineManifest = (id: string): PluginManifest => ({
+ id,
+ name: id,
+ version: '1.0.0',
+ type: PluginType.ENGINE,
+ main: 'index.js',
+ });
+
+ const makeLoader = (activeEngine: string): PluginLoaderService => {
+ const config = {
+ get: (k: string) => (k === 'engine.type' ? activeEngine : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ return new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);
+ };
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-eng-'));
+ storage = new PluginStorageService({
+ get: (k: string) => (k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService);
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ it('rejects enabling an engine that is not the configured active engine', async () => {
+ const loader = makeLoader('whatsapp-web.js');
+ loader.registerBuiltInPlugin(engineManifest('baileys'), {});
+
+ await expect(loader.enablePlugin('baileys')).rejects.toThrow(/active engine/i);
+ // Rejected up front — the plugin stays INSTALLED (not flipped to ERROR).
+ expect(loader.getPlugin('baileys')?.status).toBe(PluginStatus.INSTALLED);
+ });
+
+ it('allows enabling the configured active engine', async () => {
+ const loader = makeLoader('baileys');
+ loader.registerBuiltInPlugin(engineManifest('baileys'), {});
+
+ await loader.enablePlugin('baileys');
+ expect(loader.getPlugin('baileys')?.status).toBe(PluginStatus.ENABLED);
+ });
+});
+
+describe('PluginLoaderService — uninstall', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let storage: PluginStorageService;
+ let loader: PluginLoaderService;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-uninst-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ storage = new PluginStorageService(config);
+ loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const writeUserPlugin = (id: string): string => {
+ const dir = path.join(pluginsDir, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'manifest.json'),
+ JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
+ );
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+ return dir;
+ };
+
+ it('removes the plugin directory, registry entry, and runtime instance', async () => {
+ const dir = writeUserPlugin('user-plg');
+ loader.loadPlugin(dir);
+ expect(storage.getPluginEntry('user-plg')).toBeDefined();
+
+ await loader.uninstallPlugin('user-plg');
+
+ expect(fs.existsSync(dir)).toBe(false);
+ expect(storage.getPluginEntry('user-plg')).toBeUndefined();
+ expect(loader.getPlugin('user-plg')).toBeUndefined();
+ });
+
+ it('refuses to uninstall a built-in plugin', async () => {
+ loader.registerBuiltInPlugin(
+ { id: 'core-engine', name: 'Core', version: '1.0.0', type: PluginType.ENGINE, main: 'x.js' },
+ {},
+ );
+ await expect(loader.uninstallPlugin('core-engine')).rejects.toThrow(/built-in/i);
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index f9988dc38..194b39475 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -4,7 +4,7 @@ import { ModuleRef } from '@nestjs/core';
import * as fs from 'fs';
import * as path from 'path';
import { createLogger } from '../../common/services/logger.service';
-import { HookManager } from '../hooks';
+import { HookManager, HookEvent } from '../hooks';
import {
PluginCapabilityError,
PluginCapabilityPermission,
@@ -19,10 +19,19 @@ import {
PluginLogger,
} from './plugin.interfaces';
import { PluginStorageService } from './plugin-storage.service';
+import { PluginWorkerHost } from './sandbox/plugin-worker-host';
+import { WorkerThreadChannel } from './sandbox/worker-thread-channel';
+import { dispatchCapabilityVerb } from './sandbox/capability-router';
+import { PluginLogLevel } from './sandbox/protocol';
import type { MessageService } from '../../modules/message/message.service';
import type { SessionService } from '../../modules/session/session.service';
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+/** Default per-plugin heap cap for the sandbox worker; an OOM terminates the worker, not the host. */
+const SANDBOX_MAX_OLD_GEN_MB = 256;
+/** Time budget for a sandboxed plugin's hook handler before the chain proceeds without it. */
+const SANDBOX_HOOK_TIMEOUT_MS = 5000;
+
/**
* Resolve a plugin's `main` entry to an absolute path, asserting it stays inside
* <pluginsDir>/<pluginId>. `main` comes from a user-supplied manifest, so a
@@ -41,6 +50,8 @@ export function resolvePluginMainPath(pluginsDir: string, pluginId: string, main
export class PluginLoaderService implements OnModuleInit {
private readonly logger = createLogger('PluginLoaderService');
private readonly plugins = new Map<string, PluginInstance>();
+ // Live worker host per enabled sandboxed (untrusted) plugin. Built-ins are not in here.
+ private readonly sandboxHosts = new Map<string, PluginWorkerHost>();
private readonly pluginsDir: string;
constructor(
@@ -131,6 +142,7 @@ export class PluginLoaderService implements OnModuleInit {
config: storedConfig,
instance: null,
loadedAt: new Date(),
+ builtIn: false,
};
this.plugins.set(manifest.id, pluginInstance);
@@ -185,31 +197,23 @@ export class PluginLoaderService implements OnModuleInit {
return; // Already enabled
}
- try {
- // Create plugin context
- const context = this.createPluginContext(plugin);
-
- // Load the plugin instance if not already loaded
- if (!plugin.instance) {
- // Containment guard: reject a manifest.main that escapes the plugin dir.
- const mainPath = resolvePluginMainPath(this.pluginsDir, pluginId, plugin.manifest.main);
- // Dynamic require for user plugins
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const pluginModule = require(mainPath) as { default?: new () => IPlugin };
- if (pluginModule.default) {
- plugin.instance = new pluginModule.default();
- } else {
- throw new Error(`Plugin ${pluginId} does not export a default class`);
- }
- }
-
- // Call lifecycle hooks
- if (plugin.instance.onLoad) {
- await plugin.instance.onLoad(context);
+ // Engines are mutually exclusive and pinned to the deployment's engine.type config (the factory
+ // reads that, not plugin status). Enabling a second engine at runtime would show two "active"
+ // engines and desync the factory, so reject anything but the configured active engine.
+ if (plugin.manifest.type === PluginType.ENGINE) {
+ const activeEngine = this.configService.get<string>('engine.type') ?? 'whatsapp-web.js';
+ if (pluginId !== activeEngine) {
+ throw new Error(
+ `Engine "${pluginId}" is not the active engine ("${activeEngine}"). Set engine.type and restart to switch engines.`,
+ );
}
+ }
- if (plugin.instance.onEnable) {
- await plugin.instance.onEnable(context);
+ try {
+ if (plugin.builtIn === false) {
+ await this.enableSandboxed(pluginId, plugin);
+ } else {
+ await this.enableInProcess(pluginId, plugin);
}
plugin.status = PluginStatus.ENABLED;
@@ -244,10 +248,16 @@ export class PluginLoaderService implements OnModuleInit {
}
try {
- const context = this.createPluginContext(plugin);
-
- if (plugin.instance?.onDisable) {
- await plugin.instance.onDisable(context);
+ const host = this.sandboxHosts.get(pluginId);
+ if (host) {
+ await host.runLifecycle('onDisable');
+ await host.terminate();
+ this.sandboxHosts.delete(pluginId);
+ } else {
+ const context = this.createPluginContext(plugin);
+ if (plugin.instance?.onDisable) {
+ await plugin.instance.onDisable(context);
+ }
}
// Unregister all hooks for this plugin
@@ -293,6 +303,41 @@ export class PluginLoaderService implements OnModuleInit {
});
}
+ /** Absolute path of the directory user plugins are loaded from (used by install/uninstall). */
+ getPluginsDir(): string {
+ return this.pluginsDir;
+ }
+
+ /** Whether a plugin is a first-party built-in (engine / bundled extension) vs an installed user plugin. */
+ isBuiltIn(pluginId: string): boolean {
+ return this.pluginStorage.getPluginEntry(pluginId)?.builtIn ?? false;
+ }
+
+ /**
+ * Fully remove an installed user plugin: disable + unload from the runtime, drop its persisted
+ * registry entry, and delete its directory from disk. Built-ins (engines, bundled extensions) are
+ * registered programmatically with no on-disk dir and must never be removable.
+ */
+ async uninstallPlugin(pluginId: string): Promise<void> {
+ if (this.pluginStorage.getPluginEntry(pluginId)?.builtIn) {
+ throw new Error(`Cannot uninstall built-in plugin ${pluginId}`);
+ }
+
+ if (this.plugins.has(pluginId)) {
+ await this.unloadPlugin(pluginId);
+ }
+ this.pluginStorage.deletePluginEntry(pluginId);
+
+ // Delete the plugin's directory, guarding against a traversal id escaping the plugins dir.
+ const base = path.resolve(this.pluginsDir);
+ const dir = path.resolve(base, pluginId);
+ if (dir !== base && dir.startsWith(base + path.sep) && fs.existsSync(dir)) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+
+ this.logger.log(`Plugin uninstalled: ${pluginId}`, { pluginId, action: 'plugin_uninstalled' });
+ }
+
updatePluginConfig(pluginId: string, config: Record<string, unknown>): void {
const plugin = this.plugins.get(pluginId);
if (!plugin) {
@@ -381,6 +426,115 @@ export class PluginLoaderService implements OnModuleInit {
return this.resolveEngine(manifest, sessionId);
}
+ /**
+ * Build a worker host for a sandboxed (untrusted) plugin. Overridable so tests can inject a fake
+ * instead of spawning a real OS thread. Production loads the compiled worker bootstrap from dist.
+ */
+ protected createSandboxHost(
+ capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,
+ onHookSubscribe?: (event: string, priority?: number) => void,
+ onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,
+ ): PluginWorkerHost {
+ const workerEntry = path.join(__dirname, 'sandbox', 'worker-bootstrap.js');
+ return new PluginWorkerHost(
+ new WorkerThreadChannel({ workerEntry, maxOldGenerationSizeMb: SANDBOX_MAX_OLD_GEN_MB }),
+ capDispatcher,
+ onHookSubscribe,
+ onLog,
+ );
+ }
+
+ /** Built-in (trusted) enable: require + run the lifecycle in-process with the live capability context. */
+ private async enableInProcess(pluginId: string, plugin: PluginInstance): Promise<void> {
+ const context = this.createPluginContext(plugin);
+
+ if (!plugin.instance) {
+ // Containment guard: reject a manifest.main that escapes the plugin dir.
+ const mainPath = resolvePluginMainPath(this.pluginsDir, pluginId, plugin.manifest.main);
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const pluginModule = require(mainPath) as { default?: new () => IPlugin };
+ if (pluginModule.default) {
+ plugin.instance = new pluginModule.default();
+ } else {
+ throw new Error(`Plugin ${pluginId} does not export a default class`);
+ }
+ }
+
+ if (plugin.instance.onLoad) {
+ await plugin.instance.onLoad(context);
+ }
+ if (plugin.instance.onEnable) {
+ await plugin.instance.onEnable(context);
+ }
+ }
+
+ /**
+ * Untrusted enable: load the plugin in an isolated worker and drive its lifecycle there. Capability
+ * calls and hooks round-trip to the host, which enforces permission + session scope. A failure
+ * tears the worker back down.
+ */
+ private async enableSandboxed(pluginId: string, plugin: PluginInstance): Promise<void> {
+ // Containment guard: reject a manifest.main that escapes the plugin dir.
+ const mainPath = resolvePluginMainPath(this.pluginsDir, pluginId, plugin.manifest.main);
+ // The capability dispatcher runs a worker request through the SAME context an in-process plugin
+ // gets, so permission + session-scope checks (assertPermission / assertSessionAllowed) apply
+ // identically. The worker can only ask; the host is the gatekeeper.
+ const context = this.createPluginContext(plugin);
+
+ // When the worker subscribes to a hook, register a shim with the hook manager that dispatches the
+ // event into the worker (time-bounded, so a wedged plugin can't stall the chain). The shim looks
+ // the host up at fire time, so disabling the plugin (which removes it + unregisters hooks) stops it.
+ const onHookSubscribe = (event: string, priority?: number): void => {
+ this.hookManager.register(
+ pluginId,
+ event as HookEvent,
+ async hookCtx => {
+ const liveHost = this.sandboxHosts.get(pluginId);
+ if (!liveHost) return { continue: true };
+ return liveHost
+ .dispatchHook({
+ event,
+ data: hookCtx.data,
+ sessionId: hookCtx.sessionId,
+ source: hookCtx.source,
+ timeoutMs: SANDBOX_HOOK_TIMEOUT_MS,
+ onTimeout: () =>
+ this.logger.warn(`Sandboxed plugin ${pluginId} hook '${event}' timed out`, {
+ pluginId,
+ event,
+ action: 'sandbox_hook_timeout',
+ }),
+ })
+ .then(result => ({ continue: result.continue, data: result.data }));
+ },
+ priority,
+ );
+ };
+
+ // Route the worker plugin's ctx.logger.* calls to the same per-plugin logger an in-process plugin
+ // uses, so sandboxed plugins log identically (prefixed + structured) instead of bare stdout.
+ const onLog = (level: PluginLogLevel, message: string, meta?: Record<string, unknown>): void => {
+ if (level === 'error') context.logger.error(message, undefined, meta);
+ else context.logger[level](message, meta);
+ };
+
+ const host = this.createSandboxHost(
+ (verb, args) => dispatchCapabilityVerb(context, verb, args),
+ onHookSubscribe,
+ onLog,
+ );
+ this.sandboxHosts.set(pluginId, host);
+ try {
+ await host.load(mainPath, { pluginId, config: plugin.config });
+ await host.runLifecycle('onLoad');
+ await host.runLifecycle('onEnable');
+ } catch (error) {
+ this.sandboxHosts.delete(pluginId);
+ await host.terminate().catch(() => undefined);
+ throw error;
+ }
+ }
+
private createPluginContext(plugin: PluginInstance): PluginContext {
const pluginLogger: PluginLogger = {
log: (message, meta) =>
@@ -477,6 +631,7 @@ export class PluginLoaderService implements OnModuleInit {
config: effectiveConfig,
instance,
loadedAt: new Date(),
+ builtIn: true,
};
this.plugins.set(manifest.id, pluginInstance);
diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.ts
index b4add6b79..bd25f75d8 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -220,6 +220,9 @@ export interface PluginInstance {
error?: string;
loadedAt?: Date;
enabledAt?: Date;
+ // First-party built-ins (engines, bundled extensions) run in-process; plugins loaded from the
+ // plugins directory are untrusted and run sandboxed in a worker. `false` => sandboxed.
+ builtIn?: boolean;
}
// ============================================================================
diff --git a/src/core/plugins/sandbox/capability-router.spec.ts b/src/core/plugins/sandbox/capability-router.spec.ts
new file mode 100644
index 000000000..867a97d00
--- /dev/null
+++ b/src/core/plugins/sandbox/capability-router.spec.ts
@@ -0,0 +1,61 @@
+import { dispatchCapabilityVerb, CapabilityContext } from './capability-router';
+
+function makeContext() {
+ return {
+ messages: {
+ sendText: jest.fn().mockResolvedValue({ messageId: 'm1' }),
+ reply: jest.fn().mockResolvedValue({ messageId: 'm2' }),
+ },
+ engine: {
+ getGroupInfo: jest.fn().mockResolvedValue({ id: 'g' }),
+ getContacts: jest.fn().mockResolvedValue([]),
+ getContactById: jest.fn().mockResolvedValue(null),
+ checkNumberExists: jest.fn().mockResolvedValue(true),
+ getChats: jest.fn().mockResolvedValue([]),
+ },
+ storage: {
+ get: jest.fn().mockResolvedValue('v'),
+ set: jest.fn().mockResolvedValue(undefined),
+ delete: jest.fn().mockResolvedValue(undefined),
+ list: jest.fn().mockResolvedValue([]),
+ },
+ };
+}
+
+describe('dispatchCapabilityVerb', () => {
+ it('routes messages.sendText to the context with positional args', async () => {
+ const ctx = makeContext();
+ const out = await dispatchCapabilityVerb(ctx, 'messages.sendText', ['s', 'c', 'hi']);
+ expect(ctx.messages.sendText).toHaveBeenCalledWith('s', 'c', 'hi');
+ expect(out).toEqual({ messageId: 'm1' });
+ });
+
+ it('routes messages.reply', async () => {
+ const ctx = makeContext();
+ await dispatchCapabilityVerb(ctx, 'messages.reply', ['s', 'c', 'q', 'hi']);
+ expect(ctx.messages.reply).toHaveBeenCalledWith('s', 'c', 'q', 'hi');
+ });
+
+ it('routes engine.getGroupInfo', async () => {
+ const ctx = makeContext();
+ await dispatchCapabilityVerb(ctx, 'engine.getGroupInfo', ['s', 'g']);
+ expect(ctx.engine.getGroupInfo).toHaveBeenCalledWith('s', 'g');
+ });
+
+ it('routes storage.get and returns its value', async () => {
+ const ctx = makeContext();
+ const out = await dispatchCapabilityVerb(ctx, 'storage.get', ['k']);
+ expect(ctx.storage.get).toHaveBeenCalledWith('k');
+ expect(out).toBe('v');
+ });
+
+ it('rejects an unknown verb — only allowlisted capabilities are reachable', async () => {
+ const ctx = makeContext();
+ await expect(dispatchCapabilityVerb(ctx as unknown as CapabilityContext, 'process.exit', [0])).rejects.toThrow(
+ /unknown capability verb/i,
+ );
+ await expect(
+ dispatchCapabilityVerb(ctx as unknown as CapabilityContext, 'storage.constructor', []),
+ ).rejects.toThrow(/unknown capability verb/i);
+ });
+});
diff --git a/src/core/plugins/sandbox/capability-router.ts b/src/core/plugins/sandbox/capability-router.ts
new file mode 100644
index 000000000..84908bcbd
--- /dev/null
+++ b/src/core/plugins/sandbox/capability-router.ts
@@ -0,0 +1,47 @@
+import { PluginContext } from '../plugin.interfaces';
+
+/** The subset of the plugin context a sandboxed plugin reaches across the bridge. */
+export type CapabilityContext = Pick<PluginContext, 'messages' | 'engine' | 'storage'>;
+
+/**
+ * Dispatch a worker-initiated capability `verb` to the live, permission-enforcing context the loader
+ * built for this plugin. Allowlisted by design: only the verbs below are reachable, so a hostile
+ * worker cannot invoke an arbitrary method on the context. Args are positional, one per signature.
+ *
+ * Permission + session-scope checks are NOT here — they live inside the context's own verbs
+ * (assertPermission / assertSessionAllowed), so a sandboxed call is gated exactly like an in-process
+ * one. This router is purely the wire-to-method mapping.
+ */
+export async function dispatchCapabilityVerb(
+ context: CapabilityContext,
+ verb: string,
+ args: unknown[],
+): Promise<unknown> {
+ const s = (index: number): string => args[index] as string;
+ switch (verb) {
+ case 'messages.sendText':
+ return context.messages.sendText(s(0), s(1), s(2));
+ case 'messages.reply':
+ return context.messages.reply(s(0), s(1), s(2), s(3));
+ case 'engine.getGroupInfo':
+ return context.engine.getGroupInfo(s(0), s(1));
+ case 'engine.getContacts':
+ return context.engine.getContacts(s(0));
+ case 'engine.getContactById':
+ return context.engine.getContactById(s(0), s(1));
+ case 'engine.checkNumberExists':
+ return context.engine.checkNumberExists(s(0), s(1));
+ case 'engine.getChats':
+ return context.engine.getChats(s(0));
+ case 'storage.get':
+ return context.storage.get(s(0));
+ case 'storage.set':
+ return context.storage.set(s(0), args[1]);
+ case 'storage.delete':
+ return context.storage.delete(s(0));
+ case 'storage.list':
+ return context.storage.list(args[0] as string | undefined);
+ default:
+ throw new Error(`Unknown capability verb: ${verb}`);
+ }
+}
diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
new file mode 100644
index 000000000..e4ac9bff6
--- /dev/null
+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
@@ -0,0 +1,252 @@
+import { PluginWorkerHost } from './plugin-worker-host';
+import { PluginWorkerChannel, HostToWorkerMessage, WorkerToHostMessage } from './protocol';
+
+/** In-memory channel double: records what the host posts, lets the test push worker replies back. */
+class FakeChannel implements PluginWorkerChannel {
+ sent: HostToWorkerMessage[] = [];
+ terminated = false;
+ private onMsg?: (m: WorkerToHostMessage) => void;
+ private onExitCb?: (code: number) => void;
+
+ postMessage(message: HostToWorkerMessage): void {
+ this.sent.push(message);
+ }
+ onMessage(handler: (message: WorkerToHostMessage) => void): void {
+ this.onMsg = handler;
+ }
+ onExit(handler: (code: number) => void): void {
+ this.onExitCb = handler;
+ }
+ terminate(): Promise<void> {
+ this.terminated = true;
+ return Promise.resolve();
+ }
+
+ // test triggers
+ reply(message: WorkerToHostMessage): void {
+ this.onMsg?.(message);
+ }
+ crash(code = 1): void {
+ this.onExitCb?.(code);
+ }
+ last(): HostToWorkerMessage {
+ return this.sent[this.sent.length - 1];
+ }
+}
+
+const lastLifecycle = (ch: FakeChannel) => ch.last() as Extract<HostToWorkerMessage, { kind: 'lifecycle' }>;
+
+describe('PluginWorkerHost', () => {
+ it('posts a load message and resolves load() when the worker reports ready', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const p = host.load('/plugins/demo/index.js');
+ expect(ch.last()).toEqual({ kind: 'load', mainPath: '/plugins/demo/index.js' });
+
+ ch.reply({ kind: 'ready' });
+ await expect(p).resolves.toBeUndefined();
+ });
+
+ it('rejects load() when the worker errors before becoming ready', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const p = host.load('/plugins/broken/index.js');
+ ch.reply({ kind: 'error', error: 'Cannot find module' });
+
+ await expect(p).rejects.toThrow('Cannot find module');
+ });
+
+ it('runLifecycle() sends a correlated id and resolves on a matching ok result', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+ void host.load('/p/index.js');
+ ch.reply({ kind: 'ready' });
+
+ const p = host.runLifecycle('onEnable');
+ const msg = lastLifecycle(ch);
+ expect(msg.kind).toBe('lifecycle');
+ expect(msg.method).toBe('onEnable');
+
+ ch.reply({ kind: 'lifecycle-result', id: msg.id, ok: true });
+ await expect(p).resolves.toBeUndefined();
+ });
+
+ it('runLifecycle() rejects on an error result, surfacing the worker error message', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+ void host.load('/p/index.js');
+ ch.reply({ kind: 'ready' });
+
+ const p = host.runLifecycle('onEnable');
+ ch.reply({ kind: 'lifecycle-result', id: lastLifecycle(ch).id, ok: false, error: 'onEnable threw' });
+
+ await expect(p).rejects.toThrow('onEnable threw');
+ });
+
+ it('correlates concurrent lifecycle calls by id (no cross-resolution)', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+ void host.load('/p/index.js');
+ ch.reply({ kind: 'ready' });
+
+ const enable = host.runLifecycle('onEnable');
+ const enableId = lastLifecycle(ch).id;
+ const disable = host.runLifecycle('onDisable');
+ const disableId = lastLifecycle(ch).id;
+ expect(disableId).not.toBe(enableId);
+
+ // Resolve the second call first; the first must stay pending.
+ ch.reply({ kind: 'lifecycle-result', id: disableId, ok: true });
+ await expect(disable).resolves.toBeUndefined();
+ ch.reply({ kind: 'lifecycle-result', id: enableId, ok: true });
+ await expect(enable).resolves.toBeUndefined();
+ });
+
+ it('rejects all pending calls when the worker exits unexpectedly', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+ void host.load('/p/index.js');
+ ch.reply({ kind: 'ready' });
+
+ const p = host.runLifecycle('onEnable');
+ ch.crash(1);
+
+ await expect(p).rejects.toThrow(/exit/i);
+ });
+
+ it('terminate() terminates the underlying channel', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ await host.terminate();
+ expect(ch.terminated).toBe(true);
+ });
+
+ describe('capability requests from the worker', () => {
+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
+
+ it('dispatches a cap request and posts the result back', async () => {
+ const ch = new FakeChannel();
+ const dispatcher = jest.fn().mockResolvedValue({ messageId: 'wamid' });
+ new PluginWorkerHost(ch, dispatcher);
+
+ ch.reply({ kind: 'cap', id: 5, verb: 'messages.sendText', args: ['s1', 'c1', 'hi'] });
+ await flush();
+
+ expect(dispatcher).toHaveBeenCalledWith('messages.sendText', ['s1', 'c1', 'hi']);
+ expect(ch.sent).toContainEqual({ kind: 'cap-result', id: 5, ok: true, result: { messageId: 'wamid' } });
+ });
+
+ it('posts an error cap-result when the dispatcher rejects (e.g. permission denied)', async () => {
+ const ch = new FakeChannel();
+ const dispatcher = jest.fn().mockRejectedValue(new Error('missing permission'));
+ new PluginWorkerHost(ch, dispatcher);
+
+ ch.reply({ kind: 'cap', id: 7, verb: 'messages.sendText', args: [] });
+ await flush();
+
+ expect(ch.sent).toContainEqual({ kind: 'cap-result', id: 7, ok: false, error: 'missing permission' });
+ });
+
+ it('fails a cap request when no dispatcher is configured', async () => {
+ const ch = new FakeChannel();
+ new PluginWorkerHost(ch);
+
+ ch.reply({ kind: 'cap', id: 9, verb: 'messages.sendText', args: [] });
+ await flush();
+
+ expect(ch.sent.find(m => m.kind === 'cap-result')).toMatchObject({ id: 9, ok: false });
+ });
+ });
+
+ describe('hook bridge', () => {
+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
+
+ it('calls onHookSubscribe when the worker subscribes to an event', async () => {
+ const ch = new FakeChannel();
+ const onHookSubscribe = jest.fn();
+ new PluginWorkerHost(ch, undefined, onHookSubscribe);
+
+ ch.reply({ kind: 'hook-subscribe', event: 'message:received', priority: 50 });
+ await flush();
+
+ expect(onHookSubscribe).toHaveBeenCalledWith('message:received', 50);
+ });
+
+ it('dispatchHook posts a hook and resolves on the matching hook-result', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.dispatchHook({
+ event: 'message:received',
+ data: { body: 'hi' },
+ source: 'Engine',
+ timeoutMs: 1000,
+ });
+ const sent = ch.sent.find(m => m.kind === 'hook') as Extract<HostToWorkerMessage, { kind: 'hook' }>;
+ expect(sent).toMatchObject({ kind: 'hook', event: 'message:received', data: { body: 'hi' }, source: 'Engine' });
+
+ ch.reply({ kind: 'hook-result', id: sent.id, continue: false, data: { body: 'modified' } });
+ await expect(pending).resolves.toEqual({ continue: false, data: { body: 'modified' } });
+ });
+
+ it('dispatchHook resolves continue:true on timeout so the chain is not stalled', async () => {
+ jest.useFakeTimers();
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+ const onTimeout = jest.fn();
+
+ const pending = host.dispatchHook({
+ event: 'message:received',
+ data: {},
+ source: 'Engine',
+ timeoutMs: 100,
+ onTimeout,
+ });
+ jest.advanceTimersByTime(100);
+
+ await expect(pending).resolves.toEqual({ continue: true });
+ expect(onTimeout).toHaveBeenCalled();
+ jest.useRealTimers();
+ });
+ });
+
+ describe('logger + static context', () => {
+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
+
+ it('load() forwards the static context (pluginId, config) to the worker', () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ void host.load('/p/index.js', { pluginId: 'p', config: { a: 1 } });
+
+ expect(ch.last()).toMatchObject({
+ kind: 'load',
+ mainPath: '/p/index.js',
+ context: { pluginId: 'p', config: { a: 1 } },
+ });
+ });
+
+ it('load() omits context when none is supplied', () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ void host.load('/p/index.js');
+
+ expect(ch.last()).toEqual({ kind: 'load', mainPath: '/p/index.js' });
+ });
+
+ it('routes a worker log message to onLog', async () => {
+ const ch = new FakeChannel();
+ const onLog = jest.fn();
+ new PluginWorkerHost(ch, undefined, undefined, onLog);
+
+ ch.reply({ kind: 'log', level: 'warn', message: 'heads up', meta: { x: 1 } });
+ await flush();
+
+ expect(onLog).toHaveBeenCalledWith('warn', 'heads up', { x: 1 });
+ });
+ });
+});
diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.ts
new file mode 100644
index 000000000..e05f71fce
--- /dev/null
+++ b/src/core/plugins/sandbox/plugin-worker-host.ts
@@ -0,0 +1,171 @@
+import {
+ PluginWorkerChannel,
+ PluginLifecycleMethod,
+ WorkerToHostMessage,
+ SandboxStaticContext,
+ PluginLogLevel,
+} from './protocol';
+
+/**
+ * Host-side driver for a single untrusted plugin running in a worker. Owns the request/response
+ * correlation over a {@link PluginWorkerChannel}: it posts `load`/`lifecycle` messages and resolves
+ * the matching promise when the worker replies, and fails every outstanding call if the worker dies.
+ *
+ * Phase B1 covers lifecycle only. The capability bridge (B2) and hook bridge (B3) extend this with
+ * their own correlated message kinds, all over the same channel.
+ */
+export class PluginWorkerHost {
+ private nextId = 1;
+ private ready = false;
+ private dead = false;
+ private readyWaiters: Array<{ resolve: () => void; reject: (error: Error) => void }> = [];
+ private readonly pending = new Map<number, { resolve: () => void; reject: (error: Error) => void }>();
+ private readonly hookPending = new Map<
+ number,
+ { resolve: (result: { continue: boolean; data?: unknown }) => void; timer: ReturnType<typeof setTimeout> }
+ >();
+
+ constructor(
+ private readonly channel: PluginWorkerChannel,
+ // Runs a worker-initiated capability call host-side (validating permission + session scope before
+ // the real verb). Absent => the worker has no capabilities (e.g. before the bridge is wired).
+ private readonly capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,
+ // Called when the worker subscribes a handler to an event, so the host can register a shim with
+ // the hook manager that dispatches into the worker.
+ private readonly onHookSubscribe?: (event: string, priority?: number) => void,
+ // Routes a worker plugin's ctx.logger.* call to the host's per-plugin logger.
+ private readonly onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,
+ ) {
+ this.channel.onMessage(message => this.handleMessage(message));
+ this.channel.onExit(code => this.handleExit(code));
+ }
+
+ /**
+ * Dispatch a hook event to the worker and await its handler result. Bounded by `timeoutMs`: if the
+ * worker's handler is slow or wedged, this resolves `{ continue: true }` so the host's hook chain
+ * is never stalled by an untrusted plugin (and `onTimeout` flags it for the caller).
+ */
+ dispatchHook(options: {
+ event: string;
+ data: unknown;
+ source: string;
+ sessionId?: string;
+ timeoutMs: number;
+ onTimeout?: () => void;
+ }): Promise<{ continue: boolean; data?: unknown }> {
+ const id = this.nextId++;
+ return new Promise(resolve => {
+ const timer = setTimeout(() => {
+ this.hookPending.delete(id);
+ options.onTimeout?.();
+ resolve({ continue: true });
+ }, options.timeoutMs);
+ this.hookPending.set(id, { resolve, timer });
+ this.channel.postMessage({
+ kind: 'hook',
+ id,
+ event: options.event,
+ data: options.data,
+ sessionId: options.sessionId,
+ source: options.source,
+ });
+ });
+ }
+
+ /** Load the plugin module in the worker; resolves once it reports `ready`, rejects if it errors. */
+ load(mainPath: string, context?: SandboxStaticContext): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (this.dead) return reject(new Error('plugin worker is no longer running'));
+ if (this.ready) return resolve();
+ this.readyWaiters.push({ resolve, reject });
+ this.channel.postMessage(context ? { kind: 'load', mainPath, context } : { kind: 'load', mainPath });
+ });
+ }
+
+ /** Invoke a plugin lifecycle method in the worker; resolves/rejects on the correlated result. */
+ runLifecycle(method: PluginLifecycleMethod): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (this.dead) return reject(new Error('plugin worker is no longer running'));
+ const id = this.nextId++;
+ this.pending.set(id, { resolve, reject });
+ this.channel.postMessage({ kind: 'lifecycle', id, method });
+ });
+ }
+
+ /** Tear the worker down. */
+ terminate(): Promise<void> {
+ return this.channel.terminate();
+ }
+
+ private handleMessage(message: WorkerToHostMessage): void {
+ switch (message.kind) {
+ case 'ready':
+ this.ready = true;
+ this.drain(this.readyWaiters, w => w.resolve());
+ break;
+ case 'error': {
+ const error = new Error(message.error);
+ this.drain(this.readyWaiters, w => w.reject(error));
+ break;
+ }
+ case 'lifecycle-result': {
+ const waiter = this.pending.get(message.id);
+ if (!waiter) return;
+ this.pending.delete(message.id);
+ if (message.ok) waiter.resolve();
+ else waiter.reject(new Error(message.error));
+ break;
+ }
+ case 'cap':
+ void this.handleCapRequest(message);
+ break;
+ case 'hook-subscribe':
+ this.onHookSubscribe?.(message.event, message.priority);
+ break;
+ case 'log':
+ this.onLog?.(message.level, message.message, message.meta);
+ break;
+ case 'hook-result': {
+ const waiter = this.hookPending.get(message.id);
+ if (!waiter) return;
+ this.hookPending.delete(message.id);
+ clearTimeout(waiter.timer);
+ const result: { continue: boolean; data?: unknown } = { continue: message.continue };
+ if (message.data !== undefined) result.data = message.data;
+ waiter.resolve(result);
+ break;
+ }
+ }
+ }
+
+ private async handleCapRequest(message: Extract<WorkerToHostMessage, { kind: 'cap' }>): Promise<void> {
+ if (!this.capDispatcher) {
+ this.channel.postMessage({ kind: 'cap-result', id: message.id, ok: false, error: 'no capability dispatcher' });
+ return;
+ }
+ try {
+ const result = await this.capDispatcher(message.verb, message.args);
+ this.channel.postMessage({ kind: 'cap-result', id: message.id, ok: true, result });
+ } catch (error) {
+ this.channel.postMessage({
+ kind: 'cap-result',
+ id: message.id,
+ ok: false,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ private handleExit(code: number): void {
+ this.dead = true;
+ const error = new Error(`plugin worker exited unexpectedly (code ${code})`);
+ this.drain(this.readyWaiters, w => w.reject(error));
+ this.pending.forEach(waiter => waiter.reject(error));
+ this.pending.clear();
+ }
+
+ private drain<T>(waiters: T[], fn: (w: T) => void): void {
+ const current = waiters.splice(0, waiters.length);
+ current.forEach(fn);
+ }
+}
diff --git a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
new file mode 100644
index 000000000..c5747c35e
--- /dev/null
+++ b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
@@ -0,0 +1,153 @@
+import * as path from 'path';
+import { WorkerThreadChannel } from './worker-thread-channel';
+import { PluginWorkerHost } from './plugin-worker-host';
+
+// Repo root, from src/core/plugins/sandbox.
+const ROOT = path.resolve(__dirname, '../../../..');
+const BOOTSTRAP = path.resolve(__dirname, 'worker-bootstrap.ts');
+const FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/echo-plugin.cjs');
+const CAP_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/cap-echo-plugin.cjs');
+const HOOK_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-plugin.cjs');
+const HOOK_HANG_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-hang-plugin.cjs');
+const RUNAWAY_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/runaway-plugin.cjs');
+const CTX_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-aware-plugin.cjs');
+const flushAsync = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
+
+// Run the TS bootstrap inside the worker via ts-node. The base tsconfig is nodenext; we pin the
+// worker's transpile to CommonJS (same override the jest/ts-jest config uses) so `require()` works.
+// Production loads the compiled `worker-bootstrap.js` directly and needs none of this.
+const TS_NODE_OPTS = JSON.stringify({ module: 'commonjs', moduleResolution: 'node', resolvePackageJsonExports: false });
+
+const makeChannel = (): WorkerThreadChannel =>
+ new WorkerThreadChannel({
+ workerEntry: BOOTSTRAP,
+ execArgv: ['-r', 'ts-node/register/transpile-only'],
+ env: { ...process.env, TS_NODE_COMPILER_OPTIONS: TS_NODE_OPTS },
+ });
+
+const makeHost = (capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>): PluginWorkerHost =>
+ new PluginWorkerHost(makeChannel(), capDispatcher);
+
+describe('plugin worker — real worker_threads round-trip (B1)', () => {
+ jest.setTimeout(30000);
+
+ it('loads a plugin and runs its lifecycle in a real worker thread', async () => {
+ const host = makeHost();
+ await host.load(FIXTURE);
+ await host.runLifecycle('onEnable');
+ await host.runLifecycle('onDisable');
+ await host.terminate();
+ });
+
+ it('rejects load() when the plugin module cannot be required', async () => {
+ const host = makeHost();
+ await expect(host.load(path.resolve(ROOT, 'test/fixtures/sandbox/missing.cjs'))).rejects.toThrow();
+ await host.terminate();
+ });
+
+ it('round-trips a capability call: the worker plugin invokes ctx.messages.sendText and gets the result', async () => {
+ const dispatcher = jest.fn().mockResolvedValue({ messageId: 'wamid' });
+ const host = makeHost(dispatcher);
+
+ await host.load(CAP_FIXTURE);
+ // onEnable awaits ctx.messages.sendText and throws unless it gets { messageId: 'wamid' } back,
+ // so this resolving proves the full worker -> host -> worker round-trip.
+ await host.runLifecycle('onEnable');
+
+ expect(dispatcher).toHaveBeenCalledWith('messages.sendText', ['s', 'c', 'hi']);
+ await host.terminate();
+ });
+
+ it('round-trips a hook: the worker registers a handler, the host dispatches and gets continue/data', async () => {
+ const subscribed: string[] = [];
+ const host = new PluginWorkerHost(makeChannel(), undefined, event => subscribed.push(event));
+
+ await host.load(HOOK_FIXTURE);
+ await host.runLifecycle('onEnable'); // the plugin registers its hook here
+ await flushAsync(); // let the hook-subscribe message land
+ expect(subscribed).toContain('message:received');
+
+ const result = await host.dispatchHook({
+ event: 'message:received',
+ data: { body: 'hi' },
+ source: 'Engine',
+ timeoutMs: 5000,
+ });
+ expect(result).toEqual({ continue: false, data: { body: 'hi', seen: true } });
+ await host.terminate();
+ });
+
+ it('a wedged worker hook handler times out so the host chain proceeds', async () => {
+ const host = new PluginWorkerHost(makeChannel(), undefined, () => undefined);
+
+ await host.load(HOOK_HANG_FIXTURE);
+ await host.runLifecycle('onEnable');
+ await flushAsync();
+
+ const onTimeout = jest.fn();
+ const result = await host.dispatchHook({
+ event: 'message:received',
+ data: {},
+ source: 'Engine',
+ timeoutMs: 200,
+ onTimeout,
+ });
+ expect(result).toEqual({ continue: true });
+ expect(onTimeout).toHaveBeenCalled();
+ await host.terminate();
+ });
+
+ it('force-terminates a runaway (infinite-loop) plugin', async () => {
+ const host = makeHost();
+ await host.load(RUNAWAY_FIXTURE);
+
+ // onEnable spins forever and blocks the worker event loop — it can never reply, so cooperative
+ // shutdown is impossible. terminate() must still reclaim the thread.
+ const wedged = host.runLifecycle('onEnable');
+ wedged.catch(() => undefined); // terminate() rejects this pending call; swallow it
+ await new Promise(resolve => setTimeout(resolve, 150));
+
+ await expect(host.terminate()).resolves.toBeUndefined();
+ });
+
+ it('preserves a structured-clone-safe hook payload across the worker boundary', async () => {
+ const host = new PluginWorkerHost(makeChannel(), undefined, () => undefined);
+ await host.load(HOOK_FIXTURE); // its handler returns { ...data, seen: true }
+ await host.runLifecycle('onEnable');
+ await flushAsync();
+
+ const payload = {
+ body: 'hi',
+ meta: { ts: new Date('2026-06-22T00:00:00.000Z'), nested: { n: 1 } },
+ };
+ const result = await host.dispatchHook({
+ event: 'message:received',
+ data: payload,
+ source: 'Engine',
+ timeoutMs: 5000,
+ });
+ const data = result.data as typeof payload & { seen: boolean };
+
+ expect(data.mentions).toEqual(['[email protected]', '[email protected]']);
+ expect(data.meta.nested).toEqual({ n: 1 });
+ expect(data.meta.ts.getTime()).toBe(new Date('2026-06-22T00:00:00.000Z').getTime());
+ expect(data.seen).toBe(true);
+ await host.terminate();
+ });
+
+ it('bridges ctx.logger and ctx.config into a sandboxed plugin', async () => {
+ const logs: Array<{ level: string; message: string; meta?: Record<string, unknown> }> = [];
+ const host = new PluginWorkerHost(makeChannel(), undefined, undefined, (level, message, meta) =>
+ logs.push({ level, message, meta }),
+ );
+
+ await host.load(CTX_FIXTURE, { pluginId: 'ctx-demo', config: { greeting: 'hi' } });
+ await host.runLifecycle('onEnable');
+ await flushAsync();
+
+ // The plugin read ctx.pluginId + ctx.config and logged via ctx.logger; all of it crossed the bridge.
+ expect(logs).toContainEqual({ level: 'log', message: 'hello from ctx-demo', meta: { greeting: 'hi' } });
+ await host.terminate();
+ });
+});
diff --git a/src/core/plugins/sandbox/protocol.ts b/src/core/plugins/sandbox/protocol.ts
new file mode 100644
index 000000000..87698cbe2
--- /dev/null
+++ b/src/core/plugins/sandbox/protocol.ts
@@ -0,0 +1,56 @@
+/**
+ * Wire protocol between the host (PluginWorkerHost) and an untrusted plugin worker.
+ *
+ * The worker has exactly one channel out — these messages — and no ambient access to the host. The
+ * host validates every request before acting on it, so a hostile worker cannot escalate beyond what
+ * its manifest declares.
+ *
+ * Phase B1 scope: lifecycle only (load + onLoad/onEnable/onDisable/onUnload). The capability bridge
+ * (B2) and hook bridge (B3) add more message kinds later.
+ */
+
+export type PluginLifecycleMethod = 'onLoad' | 'onEnable' | 'onDisable' | 'onUnload';
+
+/** Static context fields handed to a sandboxed plugin at load (serializable; no live references). */
+export interface SandboxStaticContext {
+ pluginId: string;
+ config: Record<string, unknown>;
+}
+
+export type PluginLogLevel = 'log' | 'debug' | 'warn' | 'error';
+
+export type HostToWorkerMessage =
+ | { kind: 'load'; mainPath: string; context?: SandboxStaticContext }
+ | { kind: 'lifecycle'; id: number; method: PluginLifecycleMethod }
+ // Reply to a worker-initiated capability call.
+ | { kind: 'cap-result'; id: number; ok: true; result: unknown }
+ | { kind: 'cap-result'; id: number; ok: false; error: string }
+ // Dispatch a subscribed hook to the worker; it runs its handler(s) and replies with hook-result.
+ | { kind: 'hook'; id: number; event: string; data: unknown; sessionId?: string; source: string };
+
+export type WorkerToHostMessage =
+ | { kind: 'ready' }
+ | { kind: 'lifecycle-result'; id: number; ok: true }
+ | { kind: 'lifecycle-result'; id: number; ok: false; error: string }
+ // Worker-initiated capability call (ctx.messages.* / ctx.engine.* / ctx.storage.*). The host
+ // validates it (permission + session scope) before running the real verb and replying.
+ | { kind: 'cap'; id: number; verb: string; args: unknown[] }
+ // The worker asks the host to dispatch `event` to it (registered a handler for it).
+ | { kind: 'hook-subscribe'; event: string; priority?: number }
+ // The worker's handler result for a dispatched hook (continue/modify/error).
+ | { kind: 'hook-result'; id: number; continue: boolean; data?: unknown; error?: string }
+ // The worker plugin's ctx.logger.* call, routed to the host's per-plugin logger.
+ | { kind: 'log'; level: PluginLogLevel; message: string; meta?: Record<string, unknown> }
+ | { kind: 'error'; error: string };
+
+/**
+ * Transport abstraction over the worker. The real implementation wraps a Node `worker_thread`; tests
+ * use an in-memory fake. Keeping the host's protocol logic behind this interface makes it unit-
+ * testable without spawning an OS thread, and leaves room for a child-process transport later.
+ */
+export interface PluginWorkerChannel {
+ postMessage(message: HostToWorkerMessage): void;
+ onMessage(handler: (message: WorkerToHostMessage) => void): void;
+ onExit(handler: (code: number) => void): void;
+ terminate(): Promise<void>;
+}
diff --git a/src/core/plugins/sandbox/worker-bootstrap.ts b/src/core/plugins/sandbox/worker-bootstrap.ts
new file mode 100644
index 000000000..ff13eddaf
--- /dev/null
+++ b/src/core/plugins/sandbox/worker-bootstrap.ts
@@ -0,0 +1,90 @@
+import { parentPort } from 'worker_threads';
+import { HostToWorkerMessage, WorkerToHostMessage } from './protocol';
+import { WorkerCapabilityClient, buildSandboxContext } from './worker-capability';
+import { WorkerHookRegistry, WorkerHookHandler } from './worker-hooks';
+
+/**
+ * Worker entry for an untrusted plugin. Loads the plugin module and drives its lifecycle in response
+ * to host messages. This is the only code that runs alongside untrusted plugin code, so it keeps no
+ * host references — its sole channel out is `parentPort`, and every capability call round-trips to
+ * the host (which validates permission + session scope) via the capability client.
+ */
+
+interface LifecyclePlugin {
+ onLoad?(context: unknown): unknown;
+ onEnable?(context: unknown): unknown;
+ onDisable?(context: unknown): unknown;
+ onUnload?(context: unknown): unknown;
+}
+
+const port = parentPort;
+if (!port) {
+ throw new Error('worker-bootstrap must be run as a worker thread');
+}
+
+const send = (message: WorkerToHostMessage): void => port.postMessage(message);
+const errorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+
+const capClient = new WorkerCapabilityClient(send);
+const hookRegistry = new WorkerHookRegistry(send);
+
+// ctx.logger proxy: forwards to the host's per-plugin logger (the same one in-process plugins use).
+const logger = {
+ log: (message: string, meta?: Record<string, unknown>) => send({ kind: 'log', level: 'log', message, meta }),
+ debug: (message: string, meta?: Record<string, unknown>) => send({ kind: 'log', level: 'debug', message, meta }),
+ warn: (message: string, meta?: Record<string, unknown>) => send({ kind: 'log', level: 'warn', message, meta }),
+ error: (message: string, error?: unknown, meta?: Record<string, unknown>) =>
+ send({
+ kind: 'log',
+ level: 'error',
+ message,
+ meta: error !== undefined ? { ...meta, error: errorMessage(error) } : meta,
+ }),
+};
+let plugin: LifecyclePlugin | null = null;
+let context: Record<string, unknown> | null = null;
+
+port.on('message', (message: HostToWorkerMessage) => {
+ if (message.kind === 'cap-result') {
+ capClient.handleResult(message);
+ return;
+ }
+ if (message.kind === 'hook') {
+ void hookRegistry.handleHook(message);
+ return;
+ }
+ void handle(message);
+});
+
+async function handle(message: HostToWorkerMessage): Promise<void> {
+ if (message.kind === 'load') {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const mod = require(message.mainPath) as { default?: new () => LifecyclePlugin } & (new () => LifecyclePlugin);
+ const PluginCtor = mod.default ?? mod;
+ plugin = new PluginCtor();
+ const staticContext = message.context ?? { pluginId: 'unknown', config: {} };
+ context = {
+ pluginId: staticContext.pluginId,
+ config: staticContext.config,
+ logger,
+ ...buildSandboxContext(capClient),
+ registerHook: (event: string, handler: WorkerHookHandler, priority?: number) =>
+ hookRegistry.register(event, handler, priority),
+ };
+ send({ kind: 'ready' });
+ } catch (error) {
+ send({ kind: 'error', error: errorMessage(error) });
+ }
+ return;
+ }
+
+ if (message.kind === 'lifecycle') {
+ try {
+ await plugin?.[message.method]?.(context);
+ send({ kind: 'lifecycle-result', id: message.id, ok: true });
+ } catch (error) {
+ send({ kind: 'lifecycle-result', id: message.id, ok: false, error: errorMessage(error) });
+ }
+ }
+}
diff --git a/src/core/plugins/sandbox/worker-capability.spec.ts b/src/core/plugins/sandbox/worker-capability.spec.ts
new file mode 100644
index 000000000..adb2e3ffe
--- /dev/null
+++ b/src/core/plugins/sandbox/worker-capability.spec.ts
@@ -0,0 +1,61 @@
+import { WorkerCapabilityClient, buildSandboxContext } from './worker-capability';
+import { WorkerToHostMessage } from './protocol';
+
+describe('WorkerCapabilityClient', () => {
+ it('posts a cap request and resolves on the matching cap-result', async () => {
+ const sent: WorkerToHostMessage[] = [];
+ const client = new WorkerCapabilityClient(m => sent.push(m));
+
+ const pending = client.call('messages.sendText', ['s', 'c', 'hi']);
+ const req = sent[0] as Extract<WorkerToHostMessage, { kind: 'cap' }>;
+ expect(req).toMatchObject({ kind: 'cap', verb: 'messages.sendText', args: ['s', 'c', 'hi'] });
+
+ client.handleResult({ kind: 'cap-result', id: req.id, ok: true, result: { messageId: 'm' } });
+ await expect(pending).resolves.toEqual({ messageId: 'm' });
+ });
+
+ it('rejects on an error cap-result', async () => {
+ const sent: WorkerToHostMessage[] = [];
+ const client = new WorkerCapabilityClient(m => sent.push(m));
+
+ const pending = client.call('messages.sendText', []);
+ const req = sent[0] as Extract<WorkerToHostMessage, { kind: 'cap' }>;
+ client.handleResult({ kind: 'cap-result', id: req.id, ok: false, error: 'permission denied' });
+
+ await expect(pending).rejects.toThrow('permission denied');
+ });
+
+ it('correlates concurrent calls by id', async () => {
+ const sent: WorkerToHostMessage[] = [];
+ const client = new WorkerCapabilityClient(m => sent.push(m));
+
+ const a = client.call('storage.get', ['a']);
+ const b = client.call('storage.get', ['b']);
+ const [reqA, reqB] = sent as Extract<WorkerToHostMessage, { kind: 'cap' }>[];
+ expect(reqA.id).not.toBe(reqB.id);
+
+ client.handleResult({ kind: 'cap-result', id: reqB.id, ok: true, result: 'B' });
+ client.handleResult({ kind: 'cap-result', id: reqA.id, ok: true, result: 'A' });
+ await expect(a).resolves.toBe('A');
+ await expect(b).resolves.toBe('B');
+ });
+});
+
+describe('buildSandboxContext', () => {
+ it('proxies each capability verb to client.call with positional args', async () => {
+ const call = jest.fn().mockResolvedValue('ok');
+ const ctx = buildSandboxContext({ call } as unknown as WorkerCapabilityClient);
+
+ await ctx.messages.sendText('s', 'c', 'hi');
+ expect(call).toHaveBeenCalledWith('messages.sendText', ['s', 'c', 'hi']);
+
+ await ctx.messages.reply('s', 'c', 'q', 'hi');
+ expect(call).toHaveBeenCalledWith('messages.reply', ['s', 'c', 'q', 'hi']);
+
+ await ctx.engine.getGroupInfo('s', 'g');
+ expect(call).toHaveBeenCalledWith('engine.getGroupInfo', ['s', 'g']);
+
+ await ctx.storage.set('k', { a: 1 });
+ expect(call).toHaveBeenCalledWith('storage.set', ['k', { a: 1 }]);
+ });
+});
diff --git a/src/core/plugins/sandbox/worker-capability.ts b/src/core/plugins/sandbox/worker-capability.ts
new file mode 100644
index 000000000..479b49f54
--- /dev/null
+++ b/src/core/plugins/sandbox/worker-capability.ts
@@ -0,0 +1,73 @@
+import { WorkerToHostMessage, HostToWorkerMessage } from './protocol';
+
+/**
+ * Worker-side correlation for capability calls. Each `call` posts a `cap` request and resolves when
+ * the host's matching `cap-result` arrives. The mirror of the host's PluginWorkerHost correlation.
+ */
+export class WorkerCapabilityClient {
+ private nextId = 1;
+ private readonly pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
+
+ constructor(private readonly post: (message: WorkerToHostMessage) => void) {}
+
+ call(verb: string, args: unknown[]): Promise<unknown> {
+ const id = this.nextId++;
+ return new Promise((resolve, reject) => {
+ this.pending.set(id, { resolve, reject });
+ this.post({ kind: 'cap', id, verb, args });
+ });
+ }
+
+ handleResult(message: Extract<HostToWorkerMessage, { kind: 'cap-result' }>): void {
+ const waiter = this.pending.get(message.id);
+ if (!waiter) return;
+ this.pending.delete(message.id);
+ if (message.ok) waiter.resolve(message.result);
+ else waiter.reject(new Error(message.error));
+ }
+}
+
+/** The capability surface a sandboxed plugin sees — every method round-trips to the host. */
+export interface SandboxCapabilityContext {
+ messages: {
+ sendText(sessionId: string, chatId: string, text: string): Promise<unknown>;
+ reply(sessionId: string, chatId: string, quotedMessageId: string, text: string): Promise<unknown>;
+ };
+ engine: {
+ getGroupInfo(sessionId: string, groupId: string): Promise<unknown>;
+ getContacts(sessionId: string): Promise<unknown>;
+ getContactById(sessionId: string, contactId: string): Promise<unknown>;
+ checkNumberExists(sessionId: string, phone: string): Promise<unknown>;
+ getChats(sessionId: string): Promise<unknown>;
+ };
+ storage: {
+ get(key: string): Promise<unknown>;
+ set(key: string, value: unknown): Promise<unknown>;
+ delete(key: string): Promise<unknown>;
+ list(prefix?: string): Promise<unknown>;
+ };
+}
+
+/** Build the proxy capability context handed to a sandboxed plugin in the worker. */
+export function buildSandboxContext(client: WorkerCapabilityClient): SandboxCapabilityContext {
+ return {
+ messages: {
+ sendText: (sessionId, chatId, text) => client.call('messages.sendText', [sessionId, chatId, text]),
+ reply: (sessionId, chatId, quotedMessageId, text) =>
+ client.call('messages.reply', [sessionId, chatId, quotedMessageId, text]),
+ },
+ engine: {
+ getGroupInfo: (sessionId, groupId) => client.call('engine.getGroupInfo', [sessionId, groupId]),
+ getContacts: sessionId => client.call('engine.getContacts', [sessionId]),
+ getContactById: (sessionId, contactId) => client.call('engine.getContactById', [sessionId, contactId]),
+ checkNumberExists: (sessionId, phone) => client.call('engine.checkNumberExists', [sessionId, phone]),
+ getChats: sessionId => client.call('engine.getChats', [sessionId]),
+ },
+ storage: {
+ get: key => client.call('storage.get', [key]),
+ set: (key, value) => client.call('storage.set', [key, value]),
+ delete: key => client.call('storage.delete', [key]),
+ list: prefix => client.call('storage.list', [prefix]),
+ },
+ };
+}
diff --git a/src/core/plugins/sandbox/worker-hooks.spec.ts b/src/core/plugins/sandbox/worker-hooks.spec.ts
new file mode 100644
index 000000000..bb3813975
--- /dev/null
+++ b/src/core/plugins/sandbox/worker-hooks.spec.ts
@@ -0,0 +1,63 @@
+import { WorkerHookRegistry } from './worker-hooks';
+import { WorkerToHostMessage } from './protocol';
+
+const collect = () => {
+ const sent: WorkerToHostMessage[] = [];
+ return { sent, post: (m: WorkerToHostMessage) => sent.push(m) };
+};
+const num = (data: unknown): number => (data as { n: number }).n;
+
+describe('WorkerHookRegistry', () => {
+ it('posts hook-subscribe on the first registration for an event', () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+
+ reg.register('message:received', () => Promise.resolve({ continue: true }), 50);
+
+ expect(sent).toContainEqual({ kind: 'hook-subscribe', event: 'message:received', priority: 50 });
+ });
+
+ it('does not re-subscribe for a second handler on the same event', () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+
+ reg.register('message:received', () => Promise.resolve({ continue: true }));
+ reg.register('message:received', () => Promise.resolve({ continue: true }));
+
+ expect(sent.filter(m => m.kind === 'hook-subscribe')).toHaveLength(1);
+ });
+
+ it('runs the handler on a hook and replies with continue + modified data', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+ reg.register('message:received', ctx =>
+ Promise.resolve({ continue: false, data: { ...(ctx.data as object), tagged: true } }),
+ );
+
+ await reg.handleHook({ kind: 'hook', id: 3, event: 'message:received', data: { body: 'hi' }, source: 'Engine' });
+
+ expect(sent).toContainEqual({ kind: 'hook-result', id: 3, continue: false, data: { body: 'hi', tagged: true } });
+ });
+
+ it('threads data through handlers in priority order and stops on continue:false', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+ reg.register('e', () => Promise.resolve({ continue: true, data: { n: 1 } }), 10);
+ reg.register('e', ctx => Promise.resolve({ continue: false, data: { n: num(ctx.data) + 1 } }), 20);
+ reg.register('e', () => Promise.resolve({ continue: true, data: { n: 99 } }), 30); // must not run
+
+ await reg.handleHook({ kind: 'hook', id: 1, event: 'e', data: {}, source: 's' });
+
+ expect(sent.find(m => m.kind === 'hook-result')).toMatchObject({ continue: false, data: { n: 2 } });
+ });
+
+ it('a throwing handler does not break the chain', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+ reg.register('e', () => Promise.reject(new Error('boom')));
+
+ await reg.handleHook({ kind: 'hook', id: 1, event: 'e', data: { x: 1 }, source: 's' });
+
+ expect(sent.find(m => m.kind === 'hook-result')).toMatchObject({ continue: true });
+ });
+});
diff --git a/src/core/plugins/sandbox/worker-hooks.ts b/src/core/plugins/sandbox/worker-hooks.ts
new file mode 100644
index 000000000..7106cc3f1
--- /dev/null
+++ b/src/core/plugins/sandbox/worker-hooks.ts
@@ -0,0 +1,64 @@
+import { WorkerToHostMessage, HostToWorkerMessage } from './protocol';
+
+export interface WorkerHookContext {
+ event: string;
+ data: unknown;
+ sessionId?: string;
+ source: string;
+ timestamp: Date;
+}
+
+export interface WorkerHookResult {
+ continue: boolean;
+ data?: unknown;
+}
+
+export type WorkerHookHandler = (ctx: WorkerHookContext) => Promise<WorkerHookResult> | WorkerHookResult;
+
+/**
+ * Worker-side hook handling. A sandboxed plugin registers handlers here (via ctx.registerHook). The
+ * registry subscribes the host to each event the first time it sees a handler for it, and on a `hook`
+ * message runs the plugin's handlers in priority order — threading data, stopping on continue:false,
+ * and swallowing a handler error so one bad handler can't break the chain.
+ */
+export class WorkerHookRegistry {
+ private readonly handlers = new Map<string, { handler: WorkerHookHandler; priority: number }[]>();
+
+ constructor(private readonly post: (message: WorkerToHostMessage) => void) {}
+
+ register(event: string, handler: WorkerHookHandler, priority = 100): void {
+ const list = this.handlers.get(event);
+ if (list) {
+ list.push({ handler, priority });
+ list.sort((a, b) => a.priority - b.priority);
+ return;
+ }
+ this.handlers.set(event, [{ handler, priority }]);
+ this.post({ kind: 'hook-subscribe', event, priority });
+ }
+
+ async handleHook(message: Extract<HostToWorkerMessage, { kind: 'hook' }>): Promise<void> {
+ const list = this.handlers.get(message.event) ?? [];
+ let data = message.data;
+ let shouldContinue = true;
+ for (const { handler } of list) {
+ try {
+ const result = await handler({
+ event: message.event,
+ data,
+ sessionId: message.sessionId,
+ source: message.source,
+ timestamp: new Date(),
+ });
+ if (result.data !== undefined) data = result.data;
+ if (!result.continue) {
+ shouldContinue = false;
+ break;
+ }
+ } catch {
+ // A handler error must not break the chain (mirrors the host hook manager).
+ }
+ }
+ this.post({ kind: 'hook-result', id: message.id, continue: shouldContinue, data });
+ }
+}
diff --git a/src/core/plugins/sandbox/worker-thread-channel.ts b/src/core/plugins/sandbox/worker-thread-channel.ts
new file mode 100644
index 000000000..3c32a158d
--- /dev/null
+++ b/src/core/plugins/sandbox/worker-thread-channel.ts
@@ -0,0 +1,54 @@
+import { Worker } from 'worker_threads';
+import { PluginWorkerChannel, HostToWorkerMessage, WorkerToHostMessage } from './protocol';
+
+export interface WorkerThreadChannelOptions {
+ /** Path to the worker bootstrap entry (compiled `worker-bootstrap.js` in production). */
+ workerEntry: string;
+ /** Hard memory cap for the worker; an OOM terminates the worker, not the host. */
+ maxOldGenerationSizeMb?: number;
+ /** Extra Node args for the worker (e.g. a TS loader in tests). */
+ execArgv?: string[];
+ /** Environment for the worker. Later phases use this to hand the worker a minimal, scrubbed env. */
+ env?: NodeJS.ProcessEnv;
+}
+
+/**
+ * Real {@link PluginWorkerChannel} backed by a Node `worker_thread`. Deliberately thin: it only
+ * shuttles messages and surfaces worker lifetime events. All protocol logic lives in
+ * {@link PluginWorkerHost}, so this adapter (and a future child-process variant) stays trivial.
+ */
+export class WorkerThreadChannel implements PluginWorkerChannel {
+ private readonly worker: Worker;
+
+ constructor(options: WorkerThreadChannelOptions) {
+ this.worker = new Worker(options.workerEntry, {
+ execArgv: options.execArgv,
+ env: options.env,
+ resourceLimits:
+ options.maxOldGenerationSizeMb !== undefined
+ ? { maxOldGenerationSizeMb: options.maxOldGenerationSizeMb }
+ : undefined,
+ });
+ }
+
+ postMessage(message: HostToWorkerMessage): void {
+ this.worker.postMessage(message);
+ }
+
+ onMessage(handler: (message: WorkerToHostMessage) => void): void {
+ this.worker.on('message', handler);
+ // Surface a worker startup/runtime crash as a protocol error so the host's pending call rejects
+ // with the real reason instead of only an opaque exit code.
+ this.worker.on('error', (error: unknown) =>
+ handler({ kind: 'error', error: error instanceof Error ? error.message : String(error) }),
+ );
+ }
+
+ onExit(handler: (code: number) => void): void {
+ this.worker.on('exit', handler);
+ }
+
+ async terminate(): Promise<void> {
+ await this.worker.terminate();
+ }
+}
diff --git a/src/modules/plugins/plugin-installer.spec.ts b/src/modules/plugins/plugin-installer.spec.ts
new file mode 100644
index 000000000..f832e628a
--- /dev/null
+++ b/src/modules/plugins/plugin-installer.spec.ts
@@ -0,0 +1,98 @@
+import AdmZip from 'adm-zip';
+import { parsePluginPackage } from './plugin-installer';
+
+const validManifest = { id: 'my-plg', name: 'My Plugin', version: '1.0.0', type: 'extension', main: 'index.js' };
+
+function zipOf(files: Record<string, string>): Buffer {
+ const z = new AdmZip();
+ for (const [name, content] of Object.entries(files)) z.addFile(name, Buffer.from(content));
+ return z.toBuffer();
+}
+
+describe('parsePluginPackage', () => {
+ it('parses a flat package (manifest + files at the root)', () => {
+ const out = parsePluginPackage(
+ zipOf({ 'manifest.json': JSON.stringify(validManifest), 'index.js': 'module.exports=class{}' }),
+ );
+ expect(out.manifest.id).toBe('my-plg');
+ expect(out.entries.map(e => e.relPath).sort()).toEqual(['index.js', 'manifest.json']);
+ });
+
+ it('strips a single wrapping folder (a zipped plugin directory)', () => {
+ const out = parsePluginPackage(
+ zipOf({ 'my-plg/manifest.json': JSON.stringify(validManifest), 'my-plg/index.js': 'x' }),
+ );
+ expect(out.entries.map(e => e.relPath).sort()).toEqual(['index.js', 'manifest.json']);
+ });
+
+ it('ignores cruft outside the package root (e.g. __MACOSX)', () => {
+ const out = parsePluginPackage(
+ zipOf({ 'my-plg/manifest.json': JSON.stringify(validManifest), 'my-plg/index.js': 'x', '__MACOSX/._x': 'junk' }),
+ );
+ expect(out.entries.map(e => e.relPath).sort()).toEqual(['index.js', 'manifest.json']);
+ });
+
+ it('rejects an archive with no manifest.json', () => {
+ expect(() => parsePluginPackage(zipOf({ 'index.js': 'x' }))).toThrow(/no manifest/i);
+ });
+
+ it('rejects a manifest missing a required field', () => {
+ const bad = { ...validManifest, main: undefined };
+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(
+ /required field: main/i,
+ );
+ });
+
+ it('rejects an unsafe plugin id', () => {
+ const bad = { ...validManifest, id: '../evil' };
+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(
+ /invalid plugin id/i,
+ );
+ });
+
+ it('rejects an id reserved by a built-in', () => {
+ const bad = { ...validManifest, id: 'baileys' };
+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(
+ /reserved/i,
+ );
+ });
+
+ it('rejects an engine-type package (engines are built-in, not user-installable)', () => {
+ const bad = { ...validManifest, id: 'my-engine', type: 'engine' };
+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(
+ /extension/i,
+ );
+ });
+
+ it('rejects an unknown plugin type', () => {
+ const bad = { ...validManifest, type: 'wormhole' };
+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(/type/i);
+ });
+
+ it('rejects a zip-slip path escaping the package root', () => {
+ // adm-zip sanitizes names on add, so forge the malicious entry name directly to simulate a
+ // hand-crafted archive.
+ const z = new AdmZip();
+ z.addFile('manifest.json', Buffer.from(JSON.stringify(validManifest)));
+ z.addFile('index.js', Buffer.from('x'));
+ z.addFile('evil.js', Buffer.from('pwned'));
+ z.getEntries().find(e => e.entryName === 'evil.js')!.entryName = '../evil.js';
+ expect(() => parsePluginPackage(z.toBuffer())).toThrow(/unsafe path/i);
+ });
+
+ it('rejects a package missing its declared main file', () => {
+ const buf = zipOf({ 'manifest.json': JSON.stringify(validManifest), 'other.js': 'x' });
+ expect(() => parsePluginPackage(buf)).toThrow(/missing its main file/i);
+ });
+
+ it('rejects too many files', () => {
+ const files: Record<string, string> = { 'manifest.json': JSON.stringify(validManifest), 'index.js': 'x' };
+ for (let i = 0; i < 5; i++) files[`f${i}.txt`] = 'x';
+ expect(() => parsePluginPackage(zipOf(files), { maxEntries: 3, maxTotalBytes: 1e9 })).toThrow(/too many/i);
+ });
+
+ it('rejects an archive that exceeds the size limit (before decompressing)', () => {
+ const buf = zipOf({ 'manifest.json': JSON.stringify(validManifest), 'index.js': 'a'.repeat(100) });
+ expect(() => parsePluginPackage(buf, { maxEntries: 100, maxTotalBytes: 10 })).toThrow(/size limit/i);
+ });
+});
diff --git a/src/modules/plugins/plugin-installer.ts b/src/modules/plugins/plugin-installer.ts
new file mode 100644
index 000000000..55746d26f
--- /dev/null
+++ b/src/modules/plugins/plugin-installer.ts
@@ -0,0 +1,99 @@
+import AdmZip from 'adm-zip';
+import * as path from 'path';
+import { BadRequestException } from '@nestjs/common';
+import { PluginManifest, PluginType } from '../../core/plugins';
+
+export interface PackageLimits {
+ /** Max number of files in the archive (cheap zip-bomb / fork-bomb guard). */
+ maxEntries: number;
+ /** Max total uncompressed bytes (checked against the zip headers BEFORE decompressing). */
+ maxTotalBytes: number;
+}
+
+export const DEFAULT_PACKAGE_LIMITS: PackageLimits = { maxEntries: 200, maxTotalBytes: 20 * 1024 * 1024 };
+
+/** Plugin ids that ship built-in and must never be shadowed by an uploaded package. */
+export const RESERVED_PLUGIN_IDS = new Set(['whatsapp-web.js', 'baileys', 'auto-reply', 'translation']);
+
+/** Only extensions are user-installable; engines (and other tiers) are built-in by design. */
+export const INSTALLABLE_TYPES = new Set<string>([PluginType.EXTENSION]);
+
+const SAFE_ID = /^[a-z0-9][a-z0-9._-]*$/i;
+const REQUIRED_FIELDS = ['id', 'name', 'version', 'type', 'main'] as const;
+
+export interface ParsedPackage {
+ manifest: PluginManifest;
+ /** Files to write under the plugin directory, relative to the package root, zip-slip-safe. */
+ entries: { relPath: string; data: Buffer }[];
+}
+
+/**
+ * Parse + validate an uploaded plugin `.zip` without touching the filesystem. Locates the package
+ * root (the shallowest `manifest.json`, so both a flat zip and a single-folder zip work), validates
+ * the manifest and id, and resolves every file path defensively (rejects absolute / `..` escapes and
+ * over-size archives). The caller writes the returned entries; this function decides what is safe.
+ */
+export function parsePluginPackage(buffer: Buffer, limits: PackageLimits = DEFAULT_PACKAGE_LIMITS): ParsedPackage {
+ let zip: AdmZip;
+ try {
+ zip = new AdmZip(buffer);
+ } catch {
+ throw new BadRequestException('Uploaded file is not a valid .zip archive');
+ }
+
+ const files = zip.getEntries().filter(e => !e.isDirectory);
+ if (files.length === 0) throw new BadRequestException('The archive is empty');
+ if (files.length > limits.maxEntries) throw new BadRequestException('The archive has too many files');
+
+ // Package root = directory of the shallowest manifest.json (handles flat and single-folder zips).
+ const manifestEntry = files
+ .filter(e => path.posix.basename(e.entryName) === 'manifest.json')
+ .sort((a, b) => a.entryName.split('/').length - b.entryName.split('/').length)[0];
+ if (!manifestEntry) throw new BadRequestException('The archive has no manifest.json');
+ const dir = path.posix.dirname(manifestEntry.entryName);
+ const prefix = dir === '.' ? '' : dir + '/';
+
+ let manifest: PluginManifest;
+ try {
+ manifest = JSON.parse(manifestEntry.getData().toString('utf-8')) as PluginManifest;
+ } catch {
+ throw new BadRequestException('manifest.json is not valid JSON');
+ }
+ for (const field of REQUIRED_FIELDS) {
+ if (!manifest[field]) throw new BadRequestException(`manifest.json is missing required field: ${field}`);
+ }
+ if (!SAFE_ID.test(manifest.id) || manifest.id.includes('..')) {
+ throw new BadRequestException(`Invalid plugin id: "${manifest.id}"`);
+ }
+ if (RESERVED_PLUGIN_IDS.has(manifest.id)) {
+ throw new BadRequestException(`Plugin id "${manifest.id}" is reserved by a built-in plugin`);
+ }
+ if (!INSTALLABLE_TYPES.has(manifest.type)) {
+ throw new BadRequestException(
+ `Plugin type "${manifest.type}" is not installable — only extension plugins can be installed (engines and other tiers are built-in).`,
+ );
+ }
+
+ // Size guard FIRST, off the declared header sizes, so a zip bomb is rejected before we decompress.
+ const packaged = files.filter(e => !prefix || e.entryName.startsWith(prefix));
+ const declared = packaged.reduce((sum, e) => sum + e.header.size, 0);
+ if (declared > limits.maxTotalBytes) throw new BadRequestException('The archive contents exceed the size limit');
+
+ const entries: { relPath: string; data: Buffer }[] = [];
+ for (const e of packaged) {
+ const relPath = e.entryName.slice(prefix.length);
+ if (!relPath) continue;
+ const norm = path.posix.normalize(relPath);
+ if (relPath.includes('\\') || norm.startsWith('..') || norm === '..' || path.posix.isAbsolute(norm)) {
+ throw new BadRequestException(`Unsafe path in archive: ${e.entryName}`);
+ }
+ entries.push({ relPath: norm, data: e.getData() });
+ }
+
+ const mainRel = path.posix.normalize(manifest.main);
+ if (!entries.some(en => en.relPath === mainRel)) {
+ throw new BadRequestException(`The archive is missing its main file: ${manifest.main}`);
+ }
+
+ return { manifest, entries };
+}
diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.ts
index 7e892444b..b1d48b8ba 100644
--- a/src/modules/plugins/plugins.controller.ts
+++ b/src/modules/plugins/plugins.controller.ts
@@ -1,10 +1,26 @@
-import { Controller, Get, Post, Put, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';
-import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
+import {
+ Controller,
+ Get,
+ Post,
+ Put,
+ Delete,
+ Param,
+ Body,
+ HttpCode,
+ HttpStatus,
+ UseInterceptors,
+ UploadedFile,
+} from '@nestjs/common';
+import { FileInterceptor } from '@nestjs/platform-express';
+import { ApiTags, ApiOperation, ApiResponse, ApiConsumes } from '@nestjs/swagger';
import { PluginsService } from './plugins.service';
import { PluginDto, PluginConfigDto } from './dto/plugin.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
+/** Max accepted upload size for a plugin package (compressed). */
+const MAX_PLUGIN_UPLOAD_BYTES = 5 * 1024 * 1024;
+
@ApiTags('plugins')
@Controller('plugins')
export class PluginsController {
@@ -18,6 +34,18 @@ export class PluginsController {
return this.pluginsService.findAll();
}
+ @Post('install')
+ @RequireRole(ApiKeyRole.ADMIN)
+ @UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_PLUGIN_UPLOAD_BYTES } }))
+ @ApiConsumes('multipart/form-data')
+ @ApiOperation({ summary: 'Install a plugin from an uploaded .zip package' })
+ @ApiResponse({ status: 201, description: 'Plugin installed' })
+ @ApiResponse({ status: 400, description: 'Invalid package' })
+ @ApiResponse({ status: 409, description: 'Plugin already installed' })
+ install(@UploadedFile() file: { buffer?: Buffer }): PluginDto {
+ return this.pluginsService.install(file);
+ }
+
@Get(':id')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Get plugin by ID' })
@@ -53,6 +81,16 @@ export class PluginsController {
return this.pluginsService.updateConfig(id, configDto.config);
}
+ @Delete(':id')
+ @RequireRole(ApiKeyRole.ADMIN)
+ @ApiOperation({ summary: 'Uninstall a plugin (removes its files; built-ins are protected)' })
+ @ApiResponse({ status: 200, description: 'Plugin uninstalled' })
+ @ApiResponse({ status: 400, description: 'Cannot uninstall (e.g. built-in)' })
+ @ApiResponse({ status: 404, description: 'Plugin not found' })
+ async uninstall(@Param('id') id: string): Promise<{ success: boolean; message: string }> {
+ return await this.pluginsService.uninstall(id);
+ }
+
@Get(':id/health')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Check plugin health' })
diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.ts
new file mode 100644
index 000000000..7c3ca6191
--- /dev/null
+++ b/src/modules/plugins/plugins.service.spec.ts
@@ -0,0 +1,82 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import AdmZip from 'adm-zip';
+import { ConfigService } from '@nestjs/config';
+import { ModuleRef } from '@nestjs/core';
+import { PluginsService } from './plugins.service';
+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
+import { PluginStorageService } from '../../core/plugins/plugin-storage.service';
+import { HookManager } from '../../core/hooks';
+
+const manifest = { id: 'svc-plg', name: 'Svc Plugin', version: '1.0.0', type: 'extension', main: 'index.js' };
+
+function pkg(over: Record<string, unknown> = {}): Buffer {
+ const z = new AdmZip();
+ z.addFile('manifest.json', Buffer.from(JSON.stringify({ ...manifest, ...over })));
+ z.addFile('index.js', Buffer.from('module.exports = class {};'));
+ return z.toBuffer();
+}
+
+describe('PluginsService — install / uninstall (real loader + disk)', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let loader: PluginLoaderService;
+ let service: PluginsService;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-svc-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ loader = new PluginLoaderService(
+ config,
+ new HookManager(),
+ new PluginStorageService(config),
+ {} as unknown as ModuleRef,
+ );
+ service = new PluginsService(loader);
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ it('installs a valid package — writes the files, loads it, reports builtIn:false', () => {
+ const dto = service.install({ buffer: pkg() });
+
+ expect(dto.id).toBe('svc-plg');
+ expect(dto.status).toBe('installed');
+ expect(dto.builtIn).toBe(false);
+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg', 'index.js'))).toBe(true);
+ expect(loader.getPlugin('svc-plg')).toBeDefined();
+ });
+
+ it('rejects an empty upload', () => {
+ expect(() => service.install({ buffer: Buffer.alloc(0) })).toThrow(/no plugin file/i);
+ });
+
+ it('rejects a duplicate install (already installed)', () => {
+ service.install({ buffer: pkg() });
+ expect(() => service.install({ buffer: pkg() })).toThrow(/already installed/i);
+ });
+
+ it('does not leave a directory behind when the package is invalid', () => {
+ // Reserved id is rejected by the parser before anything is written.
+ expect(() => service.install({ buffer: pkg({ id: 'baileys' }) })).toThrow(/reserved/i);
+ expect(fs.existsSync(path.join(pluginsDir, 'baileys'))).toBe(false);
+ });
+
+ it('uninstalls a user plugin — removes its files, registry entry, and runtime instance', async () => {
+ service.install({ buffer: pkg() });
+
+ const res = await service.uninstall('svc-plg');
+
+ expect(res.success).toBe(true);
+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg'))).toBe(false);
+ expect(loader.getPlugin('svc-plg')).toBeUndefined();
+ });
+
+ it('uninstalling an unknown plugin throws NotFound', async () => {
+ await expect(service.uninstall('nope')).rejects.toThrow(/not found/i);
+ });
+});
diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.ts
index 804241bb8..2418356c5 100644
--- a/src/modules/plugins/plugins.service.ts
+++ b/src/modules/plugins/plugins.service.ts
@@ -1,7 +1,10 @@
-import { Injectable, NotFoundException } from '@nestjs/common';
+import { Injectable, NotFoundException, BadRequestException, ConflictException, HttpException } from '@nestjs/common';
+import * as fs from 'fs';
+import * as path from 'path';
import { PluginLoaderService, PluginStatus } from '../../core/plugins';
import { PluginDto } from './dto/plugin.dto';
import { redactSecretConfig, restoreSecretConfig } from './redact-config';
+import { parsePluginPackage } from './plugin-installer';
@Injectable()
export class PluginsService {
@@ -19,7 +22,7 @@ export class PluginsService {
author: plugin.manifest.author,
status: plugin.status,
config: redactSecretConfig(plugin.config, plugin.manifest.configSchema),
- builtIn: plugin.manifest.id === 'whatsapp-web.js', // Built-in engines
+ builtIn: this.pluginLoader.isBuiltIn(plugin.manifest.id),
provides: plugin.manifest.provides ?? [],
configSchema: plugin.manifest.configSchema,
loadedAt: plugin.loadedAt?.toISOString(),
@@ -44,7 +47,7 @@ export class PluginsService {
author: plugin.manifest.author,
status: plugin.status,
config: redactSecretConfig(plugin.config, plugin.manifest.configSchema),
- builtIn: plugin.manifest.id === 'whatsapp-web.js',
+ builtIn: this.pluginLoader.isBuiltIn(plugin.manifest.id),
provides: plugin.manifest.provides ?? [],
configSchema: plugin.manifest.configSchema,
loadedAt: plugin.loadedAt?.toISOString(),
@@ -118,6 +121,57 @@ export class PluginsService {
}
}
+ /** Install a plugin from an uploaded .zip: validate the package, write it to the plugins dir, and load it. */
+ install(file?: { buffer?: Buffer }): PluginDto {
+ if (!file?.buffer?.length) {
+ throw new BadRequestException('No plugin file uploaded');
+ }
+
+ const { manifest, entries } = parsePluginPackage(file.buffer);
+
+ if (this.pluginLoader.getPlugin(manifest.id)) {
+ throw new ConflictException(`Plugin "${manifest.id}" is already installed`);
+ }
+ const dir = path.join(this.pluginLoader.getPluginsDir(), manifest.id);
+ if (fs.existsSync(dir)) {
+ throw new ConflictException(`A plugin directory "${manifest.id}" already exists`);
+ }
+
+ // Write the validated entries then load; roll back the directory on any failure so a bad
+ // package never leaves a half-installed plugin behind.
+ try {
+ for (const entry of entries) {
+ const dest = path.join(dir, entry.relPath);
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ fs.writeFileSync(dest, entry.data);
+ }
+ this.pluginLoader.loadPlugin(dir);
+ } catch (error) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ if (error instanceof HttpException) throw error;
+ throw new BadRequestException(
+ `Failed to install plugin: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+
+ return this.findOne(manifest.id);
+ }
+
+ /** Uninstall an installed user plugin: disable, unload, and delete its files. Built-ins are protected. */
+ async uninstall(id: string): Promise<{ success: boolean; message: string }> {
+ const plugin = this.pluginLoader.getPlugin(id);
+ if (!plugin) {
+ throw new NotFoundException(`Plugin ${id} not found`);
+ }
+
+ try {
+ await this.pluginLoader.uninstallPlugin(id);
+ return { success: true, message: `Plugin ${id} uninstalled successfully` };
+ } catch (error) {
+ throw new BadRequestException(error instanceof Error ? error.message : String(error));
+ }
+ }
+
async healthCheck(id: string): Promise<{ healthy: boolean; message?: string }> {
const plugin = this.pluginLoader.getPlugin(id);
diff --git a/test/fixtures/sandbox/cap-echo-plugin.cjs b/test/fixtures/sandbox/cap-echo-plugin.cjs
new file mode 100644
index 000000000..f4c49d449
--- /dev/null
+++ b/test/fixtures/sandbox/cap-echo-plugin.cjs
@@ -0,0 +1,11 @@
+// Sandbox fixture: exercises the capability bridge. onEnable calls a host capability and only
+// resolves if it gets the expected result back — so a broken round-trip surfaces as a lifecycle
+// rejection in the integration test.
+module.exports = class CapEchoPlugin {
+ async onEnable(ctx) {
+ const result = await ctx.messages.sendText('s', 'c', 'hi');
+ if (!result || result.messageId !== 'wamid') {
+ throw new Error('unexpected capability result: ' + JSON.stringify(result));
+ }
+ }
+};
diff --git a/test/fixtures/sandbox/ctx-aware-plugin.cjs b/test/fixtures/sandbox/ctx-aware-plugin.cjs
new file mode 100644
index 000000000..843f4c336
--- /dev/null
+++ b/test/fixtures/sandbox/ctx-aware-plugin.cjs
@@ -0,0 +1,7 @@
+// Sandbox fixture: uses ctx.logger and ctx.config (and ctx.pluginId) to prove the bridged context
+// is complete — the log surfaces on the host via onLog, carrying the static config.
+module.exports = class CtxAwarePlugin {
+ async onEnable(ctx) {
+ ctx.logger.log('hello from ' + ctx.pluginId, { greeting: ctx.config.greeting });
+ }
+};
diff --git a/test/fixtures/sandbox/echo-plugin.cjs b/test/fixtures/sandbox/echo-plugin.cjs
new file mode 100644
index 000000000..93718b3cb
--- /dev/null
+++ b/test/fixtures/sandbox/echo-plugin.cjs
@@ -0,0 +1,10 @@
+// Trivial lifecycle plugin for the sandbox worker integration test. A clean return from each
+// lifecycle method signals success to the host (no capability context is used in phase B1).
+module.exports = class EchoPlugin {
+ async onEnable() {
+ /* no-op */
+ }
+ async onDisable() {
+ /* no-op */
+ }
+};
diff --git a/test/fixtures/sandbox/hook-hang-plugin.cjs b/test/fixtures/sandbox/hook-hang-plugin.cjs
new file mode 100644
index 000000000..e27b07316
--- /dev/null
+++ b/test/fixtures/sandbox/hook-hang-plugin.cjs
@@ -0,0 +1,7 @@
+// Sandbox fixture: a hook handler that never resolves, to prove the host's per-handler timeout lets
+// the chain proceed instead of stalling on a wedged untrusted plugin.
+module.exports = class HookHangPlugin {
+ async onEnable(ctx) {
+ ctx.registerHook('message:received', () => new Promise(() => {}));
+ }
+};
diff --git a/test/fixtures/sandbox/hook-plugin.cjs b/test/fixtures/sandbox/hook-plugin.cjs
new file mode 100644
index 000000000..c99e7a43d
--- /dev/null
+++ b/test/fixtures/sandbox/hook-plugin.cjs
@@ -0,0 +1,10 @@
+// Sandbox fixture: registers a message:received hook that swallows the event and tags the data,
+// so the integration test can assert the full hook round-trip (host dispatch -> worker handler).
+module.exports = class HookPlugin {
+ async onEnable(ctx) {
+ ctx.registerHook('message:received', async (hookCtx) => ({
+ continue: false,
+ data: { ...hookCtx.data, seen: true },
+ }));
+ }
+};
diff --git a/test/fixtures/sandbox/runaway-plugin.cjs b/test/fixtures/sandbox/runaway-plugin.cjs
new file mode 100644
index 000000000..9c98435f0
--- /dev/null
+++ b/test/fixtures/sandbox/runaway-plugin.cjs
@@ -0,0 +1,11 @@
+// Sandbox fixture: a plugin that wedges the worker in an infinite loop. Proves the host can force-
+// terminate a runaway untrusted plugin (the loop blocks the worker event loop, so cooperative
+// shutdown is impossible — only terminate() reclaims it).
+module.exports = class RunawayPlugin {
+ async onEnable() {
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ /* spin forever */
+ }
+ }
+};