Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(messages): generate link previews safely, and accept caller-supplied ones

Yudhi Armyndharisa403d6ca305a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 39ee06bc8..981fd05f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Link previews on Baileys, generated safely — and `customLinkPreview` for supplying your own.**
+
+ Baileys produced no previews at all before this. Its own generator delegates to `link-preview-js`,
+ an optional peer this project does not install, so every message containing a URL quietly attempted
+ to load it, threw, and was swallowed with a warning.
+
+ Installing that package was the obvious fix and is the wrong one: it carries an **unfixed** SSRF
+ advisory ([GHSA-4gp8-rjrq-ch6q](https://github.com/advisories/GHSA-4gp8-rjrq-ch6q), CWE-918 — "IPv6
+ and internal loopback attacks", no patched release), and the URL being fetched comes from message
+ text, so an attacker chooses the destination. Guarding in front of it would still leave a
+ DNS-rebinding window, because the package re-resolves when it fetches.
+
+ So the gateway generates previews itself, through the SSRF guard it already uses elsewhere — which
+ validates the destination **and pins the connection to the vetted address**. No new dependency, no
+ code under advisory, and `WEBHOOK_SSRF_PROTECT` / `SSRF_ALLOWED_HOSTS` govern it like every other
+ outbound fetch. Non-http schemes never reach the fetch layer, non-document responses are not read,
+ the body is size-capped, and any failure yields no preview rather than a failed send.
+
+ `customLinkPreview` (`{ url, title, description? }`) attaches a preview you supply, fetching
+ nothing — so it works for URLs this server cannot reach. Baileys only: whatsapp-web.js takes a
+ boolean and has nowhere to put a title, so it answers `501` rather than silently sending a message
+ that looks nothing like what was asked for. Combining it with `linkPreview: false` is a `400`.
+
- **`linkPreview` on `send-text`**, in all five SDKs and the MCP tool. Sending `false` suppresses the
URL preview on both engines.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 22384015f..4a69e9310 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1302,6 +1302,7 @@ Send a plain text message.
| text | string | Yes | non-empty, max 4096 | Message text |
| mentions | string[] | No | array of WIDs | WIDs to @mention (e.g. `["[email protected]"]`). See **Mentions** below |
| linkPreview | boolean | No | — | `false` suppresses the URL preview. See **Link previews** below |
+| customLinkPreview | object | No | `{ url, title, description? }` | Attach a preview you supply. **Baileys only.** See **Link previews** below |
```json
{ "chatId": "[email protected]", "text": "Hello from OpenWA!" }
@@ -1318,11 +1319,23 @@ the two engines genuinely differ:
| | whatsapp-web.js | Baileys |
| --- | --- | --- |
| `linkPreview: false` | no preview | no preview |
-| unset / `true` | asks WhatsApp Web to build a preview in-page | **no preview** — its generator is an optional package this gateway does not install |
-
-So `true` does not force a preview onto Baileys; it only declines to suppress one. Sending `false` on
-Baileys additionally skips a generator call that currently fails and is swallowed with a warning on
-every message containing a URL.
+| unset / `true` | asks WhatsApp Web to build a preview in-page | the gateway fetches the page itself and builds one |
+| `customLinkPreview` | `501` — the library takes a boolean only, with no way to pass a title | preview attached verbatim, nothing fetched |
+
+**How Baileys previews are generated.** Not with the library's own generator. That one delegates to
+`link-preview-js`, which carries an unfixed SSRF advisory
+([GHSA-4gp8-rjrq-ch6q](https://github.com/advisories/GHSA-4gp8-rjrq-ch6q), CWE-918 — "IPv6 and
+internal loopback attacks", no patched release). Since the URL comes from message text, an attacker
+influences what this server fetches, so the gateway supplies its own generator instead: it fetches
+through the same SSRF guard used elsewhere, which validates the destination **and pins the
+connection to the vetted address**, closing the DNS-rebinding window a validate-then-delegate
+approach would leave open. `WEBHOOK_SSRF_PROTECT` and `SSRF_ALLOWED_HOSTS` apply, so a deployment
+that intentionally allows an internal host keeps that behaviour. A refused, slow or broken site
+yields no preview — never a failed send.
+
+`customLinkPreview` fetches **nothing at all**, so it works for URLs this server cannot reach, and it
+cannot be combined with `linkPreview: false` — that asks for the opposite, and the request is
+rejected with `400` rather than guessing which half was meant.
> whatsapp-web.js's own documentation notes the flag "has no effect on multi-device accounts". Its
> code does act on the flag, but that caveat is upstream's and is repeated here rather than
diff --git a/openapi.json b/openapi.json
index c41844ba9..674250c91 100644
--- a/openapi.json
+++ b/openapi.json
@@ -7759,6 +7759,32 @@
}
}
},
+ "CustomLinkPreviewDto": {
+ "type": "object",
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "The URL as it appears in the message text — WhatsApp anchors the preview to it.",
+ "example": "https://example.com/launch"
+ },
+ "title": {
+ "type": "string",
+ "description": "Required: WhatsApp will not render a preview without a title.",
+ "example": "We just launched",
+ "maxLength": 256
+ },
+ "description": {
+ "type": "string",
+ "description": "Preview description",
+ "example": "Read the announcement.",
+ "maxLength": 1024
+ }
+ },
+ "required": [
+ "url",
+ "title"
+ ]
+ },
"SendTextMessageDto": {
"type": "object",
"properties": {
@@ -7787,6 +7813,14 @@
"type": "boolean",
"description": "Set `false` to suppress the URL preview. Guaranteed only in that direction: leaving it unset means whatever the engine does by default, and the engines differ — whatsapp-web.js asks WhatsApp Web to build a preview, while Baileys builds none unless its optional preview generator is installed. Sending `true` therefore does not force a preview on Baileys.",
"example": false
+ },
+ "customLinkPreview": {
+ "description": "Attach a preview you supply yourself, instead of one fetched from the URL. Nothing is fetched for these, so a preview can be attached even for a URL this server cannot reach. **Baileys only** — whatsapp-web.js takes a boolean and answers `501`. Cannot be combined with `linkPreview: false`, which asks for the opposite.",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomLinkPreviewDto"
+ }
+ ]
}
},
"required": [
diff --git a/sdk/go/types_message.go b/sdk/go/types_message.go
index c1cdf1dde..669f3009c 100644
--- a/sdk/go/types_message.go
+++ b/sdk/go/types_message.go
@@ -19,6 +19,10 @@ type SendTextRequest struct {
// means the engine default, and the engines differ — whatsapp-web.js asks WhatsApp Web to build a
// preview, Baileys builds none unless its optional generator is installed.
LinkPreview *bool `json:"linkPreview,omitempty"`
+ // CustomLinkPreview attaches a preview you supply instead of one fetched from the URL. Nothing is
+ // fetched, so it works even for a URL the gateway cannot reach. Baileys only — whatsapp-web.js
+ // takes a boolean and answers 501. Cannot be combined with LinkPreview=false.
+ CustomLinkPreview *CustomLinkPreview `json:"customLinkPreview,omitempty"`
}
// SendMediaRequest sends image/video/document/sticker media. Provide exactly
diff --git a/sdk/go/types_session.go b/sdk/go/types_session.go
index 18a745352..0e616ef0d 100644
--- a/sdk/go/types_session.go
+++ b/sdk/go/types_session.go
@@ -39,6 +39,14 @@ type MuteChannelRequest struct {
Mute bool `json:"mute"`
}
+// CustomLinkPreview is a caller-supplied link preview. Nothing is fetched for these.
+type CustomLinkPreview struct {
+ URL string `json:"url"`
+ // Title is required — WhatsApp will not render a preview without one.
+ Title string `json:"title"`
+ Description string `json:"description,omitempty"`
+}
+
// UpsertLabelRequest is a label create-or-update body. The id travels in the path, because WhatsApp
// keys the write on it.
type UpsertLabelRequest struct {
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/CustomLinkPreview.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/CustomLinkPreview.java
new file mode 100644
index 000000000..b48d2e35f
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/CustomLinkPreview.java
@@ -0,0 +1,11 @@
+package com.rmyndharis.openwa.model;
+
+/**
+ * A caller-supplied link preview, used instead of one fetched from the URL.
+ *
+ * <p>Nothing is fetched for these, so a preview can be attached even for a URL the gateway cannot
+ * reach. Baileys only — whatsapp-web.js takes a boolean and answers {@code 501}.
+ *
+ * @param title required — WhatsApp will not render a preview without one
+ */
+public record CustomLinkPreview(String url, String title, String description) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextRequest.java
index 080176fd7..693336642 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextRequest.java
@@ -3,15 +3,16 @@ package com.rmyndharis.openwa.model;
import java.util.List;
/** Request body for sending a text message. */
-public record SendTextRequest(String chatId, String text, List<String> mentions, Boolean linkPreview) {
+public record SendTextRequest(
+ String chatId, String text, List<String> mentions, Boolean linkPreview, CustomLinkPreview customLinkPreview) {
/** Back-compatible constructor without mentions. */
public SendTextRequest(String chatId, String text) {
- this(chatId, text, null, null);
+ this(chatId, text, null, null, null);
}
/** Back-compatible constructor without a link-preview choice. */
public SendTextRequest(String chatId, String text, List<String> mentions) {
- this(chatId, text, mentions, null);
+ this(chatId, text, mentions, null, null);
}
public static Builder builder() {
@@ -23,6 +24,7 @@ public record SendTextRequest(String chatId, String text, List<String> mentions,
private String text;
private List<String> mentions;
private Boolean linkPreview;
+ private CustomLinkPreview customLinkPreview;
public Builder chatId(String v) {
this.chatId = v;
@@ -51,8 +53,17 @@ public record SendTextRequest(String chatId, String text, List<String> mentions,
return this;
}
+ /**
+ * Attach a preview you supply instead of one fetched from the URL. Baileys only; cannot be
+ * combined with {@code linkPreview(false)}.
+ */
+ public Builder customLinkPreview(CustomLinkPreview v) {
+ this.customLinkPreview = v;
+ return this;
+ }
+
public SendTextRequest build() {
- return new SendTextRequest(chatId, text, mentions, linkPreview);
+ return new SendTextRequest(chatId, text, mentions, linkPreview, customLinkPreview);
}
}
}
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 483a9ec92..f31138186 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -194,6 +194,12 @@ export interface SendTextRequest {
* Baileys builds none unless its optional generator is installed.
*/
linkPreview?: boolean;
+ /**
+ * Attach a preview you supply yourself instead of one fetched from the URL. Nothing is fetched, so
+ * this works even for a URL the gateway cannot reach. **Baileys only** — whatsapp-web.js takes a
+ * boolean and answers 501. Cannot be combined with `linkPreview: false`.
+ */
+ customLinkPreview?: { url: string; title: string; description?: string };
}
export interface SendMediaRequest {
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index 2134859c8..81db22b79 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -103,6 +103,15 @@ class GroupJoinInfo(TypedDict, total=False):
participantCount: int
+class CustomLinkPreview(TypedDict, total=False):
+ """A caller-supplied link preview. Nothing is fetched for these."""
+
+ url: str
+ # Required -- WhatsApp will not render a preview without a title.
+ title: str
+ description: str
+
+
# ── Session ───────────────────────────────────────────────────────
@@ -196,6 +205,10 @@ class SendTextRequest(TypedDict, total=False):
# engine default, and the engines differ -- whatsapp-web.js asks WhatsApp Web to build a preview,
# Baileys builds none unless its optional generator is installed.
linkPreview: bool
+ # Attach a preview you supply yourself instead of one fetched from the URL. Nothing is fetched,
+ # so this works even for a URL the gateway cannot reach. Baileys only -- whatsapp-web.js takes a
+ # boolean and answers 501. Cannot be combined with linkPreview=False.
+ customLinkPreview: CustomLinkPreview
class SendMediaRequest(TypedDict, total=False):
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index 34f3bdf6c..ba01cfaa1 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -1,6 +1,8 @@
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';
+import { generateSafeLinkPreview } from './safe-link-preview';
import {
+ CustomLinkPreview,
ChatState,
ContactCard,
EngineEventCallbacks,
@@ -81,11 +83,18 @@ export class BaileysMessaging {
chatId: string,
text: string,
mentions?: string[],
- sendOptions?: { linkPreview?: boolean },
+ sendOptions?: { linkPreview?: boolean; customPreview?: CustomLinkPreview },
): Promise<MessageResult> {
this.host.ensureReady();
const jid = await this.toDeliverableJid(chatId);
- const options = this.withEphemeral(jid);
+ // Baileys spreads the caller's options LAST (messages-send.js:1086), so `getUrlInfo` here
+ // replaces its hardcoded one — which delegates to a package carrying an unfixed SSRF advisory
+ // (see safe-link-preview.ts). Passed on every text send so that generator is never reachable,
+ // not only when a preview was asked for.
+ const options = {
+ ...(this.withEphemeral(jid) ?? {}),
+ getUrlInfo: (text: string) => generateSafeLinkPreview(text),
+ };
// `linkPreview: null` is Baileys' explicit "no preview": with the key absent it instead calls the
// configured generator (Utils/messages.js:279-281). Suppressing therefore also skips that call —
// which today fails anyway, since the generator dynamically imports an optional package this
@@ -94,10 +103,20 @@ export class BaileysMessaging {
text,
...this.withMentions(mentions),
...(sendOptions?.linkPreview === false ? { linkPreview: null } : {}),
+ // A caller-supplied preview short-circuits generation entirely: with the key present Baileys
+ // never calls getUrlInfo, so nothing is fetched and the metadata is used verbatim.
+ ...(sendOptions?.customPreview
+ ? {
+ linkPreview: {
+ 'matched-text': sendOptions.customPreview.url,
+ 'canonical-url': sendOptions.customPreview.url,
+ title: sendOptions.customPreview.title,
+ ...(sendOptions.customPreview.description ? { description: sendOptions.customPreview.description } : {}),
+ },
+ }
+ : {}),
};
- const sent = options
- ? await this.sock().sendMessage(jid, content, options)
- : await this.sock().sendMessage(jid, content);
+ const sent = await this.sock().sendMessage(jid, content, options);
if (sent) {
void this.host.putStoredMessage(sent)?.catch(err =>
this.host.logger.warn('Failed to persist sent message to store', {
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index ab2596088..96689ff8b 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -169,6 +169,15 @@ const newAdapter = (): BaileysAdapter =>
const noopCallbacks = (over: Partial<EngineEventCallbacks> = {}): EngineEventCallbacks => over;
+/**
+ * Every text send now carries send-options, because that is how the SSRF-safe preview generator
+ * replaces the library's own (see safe-link-preview.ts). Matching on the shape rather than
+ * `expect.anything()` keeps the assertion honest: the options object disappearing would mean
+ * Baileys' vulnerable generator became reachable again.
+ */
+const safeSendOptions = (): unknown =>
+ expect.objectContaining({ getUrlInfo: expect.any(Function) as unknown }) as unknown;
+
function firstEditedMessage(callback: jest.Mock): EditedMessage {
const calls = callback.mock.calls as Array<[EditedMessage]>;
const first = calls[0];
@@ -1166,7 +1175,7 @@ describe('BaileysAdapter messaging', () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
const adapter = await readyAdapter();
const res = await adapter.sendTextMessage('[email protected]', 'hello');
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'hello' });
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'hello' }, safeSendOptions());
expect(res).toEqual({ id: 'OUT1', timestamp: 1700000001 });
});
@@ -1205,7 +1214,7 @@ describe('BaileysAdapter messaging', () => {
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'hello');
expect(fakeSock.signalRepository.lidMapping.getLIDForPN).toHaveBeenCalledWith('[email protected]');
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('484848@lid', { text: 'hello' });
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('484848@lid', { text: 'hello' }, safeSendOptions());
});
it('sendTextMessage keeps the phone jid when no LID mapping is known', async () => {
@@ -1213,7 +1222,7 @@ describe('BaileysAdapter messaging', () => {
fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue(null) } };
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'hello');
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'hello' });
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'hello' }, safeSendOptions());
});
it('sendTextMessage honors the chat disappearing timer when one is cached (#473)', async () => {
@@ -1224,7 +1233,8 @@ describe('BaileysAdapter messaging', () => {
expect(fakeSock.sendMessage).toHaveBeenCalledWith(
{ text: 'hello' },
- { ephemeralExpiration: 604800 },
+ // The disappearing timer still rides on the same options object the generator now shares.
+ expect.objectContaining({ ephemeralExpiration: 604800, getUrlInfo: expect.any(Function) as unknown }) as unknown,
);
});
@@ -1232,17 +1242,18 @@ describe('BaileysAdapter messaging', () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'hi @62811', ['[email protected]']);
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {
- text: 'hi @62811',
- mentions: ['[email protected]'],
- });
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(
+ { text: 'hi @62811', mentions: ['[email protected]'] },
+ safeSendOptions(),
+ );
});
it('sendTextMessage omits the mentions key when none are given (no behavior change)', async () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'plain', []);
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'plain' });
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'plain' }, safeSendOptions());
});
it('getNumberId resolves via onWhatsApp and returns a NEUTRAL jid (never @s.whatsapp.net)', async () => {
@@ -4650,3 +4661,50 @@ describe('BaileysAdapter link preview', () => {
expect(sentContent()).not.toHaveProperty('linkPreview');
});
});
+
+// A caller-supplied preview short-circuits generation: with the key present Baileys never calls
+// getUrlInfo, so nothing is fetched and a preview can be attached for a URL this server cannot reach.
+describe('BaileysAdapter custom link preview', () => {
+ beforeEach(() => {
+ fakeSock.user = undefined;
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ });
+
+ const readyAdapter = async () => {
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({}));
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+ fakeSock.fire('connection.update', { connection: 'open' });
+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'M1' }, messageTimestamp: 1 });
+ return adapter;
+ };
+
+ const sentContent = (): Record<string, unknown> =>
+ (fakeSock.sendMessage.mock.calls[0] as [string, Record<string, unknown>])[1];
+
+ it('maps the supplied metadata into the shape WhatsApp expects', async () => {
+ const adapter = await readyAdapter();
+
+ await adapter.sendTextMessage('[email protected]', 'see https://example.com', undefined, {
+ customPreview: { url: 'https://example.com', title: 'Example', description: 'A site' },
+ });
+
+ expect(sentContent().linkPreview).toEqual({
+ 'matched-text': 'https://example.com',
+ 'canonical-url': 'https://example.com',
+ title: 'Example',
+ description: 'A site',
+ });
+ });
+
+ it('omits a description that was not supplied', async () => {
+ const adapter = await readyAdapter();
+
+ await adapter.sendTextMessage('[email protected]', 'x', undefined, {
+ customPreview: { url: 'https://example.com', title: 'Example' },
+ });
+
+ expect(sentContent().linkPreview).not.toHaveProperty('description');
+ });
+});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 98a0d6ce8..a1d936028 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -25,6 +25,7 @@ import {
IncomingMessage,
IWhatsAppEngine,
Label,
+ CustomLinkPreview,
GroupJoinInfo,
LabelInput,
LocationInput,
@@ -285,7 +286,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
chatId: string,
text: string,
mentions?: string[],
- options?: { linkPreview?: boolean },
+ options?: { linkPreview?: boolean; customPreview?: CustomLinkPreview },
): Promise<MessageResult> {
return this.messaging.sendTextMessage(chatId, text, mentions, options);
}
diff --git a/src/engine/adapters/safe-link-preview.spec.ts b/src/engine/adapters/safe-link-preview.spec.ts
new file mode 100644
index 000000000..66e3b7e43
--- /dev/null
+++ b/src/engine/adapters/safe-link-preview.spec.ts
@@ -0,0 +1,174 @@
+import { generateSafeLinkPreview } from './safe-link-preview';
+import * as ssrfGuard from '../../common/security/ssrf-guard';
+
+/**
+ * This generator exists because the library's own delegates to a package with an unfixed SSRF
+ * advisory, and its input is attacker-influenced — a URL pasted into a message makes this server
+ * fetch it. So the tests that matter most are not about parsing: they are that nothing is fetched
+ * outside the guard, that non-http schemes never reach the fetch layer at all, and that a hostile or
+ * broken response can never turn into a failed send.
+ */
+describe('generateSafeLinkPreview', () => {
+ let withSafeFetch: jest.SpyInstance;
+
+ /** Stand in for the guard, handing the callback a response with the given body/headers. */
+ const respondWith = (body: string, contentType = 'text/html', ok = true): void => {
+ withSafeFetch = jest.spyOn(ssrfGuard, 'withSafeFetch').mockImplementation((_url, _init, use) =>
+ Promise.resolve(
+ use({
+ ok,
+ headers: { get: (name: string) => (name === 'content-type' ? contentType : null) },
+ body: null,
+ text: () => Promise.resolve(body),
+ } as never),
+ ),
+ );
+ };
+
+ afterEach(() => jest.restoreAllMocks());
+
+ describe('the fetch never escapes the guard', () => {
+ it('goes through withSafeFetch, not a bare fetch', async () => {
+ respondWith('<title>Example</title>');
+
+ await generateSafeLinkPreview('https://example.com/a');
+
+ expect(withSafeFetch).toHaveBeenCalledTimes(1);
+ expect((withSafeFetch.mock.calls[0] as unknown[])[0]).toBe('https://example.com/a');
+ });
+
+ // The guard rejects a blocked destination by throwing. That must surface as "no preview", never
+ // as a failed send — and never as a leaked internal address in an error message.
+ it('returns nothing when the guard refuses the destination', async () => {
+ jest
+ .spyOn(ssrfGuard, 'withSafeFetch')
+ .mockRejectedValue(new ssrfGuard.SsrfBlockedError('blocked 169.254.169.254'));
+
+ await expect(generateSafeLinkPreview('http://169.254.169.254/latest/meta-data')).resolves.toBeUndefined();
+ });
+
+ // Non-http schemes are the shapes an attacker reaches for, and the fetch layer should never be
+ // asked about them at all.
+ it.each(['file:///etc/passwd', 'ftp://internal/secrets', 'javascript:alert(1)', 'data:text/html,x'])(
+ 'refuses %s without fetching',
+ async raw => {
+ const spy = jest.spyOn(ssrfGuard, 'withSafeFetch');
+
+ await expect(generateSafeLinkPreview(raw)).resolves.toBeUndefined();
+
+ expect(spy).not.toHaveBeenCalled();
+ },
+ );
+
+ it('does not fetch an unparseable URL', async () => {
+ const spy = jest.spyOn(ssrfGuard, 'withSafeFetch');
+
+ await expect(generateSafeLinkPreview('http://[not a host]')).resolves.toBeUndefined();
+
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ // A bare host is what people actually paste, and treating it as https is what a reader does.
+ it('adds https to a scheme-less URL rather than refusing it', async () => {
+ respondWith('<title>Example</title>');
+
+ await generateSafeLinkPreview('example.com/path');
+
+ expect((withSafeFetch.mock.calls[0] as unknown[])[0]).toBe('https://example.com/path');
+ });
+ });
+
+ describe('what it extracts', () => {
+ it('prefers Open Graph metadata', async () => {
+ respondWith(
+ `<html><head><title>Fallback</title>
+ <meta property="og:title" content="Real title">
+ <meta property="og:description" content="Real description"></head></html>`,
+ );
+
+ await expect(generateSafeLinkPreview('https://example.com')).resolves.toEqual({
+ 'matched-text': 'https://example.com',
+ 'canonical-url': 'https://example.com/',
+ title: 'Real title',
+ description: 'Real description',
+ });
+ });
+
+ it('falls back to the document title', async () => {
+ respondWith('<html><head><title>Just a title</title></head></html>');
+
+ await expect(generateSafeLinkPreview('https://example.com')).resolves.toMatchObject({
+ title: 'Just a title',
+ });
+ });
+
+ // matched-text is what WhatsApp anchors the preview to in the message body, so it must be the
+ // text that appeared there — not the normalised URL that was fetched.
+ it('keeps the matched text verbatim while reporting the normalised URL separately', async () => {
+ respondWith('<title>T</title>');
+
+ const info = await generateSafeLinkPreview('example.com');
+
+ expect(info?.['matched-text']).toBe('example.com');
+ expect(info?.['canonical-url']).toBe('https://example.com/');
+ });
+
+ // WhatsApp requires a title. The hostname is a fact about the URL rather than an invention.
+ it('uses the hostname when the page has a description but no title', async () => {
+ respondWith('<meta property="og:description" content="Only a description">');
+
+ await expect(generateSafeLinkPreview('https://news.example.com/a')).resolves.toMatchObject({
+ title: 'news.example.com',
+ description: 'Only a description',
+ });
+ });
+
+ it('decodes the entities that show up in real metadata', async () => {
+ respondWith('<meta property="og:title" content="Tom &amp; Jerry&#39;s &quot;show&quot;">');
+
+ await expect(generateSafeLinkPreview('https://example.com')).resolves.toMatchObject({
+ title: 'Tom & Jerry\'s "show"',
+ });
+ });
+
+ // Decoding the ampersand first would turn `&amp;lt;` into `<`.
+ it('does not double-decode', async () => {
+ respondWith('<meta property="og:title" content="&amp;lt;script&amp;gt;">');
+
+ await expect(generateSafeLinkPreview('https://example.com')).resolves.toMatchObject({
+ title: '&lt;script&gt;',
+ });
+ });
+ });
+
+ describe('when there is nothing worth showing', () => {
+ it('returns nothing for a page with neither title nor description', async () => {
+ respondWith('<html><body>no metadata here</body></html>');
+
+ await expect(generateSafeLinkPreview('https://example.com')).resolves.toBeUndefined();
+ });
+
+ // Reading a non-document means pulling an arbitrary binary into memory for no metadata.
+ it.each(['image/png', 'application/octet-stream', 'application/pdf'])(
+ 'returns nothing for a %s response',
+ async contentType => {
+ respondWith('<title>ignored</title>', contentType);
+
+ await expect(generateSafeLinkPreview('https://example.com')).resolves.toBeUndefined();
+ },
+ );
+
+ it('returns nothing for a non-ok response', async () => {
+ respondWith('<title>Not found</title>', 'text/html', false);
+
+ await expect(generateSafeLinkPreview('https://example.com')).resolves.toBeUndefined();
+ });
+
+ // A preview is decoration. A slow or broken site must never turn into a failed message send.
+ it('returns nothing when the fetch throws', async () => {
+ jest.spyOn(ssrfGuard, 'withSafeFetch').mockRejectedValue(new Error('socket hang up'));
+
+ await expect(generateSafeLinkPreview('https://example.com')).resolves.toBeUndefined();
+ });
+ });
+});
diff --git a/src/engine/adapters/safe-link-preview.ts b/src/engine/adapters/safe-link-preview.ts
new file mode 100644
index 000000000..48505799f
--- /dev/null
+++ b/src/engine/adapters/safe-link-preview.ts
@@ -0,0 +1,168 @@
+import type { Response } from 'undici';
+import { withSafeFetch } from '../../common/security/ssrf-guard';
+
+/**
+ * The link-preview payload WhatsApp accepts, in Baileys' own field names.
+ *
+ * `matched-text` is the URL as it appeared in the message: WhatsApp uses it to decide which part of
+ * the text to render as the preview's anchor, so it must be the text that was matched, not the
+ * normalised URL that was fetched.
+ */
+export interface SafeUrlInfo {
+ 'matched-text': string;
+ 'canonical-url': string;
+ /** Required by WhatsApp. Falls back to the hostname, which is a fact about the URL, not a guess. */
+ title: string;
+ description?: string;
+}
+
+/**
+ * Generate a link preview WITHOUT the library's own generator.
+ *
+ * Baileys ships one, but it delegates to `link-preview-js`, which carries an unfixed SSRF advisory
+ * (GHSA-4gp8-rjrq-ch6q — "IPv6 and internal loopback attacks", CWE-918, no patched release). The
+ * input here is attacker-influenced — a URL pasted into a message causes this server to make a
+ * request — so that generator is never reached: Baileys spreads the caller's send options last
+ * (messages-send.js:1086), so passing this as `getUrlInfo` there wins over its hardcoded one.
+ *
+ * `withSafeFetch` validates the destination and then PINS the connection to the vetted addresses, so
+ * a hostname that resolves publicly once and to `127.0.0.1` a moment later cannot be used to reach
+ * the loopback interface — the rebinding window that a validate-then-hand-off approach would leave
+ * open. It also honours the deployment's own `WEBHOOK_SSRF_PROTECT` / `SSRF_ALLOWED_HOSTS` settings,
+ * so an operator who intentionally allows an internal host keeps that behaviour here too.
+ *
+ * Returns undefined rather than throwing on any failure: a preview is decoration, and a site that is
+ * slow, unreachable, or refused must never turn into a failed message send.
+ */
+export async function generateSafeLinkPreview(
+ matchedText: string,
+ opts: { timeoutMs?: number; maxBytes?: number } = {},
+): Promise<SafeUrlInfo | undefined> {
+ const timeoutMs = opts.timeoutMs ?? 3000;
+ const maxBytes = opts.maxBytes ?? 512 * 1024;
+
+ const url = normaliseUrl(matchedText);
+ if (!url) return undefined;
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ return await withSafeFetch(
+ url,
+ {
+ signal: controller.signal,
+ // Only a document is useful here, and asking for it keeps a server from streaming back
+ // something enormous that would be read and discarded.
+ headers: { accept: 'text/html,application/xhtml+xml', 'user-agent': 'WhatsApp/2' },
+ },
+ async response => {
+ if (!response.ok) return undefined;
+ const type = response.headers.get('content-type') ?? '';
+ // Anything that is not markup has no metadata to read, and reading it would mean pulling an
+ // arbitrary binary into memory for nothing.
+ if (!type.includes('html') && !type.includes('xml')) return undefined;
+
+ const html = await readCapped(response, maxBytes);
+ const title = firstMatch(html, [
+ /<meta[^>]+property=["']og:title["'][^>]+content=["']([^"']*)["']/i,
+ /<meta[^>]+content=["']([^"']*)["'][^>]+property=["']og:title["']/i,
+ /<title[^>]*>([^<]*)<\/title>/i,
+ ]);
+ const description = firstMatch(html, [
+ /<meta[^>]+property=["']og:description["'][^>]+content=["']([^"']*)["']/i,
+ /<meta[^>]+content=["']([^"']*)["'][^>]+property=["']og:description["']/i,
+ /<meta[^>]+name=["']description["'][^>]+content=["']([^"']*)["']/i,
+ ]);
+
+ // A page with neither says nothing the raw link does not, so there is no point attaching a
+ // preview at all.
+ if (!title && !description) return undefined;
+
+ return {
+ 'matched-text': matchedText,
+ 'canonical-url': url,
+ // WhatsApp requires a title. When the page has none, the hostname is used — it is a fact
+ // about the URL rather than an invention, and it is what a reader would call the site.
+ title: title ? decodeEntities(title) : new URL(url).hostname,
+ ...(description ? { description: decodeEntities(description) } : {}),
+ };
+ },
+ );
+ } catch {
+ // Blocked destination, DNS failure, timeout, malformed response — all the same to a caller who
+ // just wants their message sent.
+ return undefined;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * Accept only http(s), and add a scheme to a bare `example.com` the way a reader would.
+ *
+ * Rejecting other schemes here matters: `file:`, `ftp:` and friends are not previewable and are the
+ * shapes an attacker reaches for, and the fetch layer should never be asked about them at all.
+ */
+function normaliseUrl(matchedText: string): string | undefined {
+ // Anything that ALREADY carries a scheme is judged on that scheme alone. Prefixing `https://` onto
+ // it instead would turn `file:///etc/passwd` into `https://file:///etc/passwd`, which parses
+ // happily as an https URL and would be handed to the fetch layer — a scheme filter that admits the
+ // very schemes it exists to exclude.
+ const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(matchedText);
+ if (hasScheme && !/^https?:\/\//i.test(matchedText)) return undefined;
+
+ try {
+ const parsed = new URL(hasScheme ? matchedText : `https://${matchedText}`);
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.toString() : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Read at most `maxBytes` of the body. A preview needs the `<head>`, which arrives first, so there is
+ * no reason to accept a multi-gigabyte response from a host chosen by a stranger.
+ */
+async function readCapped(response: Response, maxBytes: number): Promise<string> {
+ const reader = (response.body as ReadableStream<Uint8Array> | null)?.getReader();
+ if (!reader) return (await response.text()).slice(0, maxBytes);
+
+ const decoder = new TextDecoder();
+ let out = '';
+ let read = 0;
+ for (;;) {
+ const chunk = await reader.read();
+ if (chunk.done) break;
+ const value: Uint8Array = chunk.value;
+ read += value.byteLength;
+ out += decoder.decode(value, { stream: true });
+ if (read >= maxBytes) {
+ await reader.cancel();
+ break;
+ }
+ }
+ return out;
+}
+
+function firstMatch(html: string, patterns: RegExp[]): string | undefined {
+ for (const pattern of patterns) {
+ const value = pattern.exec(html)?.[1]?.trim();
+ if (value) return value;
+ }
+ return undefined;
+}
+
+/** The handful of entities that actually show up in title/description text. */
+function decodeEntities(value: string): string {
+ return (
+ value
+ .replace(/&quot;/g, '"')
+ .replace(/&#0?39;/g, "'")
+ .replace(/&apos;/g, "'")
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&nbsp;/g, ' ')
+ // Ampersand last: decoding it first would let `&amp;lt;` become `<`.
+ .replace(/&amp;/g, '&')
+ );
+}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 99d804061..19273ed35 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -5897,3 +5897,22 @@ describe('WhatsAppWebJsAdapter link preview', () => {
expect(sentOptions(sendMessage)).toEqual({ mentions: ['[email protected]'], linkPreview: false });
});
});
+
+// whatsapp-web.js takes a boolean only — there is no way to hand it a title or description. Silently
+// dropping the caller's preview would send a message that looks nothing like what they asked for.
+describe('WhatsAppWebJsAdapter custom link preview', () => {
+ it('refuses a caller-supplied preview rather than ignoring it', async () => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ const sendMessage = jest.fn();
+ (adapter as unknown as { client: unknown }).client = { sendMessage };
+
+ await expect(
+ adapter.sendTextMessage('[email protected]', 'hi', undefined, {
+ customPreview: { url: 'https://example.com', title: 'Example' },
+ }),
+ ).rejects.toThrow(/customPreview/);
+
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 6fb0d23d5..0d2906abf 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -41,6 +41,7 @@ import {
ChatState,
LabelInput,
GroupEvent,
+ CustomLinkPreview,
GroupJoinInfo,
IncomingCallEvent,
AccountRestriction,
@@ -1340,7 +1341,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
chatId: string,
text: string,
mentions?: string[],
- options?: { linkPreview?: boolean },
+ options?: { linkPreview?: boolean; customPreview?: CustomLinkPreview },
): Promise<MessageResult> {
return this.messaging.sendTextMessage(chatId, text, mentions, options);
}
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 50d204c0d..a44dd179e 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -1,5 +1,6 @@
import { MessageMedia, MessageTypes, type Client, type Message } from 'whatsapp-web.js';
import {
+ CustomLinkPreview,
IncomingMessage,
LocationInput,
ContactCard,
@@ -18,6 +19,7 @@ import { chatKind, userPart } from '../identity/wa-id';
import { chatHistoryMediaBudgetBytes, coerceDeclaredSize, ingestMediaBudgetBytes } from './inbound-media-cap';
import { buildIncomingMessageBase } from './message-mapper';
import { buildVCard } from './vcard';
+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { type WwebjsEngineHost } from './wwebjs-host';
/**
@@ -270,7 +272,7 @@ export class WwebjsMessaging {
chatId: string,
text: string,
mentions?: string[],
- options?: { linkPreview?: boolean },
+ options?: { linkPreview?: boolean; customPreview?: CustomLinkPreview },
): Promise<MessageResult> {
this.host.ensureReady();
// wwebjs accepts neutral `<phone>@c.us` WIDs directly as mentionedJidList, so no de-normalization
@@ -280,6 +282,12 @@ export class WwebjsMessaging {
// `linkPreview === false ? undefined : true` (Client.js:1458), so passing `true` is identical to
// passing nothing — sending it anyway would add an options object to every plain send for no
// change in behaviour.
+ // whatsapp-web.js takes a BOOLEAN only (index.d.ts:1547) — there is no way to hand it title,
+ // description or a thumbnail. Silently dropping the caller's preview would send a message that
+ // looks nothing like what they asked for, so it refuses instead.
+ if (options?.customPreview) {
+ throw new EngineNotSupportedError('sendTextMessage(customPreview)');
+ }
const sendOptions: { mentions?: string[]; linkPreview?: boolean } = {};
if (mentions?.length) sendOptions.mentions = mentions;
if (options?.linkPreview === false) sendOptions.linkPreview = false;
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 669e81a97..4c6cf5f17 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -259,6 +259,20 @@ export interface GroupJoinInfo {
participantCount?: number;
}
+/**
+ * A caller-supplied link preview, used instead of fetching one.
+ *
+ * Nothing is fetched for these: the caller states the metadata, so the gateway makes no outbound
+ * request at all — which also means a preview can be attached for a URL this server could not reach.
+ */
+export interface CustomLinkPreview {
+ /** The URL as it appears in the message text; WhatsApp anchors the preview to it. */
+ url: string;
+ /** Required — WhatsApp will not render a preview without one. */
+ title: string;
+ description?: string;
+}
+
export interface ContactCard {
name: string;
number: string;
@@ -786,7 +800,7 @@ export interface IWhatsAppEngine {
chatId: string,
text: string,
mentions?: string[],
- options?: { linkPreview?: boolean },
+ options?: { linkPreview?: boolean; customPreview?: CustomLinkPreview },
): Promise<MessageResult>;
sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult>;
sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult>;
diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.ts
index 313ee3db4..9ebdfbb55 100644
--- a/src/modules/message/dto/send-message.dto.ts
+++ b/src/modules/message/dto/send-message.dto.ts
@@ -1,5 +1,6 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
+ ValidateNested,
IsString,
IsNotEmpty,
IsOptional,
@@ -10,6 +11,7 @@ import {
ArrayMaxSize,
IsBoolean,
} from 'class-validator';
+import { Type } from 'class-transformer';
import { ToStrictBoolean } from '../../../common/utils/strict-boolean';
const MENTIONS_DESCRIPTION =
@@ -19,6 +21,33 @@ const MENTIONS_DESCRIPTION =
// (src/core/agent-tools/tools/message.tools.ts) so MCP and REST enforce the same limit.
export const MESSAGE_TEXT_MAX_LENGTH = 4096;
+export class CustomLinkPreviewDto {
+ @ApiProperty({
+ description: 'The URL as it appears in the message text — WhatsApp anchors the preview to it.',
+ example: 'https://example.com/launch',
+ })
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(2048)
+ url: string;
+
+ @ApiProperty({
+ description: 'Required: WhatsApp will not render a preview without a title.',
+ example: 'We just launched',
+ maxLength: 256,
+ })
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(256)
+ title: string;
+
+ @ApiPropertyOptional({ description: 'Preview description', example: 'Read the announcement.', maxLength: 1024 })
+ @IsOptional()
+ @IsString()
+ @MaxLength(1024)
+ description?: string;
+}
+
export class SendTextMessageDto {
@ApiProperty({
description: 'WhatsApp chat ID ([email protected] for individual, [email protected] for groups)',
@@ -60,6 +89,19 @@ export class SendTextMessageDto {
@IsOptional()
@IsBoolean()
linkPreview?: boolean;
+
+ @ApiPropertyOptional({
+ type: CustomLinkPreviewDto,
+ description:
+ 'Attach a preview you supply yourself, instead of one fetched from the URL. Nothing is ' +
+ 'fetched for these, so a preview can be attached even for a URL this server cannot reach. ' +
+ '**Baileys only** — whatsapp-web.js takes a boolean and answers `501`. Cannot be combined ' +
+ 'with `linkPreview: false`, which asks for the opposite.',
+ })
+ @IsOptional()
+ @ValidateNested()
+ @Type(() => CustomLinkPreviewDto)
+ customLinkPreview?: CustomLinkPreviewDto;
}
export class SendMediaMessageDto {
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 681ed6049..8fd32d7f3 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -200,6 +200,42 @@ describe('MessageService', () => {
expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi');
});
+ it('threads a caller-supplied preview through to the engine', async () => {
+ const input = {
+ chatId: '[email protected]',
+ text: 'see https://example.com',
+ customLinkPreview: { url: 'https://example.com', title: 'Example', description: 'A site' },
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({
+ continue: true,
+ data: { sessionId: 'sess-1', input, type: 'text' },
+ });
+
+ await service.sendText('sess-1', input);
+
+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(
+ 'see https://example.com',
+ undefined,
+ { customPreview: { url: 'https://example.com', title: 'Example', description: 'A site' } },
+ );
+ });
+
+ // Suppressing the preview and supplying one are opposite requests; guessing which was meant
+ // would send a message the caller did not ask for either way.
+ it('refuses a suppression combined with a supplied preview, before reaching the engine', async () => {
+ await expect(
+ service.sendText('sess-1', {
+ chatId: '[email protected]',
+ text: 'hi',
+ linkPreview: false,
+ customLinkPreview: { url: 'https://example.com', title: 'Example' },
+ }),
+ ).rejects.toBeInstanceOf(BadRequestException);
+
+ expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();
+ });
+
it('should save outgoing message as pending before sending, then update to sent', async () => {
await service.sendText('sess-1', {
chatId: '[email protected]',
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 3b977c81e..17fcb5be7 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -109,6 +109,11 @@ export class MessageService {
) {}
async sendText(sessionId: string, dto: SendTextMessageDto): Promise<MessageResponseDto> {
+ // Asking to suppress the preview AND to attach one is a contradiction, and guessing which half
+ // the caller meant would send a message they did not ask for either way.
+ if (dto.linkPreview === false && dto.customLinkPreview) {
+ throw new BadRequestException('linkPreview: false cannot be combined with customLinkPreview');
+ }
const finalDto = await this.applySendingGate(sessionId, 'text', dto);
const engine = this.getEngine(sessionId);
@@ -129,9 +134,12 @@ export class MessageService {
// nor a preview choice keeps its two-argument shape, and one with mentions alone keeps its
// three — trailing `undefined`s would be harmless to the engines but would rewrite the call
// shape of every existing send for no behavioural gain.
- const { linkPreview } = finalDto;
- if (linkPreview !== undefined) {
- result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions, { linkPreview });
+ const { linkPreview, customLinkPreview } = finalDto;
+ if (linkPreview !== undefined || customLinkPreview) {
+ result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions, {
+ ...(linkPreview === undefined ? {} : { linkPreview }),
+ ...(customLinkPreview ? { customPreview: customLinkPreview } : {}),
+ });
} else if (finalDto.mentions?.length) {
result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions);
} else {