Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): richer config schema + recursive dashboard form (#439)
Yudhi Armyndharis3a788225a42b
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 125e9baaf..37ad1977a 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -647,7 +647,8 @@"sessionDataPath": "مسار بيانات الجلسة","browserArgs": "مُعطيات المتصفح","noOptions": "لا توجد خيارات إعداد لهذه الإضافة",- "save": "حفظ الإعدادات"+ "save": "حفظ الإعدادات",+ "addItem": "إضافة"},"rail": {"engine": "المحرك النشط",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 130cd96e7..0f774cb2d 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -647,7 +647,8 @@"sessionDataPath": "Session Data Path","browserArgs": "Browser Arguments","noOptions": "No configuration options available for this plugin",- "save": "Save Configuration"+ "save": "Save Configuration",+ "addItem": "Add"},"rail": {"engine": "Active engine",@@ -677,4 +678,4 @@"uninstallFailed": "Uninstall failed"}}-}\ No newline at end of file+}diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex a3e020346..6a1b01e23 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -647,7 +647,8 @@"sessionDataPath": "Ruta de datos de sesión","browserArgs": "Argumentos del navegador","noOptions": "No hay opciones de configuración disponibles para este plugin",- "save": "Guardar configuración"+ "save": "Guardar configuración",+ "addItem": "Añadir"},"rail": {"engine": "Motor activo",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex d361e4bf0..044b6e7e0 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -647,7 +647,8 @@"sessionDataPath": "Chemin des données de session","browserArgs": "Arguments du navigateur","noOptions": "Aucune option de configuration disponible pour ce plugin",- "save": "Enregistrer la configuration"+ "save": "Enregistrer la configuration",+ "addItem": "Ajouter"},"rail": {"engine": "Moteur actif",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 3d28c5104..2be44e809 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -647,7 +647,8 @@"sessionDataPath": "נתיב נתוני Session","browserArgs": "ארגומנטים של הדפדפן","noOptions": "אין אפשרויות הגדרה זמינות עבור תוסף זה",- "save": "שמירת תצורה"+ "save": "שמירת תצורה",+ "addItem": "הוספה"},"rail": {"engine": "מנוע פעיל",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 2005cbe15..f5f9a6012 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -647,7 +647,8 @@"sessionDataPath": "Percorso Dati Sessione","browserArgs": "Argomenti del Browser","noOptions": "Nessuna opzione di configurazione disponibile per questo plugin",- "save": "Salva Configurazione"+ "save": "Salva Configurazione",+ "addItem": "Aggiungi"},"rail": {"engine": "Motore attivo",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex 36100967b..7afe053fe 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -647,7 +647,8 @@"sessionDataPath": "సెషన్ డేటా పాత్","browserArgs": "బ్రౌజర్ ఆర్గుమెంట్స్","noOptions": "ఈ ప్లగిన్ కోసం ఎలాంటి కాన్ఫిగరేషన్ ఆప్షన్లు అందుబాటులో లేవు",- "save": "కాన్ఫిగరేషన్ను సేవ్ చేయి"+ "save": "కాన్ఫిగరేషన్ను సేవ్ చేయి",+ "addItem": "జోడించు"},"rail": {"engine": "యాక్టివ్ ఇంజిన్",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex 8fc1f064f..500c54483 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -647,7 +647,8 @@"sessionDataPath": "会话数据路径","browserArgs": "浏览器参数","noOptions": "此插件没有可用配置项",- "save": "保存配置"+ "save": "保存配置",+ "addItem": "添加"},"rail": {"engine": "活动引擎",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 28dfc79c9..c368c358a 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -647,7 +647,8 @@"sessionDataPath": "工作階段資料路徑","browserArgs": "瀏覽器參數","noOptions": "此外掛沒有可用設定選項",- "save": "儲存設定"+ "save": "儲存設定",+ "addItem": "新增"},"rail": {"engine": "使用中的引擎",diff --git a/dashboard/src/pages/Plugins.css b/dashboard/src/pages/Plugins.cssindex a053a3fb6..761cf7abe 100644--- a/dashboard/src/pages/Plugins.css+++ b/dashboard/src/pages/Plugins.css@@ -452,7 +452,8 @@}.config-form .form-group input,-.config-form .form-group select {+.config-form .form-group select,+.config-form .form-group textarea {width: 100%;padding: 0.75rem 1rem;border: 1px solid var(--border);@@ -463,14 +464,103 @@box-sizing: border-box;}+.config-form .form-group textarea {+ font-family: inherit;+ resize: vertical;+ min-height: 4.5rem;+}+.config-form .form-group input:focus,-.config-form .form-group select:focus {+.config-form .form-group select:focus,+.config-form .form-group textarea:focus {outline: none;border-color: var(--primary);background: var(--bg-white);box-shadow: 0 0 0 3px rgba(37, 211, 102, 0.1);}+/* Nested object — a bordered group of sub-fields. */+.config-form .config-fieldset {+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 0.75rem 1rem 0.25rem;+ margin: 0 0 1.25rem;+ min-width: 0;+}++.config-form .config-fieldset > legend {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--text-secondary);+ padding: 0 0.4rem;+}++/* Array-of-rows — repeating rows with add/remove. */+.config-form .config-array {+ margin-bottom: 1.25rem;+}++.config-form .config-array > label {+ display: block;+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--text-secondary);+ margin-bottom: 0.5rem;+}++.config-form .config-array-row {+ display: flex;+ align-items: flex-start;+ gap: 0.5rem;+ margin-bottom: 0.5rem;+}++.config-form .config-array-row-body {+ flex: 1;+ min-width: 0;+ border-left: 2px solid var(--border);+ padding-left: 0.75rem;+}++.config-form .config-array-remove {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0.45rem;+ border: 1px solid var(--border);+ border-radius: 8px;+ background: var(--bg-light);+ color: var(--danger, #e5484d);+ cursor: pointer;+ transition: all 0.2s;+}++.config-form .config-array-remove:hover {+ background: var(--danger, #e5484d);+ color: #fff;+ border-color: var(--danger, #e5484d);+}++.config-form .config-array-add {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ padding: 0.5rem 0.85rem;+ border: 1px dashed var(--border);+ border-radius: 8px;+ background: transparent;+ color: var(--text-secondary);+ font-size: 0.8125rem;+ font-weight: 600;+ cursor: pointer;+ transition: all 0.2s;+}++.config-form .config-array-add:hover {+ border-color: var(--primary);+ color: var(--primary);+}+.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 a2a7976ad..177ef762f 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -20,9 +20,10 @@ import {Trash2,Globe,Download,+ Plus,} from 'lucide-react';import { pluginsApi, infraApi } from '../services/api';-import type { Plugin, CatalogPlugin } from '../services/api';+import type { Plugin, CatalogPlugin, PluginConfigField } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';import {usePluginsQuery,@@ -52,6 +53,193 @@ interface EngineConfig {browserArgs: string;}+/** A blank value for a field, used to seed a form and to add a new array row. */+function emptyForField(field: PluginConfigField): unknown {+ if (field.default !== undefined) return field.default;+ // A <select> always shows its first option, so seed enum state to it — otherwise the form shows a+ // value the user never picked and would save '' instead.+ if (field.enum && field.enum.length > 0) return field.enum[0];+ switch (field.type) {+ case 'boolean':+ return false;+ case 'array':+ return [];+ case 'object': {+ const obj: Record<string, unknown> = {};+ if (field.properties) for (const [k, sub] of Object.entries(field.properties)) obj[k] = emptyForField(sub);+ return obj;+ }+ default: // string | number | textarea — empty string (number coerced on input)+ return '';+ }+}++/**+ * 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+ * keystrokes. The secret redact/restore round-trip lives server-side (PUT /plugins/:id/config).+ */+function ConfigField({+ field,+ label,+ value,+ onChange,+}: {+ field: PluginConfigField;+ label: string;+ value: unknown;+ onChange: (next: unknown) => void;+}) {+ const { t } = useTranslation();+ const desc = field.description ? <small>{field.description}</small> : null;+ const labelEl = (+ <label>+ {label}+ {field.required && <span className="required-mark"> *</span>}+ </label>+ );++ if (field.type === 'boolean') {+ return (+ <div className="form-group toggle-group">+ <div className="toggle-info">+ <label>{label}</label>+ {desc}+ </div>+ <label className="toggle-switch">+ <input type="checkbox" checked={Boolean(value)} onChange={e => onChange(e.target.checked)} />+ <span className="toggle-slider"></span>+ </label>+ </div>+ );+ }++ if (field.enum && field.enum.length > 0) {+ const options = field.enum;+ return (+ <div className="form-group">+ {labelEl}+ <select+ value={String(value ?? '')}+ // Restore the option's original type (e.g. a number/boolean enum), not the raw string value.+ onChange={e => onChange(options.find(o => String(o) === e.target.value) ?? e.target.value)}+ >+ {options.map(opt => (+ <option key={String(opt)} value={String(opt)}>+ {String(opt)}+ </option>+ ))}+ </select>+ {desc}+ </div>+ );+ }++ if (field.type === 'object') {+ const obj = value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};+ const props = field.properties ?? {};+ return (+ <fieldset className="config-fieldset">+ <legend>{label}</legend>+ {desc}+ {Object.entries(props).map(([k, sub]) => (+ <ConfigField+ key={k}+ field={sub}+ label={sub.title || k}+ value={obj[k]}+ onChange={v => onChange({ ...obj, [k]: v })}+ />+ ))}+ </fieldset>+ );+ }++ if (field.type === 'array') {+ const rows = Array.isArray(value) ? value : [];+ const item = field.items;+ if (!item) {+ // No element schema declared — nothing to render safely (don't fall through to a text input+ // that would stringify the array to "[object Object]"/"" and corrupt it).+ return (+ <div className="config-array">+ {labelEl}+ {desc}+ </div>+ );+ }+ return (+ <div className="config-array">+ {labelEl}+ {desc}+ {rows.map((row, i) => (+ <div className="config-array-row" key={i}>+ <div className="config-array-row-body">+ <ConfigField+ field={item}+ label={`#${i + 1}`}+ value={row}+ onChange={v => onChange(rows.map((r, j) => (j === i ? v : r)))}+ />+ </div>+ <button+ type="button"+ className="config-array-remove"+ title={t('common.delete')}+ aria-label={t('common.delete')}+ onClick={() => onChange(rows.filter((_, j) => j !== i))}+ >+ <Trash2 size={14} />+ </button>+ </div>+ ))}+ <button type="button" className="config-array-add" onClick={() => onChange([...rows, emptyForField(item)])}>+ <Plus size={14} /> {t('plugins.config.addItem')}+ </button>+ </div>+ );+ }++ if (field.type === 'textarea') {+ return (+ <div className="form-group">+ {labelEl}+ <textarea+ value={value === undefined || value === null ? '' : String(value)}+ placeholder={field.default !== undefined ? String(field.default) : undefined}+ minLength={field.min}+ maxLength={field.max}+ rows={4}+ onChange={e => onChange(e.target.value)}+ />+ {desc}+ </div>+ );+ }++ const inputType = field.type === 'number' ? 'number' : field.secret ? 'password' : 'text';+ return (+ <div className="form-group">+ {labelEl}+ <input+ type={inputType}+ value={value === undefined || value === null ? '' : String(value)}+ placeholder={field.default !== undefined ? String(field.default) : undefined}+ autoComplete={field.secret ? 'new-password' : undefined}+ min={field.type === 'number' ? field.min : undefined}+ max={field.type === 'number' ? field.max : undefined}+ minLength={field.type !== 'number' ? field.min : undefined}+ maxLength={field.type !== 'number' ? field.max : undefined}+ pattern={field.type !== 'number' ? field.pattern : undefined}+ onChange={e =>+ onChange(field.type === 'number' ? (e.target.value === '' ? '' : Number(e.target.value)) : e.target.value)+ }+ />+ {desc}+ </div>+ );+}+export default function Plugins() {const { t } = useTranslation();useDocumentTitle(t('plugins.title'));@@ -130,7 +318,7 @@ export default function Plugins() {if (plugin.configSchema?.properties) {const initial: Record<string, unknown> = {};for (const [key, field] of Object.entries(plugin.configSchema.properties)) {- initial[key] = plugin.config[key] ?? field.default ?? (field.type === 'boolean' ? false : '');+ initial[key] = plugin.config[key] ?? emptyForField(field);}setSchemaConfig(initial);}@@ -715,76 +903,15 @@ export default function Plugins() {</>) : configPlugin.configSchema && Object.keys(configPlugin.configSchema.properties).length > 0 ? (<div className="config-form">- {Object.entries(configPlugin.configSchema.properties).map(([key, field]) => {- const value = schemaConfig[key];- const label = field.title || key;-- if (field.type === 'boolean') {- return (- <div className="form-group toggle-group" key={key}>- <div className="toggle-info">- <label>{label}</label>- {field.description && <small>{field.description}</small>}- </div>- <label className="toggle-switch">- <input- type="checkbox"- checked={Boolean(value)}- onChange={e => setSchemaConfig({ ...schemaConfig, [key]: e.target.checked })}- />- <span className="toggle-slider"></span>- </label>- </div>- );- }-- if (field.enum && field.enum.length > 0) {- return (- <div className="form-group" key={key}>- <label>{label}</label>- <select- value={String(value ?? '')}- onChange={e => setSchemaConfig({ ...schemaConfig, [key]: e.target.value })}- >- {field.enum.map(opt => (- <option key={String(opt)} value={String(opt)}>- {String(opt)}- </option>- ))}- </select>- {field.description && <small>{field.description}</small>}- </div>- );- }-- const inputType = field.type === 'number' ? 'number' : field.secret ? 'password' : 'text';- return (- <div className="form-group" key={key}>- <label>- {label}- {field.required && <span className="required-mark"> *</span>}- </label>- <input- type={inputType}- value={value === undefined || value === null ? '' : String(value)}- placeholder={field.default !== undefined ? String(field.default) : undefined}- autoComplete={field.secret ? 'new-password' : undefined}- onChange={e =>- setSchemaConfig({- ...schemaConfig,- [key]:- field.type === 'number'- ? e.target.value === ''- ? ''- : Number(e.target.value)- : e.target.value,- })- }- />- {field.description && <small>{field.description}</small>}- </div>- );- })}+ {Object.entries(configPlugin.configSchema.properties).map(([key, field]) => (+ <ConfigField+ key={key}+ field={field}+ label={field.title || key}+ value={schemaConfig[key]}+ onChange={v => setSchemaConfig({ ...schemaConfig, [key]: v })}+ />+ ))}</div>) : (<div className="no-config">diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 8eb485b05..f75052846 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -582,15 +582,21 @@ export const settingsApi = {// Plugin Types// =============================================================================-/** Field definition within a plugin's config schema (mirrors the backend PluginConfigSchema). */+/** Field definition within a plugin's config schema (mirrors the backend PluginConfigField). */export interface PluginConfigField {- type: 'string' | 'number' | 'boolean' | 'array' | 'object';+ // 'textarea' is a multi-line string; a field with `enum` renders as a <select>.+ type: 'string' | 'number' | 'boolean' | 'array' | 'object' | 'textarea';title?: string;description?: string;default?: unknown;enum?: unknown[];required?: boolean;secret?: boolean;+ min?: number;+ max?: number;+ pattern?: string;+ items?: PluginConfigField; // array element schema; array-of-rows when items.type === 'object'+ properties?: Record<string, PluginConfigField>; // nested-object fields}export interface PluginConfigSchema {diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex f9593c59f..692e625b1 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -81,20 +81,32 @@ export interface PluginManifest {net?: { allow?: string[] };}+/**+ * One field in a plugin's config schema. Recursive: an `object` field nests `properties`, an `array`+ * field describes its element with `items` (array-of-rows when `items.type === 'object'`). The host+ * renders this into an authenticated form; the plugin still reads `ctx.config` defensively.+ */+export interface PluginConfigField {+ // 'textarea' is a string rendered multi-line; a field with `enum` renders as a <select>.+ type: 'string' | 'number' | 'boolean' | 'array' | 'object' | 'textarea';+ title?: string;+ description?: string;+ default?: unknown;+ enum?: unknown[]; // when present (any scalar type), the field renders as a <select>+ required?: boolean;+ secret?: boolean; // sensitive value (e.g. API key): masked on read, preserved on an unchanged write+ // Validation hints, surfaced as HTML input attributes (advisory — not hard-enforced server-side):+ min?: number; // number: value bound; string/textarea: minLength; array: min rows+ max?: number; // number: value bound; string/textarea: maxLength; array: max rows+ pattern?: string; // string/textarea: HTML validation regex+ // Composite kinds:+ items?: PluginConfigField; // array element schema; array-of-rows when items.type === 'object'+ properties?: Record<string, PluginConfigField>; // nested-object fields (type: 'object')+}+export interface PluginConfigSchema {type: 'object';- properties: Record<- string,- {- type: 'string' | 'number' | 'boolean' | 'array' | 'object';- title?: string;- description?: string;- default?: unknown;- enum?: unknown[];- required?: boolean;- secret?: boolean; // For sensitive values like API keys- }- >;+ properties: Record<string, PluginConfigField>;}// ============================================================================diff --git a/src/modules/plugins/redact-config.spec.ts b/src/modules/plugins/redact-config.spec.tsindex d347db515..ee4d1b81d 100644--- a/src/modules/plugins/redact-config.spec.ts+++ b/src/modules/plugins/redact-config.spec.ts@@ -56,3 +56,154 @@ describe('restoreSecretConfig', () => {expect(restoreSecretConfig({ apiKey: '' }, undefined, schema)).not.toHaveProperty('apiKey');});});++// v0.7 richer schema: secrets can live inside a nested object or in each row of an array-of-rows,+// so redaction (read) and restoration (write) must recurse — else a nested secret leaks via GET, or+// gets clobbered by the mask on the round-trip PUT.+const nestedSchema: PluginConfigSchema = {+ type: 'object',+ properties: {+ provider: {+ type: 'object',+ properties: {+ apiKey: { type: 'string', secret: true },+ region: { type: 'string' },+ },+ },+ endpoints: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ url: { type: 'string' },+ token: { type: 'string', secret: true },+ },+ },+ },+ },+};++describe('redactSecretConfig (nested)', () => {+ it('masks a secret nested inside an object', () => {+ expect(redactSecretConfig({ provider: { apiKey: 'k', region: 'us' } }, nestedSchema)).toEqual({+ provider: { apiKey: SECRET_SENTINEL, region: 'us' },+ });+ });++ it('masks a secret sub-field in every row of an array-of-rows (leaving empty ones untouched)', () => {+ expect(+ redactSecretConfig(+ {+ endpoints: [+ { url: 'a', token: 't1' },+ { url: 'b', token: '' },+ ],+ },+ nestedSchema,+ ),+ ).toEqual({+ endpoints: [+ { url: 'a', token: SECRET_SENTINEL },+ { url: 'b', token: '' },+ ],+ });+ });+});++describe('restoreSecretConfig (nested)', () => {+ it('restores a nested-object secret when the incoming value is the sentinel', () => {+ expect(+ restoreSecretConfig(+ { provider: { apiKey: SECRET_SENTINEL, region: 'eu' } },+ { provider: { apiKey: 'real', region: 'us' } },+ nestedSchema,+ ),+ ).toEqual({ provider: { apiKey: 'real', region: 'eu' } });+ });++ it('restores per-row array-of-rows secrets, keeping genuinely-new ones', () => {+ expect(+ restoreSecretConfig(+ {+ endpoints: [+ { url: 'a', token: SECRET_SENTINEL },+ { url: 'b', token: 'new' },+ ],+ },+ {+ endpoints: [+ { url: 'a', token: 'real1' },+ { url: 'b', token: 'real2' },+ ],+ },+ nestedSchema,+ ),+ ).toEqual({+ endpoints: [+ { url: 'a', token: 'real1' },+ { url: 'b', token: 'new' },+ ],+ });+ });++ // Rows are matched to the stored secret by their non-secret content, NOT by array index — so+ // adding/removing/reordering a row can never bind a sentinel to a different row's stored secret.+ it('restores by content after a row is removed (no positional drift)', () => {+ expect(+ restoreSecretConfig(+ { endpoints: [{ url: 'b', token: SECRET_SENTINEL }] },+ {+ endpoints: [+ { url: 'a', token: 'real_a' },+ { url: 'b', token: 'real_b' },+ ],+ },+ nestedSchema,+ ),+ ).toEqual({ endpoints: [{ url: 'b', token: 'real_b' }] });+ });++ it('restores by content after rows are reordered', () => {+ expect(+ restoreSecretConfig(+ {+ endpoints: [+ { url: 'b', token: SECRET_SENTINEL },+ { url: 'a', token: SECRET_SENTINEL },+ ],+ },+ {+ endpoints: [+ { url: 'a', token: 'real_a' },+ { url: 'b', token: 'real_b' },+ ],+ },+ nestedSchema,+ ),+ ).toEqual({+ endpoints: [+ { url: 'b', token: 'real_b' },+ { url: 'a', token: 'real_a' },+ ],+ });+ });++ it('does not mis-target a secret onto a newly-inserted row', () => {+ // New row "NEW" has no stored counterpart → its sentinel is dropped (not filled with a's secret);+ // existing row "a" keeps its own secret regardless of the index shift.+ expect(+ restoreSecretConfig(+ {+ endpoints: [+ { url: 'NEW', token: SECRET_SENTINEL },+ { url: 'a', token: SECRET_SENTINEL },+ ],+ },+ { endpoints: [{ url: 'a', token: 'real1' }] },+ nestedSchema,+ ),+ ).toEqual({+ endpoints: [{ url: 'NEW' }, { url: 'a', token: 'real1' }],+ });+ });+});diff --git a/src/modules/plugins/redact-config.ts b/src/modules/plugins/redact-config.tsindex 32ee4e415..c218062cb 100644--- a/src/modules/plugins/redact-config.ts+++ b/src/modules/plugins/redact-config.ts@@ -1,54 +1,148 @@-import type { PluginConfigSchema } from '../../core/plugins/plugin.interfaces';+import type { PluginConfigField, PluginConfigSchema } from '../../core/plugins/plugin.interfaces';/** Mask shown for a stored secret on read. Treated as "unchanged" on write. */export const SECRET_SENTINEL = '***';-function secretKeys(schema?: PluginConfigSchema): string[] {- if (!schema?.properties) return [];- return Object.entries(schema.properties)- .filter(([, prop]) => prop?.secret)- .map(([key]) => key);+const isMeaningful = (v: unknown): boolean => v !== undefined && v !== null && v !== '';++const isPlainObject = (v: unknown): v is Record<string, unknown> =>+ typeof v === 'object' && v !== null && !Array.isArray(v);++/**+ * Redact one value against its field. Recurses into nested objects and into each row of an+ * array-of-rows so a `secret`-flagged field at any depth is masked. An empty/absent secret is left+ * as-is so the mask never implies a secret that isn't set.+ */+function redactValue(value: unknown, field: PluginConfigField): unknown {+ if (field.type === 'object' && field.properties && isPlainObject(value)) {+ return redactObject(value, field.properties);+ }+ if (field.type === 'array' && field.items && Array.isArray(value)) {+ return value.map(item => redactValue(item, field.items as PluginConfigField));+ }+ if (field.secret && isMeaningful(value)) return SECRET_SENTINEL;+ return value;}-const isMeaningful = (v: unknown): boolean => v !== undefined && v !== null && v !== '';+function redactObject(+ config: Record<string, unknown>,+ properties: Record<string, PluginConfigField>,+): Record<string, unknown> {+ const out = { ...config };+ for (const [key, field] of Object.entries(properties)) {+ if (key in out) out[key] = redactValue(out[key], field);+ }+ return out;+}/*** Replace secret-flagged, non-empty config values with {@link SECRET_SENTINEL} so a read (GET- * /plugins) never leaks them. An empty/absent secret is left as-is so the mask never implies a- * secret that isn't set. Returns a copy; non-secret fields and shape are untouched (bare payload).+ * /plugins) never leaks them — at any depth. Returns a copy; non-secret fields, unknown keys, and+ * shape are untouched (bare payload).*/export function redactSecretConfig(config: Record<string, unknown> | undefined,schema?: PluginConfigSchema,): Record<string, unknown> {const out = { ...(config ?? {}) };- for (const key of secretKeys(schema)) {- if (isMeaningful(out[key])) out[key] = SECRET_SENTINEL;+ if (!schema?.properties) return out;+ return redactObject(out, schema.properties);+}++/** Deterministic JSON (object keys sorted) so two equal shapes compare equal regardless of key order. */+function stableStringify(v: unknown): string {+ if (Array.isArray(v)) return '[' + v.map(stableStringify).join(',') + ']';+ if (isPlainObject(v)) {+ return (+ '{' ++ Object.keys(v)+ .sort()+ .map(k => JSON.stringify(k) + ':' + stableStringify(v[k]))+ .join(',') ++ '}'+ );}- return out;+ return JSON.stringify(v) ?? 'null';}/**- * On write (PUT /plugins/:id/config), the dashboard sends the whole config back — including the- * masked secret. Treat a sentinel/empty secret as "keep existing": restore the stored value, or- * drop the key when there's nothing stored, so the real secret is never overwritten by the mask.- * A genuinely-new secret value is stored as provided.+ * An array element's identity for matching on restore: the element with its secrets masked, so a+ * stored row (real secret) and the dashboard's round-tripped row (sentinel secret) share a signature+ * iff their NON-secret content is equal. Scalar-secret elements collapse to the same signature and so+ * are deliberately ambiguous (never auto-restored to the wrong one).*/-export function restoreSecretConfig(+function elementSignature(value: unknown, field: PluginConfigField): string {+ return stableStringify(redactValue(value, field));+}++/** Restore one value against its field. `keep:false` means drop the key (sentinel with nothing stored). */+function restoreValue(+ incoming: unknown,+ existing: unknown,+ field: PluginConfigField,+): { keep: boolean; value?: unknown } {+ if (field.type === 'object' && field.properties && isPlainObject(incoming)) {+ return {+ keep: true,+ value: restoreObject(incoming, isPlainObject(existing) ? existing : undefined, field.properties),+ };+ }+ if (field.type === 'array' && field.items && Array.isArray(incoming)) {+ const itemField = field.items;+ const existingArr = Array.isArray(existing) ? existing : [];+ // Match each incoming element to its stored counterpart by NON-SECRET content (a row's signature+ // is the row with its secrets masked), not by array index. Adding / removing / reordering rows+ // then can't bind a sentinel to a different row's secret. Only an unambiguous match (exactly one+ // stored element with that signature) restores; otherwise the sentinel is treated as "nothing+ // stored" (dropped), so a secret may be lost on an ambiguous edit but is never mis-targeted.+ const sigCount = new Map<string, number>();+ const sigFirst = new Map<string, unknown>();+ for (const ex of existingArr) {+ const s = elementSignature(ex, itemField);+ sigCount.set(s, (sigCount.get(s) ?? 0) + 1);+ if (!sigFirst.has(s)) sigFirst.set(s, ex);+ }+ return {+ keep: true,+ value: incoming.map(item => {+ const s = elementSignature(item, itemField);+ const match = sigCount.get(s) === 1 ? sigFirst.get(s) : undefined;+ return restoreValue(item, match, itemField).value;+ }),+ };+ }+ if (field.secret && (incoming === SECRET_SENTINEL || !isMeaningful(incoming))) {+ if (isMeaningful(existing)) return { keep: true, value: existing };+ return { keep: false };+ }+ return { keep: true, value: incoming };+}++function restoreObject(incoming: Record<string, unknown>,existing: Record<string, unknown> | undefined,- schema?: PluginConfigSchema,+ properties: Record<string, PluginConfigField>,): Record<string, unknown> {const out = { ...incoming };- for (const key of secretKeys(schema)) {- const v = out[key];- if (v === SECRET_SENTINEL || !isMeaningful(v)) {- if (existing && isMeaningful(existing[key])) {- out[key] = existing[key];- } else {- delete out[key];- }- }+ for (const [key, field] of Object.entries(properties)) {+ if (!(key in out)) continue;+ const r = restoreValue(out[key], existing?.[key], field);+ if (r.keep) out[key] = r.value;+ else delete out[key];}return out;}++/**+ * On write (PUT /plugins/:id/config), the dashboard sends the whole config back — including masked+ * secrets at any depth. Treat a sentinel/empty secret as "keep existing": restore the stored value,+ * or drop the key when there's nothing stored. A genuinely-new value is stored as provided.+ */+export function restoreSecretConfig(+ incoming: Record<string, unknown>,+ existing: Record<string, unknown> | undefined,+ schema?: PluginConfigSchema,+): Record<string, unknown> {+ if (!schema?.properties) return { ...incoming };+ return restoreObject(incoming, existing, schema.properties);+}