Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(plugins): split the enableSandboxed and createPluginContext god methods
Yudhi Armyndharis516806487325
diff --git a/src/core/plugins/plugin-capability-context.ts b/src/core/plugins/plugin-capability-context.tsindex 1cab07ab6..d768598f4 100644--- a/src/core/plugins/plugin-capability-context.ts+++ b/src/core/plugins/plugin-capability-context.ts@@ -164,21 +164,6 @@ export class PluginCapabilityContext {}}createPluginContext(plugin: PluginInstance): PluginContext {- const pluginLogger: PluginLogger = {- log: (message, meta) =>- this.logger.log(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),- debug: (message, meta) =>- this.logger.debug(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),- warn: (message, meta) =>- this.logger.warn(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),- error: (message, error, meta) =>- this.logger.error(- `[${plugin.manifest.id}] ${message}`,- error instanceof Error ? error.message : String(error),- { ...meta, pluginId: plugin.manifest.id },- ),- };-const hookSession = this.hookSession;return {pluginId: plugin.manifest.id,@@ -194,7 +179,7 @@ export class PluginCapabilityContext {);},hookManager: this.hookManager,- logger: pluginLogger,+ logger: this.buildPluginLogger(plugin),storage: this.pluginStorage.createPluginStorage(plugin.manifest.id),registerHook: (event, handler, priority) => {// Wrap with the per-session activation gate so an in-process plugin only handles events for@@ -218,200 +203,239 @@ export class PluginCapabilityContext {`Plugin ${plugin.manifest.id}: registerWebhook (ingress) is only available to sandboxed plugins`,);},- messages: {- sendText: async (sessionId, chatId, text) => {- // 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- // assertSessionActive.- this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);- this.resolveEngine(plugin, sessionId);- return this.hostServices.getMessageService().sendText(sessionId, { chatId, text });- },- reply: async (sessionId, chatId, quotedMessageId, text) => {- this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);- this.resolveEngine(plugin, sessionId);- return this.hostServices.getMessageService().reply(sessionId, { chatId, quotedMessageId, text });- },- } satisfies PluginMessagingCapability,- engine: {- 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, sessionId).getContactById(contactId),- checkNumberExists: async (sessionId, phone) =>- this.resolveEngineRead(plugin, sessionId).checkNumberExists(phone),- getChats: async sessionId => this.resolveEngineRead(plugin, sessionId).getChats(),- getChatHistory: async (sessionId, chatId, limit, includeMedia) =>- this.resolveEngineRead(plugin, sessionId).getChatHistory(- chatId,- // Clamp to the REST non-deep ceiling (MessageService.MAX_CHAT_HISTORY_LIMIT = 100) so an- // untrusted plugin can't request an unbounded history fetch.- Math.min(Math.max(Math.trunc(limit ?? 50), 1), 100),- includeMedia ?? false,- ),- canonicalChatId: (sessionId, chatId) => {- // resolveEngineRead is the gate only (engine:read permission + live session); the resolution- // itself is a synchronous host lid->phone lookup, not an engine call, mirroring the webhook- // from-filter. Not `async` (nothing to await) — a resolved promise satisfies the signature.- this.resolveEngineRead(plugin, sessionId);- return Promise.resolve(toNeutralJid(chatId, jid => this.lidMappingStore?.getCached(userPart(jid)) ?? null));- },- } satisfies PluginEngineReadCapability,- net: {- fetch: async (url, init) => {- // Two gates: the declared permission, then the effective host allowlist = manifest net.allow- // UNION the hosts of net.allowConfigHosts keys across the base config AND every per-session- // override. The host gate has no firing-session context for a sandboxed plugin's cap round-trip,- // so admit every operator-configured tenant host (all public + still SSRF-guarded at connect)- // rather than resolving a single, possibly wrong (base-only), one. The SSRF guard inside- // performPluginFetch still blocks internal IPs even when the host is allowlisted.- this.assertPermission(plugin.manifest, PluginCapabilityPermission.NET_FETCH);- const netConfigs = [plugin.config ?? {}, ...Object.values(plugin.sessionConfig ?? {})];- const allow = [- ...new Set(- netConfigs.flatMap(cfg =>- effectiveNetAllow(plugin.manifest.net?.allow, plugin.manifest.net?.allowConfigHosts, cfg),- ),+ messages: this.buildMessagesCapability(plugin),+ engine: this.buildEngineReadCapability(plugin),+ net: this.buildNetCapability(plugin),+ conversations: this.buildConversationsCapability(plugin),+ handover: this.buildHandoverCapability(plugin),+ mappings: this.buildMappingsCapability(plugin),+ };+ }++ private buildPluginLogger(plugin: PluginInstance): PluginLogger {+ return {+ log: (message, meta) =>+ this.logger.log(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),+ debug: (message, meta) =>+ this.logger.debug(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),+ warn: (message, meta) =>+ this.logger.warn(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),+ error: (message, error, meta) =>+ this.logger.error(+ `[${plugin.manifest.id}] ${message}`,+ error instanceof Error ? error.message : String(error),+ { ...meta, pluginId: plugin.manifest.id },+ ),+ };+ }++ private buildMessagesCapability(plugin: PluginInstance): PluginMessagingCapability {+ return {+ sendText: async (sessionId, chatId, text) => {+ // 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+ // assertSessionActive.+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);+ this.resolveEngine(plugin, sessionId);+ return this.hostServices.getMessageService().sendText(sessionId, { chatId, text });+ },+ reply: async (sessionId, chatId, quotedMessageId, text) => {+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);+ this.resolveEngine(plugin, sessionId);+ return this.hostServices.getMessageService().reply(sessionId, { chatId, quotedMessageId, text });+ },+ } satisfies PluginMessagingCapability;+ }++ private buildEngineReadCapability(plugin: PluginInstance): PluginEngineReadCapability {+ return {+ 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, sessionId).getContactById(contactId),+ checkNumberExists: async (sessionId, phone) => this.resolveEngineRead(plugin, sessionId).checkNumberExists(phone),+ getChats: async sessionId => this.resolveEngineRead(plugin, sessionId).getChats(),+ getChatHistory: async (sessionId, chatId, limit, includeMedia) =>+ this.resolveEngineRead(plugin, sessionId).getChatHistory(+ chatId,+ // Clamp to the REST non-deep ceiling (MessageService.MAX_CHAT_HISTORY_LIMIT = 100) so an+ // untrusted plugin can't request an unbounded history fetch.+ Math.min(Math.max(Math.trunc(limit ?? 50), 1), 100),+ includeMedia ?? false,+ ),+ canonicalChatId: (sessionId, chatId) => {+ // resolveEngineRead is the gate only (engine:read permission + live session); the resolution+ // itself is a synchronous host lid->phone lookup, not an engine call, mirroring the webhook+ // from-filter. Not `async` (nothing to await) — a resolved promise satisfies the signature.+ this.resolveEngineRead(plugin, sessionId);+ return Promise.resolve(toNeutralJid(chatId, jid => this.lidMappingStore?.getCached(userPart(jid)) ?? null));+ },+ } satisfies PluginEngineReadCapability;+ }++ private buildNetCapability(plugin: PluginInstance): PluginNetCapability {+ return {+ fetch: async (url, init) => {+ // Two gates: the declared permission, then the effective host allowlist = manifest net.allow+ // UNION the hosts of net.allowConfigHosts keys across the base config AND every per-session+ // override. The host gate has no firing-session context for a sandboxed plugin's cap round-trip,+ // so admit every operator-configured tenant host (all public + still SSRF-guarded at connect)+ // rather than resolving a single, possibly wrong (base-only), one. The SSRF guard inside+ // performPluginFetch still blocks internal IPs even when the host is allowlisted.+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.NET_FETCH);+ const netConfigs = [plugin.config ?? {}, ...Object.values(plugin.sessionConfig ?? {})];+ const allow = [+ ...new Set(+ netConfigs.flatMap(cfg =>+ effectiveNetAllow(plugin.manifest.net?.allow, plugin.manifest.net?.allowConfigHosts, cfg),),- ];- if (!isNetHostAllowed(allow, url)) {- throw new PluginCapabilityError(- `Plugin ${plugin.manifest.id} may not fetch ${url} — add its host to net.allow or net.allowConfigHosts`,- );- }- return performPluginFetch(url, init);- },- } satisfies PluginNetCapability,- conversations: buildConversationSendFacade({- manifest: plugin.manifest,- assertPermission: this.assertPermission.bind(this),- assertSessionActive: (sessionId: string) => this.assertSessionActive(plugin, sessionId),- resolveChatId: async env => {- if (!env.instanceId || !env.source?.externalConversationId) {- throw new PluginCapabilityError(- `Plugin ${plugin.manifest.id}: conversation.send requires chatId, or both instanceId and source to resolve one`,- );- }- const mapping = await this.hostServices- .getConversationMappingService()- .getByProvider(plugin.manifest.id, env.instanceId, env.source.externalConversationId);- if (!mapping) {- throw new PluginCapabilityError(- `Plugin ${plugin.manifest.id}: no conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId}`,- );- }- // Fail closed on a cross-session mapping: getByProvider keys on (pluginId, instanceId,- // providerConversationId) only, so a stale row can resolve to a chat owned by a DIFFERENT- // session than the envelope's. Parity with the assertSessionActive(m.sessionId) check on- // mappings.getByProvider below — never send through a session the mapping does not belong to.- // (mapping.sessionId is NOT NULL in the entity, so a plain inequality check suffices. The- // env.sessionId guard is for the type only — the facade rejects a missing sessionId first.)- if (env.sessionId && mapping.sessionId !== env.sessionId) {- // Repair path: the mapping's session was DELETED (operator re-paired under a new id), so- // the row is stale rather than cross-session. Rebind it to the envelope's session —- // already activation-gated by the facade — and let the send proceed; without this the- // dead session's rows bricked conversation.send permanently. A mapping owned by another- // EXISTING session is a genuine cross-session violation and still throws.- if (await this.isSessionGone(mapping.sessionId)) {- await this.hostServices.getConversationMappingService().rebindSession(mapping.id, env.sessionId);- this.logger.warn(- `Rebound conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId} ` +- `from deleted session ${mapping.sessionId} to ${env.sessionId}`,- { pluginId: plugin.manifest.id, action: 'conversation_mapping_rebound' },- );- return mapping.chatId;- }- throw new PluginCapabilityError(- `Plugin ${plugin.manifest.id}: conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId} belongs to session ${mapping.sessionId}, not ${env.sessionId}`,- );- }- return mapping.chatId;- },- // Re-establish the in-flight hook context around the downstream send so an adapter that calls- // conversation.send from within its own ingress handling can't echo-loop back into itself via- // its own outbound message:sending hook. Gate on an ALREADY-in-flight event (mirrors the- // worker-cap wrap's `inFlight.length > 0` check): a plain top-level send must NOT suppress- // message:sending for unrelated observers (audit/moderation) — only genuine re-entrancy does.- runGuarded: (events, run) =>- (events as HookEvent[]).some(e => this.hookManager.isInFlight(e))- ? this.hookManager.runInFlight(events as HookEvent[], run)- : run(),- sendText: (sessionId, opts) => this.hostServices.getMessageService().sendText(sessionId, opts),- reply: (sessionId, opts) => this.hostServices.getMessageService().reply(sessionId, opts),- sendMedia: (sessionId, opts) =>- dispatchConversationMedia(this.hostServices.getMessageService(), sessionId, opts),- sendLocation: (sessionId, opts) => this.hostServices.getMessageService().sendLocation(sessionId, opts),- } satisfies Parameters<typeof buildConversationSendFacade>[0]) satisfies PluginConversationsCapability,- handover: {- set: async (key, state) => {- // 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.assertSessionActive(plugin, key.sessionId);- const mapping = await this.hostServices.getConversationMappingService().get({- sessionId: key.sessionId,- chatId: key.chatId,- pluginId: plugin.manifest.id,- instanceId: key.instanceId,- });- if (!mapping) {- throw new PluginCapabilityError(- `Plugin ${plugin.manifest.id}: no conversation mapping for session ${key.sessionId} / chat ${key.chatId} / instance ${key.instanceId}`,+ ),+ ];+ if (!isNetHostAllowed(allow, url)) {+ throw new PluginCapabilityError(+ `Plugin ${plugin.manifest.id} may not fetch ${url} — add its host to net.allow or net.allowConfigHosts`,+ );+ }+ return performPluginFetch(url, init);+ },+ } satisfies PluginNetCapability;+ }++ private buildConversationsCapability(plugin: PluginInstance): PluginConversationsCapability {+ return buildConversationSendFacade({+ manifest: plugin.manifest,+ assertPermission: this.assertPermission.bind(this),+ assertSessionActive: (sessionId: string) => this.assertSessionActive(plugin, sessionId),+ resolveChatId: async env => {+ if (!env.instanceId || !env.source?.externalConversationId) {+ throw new PluginCapabilityError(+ `Plugin ${plugin.manifest.id}: conversation.send requires chatId, or both instanceId and source to resolve one`,+ );+ }+ const mapping = await this.hostServices+ .getConversationMappingService()+ .getByProvider(plugin.manifest.id, env.instanceId, env.source.externalConversationId);+ if (!mapping) {+ throw new PluginCapabilityError(+ `Plugin ${plugin.manifest.id}: no conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId}`,+ );+ }+ // Fail closed on a cross-session mapping: getByProvider keys on (pluginId, instanceId,+ // providerConversationId) only, so a stale row can resolve to a chat owned by a DIFFERENT+ // session than the envelope's. Parity with the assertSessionActive(m.sessionId) check on+ // mappings.getByProvider below — never send through a session the mapping does not belong to.+ // (mapping.sessionId is NOT NULL in the entity, so a plain inequality check suffices. The+ // env.sessionId guard is for the type only — the facade rejects a missing sessionId first.)+ if (env.sessionId && mapping.sessionId !== env.sessionId) {+ // Repair path: the mapping's session was DELETED (operator re-paired under a new id), so+ // the row is stale rather than cross-session. Rebind it to the envelope's session —+ // already activation-gated by the facade — and let the send proceed; without this the+ // dead session's rows bricked conversation.send permanently. A mapping owned by another+ // EXISTING session is a genuine cross-session violation and still throws.+ if (await this.isSessionGone(mapping.sessionId)) {+ await this.hostServices.getConversationMappingService().rebindSession(mapping.id, env.sessionId);+ this.logger.warn(+ `Rebound conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId} ` ++ `from deleted session ${mapping.sessionId} to ${env.sessionId}`,+ { pluginId: plugin.manifest.id, action: 'conversation_mapping_rebound' },);+ return mapping.chatId;}- await this.hostServices.getConversationMappingService().setHandover(mapping.id, state);- },- } satisfies PluginHandoverCapability,- mappings: {- upsert: async (key, providerConversationId) => {- this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);- this.assertSessionActive(plugin, key.sessionId);- const mappingKey = {- sessionId: key.sessionId,- chatId: key.chatId,- pluginId: plugin.manifest.id,- instanceId: key.instanceId,- };- try {- await this.hostServices.getConversationMappingService().upsert(mappingKey, providerConversationId);- } catch (error) {- if (!(error instanceof ConversationMappingConflict)) throw error;- // The reverse unique key is held by another row. If that row's session was DELETED- // (operator re-paired under a new id), the adapter can never converge — the forward key- // carries the new sessionId, so every upsert bricks on the dead session's row. Supersede- // the stale row and retry once. A row owned by an EXISTING session is a genuine conflict- // and rethrows.- const stale = await this.hostServices- .getConversationMappingService()- .getByProvider(plugin.manifest.id, key.instanceId, providerConversationId);- if (!stale || !(await this.isSessionGone(stale.sessionId))) throw error;- await this.hostServices.getConversationMappingService().delete(stale.id);- await this.hostServices.getConversationMappingService().upsert(mappingKey, providerConversationId);- }- },- get: async key => {- this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);- this.assertSessionActive(plugin, key.sessionId);- const m = await this.hostServices.getConversationMappingService().get({- sessionId: key.sessionId,- chatId: key.chatId,- pluginId: plugin.manifest.id,- instanceId: key.instanceId,- });- return m ? { providerConversationId: m.providerConversationId, handoverState: m.handoverState } : null;- },- getByProvider: async (instanceId, providerConversationId) => {- this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);- const m = await this.hostServices+ throw new PluginCapabilityError(+ `Plugin ${plugin.manifest.id}: conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId} belongs to session ${mapping.sessionId}, not ${env.sessionId}`,+ );+ }+ return mapping.chatId;+ },+ // Re-establish the in-flight hook context around the downstream send so an adapter that calls+ // conversation.send from within its own ingress handling can't echo-loop back into itself via+ // its own outbound message:sending hook. Gate on an ALREADY-in-flight event (mirrors the+ // worker-cap wrap's `inFlight.length > 0` check): a plain top-level send must NOT suppress+ // message:sending for unrelated observers (audit/moderation) — only genuine re-entrancy does.+ runGuarded: (events, run) =>+ (events as HookEvent[]).some(e => this.hookManager.isInFlight(e))+ ? this.hookManager.runInFlight(events as HookEvent[], run)+ : run(),+ sendText: (sessionId, opts) => this.hostServices.getMessageService().sendText(sessionId, opts),+ reply: (sessionId, opts) => this.hostServices.getMessageService().reply(sessionId, opts),+ sendMedia: (sessionId, opts) => dispatchConversationMedia(this.hostServices.getMessageService(), sessionId, opts),+ sendLocation: (sessionId, opts) => this.hostServices.getMessageService().sendLocation(sessionId, opts),+ } satisfies Parameters<typeof buildConversationSendFacade>[0]) satisfies PluginConversationsCapability;+ }++ private buildHandoverCapability(plugin: PluginInstance): PluginHandoverCapability {+ return {+ set: async (key, state) => {+ // 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.assertSessionActive(plugin, key.sessionId);+ const mapping = await this.hostServices.getConversationMappingService().get({+ sessionId: key.sessionId,+ chatId: key.chatId,+ pluginId: plugin.manifest.id,+ instanceId: key.instanceId,+ });+ if (!mapping) {+ throw new PluginCapabilityError(+ `Plugin ${plugin.manifest.id}: no conversation mapping for session ${key.sessionId} / chat ${key.chatId} / instance ${key.instanceId}`,+ );+ }+ await this.hostServices.getConversationMappingService().setHandover(mapping.id, state);+ },+ } satisfies PluginHandoverCapability;+ }++ private buildMappingsCapability(plugin: PluginInstance): PluginMappingsCapability {+ return {+ upsert: async (key, providerConversationId) => {+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);+ this.assertSessionActive(plugin, key.sessionId);+ const mappingKey = {+ sessionId: key.sessionId,+ chatId: key.chatId,+ pluginId: plugin.manifest.id,+ instanceId: key.instanceId,+ };+ try {+ await this.hostServices.getConversationMappingService().upsert(mappingKey, providerConversationId);+ } catch (error) {+ if (!(error instanceof ConversationMappingConflict)) throw error;+ // The reverse unique key is held by another row. If that row's session was DELETED+ // (operator re-paired under a new id), the adapter can never converge — the forward key+ // carries the new sessionId, so every upsert bricks on the dead session's row. Supersede+ // the stale row and retry once. A row owned by an EXISTING session is a genuine conflict+ // and rethrows.+ const stale = await this.hostServices.getConversationMappingService()- .getByProvider(plugin.manifest.id, instanceId, providerConversationId);- // 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,- };+ .getByProvider(plugin.manifest.id, key.instanceId, providerConversationId);+ if (!stale || !(await this.isSessionGone(stale.sessionId))) throw error;+ await this.hostServices.getConversationMappingService().delete(stale.id);+ await this.hostServices.getConversationMappingService().upsert(mappingKey, providerConversationId);+ }+ },+ get: async key => {+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);+ this.assertSessionActive(plugin, key.sessionId);+ const m = await this.hostServices.getConversationMappingService().get({+ sessionId: key.sessionId,+ chatId: key.chatId,+ pluginId: plugin.manifest.id,+ instanceId: key.instanceId,+ });+ return m ? { providerConversationId: m.providerConversationId, handoverState: m.handoverState } : null;+ },+ getByProvider: async (instanceId, providerConversationId) => {+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);+ const m = await this.hostServices+ .getConversationMappingService()+ .getByProvider(plugin.manifest.id, instanceId, providerConversationId);+ // 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-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 9673f6872..f7e5bf3fc 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -9,6 +9,7 @@ import { createLogger } from '../../common/services/logger.service';import { HookManager, HookEvent, KNOWN_HOOK_EVENTS, isKnownHookEvent } from '../hooks';import {PluginCapabilityPermission,+ PluginContext,PluginManifest,PluginInstance,PluginRegistryEntry,@@ -82,6 +83,13 @@ const SANDBOX_LOG_MAX_PER_WINDOW = 200;const SANDBOX_LOG_WINDOW_MS = 10000;const SANDBOX_LOG_MAX_MESSAGE_LENGTH = 8192;+/** Per-enable log-relay rate-limit window, shared by the onLog relay and the onWorkerExit final flush. */+interface SandboxLogRelayState {+ windowStart: number;+ count: number;+ dropped: number;+}+/*** Host process.env keys an untrusted plugin worker is allowed to see. Everything else — secrets like* API_MASTER_KEY, API_KEY_PEPPER, the DATABASE_/REDIS_ vars, DOCKER_HOST — is withheld. The worker is@@ -1097,19 +1105,75 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap// identically. The worker can only ask; the host is the gatekeeper.const context = this.capabilities.createPluginContext(plugin);- // When the worker subscribes to a hook, register a shim with the hook manager that dispatches the- // event into the worker (time-bounded, so a wedged plugin can't stall the chain). The shim looks- // the host up at fire time, so disabling the plugin (which removes it + unregisters hooks) stops it.- // Harden the IPC boundary against an untrusted worker flooding the host hook registry. HookEvent is- // a type-only union and the wire payload is an arbitrary string, so a hostile/buggy worker can post- // 'hook-subscribe' with (a) the same event repeatedly and (b) unbounded fabricated event names- // ('x:0','x:1',…). Without guards each call adds a live host-side registration (unbounded host-heap- // growth + an O(n log n) re-sort). Three guards, all local to this enableSandboxed call (dropped on- // disable): reject unknown events (bounds growth to the finite known set + drops events that can- // never fire), dedup per event, and a belt-and-suspenders size cap.+ const onHookSubscribe = this.buildHookSubscribeHandler(pluginId, plugin);++ // When the worker claims an ingress route, record it against the manifest-declared routes so the+ // host knows which routes this worker will handle. Same hardening as onHookSubscribe (the wire+ // `route` is an arbitrary untrusted string): drop when the manifest lacks 'webhook:ingress', drop+ // an undeclared route (warn once), dedup, and cap. subscribedRoutes is local to this enable call,+ // so it is dropped on disable exactly as subscribedEvents is.+ const subscribedRoutes = new Set<string>();+ const declaredRoutes = new Set((plugin.manifest.ingress ?? []).map(r => r.route));+ const onWebhookSubscribe = makeOnWebhookSubscribe({+ pluginId,+ declaredRoutes,+ hasPermission: (plugin.manifest.permissions ?? []).includes(PluginCapabilityPermission.WEBHOOK_INGRESS),+ subscribed: subscribedRoutes,+ maxRoutes: declaredRoutes.size,+ warn: (message, meta) => this.logger.warn(message, meta),+ });++ const logRelayState: SandboxLogRelayState = { windowStart: Date.now(), count: 0, dropped: 0 };+ const onLog = this.buildLogRelay(pluginId, context, logRelayState);++ const onSearchProviderRegister = this.buildSearchProviderRegistrar(pluginId, plugin);++ const onWorkerExit = this.buildWorkerExitHandler(pluginId, logRelayState);++ const host = this.createSandboxHost(+ (verb, args) => dispatchCapabilityVerb(context, verb, args),+ onHookSubscribe,+ onWebhookSubscribe,+ onLog,+ // Re-establish the in-flight hook context for worker-initiated capability calls, so a sandboxed+ // plugin that sends from within a send hook can't loop the event back into itself unboundedly.+ (events, run) => this.hookManager.runInFlight(events as HookEvent[], run),+ onSearchProviderRegister,+ onWorkerExit,+ );+ this.sandboxHosts.set(pluginId, host);+ try {+ await host.load(mainPath, { pluginId, config: plugin.config }, SANDBOX_LIFECYCLE_TIMEOUT_MS);+ await host.runLifecycle('onLoad', SANDBOX_LIFECYCLE_TIMEOUT_MS);+ await host.runLifecycle('onEnable', SANDBOX_LIFECYCLE_TIMEOUT_MS);+ } catch (error) {+ this.sandboxHosts.delete(pluginId);+ // Drop a search provider registered mid-onEnable before the failure: without this, a plugin that+ // registers then throws leaves a dead provider as the ACTIVE registry entry in auto mode, so every+ // /search routes to a terminated worker → outage. Mirrors disablePlugin's cleanup.+ unregisterPluginSearchProvider(this.hostServices.getSearchRegistry(), pluginId);+ await host.terminate().catch(() => undefined);+ throw error;+ }+ }++ // When the worker subscribes to a hook, register a shim with the hook manager that dispatches the+ // event into the worker (time-bounded, so a wedged plugin can't stall the chain). The shim looks+ // the host up at fire time, so disabling the plugin (which removes it + unregisters hooks) stops it.+ // Harden the IPC boundary against an untrusted worker flooding the host hook registry. HookEvent is+ // a type-only union and the wire payload is an arbitrary string, so a hostile/buggy worker can post+ // 'hook-subscribe' with (a) the same event repeatedly and (b) unbounded fabricated event names+ // ('x:0','x:1',…). Without guards each call adds a live host-side registration (unbounded host-heap+ // growth + an O(n log n) re-sort). Three guards, all local to this enableSandboxed call (dropped on+ // disable): reject unknown events (bounds growth to the finite known set + drops events that can+ // never fire), dedup per event, and a belt-and-suspenders size cap.+ private buildHookSubscribeHandler(+ pluginId: string,+ plugin: PluginInstance,+ ): (event: string, priority?: number) => void {const subscribedEvents = new Set<HookEvent>();let unknownEventWarned = false;- const onHookSubscribe = (event: string, priority?: number): void => {+ return (event: string, priority?: number): void => {if (!isKnownHookEvent(event)) {if (!unknownEventWarned) {unknownEventWarned = true; // warn at most once per plugin so a flood isn't a log-flood vector@@ -1197,49 +1261,36 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrappriority,);};+ }- // When the worker claims an ingress route, record it against the manifest-declared routes so the- // host knows which routes this worker will handle. Same hardening as onHookSubscribe (the wire- // `route` is an arbitrary untrusted string): drop when the manifest lacks 'webhook:ingress', drop- // an undeclared route (warn once), dedup, and cap. subscribedRoutes is local to this enable call,- // so it is dropped on disable exactly as subscribedEvents is.- const subscribedRoutes = new Set<string>();- const declaredRoutes = new Set((plugin.manifest.ingress ?? []).map(r => r.route));- const onWebhookSubscribe = makeOnWebhookSubscribe({- pluginId,- declaredRoutes,- hasPermission: (plugin.manifest.permissions ?? []).includes(PluginCapabilityPermission.WEBHOOK_INGRESS),- subscribed: subscribedRoutes,- maxRoutes: declaredRoutes.size,- warn: (message, meta) => this.logger.warn(message, meta),- });-- // Route the worker plugin's ctx.logger.* calls to the same per-plugin logger an in-process plugin- // uses, so sandboxed plugins log identically (prefixed + structured) instead of bare stdout. The- // relay is bounded: oversized lines are truncated and throughput is capped per window — a chatty- // or buggy plugin must not flood the host log. Dropped lines are counted and surfaced as one warn- // per window (never one line per drop, or the bound itself would be a flood vector), plus a final- // flush on worker exit so a plugin that goes quiet first doesn't silently lose the count. State is- // local to this enable call, so it resets on disable.- let logWindowStart = Date.now();- let logCount = 0;- let logDropped = 0;- const onLog = (level: PluginLogLevel, message: string, meta?: Record<string, unknown>): void => {+ // Route the worker plugin's ctx.logger.* calls to the same per-plugin logger an in-process plugin+ // uses, so sandboxed plugins log identically (prefixed + structured) instead of bare stdout. The+ // relay is bounded: oversized lines are truncated and throughput is capped per window — a chatty+ // or buggy plugin must not flood the host log. Dropped lines are counted and surfaced as one warn+ // per window (never one line per drop, or the bound itself would be a flood vector), plus a final+ // flush on worker exit so a plugin that goes quiet first doesn't silently lose the count. State is+ // local to this enable call, so it resets on disable.+ private buildLogRelay(+ pluginId: string,+ context: PluginContext,+ state: SandboxLogRelayState,+ ): (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void {+ return (level: PluginLogLevel, message: string, meta?: Record<string, unknown>): void => {const now = Date.now();- if (now - logWindowStart >= SANDBOX_LOG_WINDOW_MS) {- if (logDropped > 0) {+ if (now - state.windowStart >= SANDBOX_LOG_WINDOW_MS) {+ if (state.dropped > 0) {this.logger.warn(- `Dropped ${logDropped} log messages from sandboxed plugin ${pluginId} (log relay rate limit)`,- { pluginId, action: 'sandbox_log_relay_dropped', dropped: logDropped },+ `Dropped ${state.dropped} log messages from sandboxed plugin ${pluginId} (log relay rate limit)`,+ { pluginId, action: 'sandbox_log_relay_dropped', dropped: state.dropped },);}- logWindowStart = now;- logCount = 0;- logDropped = 0;+ state.windowStart = now;+ state.count = 0;+ state.dropped = 0;}- logCount++;- if (logCount > SANDBOX_LOG_MAX_PER_WINDOW) {- logDropped++;+ state.count++;+ if (state.count > SANDBOX_LOG_MAX_PER_WINDOW) {+ state.dropped++;return;}const bounded =@@ -1249,14 +1300,16 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapif (level === 'error') context.logger.error(bounded, undefined, meta);else context.logger[level](bounded, meta);};+ }- // When the worker declares itself a search provider (ctx.registerSearchProvider →- // search-provider-register), register a PluginSearchProvider in the SearchProviderRegistry. The host- // is in sandboxHosts by the time registration fires (during onLoad/onEnable), so look it up lazily- // like onHookSubscribe. Search disabled (no registry, or SEARCH_PROVIDER=none) → the util skips, and- // a manifest without 'search:provide' is denied there — the wire declaration is untrusted input, and- // this bridge bypasses the capability router that gates the ctx.* capabilities.- const onSearchProviderRegister = (): void => {+ // When the worker declares itself a search provider (ctx.registerSearchProvider →+ // search-provider-register), register a PluginSearchProvider in the SearchProviderRegistry. The host+ // is in sandboxHosts by the time registration fires (during onLoad/onEnable), so look it up lazily+ // like onHookSubscribe. Search disabled (no registry, or SEARCH_PROVIDER=none) → the util skips, and+ // a manifest without 'search:provide' is denied there — the wire declaration is untrusted input, and+ // this bridge bypasses the capability router that gates the ctx.* capabilities.+ private buildSearchProviderRegistrar(pluginId: string, plugin: PluginInstance): () => void {+ return (): void => {const liveHost = this.sandboxHosts.get(pluginId);if (!liveHost) return;registerPluginSearchProvider({@@ -1270,22 +1323,27 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapwarn: (message, meta) => this.logger.warn(message, meta),});};+ }- // A worker that crashes AFTER a successful enable is otherwise invisible to the loader (handleExit only- // drains in-flight calls). Drop the plugin's search-provider entry so the registry falls back to- // builtin-fts instead of routing every /search to a dead worker (auto mode would otherwise pin the dead- // provider ACTIVE). Mirrors the enable-failure cleanup. Broader crash-lifecycle cleanup (status, hooks)- // is a pre-existing gap for all bridges and out of scope here.- const onWorkerExit = (code: number, intentional: boolean): void => {+ // A worker that crashes AFTER a successful enable is otherwise invisible to the loader (handleExit only+ // drains in-flight calls). Drop the plugin's search-provider entry so the registry falls back to+ // builtin-fts instead of routing every /search to a dead worker (auto mode would otherwise pin the dead+ // provider ACTIVE). Mirrors the enable-failure cleanup. Broader crash-lifecycle cleanup (status, hooks)+ // is a pre-existing gap for all bridges and out of scope here.+ private buildWorkerExitHandler(+ pluginId: string,+ logRelayState: SandboxLogRelayState,+ ): (code: number, intentional: boolean) => void {+ return (code: number, intentional: boolean): void => {// Final log-relay flush: the per-window drop warn above only fires when a new line arrives in a// later window, so without this a plugin that goes quiet (or is disabled) before the rollover// silently discards its pending count. The worker is gone, so no further lines can arrive.- if (logDropped > 0) {+ if (logRelayState.dropped > 0) {this.logger.warn(- `Dropped ${logDropped} log messages from sandboxed plugin ${pluginId} (log relay rate limit)`,- { pluginId, action: 'sandbox_log_relay_dropped', dropped: logDropped },+ `Dropped ${logRelayState.dropped} log messages from sandboxed plugin ${pluginId} (log relay rate limit)`,+ { pluginId, action: 'sandbox_log_relay_dropped', dropped: logRelayState.dropped },);- logDropped = 0;+ logRelayState.dropped = 0;}// Always release the search-provider slot so the registry can fall back to builtin-fts. On a crash// this is the only cleanup; on a deliberate disable/enable-failure the explicit unregister already@@ -1310,32 +1368,6 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapaction: 'sandbox_worker_exit',});};-- const host = this.createSandboxHost(- (verb, args) => dispatchCapabilityVerb(context, verb, args),- onHookSubscribe,- onWebhookSubscribe,- onLog,- // Re-establish the in-flight hook context for worker-initiated capability calls, so a sandboxed- // plugin that sends from within a send hook can't loop the event back into itself unboundedly.- (events, run) => this.hookManager.runInFlight(events as HookEvent[], run),- onSearchProviderRegister,- onWorkerExit,- );- this.sandboxHosts.set(pluginId, host);- try {- await host.load(mainPath, { pluginId, config: plugin.config }, SANDBOX_LIFECYCLE_TIMEOUT_MS);- await host.runLifecycle('onLoad', SANDBOX_LIFECYCLE_TIMEOUT_MS);- await host.runLifecycle('onEnable', SANDBOX_LIFECYCLE_TIMEOUT_MS);- } catch (error) {- this.sandboxHosts.delete(pluginId);- // Drop a search provider registered mid-onEnable before the failure: without this, a plugin that- // registers then throws leaves a dead provider as the ACTIVE registry entry in auto mode, so every- // /search routes to a terminated worker → outage. Mirrors disablePlugin's cleanup.- unregisterPluginSearchProvider(this.hostServices.getSearchRegistry(), pluginId);- await host.terminate().catch(() => undefined);- throw error;- }}getPlugin(pluginId: string): PluginInstance | undefined {