link-stack/apps/bridge-whatsapp/src/service.ts

421 lines
13 KiB
TypeScript
Raw Normal View History

2024-05-07 14:16:01 +02:00
import { Server } from "@hapi/hapi";
import { Service } from "@hapipal/schmervice";
import makeWASocket, {
DisconnectReason,
proto,
downloadContentFromMessage,
fetchLatestBaileysVersion,
isJidBroadcast,
isJidStatusBroadcast,
useMultiFileAuthState,
} from "@whiskeysockets/baileys";
2025-12-02 16:55:07 +01:00
type MediaType = "audio" | "document" | "image" | "video" | "sticker";
2024-05-07 14:16:01 +02:00
import fs from "fs";
import { createLogger } from "@link-stack/logger";
import {
getMaxAttachmentSize,
getMaxTotalAttachmentSize,
MAX_ATTACHMENTS,
} from "@link-stack/bridge-common";
const logger = createLogger("bridge-whatsapp-service");
2024-05-07 14:16:01 +02:00
export type AuthCompleteCallback = (error?: string) => void;
export default class WhatsappService extends Service {
connections: { [key: string]: any } = {};
loginConnections: { [key: string]: any } = {};
2025-12-02 16:55:07 +01:00
static browserDescription: [string, string, string] = ["Bridge", "Chrome", "2.0"];
2024-05-07 14:16:01 +02:00
constructor(server: Server, options: never) {
super(server, options);
}
2024-05-17 09:20:00 +02:00
getBaseDirectory(): string {
return `/home/node/baileys`;
}
2024-05-15 14:39:33 +02:00
getBotDirectory(id: string): string {
// Validate that ID contains only safe characters (alphanumeric, dash, underscore)
if (!/^[a-zA-Z0-9_-]+$/.test(id)) {
throw new Error(`Invalid bot ID format: ${id}`);
}
// Prevent path traversal by checking for suspicious patterns
2025-12-02 16:55:07 +01:00
if (id.includes("..") || id.includes("/") || id.includes("\\")) {
throw new Error(`Path traversal detected in bot ID: ${id}`);
}
const botPath = `${this.getBaseDirectory()}/${id}`;
// Ensure the resolved path is still within the base directory
if (!botPath.startsWith(this.getBaseDirectory())) {
throw new Error(`Invalid bot path: ${botPath}`);
}
return botPath;
2024-05-15 14:39:33 +02:00
}
getAuthDirectory(id: string): string {
return `${this.getBotDirectory(id)}/auth`;
2024-05-07 14:16:01 +02:00
}
async initialize(): Promise<void> {
this.updateConnections();
}
async teardown(): Promise<void> {
this.resetConnections();
}
private async sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
private async resetConnections() {
for (const connection of Object.values(this.connections)) {
try {
connection.end(null);
} catch (error) {
logger.error({ error }, "Connection reset error");
2024-05-07 14:16:01 +02:00
}
}
this.connections = {};
}
private async createConnection(
2024-05-15 14:39:33 +02:00
botID: string,
2024-05-07 14:16:01 +02:00
server: Server,
options: any,
authCompleteCallback?: any,
) {
2024-05-15 14:39:33 +02:00
const authDirectory = this.getAuthDirectory(botID);
const { state, saveCreds } = await useMultiFileAuthState(authDirectory);
2024-05-07 14:16:01 +02:00
const msgRetryCounterMap: any = {};
const socket = makeWASocket({
...options,
auth: state,
2024-07-19 11:25:35 +02:00
generateHighQualityLinkPreview: false,
2024-05-07 14:16:01 +02:00
msgRetryCounterMap,
2025-12-02 16:55:07 +01:00
shouldIgnoreJid: (jid) => isJidBroadcast(jid) || isJidStatusBroadcast(jid),
2024-05-07 14:16:01 +02:00
});
let pause = 5000;
socket.ev.process(async (events) => {
if (events["connection.update"]) {
const update = events["connection.update"];
2025-12-02 16:55:07 +01:00
const { connection: connectionState, lastDisconnect, qr, isNewLogin } = update;
2024-05-07 14:16:01 +02:00
if (qr) {
logger.info("got qr code");
2024-05-15 14:39:33 +02:00
const botDirectory = this.getBotDirectory(botID);
2024-05-16 18:22:10 +02:00
const qrPath = `${botDirectory}/qr.txt`;
fs.writeFileSync(qrPath, qr, "utf8");
2024-05-07 14:16:01 +02:00
} else if (isNewLogin) {
logger.info("got new login");
2024-05-15 14:39:33 +02:00
const botDirectory = this.getBotDirectory(botID);
const verifiedFile = `${botDirectory}/verified`;
fs.writeFileSync(verifiedFile, "");
2024-05-07 14:16:01 +02:00
} else if (connectionState === "open") {
logger.info("opened connection");
2024-05-07 14:16:01 +02:00
} else if (connectionState === "close") {
logger.info({ lastDisconnect }, "connection closed");
2025-12-02 16:55:07 +01:00
const disconnectStatusCode = (lastDisconnect?.error as any)?.output?.statusCode;
2024-05-07 14:16:01 +02:00
if (disconnectStatusCode === DisconnectReason.restartRequired) {
logger.info("reconnecting after got new login");
2024-05-15 14:39:33 +02:00
await this.createConnection(botID, server, options);
2024-05-07 14:16:01 +02:00
authCompleteCallback?.();
} else if (disconnectStatusCode !== DisconnectReason.loggedOut) {
logger.info("reconnecting");
2024-05-07 14:16:01 +02:00
await this.sleep(pause);
pause *= 2;
2024-05-15 14:39:33 +02:00
this.createConnection(botID, server, options);
2024-05-07 14:16:01 +02:00
}
}
}
if (events["creds.update"]) {
logger.info("creds update");
2024-05-07 14:16:01 +02:00
await saveCreds();
}
if (events["messages.upsert"]) {
logger.info("messages upsert");
2024-05-07 14:16:01 +02:00
const upsert = events["messages.upsert"];
const { messages } = upsert;
if (messages) {
2024-05-15 14:39:33 +02:00
await this.queueUnreadMessages(botID, messages);
2024-05-07 14:16:01 +02:00
}
}
});
2024-05-15 14:39:33 +02:00
this.connections[botID] = { socket, msgRetryCounterMap };
2024-05-07 14:16:01 +02:00
}
private async updateConnections() {
this.resetConnections();
2024-05-15 14:39:33 +02:00
2024-05-17 09:20:00 +02:00
const baseDirectory = this.getBaseDirectory();
const botIDs = fs.readdirSync(baseDirectory);
2024-05-15 14:39:33 +02:00
for await (const botID of botIDs) {
const directory = this.getBotDirectory(botID);
const verifiedFile = `${directory}/verified`;
if (fs.existsSync(verifiedFile)) {
2024-05-07 14:16:01 +02:00
const { version, isLatest } = await fetchLatestBaileysVersion();
2025-12-02 16:55:07 +01:00
logger.info({ version: version.join("."), isLatest }, "using WA version");
2024-05-07 14:16:01 +02:00
2024-05-15 14:39:33 +02:00
await this.createConnection(botID, this.server, {
2024-05-07 14:16:01 +02:00
browser: WhatsappService.browserDescription,
2024-05-15 14:39:33 +02:00
printQRInTerminal: true,
2024-05-07 14:16:01 +02:00
version,
});
}
}
}
2025-12-02 16:55:07 +01:00
private async queueMessage(botID: string, webMessageInfo: proto.IWebMessageInfo) {
const { key, message, messageTimestamp } = webMessageInfo;
if (!key) {
logger.warn("Message missing key, skipping");
return;
}
const { id, fromMe, remoteJid } = key;
logger.info("Message type debug");
for (const key in message) {
logger.info(
{ key, exists: !!message[key as keyof proto.IMessage] },
"Message field",
);
}
2025-12-02 16:55:07 +01:00
const isValidMessage = message && remoteJid !== "status@broadcast" && !fromMe;
2024-07-19 11:25:35 +02:00
if (isValidMessage) {
2025-12-02 16:55:07 +01:00
const { audioMessage, documentMessage, imageMessage, videoMessage } = message;
2024-05-07 14:16:01 +02:00
const isMediaMessage =
audioMessage || documentMessage || imageMessage || videoMessage;
const messageContent = Object.values(message)[0];
let messageType: MediaType;
2024-07-18 11:08:01 +02:00
let attachment: string | null | undefined;
2024-06-05 15:12:48 +02:00
let filename: string | null | undefined;
2024-07-18 11:08:01 +02:00
let mimeType: string | null | undefined;
2024-05-07 14:16:01 +02:00
if (isMediaMessage) {
if (audioMessage) {
messageType = "audio";
const extension = audioMessage.mimetype?.split("/").pop() || "audio";
filename = `${id}.${extension}`;
2024-07-18 11:08:01 +02:00
mimeType = audioMessage.mimetype;
2024-05-07 14:16:01 +02:00
} else if (documentMessage) {
messageType = "document";
filename = documentMessage.fileName || `${id}.bin`;
2024-07-18 11:08:01 +02:00
mimeType = documentMessage.mimetype;
2024-05-07 14:16:01 +02:00
} else if (imageMessage) {
messageType = "image";
const extension = imageMessage.mimetype?.split("/").pop() || "jpg";
filename = `${id}.${extension}`;
2024-07-18 11:08:01 +02:00
mimeType = imageMessage.mimetype;
2024-05-07 14:16:01 +02:00
} else if (videoMessage) {
messageType = "video";
const extension = videoMessage.mimetype?.split("/").pop() || "mp4";
filename = `${id}.${extension}`;
2024-07-18 11:08:01 +02:00
mimeType = videoMessage.mimetype;
2024-05-07 14:16:01 +02:00
}
const stream = await downloadContentFromMessage(
messageContent,
2024-06-05 15:12:48 +02:00
// @ts-ignore
2024-05-07 14:16:01 +02:00
messageType,
);
let buffer = Buffer.from([]);
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk]);
}
attachment = buffer.toString("base64");
}
if (messageContent || attachment) {
2024-07-19 11:25:35 +02:00
const conversation = message?.conversation;
const extendedTextMessage = message?.extendedTextMessage?.text;
const imageMessage = message?.imageMessage?.caption;
const videoMessage = message?.videoMessage?.caption;
const messageText = [
conversation,
extendedTextMessage,
imageMessage,
videoMessage,
].find((text) => text && text !== "");
2024-05-17 09:20:00 +02:00
const payload = {
2024-07-18 11:08:01 +02:00
to: botID,
2024-07-19 11:25:35 +02:00
from: remoteJid?.split("@")[0],
2024-07-18 11:08:01 +02:00
messageId: id,
sentAt: new Date((messageTimestamp as number) * 1000).toISOString(),
2024-07-19 11:25:35 +02:00
message: messageText,
2024-07-18 11:08:01 +02:00
attachment,
filename,
mimeType,
2024-05-17 09:20:00 +02:00
};
2024-05-16 18:22:10 +02:00
await fetch(
`${process.env.BRIDGE_FRONTEND_URL}/api/whatsapp/bots/${botID}/receive`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
2024-05-17 09:20:00 +02:00
body: JSON.stringify(payload),
2024-05-15 14:39:33 +02:00
},
2024-05-16 18:22:10 +02:00
);
2024-05-07 14:16:01 +02:00
}
}
}
2025-12-02 16:55:07 +01:00
private async queueUnreadMessages(botID: string, messages: proto.IWebMessageInfo[]) {
2024-05-07 14:16:01 +02:00
for await (const message of messages) {
2024-05-15 14:39:33 +02:00
await this.queueMessage(botID, message);
2024-05-07 14:16:01 +02:00
}
}
2024-05-15 14:39:33 +02:00
getBot(botID: string): Record<string, any> {
const botDirectory = this.getBotDirectory(botID);
2024-05-16 18:22:10 +02:00
const qrPath = `${botDirectory}/qr.txt`;
2024-05-15 14:39:33 +02:00
const verifiedFile = `${botDirectory}/verified`;
2024-05-16 18:22:10 +02:00
const qr = fs.existsSync(qrPath) ? fs.readFileSync(qrPath, "utf8") : null;
2024-05-15 14:39:33 +02:00
const verified = fs.existsSync(verifiedFile);
2024-05-07 14:16:01 +02:00
2024-05-15 14:39:33 +02:00
return { qr, verified };
2024-05-07 14:16:01 +02:00
}
2024-05-15 14:39:33 +02:00
async unverify(botID: string): Promise<void> {
// Step 1: Close and remove the active connection if it exists
const connection = this.connections[botID];
if (connection?.socket) {
try {
// Properly close the WebSocket connection
await connection.socket.logout();
} catch (error) {
logger.warn({ botID, error }, "Error during logout, forcing disconnect");
try {
connection.socket.end(undefined);
} catch (endError) {
logger.warn({ botID, endError }, "Error ending socket connection");
}
}
}
// Step 2: Remove from in-memory connections
delete this.connections[botID];
// Step 3: Remove the bot directory (auth state, QR code, verified marker)
2024-05-15 14:39:33 +02:00
const botDirectory = this.getBotDirectory(botID);
if (fs.existsSync(botDirectory)) {
fs.rmSync(botDirectory, { recursive: true, force: true });
}
2024-05-07 14:16:01 +02:00
}
2025-12-02 16:55:07 +01:00
async register(botID: string, callback?: AuthCompleteCallback): Promise<void> {
2024-05-07 14:16:01 +02:00
const { version } = await fetchLatestBaileysVersion();
2024-05-17 09:20:00 +02:00
await this.createConnection(
botID,
this.server,
{ version, browser: WhatsappService.browserDescription },
callback,
);
callback?.();
2024-05-07 14:16:01 +02:00
}
async send(
2024-05-15 14:39:33 +02:00
botID: string,
2024-05-07 14:16:01 +02:00
phoneNumber: string,
message: string,
attachments?: Array<{ data: string; filename: string; mime_type: string }>,
2024-05-07 14:16:01 +02:00
): Promise<void> {
2024-05-15 14:39:33 +02:00
const connection = this.connections[botID]?.socket;
2024-05-07 14:16:01 +02:00
const recipient = `${phoneNumber.replace(/\D+/g, "")}@s.whatsapp.net`;
// Send text message if provided
if (message) {
await connection.sendMessage(recipient, { text: message });
}
// Send attachments if provided with size validation
if (attachments && attachments.length > 0) {
const MAX_ATTACHMENT_SIZE = getMaxAttachmentSize();
const MAX_TOTAL_SIZE = getMaxTotalAttachmentSize();
if (attachments.length > MAX_ATTACHMENTS) {
2025-12-02 16:55:07 +01:00
throw new Error(
`Too many attachments: ${attachments.length} (max ${MAX_ATTACHMENTS})`,
);
}
let totalSize = 0;
for (const attachment of attachments) {
// Calculate size before converting to buffer
const estimatedSize = (attachment.data.length * 3) / 4;
if (estimatedSize > MAX_ATTACHMENT_SIZE) {
2025-12-02 16:55:07 +01:00
logger.warn(
{
filename: attachment.filename,
size: estimatedSize,
maxSize: MAX_ATTACHMENT_SIZE,
},
"Attachment exceeds size limit, skipping",
);
continue;
}
totalSize += estimatedSize;
if (totalSize > MAX_TOTAL_SIZE) {
2025-12-02 16:55:07 +01:00
logger.warn(
{
totalSize,
maxTotalSize: MAX_TOTAL_SIZE,
},
"Total attachment size exceeds limit, skipping remaining",
);
break;
}
const buffer = Buffer.from(attachment.data, "base64");
if (attachment.mime_type.startsWith("image/")) {
await connection.sendMessage(recipient, {
image: buffer,
caption: attachment.filename,
});
} else if (attachment.mime_type.startsWith("video/")) {
await connection.sendMessage(recipient, {
video: buffer,
caption: attachment.filename,
});
} else if (attachment.mime_type.startsWith("audio/")) {
await connection.sendMessage(recipient, {
audio: buffer,
mimetype: attachment.mime_type,
});
} else {
await connection.sendMessage(recipient, {
document: buffer,
fileName: attachment.filename,
mimetype: attachment.mime_type,
});
}
}
}
2024-05-07 14:16:01 +02:00
}
async receive(
2024-05-15 14:39:33 +02:00
botID: string,
2024-05-07 14:16:01 +02:00
_lastReceivedDate: Date,
): Promise<proto.IWebMessageInfo[]> {
2024-05-15 14:39:33 +02:00
const connection = this.connections[botID]?.socket;
2024-05-07 14:16:01 +02:00
const messages = await connection.loadAllUnreadMessages();
2024-05-15 14:39:33 +02:00
2024-05-07 14:16:01 +02:00
return messages;
}
}