Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): add scoped read-only ctx.engine capability

rmyndharisc03fc07fdf28
diff --git a/src/core/plugins/plugin-capability.spec.ts b/src/core/plugins/plugin-capability.spec.ts
index 9453114b6..3babd2adc 100644
--- a/src/core/plugins/plugin-capability.spec.ts
+++ b/src/core/plugins/plugin-capability.spec.ts
@@ -12,6 +12,7 @@ import {
PluginType,
} from './plugin.interfaces';
import { MessageService } from '../../modules/message/message.service';
+import { SessionService } from '../../modules/session/session.service';
function makePlugin(sessions?: string[]): PluginInstance {
const manifest: PluginManifest = {
@@ -87,3 +88,53 @@ describe('PluginLoaderService capability facade — ctx.messages', () => {
expect(messageService.sendText).not.toHaveBeenCalled();
});
});
+
+describe('PluginLoaderService capability facade — ctx.engine', () => {
+ let loader: PluginLoaderService;
+ let moduleRef: { get: jest.Mock };
+
+ function build(getEngineReturn: unknown): { sessionService: { getEngine: jest.Mock } } {
+ const sessionService = { getEngine: jest.fn().mockReturnValue(getEngineReturn) };
+ moduleRef = { get: jest.fn().mockReturnValue(sessionService) };
+ 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,
+ );
+ return { sessionService };
+ }
+
+ function contextFor(plugin: PluginInstance): PluginContext {
+ return (
+ loader as unknown as { createPluginContext: (p: PluginInstance) => PluginContext }
+ ).createPluginContext(plugin);
+ }
+
+ it('engine.getGroupInfo delegates to SessionService.getEngine(id).getGroupInfo', async () => {
+ const engine = { getGroupInfo: jest.fn().mockResolvedValue({ id: '[email protected]' }) };
+ const { sessionService } = build(engine);
+ const ctx = contextFor(makePlugin(['*']));
+ await ctx.engine.getGroupInfo('sess-1', '[email protected]');
+ expect(moduleRef.get).toHaveBeenCalledWith(SessionService, { strict: false });
+ expect(sessionService.getEngine).toHaveBeenCalledWith('sess-1');
+ expect(engine.getGroupInfo).toHaveBeenCalledWith('[email protected]');
+ });
+
+ it('throws PluginCapabilityError when the session has no active engine', async () => {
+ build(undefined);
+ const ctx = contextFor(makePlugin(['*']));
+ await expect(ctx.engine.getContacts('dead-session')).rejects.toBeInstanceOf(PluginCapabilityError);
+ });
+
+ it('rejects an out-of-scope session before resolving the engine', async () => {
+ const { sessionService } = build({ getChats: jest.fn() });
+ const ctx = contextFor(makePlugin(['allowed']));
+ await expect(ctx.engine.getChats('other')).rejects.toBeInstanceOf(PluginCapabilityError);
+ expect(sessionService.getEngine).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index c50e545df..8effcb1b8 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,
+ PluginEngineReadCapability,
PluginManifest,
PluginMessagingCapability,
PluginInstance,
@@ -18,6 +19,8 @@ import {
} from './plugin.interfaces';
import { PluginStorageService } from './plugin-storage.service';
import { MessageService } from '../../modules/message/message.service';
+import { SessionService } from '../../modules/session/session.service';
+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
/**
* Resolve a plugin's `main` entry to an absolute path, asserting it stays inside
@@ -294,6 +297,22 @@ export class PluginLoaderService implements OnModuleInit {
}
}
+ /**
+ * Scope-check, then resolve the live engine for a session. getEngine returns undefined for an
+ * unknown OR unstarted session (no throw), so guard it into a defined PluginCapabilityError.
+ * A present-but-not-READY engine throws EngineNotReadyError from the adapter on use (→ 409).
+ */
+ private resolveEngine(manifest: PluginManifest, sessionId: string): IWhatsAppEngine {
+ this.assertSessionAllowed(manifest, sessionId);
+ const engine = this.moduleRef.get(SessionService, { strict: false }).getEngine(sessionId);
+ if (!engine) {
+ throw new PluginCapabilityError(
+ `Session ${sessionId} has no active engine (unknown or not started)`,
+ );
+ }
+ return engine;
+ }
+
private createPluginContext(plugin: PluginInstance): PluginContext {
const pluginLogger: PluginLogger = {
log: (message, meta) =>
@@ -332,6 +351,16 @@ export class PluginLoaderService implements OnModuleInit {
.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(),
+ getContactById: async (sessionId, contactId) =>
+ this.resolveEngine(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(),
+ } satisfies PluginEngineReadCapability,
};
}
diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.ts
index adf544c63..930462a70 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -5,6 +5,7 @@
import { HookManager, HookEvent, HookHandler } from '../hooks';
import type { MessageResponseDto } from '../../modules/message/dto';
+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
// ============================================================================
// Plugin Types
@@ -108,6 +109,14 @@ export interface PluginMessagingCapability {
): Promise<MessageResponseDto>;
}
+export interface PluginEngineReadCapability {
+ getGroupInfo(sessionId: string, groupId: string): ReturnType<IWhatsAppEngine['getGroupInfo']>;
+ getContacts(sessionId: string): ReturnType<IWhatsAppEngine['getContacts']>;
+ getContactById(sessionId: string, contactId: string): ReturnType<IWhatsAppEngine['getContactById']>;
+ checkNumberExists(sessionId: string, phone: string): ReturnType<IWhatsAppEngine['checkNumberExists']>;
+ getChats(sessionId: string): ReturnType<IWhatsAppEngine['getChats']>;
+}
+
// ============================================================================
// Plugin Context (passed to plugin on initialization)
// ============================================================================
@@ -134,6 +143,9 @@ export interface PluginContext {
// Curated write surface — routes through MessageService (persistence preserved).
messages: PluginMessagingCapability;
+
+ // Read-only, scoped engine queries.
+ engine: PluginEngineReadCapability;
}
export interface PluginLogger {