Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): scope capability calls to activated sessions and bound net.fetch memory (#594)
Yudhi Armyndharisa943694d72c1
diff --git a/src/core/plugins/conversation-send-facade.spec.ts b/src/core/plugins/conversation-send-facade.spec.tsindex b5443c434..0c45d1131 100644--- a/src/core/plugins/conversation-send-facade.spec.ts+++ b/src/core/plugins/conversation-send-facade.spec.ts@@ -8,7 +8,7 @@ describe('conversation.send facade', () => {const facade = buildConversationSendFacade({manifest: manifest(['conversation:send']) as never,assertPermission: () => undefined,- assertSessionAllowed: jest.fn(),+ assertSessionActive: jest.fn(),resolveChatId: () => Promise.resolve('[email protected]'),runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),sendText: jest.fn(),@@ -23,7 +23,7 @@ describe('conversation.send facade', () => {assertPermission: (m: { permissions: string[] }, p: string) => {if (!m.permissions.includes(p)) throw new Error(`missing ${p}`);},- assertSessionAllowed: () => undefined,+ assertSessionActive: () => undefined,resolveChatId: () => Promise.resolve('[email protected]'),runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),sendText: jest.fn(),@@ -41,7 +41,7 @@ describe('conversation.send facade', () => {const facade = buildConversationSendFacade({manifest: manifest(['conversation:send']) as never,assertPermission: () => undefined,- assertSessionAllowed: jest.fn(),+ assertSessionActive: jest.fn(),resolveChatId,runGuarded,sendText,diff --git a/src/core/plugins/conversation-send-facade.ts b/src/core/plugins/conversation-send-facade.tsindex eeb30c64a..6d3386e75 100644--- a/src/core/plugins/conversation-send-facade.ts+++ b/src/core/plugins/conversation-send-facade.ts@@ -8,7 +8,9 @@ import {export interface ConversationSendDeps {manifest: PluginManifest;assertPermission: (manifest: PluginManifest, permission: string) => void;- assertSessionAllowed: (manifest: PluginManifest, sessionId: string) => void;+ // Full session gate for THIS plugin (manifest scope AND operator activation), bound to the plugin by+ // the loader — so conversation.send is confined to activated sessions like every other capability.+ assertSessionActive: (sessionId: string) => void;// Resolve the WA chat id from conversation_mappings when the envelope omits chatId.resolveChatId: (env: ConversationSendEnvelope) => Promise<string>;// Seed the hook in-flight set so an adapter's own outbound message:sending hook cannot echo-loop@@ -28,7 +30,7 @@ export function buildConversationSendFacade(deps: ConversationSendDeps) {deps.assertPermission(deps.manifest, PluginCapabilityPermission.CONVERSATION_SEND);const sessionId = env.sessionId;if (!sessionId) throw new PluginCapabilityError('conversation.send: sessionId is required');- deps.assertSessionAllowed(deps.manifest, sessionId);+ deps.assertSessionActive(sessionId);const chatId = env.chatId ?? (await deps.resolveChatId(env));// Only text/reply are wired in P0; media types are additive in a later minor.return deps.runGuarded(MESSAGE_HOOK_EVENTS, async () => {diff --git a/src/core/plugins/plugin-capability.spec.ts b/src/core/plugins/plugin-capability.spec.tsindex 827c0d398..0c23e0d00 100644--- a/src/core/plugins/plugin-capability.spec.ts+++ b/src/core/plugins/plugin-capability.spec.ts@@ -14,7 +14,12 @@ import {import { MessageService } from '../../modules/message/message.service';import { SessionService } from '../../modules/session/session.service';-function makePlugin(sessions?: string[], permissions: string[] = ['messages:send', 'engine:read']): PluginInstance {+function makePlugin(+ sessions?: string[],+ permissions: string[] = ['messages:send', 'engine:read'],+ activeSessions?: string[],+ sessionScoped?: boolean,+): PluginInstance {const manifest: PluginManifest = {id: 'test-ext',name: 'Test Extension',@@ -23,8 +28,9 @@ function makePlugin(sessions?: string[], permissions: string[] = ['messages:sendmain: 'index.ts',sessions,permissions,+ sessionScoped,};- return { manifest, status: PluginStatus.INSTALLED, config: {}, instance: null };+ return { manifest, status: PluginStatus.INSTALLED, config: {}, instance: null, activeSessions };}describe('PluginLoaderService capability facade — ctx.messages', () => {@@ -95,6 +101,33 @@ describe('PluginLoaderService capability facade — ctx.messages', () => {expect(messageService.sendText).not.toHaveBeenCalled();});+ it('denies sendText when the plugin is DEACTIVATED for the session, even if manifest.sessions is ["*"]', async () => {+ // manifest allows all sessions, but the operator activated the plugin only for sess-1 — a capability+ // call to sess-2 must be denied (per-session activation is a real boundary, not just a hook filter).+ const ctx = contextFor(makePlugin(['*'], ['messages:send', 'engine:read'], ['sess-1']));+ await expect(ctx.messages.sendText('sess-2', '[email protected]', 'hi')).rejects.toBeInstanceOf(PluginCapabilityError);+ expect(moduleRef.get).not.toHaveBeenCalled();+ expect(messageService.sendText).not.toHaveBeenCalled();+ });++ it('allows sendText when the plugin IS activated for the session', async () => {+ const ctx = contextFor(makePlugin(['*'], ['messages:send', 'engine:read'], ['sess-1']));+ await ctx.messages.sendText('sess-1', '[email protected]', 'hi');+ expect(messageService.sendText).toHaveBeenCalledWith('sess-1', { chatId: '[email protected]', text: 'hi' });+ });++ it('allows any session when activeSessions is undefined (operator never restricted it)', async () => {+ const ctx = contextFor(makePlugin(['*'], ['messages:send', 'engine:read'], undefined));+ await ctx.messages.sendText('whatever', '[email protected]', 'hi');+ expect(messageService.sendText).toHaveBeenCalledWith('whatever', { chatId: '[email protected]', text: 'hi' });+ });++ it('a global (sessionScoped:false) plugin is allowed on any session regardless of activeSessions', async () => {+ const ctx = contextFor(makePlugin(['*'], ['messages:send', 'engine:read'], [], false));+ await ctx.messages.sendText('sess-9', '[email protected]', 'hi');+ expect(messageService.sendText).toHaveBeenCalledWith('sess-9', { chatId: '[email protected]', text: 'hi' });+ });+it('rejects sendText with PluginCapabilityError when the session has no active engine', async () => {sessionService.getEngine.mockReturnValue(undefined);const ctx = contextFor(makePlugin(['*']));@@ -172,6 +205,13 @@ describe('PluginLoaderService capability facade — ctx.engine', () => {expect(sessionService.getEngine).not.toHaveBeenCalled();});+ it('denies engine reads when the plugin is deactivated for the session (activeSessions excludes it)', async () => {+ const { sessionService } = build({ getGroupInfo: jest.fn() });+ const ctx = contextFor(makePlugin(['*'], ['engine:read'], ['sess-1']));+ await expect(ctx.engine.getGroupInfo('sess-2', '[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);diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex a3c470cc4..e625ce711 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -674,13 +674,28 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {return isPluginActiveForSession(plugin.manifest.sessionScoped ?? true, plugin.activeSessions ?? ['*'], sessionId);}+ /**+ * The capability session gate. A plugin may act on `sessionId` only if BOTH hold: its manifest scope+ * allows the session (the static author boundary, assertSessionAllowed) AND the operator has activated+ * the plugin for that session (the dynamic boundary, the same gate hook dispatch uses). manifest.sessions+ * alone is not enough — a general adapter ships `['*']` and is scoped by operator activation, so without+ * the activeSessions check a plugin activated for one session could reach another's engine/mappings/+ * handover. Defaults (`activeSessions ?? ['*']`, `sessionScoped:false`) preserve every unrestricted flow.+ */+ private assertSessionActive(plugin: PluginInstance, sessionId: string): void {+ this.assertSessionAllowed(plugin.manifest, sessionId);+ if (!this.isHookActive(plugin, sessionId)) {+ throw new PluginCapabilityError(`Plugin ${plugin.manifest.id} is not activated for session ${sessionId}`);+ }+ }+/*** 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);+ private resolveEngine(plugin: PluginInstance, sessionId: string): IWhatsAppEngine {+ this.assertSessionActive(plugin, sessionId);const engine = this.getSessionService().getEngine(sessionId);if (!engine) {throw new PluginCapabilityError(`Session ${sessionId} has no active engine (unknown or not started)`);@@ -689,9 +704,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {}/** 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 resolveEngineRead(plugin: PluginInstance, sessionId: string): IWhatsAppEngine {+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.ENGINE_READ);+ return this.resolveEngine(plugin, sessionId);}/**@@ -755,7 +770,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {// Containment guard: reject a manifest.main that escapes the plugin dir.const mainPath = resolvePluginMainPath(this.pluginsDir, pluginId, plugin.manifest.main);// The capability dispatcher runs a worker request through the SAME context an in-process plugin- // gets, so permission + session-scope checks (assertPermission / assertSessionAllowed) apply+ // gets, so permission + session-scope checks (assertPermission / assertSessionActive) apply// identically. The worker can only ask; the host is the gatekeeper.const context = this.createPluginContext(plugin);@@ -950,26 +965,25 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {// 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.+ // assertSessionActive.this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);- this.resolveEngine(plugin.manifest, sessionId);+ this.resolveEngine(plugin, 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);+ this.resolveEngine(plugin, sessionId);return this.getMessageService().reply(sessionId, { chatId, quotedMessageId, text });},} satisfies PluginMessagingCapability,engine: {- getGroupInfo: async (sessionId, groupId) =>- this.resolveEngineRead(plugin.manifest, sessionId).getGroupInfo(groupId),- getContacts: async sessionId => this.resolveEngineRead(plugin.manifest, sessionId).getContacts(),+ getGroupInfo: async (sessionId, groupId) => this.resolveEngineRead(plugin, sessionId).getGroupInfo(groupId),+ getContacts: async sessionId => this.resolveEngineRead(plugin, sessionId).getContacts(),getContactById: async (sessionId, contactId) =>- this.resolveEngineRead(plugin.manifest, sessionId).getContactById(contactId),+ this.resolveEngineRead(plugin, sessionId).getContactById(contactId),checkNumberExists: async (sessionId, phone) =>- this.resolveEngineRead(plugin.manifest, sessionId).checkNumberExists(phone),- getChats: async sessionId => this.resolveEngineRead(plugin.manifest, sessionId).getChats(),+ this.resolveEngineRead(plugin, sessionId).checkNumberExists(phone),+ getChats: async sessionId => this.resolveEngineRead(plugin, sessionId).getChats(),} satisfies PluginEngineReadCapability,net: {fetch: async (url, init) => {@@ -999,7 +1013,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {conversations: buildConversationSendFacade({manifest: plugin.manifest,assertPermission: this.assertPermission.bind(this),- assertSessionAllowed: this.assertSessionAllowed.bind(this),+ assertSessionActive: (sessionId: string) => this.assertSessionActive(plugin, sessionId),resolveChatId: async env => {if (!env.instanceId || !env.source) {throw new PluginCapabilityError(@@ -1035,7 +1049,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {// Same gate as conversation.send: flipping handover is part of owning the conversation, so// it reuses CONVERSATION_SEND rather than adding a new permission.this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);- this.assertSessionAllowed(plugin.manifest, key.sessionId);+ this.assertSessionActive(plugin, key.sessionId);const mapping = await this.getConversationMappingService().get({sessionId: key.sessionId,chatId: key.chatId,@@ -1053,7 +1067,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {mappings: {upsert: async (key, providerConversationId) => {this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);- this.assertSessionAllowed(plugin.manifest, key.sessionId);+ this.assertSessionActive(plugin, key.sessionId);await this.getConversationMappingService().upsert({ sessionId: key.sessionId, chatId: key.chatId, pluginId: plugin.manifest.id, instanceId: key.instanceId },providerConversationId,@@ -1061,7 +1075,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {},get: async key => {this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);- this.assertSessionAllowed(plugin.manifest, key.sessionId);+ this.assertSessionActive(plugin, key.sessionId);const m = await this.getConversationMappingService().get({sessionId: key.sessionId,chatId: key.chatId,@@ -1077,8 +1091,8 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {instanceId,providerConversationId,);- // Parity with get/upsert: a plugin may only read a mapping for a session it is scoped to.- if (m) this.assertSessionAllowed(plugin.manifest, m.sessionId);+ // Parity with get/upsert: a plugin may only read a mapping for a session it is activated for.+ if (m) this.assertSessionActive(plugin, m.sessionId);return m ? { sessionId: m.sessionId, chatId: m.chatId, handoverState: m.handoverState } : null;},} satisfies PluginMappingsCapability,diff --git a/src/core/plugins/plugin-net.spec.ts b/src/core/plugins/plugin-net.spec.tsindex cc1f61fd8..5d7a4f1e1 100644--- a/src/core/plugins/plugin-net.spec.ts+++ b/src/core/plugins/plugin-net.spec.ts@@ -95,6 +95,33 @@ describe('performPluginFetch', () => {await expect(performPluginFetch('https://api.example.com/t', {}, { fetch: fetcher })).rejects.toThrow(/cap/i);});++ it('rejects once the global concurrent-fetch cap is reached, and recovers after slots free up', async () => {+ // Each in-flight fetch buffers up to the body cap host-side, so total buffering must stay bounded.+ // Hold all slots open with a gated fetch, prove the next call rejects fast, then drain and recover.+ let release!: () => void;+ const gate = new Promise<void>(r => (release = r));+ const blocking = (<T>(_url: string, _init: RequestInit, use: (r: Response) => Promise<T> | T): Promise<T> =>+ gate.then(() => use(cannedResponse('{}', {})))) as typeof withSafeFetch;++ const inflight: Promise<unknown>[] = [];+ for (let i = 0; i < 16; i++) {+ inflight.push(performPluginFetch('https://api.example.com/t', {}, { fetch: blocking }));+ }+ // The 17th call reserves no slot — it rejects immediately without awaiting the gate.+ await expect(performPluginFetch('https://api.example.com/t', {}, { fetch: blocking })).rejects.toThrow(+ /too many concurrent/i,+ );++ release();+ await Promise.all(inflight);++ // Slots freed → a fresh fetch succeeds again.+ const sink: { init?: RequestInit } = {};+ await expect(+ performPluginFetch('https://api.example.com/t', {}, { fetch: fakeSafeFetch(cannedResponse('{}', {}), sink) }),+ ).resolves.toMatchObject({ ok: true });+ });});describe('effectiveNetAllow', () => {diff --git a/src/core/plugins/plugin-net.ts b/src/core/plugins/plugin-net.tsindex 104ce981b..604cb19fb 100644--- a/src/core/plugins/plugin-net.ts+++ b/src/core/plugins/plugin-net.ts@@ -5,6 +5,15 @@ const DEFAULT_TIMEOUT_MS = 15000;const MAX_TIMEOUT_MS = 30000;/** Cap the buffered response body so a hostile endpoint can't exhaust host memory through a plugin. */const MAX_BODY_BYTES = 10 * 1024 * 1024;+/**+ * Global cap on concurrent plugin fetches. Each buffers up to MAX_BODY_BYTES host-side (outside the+ * worker heap cap), so without a ceiling many concurrent fetches across plugins/workers could OOM the+ * host. This bounds total plugin-fetch buffering to MAX_INFLIGHT_FETCHES × MAX_BODY_BYTES regardless of+ * plugin or worker count. Reject-when-full (mirrors the sandbox in-flight-cap pattern) instead of an+ * unbounded queue, so abuse fails fast rather than deferring the memory blow-up.+ */+const MAX_INFLIGHT_FETCHES = 16;+let inFlightFetches = 0;/** Request a sandboxed plugin may make through ctx.net.fetch. Body may be a string (text/JSON) or raw* bytes (binary uploads, e.g. multipart) — a Uint8Array survives the worker structuredClone bridge. */@@ -86,6 +95,13 @@ export async function performPluginFetch(deps: { fetch?: typeof withSafeFetch } = {},): Promise<PluginNetResponse> {const safeFetch = deps.fetch ?? withSafeFetch;+ // Reject-when-full BEFORE reserving a slot, so total concurrent host-side buffering stays bounded to+ // MAX_INFLIGHT_FETCHES × MAX_BODY_BYTES. Check + increment are synchronous (single event-loop turn),+ // so no interleaving can overshoot the cap; the slot is released in the finally below.+ if (inFlightFetches >= MAX_INFLIGHT_FETCHES) {+ throw new Error(`too many concurrent plugin net.fetch calls (max ${MAX_INFLIGHT_FETCHES}); retry shortly`);+ }+ inFlightFetches++;// Coerce a non-finite timeoutMs (a string/object/NaN from the untrusted worker) to the default// instead of letting it flow through as NaN — `Math.max('abc', 1)` is NaN, and AbortSignal.timeout(NaN)// throws a RangeError, silently defeating the documented default + hard-cap clamp.@@ -93,48 +109,52 @@ export async function performPluginFetch(typeof init.timeoutMs === 'number' && Number.isFinite(init.timeoutMs) ? init.timeoutMs : DEFAULT_TIMEOUT_MS;const timeoutMs = Math.min(Math.max(requested, 1), MAX_TIMEOUT_MS);- return safeFetch<PluginNetResponse>(- url,- {- method: init.method ?? 'GET',- headers: init.headers,- body: init.body,- signal: AbortSignal.timeout(timeoutMs),- },- async response => {- const declared = Number(response.headers.get('content-length') ?? '');- if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {- throw new Error(`plugin net.fetch response exceeds the ${MAX_BODY_BYTES}-byte cap`);- }- // Stream with a running cap so a chunked response without an honest content-length can't blow- // past the limit (arrayBuffer() would buffer the whole body first). Mirrors plugin-download.- const reader = response.body?.getReader();- const chunks: Buffer[] = [];- let total = 0;- if (reader) {- for (;;) {- const { done, value } = (await reader.read()) as { done: boolean; value?: Uint8Array };- if (done) break;- if (!value) continue;- total += value.byteLength;- if (total > MAX_BODY_BYTES) {- await reader.cancel().catch(() => undefined);- throw new Error(`plugin net.fetch response exceeds the ${MAX_BODY_BYTES}-byte cap`);+ try {+ return await safeFetch<PluginNetResponse>(+ url,+ {+ method: init.method ?? 'GET',+ headers: init.headers,+ body: init.body,+ signal: AbortSignal.timeout(timeoutMs),+ },+ async response => {+ const declared = Number(response.headers.get('content-length') ?? '');+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {+ throw new Error(`plugin net.fetch response exceeds the ${MAX_BODY_BYTES}-byte cap`);+ }+ // Stream with a running cap so a chunked response without an honest content-length can't blow+ // past the limit (arrayBuffer() would buffer the whole body first). Mirrors plugin-download.+ const reader = response.body?.getReader();+ const chunks: Buffer[] = [];+ let total = 0;+ if (reader) {+ for (;;) {+ const { done, value } = (await reader.read()) as { done: boolean; value?: Uint8Array };+ if (done) break;+ if (!value) continue;+ total += value.byteLength;+ if (total > MAX_BODY_BYTES) {+ await reader.cancel().catch(() => undefined);+ throw new Error(`plugin net.fetch response exceeds the ${MAX_BODY_BYTES}-byte cap`);+ }+ chunks.push(Buffer.from(value));}- chunks.push(Buffer.from(value));}- }- const headers: Record<string, string> = {};- response.headers.forEach((value, key) => {- headers[key] = value;- });- return {- ok: response.ok,- status: response.status,- statusText: response.statusText,- headers,- body: Buffer.concat(chunks).toString('utf-8'),- };- },- );+ const headers: Record<string, string> = {};+ response.headers.forEach((value, key) => {+ headers[key] = value;+ });+ return {+ ok: response.ok,+ status: response.status,+ statusText: response.statusText,+ headers,+ body: Buffer.concat(chunks).toString('utf-8'),+ };+ },+ );+ } finally {+ inFlightFetches--;+ }}diff --git a/src/core/plugins/sandbox/capability-router.ts b/src/core/plugins/sandbox/capability-router.tsindex 0789671b1..c333b83b9 100644--- a/src/core/plugins/sandbox/capability-router.ts+++ b/src/core/plugins/sandbox/capability-router.ts@@ -25,7 +25,7 @@ export type CapabilityContext = Pick<PluginContext, 'messages' | 'engine' | 'sto* worker cannot invoke an arbitrary method on the context. Args are positional, one per signature.** Permission + session-scope checks are NOT here — they live inside the context's own verbs- * (assertPermission / assertSessionAllowed), so a sandboxed call is gated exactly like an in-process+ * (assertPermission / assertSessionActive), so a sandboxed call is gated exactly like an in-process* one. This router is purely the wire-to-method mapping.*/export async function dispatchCapabilityVerb(