Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): sandboxed-iframe config UI (B-full) (#440)
Yudhi Armyndharis0cb666fcab57
diff --git a/dashboard/src/pages/Plugins.css b/dashboard/src/pages/Plugins.cssindex 761cf7abe..f3c626a38 100644--- a/dashboard/src/pages/Plugins.css+++ b/dashboard/src/pages/Plugins.css@@ -561,6 +561,29 @@color: var(--primary);}+/* Sandboxed-iframe config editor (B-full). */+.plugin-config-ui-frame {+ display: block;+ width: 100%;+ border: 1px solid var(--border);+ border-radius: 8px;+ background: var(--bg-white);+}++.config-ui-status {+ display: flex;+ align-items: center;+ justify-content: center;+ min-height: 200px;+ color: var(--text-muted);+}++.config-ui-error {+ padding: 1rem;+ text-align: center;+ color: var(--danger, #e5484d);+}+.config-form .form-group small {display: block;margin-top: 0.4rem;diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex 177ef762f..5ff9df3b9 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';import { useQueryClient } from '@tanstack/react-query';import {@@ -240,6 +240,91 @@ function ConfigField({);}+/**+ * Renders a plugin's sandboxed-iframe config editor. The entry HTML is fetched WITH the API key+ * (which never enters the iframe) and injected as `srcdoc` into a `sandbox="allow-scripts"` iframe+ * (opaque origin — no access to the parent). The editor talks to the host over a postMessage bridge:+ * iframe → host { type: 'config:get' } → host → iframe { type: 'config:value', config, schema }+ * iframe → host { type: 'config:save', config } → host → iframe { type: 'config:saved' } | { type: 'config:error', message }+ * The host makes the authenticated PUT (secret redact/restore applies); the iframe only ever sees the+ * already-redacted config.+ */+function PluginConfigUi({ plugin }: { plugin: Plugin }) {+ const { t } = useTranslation();+ const toast = useToast();+ const queryClient = useQueryClient();+ const iframeRef = useRef<HTMLIFrameElement>(null);+ const [html, setHtml] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ pluginsApi+ .getConfigUi(plugin.id)+ .then(h => {+ if (!cancelled) setHtml(h);+ })+ .catch(e => {+ if (!cancelled) setError(e instanceof Error ? e.message : t('common.unknownError'));+ });+ return () => {+ cancelled = true;+ };+ }, [plugin.id, t]);++ useEffect(() => {+ const onMessage = (e: MessageEvent) => {+ const frame = iframeRef.current?.contentWindow;+ if (!frame || e.source !== frame) return; // only our sandboxed iframe (its origin is opaque 'null')+ const msg = e.data as { type?: string; config?: Record<string, unknown> };+ const post = (m: unknown) => frame.postMessage(m, '*');+ if (msg?.type === 'config:get') {+ // Only expose schema-DECLARED fields (already secret-redacted by the API). An undeclared key+ // may hold a secret the host can't mask, so it never reaches the untrusted iframe; with no+ // schema there is nothing safe to send. The plugin must declare its fields to pre-fill them.+ const props = plugin.configSchema?.properties;+ const safeConfig = props+ ? Object.fromEntries(Object.keys(props).flatMap(k => (k in plugin.config ? [[k, plugin.config[k]]] : [])))+ : {};+ post({ type: 'config:value', config: safeConfig, schema: plugin.configSchema });+ } else if (msg?.type === 'config:save') {+ void (async () => {+ try {+ await pluginsApi.updateConfig(plugin.id, msg.config ?? {});+ void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });+ post({ type: 'config:saved' });+ toast.success(t('plugins.toasts.savedTitle'), t('plugins.toasts.savedDesc'));+ } catch (err) {+ const message = err instanceof Error ? err.message : t('common.unknownError');+ post({ type: 'config:error', message });+ toast.error(t('plugins.toasts.saveFailed'), message);+ }+ })();+ }+ };+ window.addEventListener('message', onMessage);+ return () => window.removeEventListener('message', onMessage);+ }, [plugin, queryClient, t, toast]);++ if (error) return <div className="config-ui-status config-ui-error">{error}</div>;+ if (html === null)+ return (+ <div className="config-ui-status">+ <Loader2 size={24} className="animate-spin" />+ </div>+ );+ return (+ <iframe+ ref={iframeRef}+ className="plugin-config-ui-frame"+ sandbox="allow-scripts"+ srcDoc={html}+ title={plugin.name}+ style={{ height: plugin.configUi?.height ?? 600 }}+ />+ );+}+export default function Plugins() {const { t } = useTranslation();useDocumentTitle(t('plugins.title'));@@ -901,6 +986,8 @@ export default function Plugins() {</div></div></>+ ) : configPlugin.configUi ? (+ <PluginConfigUi plugin={configPlugin} />) : configPlugin.configSchema && Object.keys(configPlugin.configSchema.properties).length > 0 ? (<div className="config-form">{Object.entries(configPlugin.configSchema.properties).map(([key, field]) => (@@ -929,7 +1016,8 @@ export default function Plugins() {<button className="btn-primary" onClick={handleSaveConfig} disabled={savingConfig}>{savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}</button>- ) : configPlugin.configSchema && Object.keys(configPlugin.configSchema.properties).length > 0 ? (+ ) : configPlugin.configUi ? null : configPlugin.configSchema &&+ Object.keys(configPlugin.configSchema.properties).length > 0 ? (<button className="btn-primary" onClick={handleSaveSchemaConfig} disabled={savingConfig}>{savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}</button>diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex f75052846..0bdb12eee 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -321,6 +321,29 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<return response.json();}+/** Like {@link request} but returns the raw response text — e.g. a plugin's HTML config-UI bundle. */+async function requestText(endpoint: string): Promise<string> {+ const apiKey = sessionStorage.getItem('openwa_api_key');+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {+ headers: { ...(apiKey ? { 'X-API-Key': apiKey } : {}) },+ });++ if (response.status === 401) {+ sessionStorage.removeItem('openwa_api_key');+ if (typeof window !== 'undefined') {+ window.location.assign('/');+ return new Promise<string>(() => {});+ }+ }++ if (!response.ok) {+ const error = await response.json().catch(() => ({}));+ throw new Error(error.message || `HTTP ${response.status}`);+ }++ return response.text();+}+// =============================================================================// Session API// =============================================================================@@ -617,6 +640,8 @@ export interface Plugin {provides: string[];/** Declared config fields, when the plugin exposes a schema (drives the dashboard config form). */configSchema?: PluginConfigSchema;+ /** When set, the plugin ships a sandboxed-iframe config editor (preferred over configSchema). */+ configUi?: { entry: string; height?: number };loadedAt?: string;enabledAt?: string;error?: string;@@ -682,6 +707,8 @@ export const pluginsApi = {updateFromUrl: (id: string, url: string) =>request<Plugin>(`/plugins/${id}/update`, { method: 'POST', body: JSON.stringify({ url }) }),catalog: () => request<CatalogPlugin[]>('/plugins/catalog'),+ /** Fetch a plugin's sandboxed config-UI entry HTML (the API key stays here, in the parent). */+ getConfigUi: (id: string) => requestText(`/plugins/${id}/config-ui`),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/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 692e625b1..e72085998 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -52,6 +52,13 @@ export interface PluginManifest {// Configuration schema (optional, for UI generation)configSchema?: PluginConfigSchema;+ // Optional sandboxed-iframe config editor. `entry` is a plugin-relative path to a self-contained+ // HTML file (inline JS/CSS — a sandboxed opaque-origin iframe can't load subresources). Served by+ // the host via the authenticated GET /plugins/:id/config-ui and injected as an iframe `srcdoc`; the+ // editor exchanges config over a postMessage bridge (the API key never reaches the iframe). When+ // present, the dashboard prefers it over the declarative `configSchema` form.+ configUi?: { entry: string; height?: number };+// Hooks this plugin listens tohooks?: HookEvent[];diff --git a/src/modules/plugins/dto/plugin.dto.ts b/src/modules/plugins/dto/plugin.dto.tsindex 1e6c28aa5..4457bc7eb 100644--- a/src/modules/plugins/dto/plugin.dto.ts+++ b/src/modules/plugins/dto/plugin.dto.ts@@ -43,6 +43,9 @@ export class PluginDto {@ApiPropertyOptional({ description: 'Configuration schema' })configSchema?: PluginConfigSchema;+ @ApiPropertyOptional({ description: 'Sandboxed-iframe config editor (entry HTML + optional height)' })+ configUi?: { entry: string; height?: number };+@ApiPropertyOptional({ description: 'When the plugin was loaded' })loadedAt?: string;diff --git a/src/modules/plugins/plugins.controller.spec.ts b/src/modules/plugins/plugins.controller.spec.tsindex d4e39840c..41be06cd2 100644--- a/src/modules/plugins/plugins.controller.spec.ts+++ b/src/modules/plugins/plugins.controller.spec.ts@@ -9,7 +9,7 @@ describe('PluginsController authorization', () => {// Plugin reads expose installed versions, non-secret config, and health/error text — privileged// inventory on par with the ADMIN-gated write routes and the InfraController convention. A// VIEWER/OPERATOR key (or a session-scoped key) must not be able to enumerate it via the raw API.- const adminOnly = ['findAll', 'findOne', 'healthCheck', 'enable', 'disable', 'updateConfig'] as const;+ const adminOnly = ['findAll', 'findOne', 'healthCheck', 'enable', 'disable', 'updateConfig', 'getConfigUi'] as const;it.each(adminOnly)('%s requires the ADMIN role', method => {const handler = PluginsController.prototype[method];diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.tsindex 74916b3a3..4cf0cd4eb 100644--- a/src/modules/plugins/plugins.controller.ts+++ b/src/modules/plugins/plugins.controller.ts@@ -6,6 +6,7 @@ import {Delete,Param,Body,+ Header,HttpCode,HttpStatus,UseInterceptors,@@ -102,6 +103,21 @@ export class PluginsController {return this.pluginsService.updateConfig(id, configDto.config);}+ // The dashboard fetches this WITH the API key and injects the body as an iframe `srcdoc` (sandboxed,+ // opaque origin). Served as untrusted HTML, so it's CSP-sandboxed + nosniff in case it's ever loaded+ // directly as a document (it can't be in a browser — navigations don't carry the X-API-Key header).+ @Get(':id/config-ui')+ @RequireRole(ApiKeyRole.ADMIN)+ @Header('Content-Type', 'text/html; charset=utf-8')+ @Header('Content-Security-Policy', 'sandbox')+ @Header('X-Content-Type-Options', 'nosniff')+ @ApiOperation({ summary: "Serve a plugin's sandboxed config-UI entry HTML (for an iframe srcdoc)" })+ @ApiResponse({ status: 200, description: 'Config UI HTML' })+ @ApiResponse({ status: 404, description: 'Plugin not found or has no config UI' })+ getConfigUi(@Param('id') id: string): string {+ return this.pluginsService.getConfigUiHtml(id);+ }+@Put(':id/sessions')@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: "Set which sessions a session-scoped plugin is activated for (['*'] = all)" })diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex 19d77383f..fe8635f44 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -121,3 +121,85 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {enableSpy.mockRestore();});});++describe('PluginsService — getConfigUiHtml (sandboxed config editor)', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let loader: PluginLoaderService;+ let service: PluginsService;++ const HTML = '<!doctype html><title>cfg</title><script>parent.postMessage({type:"config:get"},"*")</script>';++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-cfgui-'));+ 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, config);+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ function installUi(over: Record<string, unknown> = {}, files: Record<string, string> = {}): void {+ const z = new AdmZip();+ z.addFile(+ 'manifest.json',+ Buffer.from(JSON.stringify({ ...manifest, id: 'cfgui-plg', configUi: { entry: 'config/index.html' }, ...over })),+ );+ z.addFile('index.js', Buffer.from('module.exports = class {};'));+ for (const [p, c] of Object.entries(files)) z.addFile(p, Buffer.from(c));+ service.install({ buffer: z.toBuffer() });+ }++ it('serves the configUi entry HTML for an installed plugin', () => {+ installUi({}, { 'config/index.html': HTML });+ expect(service.getConfigUiHtml('cfgui-plg')).toBe(HTML);+ });++ it('exposes configUi on the DTO so the dashboard can render the iframe', () => {+ installUi({ configUi: { entry: 'config/index.html', height: 480 } }, { 'config/index.html': HTML });+ expect(service.findOne('cfgui-plg').configUi).toEqual({ entry: 'config/index.html', height: 480 });+ });++ it('throws NotFound when the plugin does not exist', () => {+ expect(() => service.getConfigUiHtml('ghost')).toThrow(/not found/i);+ });++ it('throws NotFound when the plugin declares no configUi', () => {+ const z = new AdmZip();+ z.addFile('manifest.json', Buffer.from(JSON.stringify({ ...manifest, id: 'no-ui' })));+ z.addFile('index.js', Buffer.from('module.exports = class {};'));+ service.install({ buffer: z.toBuffer() });+ expect(() => service.getConfigUiHtml('no-ui')).toThrow(/config ui/i);+ });++ it('throws NotFound when the entry file is missing from the package', () => {+ installUi({ configUi: { entry: 'config/missing.html' } }, { 'config/index.html': HTML });+ expect(() => service.getConfigUiHtml('cfgui-plg')).toThrow(/not found/i);+ });++ it('rejects a configUi entry that escapes the plugin directory (404, not a 500)', () => {+ installUi({ configUi: { entry: '../../../etc/passwd' } }, { 'config/index.html': HTML });+ expect(() => service.getConfigUiHtml('cfgui-plg')).toThrow(/not found/i);+ });++ it('rejects a non-string configUi entry from an untrusted manifest', () => {+ installUi({ configUi: { entry: 123 } }, { 'config/index.html': HTML });+ expect(() => service.getConfigUiHtml('cfgui-plg')).toThrow(/config ui/i);+ });++ it('rejects a configUi entry that is a symlink escaping the plugin directory', () => {+ installUi({ configUi: { entry: 'config/escape.html' } }, { 'config/index.html': HTML });+ const outside = path.join(tmpDir, 'outside-secret.txt');+ fs.writeFileSync(outside, 'TOP SECRET');+ fs.symlinkSync(outside, path.join(pluginsDir, 'cfgui-plg', 'config', 'escape.html'));+ expect(() => service.getConfigUiHtml('cfgui-plg')).toThrow(/not found/i);+ });+});diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex e027fbba3..a8dcf83ad 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -2,7 +2,7 @@ import { Injectable, NotFoundException, BadRequestException, ConflictException,import { ConfigService } from '@nestjs/config';import * as fs from 'fs';import * as path from 'path';-import { PluginLoaderService, PluginStatus } from '../../core/plugins';+import { PluginLoaderService, PluginStatus, resolvePluginMainPath } from '../../core/plugins';import { PluginDto } from './dto/plugin.dto';import { redactSecretConfig, restoreSecretConfig } from './redact-config';import { parsePluginPackage } from './plugin-installer';@@ -34,6 +34,7 @@ export class PluginsService {builtIn: this.pluginLoader.isBuiltIn(plugin.manifest.id),provides: plugin.manifest.provides ?? [],configSchema: plugin.manifest.configSchema,+ configUi: plugin.manifest.configUi,sessionScoped: plugin.manifest.sessionScoped !== false,activeSessions: plugin.activeSessions ?? ['*'],loadedAt: plugin.loadedAt?.toISOString(),@@ -61,6 +62,7 @@ export class PluginsService {builtIn: this.pluginLoader.isBuiltIn(plugin.manifest.id),provides: plugin.manifest.provides ?? [],configSchema: plugin.manifest.configSchema,+ configUi: plugin.manifest.configUi,sessionScoped: plugin.manifest.sessionScoped !== false,activeSessions: plugin.activeSessions ?? ['*'],loadedAt: plugin.loadedAt?.toISOString(),@@ -147,6 +149,43 @@ export class PluginsService {}}+ /**+ * Read a plugin's sandboxed config-UI entry HTML (manifest `configUi.entry`). The dashboard fetches+ * this with the API key and injects it as an iframe `srcdoc`, so the file must be self-contained.+ * Path is escape-guarded against the plugin directory; the entry is plugin-author-supplied.+ */+ getConfigUiHtml(id: string): string {+ const plugin = this.pluginLoader.getPlugin(id);+ if (!plugin) {+ throw new NotFoundException(`Plugin ${id} not found`);+ }+ const entry = plugin.manifest.configUi?.entry;+ // `entry` is untrusted manifest JSON — a non-string (or escaping) value is treated as "no config+ // UI" (404), never a raw 500.+ if (!entry || typeof entry !== 'string') {+ throw new NotFoundException(`Plugin ${id} has no config UI`);+ }+ const base = path.resolve(this.pluginLoader.getPluginsDir(), id);+ let file: string;+ try {+ file = resolvePluginMainPath(this.pluginLoader.getPluginsDir(), id, entry);+ } catch {+ throw new NotFoundException(`Config UI entry not found for plugin ${id}`);+ }+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) {+ throw new NotFoundException(`Config UI entry not found for plugin ${id}`);+ }+ // Defense-in-depth: the lexical guard above is symlink-blind; resolve links on BOTH the file and+ // the plugin dir (so a symlinked tmp root like macOS /var→/private/var doesn't false-positive) and+ // re-check containment before reading an arbitrary host file into the main process and serving it.+ const real = fs.realpathSync(file);+ const realBase = fs.realpathSync(base);+ if (real !== realBase && !real.startsWith(realBase + path.sep)) {+ throw new NotFoundException(`Config UI entry not found for plugin ${id}`);+ }+ return fs.readFileSync(real, 'utf-8');+ }+/** 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) {