Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): SSRF-guarded ctx.net.fetch capability for sandboxed plugins (#437)

Yudhi Armyndharis3ea7b3592dbb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 21b980ec9..6d142a531 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- Plugins: a new `ctx.net.fetch` capability lets a sandboxed plugin make outbound HTTP through the host's SSRF guard (resolve-once-pin, redirects refused), gated by a `net:fetch` permission plus a manifest `net.allow` host allowlist (`host:port`, bare `host`, or `*` for any public host; internal IPs are always blocked). Responses are bounded by a timeout and a size cap. (#437)
+
## [0.6.2] - 2026-06-23
Plugin platform follow-ups (sandbox hardening, install-from-URL + catalog), a mark-chat-unread
diff --git a/src/core/plugins/plugin-capability.spec.ts b/src/core/plugins/plugin-capability.spec.ts
index dd24d02e8..827c0d398 100644
--- a/src/core/plugins/plugin-capability.spec.ts
+++ b/src/core/plugins/plugin-capability.spec.ts
@@ -180,3 +180,40 @@ describe('PluginLoaderService capability facade — ctx.engine', () => {
expect(engine.getGroupInfo).toHaveBeenCalledWith('[email protected]');
});
});
+
+describe('PluginLoaderService capability facade — ctx.net', () => {
+ function loaderWith(): PluginLoaderService {
+ const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
+ const pluginStorage = { createPluginStorage: jest.fn().mockReturnValue({}) } as unknown as PluginStorageService;
+ return new PluginLoaderService(configService, new HookManager(), pluginStorage, {
+ get: jest.fn(),
+ } as unknown as ModuleRef);
+ }
+ function netPlugin(permissions: string[], allow?: string[]): PluginInstance {
+ const manifest: PluginManifest = {
+ id: 'net-ext',
+ name: 'Net Extension',
+ version: '1.0.0',
+ type: PluginType.EXTENSION,
+ main: 'index.ts',
+ permissions,
+ net: allow ? { allow } : undefined,
+ };
+ return { manifest, status: PluginStatus.INSTALLED, config: {}, instance: null };
+ }
+ function contextFor(loader: PluginLoaderService, plugin: PluginInstance): PluginContext {
+ return (loader as unknown as { createPluginContext: (p: PluginInstance) => PluginContext }).createPluginContext(
+ plugin,
+ );
+ }
+
+ it('denies net.fetch when the plugin does not declare net:fetch', async () => {
+ const ctx = contextFor(loaderWith(), netPlugin([], ['*']));
+ await expect(ctx.net.fetch('https://api.example.com/x')).rejects.toBeInstanceOf(PluginCapabilityError);
+ });
+
+ it('denies net.fetch when the host is not in the manifest net.allow list', async () => {
+ const ctx = contextFor(loaderWith(), netPlugin(['net:fetch'], ['only.example.com:443']));
+ await expect(ctx.net.fetch('https://api.example.com/x')).rejects.toBeInstanceOf(PluginCapabilityError);
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 7a4118d8a..1509af7f2 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -11,6 +11,7 @@ import {
PluginEngineReadCapability,
PluginManifest,
PluginMessagingCapability,
+ PluginNetCapability,
PluginInstance,
PluginStatus,
PluginContext,
@@ -18,6 +19,7 @@ import {
PluginType,
PluginLogger,
} from './plugin.interfaces';
+import { isNetHostAllowed, performPluginFetch } from './plugin-net';
import { PluginStorageService } from './plugin-storage.service';
import { PluginWorkerHost } from './sandbox/plugin-worker-host';
import { WorkerThreadChannel } from './sandbox/worker-thread-channel';
@@ -691,6 +693,19 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
this.resolveEngineRead(plugin.manifest, sessionId).checkNumberExists(phone),
getChats: async sessionId => this.resolveEngineRead(plugin.manifest, sessionId).getChats(),
} satisfies PluginEngineReadCapability,
+ net: {
+ fetch: async (url, init) => {
+ // Two gates: the declared permission, then the manifest host allowlist. The SSRF guard
+ // inside performPluginFetch still blocks internal IPs even when the host is allowlisted.
+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.NET_FETCH);
+ if (!isNetHostAllowed(plugin.manifest.net?.allow, url)) {
+ throw new PluginCapabilityError(
+ `Plugin ${plugin.manifest.id} may not fetch ${url} — add its host to the manifest net.allow list`,
+ );
+ }
+ return performPluginFetch(url, init);
+ },
+ } satisfies PluginNetCapability,
};
}
diff --git a/src/core/plugins/plugin-net.spec.ts b/src/core/plugins/plugin-net.spec.ts
new file mode 100644
index 000000000..c199a336c
--- /dev/null
+++ b/src/core/plugins/plugin-net.spec.ts
@@ -0,0 +1,87 @@
+import { isNetHostAllowed, performPluginFetch } from './plugin-net';
+import type { withSafeFetch } from '../../common/security/ssrf-guard';
+
+/** A stand-in for withSafeFetch that hands `use` a canned Response and records the init it was given. */
+function fakeSafeFetch(response: Response, sink: { init?: RequestInit }): typeof withSafeFetch {
+ return (<T>(_url: string, init: RequestInit, use: (r: Response) => Promise<T> | T): Promise<T> => {
+ sink.init = init;
+ return Promise.resolve(use(response));
+ }) as typeof withSafeFetch;
+}
+
+function cannedResponse(body: string, headers: Record<string, string>, status = 200): Response {
+ const bytes = new TextEncoder().encode(body);
+ let read = false;
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status === 200 ? 'OK' : 'ERR',
+ headers: new Headers(headers),
+ // Minimal ReadableStream-like body: yields the bytes once, then done.
+ body: {
+ getReader: () => ({
+ read: () =>
+ Promise.resolve(read ? { done: true, value: undefined } : ((read = true), { done: false, value: bytes })),
+ cancel: () => Promise.resolve(),
+ }),
+ },
+ } as unknown as Response;
+}
+
+describe('isNetHostAllowed', () => {
+ it('denies by default (no allowlist)', () => {
+ expect(isNetHostAllowed(undefined, 'https://api.example.com/x')).toBe(false);
+ expect(isNetHostAllowed([], 'https://api.example.com/x')).toBe(false);
+ });
+
+ it("'*' allows any public host (the SSRF guard still blocks internal IPs at fetch time)", () => {
+ expect(isNetHostAllowed(['*'], 'https://api.example.com/x')).toBe(true);
+ expect(isNetHostAllowed(['*'], 'http://other.example.org:8080/y')).toBe(true);
+ });
+
+ it('matches host:port, defaulting the port from the scheme', () => {
+ expect(isNetHostAllowed(['api.example.com:443'], 'https://api.example.com/x')).toBe(true);
+ expect(isNetHostAllowed(['api.example.com:80'], 'http://api.example.com/x')).toBe(true);
+ expect(isNetHostAllowed(['api.example.com:443'], 'https://api.example.com:8443/x')).toBe(false);
+ });
+
+ it('a bare host (no port) allows any port on that host', () => {
+ expect(isNetHostAllowed(['api.example.com'], 'https://api.example.com:8443/x')).toBe(true);
+ expect(isNetHostAllowed(['api.example.com'], 'https://other.example.com/x')).toBe(false);
+ });
+
+ it('rejects non-http(s) schemes and unparseable URLs', () => {
+ expect(isNetHostAllowed(['*'], 'ftp://api.example.com/x')).toBe(false);
+ expect(isNetHostAllowed(['*'], 'file:///etc/passwd')).toBe(false);
+ expect(isNetHostAllowed(['*'], 'not a url')).toBe(false);
+ });
+});
+
+describe('performPluginFetch', () => {
+ it('routes through the safe-fetch guard and serializes the response', async () => {
+ const sink: { init?: RequestInit } = {};
+ const fetcher = fakeSafeFetch(cannedResponse('{"hello":"hi"}', { 'content-type': 'application/json' }), sink);
+
+ const res = await performPluginFetch(
+ 'https://api.example.com/t',
+ { method: 'POST', body: '{}', headers: { 'x-k': 'v' } },
+ { fetch: fetcher },
+ );
+
+ expect(res.ok).toBe(true);
+ expect(res.status).toBe(200);
+ expect(JSON.parse(res.body)).toEqual({ hello: 'hi' });
+ expect(res.headers['content-type']).toBe('application/json');
+ // method/headers/body are passed to the guarded fetch (which does the SSRF pinning).
+ expect(sink.init?.method).toBe('POST');
+ expect(sink.init?.body).toBe('{}');
+ });
+
+ it('rejects a response whose declared content-length exceeds the cap', async () => {
+ const sink: { init?: RequestInit } = {};
+ const big = String(11 * 1024 * 1024);
+ const fetcher = fakeSafeFetch(cannedResponse('x', { 'content-length': big }), sink);
+
+ await expect(performPluginFetch('https://api.example.com/t', {}, { fetch: fetcher })).rejects.toThrow(/cap/i);
+ });
+});
diff --git a/src/core/plugins/plugin-net.ts b/src/core/plugins/plugin-net.ts
new file mode 100644
index 000000000..8dd63f179
--- /dev/null
+++ b/src/core/plugins/plugin-net.ts
@@ -0,0 +1,107 @@
+import { withSafeFetch } from '../../common/security/ssrf-guard';
+
+/** Default + hard-cap timeout for a plugin's outbound request. */
+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;
+
+/** Request a sandboxed plugin may make through ctx.net.fetch. Body is a string (text/JSON APIs). */
+export interface PluginNetRequestInit {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+ timeoutMs?: number;
+}
+
+/**
+ * Serializable response handed back to the plugin. No streaming / no methods — it must cross the
+ * worker boundary via structuredClone, so the body is read host-side and returned as a string.
+ */
+export interface PluginNetResponse {
+ ok: boolean;
+ status: number;
+ statusText: string;
+ headers: Record<string, string>;
+ body: string;
+}
+
+/**
+ * Is `url` allowed by a plugin's manifest `net.allow` list? Deny-by-default. `'*'` allows any host
+ * (the SSRF guard still blocks internal IPs at connect time); an entry may be `host:port` (exact) or
+ * a bare `host` (any port). Only http(s) is ever allowed.
+ */
+export function isNetHostAllowed(allow: string[] | undefined, url: string): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
+
+ const list = allow ?? [];
+ if (list.includes('*')) return true;
+
+ const port = parsed.port || (parsed.protocol === 'https:' ? '443' : '80');
+ return list.includes(`${parsed.hostname}:${port}`) || list.includes(parsed.hostname);
+}
+
+/**
+ * Perform a plugin's outbound request through the SSRF guard (resolve-once-pin, redirect-refused),
+ * bounded by a timeout and a response-size cap, and serialize the response for the capability bridge.
+ * `deps.fetch` is injectable for tests; production uses {@link withSafeFetch}.
+ */
+export async function performPluginFetch(
+ url: string,
+ init: PluginNetRequestInit = {},
+ deps: { fetch?: typeof withSafeFetch } = {},
+): Promise<PluginNetResponse> {
+ const safeFetch = deps.fetch ?? withSafeFetch;
+ const timeoutMs = Math.min(Math.max(init.timeoutMs ?? DEFAULT_TIMEOUT_MS, 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`);
+ }
+ 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'),
+ };
+ },
+ );
+}
diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.ts
index bd25f75d8..e79911236 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -6,6 +6,7 @@
import { HookManager, HookEvent, HookHandler } from '../hooks';
import type { MessageResponseDto } from '../../modules/message/dto';
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+import type { PluginNetRequestInit, PluginNetResponse } from './plugin-net';
// ============================================================================
// Plugin Types
@@ -68,6 +69,11 @@ export interface PluginManifest {
// 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[];
+
+ // Outbound-HTTP host allowlist for `ctx.net.fetch` (requires the `net:fetch` permission). Each
+ // entry is `host:port` (exact) or a bare `host` (any port); `'*'` allows any public host. Absent /
+ // empty = deny all. The SSRF guard still blocks internal IPs regardless of this list.
+ net?: { allow?: string[] };
}
export interface PluginConfigSchema {
@@ -100,6 +106,8 @@ export const PluginCapabilityPermission = {
MESSAGES_SEND: 'messages:send',
/** `ctx.engine.*` — read-only engine queries (group info, contacts, chats, number check). */
ENGINE_READ: 'engine:read',
+ /** `ctx.net.fetch` — SSRF-guarded outbound HTTP, scoped to the manifest `net.allow` host list. */
+ NET_FETCH: 'net:fetch',
} as const;
export type PluginCapabilityPermission = (typeof PluginCapabilityPermission)[keyof typeof PluginCapabilityPermission];
@@ -127,6 +135,11 @@ export interface PluginEngineReadCapability {
getChats(sessionId: string): ReturnType<IWhatsAppEngine['getChats']>;
}
+/** Outbound HTTP for a plugin — always through the host SSRF guard, scoped to `manifest.net.allow`. */
+export interface PluginNetCapability {
+ fetch(url: string, init?: PluginNetRequestInit): Promise<PluginNetResponse>;
+}
+
// ============================================================================
// Plugin Context (passed to plugin on initialization)
// ============================================================================
@@ -156,6 +169,9 @@ export interface PluginContext {
// Read-only, scoped engine queries.
engine: PluginEngineReadCapability;
+
+ // SSRF-guarded outbound HTTP, scoped to the manifest `net.allow` host list.
+ net: PluginNetCapability;
}
export interface PluginLogger {
diff --git a/src/core/plugins/sandbox/capability-router.spec.ts b/src/core/plugins/sandbox/capability-router.spec.ts
index 867a97d00..36652d8be 100644
--- a/src/core/plugins/sandbox/capability-router.spec.ts
+++ b/src/core/plugins/sandbox/capability-router.spec.ts
@@ -19,6 +19,9 @@ function makeContext() {
delete: jest.fn().mockResolvedValue(undefined),
list: jest.fn().mockResolvedValue([]),
},
+ net: {
+ fetch: jest.fn().mockResolvedValue({ ok: true, status: 200, statusText: 'OK', headers: {}, body: 'x' }),
+ },
};
}
@@ -49,6 +52,14 @@ describe('dispatchCapabilityVerb', () => {
expect(out).toBe('v');
});
+ it('routes net.fetch with the url + init and returns the serialized response', async () => {
+ const ctx = makeContext();
+ const init = { method: 'POST', body: '{}' };
+ const out = await dispatchCapabilityVerb(ctx, 'net.fetch', ['https://api.example.com/t', init]);
+ expect(ctx.net.fetch).toHaveBeenCalledWith('https://api.example.com/t', init);
+ expect(out).toMatchObject({ ok: true, status: 200, body: 'x' });
+ });
+
it('rejects an unknown verb — only allowlisted capabilities are reachable', async () => {
const ctx = makeContext();
await expect(dispatchCapabilityVerb(ctx as unknown as CapabilityContext, 'process.exit', [0])).rejects.toThrow(
diff --git a/src/core/plugins/sandbox/capability-router.ts b/src/core/plugins/sandbox/capability-router.ts
index 84908bcbd..44e846f78 100644
--- a/src/core/plugins/sandbox/capability-router.ts
+++ b/src/core/plugins/sandbox/capability-router.ts
@@ -1,7 +1,7 @@
import { PluginContext } from '../plugin.interfaces';
/** The subset of the plugin context a sandboxed plugin reaches across the bridge. */
-export type CapabilityContext = Pick<PluginContext, 'messages' | 'engine' | 'storage'>;
+export type CapabilityContext = Pick<PluginContext, 'messages' | 'engine' | 'storage' | 'net'>;
/**
* Dispatch a worker-initiated capability `verb` to the live, permission-enforcing context the loader
@@ -41,6 +41,8 @@ export async function dispatchCapabilityVerb(
return context.storage.delete(s(0));
case 'storage.list':
return context.storage.list(args[0] as string | undefined);
+ case 'net.fetch':
+ return context.net.fetch(s(0), args[1] as Parameters<typeof context.net.fetch>[1]);
default:
throw new Error(`Unknown capability verb: ${verb}`);
}
diff --git a/src/core/plugins/sandbox/worker-capability.ts b/src/core/plugins/sandbox/worker-capability.ts
index 479b49f54..89095cf86 100644
--- a/src/core/plugins/sandbox/worker-capability.ts
+++ b/src/core/plugins/sandbox/worker-capability.ts
@@ -46,6 +46,9 @@ export interface SandboxCapabilityContext {
delete(key: string): Promise<unknown>;
list(prefix?: string): Promise<unknown>;
};
+ net: {
+ fetch(url: string, init?: unknown): Promise<unknown>;
+ };
}
/** Build the proxy capability context handed to a sandboxed plugin in the worker. */
@@ -69,5 +72,8 @@ export function buildSandboxContext(client: WorkerCapabilityClient): SandboxCapa
delete: key => client.call('storage.delete', [key]),
list: prefix => client.call('storage.list', [prefix]),
},
+ net: {
+ fetch: (url, init) => client.call('net.fetch', [url, init]),
+ },
};
}