Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): gate ctx.storage behind a declared storage:use permission

Yudhi Armyndharisa67195d73bcf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68d524539..d363e4927 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `message.controller.spec.ts` holds the two headers the stored-media download sends, `X-Content-Type-Options: nosniff` and `Content-Disposition: attachment`; deleting either had passed every suite in the repo.
- Optional `quotedMessageId` on every `send-*` message endpoint and its MCP tool, so a reply can carry media, a location, a contact card or a poll instead of only text. An id the engine cannot resolve now fails the send rather than delivering the message unquoted. Thanks @nirizr for the report.
+### Changed
+
+- Plugins must declare a `storage:use` permission to reach `ctx.storage`, and an installed plugin that persists state needs that one manifest line added before it can store again. The four storage verbs dispatched with no permission check at all, so a plugin whose manifest declared nothing still wrote to the host disk and the operator reading that manifest could not see it. The per-plugin directory, key check and byte quota already bounded the access, so this puts a plugin's use of host storage in the manifest rather than closing an escape.
+- Seven official plugins declare it as of `chatwoot-adapter` 0.9.1, `chat-flow` 1.1.2, `group-translate` 1.3.1, `gsheets-logger` 0.3.3, `http-action` 0.2.2, `typebot-connector` 0.2.2 and `voice-transcription` 1.2.3; upgrade to at least these before upgrading the gateway, since a plugin below them is denied at its next storage call rather than at load. `after-hours`, `faq-bot` and `supabase-otp-hook` never touch `ctx.storage` and need no upgrade.
+
### Fixed
- The dashboard bundled all thirteen locales into one 476 KB chunk the page preloaded, so every visitor downloaded twelve languages to read one; each is now fetched on demand.
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index 8273f482c..35bf87d51 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -274,7 +274,7 @@ export interface PluginContext {
hookManager: HookManager;
logger: PluginLogger; // log / debug / warn / error
- storage: PluginStorage; // get / set / delete / list — scoped to this plugin
+ storage: PluginStorage; // get / set / delete / list — requires 'storage:use', scoped to this plugin
// Register a hook handler (optionally with a priority; lower runs first).
registerHook: (event: HookEvent, handler: HookHandler, priority?: number) => void;
@@ -539,11 +539,12 @@ data dir (built-ins are protected and cannot be uninstalled). The unload path di
for a sandboxed plugin it runs in the worker between `onDisable` and terminate (a plain disable does
NOT fire `onUnload` — disable is reversible and its cleanup hook is `onDisable`).
-**Context.** `createPluginContext` builds the `PluginContext` (§19.4): a per-plugin logger, plugin-scoped
-storage, `registerHook` (wrapped with the per-session activation gate), `registerWebhook`, the live
-`config` getter, and the permission-checked `messages` / `engine` / `net` / `conversations` / `handover` /
-`mappings` capabilities. The capability methods call `assertPermission` before doing any work, and — for
-everything but `net` — `assertSessionActive` → `assertSessionAllowed` on the session they act on, so a
+**Context.** `createPluginContext` builds the `PluginContext` (§19.4): a per-plugin logger,
+`registerHook` (wrapped with the per-session activation gate), `registerWebhook`, the live
+`config` getter, and the permission-checked `messages` / `engine` / `net` / `storage` / `conversations` /
+`handover` / `mappings` capabilities. The capability methods call `assertPermission` before doing any
+work, and — for everything but `net` and `storage`, which are not keyed to a session —
+`assertSessionActive` → `assertSessionAllowed` on the session they act on, so a
missing grant or out-of-scope session fails with a `PluginCapabilityError`.
> ⚠️ **`ctx.storage` is plugin-scoped, not per-session — unlike `ctx.config`.** `ctx.config` is merged
@@ -569,7 +570,8 @@ are not sandboxed. There is no `auto-reply` / `translation` plugin bundled in th
### Example: a hook-based message plugin
A disk-installed extension implements `IPlugin`, registers hooks in `onLoad`, and uses the capability
-facade. This auto-reply sketch needs only `messages:send` in its manifest `permissions`:
+facade. This auto-reply sketch needs `messages:send` and `storage:use` in its manifest `permissions` —
+the latter because it records a counter through `ctx.storage`:
```typescript
// plugins/auto-reply/index.ts
@@ -641,7 +643,7 @@ URL / catalog), not an npm/github source descriptor.
### Permission model
-There are exactly **six** capability permissions, declared in the manifest `permissions` array — four
+There are exactly **seven** capability permissions, declared in the manifest `permissions` array — five
enforced at the capability boundary, plus two on the worker-declaration bridges: `webhook:ingress` at
load and at route subscription, and `search:provide` when the provider declaration reaches the host:
@@ -655,6 +657,9 @@ export const PluginCapabilityPermission = {
ENGINE_READ: 'engine:read',
/** ctx.net.fetch — SSRF-guarded outbound HTTP, scoped to the manifest net.allow host list. */
NET_FETCH: 'net:fetch',
+ /** ctx.storage.* — per-plugin key/value persistence on the host disk (get / set / delete / list).
+ * A declaration boundary: the per-plugin directory, key check and quota already bound the access. */
+ STORAGE_USE: 'storage:use',
/** ctx.registerWebhook — claim an inbound ingress route declared in the manifest. */
WEBHOOK_INGRESS: 'webhook:ingress',
/** ctx.conversations.send plus ctx.handover.* and ctx.mappings.* — the normalized outbound surface. */
@@ -665,7 +670,7 @@ export const PluginCapabilityPermission = {
} as const;
```
-There is no `PermissionChecker` class and no `PermissionDeniedError`. Enforcement of the four
+There is no `PermissionChecker` class and no `PermissionDeniedError`. Enforcement of the five
capability-facade permissions lives in the loader: each capability method calls
`assertPermission(manifest, permission)` before doing any work, and a plugin whose manifest does not
declare the matching permission (or declares none) is rejected with a `PluginCapabilityError`:
diff --git a/docs/30-plugin-sandboxing.md b/docs/30-plugin-sandboxing.md
index 8edb8b66f..28530c9c8 100644
--- a/docs/30-plugin-sandboxing.md
+++ b/docs/30-plugin-sandboxing.md
@@ -97,8 +97,10 @@ in-process plugin that calls it fails loud rather than silently never firing —
`messages:send` for `ctx.messages`, `engine:read` for `ctx.engine`, `net:fetch` for `ctx.net.fetch`
(plus a `net.allow` host list), `conversation:send` for `ctx.conversations` / `ctx.handover` /
`ctx.mappings`, `webhook:ingress` for `ctx.registerWebhook` (enforced at load and again at route
- subscription), and `search:provide` for `ctx.registerSearchProvider` (enforced when the declaration
- reaches the host). `ctx.storage` needs no permission — it is already per-plugin scoped. See
+ subscription), `search:provide` for `ctx.registerSearchProvider` (enforced when the declaration
+ reaches the host), and `storage:use` for `ctx.storage`. Storage was already confined to a
+ per-plugin directory with a byte quota, so its permission is what makes the persistence visible in
+ the manifest rather than what confines it. See
[19 — Plugin Architecture](./19-plugin-architecture.md).
Sandboxing was a **breaking change for third-party plugin authoring** when it shipped in v0.6.0.
diff --git a/src/core/plugins/plugin-capability-context.ts b/src/core/plugins/plugin-capability-context.ts
index d768598f4..e739d1ca6 100644
--- a/src/core/plugins/plugin-capability-context.ts
+++ b/src/core/plugins/plugin-capability-context.ts
@@ -25,6 +25,7 @@ import {
type PluginMappingsCapability,
type PluginMessagingCapability,
type PluginNetCapability,
+ type PluginStorage,
} from './plugin.interfaces';
/**
@@ -180,7 +181,7 @@ export class PluginCapabilityContext {
},
hookManager: this.hookManager,
logger: this.buildPluginLogger(plugin),
- storage: this.pluginStorage.createPluginStorage(plugin.manifest.id),
+ storage: this.buildStorageCapability(plugin),
registerHook: (event, handler, priority) => {
// Wrap with the per-session activation gate so an in-process plugin only handles events for
// the sessions it is activated for (mirrors the sandboxed shim), and scope the firing
@@ -274,6 +275,43 @@ export class PluginCapabilityContext {
} satisfies PluginEngineReadCapability;
}
+ /**
+ * Per-plugin persistence, behind the permission its manifest must declare. The gate goes on all
+ * four verbs rather than on the factory, because the sandbox bridge routes a worker's `storage.*`
+ * through this same object — gating only the in-process handle would leave the sandboxed path,
+ * the one that actually runs untrusted code, ungated.
+ *
+ * No session gate: storage is keyed by plugin, not by session, so there is no session to check.
+ *
+ * Every verb is `async` so a denial arrives as a REJECTION. The backing implementation in
+ * PluginStorageService never throws synchronously — an unsafe key and an exceeded quota both come
+ * back as a rejected promise — so a synchronous gate would have been the only sync throw on this
+ * surface, escaping a plugin that handles failure with `.catch()` alone and taking down the caller
+ * instead of failing the capability.
+ */
+ private buildStorageCapability(plugin: PluginInstance): PluginStorage {
+ const storage = this.pluginStorage.createPluginStorage(plugin.manifest.id);
+ const gate = (): void => this.assertPermission(plugin.manifest, PluginCapabilityPermission.STORAGE_USE);
+ return {
+ get: async <T = unknown>(key: string): Promise<T | null> => {
+ gate();
+ return storage.get<T>(key);
+ },
+ set: async <T = unknown>(key: string, value: T): Promise<void> => {
+ gate();
+ return storage.set<T>(key, value);
+ },
+ delete: async (key: string): Promise<void> => {
+ gate();
+ return storage.delete(key);
+ },
+ list: async (prefix?: string): Promise<string[]> => {
+ gate();
+ return storage.list(prefix);
+ },
+ } satisfies PluginStorage;
+ }
+
private buildNetCapability(plugin: PluginInstance): PluginNetCapability {
return {
fetch: async (url, init) => {
diff --git a/src/core/plugins/plugin-capability.spec.ts b/src/core/plugins/plugin-capability.spec.ts
index 933821430..2497259b2 100644
--- a/src/core/plugins/plugin-capability.spec.ts
+++ b/src/core/plugins/plugin-capability.spec.ts
@@ -371,3 +371,70 @@ describe('PluginLoaderService capability facade — ctx.conversations', () => {
expect(messageService.sendText).toHaveBeenCalledWith('sess-1', { chatId: '[email protected]', text: 'hi' });
});
});
+
+describe('PluginLoaderService capability facade — ctx.storage', () => {
+ let loader: PluginLoaderService;
+ let backing: { get: jest.Mock; set: jest.Mock; delete: jest.Mock; list: jest.Mock };
+
+ beforeEach(() => {
+ backing = {
+ get: jest.fn().mockResolvedValue(null),
+ set: jest.fn().mockResolvedValue(undefined),
+ delete: jest.fn().mockResolvedValue(undefined),
+ list: jest.fn().mockResolvedValue([]),
+ };
+ const pluginStorage = {
+ createPluginStorage: jest.fn().mockReturnValue(backing),
+ } as unknown as PluginStorageService;
+ loader = new PluginLoaderService(
+ { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService,
+ new HookManager(),
+ pluginStorage,
+ { get: jest.fn() } as unknown as ModuleRef,
+ );
+ });
+
+ function contextFor(plugin: PluginInstance): PluginContext {
+ return (
+ loader as unknown as { capabilities: { createPluginContext: (p: PluginInstance) => PluginContext } }
+ ).capabilities.createPluginContext(plugin);
+ }
+
+ // Every verb, not just the write ones: `list` alone enumerates whatever a previous version of the
+ // plugin persisted, and `get` reads it back.
+ const VERBS: Array<[string, (ctx: PluginContext) => Promise<unknown>]> = [
+ ['get', ctx => ctx.storage.get('k')],
+ ['set', ctx => ctx.storage.set('k', { v: 1 })],
+ ['delete', ctx => ctx.storage.delete('k')],
+ ['list', ctx => ctx.storage.list('prefix')],
+ ];
+
+ it.each(VERBS)('denies storage.%s when the plugin does not declare storage:use', async (verb, call) => {
+ const ctx = contextFor(makePlugin(['*'], [])); // no permissions at all
+ await expect(call(ctx)).rejects.toBeInstanceOf(PluginCapabilityError);
+ expect(backing[verb as keyof typeof backing]).not.toHaveBeenCalled();
+ });
+
+ it.each(VERBS)('allows storage.%s once the manifest declares storage:use', async (verb, call) => {
+ const ctx = contextFor(makePlugin(['*'], ['storage:use']));
+ await expect(call(ctx)).resolves.not.toThrow();
+ expect(backing[verb as keyof typeof backing]).toHaveBeenCalled();
+ });
+
+ it('passes the caller arguments through untouched', async () => {
+ const ctx = contextFor(makePlugin(['*'], ['storage:use']));
+ await ctx.storage.set('group:sess-1:[email protected]', { seen: 2 });
+ await ctx.storage.list('group:');
+ expect(backing.set).toHaveBeenCalledWith('group:sess-1:[email protected]', { seen: 2 });
+ expect(backing.list).toHaveBeenCalledWith('group:');
+ });
+
+ it('is not gated by session scope — storage is keyed by plugin, not by session', async () => {
+ // A plugin the operator activated for one session only still owns one storage namespace, so the
+ // permission is the whole gate here. Asserting it keeps a later "add assertSessionActive for
+ // symmetry" change from quietly bricking every stored key outside the active session.
+ const ctx = contextFor(makePlugin(['sess-1'], ['storage:use'], ['sess-1']));
+ await expect(ctx.storage.get('anything')).resolves.toBeNull();
+ expect(backing.get).toHaveBeenCalledWith('anything');
+ });
+});
diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.ts
index 651c8ce31..22a3fcd02 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -166,6 +166,14 @@ export const PluginCapabilityPermission = {
ENGINE_READ: 'engine:read',
/** `ctx.net.fetch` — SSRF-guarded outbound HTTP, scoped to the manifest `net.allow` host list. */
NET_FETCH: 'net:fetch',
+ /**
+ * `ctx.storage.*` — per-plugin key/value persistence on the host disk (get / set / delete / list).
+ * The per-plugin directory, the key-shape check and the byte quota already bound what a plugin can
+ * reach, so this is a DECLARATION boundary rather than a containment one: without it a manifest
+ * declaring no permissions at all still wrote to disk, and the operator reading that manifest had
+ * no way to see it.
+ */
+ STORAGE_USE: 'storage:use',
/** `ctx.registerWebhook` — claim an inbound ingress route. Loader-enforced; cannot be widened by config. */
WEBHOOK_INGRESS: 'webhook:ingress',
/** `ctx.conversations.send` — normalized outbound send translated to MessageService. */