Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): serve status media inert and make session credential dirs owner-only
Yudhi Armyndharise5d9e9d03234
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a020086c7..8e6d1fd99 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Security++- `GET /sessions/:sessionId/status/:statusId/media` now serves `image/svg+xml` status media as an inert download (`application/octet-stream` plus `Content-Disposition: attachment`), matching the chat-media route: SVG is scriptable despite the `image/` prefix, and serving it with its declared Content-Type made the endpoint stored-XSS material on the API origin.+- Session credential directories (whatsapp-web.js profiles and Baileys auth state) are created owner-only (`0o700`) and re-tightened on every session start, whichever engine runs: read access to the data volume alone is no longer equivalent to taking over the linked WhatsApp account.+## [0.19.0] - 2026-08-15### Securitydiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex a97e47d6e..e1cd9d58b 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4060,7 +4060,7 @@ Stream a stored status's media bytes (the file behind a `mediaUrl` returned abov| sessionId | string | WhatsApp session identifier || statusId | string | The status `id` (e.g. from a `GET /status` response) |-**Response** `200` — the raw media bytes as the response body, with `Content-Type` set to the stored mimetype (e.g. `image/jpeg`, `video/mp4`). Streamed via `StreamableFile` from whatever backs `StorageService` (local disk or S3 — the route does not care which).+**Response** `200` — the raw media bytes as the response body, served as an **attachment** (`Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`). `Content-Type` is the stored mimetype when it belongs to the image/video/audio families — except `image/svg+xml` in any parameterized or whitespace-padded form, which is scriptable despite the `image/` prefix — and `application/octet-stream` otherwise, so no stored status media is ever served as active content on the API origin. Streamed via `StreamableFile` from whatever backs `StorageService` (local disk or S3 — the route does not care which).**Errors:** `401` missing/invalid API key, or key not scoped to this session · `404` `Status media not found or expired` — the status is text-only, its media was omitted (e.g. over the configured size cap), or the 24h TTL has since purged the rowdiff --git a/src/common/utils/private-dir.util.spec.ts b/src/common/utils/private-dir.util.spec.tsnew file mode 100644index 000000000..c251b87bc--- /dev/null+++ b/src/common/utils/private-dir.util.spec.ts@@ -0,0 +1,46 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { ensurePrivateDir } from './private-dir.util';++// Session credential directories (whatsapp-web.js profiles, baileys creds.json) hold everything+// needed to take over the linked WhatsApp account — read access to the volume must not be enough.+// The plugin registry already writes itself owner-only (plugin-storage.service); these tests pin+// the same guarantee for dirs created on the engine path.+describe('ensurePrivateDir', () => {+ let tmpRoot: string;++ beforeEach(() => {+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'private-dir-'));+ });+ afterEach(() => {+ fs.rmSync(tmpRoot, { recursive: true, force: true });+ });++ it('creates a fresh nested directory with owner-only permissions (0o700)', () => {+ const dir = path.join(tmpRoot, 'baileys', 'alice');++ ensurePrivateDir(dir);++ expect(fs.existsSync(dir)).toBe(true);+ expect(fs.statSync(dir).mode & 0o777).toBe(0o700);+ });++ it('tightens a pre-existing world-readable directory back to 0o700', () => {+ // mkdir's `mode` only applies to directories it creates; an upgraded deployment reuses the+ // session dir it already has, so the re-chmod half is what protects existing installs.+ const dir = path.join(tmpRoot, 'sessions', 'session-alice');+ fs.mkdirSync(dir, { recursive: true, mode: 0o755 });++ ensurePrivateDir(dir);++ expect(fs.statSync(dir).mode & 0o777).toBe(0o700);+ });++ it('is best-effort: an unwritable location must not throw (the engine lib owns real failures)', () => {+ const file = path.join(tmpRoot, 'blocker');+ fs.writeFileSync(file, 'not a directory');++ expect(() => ensurePrivateDir(path.join(file, 'under-a-file'))).not.toThrow();+ });+});diff --git a/src/common/utils/private-dir.util.ts b/src/common/utils/private-dir.util.tsnew file mode 100644index 000000000..6c887a296--- /dev/null+++ b/src/common/utils/private-dir.util.ts@@ -0,0 +1,20 @@+import * as fs from 'fs';++/**+ * Create `dir` (with parents) owner-only, or tighten a pre-existing one to 0o700. Both halves are+ * needed: mkdir's `mode` applies only to directories it actually creates, so a directory that+ * already exists (an upgraded deployment reusing its session dir) keeps its old mode unless+ * chmod'd explicitly.+ *+ * Best-effort by design: callers run ahead of an engine library that creates the directory itself+ * and fails loudly when the location is genuinely unusable — a permissions-hardening failure here+ * (odd filesystem rejecting chmod, exotic mounts) must not take the session down instead.+ */+export function ensurePrivateDir(dir: string): void {+ try {+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });+ fs.chmodSync(dir, 0o700);+ } catch {+ /* best-effort hardening — the engine library creates/uses the directory regardless */+ }+}diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.tsindex 96d8d8f70..ae0be3d7a 100644--- a/src/engine/engine.factory.spec.ts+++ b/src/engine/engine.factory.spec.ts@@ -127,6 +127,55 @@ describe('EngineFactory', () => {expect(() => factory.create({ sessionId: 'sess-b', dbSessionId: 'db-b' })).toThrow(/baileys/i);});+ describe('create() makes the session credential directories owner-only', () => {+ let tmpRoot: string;++ beforeEach(() => {+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'engine-create-'));+ });+ afterEach(() => {+ fs.rmSync(tmpRoot, { recursive: true, force: true });+ });++ const buildTmpFactory = (preLoosen?: boolean) => {+ const sessionDataPath = path.join(tmpRoot, 'sessions');+ const authDir = path.join(tmpRoot, 'baileys');+ // An upgrade reuses the dirs a previous install left world-readable (default umask); fresh+ // installs have no dirs at all. Both must end at 0o700 after create().+ if (preLoosen) {+ fs.mkdirSync(path.join(sessionDataPath, 'session-alice'), { recursive: true, mode: 0o755 });+ fs.mkdirSync(path.join(authDir, 'alice'), { recursive: true, mode: 0o755 });+ }+ 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({+ 'engine.sessionDataPath': sessionDataPath,+ 'engine.baileys.authDir': authDir,+ }),+ pluginLoader,+ buildMessageStore(),+ buildLidStore(),+ );+ return {+ factory,+ wwjsDir: path.join(sessionDataPath, 'session-alice'),+ baileysDir: path.join(authDir, 'alice'),+ };+ };++ it.each([false, true])('hardens both engine shapes on a %s install', preLoosen => {+ const { factory, wwjsDir, baileysDir } = buildTmpFactory(preLoosen);++ factory.create({ sessionId: 'alice', dbSessionId: 'db-1' });++ expect(fs.statSync(wwjsDir).mode & 0o777).toBe(0o700);+ expect(fs.statSync(baileysDir).mode & 0o777).toBe(0o700);+ });+ });+describe('purgeSessionData (delete fully removes on-disk auth, keyed by session name)', () => {const noPluginLoader = () => ({ getPlugin: jest.fn() }) as unknown as PluginLoaderService;let tmpRoot: string;diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.tsindex bdc8d49f6..ad1426538 100644--- a/src/engine/engine.factory.ts+++ b/src/engine/engine.factory.ts@@ -11,6 +11,7 @@ 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';+import { ensurePrivateDir } from '../common/utils/private-dir.util';export interface EngineCreateOptions {/** Session NAME — the on-disk auth-directory key (matches the dirs purgeSessionData removes). */@@ -103,6 +104,14 @@ export class EngineFactory implements OnModuleInit {throw new Error(`Refusing to create an engine for an unsafe session name: ${JSON.stringify(options.sessionId)}`);}+ // Both engine shapes' credential dirs are made owner-only up front, whichever engine this+ // session runs and whichever construction path serves it (plugin or fallback): a whatsapp-web.js+ // profile and a baileys creds.json each hold everything needed to take over the linked account,+ // so read access to the data volume must not be enough. Mirrors purgeSessionData, which removes+ // BOTH shapes for the same engine-switch-residue reason.+ ensurePrivateDir(this.wwjsAuthDir(options.sessionId));+ ensurePrivateDir(this.baileysAuthDir(options.sessionId));+// Try to get engine from plugin systemconst enginePlugin = this.pluginLoader.getPlugin(this.engineType);diff --git a/src/modules/status/status.controller.spec.ts b/src/modules/status/status.controller.spec.tsnew file mode 100644index 000000000..a3c7a431f--- /dev/null+++ b/src/modules/status/status.controller.spec.ts@@ -0,0 +1,48 @@+import { StreamableFile } from '@nestjs/common';+import { RESPONSE_PASSTHROUGH_METADATA } from '@nestjs/common/constants';+import { StatusController } from './status.controller';+import type { StatusService } from './status.service';+import type { Response } from 'express';++/**+ * `getStatusMedia` serves third-party bytes from the API origin, exactly like the chat-media route+ * (message.controller.spec.ts holds that pair). StatusService already reduces the Content-Type to+ * an inert set, but defense is layered: attachment means even a mimetype mistake can never render+ * as active content here. The header was held by nothing — deleting the line passed every suite.+ */+describe('StatusController — stored status media download', () => {+ const getStatusMedia = jest.fn().mockResolvedValue({ buffer: Buffer.from('GIF89a'), mimetype: 'image/gif' });+ const controller = new StatusController({ getStatusMedia } as unknown as StatusService);++ // Express merges the object form of `res.set` into the header bag; accumulating mirrors that+ // regardless of how many calls the handler splits its headers across.+ const mediaResponseHeaders = async (): Promise<Record<string, string>> => {+ const headers: Record<string, string> = {};+ const res = { set: (fields: Record<string, string>) => Object.assign(headers, fields) } as unknown as Response;+ await controller.getStatusMedia('session-1', 'falsestatus@status', res);+ return headers;+ };++ it('sends nosniff, so a wrong Content-Type cannot be re-interpreted as active content', async () => {+ expect((await mediaResponseHeaders())['X-Content-Type-Options']).toBe('nosniff');+ });++ it('sends the media as an attachment, so it is never rendered on the API origin', async () => {+ expect((await mediaResponseHeaders())['Content-Disposition']).toBe('attachment');+ });++ // The headers are set on the response object directly; the bytes travel in the returned+ // StreamableFile, which Nest only sends for a passthrough-declared response parameter.+ it('declares the response passthrough, so Nest sends the returned file rather than discarding it', () => {+ expect(Reflect.getMetadata(RESPONSE_PASSTHROUGH_METADATA, StatusController, 'getStatusMedia')).toBe(true);+ });++ it('returns the stored bytes as the response body', async () => {+ const res = { set: () => undefined } as unknown as Response;++ const body = await controller.getStatusMedia('session-1', 'falsestatus@status', res);++ expect(body).toBeInstanceOf(StreamableFile);+ expect(body.getStream().read()).toEqual(Buffer.from('GIF89a'));+ });+});diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.tsindex 62b6f299d..88ce9e8bc 100644--- a/src/modules/status/status.controller.ts+++ b/src/modules/status/status.controller.ts@@ -52,7 +52,15 @@ export class StatusController {@Res({ passthrough: true }) res: Response,): Promise<StreamableFile> {const { buffer, mimetype } = await this.statusService.getStatusMedia(sessionId, statusId);- res.set({ 'Content-Type': mimetype, 'X-Content-Type-Options': 'nosniff' });+ // attachment + nosniff together, mirroring the chat-media route: the mimetype is already+ // reduced to an inert set by the service, and forcing a download means even a mistake there+ // cannot render as active content on the API origin. The dashboard fetches status media as a+ // blob (fetch ignores Content-Disposition), so nothing depends on inline display here.+ res.set({+ 'Content-Type': mimetype,+ 'X-Content-Type-Options': 'nosniff',+ 'Content-Disposition': 'attachment',+ });return new StreamableFile(buffer);}diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.tsindex 749574d51..87841627c 100644--- a/src/modules/status/status.service.spec.ts+++ b/src/modules/status/status.service.spec.ts@@ -138,6 +138,44 @@ describe('StatusService media validation and selection', () => {expect(media.mimetype).toBe('application/octet-stream');});++ it('serves image/svg+xml as inert octet-stream despite the image/ prefix (scriptable)', async () => {+ // SVG clears the (image|video|audio)/ family check yet is active content — a stored SVG+ // status served with its declared Content-Type is stored-XSS material on the API origin.+ // The chat-media path already excludes it; this closes the same hole for status media.+ store.getMedia.mockResolvedValue({ path: 'statuses/sess/x.svg', mimetype: 'image/svg+xml' });+ storageService.getFile.mockResolvedValue(Buffer.from('<svg/>'));++ const media = await service.getStatusMedia('sess', 'w1');++ expect(media.mimetype).toBe('application/octet-stream');+ });++ it.each(['image/svg+xml;charset=utf-8', 'image/svg+xml ', 'image/svg+xml ;charset=utf-8'])(+ 'serves the parameterized/spaced form %s as inert octet-stream too (browsers parse it as SVG)',+ async mimetype => {+ // The stored mimetype is engine-reported verbatim, so it can carry MIME parameters or+ // trailing OWS; a browser strips both and renders `image/svg+xml` — the exclusion must match+ // what the browser will see, not the exact byte string.+ store.getMedia.mockResolvedValue({ path: 'statuses/sess/x.svg', mimetype });+ storageService.getFile.mockResolvedValue(Buffer.from('<svg/>'));++ const media = await service.getStatusMedia('sess', 'w1');++ expect(media.mimetype).toBe('application/octet-stream');+ },+ );++ it('still serves a parameterized NON-scriptable image with its declared mimetype', async () => {+ // The exclusion is scoped to SVG: a perfectly ordinary `image/jpeg` with a charset parameter+ // (or any other image/video/audio type) must not be dragged down to octet-stream by it.+ store.getMedia.mockResolvedValue({ path: 'statuses/sess/x.jpg', mimetype: 'image/jpeg;charset=ISO-8859-1' });+ storageService.getFile.mockResolvedValue(Buffer.from('x'));++ const media = await service.getStatusMedia('sess', 'w1');++ expect(media.mimetype).toBe('image/jpeg;charset=ISO-8859-1');+ });});it('prefers explicit base64 over url for image and video status media', async () => {diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.tsindex 85b8c2f32..ff3b07dca 100644--- a/src/modules/status/status.service.ts+++ b/src/modules/status/status.service.ts@@ -10,8 +10,14 @@ import { SendPacingService, countsTowardSendBreaker } from '../message/send-paci/** Stored status media is only ever an image, a video or a voice note; a sender-declared mimetype* outside that is served as inert octet-stream so the media endpoint can't be turned into active* content (HTML/JS) on the API origin. Audio belongs here because a voice status is a first-class- * status type — without it the dashboard's audio player is handed an octet-stream it cannot play. */+ * status type — without it the dashboard's audio player is handed an octet-stream it cannot play.+ * `image/svg+xml` is excluded despite the image/ prefix: SVG is scriptable, so serving it with its+ * declared Content-Type would make the endpoint stored-XSS material — same exclusion the chat-media+ * path applies. The stored mimetype is engine-reported verbatim, so the exclusion matches what a+ * browser will parse it as: MIME parameters (`;charset=…`) and trailing whitespace are stripped by+ * the Content-Type parser, and `image/svg+xml;charset=utf-8` still renders as SVG. */const SAFE_STATUS_MIMETYPE = /^(image|video|audio)\//;+const SCRIPTABLE_SVG_MIMETYPE = /^image\/svg\+xml\s*(;|$)/;@Injectable()export class StatusService {@@ -76,7 +82,10 @@ export class StatusService {}try {const buffer = await this.storageService.getFile(media.path);- const mimetype = SAFE_STATUS_MIMETYPE.test(media.mimetype) ? media.mimetype : 'application/octet-stream';+ const mimetype =+ SAFE_STATUS_MIMETYPE.test(media.mimetype) && !SCRIPTABLE_SVG_MIMETYPE.test(media.mimetype)+ ? media.mimetype+ : 'application/octet-stream';return { buffer, mimetype };} catch (error) {// The row outlived its file: purgeExpired (or a concurrent delete) removed it between the