Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): preserve secret arrays on length change + harden plugin lifecycle (#544)

Yudhi Armyndharis44ad2cf04168
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0747b8349..42134c77e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A plugin's stored secret array is no longer wiped when its length changes.** When a plugin config had a list of secret values (e.g. API keys), adding or removing an entry from the dashboard sent every other value back as the masked sentinel; on save, the merge couldn't position-match them and silently dropped all of them. Surviving entries now keep their stored secret across an append or removal, while a genuinely-new or edited row is still never grafted with a stored value. (#544)
+- **A crash midway through a plugin update no longer leaves a backup that loads as a duplicate.** The in-place update backup is now a dot-prefixed sibling directory, and the loader skips dot-prefixed directories, so a half-finished update can't be re-loaded on the next boot as a second copy of the same plugin id. (#544)
+
+### Changed
+
+- **Sandboxed plugins have a ceiling on concurrent host capability calls.** A single worker-thread plugin can now have at most 32 capability calls (message sends, network fetches, storage writes) running host-side at once; a burst beyond that is rejected (the plugin sees a thrown error) rather than amplified into unbounded host work. (#544)
+- **Plugin lifecycle operations on the same plugin are serialized.** Enable, disable, update, uninstall, and install for a given plugin id now run one at a time, so two operations firing together can no longer race on the plugin's directory or runtime state. (#544)
- **Boot migrations are no longer aborted by the runtime query timeout on PostgreSQL.** The `data` connection sets a `statement_timeout` to bound live queries, and that limit was inherited by the migrations that run at startup — so on a large existing deployment a backfill plus `CREATE UNIQUE INDEX` over the `messages` or `templates` table could exceed it and fail boot. The two affected migrations now lift the timeout for their own transaction (PostgreSQL-only, transaction-scoped via `SET LOCAL`, a no-op on SQLite); the runtime timeout that protects live traffic is unchanged. (#543)
- **The templates migration revert is idempotent on a synchronize-bootstrapped database.** `AddTemplates` now drops its index and table with `IF EXISTS`, so a `down()` no longer errors when the schema was created by `synchronize` and the migration-only `IDX_templates_sessionId` index was never created. (#543)
### Added
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index b62cecd88..3099abb8b 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -296,6 +296,50 @@ describe('PluginLoaderService — uninstall', () => {
});
});
+describe('PluginLoaderService — skips dot-prefixed directories on load (crash-leftover .bak)', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let loader: PluginLoaderService;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-dotskip-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ loader = new PluginLoaderService(
+ config,
+ new HookManager(),
+ new PluginStorageService(config),
+ {} as unknown as ModuleRef,
+ );
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const writePlugin = (dirName: string, id: string): void => {
+ const dir = path.join(pluginsDir, dirName);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'manifest.json'),
+ JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
+ );
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+ };
+
+ it('does not scan a crash-leftover .<id>.bak directory (no duplicate-id load race)', () => {
+ writePlugin('svc-plg', 'svc-plg');
+ writePlugin('.svc-plg.bak', 'svc-plg'); // a leftover update backup carrying the SAME manifest id
+
+ const loadSpy = jest.spyOn(loader, 'loadPlugin');
+ loader.onModuleInit();
+
+ const scanned = loadSpy.mock.calls.map(c => c[0]);
+ expect(scanned).toContain(path.join(pluginsDir, 'svc-plg'));
+ expect(scanned).not.toContain(path.join(pluginsDir, '.svc-plg.bak'));
+ });
+});
+
describe('PluginLoaderService — enable concurrency', () => {
let tmpDir: string;
let loader: PluginLoaderService;
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 2059d943d..589a2761a 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -45,6 +45,12 @@ const SANDBOX_HEALTH_TIMEOUT_MS = 5000;
*/
const SANDBOX_LIFECYCLE_TIMEOUT_MS = 30000;
+/**
+ * Max concurrent worker-initiated capability calls per sandboxed plugin. A burst beyond this is rejected
+ * (the plugin sees a thrown Error) rather than amplified into unbounded host-side sends/fetches/writes.
+ */
+const SANDBOX_MAX_INFLIGHT_CAPS = 32;
+
/**
* 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
@@ -153,7 +159,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
- if (!entry.isDirectory()) continue;
+ // Skip non-directories and dot-prefixed dirs (e.g. a crash-leftover `.<id>.bak` update backup),
+ // so a half-finished update can't be re-loaded as a duplicate-id plugin on the next boot.
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
const pluginPath = path.join(dir, entry.name);
const manifestPath = path.join(pluginPath, 'manifest.json');
@@ -632,6 +640,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
onHookSubscribe,
onLog,
runWithHookGuard,
+ SANDBOX_MAX_INFLIGHT_CAPS,
);
}
diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
index edf5cfdf7..b7225891e 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
@@ -161,6 +161,37 @@ describe('PluginWorkerHost', () => {
expect(ch.sent.find(m => m.kind === 'cap-result')).toMatchObject({ id: 9, ok: false });
});
+
+ it('rejects a cap request over the in-flight limit and recovers after the in-flight one settles', async () => {
+ const ch = new FakeChannel();
+ let resolveFirst: (v: unknown) => void = () => undefined;
+ const dispatcher = jest
+ .fn()
+ .mockImplementationOnce(() => new Promise(r => (resolveFirst = r))) // first cap hangs, holding the slot
+ .mockResolvedValue({ ok: true });
+ // maxInFlightCaps = 1 (6th positional arg)
+ new PluginWorkerHost(ch, dispatcher, undefined, undefined, undefined, 1);
+
+ ch.reply({ kind: 'cap', id: 1, verb: 'messages.sendText', args: [] }); // takes the only slot
+ await flush();
+ ch.reply({ kind: 'cap', id: 2, verb: 'messages.sendText', args: [] }); // over the limit
+ await flush();
+
+ expect(dispatcher).toHaveBeenCalledTimes(1); // the over-limit cap is rejected before dispatch
+ const rejected = ch.sent.find(m => m.kind === 'cap-result' && m.id === 2) as
+ { ok: boolean; error?: string } | undefined;
+ expect(rejected?.ok).toBe(false);
+ expect(rejected?.error).toMatch(/too many concurrent/);
+
+ resolveFirst({ ok: true }); // free the slot
+ await flush();
+ ch.reply({ kind: 'cap', id: 3, verb: 'messages.sendText', args: [] });
+ await flush();
+
+ expect(dispatcher).toHaveBeenCalledTimes(2); // slot released → a fresh cap dispatches
+ const ok3 = ch.sent.find(m => m.kind === 'cap-result' && m.id === 3) as { ok: boolean } | undefined;
+ expect(ok3?.ok).toBe(true);
+ });
});
describe('hook bridge', () => {
diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.ts
index ee5aa237a..61deea54a 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.ts
@@ -41,6 +41,9 @@ export class PluginWorkerHost {
// AsyncLocalStorage re-entrancy guard does not span the worker IPC boundary).
private readonly inFlightHookEvents = new Map<string, number>();
+ // Worker-initiated capability calls currently running host-side, bounded by maxInFlightCaps.
+ private inFlightCaps = 0;
+
constructor(
private readonly channel: PluginWorkerChannel,
// Runs a worker-initiated capability call host-side (validating permission + session scope before
@@ -55,6 +58,11 @@ export class PluginWorkerHost {
// re-fires an event this worker is currently handling is short-circuited (re-entrancy across IPC).
// Absent => capability calls run with no hook guard (e.g. before the bridge is wired, or in tests).
private readonly runWithHookGuard?: (inFlightEvents: string[], run: () => Promise<unknown>) => Promise<unknown>,
+ // Max worker-initiated capability calls the host will run concurrently for this worker. When this many
+ // cap requests are in flight, further cap messages are rejected with an error cap-result (the worker
+ // sees a thrown Error) instead of queuing host-side work — bounding the aggregate sendText/net.fetch/
+ // storage load a single sandboxed plugin can trigger. Absent/undefined => no cap (legacy behavior).
+ private readonly maxInFlightCaps?: number,
) {
this.channel.onMessage(message => this.handleMessage(message));
this.channel.onExit(code => this.handleExit(code));
@@ -246,10 +254,20 @@ export class PluginWorkerHost {
}
private async handleCapRequest(message: Extract<WorkerToHostMessage, { kind: 'cap' }>): Promise<void> {
+ if (this.maxInFlightCaps !== undefined && this.inFlightCaps >= this.maxInFlightCaps) {
+ this.channel.postMessage({
+ kind: 'cap-result',
+ id: message.id,
+ ok: false,
+ error: `capability call rejected: too many concurrent capability calls (limit ${this.maxInFlightCaps})`,
+ });
+ return;
+ }
if (!this.capDispatcher) {
this.channel.postMessage({ kind: 'cap-result', id: message.id, ok: false, error: 'no capability dispatcher' });
return;
}
+ this.inFlightCaps++;
try {
const dispatcher = this.capDispatcher;
const run = (): Promise<unknown> => dispatcher(message.verb, message.args);
@@ -267,6 +285,8 @@ export class PluginWorkerHost {
ok: false,
error: error instanceof Error ? error.message : String(error),
});
+ } finally {
+ this.inFlightCaps--;
}
}
diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.ts
index b2529fbd0..2c12a5bcf 100644
--- a/src/modules/plugins/plugins.service.spec.ts
+++ b/src/modules/plugins/plugins.service.spec.ts
@@ -91,7 +91,7 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {
expect(dto.version).toBe('2.0.0');
expect(dto.config).toEqual({ apiKey: 'secret-123' }); // config survived the in-place update
expect(fs.existsSync(path.join(pluginsDir, 'svc-plg', 'index.js'))).toBe(true);
- expect(fs.existsSync(path.join(pluginsDir, 'svc-plg.bak'))).toBe(false); // backup cleaned up
+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false); // backup cleaned up
});
it('updatePackage rejects a package whose id does not match', async () => {
@@ -113,7 +113,7 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {
// The rollback must leave the OLD version loaded — not the new, half-enabled (ERROR) instance.
expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');
- expect(fs.existsSync(path.join(pluginsDir, 'svc-plg.bak'))).toBe(false);
+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);
const onDisk = JSON.parse(fs.readFileSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'), 'utf8')) as {
version: string;
};
@@ -121,6 +121,27 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {
enableSpy.mockRestore();
});
+
+ it('serializes concurrent lifecycle operations on the same plugin id', async () => {
+ service.install({ buffer: pkg() });
+ let resolveFirst: () => void = () => undefined;
+ const firstDone = new Promise<void>(r => (resolveFirst = r));
+ let calls = 0;
+ jest.spyOn(loader, 'uninstallPlugin').mockImplementation(() => {
+ calls++;
+ return calls === 1 ? firstDone : Promise.resolve();
+ });
+
+ const p1 = service.uninstall('svc-plg');
+ const p2 = service.uninstall('svc-plg');
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(calls).toBe(1); // the second op is queued behind the first, not run concurrently
+
+ resolveFirst();
+ await Promise.all([p1, p2]);
+ expect(calls).toBe(2);
+ });
});
describe('PluginsService — getConfigUiHtml (sandboxed config editor)', () => {
diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.ts
index cc3382384..a69ec3eaf 100644
--- a/src/modules/plugins/plugins.service.ts
+++ b/src/modules/plugins/plugins.service.ts
@@ -27,6 +27,23 @@ export class PluginsService {
private readonly configService: ConfigService,
) {}
+ // Serialize the directory/lifecycle-mutating operations (enable/disable/uninstall/update/install) for a
+ // given plugin id so two of them on the SAME id can't interleave (e.g. enable racing uninstall, or two
+ // updates racing on the backup dir). Mirrors the promise-chain serializer in session.service.ts.
+ private readonly opChains = new Map<string, Promise<unknown>>();
+
+ private serialize<T>(id: string, op: () => Promise<T>): Promise<T> {
+ const prior = this.opChains.get(id) ?? Promise.resolve();
+ const next = prior.catch(() => undefined).then(op);
+ this.opChains.set(id, next);
+ void next
+ .catch(() => undefined)
+ .finally(() => {
+ if (this.opChains.get(id) === next) this.opChains.delete(id);
+ });
+ return next;
+ }
+
findAll(): PluginDto[] {
const plugins = this.pluginLoader.getAllPlugins();
@@ -83,7 +100,11 @@ export class PluginsService {
};
}
- async enable(id: string): Promise<{ success: boolean; message: string }> {
+ enable(id: string): Promise<{ success: boolean; message: string }> {
+ return this.serialize(id, () => this.enableInner(id));
+ }
+
+ private async enableInner(id: string): Promise<{ success: boolean; message: string }> {
const plugin = this.pluginLoader.getPlugin(id);
if (!plugin) {
@@ -105,7 +126,11 @@ export class PluginsService {
}
}
- async disable(id: string): Promise<{ success: boolean; message: string }> {
+ disable(id: string): Promise<{ success: boolean; message: string }> {
+ return this.serialize(id, () => this.disableInner(id));
+ }
+
+ private async disableInner(id: string): Promise<{ success: boolean; message: string }> {
const plugin = this.pluginLoader.getPlugin(id);
if (!plugin) {
@@ -302,7 +327,10 @@ export class PluginsService {
`Failed to download plugin from URL: ${error instanceof Error ? error.message : String(error)}`,
);
}
- return this.install({ buffer });
+ // Peek the id (the SSRF download stays outside the lock) so the install — which writes the plugin
+ // directory — is serialized against any concurrent uninstall/update of the same id.
+ const { manifest } = parsePluginPackage(buffer);
+ return this.serialize(manifest.id, () => Promise.resolve(this.install({ buffer })));
}
/**
@@ -344,7 +372,11 @@ export class PluginsService {
* directory is backed up and restored if the swap or reload of the new version fails, so a bad update
* never leaves the plugin broken.
*/
- async updatePackage(id: string, buffer: Buffer): Promise<PluginDto> {
+ updatePackage(id: string, buffer: Buffer): Promise<PluginDto> {
+ return this.serialize(id, () => this.updatePackageInner(id, buffer));
+ }
+
+ private async updatePackageInner(id: string, buffer: Buffer): Promise<PluginDto> {
const plugin = this.pluginLoader.getPlugin(id);
if (!plugin) {
throw new NotFoundException(`Plugin ${id} not found`);
@@ -361,7 +393,9 @@ export class PluginsService {
const wasEnabled = plugin.status === PluginStatus.ENABLED;
const dir = path.join(this.pluginLoader.getPluginsDir(), id);
- const backup = `${dir}.bak`;
+ // Dot-prefixed sibling inside pluginsDir: same filesystem (so the rename stays EXDEV-safe) but
+ // skipped by the loader's directory scan, so a crash mid-update can't leave it loaded as a duplicate.
+ const backup = path.join(this.pluginLoader.getPluginsDir(), `.${id}.bak`);
// Stop the running plugin (terminates its sandbox worker) but keep its registry entry so config survives.
await this.pluginLoader.unloadPlugin(id);
@@ -420,7 +454,11 @@ export class PluginsService {
}
/** Uninstall an installed user plugin: disable, unload, and delete its files. Built-ins are protected. */
- async uninstall(id: string): Promise<{ success: boolean; message: string }> {
+ uninstall(id: string): Promise<{ success: boolean; message: string }> {
+ return this.serialize(id, () => this.uninstallInner(id));
+ }
+
+ private async uninstallInner(id: string): Promise<{ success: boolean; message: string }> {
const plugin = this.pluginLoader.getPlugin(id);
if (!plugin) {
throw new NotFoundException(`Plugin ${id} not found`);
diff --git a/src/modules/plugins/redact-config.spec.ts b/src/modules/plugins/redact-config.spec.ts
index c31871cfc..f85b30e61 100644
--- a/src/modules/plugins/redact-config.spec.ts
+++ b/src/modules/plugins/redact-config.spec.ts
@@ -281,6 +281,36 @@ describe('restoreSecretConfig (scalar-secret array)', () => {
keys: [],
});
});
+
+ it('preserves stored secrets when a new key is appended (length grows)', () => {
+ expect(
+ restoreSecretConfig(
+ { keys: [SECRET_SENTINEL, SECRET_SENTINEL, SECRET_SENTINEL, 'brand-new'] },
+ { keys: ['k1', 'k2', 'k3'] },
+ scalarSecretArraySchema,
+ ),
+ ).toEqual({ keys: ['k1', 'k2', 'k3', 'brand-new'] });
+ });
+
+ it('preserves stored secrets when a blank trailing entry is appended (the blank is dropped)', () => {
+ expect(
+ restoreSecretConfig(
+ { keys: [SECRET_SENTINEL, SECRET_SENTINEL, SECRET_SENTINEL, ''] },
+ { keys: ['k1', 'k2', 'k3'] },
+ scalarSecretArraySchema,
+ ),
+ ).toEqual({ keys: ['k1', 'k2', 'k3'] });
+ });
+
+ it('preserves the remaining stored secrets when the last key is removed (length shrinks)', () => {
+ expect(
+ restoreSecretConfig(
+ { keys: [SECRET_SENTINEL, SECRET_SENTINEL] },
+ { keys: ['k1', 'k2', 'k3'] },
+ scalarSecretArraySchema,
+ ),
+ ).toEqual({ keys: ['k1', 'k2'] });
+ });
});
// A composite field (object/array) that is itself marked secret:true must be masked as ONE unit on
diff --git a/src/modules/plugins/redact-config.ts b/src/modules/plugins/redact-config.ts
index 4ffe3da46..fe87ba25b 100644
--- a/src/modules/plugins/redact-config.ts
+++ b/src/modules/plugins/redact-config.ts
@@ -121,13 +121,21 @@ function restoreValue(
value: incoming
.map((item, i) => {
const s = elementSignature(item, itemField);
- // Prefer an unambiguous content match — a row keeps its secret across reorder / insert /
- // removal. When the signature can't disambiguate (scalar-secret elements all mask to the
- // sentinel; duplicate rows; or a row whose NON-secret field was edited), fall back to the
- // same index, but only when the array length is unchanged: a same-length round-trip is an
- // in-place edit (position i is the same logical row), whereas a length change is a true
- // insert/removal where positional binding could graft a stored secret onto a new row.
- const match = sigCount.get(s) === 1 ? sigFirst.get(s) : sameLength ? existingArr[i] : undefined;
+ // Resolution order: (1) an unambiguous content match keeps a row's secret across
+ // reorder/insert/removal; (2) on an unchanged length, fall back to the positional twin (an
+ // in-place edit — position i is the same logical row, incl. a non-secret-field rename); (3) on a
+ // length change, bind the positional twin ONLY when its masked signature still equals this
+ // element's, so an append/removal keeps each surviving sentinel's stored secret while a
+ // genuinely-new or signature-changed row at that position is never grafted with a stored secret.
+ const twin = existingArr[i];
+ const match =
+ sigCount.get(s) === 1
+ ? sigFirst.get(s)
+ : sameLength
+ ? twin
+ : twin !== undefined && elementSignature(twin, itemField) === s
+ ? twin
+ : undefined;
return restoreValue(item, match, itemField);
})
// Honor keep:false like restoreObject does (drop the element) rather than emitting `.value`