Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): add scoped ctx.messages capability, remove getService stub
rmyndharis659c4b4e80d1
diff --git a/src/core/plugins/plugin-capability.spec.ts b/src/core/plugins/plugin-capability.spec.tsnew file mode 100644index 000000000..b22b8b3d0--- /dev/null+++ b/src/core/plugins/plugin-capability.spec.ts@@ -0,0 +1,82 @@+import { ConfigService } from '@nestjs/config';+import { ModuleRef } from '@nestjs/core';+import { PluginLoaderService } from './plugin-loader.service';+import { PluginStorageService } from './plugin-storage.service';+import { HookManager } from '../hooks';+import {+ PluginCapabilityError,+ PluginContext,+ PluginInstance,+ PluginManifest,+ PluginStatus,+ PluginType,+} from './plugin.interfaces';+import { MessageService } from '../../modules/message/message.service';++function makePlugin(sessions?: string[]): PluginInstance {+ const manifest: PluginManifest = {+ id: 'test-ext',+ name: 'Test Extension',+ version: '1.0.0',+ type: PluginType.EXTENSION,+ main: 'index.ts',+ sessions,+ };+ return { manifest, status: PluginStatus.INSTALLED, config: {}, instance: null };+}++describe('PluginLoaderService capability facade — ctx.messages', () => {+ let loader: PluginLoaderService;+ let messageService: { sendText: jest.Mock; reply: jest.Mock };+ let moduleRef: { get: jest.Mock };++ beforeEach(() => {+ messageService = {+ sendText: jest.fn().mockResolvedValue({ messageId: 'wamid', timestamp: 1 }),+ reply: jest.fn().mockResolvedValue({ messageId: 'wamid', timestamp: 1 }),+ };+ moduleRef = { get: jest.fn().mockReturnValue(messageService) };+ const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;+ const pluginStorage = {+ createPluginStorage: jest.fn().mockReturnValue({}),+ } as unknown as PluginStorageService;+ loader = new PluginLoaderService(+ configService,+ new HookManager(),+ pluginStorage,+ moduleRef as unknown as ModuleRef,+ );+ });++ function contextFor(plugin: PluginInstance): PluginContext {+ return (+ loader as unknown as { createPluginContext: (p: PluginInstance) => PluginContext }+ ).createPluginContext(plugin);+ }++ it('messages.sendText delegates to MessageService.sendText with a wrapped dto', async () => {+ const ctx = contextFor(makePlugin(['*']));+ await ctx.messages.sendText('sess-1', '[email protected]', 'hi');+ expect(moduleRef.get).toHaveBeenCalledWith(MessageService, { strict: false });+ expect(messageService.sendText).toHaveBeenCalledWith('sess-1', { chatId: '[email protected]', text: 'hi' });+ });++ it('messages.reply delegates to MessageService.reply', async () => {+ const ctx = contextFor(makePlugin(['*']));+ await ctx.messages.reply('sess-1', '[email protected]', 'quoted-id', 'pong');+ expect(messageService.reply).toHaveBeenCalledWith('sess-1', {+ chatId: '[email protected]',+ quotedMessageId: 'quoted-id',+ text: 'pong',+ });+ });++ it('rejects an out-of-scope session BEFORE resolving the service', async () => {+ const ctx = contextFor(makePlugin(['allowed-session']));+ await expect(ctx.messages.sendText('other-session', '[email protected]', 'hi')).rejects.toBeInstanceOf(+ PluginCapabilityError,+ );+ expect(moduleRef.get).not.toHaveBeenCalled();+ expect(messageService.sendText).not.toHaveBeenCalled();+ });+});diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex db4bd6cc9..04f47aadb 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -1,11 +1,14 @@import { Injectable, OnModuleInit } from '@nestjs/common';import { ConfigService } from '@nestjs/config';+import { ModuleRef } from '@nestjs/core';import * as fs from 'fs';import * as path from 'path';import { createLogger } from '../../common/services/logger.service';import { HookManager } from '../hooks';import {+ PluginCapabilityError,PluginManifest,+ PluginMessagingCapability,PluginInstance,PluginStatus,PluginContext,@@ -14,6 +17,7 @@ import {PluginLogger,} from './plugin.interfaces';import { PluginStorageService } from './plugin-storage.service';+import { MessageService } from '../../modules/message/message.service';/*** Resolve a plugin's `main` entry to an absolute path, asserting it stays inside@@ -39,6 +43,10 @@ export class PluginLoaderService implements OnModuleInit {private readonly configService: ConfigService,private readonly hookManager: HookManager,private readonly pluginStorage: PluginStorageService,+ // Resolves MessageService/SessionService lazily inside capability verbs. ModuleRef+ // (not constructor injection) breaks the provider cycle+ // PluginLoaderService -> SessionService -> EngineFactory -> PluginLoaderService.+ private readonly moduleRef: ModuleRef,) {this.pluginsDir = this.configService.get<string>('plugins.dir') ?? './plugins';}@@ -273,6 +281,19 @@ export class PluginLoaderService implements OnModuleInit {});}+ /**+ * 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 = ['*'].+ */+ private assertSessionAllowed(manifest: PluginManifest, sessionId: string): void {+ const allowed = manifest.sessions ?? ['*'];+ if (!allowed.includes('*') && !allowed.includes(sessionId)) {+ throw new PluginCapabilityError(+ `Plugin ${manifest.id} is not permitted to act on session ${sessionId}`,+ );+ }+ }+private createPluginContext(plugin: PluginInstance): PluginContext {const pluginLogger: PluginLogger = {log: (message, meta) =>@@ -299,11 +320,18 @@ export class PluginLoaderService implements OnModuleInit {registerHook: (event, handler, priority) => {this.hookManager.register(plugin.manifest.id, event, handler, priority);},- getService: <T>(): T | undefined => {- // Limited service access for sandboxing- // Only expose safe services- return undefined;- },+ messages: {+ sendText: async (sessionId, chatId, text) => {+ this.assertSessionAllowed(plugin.manifest, sessionId);+ return this.moduleRef.get(MessageService, { strict: false }).sendText(sessionId, { chatId, text });+ },+ reply: async (sessionId, chatId, quotedMessageId, text) => {+ this.assertSessionAllowed(plugin.manifest, sessionId);+ return this.moduleRef+ .get(MessageService, { strict: false })+ .reply(sessionId, { chatId, quotedMessageId, text });+ },+ } satisfies PluginMessagingCapability,};}diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 7cb7e6e36..adf544c63 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -4,6 +4,7 @@*/import { HookManager, HookEvent, HookHandler } from '../hooks';+import type { MessageResponseDto } from '../../modules/message/dto';// ============================================================================// Plugin Types@@ -57,6 +58,13 @@ export interface PluginManifest {// Required features from other pluginsrequires?: string[];++ // Capabilities this plugin declares (informational at this tier; not per-verb enforced)+ permissions?: string[];++ // Session ids this plugin may act on, or ['*']. Absent = ['*'] (all). Enforced by the+ // capability facade. Static (manifest) by design: editing plugin config cannot widen scope.+ sessions?: string[];}export interface PluginConfigSchema {@@ -75,6 +83,31 @@ export interface PluginConfigSchema {>;}+// ============================================================================+// Plugin Capability+// ============================================================================++/**+ * Thrown by a plugin capability when a call is rejected (out-of-scope session,+ * unstarted session, etc.). Gives plugins a predictable failure instead of a raw TypeError.+ */+export class PluginCapabilityError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'PluginCapabilityError';+ }+}++export interface PluginMessagingCapability {+ sendText(sessionId: string, chatId: string, text: string): Promise<MessageResponseDto>;+ reply(+ sessionId: string,+ chatId: string,+ quotedMessageId: string,+ text: string,+ ): Promise<MessageResponseDto>;+}+// ============================================================================// Plugin Context (passed to plugin on initialization)// ============================================================================@@ -99,8 +132,8 @@ export interface PluginContext {// Register a hook handlerregisterHook: (event: HookEvent, handler: HookHandler, priority?: number) => void;- // Get service from DI container (limited access)- getService: <T>(token: string) => T | undefined;+ // Curated write surface — routes through MessageService (persistence preserved).+ messages: PluginMessagingCapability;}export interface PluginLogger {