Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): enforce declared capability permissions at the boundary (#412)

Yudhi Armyndharisb49fd1d112b2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2161f9ac3..0cd03db48 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
+- **Plugin capability permissions are now enforced.** A plugin may use a capability — `ctx.messages.*`
+ (send/reply) or `ctx.engine.*` (read-only group/contact/chat queries) — only if its manifest
+ declares the matching permission (`messages:send` / `engine:read`); a plugin that doesn't declare
+ it, or declares none, is denied with a clear `PluginCapabilityError`. Previously `manifest.permissions`
+ was advisory and unenforced. The built-in extensions declare exactly what they use (auto-reply:
+ `messages:send`; translation: `messages:send` + `engine:read`) and are unaffected; custom plugins
+ must declare the permissions for the capabilities they call. (#412)
- **Bulk-message variable substitution now uses the same `{{name}}` syntax as message templates.**
`POST /sessions/:id/messages/send-bulk` previously substituted `messages[].variables` with a
single-brace `{name}` convention, inconsistent with the double-brace `{{name}}` used everywhere
diff --git a/src/core/plugins/plugin-capability.spec.ts b/src/core/plugins/plugin-capability.spec.ts
index a907b4bf8..dd24d02e8 100644
--- a/src/core/plugins/plugin-capability.spec.ts
+++ b/src/core/plugins/plugin-capability.spec.ts
@@ -14,7 +14,7 @@ import {
import { MessageService } from '../../modules/message/message.service';
import { SessionService } from '../../modules/session/session.service';
-function makePlugin(sessions?: string[]): PluginInstance {
+function makePlugin(sessions?: string[], permissions: string[] = ['messages:send', 'engine:read']): PluginInstance {
const manifest: PluginManifest = {
id: 'test-ext',
name: 'Test Extension',
@@ -22,6 +22,7 @@ function makePlugin(sessions?: string[]): PluginInstance {
type: PluginType.EXTENSION,
main: 'index.ts',
sessions,
+ permissions,
};
return { manifest, status: PluginStatus.INSTALLED, config: {}, instance: null };
}
@@ -100,6 +101,19 @@ describe('PluginLoaderService capability facade — ctx.messages', () => {
await expect(ctx.messages.sendText('dead-session', '[email protected]', 'hi')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(messageService.sendText).not.toHaveBeenCalled();
});
+
+ it('denies sendText when the plugin does not declare the messages:send permission', async () => {
+ const ctx = contextFor(makePlugin(['*'], [])); // no permissions
+ await expect(ctx.messages.sendText('sess-1', '[email protected]', 'hi')).rejects.toBeInstanceOf(PluginCapabilityError);
+ expect(moduleRef.get).not.toHaveBeenCalled();
+ expect(messageService.sendText).not.toHaveBeenCalled();
+ });
+
+ it('denies reply when the plugin does not declare the messages:send permission', async () => {
+ const ctx = contextFor(makePlugin(['*'], []));
+ await expect(ctx.messages.reply('sess-1', '[email protected]', 'q', 'hi')).rejects.toBeInstanceOf(PluginCapabilityError);
+ expect(messageService.reply).not.toHaveBeenCalled();
+ });
});
describe('PluginLoaderService capability facade — ctx.engine', () => {
@@ -150,4 +164,19 @@ describe('PluginLoaderService capability facade — ctx.engine', () => {
await expect(ctx.engine.getChats('other')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(sessionService.getEngine).not.toHaveBeenCalled();
});
+
+ it('denies engine.getGroupInfo when the plugin does not declare the engine:read permission', async () => {
+ const { sessionService } = build({ getGroupInfo: jest.fn() });
+ const ctx = contextFor(makePlugin(['*'], ['messages:send'])); // has messages, lacks engine:read
+ await expect(ctx.engine.getGroupInfo('sess-1', '[email protected]')).rejects.toBeInstanceOf(PluginCapabilityError);
+ expect(sessionService.getEngine).not.toHaveBeenCalled();
+ });
+
+ it('allows engine.getGroupInfo when the plugin declares engine:read', async () => {
+ const engine = { getGroupInfo: jest.fn().mockResolvedValue({ id: '[email protected]' }) };
+ build(engine);
+ const ctx = contextFor(makePlugin(['*'], ['engine:read']));
+ await ctx.engine.getGroupInfo('sess-1', '[email protected]');
+ expect(engine.getGroupInfo).toHaveBeenCalledWith('[email protected]');
+ });
});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 81253fee8..f9988dc38 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -7,6 +7,7 @@ import { createLogger } from '../../common/services/logger.service';
import { HookManager } from '../hooks';
import {
PluginCapabilityError,
+ PluginCapabilityPermission,
PluginEngineReadCapability,
PluginManifest,
PluginMessagingCapability,
@@ -335,6 +336,20 @@ export class PluginLoaderService implements OnModuleInit {
return this.moduleRef.get(mod.SessionService, { strict: false });
}
+ /**
+ * Enforce a plugin's declared manifest permissions at the capability boundary. A plugin may only
+ * use a capability whose permission string it declares in `manifest.permissions`; anything else
+ * (including a manifest with no permissions) is denied. Runs first in each capability verb so a
+ * missing grant fails fast and uniformly as a PluginCapabilityError.
+ */
+ private assertPermission(manifest: PluginManifest, permission: PluginCapabilityPermission): void {
+ if (!(manifest.permissions ?? []).includes(permission)) {
+ throw new PluginCapabilityError(
+ `Plugin ${manifest.id} is missing the '${permission}' permission required for this capability`,
+ );
+ }
+ }
+
/**
* Enforce a plugin's manifest session scope. Runs BEFORE any engine/message resolution —
* sessionId is supplied by the plugin, so this is the security boundary. Absent = ['*'].
@@ -360,6 +375,12 @@ export class PluginLoaderService implements OnModuleInit {
return engine;
}
+ /** Engine read capabilities: require the `engine:read` permission, then resolve the live engine. */
+ private resolveEngineRead(manifest: PluginManifest, sessionId: string): IWhatsAppEngine {
+ this.assertPermission(manifest, PluginCapabilityPermission.ENGINE_READ);
+ return this.resolveEngine(manifest, sessionId);
+ }
+
private createPluginContext(plugin: PluginInstance): PluginContext {
const pluginLogger: PluginLogger = {
log: (message, meta) =>
@@ -388,26 +409,29 @@ export class PluginLoaderService implements OnModuleInit {
},
messages: {
sendText: async (sessionId, chatId, text) => {
- // Validate scope + that the session has a live engine BEFORE MessageService persists a
- // pending row: a dead/unstarted session must fail with PluginCapabilityError, not a raw
- // TypeError + orphaned row. resolveEngine also runs assertSessionAllowed.
+ // Validate permission + scope + that the session has a live engine BEFORE MessageService
+ // persists a pending row: a missing grant / dead session must fail with
+ // PluginCapabilityError, not a raw TypeError + orphaned row. resolveEngine also runs
+ // assertSessionAllowed.
+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);
this.resolveEngine(plugin.manifest, sessionId);
return this.getMessageService().sendText(sessionId, { chatId, text });
},
reply: async (sessionId, chatId, quotedMessageId, text) => {
+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);
this.resolveEngine(plugin.manifest, sessionId);
return this.getMessageService().reply(sessionId, { chatId, quotedMessageId, text });
},
} satisfies PluginMessagingCapability,
engine: {
getGroupInfo: async (sessionId, groupId) =>
- this.resolveEngine(plugin.manifest, sessionId).getGroupInfo(groupId),
- getContacts: async sessionId => this.resolveEngine(plugin.manifest, sessionId).getContacts(),
+ this.resolveEngineRead(plugin.manifest, sessionId).getGroupInfo(groupId),
+ getContacts: async sessionId => this.resolveEngineRead(plugin.manifest, sessionId).getContacts(),
getContactById: async (sessionId, contactId) =>
- this.resolveEngine(plugin.manifest, sessionId).getContactById(contactId),
+ this.resolveEngineRead(plugin.manifest, sessionId).getContactById(contactId),
checkNumberExists: async (sessionId, phone) =>
- this.resolveEngine(plugin.manifest, sessionId).checkNumberExists(phone),
- getChats: async sessionId => this.resolveEngine(plugin.manifest, sessionId).getChats(),
+ this.resolveEngineRead(plugin.manifest, sessionId).checkNumberExists(phone),
+ getChats: async sessionId => this.resolveEngineRead(plugin.manifest, sessionId).getChats(),
} satisfies PluginEngineReadCapability,
};
}
diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.ts
index bd02e904b..b4add6b79 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -60,7 +60,9 @@ export interface PluginManifest {
// Required features from other plugins
requires?: string[];
- // Capabilities this plugin declares (informational at this tier; not per-verb enforced)
+ // Capability permissions this plugin declares; the loader enforces them at the capability
+ // boundary (see PluginCapabilityPermission). A capability call whose permission is not declared
+ // here is denied with a PluginCapabilityError. Absent / empty = no capability access.
permissions?: string[];
// Session ids this plugin may act on, or ['*']. Absent = ['*'] (all). Enforced by the
@@ -89,7 +91,20 @@ export interface PluginConfigSchema {
// ============================================================================
/**
- * Thrown by a plugin capability when a call is rejected (out-of-scope session,
+ * Capability permissions a plugin declares in its manifest `permissions` and that the loader
+ * enforces at the capability boundary. A plugin may only use a capability whose permission it
+ * declares; an undeclared (or missing-permission) plugin is denied with a PluginCapabilityError.
+ */
+export const PluginCapabilityPermission = {
+ /** `ctx.messages.*` — send / reply on a session. */
+ MESSAGES_SEND: 'messages:send',
+ /** `ctx.engine.*` — read-only engine queries (group info, contacts, chats, number check). */
+ ENGINE_READ: 'engine:read',
+} as const;
+export type PluginCapabilityPermission = (typeof PluginCapabilityPermission)[keyof typeof PluginCapabilityPermission];
+
+/**
+ * Thrown by a plugin capability when a call is rejected (missing permission, out-of-scope session,
* unstarted session, etc.). Gives plugins a predictable failure instead of a raw TypeError.
*/
export class PluginCapabilityError extends Error {
diff --git a/src/plugins/extensions/extensions.module.ts b/src/plugins/extensions/extensions.module.ts
index 0d0a8089e..b3eddb95e 100644
--- a/src/plugins/extensions/extensions.module.ts
+++ b/src/plugins/extensions/extensions.module.ts
@@ -38,7 +38,8 @@ export class ExtensionsRegistrar implements OnModuleInit {
description:
"Auto-translates group messages between participants' languages via LibreTranslate. Configure in-group with /tr commands. Disabled by default.",
main: 'index.ts',
- permissions: ['messages:send'],
+ // Sends translations (messages:send) and reads group admins via ctx.engine.getGroupInfo (engine:read).
+ permissions: ['messages:send', 'engine:read'],
sessions: ['*'],
// Exposed via GET /plugins so the dashboard renders an editable config form (URL + API key, etc.).
configSchema: {