Repository navigation
feat(baileys): accept a custom link preview card in sendText - #2793
patrickreisx wants to merge 1 commit into
Conversation
linkPreview in sendText is a boolean: the preview always comes from the page of the link. Let it also be an object with the card to show (title, description and a picture as thumbnailUrl or thumbnailBase64), for pages that have no Open Graph tags or block crawlers, or when the sender wants its own picture. The object is handed to Baileys as the preview info of the message and the picture is uploaded as a high quality link thumbnail. The boolean values behave as before.
Reviewer's GuideData structuresAdd the public
APIExtend the send-text validation schema to accept either the existing boolean or a custom card object with a required title.
ImplementationBuild and upload a custom link preview card, then route custom-card requests through it instead of page-derived preview generation.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 7 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="2446" />
<code_context>
+ if (card.thumbnailBase64) {
+ image = Buffer.from(card.thumbnailBase64.replace(/^data:[^;]+;base64,/, ''), 'base64');
+ } else if (card.thumbnailUrl) {
+ const response = await axios.get(card.thumbnailUrl, {
+ responseType: 'arraybuffer',
+ timeout: 10000,
</code_context>
<issue_to_address>
**Thumbnail URLs expose internal resources**
When an authenticated caller supplies a thumbnail URL targeting an internal or private-network resource, directly or through a redirect, `axios.get` follows the caller-supplied URL without restricting private destinations, so the server fetches internal resources and can send returned image bytes to a recipient chosen by the caller.
Reject private or internal destinations and validate every redirect before fetching the thumbnail.
Also at `src/validate/message.schema.ts:84`.
</issue_to_address>
### Comment 2
<location path="src/validate/message.schema.ts" line_range="85" />
<code_context>
+ title: { type: 'string', minLength: 1 },
+ description: { type: 'string' },
+ thumbnailUrl: { type: 'string' },
+ thumbnailBase64: { type: 'string' },
+ canonicalUrl: { type: 'string' },
+ },
</code_context>
<issue_to_address>
**Large thumbnails exhaust server memory**
When a caller submits a very large base64 thumbnail, especially alongside concurrent sends, `Buffer.from` decodes the entire value, then `prepareWAMessageMedia` processes and uploads the buffer without a size limit, consuming substantial memory and CPU until the service becomes unresponsive or runs out of memory.
Enforce a maximum decoded thumbnail size before media preparation and reject oversized inputs.
Also at `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2443-2445`.
</issue_to_address>
### Comment 3
<location path="src/validate/message.schema.ts" line_range="74-91" />
<code_context>
number: { ...numberDefinition },
text: { type: 'string' },
- linkPreview: { type: 'boolean' },
+ linkPreview: {
+ description:
+ 'true/false to enable/disable the link preview, or an object with the card to show instead of the page',
+ oneOf: [
+ { type: 'boolean' },
+ {
+ type: 'object',
+ properties: {
+ title: { type: 'string', minLength: 1 },
+ description: { type: 'string' },
+ thumbnailUrl: { type: 'string' },
+ thumbnailBase64: { type: 'string' },
+ canonicalUrl: { type: 'string' },
+ },
+ required: ['title'],
+ additionalProperties: false,
+ },
+ ],
+ },
delay: {
</code_context>
<issue_to_address>
**Non-Baileys callers get different previews**
When a caller sends an object-valued `linkPreview` to a Business API, Meta, Cloud API, or Evolution instance, `BusinessStartupService` converts the object to a boolean and sends a page preview, while Evolution does not use the card fields, so callers receive a different preview or no custom card.
Support custom-card fields in these integrations or reject object-valued `linkPreview` for providers that do not support them.
Also at `src/api/dto/sendMessage.dto.ts:22`, `src/api/dto/sendMessage.dto.ts:56`.
</issue_to_address>
### Comment 4
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="2694" />
<code_context>
let previewContext: any = undefined;
- if (linkPreview !== false && (message as any)?.conversation) {
+ if (customCard && (message as any)?.conversation) {
+ linkPreview = await this.buildCustomLinkPreview(customCard, (message as any).conversation);
+ } else if (linkPreview !== false && (message as any)?.conversation) {
previewContext = await this.generateLinkPreview((message as any).conversation);
</code_context>
<issue_to_address>
**Custom-card messages arrive out of order**
When two sendText requests for the same recipient are in flight and the earlier request's custom thumbnail takes longer to prepare, the request waits for `buildCustomLinkPreview` to fetch and upload its thumbnail before calling `sendMessage`; a later request to the same recipient can send during that wait and reach WhatsApp first, reversing the callers’ send order.
Serialize outbound sends per recipient in request-arrival order, including thumbnail preparation.
</issue_to_address>
### Comment 5
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="2446" />
<code_context>
+ if (card.thumbnailBase64) {
+ image = Buffer.from(card.thumbnailBase64.replace(/^data:[^;]+;base64,/, ''), 'base64');
+ } else if (card.thumbnailUrl) {
+ const response = await axios.get(card.thumbnailUrl, {
+ responseType: 'arraybuffer',
+ timeout: 10000,
</code_context>
<issue_to_address>
**Proxy-required thumbnails lose their image**
When the instance requires its configured proxy to reach the thumbnail host, `buildCustomLinkPreview` fetches `thumbnailUrl` with plain Axios instead of the configured proxy, so the request fails and the sent card has no picture.
Use the instance's configured proxy agent for the thumbnail request.
</issue_to_address>
### Comment 6
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="2431" />
<code_context>
+ * page of the link. Baileys uses an object in `linkPreview` as the preview info of the message.
+ */
+ private async buildCustomLinkPreview(card: LinkPreviewCard, text: string) {
+ const url = text.match(/https?:\/\/[^\s]+/)?.[0]?.replace(/[.,);\]]+$/u, '');
+ if (!url) return undefined;
+
</code_context>
<issue_to_address>
**Uppercase URLs lose custom cards**
When the text contains a valid URL whose scheme is uppercase, such as `HTTPS://example.com`, `buildCustomLinkPreview` does not match the URL, returns `undefined`, and the message is sent without the supplied card. The later page-preview branch is skipped for this custom-card request.
Match the scheme case-insensitively when extracting the URL.
</issue_to_address>
### Comment 7
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="2443-2446" />
<code_context>
+
+ try {
+ let image: Buffer | undefined;
+ if (card.thumbnailBase64) {
+ image = Buffer.from(card.thumbnailBase64.replace(/^data:[^;]+;base64,/, ''), 'base64');
+ } else if (card.thumbnailUrl) {
+ const response = await axios.get(card.thumbnailUrl, {
+ responseType: 'arraybuffer',
+ timeout: 10000,
</code_context>
<issue_to_address>
**Conflicting thumbnails are accepted**
When a card supplies both `thumbnailBase64` and `thumbnailUrl`, both thumbnail fields can pass validation, but `buildCustomLinkPreview` always uses `thumbnailBase64` and skips `thumbnailUrl`; callers that supply both can see a different image from the URL they expected to take effect.
Make the schema require at most one thumbnail source, or explicitly document and validate a precedence rule.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 7 findings to address first, and a supplied thumbnailUrl is fetched by the service without restricting its destination, so a caller may reach internal endpoints and potentially expose their responses through a WhatsApp preview. Reverting stops future fetches, but cannot retract content already disclosed.
Blocking findings: src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2446, src/validate/message.schema.ts:85, src/validate/message.schema.ts:91, src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2694, src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2446, and 2 more
| if (card.thumbnailBase64) { | ||
| image = Buffer.from(card.thumbnailBase64.replace(/^data:[^;]+;base64,/, ''), 'base64'); | ||
| } else if (card.thumbnailUrl) { | ||
| const response = await axios.get(card.thumbnailUrl, { |
There was a problem hiding this comment.
🔴 Critical · Thumbnail URLs expose internal resources
When an authenticated caller supplies a thumbnail URL targeting an internal or private-network resource, directly or through a redirect, axios.get follows the caller-supplied URL without restricting private destinations, so the server fetches internal resources and can send returned image bytes to a recipient chosen by the caller.
Reject private or internal destinations and validate every redirect before fetching the thumbnail.
Also at src/validate/message.schema.ts:84.
Prompt for AI agents
In `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts` at line 2446:
**Thumbnail URLs expose internal resources**
When an authenticated caller supplies a thumbnail URL targeting an internal or private-network resource, directly or through a redirect, `axios.get` follows the caller-supplied URL without restricting private destinations, so the server fetches internal resources and can send returned image bytes to a recipient chosen by the caller.
Reject private or internal destinations and validate every redirect before fetching the thumbnail.
Also at `src/validate/message.schema.ts:84`.From .cursor/rules/project-context.mdc L86:
- **SECURITY**: Use secure defaults and proper encryption| title: { type: 'string', minLength: 1 }, | ||
| description: { type: 'string' }, | ||
| thumbnailUrl: { type: 'string' }, | ||
| thumbnailBase64: { type: 'string' }, |
There was a problem hiding this comment.
🟡 Medium · Large thumbnails exhaust server memory
When a caller submits a very large base64 thumbnail, especially alongside concurrent sends, Buffer.from decodes the entire value, then prepareWAMessageMedia processes and uploads the buffer without a size limit, consuming substantial memory and CPU until the service becomes unresponsive or runs out of memory.
Enforce a maximum decoded thumbnail size before media preparation and reject oversized inputs.
Also at src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2443-2445.
Prompt for AI agents
In `src/validate/message.schema.ts` at line 85:
**Large thumbnails exhaust server memory**
When a caller submits a very large base64 thumbnail, especially alongside concurrent sends, `Buffer.from` decodes the entire value, then `prepareWAMessageMedia` processes and uploads the buffer without a size limit, consuming substantial memory and CPU until the service becomes unresponsive or runs out of memory.
Enforce a maximum decoded thumbnail size before media preparation and reject oversized inputs.
Also at `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2443-2445`.| linkPreview: { | ||
| description: | ||
| 'true/false to enable/disable the link preview, or an object with the card to show instead of the page', | ||
| oneOf: [ | ||
| { type: 'boolean' }, | ||
| { | ||
| type: 'object', | ||
| properties: { | ||
| title: { type: 'string', minLength: 1 }, | ||
| description: { type: 'string' }, | ||
| thumbnailUrl: { type: 'string' }, | ||
| thumbnailBase64: { type: 'string' }, | ||
| canonicalUrl: { type: 'string' }, | ||
| }, | ||
| required: ['title'], | ||
| additionalProperties: false, | ||
| }, | ||
| ], |
There was a problem hiding this comment.
🟠 High · Non-Baileys callers get different previews
When a caller sends an object-valued linkPreview to a Business API, Meta, Cloud API, or Evolution instance, BusinessStartupService converts the object to a boolean and sends a page preview, while Evolution does not use the card fields, so callers receive a different preview or no custom card.
Support custom-card fields in these integrations or reject object-valued linkPreview for providers that do not support them.
Also at src/api/dto/sendMessage.dto.ts:22, src/api/dto/sendMessage.dto.ts:56.
Prompt for AI agents
In `src/validate/message.schema.ts` at lines 74-91:
**Non-Baileys callers get different previews**
When a caller sends an object-valued `linkPreview` to a Business API, Meta, Cloud API, or Evolution instance, `BusinessStartupService` converts the object to a boolean and sends a page preview, while Evolution does not use the card fields, so callers receive a different preview or no custom card.
Support custom-card fields in these integrations or reject object-valued `linkPreview` for providers that do not support them.
Also at `src/api/dto/sendMessage.dto.ts:22`, `src/api/dto/sendMessage.dto.ts:56`.From .cursor/rules/specialized-rules/dto-rules.mdc L142-147:
export class SendTextDto extends Metadata {
text: string;
linkPreview?: boolean;
mentionsEveryOne?: boolean;
mentioned?: string[];
}| let previewContext: any = undefined; | ||
| if (linkPreview !== false && (message as any)?.conversation) { | ||
| if (customCard && (message as any)?.conversation) { | ||
| linkPreview = await this.buildCustomLinkPreview(customCard, (message as any).conversation); |
There was a problem hiding this comment.
🟡 Medium · Custom-card messages arrive out of order
When two sendText requests for the same recipient are in flight and the earlier request's custom thumbnail takes longer to prepare, the request waits for buildCustomLinkPreview to fetch and upload its thumbnail before calling sendMessage; a later request to the same recipient can send during that wait and reach WhatsApp first, reversing the callers’ send order.
Serialize outbound sends per recipient in request-arrival order, including thumbnail preparation.
Prompt for AI agents
In `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts` at line 2694:
**Custom-card messages arrive out of order**
When two sendText requests for the same recipient are in flight and the earlier request's custom thumbnail takes longer to prepare, the request waits for `buildCustomLinkPreview` to fetch and upload its thumbnail before calling `sendMessage`; a later request to the same recipient can send during that wait and reach WhatsApp first, reversing the callers’ send order.
Serialize outbound sends per recipient in request-arrival order, including thumbnail preparation.| if (card.thumbnailBase64) { | ||
| image = Buffer.from(card.thumbnailBase64.replace(/^data:[^;]+;base64,/, ''), 'base64'); | ||
| } else if (card.thumbnailUrl) { | ||
| const response = await axios.get(card.thumbnailUrl, { |
There was a problem hiding this comment.
🟡 Medium · Proxy-required thumbnails lose their image
When the instance requires its configured proxy to reach the thumbnail host, buildCustomLinkPreview fetches thumbnailUrl with plain Axios instead of the configured proxy, so the request fails and the sent card has no picture.
Use the instance's configured proxy agent for the thumbnail request.
Prompt for AI agents
In `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts` at line 2446:
**Proxy-required thumbnails lose their image**
When the instance requires its configured proxy to reach the thumbnail host, `buildCustomLinkPreview` fetches `thumbnailUrl` with plain Axios instead of the configured proxy, so the request fails and the sent card has no picture.
Use the instance's configured proxy agent for the thumbnail request.| * page of the link. Baileys uses an object in `linkPreview` as the preview info of the message. | ||
| */ | ||
| private async buildCustomLinkPreview(card: LinkPreviewCard, text: string) { | ||
| const url = text.match(/https?:\/\/[^\s]+/)?.[0]?.replace(/[.,);\]]+$/u, ''); |
There was a problem hiding this comment.
🟡 Medium · Uppercase URLs lose custom cards
When the text contains a valid URL whose scheme is uppercase, such as HTTPS://example.com, buildCustomLinkPreview does not match the URL, returns undefined, and the message is sent without the supplied card. The later page-preview branch is skipped for this custom-card request.
Match the scheme case-insensitively when extracting the URL.
Prompt for AI agents
In `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts` at line 2431:
**Uppercase URLs lose custom cards**
When the text contains a valid URL whose scheme is uppercase, such as `HTTPS://example.com`, `buildCustomLinkPreview` does not match the URL, returns `undefined`, and the message is sent without the supplied card. The later page-preview branch is skipped for this custom-card request.
Match the scheme case-insensitively when extracting the URL.| if (card.thumbnailBase64) { | ||
| image = Buffer.from(card.thumbnailBase64.replace(/^data:[^;]+;base64,/, ''), 'base64'); | ||
| } else if (card.thumbnailUrl) { | ||
| const response = await axios.get(card.thumbnailUrl, { |
There was a problem hiding this comment.
🟡 Medium · Conflicting thumbnails are accepted
When a card supplies both thumbnailBase64 and thumbnailUrl, both thumbnail fields can pass validation, but buildCustomLinkPreview always uses thumbnailBase64 and skips thumbnailUrl; callers that supply both can see a different image from the URL they expected to take effect.
Make the schema require at most one thumbnail source, or explicitly document and validate a precedence rule.
Prompt for AI agents
In `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts` at lines 2443-2446:
**Conflicting thumbnails are accepted**
When a card supplies both `thumbnailBase64` and `thumbnailUrl`, both thumbnail fields can pass validation, but `buildCustomLinkPreview` always uses `thumbnailBase64` and skips `thumbnailUrl`; callers that supply both can see a different image from the URL they expected to take effect.
Make the schema require at most one thumbnail source, or explicitly document and validate a precedence rule.
📋 Description
Today
linkPreviewinPOST /message/sendText/{instance}is a boolean: the preview always comes from the page of the link (title, description and image read from its Open Graph tags). This PR letslinkPreviewalso be an object with the card to show instead:{ "number": "5511999999999", "text": "Deal of the day https://example.com/p/1", "linkPreview": { "title": "Product name | R$ 29,90", "description": "Optional description", "thumbnailBase64": "<jpeg or png, base64>" } }thumbnailUrlcan be used instead ofthumbnailBase64, andcanonicalUrlis optional (it defaults to the first link of the text).When is it useful?
How it works:
true,falseand no value behave exactly as before.BaileysStartupServicehands it to Baileys as the preview info of the message (Baileys already uses an object inmessage.linkPreviewas is, instead of fetching the page) and uploads the picture as a high quality link thumbnail, with the sameprepareWAMessageMedia(..., { mediaTypeOverride: 'thumbnail-link' })call Baileys makes for the preview it builds itself.generateLinkPreview/externalAdReply) is not used for that message.Notes for reviewers:
thumbnailUrlis fetched by the server (10 s timeout, 5 MB cap). That is the same level of trust as themediaURLssendMediaalready accepts; this PR adds no extra restriction, but I am happy to add one (for example onlythumbnailBase64).🔗 Related Issue
Related to #2262 and #2792. Not a
Closes.🧪 Type of Change
🧪 Testing
What I did
npm run build(tsc --noEmit && tsup) on this branch: passes. ESLint (with the project's Prettier rules) on the three changed files: no errors.sendTextschema with 8 payloads (nolinkPreview,true,false, a full card, a card with only a title, and the rejected ones: card without title, unknown field, a string): all as expected.buildCustomLinkPreviewof this branch (throughtsx, with Baileys7.0.0-rc13and a stub for the upload) for: picture as base64, picture as URL (from a local server), no picture, text without a link, and an unreachable picture URL. The first two return a title, the link as matched text, a JPEG thumbnail and a 1200x630 high quality thumbnail; the others behave as described above.7.0.0-rc.9), through an equivalent change on that version that hands the same object tomessage.linkPreview. The card was delivered and showed my picture and title instead of the page's, next to a normal preview of the same link.What I did not do
Run a
developinstance and send a message through this exact code: 2.4.0 returns HTTP 503 until the instance is license-activated, which I did not do. So the end-to-end path on 2.4.0 (including the real upload fromdevelop) is not verified.There is no automated test suite for this area, so I did not add tests.
Manual testing completed
Functionality verified in development environment
No breaking changes introduced
Tested with different connection types (if applicable)
📸 Screenshots (if applicable)
Not applicable.
✅ Checklist
📝 Additional Notes
The contributing guide asks for features to be discussed in an issue first. I am opening this as a draft to make the proposal concrete; I am happy to move the discussion to an issue, change the shape of the API (field names, only base64, per-instance opt-in), or close it if this is not wanted. The API docs live in a separate repository, so no documentation is changed here. No real affiliate links or personal data are included.
Summary by Sourcery
Enable custom link preview cards for text messages while maintaining the existing automatic preview options.
New Features:
Enhancements: