Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): validate imported session names and redact absolute host paths (#598)

Yudhi Armyndharisa0b524d1fb0e
diff --git a/src/common/utils/path-safety.spec.ts b/src/common/utils/path-safety.spec.ts
index 4d6049af2..3deaa1534 100644
--- a/src/common/utils/path-safety.spec.ts
+++ b/src/common/utils/path-safety.spec.ts
@@ -1,5 +1,5 @@
import * as path from 'path';
-import { isPathWithin, isSafeStorageKey } from './path-safety';
+import { isPathWithin, isSafeStorageKey, isSafeSessionName } from './path-safety';
describe('isPathWithin', () => {
const root = path.resolve('/srv/app/data');
@@ -54,3 +54,24 @@ describe('isSafeStorageKey', () => {
expect(isSafeStorageKey(`baz${String.fromCharCode(31)}.txt`)).toBe(false); // unit separator
});
});
+
+describe('isSafeSessionName', () => {
+ it.each(['my-session', 'Session1', 'abc', 'A-B-2'])('accepts the safe name %j', n => {
+ expect(isSafeSessionName(n)).toBe(true);
+ });
+
+ it.each([
+ '../../etc', // traversal
+ 'a/b', // slash
+ 'a\\b', // backslash
+ 'a.b', // dot (would traverse / change the auth dir)
+ 'has space',
+ 'name@x',
+ '', // empty
+ undefined,
+ null,
+ 123,
+ ])('rejects the unsafe name %j', n => {
+ expect(isSafeSessionName(n as unknown)).toBe(false);
+ });
+});
diff --git a/src/common/utils/path-safety.ts b/src/common/utils/path-safety.ts
index a84611984..c73222515 100644
--- a/src/common/utils/path-safety.ts
+++ b/src/common/utils/path-safety.ts
@@ -31,3 +31,14 @@ export function isSafeStorageKey(key: string): boolean {
if (path.isAbsolute(key)) return false;
return !key.split(/[/\\]/).includes('..');
}
+
+/**
+ * Returns true if `name` is a safe engine session name — the same conservative charset the
+ * CreateSessionDto enforces (letters, digits, hyphen). A session name becomes the engine auth-directory
+ * key (`path.join(authDir, name)` / `session-${name}`), so a '.', '/', or '\\' could traverse outside it
+ * (arbitrary write, and `rm -rf` on teardown). This is the sink-side guard for every path that reaches
+ * the auth dir — normal creation validates via the DTO, but data import / seed can carry a raw name.
+ */
+export function isSafeSessionName(name: unknown): name is string {
+ return typeof name === 'string' && /^[a-zA-Z0-9-]+$/.test(name);
+}
diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.ts
index f102d7d80..e75f4ae08 100644
--- a/src/engine/engine.factory.spec.ts
+++ b/src/engine/engine.factory.spec.ts
@@ -33,6 +33,18 @@ describe('EngineFactory', () => {
remember: jest.fn().mockResolvedValue(undefined),
}) as unknown as LidMappingStoreService;
+ it('refuses to create an engine for an unsafe session name (path-traversal into the auth dir)', () => {
+ const createEngine = jest.fn().mockReturnValue({});
+ const pluginLoader = {
+ getPlugin: jest.fn().mockReturnValue({ instance: { type: PluginType.ENGINE, createEngine } }),
+ } as unknown as PluginLoaderService;
+ const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());
+
+ expect(() => factory.create({ sessionId: '../../etc' })).toThrow(/unsafe session name/i);
+ expect(() => factory.create({ sessionId: 'a/b' })).toThrow(/unsafe session name/i);
+ expect(createEngine).not.toHaveBeenCalled();
+ });
+
it('passes ONLY engine-neutral fields to createEngine (no Puppeteer leak)', () => {
const createEngine = jest.fn().mockReturnValue({});
const pluginInstance = { type: PluginType.ENGINE, createEngine };
diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.ts
index 12b9ded91..5965f1d6a 100644
--- a/src/engine/engine.factory.ts
+++ b/src/engine/engine.factory.ts
@@ -8,6 +8,7 @@ import { BaileysPlugin } from '../plugins/engines/baileys';
import { createLogger } from '../common/services/logger.service';
import { BaileysMessageStoreService } from './adapters/baileys-message-store.service';
import { LidMappingStoreService } from './identity/lid-mapping-store.service';
+import { isSafeSessionName } from '../common/utils/path-safety';
export interface EngineCreateOptions {
sessionId: string;
@@ -89,6 +90,14 @@ export class EngineFactory implements OnModuleInit {
}
create(options: EngineCreateOptions): IWhatsAppEngine {
+ // The sessionId becomes the engine's on-disk auth-directory key (path.join(authDir, sessionId) /
+ // session-${sessionId}), so a name containing '.', '/' or '\\' could traverse outside it. Normal
+ // creation validates via CreateSessionDto, but alternate paths (data import, seed) can reach this
+ // sink with a raw name — assert here so the traversal can never materialize regardless of source.
+ if (!isSafeSessionName(options.sessionId)) {
+ throw new Error(`Refusing to create an engine for an unsafe session name: ${JSON.stringify(options.sessionId)}`);
+ }
+
// Try to get engine from plugin system
const enginePlugin = this.pluginLoader.getPlugin(this.engineType);
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index 8879f94c1..5a32fea14 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -821,12 +821,16 @@ describe('InfraController.exportStorage keeps the export import-able and sweeps
const result = await controller.exportStorage();
- // Import-able: under <data>/exports — the import handler only accepts paths inside data/.
- expect(result.download.startsWith(path.join(cwd, 'data', 'exports'))).toBe(true);
- expect(await exists(result.download)).toBe(true);
-
- await waitForGone(result.download);
- expect(await exists(result.download)).toBe(false);
+ // download is cwd-relative (no absolute host path leak) and stays under data/exports so the import
+ // handler — which only accepts paths inside data/ — can still consume it.
+ expect(path.isAbsolute(result.download)).toBe(false);
+ expect(result.download.startsWith(path.join('data', 'exports'))).toBe(true);
+ // Resolve against the (mocked) cwd to check on-disk existence; fs itself uses the real cwd.
+ const abs = path.join(cwd, result.download);
+ expect(await exists(abs)).toBe(true);
+
+ await waitForGone(abs);
+ expect(await exists(abs)).toBe(false);
});
});
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index 1c211e9fe..1ee83f00c 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -8,7 +8,7 @@ import { DataSource } from 'typeorm';
import { InjectDataSource } from '@nestjs/typeorm';
import { Public, RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
-import { isPathWithin } from '../../common/utils/path-safety';
+import { isPathWithin, isSafeSessionName } from '../../common/utils/path-safety';
import { writeSecretFile } from '../../common/utils/secret-file';
import { EngineFactory } from '../../engine/engine.factory';
import { getEffectiveWebVersionInfo, resolveCurrentWebVersion } from '../../engine/wa-web-version';
@@ -625,7 +625,8 @@ export class InfraController {
return {
message: `Configuration saved successfully.${profileMsg} Server restart required to apply changes.`,
saved: true,
- envPath,
+ // Return a cwd-relative path so the response doesn't disclose the absolute host filesystem layout.
+ envPath: path.relative(process.cwd(), envPath),
profiles,
};
} catch (error) {
@@ -904,6 +905,13 @@ export class InfraController {
let sessionsCount = 0;
if (data.tables.sessions?.length) {
for (const session of data.tables.sessions) {
+ // A session name becomes the engine auth-directory key, so an unvalidated imported name (this
+ // path bypasses CreateSessionDto) could traverse the filesystem. Skip + warn instead of
+ // throwing, so one bad row doesn't 500 the whole restore.
+ if (!isSafeSessionName(session.name)) {
+ warnings.push(`Skipped session ${session.id}: unsafe name ${JSON.stringify(session.name)}`);
+ continue;
+ }
try {
await queryRunner.query(
`INSERT INTO sessions (id, name, status, phone, "pushName", config, "proxyUrl", "proxyType", "connectedAt", "lastActiveAt", "createdAt", "updatedAt")
@@ -1201,7 +1209,10 @@ export class InfraController {
return {
message: 'Storage export completed',
- download: exportPath,
+ // cwd-relative rather than an absolute host path: doesn't leak the filesystem layout, and the
+ // import round-trip still works because importStorage's existsSync/createReadStream resolve a
+ // relative filePath against the same cwd this was made relative to.
+ download: path.relative(process.cwd(), exportPath),
};
}