Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(media): convert audio and video server-side
Yudhi Armyndharis2a695ad7fcd2
diff --git a/.env.example b/.env.exampleindex d1fffce8e..1c94333ea 100644--- a/.env.example+++ b/.env.example@@ -365,6 +365,24 @@ WEBHOOK_SSRF_PROTECT=true# download holds memory up to MEDIA_DOWNLOAD_MAX_BYTES; this bounds N. A non-positive/garbage value# falls back to the default.# INBOUND_MEDIA_CONCURRENCY=4 # default 4++# ---------------------------------------------------------------------------+# Server-side media conversion (opt-in)+# ---------------------------------------------------------------------------+# Transcodes caller-supplied media into what WhatsApp clients actually play, via the ffmpeg binary,+# through POST /api/sessions/:sessionId/media/convert/voice and .../video. Nothing is converted+# implicitly — sends are untouched unless a caller runs the media through these first.+#+# WhatsApp renders a playable voice-note bubble only for Ogg/Opus. Posting MP3 bytes with ptt=true+# sends them as-is, so the recipient sees a mic bubble that will not play; converting first is what+# fixes that.+#+# The official Docker image already ships ffmpeg, so there enabling the flag is all that is needed.+# On a source install the binary must be present, otherwise the endpoints answer 503 and say so.+# MEDIA_CONVERSION_ENABLED=false # default false+# FFMPEG_PATH=ffmpeg # absolute path, for a binary outside PATH+# MEDIA_CONVERSION_TIMEOUT_MS=60000 # kill one conversion after this long (default 60s)+# MEDIA_CONVERSION_MAX_OUTPUT_BYTES=52428800 # cap the CONVERTED bytes (default 50 MiB)# Aggregate base64 budget for media inlined by ONE GET .../messages/:chatId/history?includeMedia=true# call. Once the running total crosses it, remaining media messages return the declared-only `omitted`# marker instead of a download, so a media-heavy history can't stack ~100 × the per-message cap into adiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7a5290ede..3cd0125a0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Server-side media conversion, and `ffmpeg` in the image.** WhatsApp renders a playable+ voice-note bubble only for Ogg/Opus. Nothing in the pipeline transcoded, so posting MP3 bytes to+ `send-audio` with `ptt: true` sent them as they were — labelled `audio/ogg; codecs=opus`, because+ that is the default applied when no mimetype is given — and the recipient got a mic bubble that+ would not play.++ `POST /api/sessions/:sessionId/media/convert/voice` and `.../video` transcode caller-supplied+ media and return it in the same base64 shape the send endpoints accept, so converting is one extra+ call rather than a change to how sending works. `GET .../media/convert` reports whether the+ feature is usable here. Opt-in via `MEDIA_CONVERSION_ENABLED`; sends are untouched otherwise.++ ffmpeg is run as a binary rather than through a wrapper package, and comes from Debian rather than+ a bundled static build, so codec fixes arrive through the same security stream as everything else+ in the image. Measured cost: about 210 MB, with no new fixable CRITICAL/HIGH findings under the+ release image scan. ffmpeg is only ever handed a file this server wrote and is confined to the+ file protocol — left unrestricted it resolves its input as a URL and will make the request.++ This also repairs an existing gap: whatsapp-web.js requires `fluent-ffmpeg` and uses it to build+ animated stickers from video, so `send-sticker` with a video mimetype has been failing in the+ published image for want of the binary.+### Changed- **The full TypeScript strict family is now enabled.** `strictFunctionTypes`,diff --git a/Dockerfile b/Dockerfileindex 05711a69f..c253614b4 100644--- a/Dockerfile+++ b/Dockerfile@@ -68,6 +68,13 @@ FROM docker.io/node:22-slim AS productionARG TARGETARCH# sqlite3 ships the CLI so an in-container scripts/backup.sh run takes online-consistent SQLite# snapshots (.backup) instead of plain-copying a live database (which can archive a torn file).+#+# ffmpeg backs the opt-in media-conversion endpoints, and also repairs an existing gap: whatsapp-web.js+# requires fluent-ffmpeg at module load and calls it for video-to-webp animated stickers, so+# sendSticker with a video mimetype has been failing in this image for want of the binary. Measured+# cost with --no-install-recommends: ~210 MB, and no new fixable CRITICAL/HIGH findings under the+# release image scan. It is the Debian package rather than a bundled static build precisely so that+# codec CVEs arrive through the same security stream as everything else here.RUN apt-get update && apt-get install -y --no-install-recommends \$([ "$TARGETARCH" = arm64 ] && echo "chromium chromium-sandbox") \fonts-liberation \@@ -93,6 +100,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \curl \procps \sqlite3 \+ ffmpeg \&& rm -rf /var/lib/apt/lists/*# Set Puppeteer to skip automatic download during npm install (we download it explicitly below)diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 4a69e9310..fe9d36769 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5603,6 +5603,73 @@ Reject a currently ringing incoming call. Only a live call can be rejected — t> **Auto-reject per session.** Set `"config": { "autoRejectCalls": true }` when creating a session to have the server reject every incoming call automatically — the `call.received` event is still dispatched first, so automations keep full visibility.+### 6.4.15 Media conversion (opt-in)++Server-side transcoding into the shapes WhatsApp clients actually play. Disabled by default; set+`MEDIA_CONVERSION_ENABLED=true`. The official Docker image already ships the `ffmpeg` binary these+endpoints run — on a source install it must be present, or they answer `503`.++Nothing is converted implicitly: sends behave exactly as before unless a caller runs media through+these endpoints first and posts the result.++> **Why voice conversion matters.** WhatsApp renders a playable voice-note bubble only for Ogg/Opus.+> Posting MP3 bytes to `send-audio` with `ptt: true` sends those bytes as they are, so the recipient+> gets a mic bubble that will not play. Converting first is what produces a real voice note.++#### GET /api/sessions/:sessionId/media/convert++Report whether conversion is both switched on and actually runnable here, so a client can choose+between converting server-side and converting before it sends.++**Auth:** API key++**Response** `200` — `{ "available": true }`++#### POST /api/sessions/:sessionId/media/convert/voice++Convert audio (or the audio track of a video) into a WhatsApp voice note: Ogg/Opus, mono, 48 kHz,+tuned for speech. Post the returned `base64` to `send-audio` with `ptt: true`.++**Auth:** API key (OPERATOR)++**Request body**++| Name | Type | Description |+| --- | --- | --- |+| url | string | Public http(s) URL to fetch (server-side, SSRF-guarded) |+| base64 | string | Inline bytes. Takes precedence when both are given |++Exactly one of `url` / `base64` is required. No `mimetype` is accepted: the input format is+identified from the bytes.++**Response** `200`++```json+{ "base64": "T2dnUwACAAAA...", "mimetype": "audio/ogg; codecs=opus", "bytes": 14970 }+```++**Errors:** `400` neither field given, or ffmpeg refused the input (its reason is included) · `401`+missing/invalid `X-API-Key` · `403` key lacks OPERATOR role · `413` media above the size cap · `503`+conversion disabled, or the binary is not runnable++#### POST /api/sessions/:sessionId/media/convert/video++Convert video into an MP4 every WhatsApp client accepts: baseline H.264 with AAC audio, long edge+bounded at 1280 (never upscaled), index moved to the front so playback can start before the whole+file arrives.++Request body and errors are identical to the voice endpoint.++**Response** `200`++```json+{ "base64": "AAAAIGZ0eXBpc29t...", "mimetype": "video/mp4", "bytes": 90660 }+```++**Size note.** Both endpoints return the converted media inline, so the response is bounded by the+same `MEDIA_CONVERSION_MAX_OUTPUT_BYTES` cap (default 50 MiB) — and a client posting it onward is+still bound by `BODY_SIZE_LIMIT` (default 25 MiB) on that next request.+## 6.5 Real-time API (WebSocket)Live events are delivered over a **Socket.IO** connection (not a raw WebSocket). The server mounts a single Socket.IO namespace, **`/events`**, on the same port as the REST API. There are no REST routes in this module.diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex b8ae0cb5e..da9f9fc6b 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -185,6 +185,7 @@ authoritative gate. Current policy:| `src/modules/infra/` | 73% | 71% | 87% | 86% || `src/modules/integration/` | 76% | 83% | 90% | 89% || `src/modules/mcp/` | 33% | 48% | 45% | 46% |+| `src/modules/media/` | 71% | 87% | 89% | 88% || `src/modules/message/` | 57% | 66% | 81% | 80% || `src/modules/metrics/` | 61% | 65% | 68% | 65% || `src/modules/plugins/` | 67% | 63% | 74% | 73% |diff --git a/openapi.json b/openapi.jsonindex 674250c91..ac4398916 100644--- a/openapi.json+++ b/openapi.json@@ -5430,6 +5430,89 @@]}},+ "/api/sessions/{sessionId}/media/convert": {+ "get": {+ "operationId": "MediaController_conversionStatus",+ "parameters": [],+ "responses": {+ "200": {+ "description": "Reports whether conversion is switched on AND the ffmpeg binary can be run, so a client can decide between converting here and converting before it sends."+ }+ },+ "summary": "Whether server-side media conversion is available",+ "tags": [+ "media"+ ]+ }+ },+ "/api/sessions/{sessionId}/media/convert/voice": {+ "post": {+ "operationId": "MediaController_convertVoice",+ "parameters": [],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConvertMediaDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Converted bytes, ready to post to send-audio with ptt=true. WhatsApp only renders a playable mic bubble for Ogg/Opus; other formats arrive as an audio file that will not play."+ },+ "400": {+ "description": "Neither url nor base64 given, or ffmpeg refused the input."+ },+ "413": {+ "description": "The supplied media is above the media size cap."+ },+ "503": {+ "description": "Conversion is disabled, or the ffmpeg binary is not runnable."+ }+ },+ "summary": "Convert audio into a WhatsApp voice note (Ogg/Opus)",+ "tags": [+ "media"+ ]+ }+ },+ "/api/sessions/{sessionId}/media/convert/video": {+ "post": {+ "operationId": "MediaController_convertVideo",+ "parameters": [],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConvertMediaDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Converted bytes: baseline H.264 with AAC audio, long edge bounded at 1280, index moved to the front so the recipient can start playing before the whole file arrives."+ },+ "400": {+ "description": "Neither url nor base64 given, or ffmpeg refused the input."+ },+ "413": {+ "description": "The supplied media is above the media size cap."+ },+ "503": {+ "description": "Conversion is disabled, or the ffmpeg binary is not runnable."+ }+ },+ "summary": "Convert video into a WhatsApp-compatible MP4",+ "tags": [+ "media"+ ]+ }+ },"/api/sessions/{sessionId}/catalog": {"get": {"operationId": "CatalogController_getCatalog",@@ -9062,6 +9145,21 @@"video"]},+ "ConvertMediaDto": {+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "description": "Public http(s) URL of the media to convert (server-fetched, SSRF-guarded).",+ "example": "https://example.com/note.m4a"+ },+ "base64": {+ "type": "string",+ "description": "Base64-encoded media to convert. Takes precedence when both are supplied.",+ "example": "SUQzBAAAAAAA..."+ }+ }+ },"SendProductDto": {"type": "object","properties": {diff --git a/package.json b/package.jsonindex 28cf91b55..eddddf2d5 100644--- a/package.json+++ b/package.json@@ -298,6 +298,12 @@"lines": 45,"statements": 46},+ "./src/modules/media/": {+ "branches": 71,+ "functions": 87,+ "lines": 89,+ "statements": 88+ },"./src/modules/message/": {"branches": 57,"functions": 66,diff --git a/src/app.module.ts b/src/app.module.tsindex a0f752aaa..b5cc8621e 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -32,6 +32,7 @@ import { StorageModule } from './common/storage/storage.module';import { StatsModule } from './modules/stats/stats.module';import { MetricsModule } from './modules/metrics/metrics.module';import { StatusModule } from './modules/status/status.module';+import { MediaModule } from './modules/media/media.module';import { StatusStoreModule } from './modules/status-store/status-store.module';import { ChatMediaModule } from './modules/chat-media/chat-media.module';import { CatalogModule } from './modules/catalog/catalog.module';@@ -293,6 +294,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {StatsModule, // Phase 3: Statistics DashboardMetricsModule, // Prometheus /api/metricsStatusModule, // Phase 3: Status/Stories API+ MediaModule, // Server-side media conversion (opt-in)StatusStoreModule, // Phase 3: inbound status/story TTL store (24h purge + media persistence)ChatMediaModule, // opt-in chat-media archive (retention purge + orphan sweep)CatalogModule, // Phase 3: Catalog API (WhatsApp Business)diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex a69622b2a..c04917646 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -399,6 +399,30 @@ export default () => ({})(),},+ // Server-side media conversion (opt-in): transcodes caller-supplied audio and video into the+ // shapes WhatsApp clients actually play, by running the ffmpeg binary. Nothing is converted+ // implicitly — only the explicit conversion endpoints use this.+ mediaConversion: {+ // Off by default: it spawns an external process per request, so an operator opts in knowingly.+ // Even when true the endpoints stay unavailable unless the binary is actually present, so+ // enabling it on a host without ffmpeg degrades to a clear 503 rather than a spawn error.+ enabled: process.env.MEDIA_CONVERSION_ENABLED === 'true',+ // Absolute path to the binary, for hosts that keep it outside PATH. Resolved via PATH by default.+ ffmpegPath: process.env.FFMPEG_PATH || 'ffmpeg',+ // Wall-clock ceiling for one conversion (default 60s). A codec can spin on malformed input, and+ // this process is spawned on a request path, so the timeout kills it rather than tying up a slot.+ timeoutMs: (() => {+ const n = parseInt(process.env.MEDIA_CONVERSION_TIMEOUT_MS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 60_000;+ })(),+ // Cap on the CONVERTED bytes (default 50 MiB, matching the inbound media cap). Transcoding can+ // inflate as well as shrink, so the output needs its own ceiling and not just the input's.+ maxOutputBytes: (() => {+ const n = parseInt(process.env.MEDIA_CONVERSION_MAX_OUTPUT_BYTES ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 50 * 1024 * 1024;+ })(),+ },+// Message-template renderingtemplate: {// Cap on the FINAL rendered text of a send-template request (header+body+footer joined, afterdiff --git a/src/modules/media/dto/convert-media.dto.ts b/src/modules/media/dto/convert-media.dto.tsnew file mode 100644index 000000000..bad966543--- /dev/null+++ b/src/modules/media/dto/convert-media.dto.ts@@ -0,0 +1,29 @@+import { IsString, IsNotEmpty, ValidateIf } from 'class-validator';+import { ApiPropertyOptional } from '@nestjs/swagger';++/**+ * Media to convert, in the same url-or-base64 shape every other media endpoint accepts.+ *+ * No `mimetype` field: ffmpeg identifies the input from its contents, so a declared type would be+ * ignored at best and misleading at worst. The OUTPUT type is fixed by the endpoint, and is returned+ * in the response.+ */+export class ConvertMediaDto {+ @ApiPropertyOptional({+ description: 'Public http(s) URL of the media to convert (server-fetched, SSRF-guarded).',+ example: 'https://example.com/note.m4a',+ })+ @ValidateIf((dto: ConvertMediaDto) => dto.base64 === undefined || dto.url !== undefined)+ @IsString()+ @IsNotEmpty()+ url?: string;++ @ApiPropertyOptional({+ description: 'Base64-encoded media to convert. Takes precedence when both are supplied.',+ example: 'SUQzBAAAAAAA...',+ })+ @ValidateIf((dto: ConvertMediaDto) => dto.url === undefined || dto.base64 !== undefined)+ @IsString()+ @IsNotEmpty()+ base64?: string;+}diff --git a/src/modules/media/ffmpeg-run.spec.ts b/src/modules/media/ffmpeg-run.spec.tsnew file mode 100644index 000000000..8e4cac8fa--- /dev/null+++ b/src/modules/media/ffmpeg-run.spec.ts@@ -0,0 +1,139 @@+import { chmod, mkdtemp, readdir, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { FfmpegConversionError, probeFfmpeg, runFfmpeg } from './ffmpeg';++/**+ * Exercises the process wrapper itself — the timeout, the output ceiling, and the temp-directory+ * cleanup — none of which the argument-shape tests touch.+ *+ * It runs against a stub standing in for ffmpeg rather than the real binary, for two reasons: the+ * behaviours under test are about how this code handles a child process, not about transcoding, and+ * a suite that needed ffmpeg installed would simply be skipped on most machines, which is the same+ * as not having it.+ */+const describePosix = process.platform === 'win32' ? describe.skip : describe;++describePosix('runFfmpeg', () => {+ let stubPath: string;+ let workDir: string;++ beforeAll(async () => {+ workDir = await mkdtemp(join(tmpdir(), 'openwa-ffmpeg-stub-'));+ stubPath = join(workDir, 'fake-ffmpeg');+ // Behaves like ffmpeg to the degree this code depends on: writes the file named last, and+ // reports failure on stderr with a non-zero exit.+ //+ // The mode travels in the ARGUMENTS rather than the environment, because Jest sandboxes+ // process.env while spawn hands the child the real one — a mode set here would never arrive.+ // Passing it as an encoder argument also exercises the fact that those are forwarded verbatim.+ await writeFile(+ stubPath,+ `#!/bin/sh+if [ "$1" = "-version" ]; then echo "ffmpeg version stub"; exit 0; fi+mode=ok+for a in "$@"; do+ case "$a" in MODE=*) mode="\${a#MODE=}" ;; esac+ out="$a"+done+case "$mode" in+ fail) echo "Invalid data found when processing input" >&2; exit 1 ;;+ hang) sleep 30 ;;+ empty) : > "$out" ;;+ big) head -c 4096 /dev/zero > "$out" ;;+ *) printf 'converted-output' > "$out" ;;+esac+`,+ );+ await chmod(stubPath, 0o755);+ });++ /** Encoder arguments that put the stub into a given mode. */+ const mode = (name: string): string[] => [`MODE=${name}`];++ const options = (overrides: Partial<Parameters<typeof runFfmpeg>[4]> = {}) => ({+ ffmpegPath: stubPath,+ timeoutMs: 5_000,+ maxOutputBytes: 1024,+ ...overrides,+ });++ /** Temp directories this module creates, so cleanup can be asserted rather than assumed. */+ const convertDirs = async (): Promise<string[]> =>+ (await readdir(tmpdir())).filter(name => name.startsWith('openwa-convert-'));++ it('returns the bytes the process produced', async () => {+ const output = await runFfmpeg(Buffer.from('input'), 'bin', 'ogg', [], options());++ expect(output).toEqual(Buffer.from('converted-output'));+ });++ it('removes its temp directory once it has succeeded', async () => {+ const before = await convertDirs();++ await runFfmpeg(Buffer.from('input'), 'bin', 'ogg', [], options());++ expect(await convertDirs()).toEqual(before);+ });++ // The input is a file, so a failure part-way through would otherwise leave it on the volume.+ it('removes its temp directory even when the conversion fails', async () => {+ const before = await convertDirs();++ await expect(runFfmpeg(Buffer.from('input'), 'bin', 'ogg', mode('fail'), options())).rejects.toThrow();++ expect(await convertDirs()).toEqual(before);+ });++ it('reports a non-zero exit with the process’s own words', async () => {+ await expect(runFfmpeg(Buffer.from('input'), 'bin', 'ogg', mode('fail'), options())).rejects.toMatchObject({+ message: expect.stringContaining('exited with code 1') as unknown,+ detail: 'Invalid data found when processing input',+ });+ });++ // A codec stuck in a loop is the case this defends against, so the kill has to be unconditional.+ it('kills a process that overruns its timeout, rather than waiting on it', async () => {+ const startedAt = Date.now();++ await expect(+ runFfmpeg(Buffer.from('input'), 'bin', 'ogg', mode('hang'), options({ timeoutMs: 200 })),+ ).rejects.toThrow(/timed out after 200ms/);++ // Comfortably below the stub's 30s sleep: proves it was killed, not awaited.+ expect(Date.now() - startedAt).toBeLessThan(10_000);+ }, 15_000);++ // Transcoding can inflate as well as shrink, so the output needs a ceiling of its own.+ it('refuses output above the cap, and says what it measured', async () => {+ await expect(+ runFfmpeg(Buffer.from('input'), 'bin', 'ogg', mode('big'), options({ maxOutputBytes: 1000 })),+ ).rejects.toThrow(/4096 bytes, above the 1000 byte limit/);+ });++ // An empty file is a silent failure: it would otherwise be returned as a valid zero-byte result.+ it('treats an empty result as a failure', async () => {+ await expect(runFfmpeg(Buffer.from('input'), 'bin', 'ogg', mode('empty'), options())).rejects.toThrow(+ /produced no output/,+ );+ });++ it('says plainly when the binary cannot be executed at all', async () => {+ await expect(+ runFfmpeg(Buffer.from('input'), 'bin', 'ogg', [], options({ ffmpegPath: join(workDir, 'not-here') })),+ ).rejects.toBeInstanceOf(FfmpegConversionError);+ await expect(+ runFfmpeg(Buffer.from('input'), 'bin', 'ogg', [], options({ ffmpegPath: join(workDir, 'not-here') })),+ ).rejects.toThrow(/Could not run ffmpeg/);+ });++ describe('probeFfmpeg', () => {+ it('is true for a runnable binary', async () => {+ await expect(probeFfmpeg(stubPath)).resolves.toBe(true);+ });++ it('is false when the binary is missing, rather than throwing', async () => {+ await expect(probeFfmpeg(join(workDir, 'not-here'))).resolves.toBe(false);+ });+ });+});diff --git a/src/modules/media/ffmpeg.spec.ts b/src/modules/media/ffmpeg.spec.tsnew file mode 100644index 000000000..bf583ed57--- /dev/null+++ b/src/modules/media/ffmpeg.spec.ts@@ -0,0 +1,96 @@+import { buildFfmpegArgs, voiceEncodeArgs, videoEncodeArgs } from './ffmpeg';++/**+ * These pin the two things about the argument lists that are load-bearing and easy to break while+ * "tidying": the quoting inside the scale filter, and the codec choices WhatsApp actually requires.+ *+ * The scale quoting is not cosmetic. ffmpeg splits a filter description on commas, so the comma+ * inside `min(1280,iw)` terminates the filter unless the expression is quoted — the unquoted form+ * fails with `Invalid size 'min(1280'`. Because these arguments are passed through spawn rather than+ * a shell, the quotes have to be part of the string itself; a reviewer removing them as redundant+ * shell syntax would break every video conversion, and nothing else here would notice.+ */+describe('ffmpeg encoder arguments', () => {+ /** Read `-flag value` out of an argv array, so assertions do not depend on argument order. */+ const valueOf = (args: string[], flag: string): string | undefined => {+ const i = args.indexOf(flag);+ return i === -1 ? undefined : args[i + 1];+ };++ describe('voice', () => {+ const args = voiceEncodeArgs();++ // Ogg/Opus is what makes a WhatsApp client render a playable mic bubble rather than a file.+ it('encodes Opus', () => {+ expect(valueOf(args, '-c:a')).toBe('libopus');+ });++ it('drops any video stream, so converting a video yields audio only', () => {+ expect(args).toContain('-vn');+ });++ // Mono at 48 kHz with the voip tuning is what the app's own recorder produces.+ it('produces mono 48 kHz tuned for speech', () => {+ expect(valueOf(args, '-ac')).toBe('1');+ expect(valueOf(args, '-ar')).toBe('48000');+ expect(valueOf(args, '-application')).toBe('voip');+ });+ });++ describe('video', () => {+ const args = videoEncodeArgs();++ // Baseline + yuv420p is the pairing that plays on every WhatsApp client, including older Android.+ it('encodes baseline H.264 with a widely playable pixel format', () => {+ expect(valueOf(args, '-c:v')).toBe('libx264');+ expect(valueOf(args, '-profile:v')).toBe('baseline');+ expect(valueOf(args, '-pix_fmt')).toBe('yuv420p');+ });++ it('moves the index to the front so playback can start before the file finishes arriving', () => {+ expect(valueOf(args, '-movflags')).toBe('+faststart');+ });++ // The regression this exists for: unquoted, ffmpeg reads the filter as `scale=min(1280`.+ it('quotes the scale expression so its comma stays inside min()', () => {+ expect(valueOf(args, '-vf')).toBe("scale='min(1280,iw)':-2");+ });++ // -2 keeps the computed edge even, which H.264 requires; -1 would produce odd heights and fail.+ it('keeps the derived edge even', () => {+ expect(valueOf(args, '-vf')).toMatch(/:-2$/);+ });+ });+});++/**+ * ffmpeg resolves its input as a URL, and left unrestricted it will make the request: pointed at an+ * `http://` address it reaches the network, which on a cloud host includes the link-local metadata+ * endpoint. The input here is always a file this process just wrote, so confining ffmpeg to the file+ * protocol costs nothing and removes the class entirely. Losing that flag would be invisible —+ * every conversion would still succeed — which is exactly why it is pinned here.+ */+describe('ffmpeg invocation shape', () => {+ const args = buildFfmpegArgs('/tmp/openwa-convert-x/in.bin', '/tmp/openwa-convert-x/out.ogg', ['-c:a', 'libopus']);++ it('confines ffmpeg to the file protocol', () => {+ expect(args[args.indexOf('-protocol_whitelist') + 1]).toBe('file');+ });++ it('never waits on stdin, and never prompts about an existing output', () => {+ expect(args).toContain('-nostdin');+ expect(args).toContain('-y');+ });++ it('names the input immediately after -i, and the output last', () => {+ expect(args[args.indexOf('-i') + 1]).toBe('/tmp/openwa-convert-x/in.bin');+ expect(args[args.length - 1]).toBe('/tmp/openwa-convert-x/out.ogg');+ });++ // Encoder flags have to land between the input and the output; ffmpeg applies options positionally,+ // so an encoder flag placed before -i would be read as an INPUT option and silently do nothing.+ it('places encoder arguments between the input and the output', () => {+ expect(args.indexOf('-c:a')).toBeGreaterThan(args.indexOf('-i'));+ expect(args.indexOf('-c:a')).toBeLessThan(args.length - 1);+ });+});diff --git a/src/modules/media/ffmpeg.ts b/src/modules/media/ffmpeg.tsnew file mode 100644index 000000000..cc13092c7--- /dev/null+++ b/src/modules/media/ffmpeg.ts@@ -0,0 +1,190 @@+import { spawn } from 'node:child_process';+import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++/** A conversion that ffmpeg refused, timed out on, or produced too much output for. */+export class FfmpegConversionError extends Error {+ constructor(+ message: string,+ /** ffmpeg's own last words, already trimmed. Empty when it never got that far. */+ readonly detail: string = '',+ ) {+ super(message);+ this.name = 'FfmpegConversionError';+ }+}++export interface FfmpegRunOptions {+ /** Binary to execute. Resolved through PATH unless absolute. */+ ffmpegPath: string;+ /** Wall-clock ceiling; the process is killed past it. */+ timeoutMs: number;+ /** Ceiling on the produced bytes. */+ maxOutputBytes: number;+}++/**+ * The arguments every conversion starts with, before any codec choice.+ *+ * `-protocol_whitelist file` is the load-bearing one. ffmpeg treats its input as a URL, and given an+ * `http://` one it will happily make the request — verified against this project's own image, where+ * it reached for the link-local metadata address. The input here is always a file this process just+ * wrote, so restricting ffmpeg to the file protocol costs nothing and removes the whole class:+ * neither the input path nor anything a crafted container might reference can become a request.+ *+ * `-nostdin` stops a prompt (an existing output file, a missing codec) from blocking forever on a+ * stdin nobody is attached to, and `-y` means there is nothing to prompt about in the first place.+ */+const BASE_ARGS = ['-hide_banner', '-nostdin', '-loglevel', 'error', '-y', '-protocol_whitelist', 'file'] as const;++/**+ * The full argument list for one conversion. Split out from the spawn so the security-relevant+ * shape — restricted protocols, no stdin, and the fact that the only paths present are ones this+ * process chose — can be asserted without running a process.+ */+export function buildFfmpegArgs(inputPath: string, outputPath: string, encodeArgs: string[]): string[] {+ return [...BASE_ARGS, '-i', inputPath, ...encodeArgs, outputPath];+}++/**+ * Encoder arguments for a WhatsApp voice note.+ *+ * Ogg/Opus is what a WhatsApp client expects for a PTT bubble; anything else arrives as a file that+ * will not play in the mic UI. Mono at 48 kHz with the `voip` tuning is what the app's own recorder+ * produces, and 32 kbit/s is transparent for speech while keeping a long note small.+ */+export function voiceEncodeArgs(): string[] {+ return ['-vn', '-c:a', 'libopus', '-b:a', '32k', '-ar', '48000', '-ac', '1', '-application', 'voip'];+}++/**+ * Encoder arguments for a video WhatsApp will accept and preview.+ *+ * Baseline H.264 with yuv420p is the combination that plays on every WhatsApp client, including the+ * older Android ones that reject High profile. `faststart` relocates the index to the front so the+ * receiver can begin playback before the whole file arrives. The scale filter bounds the long edge+ * at 1280 while `-2` keeps the other edge even, which H.264 requires — and `min()` means a smaller+ * video is never upscaled into a larger file than it started as.+ */+export function videoEncodeArgs(): string[] {+ return [+ '-c:v',+ 'libx264',+ '-profile:v',+ 'baseline',+ '-level',+ '3.1',+ '-pix_fmt',+ 'yuv420p',+ '-vf',+ "scale='min(1280,iw)':-2",+ '-c:a',+ 'aac',+ '-b:a',+ '128k',+ '-movflags',+ '+faststart',+ ];+}++/**+ * Convert `input` by running ffmpeg once, and return the produced bytes.+ *+ * The input is written to a freshly created private directory rather than being streamed in, because+ * the muxers used here seek: Ogg rewrites its page headers and `+faststart` moves the MP4 index to+ * the front, and neither can do that on a pipe. Writing both sides to a temp directory that is+ * removed in `finally` keeps that from turning into litter on the volume.+ *+ * The caller's bytes never reach the argument list — only paths this function chose — so nothing a+ * caller sends can be read as an ffmpeg option.+ */+export async function runFfmpeg(+ input: Buffer,+ inputExtension: string,+ outputExtension: string,+ encodeArgs: string[],+ options: FfmpegRunOptions,+): Promise<Buffer> {+ const dir = await mkdtemp(join(tmpdir(), 'openwa-convert-'));+ const inputPath = join(dir, `in.${inputExtension}`);+ const outputPath = join(dir, `out.${outputExtension}`);+ try {+ await writeFile(inputPath, input);+ await execute(buildFfmpegArgs(inputPath, outputPath, encodeArgs), options);++ // Check the size on disk before reading, so an unexpectedly large result is refused instead of+ // being pulled into memory first.+ const { size } = await stat(outputPath);+ if (size > options.maxOutputBytes) {+ throw new FfmpegConversionError(+ `Converted media is ${size} bytes, above the ${options.maxOutputBytes} byte limit`,+ );+ }+ if (size === 0) {+ throw new FfmpegConversionError('Conversion produced no output');+ }+ return await readFile(outputPath);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+}++/** Spawn ffmpeg and resolve when it exits 0, else reject with whatever it wrote to stderr. */+function execute(args: string[], options: FfmpegRunOptions): Promise<void> {+ return new Promise((resolve, reject) => {+ // An argument array, never a shell string: nothing here can be word-split or expanded, so a+ // filename with a space or a quote is data rather than syntax.+ const child = spawn(options.ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'] });++ let stderr = '';+ let timedOut = false;+ // Bounded: a failing codec can produce error output indefinitely, and only the tail is useful.+ child.stderr.on('data', (chunk: Buffer) => {+ stderr = (stderr + chunk.toString()).slice(-4096);+ });++ const timer = setTimeout(() => {+ timedOut = true;+ // SIGKILL rather than SIGTERM: the case being defended against is a codec stuck in a loop,+ // which is exactly the case that would ignore a polite signal.+ child.kill('SIGKILL');+ // Reject as soon as the signal is sent rather than waiting for `close`. `close` fires when the+ // stdio pipes close, not when the process dies, so anything still holding the inherited stderr+ // keeps it pending — which would leave the timeout bounding nothing at all.+ reject(new FfmpegConversionError(`Conversion timed out after ${options.timeoutMs}ms`));+ }, options.timeoutMs);++ child.on('error', err => {+ clearTimeout(timer);+ // Spawn itself failed — almost always a missing binary, which is worth saying plainly.+ reject(new FfmpegConversionError(`Could not run ffmpeg: ${err instanceof Error ? err.message : String(err)}`));+ });++ child.on('close', code => {+ clearTimeout(timer);+ // Already rejected by the timer; a late close has nothing left to report.+ if (timedOut) return;+ if (code !== 0) {+ reject(new FfmpegConversionError(`ffmpeg exited with code ${code}`, stderr.trim()));+ return;+ }+ resolve();+ });+ });+}++/**+ * Whether the configured binary can actually be run.+ *+ * Probed by executing it rather than by looking for the file, since a path on PATH, a wrong+ * architecture and a non-executable file all differ only at exec time.+ */+export async function probeFfmpeg(ffmpegPath: string, timeoutMs = 5_000): Promise<boolean> {+ try {+ await execute(['-version'], { ffmpegPath, timeoutMs, maxOutputBytes: 0 });+ return true;+ } catch {+ return false;+ }+}diff --git a/src/modules/media/media-conversion.service.spec.ts b/src/modules/media/media-conversion.service.spec.tsnew file mode 100644index 000000000..fa4b5b145--- /dev/null+++ b/src/modules/media/media-conversion.service.spec.ts@@ -0,0 +1,159 @@+import { BadRequestException, PayloadTooLargeException, ServiceUnavailableException } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';+import { MediaConversionService } from './media-conversion.service';+import * as ffmpeg from './ffmpeg';+import * as loadRemoteMedia from '../../common/media/load-remote-media';++/**+ * The behaviours worth pinning here are the ones a caller can reach: that a host without ffmpeg says+ * so instead of failing at spawn time, that the caller's bytes are size-checked on the way in, and —+ * most of all — that a remote URL is fetched through the SSRF guard and never handed to ffmpeg,+ * which would resolve it itself.+ */+describe('MediaConversionService', () => {+ const config = (overrides: Record<string, unknown> = {}): ConfigService => {+ const values: Record<string, unknown> = {+ 'mediaConversion.enabled': true,+ 'mediaConversion.ffmpegPath': 'ffmpeg',+ 'mediaConversion.timeoutMs': 60_000,+ 'mediaConversion.maxOutputBytes': 50 * 1024 * 1024,+ ...overrides,+ };+ return { get: (key: string, fallback?: unknown) => values[key] ?? fallback } as unknown as ConfigService;+ };++ /** runFfmpeg(input, inputExtension, outputExtension, ...) — the third argument fixes the format. */+ const outputExtensionOf = (spy: jest.SpyInstance): unknown => (spy.mock.calls[0] as unknown[])[2];++ let runFfmpeg: jest.SpyInstance;+ let probeFfmpeg: jest.SpyInstance;++ beforeEach(() => {+ runFfmpeg = jest.spyOn(ffmpeg, 'runFfmpeg').mockResolvedValue(Buffer.from('converted-bytes'));+ probeFfmpeg = jest.spyOn(ffmpeg, 'probeFfmpeg').mockResolvedValue(true);+ });+ afterEach(() => jest.restoreAllMocks());++ describe('availability', () => {+ it('refuses with 503 when conversion is switched off, without probing for the binary', async () => {+ const service = new MediaConversionService(config({ 'mediaConversion.enabled': false }));++ await expect(service.convertToVoice({ base64: 'AAAA' })).rejects.toBeInstanceOf(ServiceUnavailableException);+ expect(probeFfmpeg).not.toHaveBeenCalled();+ expect(runFfmpeg).not.toHaveBeenCalled();+ });++ // Enabling the flag on a host with no ffmpeg must be a clear answer, not a spawn error.+ it('refuses with 503 when the binary cannot be run', async () => {+ probeFfmpeg.mockResolvedValue(false);+ const service = new MediaConversionService(config());++ await expect(service.convertToVoice({ base64: 'AAAA' })).rejects.toThrow(/ffmpeg binary could not be run/);+ expect(runFfmpeg).not.toHaveBeenCalled();+ });++ it('reports availability without converting anything', async () => {+ await expect(new MediaConversionService(config()).isAvailable()).resolves.toBe(true);+ await expect(+ new MediaConversionService(config({ 'mediaConversion.enabled': false })).isAvailable(),+ ).resolves.toBe(false);+ });++ // Concurrent first requests must not each spawn their own probe.+ it('probes the binary once per process, even under concurrent first calls', async () => {+ const service = new MediaConversionService(config());++ await Promise.all([service.isAvailable(), service.isAvailable(), service.convertToVoice({ base64: 'AAAA' })]);++ expect(probeFfmpeg).toHaveBeenCalledTimes(1);+ });+ });++ describe('resolving the caller’s media', () => {+ // The point of the whole endpoint shape: ffmpeg is handed BYTES, never a URL. Given a URL it+ // would fetch the address itself, outside the guard that vets and pins the destination.+ it('fetches a URL through the SSRF guard and gives ffmpeg the bytes, not the URL', async () => {+ const load = jest+ .spyOn(loadRemoteMedia, 'loadRemoteMediaBuffer')+ .mockResolvedValue({ data: Buffer.from('remote-audio'), mimetype: 'audio/mpeg' });+ const service = new MediaConversionService(config());++ await service.convertToVoice({ url: 'https://example.com/note.m4a' });++ expect(load).toHaveBeenCalledWith('https://example.com/note.m4a');+ const [input] = runFfmpeg.mock.calls[0] as [Buffer];+ expect(input).toEqual(Buffer.from('remote-audio'));+ // Nothing resembling the URL may appear anywhere in the ffmpeg call.+ expect(JSON.stringify(runFfmpeg.mock.calls[0])).not.toContain('example.com');+ });++ it('decodes base64, stripping a data: prefix', async () => {+ const service = new MediaConversionService(config());++ await service.convertToVoice({ base64: `data:audio/mpeg;base64,${Buffer.from('inline').toString('base64')}` });++ expect((runFfmpeg.mock.calls[0] as [Buffer])[0]).toEqual(Buffer.from('inline'));+ });++ it('rejects base64 above the media cap with 413, before any conversion', async () => {+ const service = new MediaConversionService(config());+ const oversized = Buffer.alloc(51 * 1024 * 1024).toString('base64');++ await expect(service.convertToVoice({ base64: oversized })).rejects.toBeInstanceOf(PayloadTooLargeException);+ expect(runFfmpeg).not.toHaveBeenCalled();+ });++ it('rejects a request carrying neither url nor base64', async () => {+ await expect(new MediaConversionService(config()).convertToVoice({})).rejects.toThrow(+ /Either url or base64 must be provided/,+ );+ });++ it('rejects base64 that decodes to nothing', async () => {+ await expect(new MediaConversionService(config()).convertToVoice({ base64: '!!!' })).rejects.toThrow(+ /did not decode/,+ );+ });+ });++ describe('conversion', () => {+ it('returns Ogg/Opus for voice, which is what makes a playable mic bubble', async () => {+ const service = new MediaConversionService(config());++ const result = await service.convertToVoice({ base64: 'AAAA' });++ expect(result).toEqual({+ base64: Buffer.from('converted-bytes').toString('base64'),+ mimetype: 'audio/ogg; codecs=opus',+ bytes: 15,+ });+ expect(outputExtensionOf(runFfmpeg)).toBe('ogg');+ });++ it('returns MP4 for video', async () => {+ const service = new MediaConversionService(config());++ const result = await service.convertToVideo({ base64: 'AAAA' });++ expect(result.mimetype).toBe('video/mp4');+ expect(outputExtensionOf(runFfmpeg)).toBe('mp4');+ });++ // ffmpeg's complaint is about the caller's own bytes, so surfacing it is what makes a 400 useful.+ it('turns an ffmpeg refusal into a 400 carrying its reason', async () => {+ runFfmpeg.mockRejectedValue(new ffmpeg.FfmpegConversionError('ffmpeg exited with code 1', 'Invalid data found'));+ const service = new MediaConversionService(config());++ await expect(service.convertToVoice({ base64: 'AAAA' })).rejects.toBeInstanceOf(BadRequestException);+ await expect(service.convertToVoice({ base64: 'AAAA' })).rejects.toThrow(/Invalid data found/);+ });++ // A programming error must not be relabelled as the caller's fault.+ it('lets an unexpected error through rather than reporting it as a bad request', async () => {+ runFfmpeg.mockRejectedValue(new TypeError('boom'));+ const service = new MediaConversionService(config());++ await expect(service.convertToVoice({ base64: 'AAAA' })).rejects.toBeInstanceOf(TypeError);+ });+ });+});diff --git a/src/modules/media/media-conversion.service.ts b/src/modules/media/media-conversion.service.tsnew file mode 100644index 000000000..036884ae9--- /dev/null+++ b/src/modules/media/media-conversion.service.ts@@ -0,0 +1,124 @@+import { BadRequestException, Injectable, ServiceUnavailableException } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';+import { createLogger } from '../../common/services/logger.service';+import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';+import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';+import { FfmpegConversionError, probeFfmpeg, runFfmpeg, videoEncodeArgs, voiceEncodeArgs } from './ffmpeg';+import type { ConvertMediaDto } from './dto/convert-media.dto';++/** What a conversion produced, in the same url-or-base64 vocabulary the send endpoints speak. */+export interface ConvertedMedia {+ /** The converted bytes, ready to hand straight to a send endpoint's `base64` field. */+ base64: string;+ /** The type the bytes now are — not the type they were. */+ mimetype: string;+ /** Decoded size, so a caller can check it against a send limit without decoding. */+ bytes: number;+}++@Injectable()+export class MediaConversionService {+ private readonly logger = createLogger('MediaConversionService');+ /** Result of the binary probe. Cached because it cannot change without a restart. */+ private binaryAvailable?: Promise<boolean>;++ constructor(private readonly configService: ConfigService) {}++ /**+ * Convert to a WhatsApp voice note: Ogg/Opus, which is what produces a playable mic bubble.+ *+ * This exists because nothing else in the pipeline transcodes. A caller who posts MP3 bytes with+ * `ptt: true` gets them sent as-is, labelled `audio/ogg; codecs=opus` because that is the default+ * applied when no mimetype is given — the declared type and the actual bytes disagree, and the+ * recipient sees a voice note that will not play.+ */+ async convertToVoice(dto: ConvertMediaDto): Promise<ConvertedMedia> {+ return this.convert(dto, 'ogg', voiceEncodeArgs(), 'audio/ogg; codecs=opus');+ }++ /** Convert to an MP4 WhatsApp will accept and preview on every client. */+ async convertToVideo(dto: ConvertMediaDto): Promise<ConvertedMedia> {+ return this.convert(dto, 'mp4', videoEncodeArgs(), 'video/mp4');+ }++ /** Whether conversion is both switched on and actually runnable on this host. */+ async isAvailable(): Promise<boolean> {+ if (!this.configService.get<boolean>('mediaConversion.enabled', false)) return false;+ return this.probeOnce();+ }++ private async convert(+ dto: ConvertMediaDto,+ outputExtension: string,+ encodeArgs: string[],+ outputMimetype: string,+ ): Promise<ConvertedMedia> {+ await this.assertAvailable();+ const input = await this.resolveInput(dto);++ try {+ const output = await runFfmpeg(input, 'bin', outputExtension, encodeArgs, {+ ffmpegPath: this.configService.get<string>('mediaConversion.ffmpegPath', 'ffmpeg'),+ timeoutMs: this.configService.get<number>('mediaConversion.timeoutMs', 60_000),+ maxOutputBytes: this.configService.get<number>('mediaConversion.maxOutputBytes', 50 * 1024 * 1024),+ });+ this.logger.log('Media converted', { inputBytes: input.length, outputBytes: output.length, outputMimetype });+ return { base64: output.toString('base64'), mimetype: outputMimetype, bytes: output.length };+ } catch (error) {+ if (error instanceof FfmpegConversionError) {+ // ffmpeg's stderr is about the caller's own bytes, so returning it is what makes a rejection+ // actionable. It never names a path the caller did not supply: the only paths in the command+ // are the temp files this process created.+ this.logger.warn('Media conversion failed', { reason: error.message, detail: error.detail });+ throw new BadRequestException(error.detail ? `${error.message}: ${error.detail}` : error.message);+ }+ throw error;+ }+ }++ /** Read the caller's media into memory, honouring the same caps and SSRF guard as a send. */+ private async resolveInput(dto: ConvertMediaDto): Promise<Buffer> {+ if (dto.base64) {+ // Checked before decoding, so an oversized payload is refused without allocating it.+ assertBase64WithinMediaCap(dto.base64);+ const data = Buffer.from(stripBase64DataUri(dto.base64) ?? '', 'base64');+ if (data.length === 0) throw new BadRequestException('base64 did not decode to any bytes');+ return data;+ }+ if (dto.url) {+ // Through the SSRF guard, exactly as a send does: it validates the host and pins the+ // connection to the vetted address. ffmpeg itself never sees a URL — it is restricted to the+ // file protocol and handed bytes this process already fetched and checked.+ const { data } = await loadRemoteMediaBuffer(dto.url);+ return data;+ }+ throw new BadRequestException('Either url or base64 must be provided');+ }++ private async assertAvailable(): Promise<void> {+ if (!this.configService.get<boolean>('mediaConversion.enabled', false)) {+ throw new ServiceUnavailableException(+ 'Media conversion is disabled. Set MEDIA_CONVERSION_ENABLED=true to enable it.',+ );+ }+ if (!(await this.probeOnce())) {+ throw new ServiceUnavailableException(+ 'Media conversion is enabled but the ffmpeg binary could not be run. Install ffmpeg, or set FFMPEG_PATH.',+ );+ }+ }++ /**+ * Probe once per process. The promise itself is memoised rather than its result, so concurrent+ * first requests share one probe instead of each spawning their own.+ */+ private probeOnce(): Promise<boolean> {+ this.binaryAvailable ??= probeFfmpeg(this.configService.get<string>('mediaConversion.ffmpegPath', 'ffmpeg')).then(+ available => {+ if (!available) this.logger.warn('Media conversion is enabled but ffmpeg could not be run');+ return available;+ },+ );+ return this.binaryAvailable;+ }+}diff --git a/src/modules/media/media.controller.spec.ts b/src/modules/media/media.controller.spec.tsnew file mode 100644index 000000000..6f06b5096--- /dev/null+++ b/src/modules/media/media.controller.spec.ts@@ -0,0 +1,89 @@+import { HttpStatus, RequestMethod } from '@nestjs/common';+import { PATH_METADATA, METHOD_METADATA, HTTP_CODE_METADATA } from '@nestjs/common/constants';+import { MediaController } from './media.controller';+import type { MediaConversionService } from './media-conversion.service';+import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';++/**+ * The handlers are thin, so what is worth asserting is the wiring around them: the route shape that+ * earns the session fence, the roles, and the status code.+ */+describe('MediaController', () => {+ // Held as standalone mocks rather than read back off the service object, so an assertion never+ // has to reference a method detached from its receiver.+ const convertToVoice = jest.fn().mockResolvedValue({ base64: 'b', mimetype: 'audio/ogg; codecs=opus', bytes: 1 });+ const convertToVideo = jest.fn().mockResolvedValue({ base64: 'b', mimetype: 'video/mp4', bytes: 1 });+ const isAvailable = jest.fn().mockResolvedValue(true);+ const controller = new MediaController({+ convertToVoice,+ convertToVideo,+ isAvailable,+ } as unknown as MediaConversionService);++ afterEach(() => jest.clearAllMocks());++ /**+ * Nest stores handler metadata on the prototype method. Looked up by name rather than as+ * `controller.convertVoice`, because that form reads as an unbound method call even though nothing+ * here invokes it.+ */+ const handler = (name: keyof MediaController): object =>+ (MediaController.prototype as unknown as Record<string, object>)[name];++ describe('routing', () => {+ /**+ * The session segment is what clears the global-route fence and, more importantly, what lets a+ * session-restricted API key use these routes at all: the guard resolves that restriction from+ * route parameters, so a deployment-global path would have to shut those keys out.+ */+ it('is mounted under a session, so a session-scoped key can reach it', () => {+ expect(Reflect.getMetadata(PATH_METADATA, MediaController)).toBe('sessions/:sessionId/media');+ });++ it('answers 200 rather than 201 — a conversion creates no resource', () => {+ expect(Reflect.getMetadata(HTTP_CODE_METADATA, handler('convertVoice'))).toBe(HttpStatus.OK);+ expect(Reflect.getMetadata(HTTP_CODE_METADATA, handler('convertVideo'))).toBe(HttpStatus.OK);+ });++ it('exposes conversion as POST and the availability probe as GET', () => {+ expect(Reflect.getMetadata(METHOD_METADATA, handler('convertVoice'))).toBe(RequestMethod.POST);+ expect(Reflect.getMetadata(METHOD_METADATA, handler('convertVideo'))).toBe(RequestMethod.POST);+ expect(Reflect.getMetadata(METHOD_METADATA, handler('conversionStatus'))).toBe(RequestMethod.GET);+ });+ });++ describe('authorization', () => {+ // Converting spends CPU and spawns a process, so it sits behind the same role as sending.+ it('requires OPERATOR to convert', () => {+ expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, handler('convertVoice'))).toBe(ApiKeyRole.OPERATOR);+ expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, handler('convertVideo'))).toBe(ApiKeyRole.OPERATOR);+ });++ // Asking whether the feature exists reveals nothing, and a read-only key needs the answer to+ // decide whether to convert on its own side.+ it('leaves the availability probe open to any valid key', () => {+ expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, handler('conversionStatus'))).toBeUndefined();+ });+ });++ describe('delegation', () => {+ it('passes the body straight to the voice conversion', async () => {+ const dto = { base64: 'AAAA' };++ await expect(controller.convertVoice(dto)).resolves.toMatchObject({ mimetype: 'audio/ogg; codecs=opus' });+ expect(convertToVoice).toHaveBeenCalledWith(dto);+ });++ it('passes the body straight to the video conversion', async () => {+ const dto = { url: 'https://example.com/clip.mov' };++ await expect(controller.convertVideo(dto)).resolves.toMatchObject({ mimetype: 'video/mp4' });+ expect(convertToVideo).toHaveBeenCalledWith(dto);+ });++ it('reports availability as a plain flag', async () => {+ await expect(controller.conversionStatus()).resolves.toEqual({ available: true });+ });+ });+});diff --git a/src/modules/media/media.controller.ts b/src/modules/media/media.controller.tsnew file mode 100644index 000000000..d92653f45--- /dev/null+++ b/src/modules/media/media.controller.ts@@ -0,0 +1,67 @@+import { Body, Controller, Get, HttpCode, HttpStatus, Post } from '@nestjs/common';+import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';+import { MediaConversionService } from './media-conversion.service';+import { ConvertMediaDto } from './dto/convert-media.dto';+import { RequireRole } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';++/**+ * Server-side transcoding, scoped to a session.+ *+ * Conversion itself needs no session — it never touches WhatsApp. The session dimension is kept+ * because this project's API keys can be restricted to specific sessions, and the guard resolves+ * that restriction from route parameters: a deployment-global route would have to be marked+ * unscoped, which would shut session-restricted keys out of a feature they need in order to send.+ */+@ApiTags('media')+@Controller('sessions/:sessionId/media')+export class MediaController {+ constructor(private readonly mediaConversion: MediaConversionService) {}++ @Get('convert')+ @ApiOperation({ summary: 'Whether server-side media conversion is available' })+ @ApiResponse({+ status: 200,+ description:+ 'Reports whether conversion is switched on AND the ffmpeg binary can be run, so a client can ' ++ 'decide between converting here and converting before it sends.',+ })+ async conversionStatus(): Promise<{ available: boolean }> {+ return { available: await this.mediaConversion.isAvailable() };+ }++ // 200, not 201: this creates no resource, it answers with a representation of what was sent.+ @Post('convert/voice')+ @HttpCode(HttpStatus.OK)+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Convert audio into a WhatsApp voice note (Ogg/Opus)' })+ @ApiResponse({+ status: 200,+ description:+ 'Converted bytes, ready to post to send-audio with ptt=true. WhatsApp only renders a playable ' ++ 'mic bubble for Ogg/Opus; other formats arrive as an audio file that will not play.',+ })+ @ApiResponse({ status: 400, description: 'Neither url nor base64 given, or ffmpeg refused the input.' })+ @ApiResponse({ status: 413, description: 'The supplied media is above the media size cap.' })+ @ApiResponse({ status: 503, description: 'Conversion is disabled, or the ffmpeg binary is not runnable.' })+ async convertVoice(@Body() dto: ConvertMediaDto) {+ return this.mediaConversion.convertToVoice(dto);+ }++ @Post('convert/video')+ @HttpCode(HttpStatus.OK)+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Convert video into a WhatsApp-compatible MP4' })+ @ApiResponse({+ status: 200,+ description:+ 'Converted bytes: baseline H.264 with AAC audio, long edge bounded at 1280, index moved to the ' ++ 'front so the recipient can start playing before the whole file arrives.',+ })+ @ApiResponse({ status: 400, description: 'Neither url nor base64 given, or ffmpeg refused the input.' })+ @ApiResponse({ status: 413, description: 'The supplied media is above the media size cap.' })+ @ApiResponse({ status: 503, description: 'Conversion is disabled, or the ffmpeg binary is not runnable.' })+ async convertVideo(@Body() dto: ConvertMediaDto) {+ return this.mediaConversion.convertToVideo(dto);+ }+}diff --git a/src/modules/media/media.module.ts b/src/modules/media/media.module.tsnew file mode 100644index 000000000..b3bcdf14d--- /dev/null+++ b/src/modules/media/media.module.ts@@ -0,0 +1,10 @@+import { Module } from '@nestjs/common';+import { MediaController } from './media.controller';+import { MediaConversionService } from './media-conversion.service';++@Module({+ controllers: [MediaController],+ providers: [MediaConversionService],+ exports: [MediaConversionService],+})+export class MediaModule {}