Update Baileys to 7RC

This commit is contained in:
Darren Clarke 2025-12-02 16:55:07 +01:00
parent b82d3cc726
commit 8d3eeee1d9
9 changed files with 115 additions and 127 deletions

View file

@ -1,33 +1,29 @@
{
"name": "@link-stack/bridge-whatsapp",
"version": "3.3.2",
"type": "module",
"main": "build/main/index.js",
"author": "Darren Clarke <darren@redaranj.com>",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@adiwajshing/keyed-db": "0.2.4",
"@hapi/hapi": "^21.4.3",
"@hapipal/schmervice": "^3.0.0",
"@hapipal/toys": "^4.0.0",
"@link-stack/bridge-common": "workspace:*",
"@link-stack/logger": "workspace:*",
"@whiskeysockets/baileys": "^6.7.21",
"hapi-pino": "^13.0.0",
"link-preview-js": "^3.1.0"
"@whiskeysockets/baileys": "7.0.0-rc.9",
"hapi-pino": "^13.0.0"
},
"devDependencies": {
"@link-stack/eslint-config": "workspace:*",
"@link-stack/jest-config": "workspace:*",
"@link-stack/typescript-config": "workspace:*",
"@types/long": "^5",
"@types/node": "*",
"dotenv-cli": "^10.0.0",
"tsx": "^4.20.6",
"typescript": "^5.9.3"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"dev": "dotenv -- tsx src/index.ts",
"dev": "node --env-file=.env --experimental-transform-types src/index.ts",
"start": "node build/main/index.js"
}
}

View file

@ -1,17 +1,17 @@
import * as Hapi from "@hapi/hapi";
import hapiPino from "hapi-pino";
import Schmervice from "@hapipal/schmervice";
import WhatsappService from "./service.js";
import WhatsappService from "./service.ts";
import {
RegisterBotRoute,
UnverifyBotRoute,
GetBotRoute,
SendMessageRoute,
ReceiveMessageRoute,
} from "./routes.js";
} from "./routes.ts";
import { createLogger } from "@link-stack/logger";
const logger = createLogger('bridge-whatsapp-index');
const logger = createLogger("bridge-whatsapp-index");
const server = Hapi.server({ port: 5000 });

View file

@ -1,6 +1,6 @@
import * as Hapi from "@hapi/hapi";
import Toys from "@hapipal/toys";
import WhatsappService from "./service";
import WhatsappService from "./service.ts";
const withDefaults = Toys.withRouteDefaults({
options: {
@ -27,15 +27,9 @@ export const SendMessageRoute = withDefaults({
description: "Send a message",
async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
const { id } = request.params;
const { phoneNumber, message, attachments } =
request.payload as MessageRequest;
const { phoneNumber, message, attachments } = request.payload as MessageRequest;
const whatsappService = getService(request);
await whatsappService.send(
id,
phoneNumber,
message as string,
attachments,
);
await whatsappService.send(id, phoneNumber, message as string, attachments);
request.logger.info(
{
id,

View file

@ -4,12 +4,13 @@ import makeWASocket, {
DisconnectReason,
proto,
downloadContentFromMessage,
MediaType,
fetchLatestBaileysVersion,
isJidBroadcast,
isJidStatusBroadcast,
useMultiFileAuthState,
} from "@whiskeysockets/baileys";
type MediaType = "audio" | "document" | "image" | "video" | "sticker";
import fs from "fs";
import { createLogger } from "@link-stack/logger";
import {
@ -26,11 +27,7 @@ export default class WhatsappService extends Service {
connections: { [key: string]: any } = {};
loginConnections: { [key: string]: any } = {};
static browserDescription: [string, string, string] = [
"Bridge",
"Chrome",
"2.0",
];
static browserDescription: [string, string, string] = ["Bridge", "Chrome", "2.0"];
constructor(server: Server, options: never) {
super(server, options);
@ -47,7 +44,7 @@ export default class WhatsappService extends Service {
}
// Prevent path traversal by checking for suspicious patterns
if (id.includes('..') || id.includes('/') || id.includes('\\')) {
if (id.includes("..") || id.includes("/") || id.includes("\\")) {
throw new Error(`Path traversal detected in bot ID: ${id}`);
}
@ -102,20 +99,14 @@ export default class WhatsappService extends Service {
auth: state,
generateHighQualityLinkPreview: false,
msgRetryCounterMap,
shouldIgnoreJid: (jid) =>
isJidBroadcast(jid) || isJidStatusBroadcast(jid),
shouldIgnoreJid: (jid) => isJidBroadcast(jid) || isJidStatusBroadcast(jid),
});
let pause = 5000;
socket.ev.process(async (events) => {
if (events["connection.update"]) {
const update = events["connection.update"];
const {
connection: connectionState,
lastDisconnect,
qr,
isNewLogin,
} = update;
const { connection: connectionState, lastDisconnect, qr, isNewLogin } = update;
if (qr) {
logger.info("got qr code");
const botDirectory = this.getBotDirectory(botID);
@ -130,8 +121,7 @@ export default class WhatsappService extends Service {
logger.info("opened connection");
} else if (connectionState === "close") {
logger.info({ lastDisconnect }, "connection closed");
const disconnectStatusCode = (lastDisconnect?.error as any)?.output
?.statusCode;
const disconnectStatusCode = (lastDisconnect?.error as any)?.output?.statusCode;
if (disconnectStatusCode === DisconnectReason.restartRequired) {
logger.info("reconnecting after got new login");
await this.createConnection(botID, server, options);
@ -174,10 +164,7 @@ export default class WhatsappService extends Service {
const verifiedFile = `${directory}/verified`;
if (fs.existsSync(verifiedFile)) {
const { version, isLatest } = await fetchLatestBaileysVersion();
logger.info(
{ version: version.join("."), isLatest },
"using WA version",
);
logger.info({ version: version.join("."), isLatest }, "using WA version");
await this.createConnection(botID, this.server, {
browser: WhatsappService.browserDescription,
@ -188,15 +175,13 @@ export default class WhatsappService extends Service {
}
}
private async queueMessage(
botID: string,
webMessageInfo: proto.IWebMessageInfo,
) {
const {
key: { id, fromMe, remoteJid },
message,
messageTimestamp,
} = webMessageInfo;
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(
@ -204,11 +189,9 @@ export default class WhatsappService extends Service {
"Message field",
);
}
const isValidMessage =
message && remoteJid !== "status@broadcast" && !fromMe;
const isValidMessage = message && remoteJid !== "status@broadcast" && !fromMe;
if (isValidMessage) {
const { audioMessage, documentMessage, imageMessage, videoMessage } =
message;
const { audioMessage, documentMessage, imageMessage, videoMessage } = message;
const isMediaMessage =
audioMessage || documentMessage || imageMessage || videoMessage;
@ -288,10 +271,7 @@ export default class WhatsappService extends Service {
}
}
private async queueUnreadMessages(
botID: string,
messages: proto.IWebMessageInfo[],
) {
private async queueUnreadMessages(botID: string, messages: proto.IWebMessageInfo[]) {
for await (const message of messages) {
await this.queueMessage(botID, message);
}
@ -334,10 +314,7 @@ export default class WhatsappService extends Service {
}
}
async register(
botID: string,
callback?: AuthCompleteCallback,
): Promise<void> {
async register(botID: string, callback?: AuthCompleteCallback): Promise<void> {
const { version } = await fetchLatestBaileysVersion();
await this.createConnection(
botID,
@ -368,7 +345,9 @@ export default class WhatsappService extends Service {
const MAX_TOTAL_SIZE = getMaxTotalAttachmentSize();
if (attachments.length > MAX_ATTACHMENTS) {
throw new Error(`Too many attachments: ${attachments.length} (max ${MAX_ATTACHMENTS})`);
throw new Error(
`Too many attachments: ${attachments.length} (max ${MAX_ATTACHMENTS})`,
);
}
let totalSize = 0;
@ -378,20 +357,26 @@ export default class WhatsappService extends Service {
const estimatedSize = (attachment.data.length * 3) / 4;
if (estimatedSize > MAX_ATTACHMENT_SIZE) {
logger.warn({
filename: attachment.filename,
size: estimatedSize,
maxSize: MAX_ATTACHMENT_SIZE
}, 'Attachment exceeds size limit, skipping');
logger.warn(
{
filename: attachment.filename,
size: estimatedSize,
maxSize: MAX_ATTACHMENT_SIZE,
},
"Attachment exceeds size limit, skipping",
);
continue;
}
totalSize += estimatedSize;
if (totalSize > MAX_TOTAL_SIZE) {
logger.warn({
totalSize,
maxTotalSize: MAX_TOTAL_SIZE
}, 'Total attachment size exceeds limit, skipping remaining');
logger.warn(
{
totalSize,
maxTotalSize: MAX_TOTAL_SIZE,
},
"Total attachment size exceeds limit, skipping remaining",
);
break;
}

View file

@ -1,4 +1,4 @@
import type WhatsappService from "./service.js";
import type WhatsappService from "./service.ts";
declare module "@hapipal/schmervice" {
interface SchmerviceDecorator {

View file

@ -1,16 +1,17 @@
{
"extends": "@link-stack/typescript-config/tsconfig.node.json",
"compilerOptions": {
"module": "commonjs",
"target": "es2018",
"module": "NodeNext",
"target": "es2022",
"esModuleInterop": true,
"moduleResolution": "node",
"moduleResolution": "NodeNext",
"outDir": "build/main",
"rootDir": "src",
"skipLibCheck": true,
"types": ["node"],
"lib": ["es2020", "DOM"],
"composite": true
"lib": ["es2022", "DOM"],
"composite": true,
"rewriteRelativeImportExtensions": true
},
"include": ["src/**/*.ts", "src/**/.*.ts"],
"exclude": ["node_modules/**"]