Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): accept only absolute http(s) media urls on every route
Yudhi Armyndharis0b390bfb88ff
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 8ff7c7e2c..4124dd93f 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2236,7 +2236,7 @@ Each `BulkMessageItemDto`: `{ chatId: string, type: 'text'|'image'|'video'|'audi`BulkMessageOptionsDto`: `{ delayBetweenMessages?: number (1000–60000, default 3000), randomizeDelay?: boolean (default true), stopOnError?: boolean (default false) }`.-Each item must carry what its `type` sends: a non-empty `chatId`, a non-empty `content.text` for `text`, and a `url` or `base64` under `content.<type>` for a media type. If any item does not, the request answers `400` and nothing is queued. The check runs again per item after `variables` and the `message:sending` gate, where a failure fails that item only.+Each item must carry what its `type` sends: a non-empty `chatId`, a non-empty `content.text` for `text`, and a `url` or `base64` under `content.<type>` for a media type. Without `base64`, the `url` must be an absolute http(s) URL; a `url` holding a placeholder is checked once `variables` fill it in. If any item does not, the request answers `400` and nothing is queued. The check runs again per item after `variables` and the `message:sending` gate, where a failure fails that item only.Each item's base64 media is checked against the media byte cap (`MEDIA_DOWNLOAD_MAX_BYTES`) twice: at batch creation, and again per item after `variables` and the `message:sending` plugin gate are applied. An item that outgrows the cap only after rendering fails individually (`failed` in `results`, with `message:failed` fired) instead of being sent. `totalMessages` in the response reflects the de-duplicated item count.diff --git a/src/common/media/media-url.spec.ts b/src/common/media/media-url.spec.tsnew file mode 100644index 000000000..20f7208d4--- /dev/null+++ b/src/common/media/media-url.spec.ts@@ -0,0 +1,33 @@+import { isMediaUrl } from './media-url';++// Both engines fetch only a string that starts with http(s):// and decode anything else as base64,+// so every other value must be refused before it reaches them.+describe('isMediaUrl', () => {+ it.each([+ 'example.com/a.jpg',+ 'ftp://example.com/a.jpg',+ 'file:///srv/a.jpg',+ 'mailto:[email protected]',+ 'http:example.com/a.jpg',+ 'https:cdn.example.com/a.jpg',+ 'https//cdn.example.com/a.jpg',+ 'https://',+ 'https://exa mple.com/a.jpg',+ '',+ 42,+ undefined,+ ])('refuses %p', value => {+ expect(isMediaUrl(value)).toBe(false);+ });++ it.each([+ 'https://example.com/a.jpg',+ 'HTTPS://EXAMPLE.COM/a.jpg',+ 'http://media-store/a.jpg',+ 'http://media_server:8080/a.jpg',+ 'https://cdn.example.com/my photo.jpg',+ `https://bucket.s3.amazonaws.com/k.jpg?X-Amz-Security-Token=${'a'.repeat(2100)}`,+ ])('accepts %s', value => {+ expect(isMediaUrl(value)).toBe(true);+ });+});diff --git a/src/common/media/media-url.ts b/src/common/media/media-url.tsnew file mode 100644index 000000000..6d11c6c34--- /dev/null+++ b/src/common/media/media-url.ts@@ -0,0 +1,34 @@+import { ValidateBy, ValidationArguments } from 'class-validator';++const HTTP_URL_PREFIX = /^https?:\/\//i;++export const MEDIA_URL_MESSAGE = 'url must be an absolute http(s) URL';++/**+ * The rule for a caller-supplied media URL. Both engines fetch only a string that starts with+ * `http://` or `https://` and decode anything else as base64, so that literal prefix is required. The+ * rest must parse as a WHATWG URL with a host, which is what the fetch accepts: a space in the path is+ * percent-encoded there, not refused. The host itself is left to the SSRF-guarded fetch, so a+ * single-label host named in SSRF_ALLOWED_HOSTS and a long presigned URL are fine.+ */+export const isMediaUrl = (value: unknown): boolean => {+ if (typeof value !== 'string' || !HTTP_URL_PREFIX.test(value)) return false;+ try {+ return new URL(value).hostname !== '';+ } catch {+ return false;+ }+};++/** {@link isMediaUrl} as a class-validator decorator; `ignoreWhen` skips the check for that object. */+export const IsMediaUrl = <T extends object>(+ options: { ignoreWhen?: (object: T) => boolean } = {},+): PropertyDecorator =>+ ValidateBy({+ name: 'isMediaUrl',+ validator: {+ validate: (value: unknown, args?: ValidationArguments) =>+ (args !== undefined && options.ignoreWhen?.(args.object as T) === true) || isMediaUrl(value),+ defaultMessage: () => MEDIA_URL_MESSAGE,+ },+ });diff --git a/src/modules/group/dto/group.dto.spec.ts b/src/modules/group/dto/group.dto.spec.tsindex 60ebc1bdc..97c75eb90 100644--- a/src/modules/group/dto/group.dto.spec.ts+++ b/src/modules/group/dto/group.dto.spec.ts@@ -9,6 +9,7 @@ import {JoinGroupDto,GroupSettingsDto,MembershipRequestActionDto,+ SetGroupPictureDto,GROUP_PARTICIPANTS_MAX,} from './group.dto';@@ -28,6 +29,19 @@ function instanceFor<T extends object>(cls: new () => T, payload: unknown): T {}describe('group DTO validation', () => {+ it('SetGroupPictureDto accepts only an absolute http(s) url, the only form the engines fetch', async () => {+ for (const url of ['example.com/a.jpg', 'ftp://example.com/a.jpg']) {+ expect((await errorsFor(SetGroupPictureDto, { url })).length).toBeGreaterThan(0);+ }+ for (const url of ['https://example.com/a.jpg', 'HTTPS://example.com/a.jpg', 'http://example.com/a.jpg']) {+ expect(await errorsFor(SetGroupPictureDto, { url })).toHaveLength(0);+ }+ expect(await errorsFor(SetGroupPictureDto, { url: 'example.com/a.jpg', base64: 'QUJD' })).toHaveLength(0);+ // A base64 that is only a data-URI prefix strips to nothing, so the url is what would be sent.+ const prefixOnly = { url: 'cdn/group.jpg', base64: 'data:image/jpeg;base64,', mimetype: 'image/jpeg' };+ expect((await errorsFor(SetGroupPictureDto, prefixOnly)).length).toBeGreaterThan(0);+ });+it('accepts a valid participants body (regression for #190)', async () => {const errors = await errorsFor(ParticipantsDto, { participants: ['[email protected]'] });expect(errors).toHaveLength(0);diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.tsindex e72711f3d..5f23bf457 100644--- a/src/modules/group/dto/group.dto.ts+++ b/src/modules/group/dto/group.dto.ts@@ -11,12 +11,13 @@ import {IsInt,Min,IsOptional,- IsUrl,Matches,ValidateIf,} from 'class-validator';import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';import type { GroupMemberAddMode } from '../../../engine/interfaces/whatsapp-engine.interface';+import { IsMediaUrl } from '../../../common/media/media-url';+import { stripBase64DataUri } from '../../message/media-cap.util';// Field caps shared with the agent-tool input schemas (src/core/agent-tools/tools/group.tools.ts)// so MCP and REST enforce the same limits on the equivalent operations.@@ -126,8 +127,9 @@ export class JoinGroupDto {export class SetGroupPictureDto {@ApiPropertyOptional({ description: 'Image URL (http/https)', example: 'https://example.com/group.jpg' })@IsOptional()- @IsUrl()- @ValidateIf((o: SetGroupPictureDto) => !o.base64)+ // base64 wins when it holds data; a base64 that is only a data-URI prefix strips to nothing, and then+ // the url is what gets sent, so it is checked.+ @IsMediaUrl<SetGroupPictureDto>({ ignoreWhen: o => !!stripBase64DataUri(o.base64) })url?: string;@ApiPropertyOptional({ description: 'Base64 encoded image data' })diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex 9d2aa7fa3..789736399 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -399,6 +399,50 @@ describe('BulkMessageService.processBatch', () => {expect(finalPartial.results[0].status).not.toBe(BatchMessageStatus.FAILED);});+ // The engines fetch only http(s) URLs and decode any other string as base64, so a media url is+ // checked for its scheme; after rendering, because `variables` may supply the whole URL.+ const imageBatch = (url: string, variables?: Record<string, string>): MessageBatch => ({+ ...makeBatch(1),+ messages: [{ chatId: '[email protected]', type: 'image', content: { image: { url } }, variables }],+ });++ it('sends a rendered media url whose variable holds a space', async () => {+ repo.findOne.mockResolvedValue(imageBatch('https://cdn.example.com/{{name}}.jpg', { name: 'John Doe' }));++ await runProcessBatch();++ expect(engine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'https://cdn.example.com/John Doe.jpg' }),+ );+ });++ it('sends a media url that variables fill in whole', async () => {+ repo.findOne.mockResolvedValue(imageBatch('{{imageUrl}}', { imageUrl: 'https://cdn.example.com/a.jpg' }));++ await runProcessBatch();++ expect(engine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'https://cdn.example.com/a.jpg' }),+ );+ });++ it.each([+ ['a rendered ftp url', '{{u}}', { u: 'ftp://example.com/a.jpg' }],+ ['an unfilled placeholder', '{{u}}', undefined],+ ['a scheme-less url', 'example.com/a.jpg', undefined],+ ])('fails an item with %s instead of sending it', async (_label, url, variables) => {+ repo.findOne.mockResolvedValue(imageBatch(url, variables));++ await runProcessBatch();++ expect(engine.sendImageMessage).not.toHaveBeenCalled();+ const finalPartial = (repo.update.mock.calls as Array<[unknown, { results: BatchMessageResult[] }]>).at(-1)![1];+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);+ expect(finalPartial.results[0].error?.message).toMatch(/absolute http\(s\) URL/);+ });+it('fails an item whose rendered text exceeds the cap instead of sending it', async () => {// Comfortably over the 64 KiB default the un-configured service falls back to.const huge = 'x'.repeat(70 * 1024);@@ -1112,6 +1156,17 @@ describe('BulkMessageService.createBatch base64 media cap', () => {}});+ it('refuses a non-http(s) media url at batch creation but lets a templated one through', async () => {+ const create = (url: string) =>+ service.createBatch('s1', {+ messages: [{ chatId: '[email protected]', type: 'image' as const, content: { image: { url } } }],+ });++ await expect(create('ftp://example.com/a.jpg')).rejects.toThrow(/absolute http\(s\) URL/);+ expect(repo.save).not.toHaveBeenCalled();+ await expect(create('https://{{host}}/a.jpg')).resolves.toBeDefined();+ });+it('reserves the cap before awaiting persistence so concurrent creates cannot overshoot it', async () => {const previous = process.env.BULK_MAX_CONCURRENT_BATCHES;process.env.BULK_MAX_CONCURRENT_BATCHES = '1';diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex b9baed476..6df246895 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -19,6 +19,7 @@ import {BatchMessageResult,} from './entities/message-batch.entity';import { SendBulkMessageDto } from './dto/bulk-message.dto';+import { isMediaUrl } from '../../common/media/media-url';import { MessageStatus } from './entities/message.entity';import { EngineRegistry } from '../../engine/engine-registry.service';import { MessageService, DEFAULT_TEMPLATE_RENDER_MAX_CHARS } from './message.service';@@ -215,7 +216,7 @@ export class BulkMessageService implements OnApplicationBootstrap {// message:sending gate are applied (see executeBatch).for (const { type, content } of messages) {this.assertContentMediaWithinCap(content);- this.assertItemContent(type, content);+ this.assertItemContent(type, content, true);}const batchId = dto.batchId || `batch_${randomUUID().split('-')[0]}`;@@ -644,7 +645,7 @@ export class BulkMessageService implements OnApplicationBootstrap {* the matching media key otherwise. The DTO cannot express this per type, so it runs at batch* creation (a 400) and again per item after variables and the message:sending gate.*/- private assertItemContent(type: string, content: BulkMessageContent): void {+ private assertItemContent(type: string, content: BulkMessageContent, beforeRender = false): void {if (type === 'text') {if (typeof content?.text !== 'string' || !content.text) {throw new BadRequestException('A text item requires a non-empty content.text');@@ -652,9 +653,16 @@ export class BulkMessageService implements OnApplicationBootstrap {return;}const media = content?.[type as 'image' | 'video' | 'audio' | 'document'];- if (!stripBase64DataUri(media?.base64) && !media?.url) {+ if (stripBase64DataUri(media?.base64)) return;+ if (!media?.url) {throw new BadRequestException(`A ${type} item requires content.${type}.url or content.${type}.base64`);}+ // Checked here rather than on the DTO because `variables` may supply the whole URL: before+ // rendering, a value holding a placeholder is left to the per-item check, which sees the rendered+ // (and plugin-rewritten) URL.+ if (!(beforeRender && typeof media.url === 'string' && media.url.includes('{')) && !isMediaUrl(media.url)) {+ throw new BadRequestException(`content.${type}.url must be an absolute http(s) URL`);+ }}/**diff --git a/src/modules/message/dto/bulk-message.dto.spec.ts b/src/modules/message/dto/bulk-message.dto.spec.tsindex 9044fddad..0cb1acc15 100644--- a/src/modules/message/dto/bulk-message.dto.spec.ts+++ b/src/modules/message/dto/bulk-message.dto.spec.ts@@ -51,3 +51,16 @@ describe('SendBulkMessageDto recipient', () => {expect(errors.length).toBeGreaterThan(0);});});++// The url scheme is checked by the service after `variables` are applied, because a placeholder may+// stand for the whole URL; the DTO only requires a string.+describe('SendBulkMessageDto media url', () => {+ it('leaves a templated url to the per-item check', async () => {+ expect(await validateBulk(imageItem({ url: '{{imageUrl}}' }))).toHaveLength(0);+ expect(await validateBulk(imageItem({ url: 'https://{{host}}/a.jpg' }))).toHaveLength(0);+ });++ it('rejects a non-string url even next to base64', async () => {+ expect((await validateBulk(imageItem({ base64: 'AAAA', url: 123 }))).length).toBeGreaterThan(0);+ });+});diff --git a/src/modules/message/dto/send-message.dto.spec.ts b/src/modules/message/dto/send-message.dto.spec.tsindex a84f4a6ac..141ade98d 100644--- a/src/modules/message/dto/send-message.dto.spec.ts+++ b/src/modules/message/dto/send-message.dto.spec.ts@@ -224,3 +224,30 @@ describe('SendMediaMessageDto mentions', () => {expect(errors).toHaveLength(0);});});++// Both engines fetch only a string that starts with http(s):// and decode anything else as base64,+// so any other url passed validation and then failed inside the engine.+describe('SendMediaMessageDto url', () => {+ it('accepts only an absolute http(s) url', async () => {+ for (const url of ['example.com/a.jpg', 'ftp://example.com/a.jpg']) {+ expect((await validateDto(SendMediaMessageDto, { chatId: '[email protected]', url })).length).toBeGreaterThan(0);+ }+ for (const url of ['https://example.com/a.jpg', 'HTTPS://example.com/a.jpg', 'http://media_server:8080/a.jpg']) {+ expect(await validateDto(SendMediaMessageDto, { chatId: '[email protected]', url })).toHaveLength(0);+ }+ });++ it('ignores a stale url next to base64', async () => {+ expect(await validateDto(SendMediaMessageDto, { chatId: '[email protected]', base64: 'AAAA', url: 'junk' })).toHaveLength(0);+ });++ it('checks the url when base64 is only a data-URI prefix, since the url is then what gets sent', async () => {+ const errors = await validateDto(SendMediaMessageDto, {+ chatId: '[email protected]',+ base64: 'data:image/jpeg;base64,',+ mimetype: 'image/jpeg',+ url: 'cdn/banner.jpg',+ });+ expect(errors.map(e => e.property)).toContain('url');+ });+});diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex 357e319a6..a3e52ff2c 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -5,7 +5,6 @@ import {IsNotEmpty,IsOptional,MaxLength,- IsUrl,ValidateIf,IsArray,ArrayMaxSize,@@ -15,6 +14,8 @@ import {import { Type } from 'class-transformer';import { IsMentionWidConstraint } from './is-mention-wid.validator';import { ToStrictBoolean } from '../../../common/utils/strict-boolean';+import { IsMediaUrl } from '../../../common/media/media-url';+import { stripBase64DataUri } from '../media-cap.util';export const MENTIONS_DESCRIPTION ='WIDs to @mention (e.g. ["[email protected]"]). The text/caption must also contain the @<number> token.';@@ -193,8 +194,9 @@ export class SendMediaMessageDto {example: 'https://example.com/image.jpg',})@IsOptional()- @IsUrl()- @ValidateIf((o: SendMediaMessageDto) => !o.base64)+ // base64 wins when it holds data, so a url next to it is not fetched and not checked; a base64 that+ // is only a data-URI prefix strips to nothing, and then the url is what gets sent.+ @IsMediaUrl<SendMediaMessageDto>({ ignoreWhen: o => !!stripBase64DataUri(o.base64) })url?: string;@ApiPropertyOptional({diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex 1bbb2696e..6355cbcd4 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -1191,6 +1191,22 @@ describe('MessageSendService', () => {// ── buildMediaInput (via sendImage) ───────────────────────────────describe('buildMediaInput validation', () => {+ // A plugin send and a message:sending rewrite never pass the DTO, and both engines decode anything+ // that is not an http(s) URL as base64.+ it('refuses a url that is not absolute http(s), including one a hook rewrote', async () => {+ await expect(service.sendImage('sess-1', { chatId: '[email protected]', url: '/files/x.png' })).rejects.toThrow(+ 'url must be an absolute http(s) URL',+ );+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: { sessionId: 'sess-1', type: 'image', input: { chatId: '[email protected]', url: 's3://bucket/key' } },+ });+ await expect(service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg' })).rejects.toThrow(+ 'url must be an absolute http(s) URL',+ );+ expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();+ });+it('should throw when neither url nor base64 is provided', async () => {await expect(service.sendImage('sess-1', { chatId: '[email protected]' })).rejects.toThrow('Either url or base64 must be provided',diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex 3cd8dea32..e04865cbf 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -18,6 +18,7 @@ import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/secuimport { resolveFeatureFlags } from '../../config/feature-flags';import { isUniqueViolation } from '../../common/utils/db-errors';import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';+import { isMediaUrl, MEDIA_URL_MESSAGE } from '../../common/media/media-url';/** Default cap on a rendered template's final text; overridable via TEMPLATE_RENDER_MAX_CHARS. */export const DEFAULT_TEMPLATE_RENDER_MAX_CHARS = 64 * 1024;@@ -827,6 +828,11 @@ export class MessageSendService {if (!dto.url && !base64) {throw new BadRequestException('Either url or base64 must be provided');}+ // The DTO checks this too, but a plugin send and a message:sending rewrite reach here without it,+ // and both engines decode anything that is not an http(s) URL as base64.+ if (!base64 && !isMediaUrl(dto.url)) {+ throw new BadRequestException(MEDIA_URL_MESSAGE);+ }if (base64 && !dto.mimetype) {throw new BadRequestException('mimetype is required when using base64 data');@@ -840,8 +846,8 @@ export class MessageSendService {mimetype: dto.mimetype || 'application/octet-stream',// base64 wins over url when both are present: it is the explicit local payload, and a stale// `url` (e.g. a Swagger/example default left in the body) must not be fetched in its place.- // Aligns the send selection with the base64-first persisted metadata and the url field's- // `@ValidateIf((o) => !o.base64)` (which skips @IsUrl when base64 is present) — #670.+ // Aligns the send selection with the base64-first persisted metadata and the url field's check,+ // which is skipped only when base64 holds data after its data-URI prefix is stripped (#670).data: base64 || dto.url!,filename: dto.filename,caption: dto.caption,diff --git a/src/modules/profile/dto/profile.dto.spec.ts b/src/modules/profile/dto/profile.dto.spec.tsindex 96d790bd3..e861d4dfd 100644--- a/src/modules/profile/dto/profile.dto.spec.ts+++ b/src/modules/profile/dto/profile.dto.spec.ts@@ -35,6 +35,19 @@ describe('profile DTO validation', () => {expect(await errorsFor(SetProfilePictureDto, { url: 'not-a-url', base64: 'QUJD' })).toHaveLength(0);});+ it('accepts only an absolute http(s) url, the only form the engines fetch', async () => {+ for (const url of ['example.com/a.jpg', 'ftp://example.com/a.jpg']) {+ expect((await errorsFor(SetProfilePictureDto, { url })).length).toBeGreaterThan(0);+ }+ for (const url of ['https://example.com/a.jpg', 'HTTPS://example.com/a.jpg', 'http://example.com/a.jpg']) {+ expect(await errorsFor(SetProfilePictureDto, { url })).toHaveLength(0);+ }+ expect(await errorsFor(SetProfilePictureDto, { url: 'example.com/a.jpg', base64: 'QUJD' })).toHaveLength(0);+ // A base64 that is only a data-URI prefix strips to nothing, so the url is what would be sent.+ const prefixOnly = { url: 'cdn/avatar.jpg', base64: 'data:image/jpeg;base64,', mimetype: 'image/jpeg' };+ expect((await errorsFor(SetProfilePictureDto, prefixOnly)).length).toBeGreaterThan(0);+ });+it('rejects a non-image mimetype fast (400) — a profile picture is an image by definition', async () => {expect((await errorsFor(SetProfilePictureDto, { base64: 'QUJD', mimetype: 'application/pdf' })).length,diff --git a/src/modules/profile/dto/profile.dto.ts b/src/modules/profile/dto/profile.dto.tsindex 3e0cf296c..a13c56a56 100644--- a/src/modules/profile/dto/profile.dto.ts+++ b/src/modules/profile/dto/profile.dto.ts@@ -1,5 +1,7 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { IsString, IsNotEmpty, MaxLength, IsOptional, IsUrl, Matches, ValidateIf } from 'class-validator';+import { IsString, IsNotEmpty, MaxLength, IsOptional, Matches, ValidateIf } from 'class-validator';+import { IsMediaUrl } from '../../../common/media/media-url';+import { stripBase64DataUri } from '../../message/media-cap.util';export class SetProfileNameDto {@ApiProperty({ description: 'New display name (WhatsApp limit: 25 characters)', maxLength: 25 })@@ -29,8 +31,9 @@ export class SetProfilePictureDto {example: 'https://example.com/avatar.jpg',})@IsOptional()- @IsUrl()- @ValidateIf((o: SetProfilePictureDto) => !o.base64)+ // base64 wins when it holds data; a base64 that is only a data-URI prefix strips to nothing, and then+ // the url is what gets sent, so it is checked.+ @IsMediaUrl<SetProfilePictureDto>({ ignoreWhen: o => !!stripBase64DataUri(o.base64) })url?: string;@ApiPropertyOptional({diff --git a/src/modules/status/dto/send-media-status.dto.spec.ts b/src/modules/status/dto/send-media-status.dto.spec.tsindex c1d3e36b3..79538a0df 100644--- a/src/modules/status/dto/send-media-status.dto.spec.ts+++ b/src/modules/status/dto/send-media-status.dto.spec.ts@@ -96,3 +96,33 @@ describe('SendVideoStatusDto recipients validation', () => {expect(errors).toHaveLength(0);});});++// Both engines fetch only a string that starts with http(s):// and decode anything else as base64.+describe('status media url', () => {+ it('accepts only an absolute http(s) url', async () => {+ for (const url of ['example.com/a.jpg', 'ftp://example.com/a.jpg']) {+ const errors = await validate(plainToInstance(SendImageStatusDto, { image: { url } }));+ expect(errors.some(e => e.property === 'image')).toBe(true);+ }+ for (const url of [+ 'https://example.com/a.jpg',+ 'HTTPS://example.com/a.jpg',+ 'http://media-store/a.jpg',+ 'http://media_server:8080/a.jpg',+ `https://bucket.s3.amazonaws.com/k.mp4?X-Amz-Security-Token=${'a'.repeat(2100)}`,+ ]) {+ expect(await validate(plainToInstance(SendVideoStatusDto, { video: { url } }))).toHaveLength(0);+ }+ });++ it('ignores a url sent next to base64, which wins', async () => {+ const both = { image: { base64: 'AAAA', mimetype: 'image/jpeg', url: 'cdn/banner.jpg' } };+ expect(await validate(plainToInstance(SendImageStatusDto, both))).toHaveLength(0);+ const alone = await validate(plainToInstance(SendImageStatusDto, { image: { url: 'cdn/banner.jpg' } }));+ expect(alone.some(e => e.property === 'image')).toBe(true);+ // A base64 that is only a data-URI prefix strips to nothing, so the url is what would be sent.+ const emptyBase64 = { image: { base64: 'data:image/jpeg;base64,', mimetype: 'image/jpeg', url: 'cdn/banner.jpg' } };+ const refused = await validate(plainToInstance(SendImageStatusDto, emptyBase64));+ expect(refused.some(e => e.property === 'image')).toBe(true);+ });+});diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.tsindex 773a720f1..43db21e38 100644--- a/src/modules/status/dto/send-media-status.dto.ts+++ b/src/modules/status/dto/send-media-status.dto.ts@@ -12,6 +12,8 @@ import {} from 'class-validator';import { Type } from 'class-transformer';import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { IsMediaUrl } from '../../../common/media/media-url';+import { stripBase64DataUri } from '../../message/media-cap.util';class StatusMediaInput {@ApiPropertyOptional({@@ -21,6 +23,9 @@ class StatusMediaInput {@ValidateIf((media: StatusMediaInput) => media.base64 === undefined || media.url !== undefined)@IsString()@IsNotEmpty()+ // base64 wins when both are sent, so a url next to it is not fetched and not checked; a base64 that is+ // only a data-URI prefix strips to nothing, and then the url is what gets sent.+ @IsMediaUrl<StatusMediaInput>({ ignoreWhen: media => !!stripBase64DataUri(media.base64) })url?: string;@ApiPropertyOptional({diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.tsindex 87841627c..ac691cee0 100644--- a/src/modules/status/status.service.spec.ts+++ b/src/modules/status/status.service.spec.ts@@ -187,6 +187,23 @@ describe('StatusService media validation and selection', () => {expect(engine.postVideoStatus).toHaveBeenCalledWith(expect.objectContaining({ data: 'QUJD' }), expect.anything());});+ it('refuses media that is neither an http(s) URL nor base64, including a message:sending rewrite', async () => {+ for (const media of [{ url: 'cdn/banner.jpg' }, { url: 'ftp://host/a.jpg' }, { base64: 'data:image/png,AAAA' }]) {+ await expect(service.postImageStatus('s1', media, { recipients: ['[email protected]'] })).rejects.toThrow(+ 'media must be an absolute http(s) URL or base64',+ );+ }+ hookManager.execute.mockImplementationOnce((_event: string, data: unknown) => {+ const gated = data as { input: object };+ const media = { mimetype: 'image/jpeg', data: 'cdn/banner.jpg' };+ return Promise.resolve({ continue: true, data: { ...gated, input: { ...gated.input, media } } });+ });+ await expect(+ service.postImageStatus('s1', { url: 'https://example.com/banner.jpg' }, { recipients: ['[email protected]'] }),+ ).rejects.toThrow('media must be an absolute http(s) URL or base64');+ expect(engine.postImageStatus).not.toHaveBeenCalled();+ });+describe('voice status', () => {// Ogg/Opus is the only thing WhatsApp plays as a status voice note, and neither engine// transcodes — so the default has to be that, not a generic audio type.diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.tsindex ff3b07dca..c29752c5e 100644--- a/src/modules/status/status.service.ts+++ b/src/modules/status/status.service.ts@@ -6,6 +6,7 @@ import type { Status, StatusResult, StatusPostOptions } from '../../engine/interimport { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';import { HookManager, applySendingGate } from '../../core/hooks';import { SendPacingService, countsTowardSendBreaker } from '../message/send-pacing.service';+import { isMediaUrl } from '../../common/media/media-url';/** 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@@ -19,6 +20,8 @@ import { SendPacingService, countsTowardSendBreaker } from '../message/send-paciconst SAFE_STATUS_MIMETYPE = /^(image|video|audio)\//;const SCRIPTABLE_SVG_MIMETYPE = /^image\/svg\+xml\s*(;|$)/;+const BASE64_TEXT = /^[A-Za-z0-9+/_\-\s]*=*\s*$/;+@Injectable()export class StatusService {// HookManager comes from the @Global() HooksModule, StorageService from the @Global()@@ -49,9 +52,9 @@ export class StatusService {/*** Re-apply the media guards to whatever the gate returned. A plugin may rewrite `media.data`, and- * a rewritten payload has to clear the same data-URI and size checks as the original — this is+ * a rewritten payload has to clear the same data-URI, url and size checks as the original — this is* what the chat path gets for free by gating first and calling buildMediaInput afterwards- * (`message.service.ts`). Here the guards run before the gate too, so a plugin cannot use a+ * (`message.service.ts`). Here the size guard runs before the gate too, so a plugin cannot use a* rewrite to slip past `MEDIA_DOWNLOAD_MAX_BYTES`.*/private guardGatedMedia(media: { mimetype: string; data: string }): { mimetype: string; data: string } {@@ -59,6 +62,12 @@ export class StatusService {// field. Both helpers are safe over either form: stripping a data-URI prefix leaves a URL// untouched, and the decoded-byte cap on a URL-length string is trivially satisfied.const data = stripBase64DataUri(media.data) ?? media.data;+ // Both engines fetch only an http(s) URL and decode anything else as base64, so a value with another+ // scheme, or with a character base64 does not use (a path with an extension), would be posted as+ // noise. A path made only of base64 characters cannot be told apart from base64 and is sent as such.+ if (!isMediaUrl(data) && !BASE64_TEXT.test(data)) {+ throw new BadRequestException('media must be an absolute http(s) URL or base64');+ }assertBase64WithinMediaCap(data);return { mimetype: media.mimetype, data };}