Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): do not carry base secrets to a host an override picks
Yudhi Armyndharisb7d07d7f0cce
diff --git a/src/core/plugins/ingress-instance-config.spec.ts b/src/core/plugins/ingress-instance-config.spec.tsindex 1c28d9402..b0e233324 100644--- a/src/core/plugins/ingress-instance-config.spec.ts+++ b/src/core/plugins/ingress-instance-config.spec.ts@@ -267,6 +267,64 @@ describe('ingress dispatch resolves config per INSTANCE, not per session scope',});});+describe('ingress dispatch does not carry a base secret to another host', () => {+ // An adapter that calls the host named in `baseUrl` with a stored token. A key that may create an+ // instance on one session, or write that session's override, picks the host; the token is the+ // operator's and belongs to the host it was saved for.+ const adapter: Partial<PluginManifest> = {+ net: { allowConfigHosts: ['baseUrl'] },+ configSchema: {+ type: 'object',+ properties: { baseUrl: { type: 'string' }, apiToken: { type: 'string', secret: true } },+ },+ };+ const baseConfig = { baseUrl: 'https://chat.example.com', apiToken: 'OPERATOR-TOKEN' };++ it('withholds the operator token from an instance that names its own host', async () => {+ const tenant = instanceRow('tenant', { baseUrl: 'https://attacker.example' }, 'S1');+ const { bridge, calls } = makeBridge({ rows: [tenant], baseConfig, manifestOverrides: adapter });++ await bridge.dispatchWebhookForInstance(job('tenant', 'S1'));++ expect(calls[0].config).toEqual({ baseUrl: 'https://attacker.example' });+ });++ it('withholds it from an instance on a session whose override names another host', async () => {+ const tenant = instanceRow('tenant', null, 'S1');+ const { bridge, calls } = makeBridge({+ rows: [tenant],+ baseConfig,+ sessionConfig: { S1: { baseUrl: 'https://attacker.example' } },+ manifestOverrides: adapter,+ });++ await bridge.dispatchWebhookForInstance(job('tenant', 'S1'));++ expect(calls[0].config).toEqual({ baseUrl: 'https://attacker.example' });+ });++ it('keeps the token for an instance that names the operator host or none', async () => {+ const same = instanceRow('same', { baseUrl: 'https://chat.example.com/other' }, 'S1');+ const none = instanceRow('none', {}, 'S2');+ const { bridge, calls } = makeBridge({ rows: [same, none], baseConfig, manifestOverrides: adapter });++ await bridge.dispatchWebhookForInstance(job('same', 'S1'));+ await bridge.dispatchWebhookForInstance(job('none', 'S2'));++ expect(calls[0].config).toMatchObject({ apiToken: 'OPERATOR-TOKEN' });+ expect(calls[1].config).toEqual(baseConfig);+ });++ it('hands an instance the token it brings for its own host', async () => {+ const tenant = instanceRow('tenant', { baseUrl: 'https://other.example', apiToken: 'TENANT-TOKEN' }, 'S1');+ const { bridge, calls } = makeBridge({ rows: [tenant], baseConfig, manifestOverrides: adapter });++ await bridge.dispatchWebhookForInstance(job('tenant', 'S1'));++ expect(calls[0].config).toEqual({ baseUrl: 'https://other.example', apiToken: 'TENANT-TOKEN' });+ });+});+describe('ingress dispatch refuses an instance that is disabled or deleted', () => {it('rejects a disabled instance without reaching the worker', async () => {const a = { ...instanceRow('acct-a', { apiToken: 'token-A' }, SHARED_SCOPE), enabled: false };diff --git a/src/core/plugins/plugin-activation.spec.ts b/src/core/plugins/plugin-activation.spec.tsindex d0ab15197..05c6fbd78 100644--- a/src/core/plugins/plugin-activation.spec.ts+++ b/src/core/plugins/plugin-activation.spec.ts@@ -1,6 +1,8 @@import {+ type ConfigLayerManifest,isAllSessionsScope,isPluginActiveForSession,+ resolveInstanceConfig,resolvePluginConfig,sessionScopeKey,} from './plugin-activation';@@ -30,17 +32,19 @@ describe('isPluginActiveForSession', () => {});});+const NO_HOSTS: ConfigLayerManifest = {};+describe('resolvePluginConfig', () => {const base = { greeting: 'hi', lang: 'en', timeoutMs: 4000 };it('returns the base config when there is no per-session override', () => {- expect(resolvePluginConfig(base, undefined, 'sess-1', true)).toEqual(base);- expect(resolvePluginConfig(base, {}, 'sess-1', true)).toEqual(base);- expect(resolvePluginConfig(base, { 'other-sess': { lang: 'he' } }, 'sess-1', true)).toEqual(base);+ expect(resolvePluginConfig(base, undefined, 'sess-1', true, NO_HOSTS)).toEqual(base);+ expect(resolvePluginConfig(base, {}, 'sess-1', true, NO_HOSTS)).toEqual(base);+ expect(resolvePluginConfig(base, { 'other-sess': { lang: 'he' } }, 'sess-1', true, NO_HOSTS)).toEqual(base);});it('shallow-merges the session override over the base (override wins per top-level key)', () => {- expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he', extra: true } }, 'sess-1', true)).toEqual({+ expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he', extra: true } }, 'sess-1', true, NO_HOSTS)).toEqual({greeting: 'hi',lang: 'he',timeoutMs: 4000,@@ -51,7 +55,7 @@ describe('resolvePluginConfig', () => {it('deep-merges a nested object override, inheriting untouched nested keys (e.g. a nested secret)', () => {const b = { smtp: { host: 'mail.x', password: 'real' }, lang: 'en' };const sc = { 'sess-1': { smtp: { host: 'mail.y' } } };- expect(resolvePluginConfig(b, sc, 'sess-1', true)).toEqual({+ expect(resolvePluginConfig(b, sc, 'sess-1', true, NO_HOSTS)).toEqual({smtp: { host: 'mail.y', password: 'real' },lang: 'en',});@@ -60,27 +64,164 @@ describe('resolvePluginConfig', () => {it('replaces arrays wholesale on override (no element-wise merge)', () => {const b = { items: [1, 2, 3] };const sc = { 'sess-1': { items: [9] } };- expect(resolvePluginConfig(b, sc, 'sess-1', true)).toEqual({ items: [9] });+ expect(resolvePluginConfig(b, sc, 'sess-1', true, NO_HOSTS)).toEqual({ items: [9] });});it('ignores overrides for a global (non-session-scoped) plugin', () => {- expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he' } }, 'sess-1', false)).toEqual(base);+ expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he' } }, 'sess-1', false, NO_HOSTS)).toEqual(base);});it('ignores overrides for a non-session-attributed event (no sessionId)', () => {- expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he' } }, undefined, true)).toEqual(base);+ expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he' } }, undefined, true, NO_HOSTS)).toEqual(base);});it('does not mutate the base or the override', () => {const b = { a: 1 };const sc = { 'sess-1': { a: 2 } };- const out = resolvePluginConfig(b, sc, 'sess-1', true);+ const out = resolvePluginConfig(b, sc, 'sess-1', true, NO_HOSTS);expect(out).toEqual({ a: 2 });expect(b).toEqual({ a: 1 });expect(sc).toEqual({ 'sess-1': { a: 2 } });});});+// An adapter that calls an operator-configured host (a Chatwoot-style base URL) with a stored token.+const adapter: ConfigLayerManifest = {+ net: { allowConfigHosts: ['baseUrl'] },+ configSchema: {+ type: 'object',+ properties: {+ baseUrl: { type: 'string' },+ apiToken: { type: 'string', secret: true },+ inboxId: { type: 'string' },+ auth: {+ type: 'object',+ properties: { user: { type: 'string' }, password: { type: 'string', secret: true } },+ },+ accounts: {+ type: 'array',+ items: {+ type: 'object',+ properties: { id: { type: 'string' }, key: { type: 'string', secret: true } },+ },+ },+ tags: { type: 'array', items: { type: 'string' } },+ },+ },+};++describe('a layer that names another host than the layer beneath', () => {+ const base = {+ baseUrl: 'https://chat.example.com',+ apiToken: 'OPERATOR-TOKEN',+ inboxId: '7',+ auth: { user: 'bot', password: 'OPERATOR-PASSWORD' },+ accounts: [{ id: 'a', key: 'OPERATOR-KEY' }],+ tags: ['x'],+ };+ const resolveFor = (override: Record<string, unknown>, manifest: ConfigLayerManifest = adapter) =>+ resolvePluginConfig(base, { 'sess-1': override }, 'sess-1', true, manifest);++ it('does not inherit the declared secrets, at any depth, and keeps everything else', () => {+ expect(resolveFor({ baseUrl: 'https://attacker.example' })).toEqual({+ baseUrl: 'https://attacker.example',+ inboxId: '7',+ auth: { user: 'bot' },+ tags: ['x'],+ });+ });++ it('keeps the secrets the layer brings itself', () => {+ expect(resolveFor({ baseUrl: 'https://other.example', apiToken: 'OWN', auth: { password: 'OWN-PW' } })).toEqual({+ baseUrl: 'https://other.example',+ apiToken: 'OWN',+ inboxId: '7',+ auth: { user: 'bot', password: 'OWN-PW' },+ tags: ['x'],+ });+ });++ it('inherits them when the layer names the same origin, however it is spelled', () => {+ for (const same of ['https://chat.example.com', 'HTTPS://Chat.Example.com:443/other/path?x=1']) {+ expect(resolveFor({ baseUrl: same })).toMatchObject({ apiToken: 'OPERATOR-TOKEN', auth: base.auth });+ }+ });++ it('inherits them when the layer leaves the host key alone', () => {+ expect(resolveFor({ inboxId: '9' })).toMatchObject({ apiToken: 'OPERATOR-TOKEN', inboxId: '9' });+ });++ it('is no redirect when the host key is set to nothing or to a non-string', () => {+ for (const none of ['', ' ', null, 5]) {+ expect(resolveFor({ baseUrl: none })).toMatchObject({ apiToken: 'OPERATOR-TOKEN' });+ }+ });++ it('counts a host named where the base names none', () => {+ expect(resolvePluginConfig({ apiToken: 'T' }, { s: { baseUrl: 'https://x.example' } }, 's', true, adapter)).toEqual(+ {+ baseUrl: 'https://x.example',+ },+ );+ });++ it('compares a value that is no URL as text', () => {+ expect(resolveFor({ baseUrl: 'chat.example.com' })).not.toHaveProperty('apiToken');+ });++ it('inherits nothing when the manifest declares no schema, as nothing can be told secret', () => {+ expect(resolveFor({ baseUrl: 'https://attacker.example' }, { net: adapter.net })).toEqual({+ baseUrl: 'https://attacker.example',+ });+ });++ it('merges as before when the manifest names no host keys', () => {+ expect(resolveFor({ baseUrl: 'https://attacker.example' }, { configSchema: adapter.configSchema })).toMatchObject({+ apiToken: 'OPERATOR-TOKEN',+ });+ expect(resolveFor({ baseUrl: 'https://attacker.example' }, { ...adapter, net: { allow: ['*'] } })).toMatchObject({+ apiToken: 'OPERATOR-TOKEN',+ });+ });++ it('does not mutate the layer beneath', () => {+ const before = JSON.stringify(base);+ resolveFor({ baseUrl: 'https://attacker.example' });+ expect(JSON.stringify(base)).toBe(before);+ });+});++describe('resolveInstanceConfig', () => {+ const resolved = { baseUrl: 'https://chat.example.com', apiToken: 'OPERATOR-TOKEN', inboxId: '7' };++ it('returns what the earlier layers produced when the instance has no config', () => {+ expect(resolveInstanceConfig(resolved, null, adapter)).toBe(resolved);+ expect(resolveInstanceConfig(resolved, undefined, adapter)).toBe(resolved);+ });++ it('does not hand the secrets beneath to an instance that names another host', () => {+ expect(resolveInstanceConfig(resolved, { baseUrl: 'https://attacker.example' }, adapter)).toEqual({+ baseUrl: 'https://attacker.example',+ inboxId: '7',+ });+ });++ it('hands them to an instance that names the same host or none', () => {+ expect(resolveInstanceConfig(resolved, { baseUrl: 'https://chat.example.com/x' }, adapter)).toMatchObject({+ apiToken: 'OPERATOR-TOKEN',+ });+ expect(resolveInstanceConfig(resolved, { inboxId: '9' }, adapter)).toMatchObject({ apiToken: 'OPERATOR-TOKEN' });+ });++ it('applies on top of a session override that kept the base host', () => {+ const viaOverride = resolvePluginConfig(resolved, { s: { inboxId: '8' } }, 's', true, adapter);+ expect(viaOverride).toMatchObject({ apiToken: 'OPERATOR-TOKEN', inboxId: '8' });+ expect(resolveInstanceConfig(viaOverride, { baseUrl: 'https://attacker.example' }, adapter)).not.toHaveProperty(+ 'apiToken',+ );+ });+});+describe('the all-sessions scope', () => {it.each([null, undefined, '', '*'])('is one key whichever way it is spelled (%j)', scope => {expect(sessionScopeKey(scope)).toBe('*');diff --git a/src/core/plugins/plugin-activation.ts b/src/core/plugins/plugin-activation.tsindex cfb7f093b..094bc08e8 100644--- a/src/core/plugins/plugin-activation.ts+++ b/src/core/plugins/plugin-activation.ts@@ -1,3 +1,5 @@+import type { PluginConfigField, PluginManifest } from './plugin.interfaces';+/*** The all-sessions scope is spelled null, undefined or '*' depending on where it was stored; this maps* every spelling to '*' and leaves a concrete session id as it is, so two scopes compare by key.@@ -43,6 +45,73 @@ function deepMerge(base: Record<string, unknown>, override: Record<string, unknoreturn out;}+/**+ * What a layered config merge needs of a manifest: the config keys that name a host the plugin may+ * call (`net.allowConfigHosts`) and the schema that says which fields are secret.+ */+export type ConfigLayerManifest = Pick<PluginManifest, 'net' | 'configSchema'>;++/** The origin a host key names, the trimmed text when it is no URL, or null when it names nothing. */+function hostOf(value: unknown): string | null {+ if (typeof value !== 'string' || value.trim() === '') return null;+ try {+ const { origin } = new URL(value);+ return origin === 'null' ? value.trim() : origin;+ } catch {+ return value.trim();+ }+}++/** Whether `layer` points a host key at an origin other than the one `beneath` names. */+const redirectsHost = (beneath: Record<string, unknown>, layer: Record<string, unknown>, hostKeys: string[]): boolean =>+ hostKeys.some(key => {+ const next = hostOf(layer[key]);+ return next !== null && next !== hostOf(beneath[key]);+ });++const holdsSecret = (field: PluginConfigField): boolean =>+ !!field.secret ||+ Object.values(field.properties ?? {}).some(holdsSecret) ||+ (!!field.items && holdsSecret(field.items));++/**+ * `config` without its declared secret fields, at any depth. A list that holds one is dropped whole,+ * because lists are replaced and never merged.+ */+function withoutSecrets(+ config: Record<string, unknown>,+ properties: Record<string, PluginConfigField>,+): Record<string, unknown> {+ const out = { ...config };+ for (const [key, field] of Object.entries(properties)) {+ const value = out[key];+ if (value === undefined) continue;+ if (field.secret || (field.type === 'array' && holdsSecret(field))) delete out[key];+ else if (field.type === 'object' && field.properties && isPlainObject(value)) {+ out[key] = withoutSecrets(value, field.properties);+ }+ }+ return out;+}++/**+ * Merge `layer` over `beneath`. A layer that points a host key at another origin than the layer+ * beneath names must bring its own secrets: the beneath secrets belong to the host they were saved+ * for, and a key allowed to write the layer (a session-restricted admin, an instance) would otherwise+ * receive them with a host of its choosing. With no schema nothing can be told secret, so nothing is+ * inherited.+ */+function mergeLayer(+ beneath: Record<string, unknown>,+ layer: Record<string, unknown>,+ manifest: ConfigLayerManifest,+): Record<string, unknown> {+ const hostKeys = manifest.net?.allowConfigHosts;+ if (!hostKeys?.length || !redirectsHost(beneath, layer, hostKeys)) return deepMerge(beneath, layer);+ const properties = manifest.configSchema?.properties;+ return deepMerge(properties ? withoutSecrets(beneath, properties) : {}, layer);+}+/*** Layer one integration instance's own config over whatever resolution produced.*@@ -56,12 +125,16 @@ function deepMerge(base: Record<string, unknown>, override: Record<string, unkno* key the row leaves unset still resolves from the layer underneath. Whether that layer can be* attributed to this instance is the caller's decision — `PluginSandboxBridge` withholds the* scope slice once siblings exist, for exactly that reason.+ *+ * A row that names another host than the layer beneath does not inherit that layer's secrets, see+ * {@link mergeLayer}.*/export function resolveInstanceConfig(resolved: Record<string, unknown>,instanceConfig: Record<string, unknown> | null | undefined,+ manifest: ConfigLayerManifest,): Record<string, unknown> {- return instanceConfig ? deepMerge(resolved, instanceConfig) : resolved;+ return instanceConfig ? mergeLayer(resolved, instanceConfig, manifest) : resolved;}/**@@ -69,15 +142,17 @@ export function resolveInstanceConfig(* over the base ('*') config, so an override only changes the keys it specifies (at any depth) and* inherits the rest from the base — a sparse override can't drop a base key (e.g. a nested secret) it* didn't touch. A global plugin and a non-session-attributed event (no sessionId) get the base- * unchanged. Returns a fresh object on merge; never mutates the inputs.+ * unchanged. Returns a fresh object on merge; never mutates the inputs. An override that names+ * another host than the base does not inherit the base secrets, see {@link mergeLayer}.*/export function resolvePluginConfig(base: Record<string, unknown>,sessionConfig: Record<string, Record<string, unknown>> | undefined,sessionId: string | undefined,sessionScoped: boolean,+ manifest: ConfigLayerManifest,): Record<string, unknown> {if (!sessionScoped || sessionId === undefined || !sessionConfig) return base;const override = sessionConfig[sessionId];- return override ? deepMerge(base, override) : base;+ return override ? mergeLayer(base, override, manifest) : base;}diff --git a/src/core/plugins/plugin-capability-context.ts b/src/core/plugins/plugin-capability-context.tsindex 40fe120b7..85f9506a7 100644--- a/src/core/plugins/plugin-capability-context.ts+++ b/src/core/plugins/plugin-capability-context.ts@@ -224,6 +224,7 @@ export class PluginCapabilityContext {plugin.sessionConfig,hookSession.getStore()?.sessionId,plugin.manifest.sessionScoped !== false,+ plugin.manifest,);},hookManager: this.hookManager,diff --git a/src/core/plugins/plugin-sandbox-bridge.ts b/src/core/plugins/plugin-sandbox-bridge.tsindex 4c50b1873..0a38a36b9 100644--- a/src/core/plugins/plugin-sandbox-bridge.ts+++ b/src/core/plugins/plugin-sandbox-bridge.ts@@ -252,9 +252,11 @@ export class PluginSandboxBridge {plugin.sessionConfig,instance?.sessionScope ?? undefined,plugin.manifest.sessionScoped !== false,+ plugin.manifest,): plugin.config,instance?.config,+ plugin.manifest,): undefined;const result = await host.dispatchWebhook({@@ -530,6 +532,7 @@ export class PluginSandboxBridge {plugin.sessionConfig,hookCtx.sessionId,plugin.manifest.sessionScoped !== false,+ plugin.manifest,),// The chain this dispatch belongs to, so a capability the handler calls is guarded// against re-firing any event of it (not only this one) once it returns to the host.