Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): remove a stored secret when a config write sends null
Yudhi Armyndharis88fcdd56aa2a
diff --git a/dashboard/src/utils/pluginConfigForm.test.ts b/dashboard/src/utils/pluginConfigForm.test.tsindex 1e5b36962..b5d1451f8 100644--- a/dashboard/src/utils/pluginConfigForm.test.ts+++ b/dashboard/src/utils/pluginConfigForm.test.ts@@ -19,6 +19,25 @@ test('coerceFieldInput: a string field passes the raw value through unchanged',assert.equal(coerceFieldInput(str, 'hi'), 'hi');});+// The gateway restores a stored secret for the mask and for an empty string, so a cleared secret input+// must not travel as ''. It is omitted here and becomes null in the save, which removes the secret.+test('coerceFieldInput: a cleared secret becomes undefined, a typed one passes through', () => {+ const secret: PluginConfigField = { type: 'string', secret: true };+ assert.equal(coerceFieldInput(secret, ''), undefined);+ assert.equal(coerceFieldInput(secret, 'sk-live'), 'sk-live');+});++test('fillClearedFields: a cleared stored secret saves null, an unset one stays omitted', () => {+ const properties: Record<string, PluginConfigField> = {+ apiKey: { type: 'string', secret: true },+ webhookKey: { type: 'string', secret: true },+ };+ const values = { apiKey: undefined, webhookKey: undefined };+ const stored = { apiKey: '***' }; // the redacted read: the mask means a secret is stored++ assert.deepEqual(fillClearedFields(values, stored, properties), { apiKey: null, webhookKey: undefined });+});+test('emptyForField: a number field seeds to undefined, not an empty string', () => {assert.equal(emptyForField(num), undefined);});diff --git a/dashboard/src/utils/pluginConfigForm.ts b/dashboard/src/utils/pluginConfigForm.tsindex 7fc0252aa..5c4a892e2 100644--- a/dashboard/src/utils/pluginConfigForm.ts+++ b/dashboard/src/utils/pluginConfigForm.ts@@ -26,9 +26,12 @@ export function emptyForField(field: PluginConfigField): unknown {}/** Coerce a text-input value to the field's type. A cleared number becomes undefined (so the key is- * omitted) rather than '' — the inverse of {@link emptyForField} for number fields. */+ * omitted) rather than '' — the inverse of {@link emptyForField} for number fields. A cleared secret+ * does too: the gateway keeps a stored secret for an empty string, so the save sends null for it+ * ({@link fillClearedFields}), the one value that removes it. */export function coerceFieldInput(field: PluginConfigField, raw: string): unknown {if (field.type === 'number') return raw === '' ? undefined : Number(raw);+ if (field.secret && raw === '') return undefined;return raw;}diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 50a7ddcc9..5d9356a6e 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6274,9 +6274,9 @@ Update a plugin's base configuration object.**Request body** — `PluginConfigDto` (class-validated; body must be exactly `{config:{…}}`)-| Field | Type | Required | Constraints | Description |-| -------- | ------ | -------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `config` | object | Yes | `@IsObject()` | Keys to set, merged over the stored config: omitted keys keep their value. Every key sent is stored, and for a built-in engine plugin (`whatsapp-web.js`, `baileys`) a stored key overrides its `.env`-derived setting on every later boot, so send only the keys you mean to change, not the whole object `GET /api/plugins/:id` returns. Masked/sentinel secret values mean "unchanged" and are restored from the stored config |+| Field | Type | Required | Constraints | Description |+| -------- | ------ | -------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `config` | object | Yes | `@IsObject()` | Keys to set, merged over the stored config: omitted keys keep their value. Every key sent is stored, and for a built-in engine plugin (`whatsapp-web.js`, `baileys`) a stored key overrides its `.env`-derived setting on every later boot, so send only the keys you mean to change, not the whole object `GET /api/plugins/:id` returns. Masked/sentinel secret values mean "unchanged" and are restored from the stored config, as does an empty string; send `null` for a secret to remove the stored value |```json{ "config": { "apiKey": "sk-...", "replyDelayMs": 1500 } }@@ -6309,9 +6309,9 @@ Set (or clear) a plugin config override for a specific session.**Request body** — `PluginConfigDto`-| Field | Type | Required | Constraints | Description |-| -------- | ------ | -------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |-| `config` | object | Yes | `@IsObject()` | Per-session override slice. Empty `{}` clears the override (falls back to base config). Masked secrets restored from the existing per-session value |+| Field | Type | Required | Constraints | Description |+| -------- | ------ | -------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `config` | object | Yes | `@IsObject()` | Per-session override slice. Empty `{}` clears the override (falls back to base config). Masked secrets restored from the existing per-session value; a secret sent as `null` is dropped from the override, so the session uses the base value |```json{ "config": { "replyDelayMs": 3000 } }@@ -6967,7 +6967,7 @@ Update an instance (secret masked in the response). Any subset of:| -------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `enabled` | boolean | Whether ingress is accepted and dispatch is active || `sessionScope` | string \| null | Re-bind to another session, or `null` to serve all sessions again (the new scope must be inside the key's `allowedSessions`, so a key restricted to sessions cannot send `null`; the old scope's binding is torn down first) |-| `config` | object | Replace the per-instance config slice |+| `config` | object | Replace the per-instance config slice; a masked secret is restored from the stored one, and a secret sent as `null` is removed |**Auth:** API key (ADMIN)diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.mdindex d9c2e2645..713046b59 100644--- a/docs/19-plugin-architecture.md+++ b/docs/19-plugin-architecture.md@@ -201,7 +201,8 @@ to translate from `locale`. Treat it as optional too, and fall back to `navigatohost.A `configSchema` field may set `secret: true` (e.g. an API key): the value is masked on read and-preserved on an unchanged write.+preserved on an unchanged write. A write keeps the stored value for the mask and for an empty string, and+removes it for an explicit `null`.### Plugin Entry Pointdiff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex d7d73ebc3..095ffb80c 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -140,7 +140,7 @@ export interface PluginConfigField {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+ secret?: boolean; // sensitive (e.g. API key): masked on read, kept on an unchanged write, removed by null// Validation hints, surfaced as HTML input attributes (advisory — not hard-enforced server-side):min?: number; // number: value bound; string/textarea: minLength; array: min rowsmax?: number; // number: value bound; string/textarea: maxLength; array: max rowsdiff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex f7286e0f4..59eded9ba 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -679,6 +679,29 @@ describe('PluginsService — per-session config', () => {expect(loader.getPlugin('sess-cfg')?.sessionConfig?.['sess-A']).toEqual({ apiKey: 'A-secret', lang: 'en' });});+ // A write is merged over the stored base config, so a removed secret has to travel as null; an empty+ // string is not a removal.+ it('removes the base secret on an explicit null and keeps it on an empty string', () => {+ service.updateConfig('sess-cfg', { apiKey: 'BASE', lang: 'en' });++ service.updateConfig('sess-cfg', { apiKey: '', lang: 'de' });+ expect(loader.getPlugin('sess-cfg')?.config).toEqual({ apiKey: 'BASE', lang: 'de' });++ expect(service.updateConfig('sess-cfg', { apiKey: null }).success).toBe(true);+ expect(loader.getPlugin('sess-cfg')?.config).toEqual({ apiKey: null, lang: 'de' });+ expect(service.findOne('sess-cfg').config).toEqual({ apiKey: null, lang: 'de' });+ });++ // The override slice replaces the stored one, and a session without its own secret inherits the base.+ it('drops a per-session secret sent as null, so the session inherits the base one', () => {+ service.updateConfig('sess-cfg', { apiKey: 'BASE' });+ service.updateSessionConfig('sess-cfg', 'sess-A', { apiKey: 'A-secret', lang: 'he' });++ service.updateSessionConfig('sess-cfg', 'sess-A', { apiKey: null, lang: 'he' });++ expect(loader.getPlugin('sess-cfg')?.sessionConfig?.['sess-A']).toEqual({ lang: 'he' });+ });+it('keeps the base config and per-session overrides independent', () => {service.updateConfig('sess-cfg', { apiKey: 'BASE', lang: 'en' });service.updateSessionConfig('sess-cfg', 'sess-A', { apiKey: 'A-secret', lang: 'he' });diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 7fcebc708..854232b7e 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -239,7 +239,9 @@ export class PluginsService {try {// The dashboard PUTs the whole (redacted) config back, so a sentinel secret means "unchanged":// restore the stored value instead of overwriting the real secret with the mask.- const merged = restoreSecretConfig(config, plugin.config, plugin.manifest.configSchema);+ const merged = restoreSecretConfig(config, plugin.config, plugin.manifest.configSchema, {+ mergedOverStored: true,+ });this.pluginLoader.updatePluginConfig(id, merged);return { success: true, message: `Plugin ${id} configuration updated` };} catch (error) {diff --git a/src/modules/plugins/redact-config.spec.ts b/src/modules/plugins/redact-config.spec.tsindex 97ec84e6d..e3beefaa2 100644--- a/src/modules/plugins/redact-config.spec.ts+++ b/src/modules/plugins/redact-config.spec.ts@@ -61,6 +61,44 @@ describe('restoreSecretConfig', () => {expect(restoreSecretConfig({ apiKey: SECRET_SENTINEL }, {}, schema)).not.toHaveProperty('apiKey');expect(restoreSecretConfig({ apiKey: '' }, undefined, schema)).not.toHaveProperty('apiKey');});++ // A retired or leaked credential has to be removable. Only an explicit null does it: a client that+ // echoes a blank for a secret it never held (a templated config with an unset variable) must not+ // wipe the stored one.+ it('removes a stored secret on an explicit null, and only on null', () => {+ const stored = { apiKey: 'real-secret', endpoint: 'https://old' };+ const merged = { mergedOverStored: true };++ // A result that replaces the stored config just loses the key.+ expect(restoreSecretConfig({ apiKey: null, endpoint: 'https://new' }, stored, schema)).toEqual({+ endpoint: 'https://new',+ });+ // One that is merged over it has to carry the null, or the merge would put the stored value back.+ expect(restoreSecretConfig({ apiKey: null, endpoint: 'https://new' }, stored, schema, merged)).toEqual({+ apiKey: null,+ endpoint: 'https://new',+ });+ for (const options of [{}, merged]) {+ expect(restoreSecretConfig({ apiKey: '' }, stored, schema, options)).toEqual({ apiKey: 'real-secret' });+ expect(restoreSecretConfig({ apiKey: SECRET_SENTINEL }, stored, schema, options)).toEqual({+ apiKey: 'real-secret',+ });+ expect(restoreSecretConfig({ endpoint: 'https://new' }, stored, schema, options)).toEqual({+ endpoint: 'https://new',+ });+ }+ });++ it('drops a null secret when nothing is stored, rather than persisting a null', () => {+ for (const options of [{}, { mergedOverStored: true }]) {+ expect(restoreSecretConfig({ apiKey: null }, {}, schema, options)).not.toHaveProperty('apiKey');+ expect(restoreSecretConfig({ apiKey: null }, undefined, schema, options)).not.toHaveProperty('apiKey');+ }+ });++ it('leaves a null in a non-secret field to the ordinary merge', () => {+ expect(restoreSecretConfig({ endpoint: null }, { endpoint: 'https://old' }, schema)).toEqual({ endpoint: null });+ });});// v0.7 richer schema: secrets can live inside a nested object or in each row of an array-of-rows,@@ -127,6 +165,43 @@ describe('restoreSecretConfig (nested)', () => {).toEqual({ provider: { apiKey: 'real', region: 'eu' } });});+ // The nested object replaces the stored one whole, even where the top level is merged over the stored+ // config, so dropping the key is what removes the secret.+ it('removes a nested-object secret on an explicit null and keeps its sibling', () => {+ for (const options of [{}, { mergedOverStored: true }]) {+ expect(+ restoreSecretConfig(+ { provider: { apiKey: null, region: 'eu' } },+ { provider: { apiKey: 'real', region: 'us' } },+ nestedSchema,+ options,+ ),+ ).toEqual({ provider: { region: 'eu' } });+ }+ });++ it('removes one row secret of an array-of-rows on an explicit null and keeps the others', () => {+ expect(+ restoreSecretConfig(+ {+ endpoints: [+ { url: 'a', token: null },+ { url: 'b', token: SECRET_SENTINEL },+ ],+ },+ {+ endpoints: [+ { url: 'a', token: 'real1' },+ { url: 'b', token: 'real2' },+ ],+ },+ nestedSchema,+ ),+ ).toEqual({+ endpoints: [{ url: 'a' }, { url: 'b', token: 'real2' }],+ });+ });+it('restores per-row array-of-rows secrets, keeping genuinely-new ones', () => {expect(restoreSecretConfig(diff --git a/src/modules/plugins/redact-config.ts b/src/modules/plugins/redact-config.tsindex c0211d17d..f4dcb844c 100644--- a/src/modules/plugins/redact-config.ts+++ b/src/modules/plugins/redact-config.ts@@ -194,10 +194,21 @@ function restoreObject(incoming: Record<string, unknown>,existing: Record<string, unknown> | undefined,properties: Record<string, PluginConfigField>,+ mergedOverStored = false,): Record<string, unknown> {const out = { ...incoming };for (const [key, field] of Object.entries(properties)) {if (!(key in out)) continue;+ // An explicit null is how a stored secret is removed: every other empty form (the mask, an empty+ // string, an absent key) keeps it, so a client that echoes a blank for a secret it does not hold+ // leaves the stored one alone. The key is dropped, which removes the secret wherever the result+ // replaces what was stored (a nested object, a row of a list, a per-session slice, an instance+ // config). Only a top-level key of a result that is merged OVER the stored config stays as the null,+ // since an omitted key would leave the stored value in place.+ if (field.secret && out[key] === null) {+ if (!mergedOverStored || !isMeaningful(existing?.[key])) delete out[key];+ continue;+ }const r = restoreValue(out[key], existing?.[key], field);if (r.keep) out[key] = r.value;else delete out[key];@@ -208,12 +219,16 @@ function restoreObject(/*** 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.+ * or drop the key when there's nothing stored. A genuinely-new value is stored as provided, and an+ * explicit `null` removes the stored secret. `mergedOverStored` is for a caller that merges the result+ * over the stored config instead of replacing it: a top-level secret removed with `null` then stays in+ * the result as `null`, so the merge does not put the stored value back.*/export function restoreSecretConfig(incoming: Record<string, unknown>,existing: Record<string, unknown> | undefined,schema?: PluginConfigSchema,+ options: { mergedOverStored?: boolean } = {},): Record<string, unknown> {// Symmetric fail-closed restore for the schemaless case: redactSecretConfig masks EVERY value to the// sentinel, so on write treat any sentinel value as "keep existing" (restore the stored value, or drop@@ -229,5 +244,5 @@ export function restoreSecretConfig(}return out;}- return restoreObject(incoming, existing, schema.properties);+ return restoreObject(incoming, existing, schema.properties, options.mergedOverStored);}