Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

chore(hardening): log secret redaction, strict engine fallback, plugin doc fixes (#527)

Yudhi Armyndharisa092f14699c5
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index 8c67b141e..fb6fea84f 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -444,6 +444,12 @@ the permission-checked `messages` / `engine` / `net` capabilities. The capabilit
`assertPermission` (and, for messages/engine, `resolveEngine` → `assertSessionAllowed`) before doing any
work, so a missing grant or out-of-scope session fails fast with a `PluginCapabilityError`.
+> ⚠️ **`ctx.storage` is plugin-scoped, not per-session — unlike `ctx.config`.** `ctx.config` is merged
+> automatically for the firing session, but `ctx.storage` is a single namespace shared across **all** of a
+> plugin's sessions. A multi-session plugin that keys state by a fixed string (mirroring the per-session
+> config model) will have one session overwrite another's. Prefix storage keys with the session id (e.g.
+> `ctx.storage.set(\`${sessionId}:lastSeen\`, …)`) whenever state must be isolated per session.
+
## 19.7 Built-in Plugins
The only plugins **shipped** as built-ins are the two WhatsApp **engine adapters**, registered
diff --git a/docs/23-plugin-sandboxing.md b/docs/23-plugin-sandboxing.md
index ab4f2c64d..9ebb63100 100644
--- a/docs/23-plugin-sandboxing.md
+++ b/docs/23-plugin-sandboxing.md
@@ -29,8 +29,11 @@ from disk is untrusted and sandboxed.
(`SANDBOX_HOOK_TIMEOUT_MS`, default 5s). A slow or wedged handler is skipped (`continue: true`) so
it can never stall the host's hook chain.
- **Resource & runaway containment.** Each worker has a heap cap (`maxOldGenerationSizeMb`, default
- 256). An OOM terminates the worker, not the host. A runaway (even an infinite synchronous loop)
- can be force-terminated; a crash rejects its in-flight calls and the host survives.
+ 256). An OOM terminates the worker, not the host. A wedged **lifecycle** call (load/unload) times out
+ and tears the worker down, and a crash rejects its in-flight calls — the host survives either way. A
+ runaway **hook** handler (e.g. an infinite synchronous loop) is skipped on the hook timeout so it can't
+ stall the host's hook chain, but the worker keeps running it (pegging a core) until the plugin is
+ reloaded or hits the heap cap — it is contained to its own thread, not instantly force-killed.
## What the sandbox does NOT guarantee
diff --git a/src/common/services/logger.service.spec.ts b/src/common/services/logger.service.spec.ts
index 154da06f2..e47764bd3 100644
--- a/src/common/services/logger.service.spec.ts
+++ b/src/common/services/logger.service.spec.ts
@@ -63,6 +63,25 @@ describe('LoggerService', () => {
});
});
+ describe('secret redaction', () => {
+ it('redacts the values of secret-named keys in the metadata', () => {
+ logger.log('auth', { password: 'hunter2', apiKey: 'abc123', userId: 'u1' });
+
+ const output = getLogOutput(consoleSpy) as unknown as Record<string, unknown>;
+ expect(output.password).toBe('[REDACTED]');
+ expect(output.apiKey).toBe('[REDACTED]');
+ expect(output.userId).toBe('u1');
+ });
+
+ it('redacts secret-named keys nested inside the metadata', () => {
+ logger.log('cfg', { config: { redisPassword: 'p', host: 'h' } });
+
+ const output = getLogOutput(consoleSpy) as unknown as { config: { redisPassword: string; host: string } };
+ expect(output.config.redisPassword).toBe('[REDACTED]');
+ expect(output.config.host).toBe('h');
+ });
+ });
+
describe('error', () => {
it('should log error messages to console.error', () => {
const errorSpy = jest.spyOn(console, 'error');
diff --git a/src/common/services/logger.service.ts b/src/common/services/logger.service.ts
index 8ed1f33f2..f5aba2505 100644
--- a/src/common/services/logger.service.ts
+++ b/src/common/services/logger.service.ts
@@ -22,6 +22,22 @@ export interface LogContext {
[key: string]: unknown;
}
+// Defense-in-depth: redact the VALUES of secret-named keys before they reach the log sink, so a
+// careless `logger.info('…', { password })` can't leak a credential. Matches the key NAME only
+// (case-insensitive), never the value's content, to avoid false positives on innocuous fields.
+const SECRET_KEY_PATTERN = /password|passwd|secret|token|api[-_]?key|authorization|credential|pepper|private[-_]?key/i;
+
+/** Return a copy of `value` with secret-named keys' values replaced by `[REDACTED]` (recursive, depth-bounded). */
+function redactSecrets(value: unknown, depth = 0): unknown {
+ if (value === null || typeof value !== 'object' || depth > 4) return value;
+ if (Array.isArray(value)) return value.map(v => redactSecrets(v, depth + 1));
+ const out: Record<string, unknown> = {};
+ for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
+ out[key] = SECRET_KEY_PATTERN.test(key) ? '[REDACTED]' : redactSecrets(val, depth + 1);
+ }
+ return out;
+}
+
// ANSI color codes — mirrors the palette NestJS's built-in ConsoleLogger uses so our
// pretty output blends in with the framework's own `[Nest] … LOG [Context]` lines.
const ANSI = {
@@ -100,7 +116,8 @@ export class LoggerService implements NestLoggerService {
const timestamp = new Date().toISOString();
const contextName = typeof context === 'string' ? context : this.context;
- const metadata = typeof context === 'object' && context !== null ? context : {};
+ const metadata =
+ typeof context === 'object' && context !== null ? (redactSecrets(context) as Record<string, unknown>) : {};
const logEntry = {
timestamp,
diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.ts
index 5eed97f15..f102d7d80 100644
--- a/src/engine/engine.factory.spec.ts
+++ b/src/engine/engine.factory.spec.ts
@@ -90,4 +90,20 @@ describe('EngineFactory', () => {
const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());
expect(() => factory.create({ sessionId: 'sess-2' })).not.toThrow();
});
+
+ it('throws instead of silently building whatsapp-web.js when a non-wwebjs engine has no plugin', () => {
+ // The legacy fallback only builds wwebjs; reaching it with ENGINE_TYPE=baileys must fail loudly
+ // rather than run the wrong engine.
+ const pluginLoader = {
+ getPlugin: jest.fn().mockReturnValue(undefined),
+ } as unknown as PluginLoaderService;
+
+ const factory = new EngineFactory(
+ buildConfigService({ 'engine.type': 'baileys' }),
+ pluginLoader,
+ buildMessageStore(),
+ buildLidStore(),
+ );
+ expect(() => factory.create({ sessionId: 'sess-b' })).toThrow(/baileys/i);
+ });
});
diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.ts
index 8709e0095..6d37b2cce 100644
--- a/src/engine/engine.factory.ts
+++ b/src/engine/engine.factory.ts
@@ -123,6 +123,15 @@ export class EngineFactory implements OnModuleInit {
}
private createFallbackEngine(options: EngineCreateOptions): IWhatsAppEngine {
+ // This legacy fallback can only construct the whatsapp-web.js adapter. If a different engine was
+ // requested (e.g. ENGINE_TYPE=baileys) and its plugin wasn't available, building wwebjs here would
+ // silently run the WRONG engine — fail loudly so the misconfiguration is visible instead.
+ if (this.engineType !== 'whatsapp-web.js') {
+ throw new Error(
+ `Engine '${this.engineType}' is unavailable and has no direct fallback; cannot start the session.`,
+ );
+ }
+
// Legacy direct creation (fallback)
return new WhatsAppWebJsAdapter({
sessionId: options.sessionId,