Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(dashboard): move the plugin config rules out of the page
Yudhi Armyndharis0faefc2b66be
diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex 858e852ea..a8c65ef81 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -1,6 +1,7 @@import { useState, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';import { localizePlugin } from '../utils/localizePlugin';+import { configUiSafeConfig, missingRequiredConfig, sparseSessionOverride } from '../utils/pluginConfigRules';import { coerceFieldInput, emptyForField } from '../utils/pluginConfigForm';import { useQueryClient } from '@tanstack/react-query';import {@@ -46,40 +47,6 @@ const pluginTypeIcons: Record<PluginType, typeof Puzzle> = {extension: Zap,};-/**- * Build a sparse per-session config override from a full edited config: include only non-secret keys- * whose value differs from the Global base (so untouched keys keep inheriting Global), plus every- * TOP-LEVEL secret key (the backend restores an untouched `***` to the stored per-session value, or- * drops it → the host's deep-merge then re-inherits it from Global). A key absent from the base whose- * value is just the empty default is skipped, so an untouched optional field never creates a spurious- * override. With no schema, the input is returned as-is.- *- * Inheritance of untouched secrets holds for top-level secret keys and secrets nested in an OBJECT- * (deep-merged). It does NOT hold for a `secret` column inside an array-of-rows: arrays are replaced- * wholesale at resolve time, so a first-time per-session override that edits any cell of such an array- * loses the untouched rows' secrets (they redact to `***`, the dashboard can't resend the real value).- * No bundled plugin ships that shape; a plugin needing per-session array secrets should re-enter them.- */-function sparseSessionOverride(full: Record<string, unknown>, plugin: Plugin): Record<string, unknown> {- const props = plugin.configSchema?.properties;- if (!props) return full;- const out: Record<string, unknown> = {};- for (const [key, field] of Object.entries(props)) {- if (!(key in full)) continue;- const val = full[key];- if (field.secret) {- out[key] = val;- continue;- }- if (JSON.stringify(val) === JSON.stringify(plugin.config[key])) continue; // unchanged → inherit Global- if (plugin.config[key] === undefined && JSON.stringify(val) === JSON.stringify(emptyForField(field))) {- continue; // untouched optional field with no Global value → don't pin a spurious empty override- }- out[key] = val;- }- return out;-}-/*** Renders one config field from a plugin's schema and reports edits via `onChange`. Recurses for* nested objects and array-of-rows. Module-scope (stable identity) so inputs keep focus across@@ -330,17 +297,12 @@ function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: str// schema there is nothing safe to send. The plugin must declare its fields to pre-fill them.// For a per-session editor (sessionId set), expose the resolved slice: the session's override// value where set, else the base value.- const props = plugin.configSchema?.properties;- const override = sessionId ? (plugin.sessionConfig?.[sessionId] ?? {}) : {};- const safeConfig = props- ? Object.fromEntries(- Object.keys(props).flatMap(k => {- if (sessionId && k in override) return [[k, override[k]]];- return k in plugin.config ? [[k, plugin.config[k]]] : [];- }),- )- : {};- post({ type: 'config:value', config: safeConfig, schema: plugin.configSchema, theme: resolvedTheme });+ post({+ type: 'config:value',+ config: configUiSafeConfig(plugin, sessionId),+ schema: plugin.configSchema,+ theme: resolvedTheme,+ });} else if (msg?.type === 'config:save') {void (async () => {try {@@ -602,17 +564,6 @@ export default function Plugins() {// INSIDE the sandbox with a raw "<id>: <field> is required" error and flips the card to ERROR.// Open the config modal instead so the user completes the fields first — cures the whole class// (after-hours `schedule`/`awayMessage`, faq-bot `rules`, any catalog plugin with required fields).- const missingRequiredConfig = (plugin: Plugin): string[] => {- const props = plugin.configSchema?.properties ?? {};- return Object.entries(props)- .filter(- ([key, field]) =>- field.required === true &&- (plugin.config[key] === undefined || plugin.config[key] === null || plugin.config[key] === ''),- )- .map(([key]) => key);- };-const handleToggle = async (plugin: Plugin) => {if (plugin.status !== 'enabled') {const missing = missingRequiredConfig(plugin);diff --git a/dashboard/src/utils/pluginConfigRules.test.ts b/dashboard/src/utils/pluginConfigRules.test.tsnew file mode 100644index 000000000..2b966fa61--- /dev/null+++ b/dashboard/src/utils/pluginConfigRules.test.ts@@ -0,0 +1,99 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { configUiSafeConfig, sparseSessionOverride, missingRequiredConfig } from './pluginConfigRules.ts';+import type { Plugin } from '../services/api';++const plugin = (over: Partial<Plugin> = {}): Plugin =>+ ({+ id: 'p',+ config: {},+ configSchema: { type: 'object', properties: {} },+ ...over,+ }) as Plugin;++const schema = (properties: Record<string, unknown>) => ({ type: 'object', properties }) as Plugin['configSchema'];++test('the config UI only ever sees SCHEMA-DECLARED keys', () => {+ // A plugin's stored config can hold keys its schema never declared. Sending the raw config would+ // hand those to an iframe the plugin itself controls.+ const p = plugin({+ configSchema: schema({ apiHost: { type: 'string' } }),+ config: { apiHost: 'https://x', leftoverFromOldVersion: 'secret-ish', hostWritten: 42 },+ });++ assert.deepEqual(configUiSafeConfig(p), { apiHost: 'https://x' });+});++test('no schema means nothing is safe to send', () => {+ const p = plugin({ configSchema: undefined, config: { anything: 'value' } });++ assert.deepEqual(configUiSafeConfig(p), {});+});++test('a declared key with no stored value is omitted rather than sent as undefined', () => {+ const p = plugin({ configSchema: schema({ a: { type: 'string' }, b: { type: 'string' } }), config: { a: '1' } });++ assert.deepEqual(configUiSafeConfig(p), { a: '1' });+});++test('a per-session editor sees the resolved slice: override where set, else base', () => {+ const p = plugin({+ configSchema: schema({ a: { type: 'string' }, b: { type: 'string' } }),+ config: { a: 'base-a', b: 'base-b' },+ sessionConfig: { s1: { a: 'override-a' } },+ } as Partial<Plugin>);++ assert.deepEqual(configUiSafeConfig(p, 's1'), { a: 'override-a', b: 'base-b' });+});++test('a sparse override keeps only what actually differs from Global', () => {+ const p = plugin({+ configSchema: schema({ changed: { type: 'string' }, same: { type: 'string' } }),+ config: { changed: 'old', same: 'unchanged' },+ });++ assert.deepEqual(sparseSessionOverride({ changed: 'new', same: 'unchanged' }, p), { changed: 'new' });+});++test('every top-level secret is always included, so the backend can restore or drop it', () => {+ const p = plugin({+ configSchema: schema({ token: { type: 'string', secret: true } }),+ config: { token: 'stored' },+ });++ // Identical to the base, and still sent: an untouched `***` is what the backend resolves.+ assert.deepEqual(sparseSessionOverride({ token: '***' }, p), { token: '***' });+});++test('an untouched optional field with no Global value does not pin a spurious override', () => {+ const p = plugin({ configSchema: schema({ note: { type: 'string' } }), config: {} });++ assert.deepEqual(sparseSessionOverride({ note: '' }, p), {});+});++test('a key the schema does not declare never reaches the override', () => {+ const p = plugin({ configSchema: schema({ a: { type: 'string' } }), config: {} });++ assert.deepEqual(sparseSessionOverride({ a: 'x', undeclared: 'y' }, p), { a: 'x' });+});++test('with no schema the input passes through unchanged', () => {+ const p = plugin({ configSchema: undefined });++ assert.deepEqual(sparseSessionOverride({ anything: 1 }, p), { anything: 1 });+});++test('missing required config lists the keys with no usable value', () => {+ const p = plugin({+ configSchema: schema({+ needed: { type: 'string', required: true },+ alsoNeeded: { type: 'string', required: true },+ blank: { type: 'string', required: true },+ optional: { type: 'string' },+ }),+ config: { needed: 'set', alsoNeeded: null, blank: '' },+ });++ // null and '' count as missing; a set value does not; optional is never reported.+ assert.deepEqual(missingRequiredConfig(p), ['alsoNeeded', 'blank']);+});diff --git a/dashboard/src/utils/pluginConfigRules.ts b/dashboard/src/utils/pluginConfigRules.tsnew file mode 100644index 000000000..e3c54f1eb--- /dev/null+++ b/dashboard/src/utils/pluginConfigRules.ts@@ -0,0 +1,79 @@+import { emptyForField } from './pluginConfigForm.ts';+import type { Plugin } from '../services/api';++/**+ * Config rules for the Plugins page, all three of which decide what leaves the browser.+ *+ * `configUiSafeConfig` is the one that matters most: it is the only thing standing between a plugin's+ * sandboxed config-UI iframe and the rest of the plugin's stored configuration. It ran inside a+ * `postMessage` handler, reachable only through an iframe, which is the least testable place in the+ * dashboard for the most security-relevant rule in it.+ */++/**+ * Everything the sandboxed config UI is allowed to see: SCHEMA-DECLARED keys only.+ *+ * A plugin's stored config can hold keys its schema never declared — left by an older version, or+ * written by the host. Sending the raw config would hand all of that to an iframe the plugin itself+ * controls. Filtering by the declared properties means a plugin can only ever read back what it asked+ * for; with no schema there is nothing safe to send at all.+ *+ * With `sessionId`, the resolved slice is exposed: the session's override where set, else the base.+ */+export function configUiSafeConfig(plugin: Plugin, sessionId?: string): Record<string, unknown> {+ const props = plugin.configSchema?.properties;+ if (!props) return {};+ const override = sessionId ? (plugin.sessionConfig?.[sessionId] ?? {}) : {};+ return Object.fromEntries(+ Object.keys(props).flatMap(k => {+ if (sessionId && k in override) return [[k, override[k]]];+ return k in plugin.config ? [[k, plugin.config[k]]] : [];+ }),+ );+}++/**+ * Build a sparse per-session config override from a full edited config: include only non-secret keys+ * whose value differs from the Global base (so untouched keys keep inheriting Global), plus every+ * TOP-LEVEL secret key (the backend restores an untouched `***` to the stored per-session value, or+ * drops it → the host's deep-merge then re-inherits it from Global). A key absent from the base whose+ * value is just the empty default is skipped, so an untouched optional field never creates a spurious+ * override. With no schema, the input is returned as-is.+ *+ * Inheritance of untouched secrets holds for top-level secret keys and secrets nested in an OBJECT+ * (deep-merged). It does NOT hold for a `secret` column inside an array-of-rows: arrays are replaced+ * wholesale at resolve time, so a first-time per-session override that edits any cell of such an array+ * loses the untouched rows' secrets (they redact to `***`, the dashboard can't resend the real value).+ * No bundled plugin ships that shape; a plugin needing per-session array secrets should re-enter them.+ */+export function sparseSessionOverride(full: Record<string, unknown>, plugin: Plugin): Record<string, unknown> {+ const props = plugin.configSchema?.properties;+ if (!props) return full;+ const out: Record<string, unknown> = {};+ for (const [key, field] of Object.entries(props)) {+ if (!(key in full)) continue;+ const val = full[key];+ if (field.secret) {+ out[key] = val;+ continue;+ }+ if (JSON.stringify(val) === JSON.stringify(plugin.config[key])) continue; // unchanged → inherit Global+ if (plugin.config[key] === undefined && JSON.stringify(val) === JSON.stringify(emptyForField(field))) {+ continue; // untouched optional field with no Global value → don't pin a spurious empty override+ }+ out[key] = val;+ }+ return out;+}++/** Required schema keys the plugin has no usable value for — enabling without these fails at load. */+export function missingRequiredConfig(plugin: Plugin): string[] {+ const props = plugin.configSchema?.properties ?? {};+ return Object.entries(props)+ .filter(+ ([key, field]) =>+ field.required === true &&+ (plugin.config[key] === undefined || plugin.config[key] === null || plugin.config[key] === ''),+ )+ .map(([key]) => key);+}