All files / src provider-web.ts

64% Statements 80/125
43.67% Branches 38/87
87.5% Functions 14/16
70.53% Lines 79/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270                                4x     4x 4x 4x 4x 4x                         4x 4x     3x 3x       3x               3x           4x       4x       4x   4x 4x 4x 3x 3x   4x 1x 1x       4x                 1x 1x 1x 1x 1x 1x       1x 1x 1x   1x 1x                     1x 1x 1x 1x 1x                                                             1x 1x 1x                                                 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x   1x   1x 1x 1x 1x 1x 1x 1x 1x         1x 1x   1x     1x 1x                               1x   1x 1x                 1x 1x 1x     1x   1x                                      
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
	DisconnectReason,
	fetchLatestBaileysVersion,
	makeCacheableSignalKeyStore,
	makeWASocket,
	useMultiFileAuthState,
} from "baileys";
import type { proto } from "baileys";
import pino from "pino";
import qrcode from "qrcode-terminal";
import { danger, info, logVerbose, success } from "./globals.js";
import { ensureDir, jidToE164, toWhatsappJid } from "./utils.js";
 
const WA_WEB_AUTH_DIR = path.join(os.homedir(), ".warelay", "waweb");
 
export async function createWaSocket(printQr: boolean, verbose: boolean) {
	await ensureDir(WA_WEB_AUTH_DIR);
	const { state, saveCreds } = await useMultiFileAuthState(WA_WEB_AUTH_DIR);
	const { version } = await fetchLatestBaileysVersion();
	const logger = pino({ level: verbose ? "info" : "silent" });
	const sock = makeWASocket({
		auth: {
			creds: state.creds,
			keys: makeCacheableSignalKeyStore(state.keys, logger),
		},
		version,
		logger,
		printQRInTerminal: false,
		browser: ["Warelay", "CLI", "1.0.0"],
		syncFullHistory: false,
		markOnlineOnConnect: false,
	});
 
	sock.ev.on("creds.update", saveCreds);
	sock.ev.on(
		"connection.update",
		(update: Partial<import("baileys").ConnectionState>) => {
			const { connection, lastDisconnect, qr } = update;
			Iif (qr && printQr) {
				console.log("Scan this QR in WhatsApp (Linked Devices):");
				qrcode.generate(qr, { small: true });
			}
			Iif (connection === "close") {
				const status = getStatusCode(lastDisconnect?.error);
				if (status === DisconnectReason.loggedOut) {
					console.error(
						danger("WhatsApp session logged out. Run: warelay web:login"),
					);
				}
			}
			Iif (connection === "open" && verbose) {
				console.log(success("WhatsApp Web connected."));
			}
		},
	);
 
	return sock;
}
 
export async function waitForWaConnection(sock: ReturnType<typeof makeWASocket>) {
	return new Promise<void>((resolve, reject) => {
		type OffCapable = {
			off?: (event: string, listener: (...args: unknown[]) => void) => void;
		};
		const evWithOff = sock.ev as unknown as OffCapable;
 
		const handler = (...args: unknown[]) => {
			const update = (args[0] ?? {}) as Partial<import("baileys").ConnectionState>;
			if (update.connection === "open") {
				evWithOff.off?.("connection.update", handler);
				resolve();
			}
			if (update.connection === "close") {
				evWithOff.off?.("connection.update", handler);
				reject(update.lastDisconnect ?? new Error("Connection closed"));
			}
		};
 
		sock.ev.on("connection.update", handler);
	});
}
 
export async function sendMessageWeb(
	to: string,
	body: string,
	options: { verbose: boolean },
) {
	const sock = await createWaSocket(false, options.verbose);
	try {
		await waitForWaConnection(sock);
		const jid = toWhatsappJid(to);
		try {
			await sock.sendPresenceUpdate("composing", jid);
		} catch (err) {
			logVerbose(`Presence update skipped: ${String(err)}`);
		}
		const result = await sock.sendMessage(jid, { text: body });
		const messageId = result?.key?.id ?? "unknown";
		console.log(success(`✅ Sent via web session. Message ID: ${messageId} -> ${jid}`));
	} finally {
		try {
			sock.ws?.close();
		} catch (err) {
			logVerbose(`Socket close failed: ${String(err)}`);
		}
	}
}
 
export async function loginWeb(
	verbose: boolean,
	waitForConnection: typeof waitForWaConnection = waitForWaConnection,
) {
	const sock = await createWaSocket(true, verbose);
	console.log(info("Waiting for WhatsApp connection..."));
	try {
		await waitForConnection(sock);
		console.log(success("✅ Linked! Credentials saved for future sends."));
	} catch (err) {
		const code =
			(err as { error?: { output?: { statusCode?: number } } })?.error?.output
				?.statusCode ??
			(err as { output?: { statusCode?: number } })?.output?.statusCode;
		if (code === 515) {
			console.log(
				info(
					"WhatsApp asked for a restart after pairing (code 515); creds are saved. You can now send with provider=web.",
				),
			);
			return;
		}
		if (code === DisconnectReason.loggedOut) {
			await fs.rm(WA_WEB_AUTH_DIR, { recursive: true, force: true });
			console.error(
				danger(
					"WhatsApp reported the session is logged out. Cleared cached web session; please rerun warelay web:login and scan the QR again.",
				),
			);
			throw new Error("Session logged out; cache cleared. Re-run web:login.");
		}
		const formatted = formatError(err);
		console.error(
			danger(
				`WhatsApp Web connection ended before fully opening. ${formatted}`,
			),
		);
		throw new Error(formatted);
	} finally {
		setTimeout(() => {
			try {
				sock.ws?.close();
			} catch {
				// ignore
			}
		}, 500);
	}
}
 
export { WA_WEB_AUTH_DIR };
 
export type WebInboundMessage = {
	id?: string;
	from: string;
	to: string;
	body: string;
	pushName?: string;
	timestamp?: number;
	sendComposing: () => Promise<void>;
	reply: (text: string) => Promise<void>;
};
 
export async function monitorWebInbox(options: {
	verbose: boolean;
	onMessage: (msg: WebInboundMessage) => Promise<void>;
}) {
	const sock = await createWaSocket(false, options.verbose);
	await waitForWaConnection(sock);
	const selfJid = sock.user?.id;
	const selfE164 = selfJid ? jidToE164(selfJid) : null;
	const seen = new Set<string>();
 
	sock.ev.on("messages.upsert", async (upsert) => {
		Iif (upsert.type !== "notify") return;
		for (const msg of upsert.messages) {
			const id = msg.key?.id ?? undefined;
			// De-dupe on message id; Baileys can emit retries.
			Iif (id && seen.has(id)) continue;
			Eif (id) seen.add(id);
			Iif (msg.key?.fromMe) continue;
			const remoteJid = msg.key?.remoteJid;
			Iif (!remoteJid) continue;
			// Ignore status/broadcast traffic; we only care about direct chats.
			Iif (remoteJid.endsWith("@status") || remoteJid.endsWith("@broadcast"))
				continue;
			const from = jidToE164(remoteJid);
			Iif (!from) continue;
			const body = extractText(msg.message);
			Iif (!body) continue;
			const chatJid = remoteJid;
			const sendComposing = async () => {
				try {
					await sock.sendPresenceUpdate("composing", chatJid);
				} catch (err) {
					logVerbose(`Presence update failed: ${String(err)}`);
				}
			};
			const reply = async (text: string) => {
				await sock.sendMessage(chatJid, { text });
			};
			const timestamp = msg.messageTimestamp
				? Number(msg.messageTimestamp) * 1000
				: undefined;
			try {
				await options.onMessage({
					id,
					from,
					to: selfE164 ?? "me",
					body,
					pushName: msg.pushName ?? undefined,
					timestamp,
					sendComposing,
					reply,
				});
			} catch (err) {
				console.error(danger(`Failed handling inbound web message: ${String(err)}`));
			}
		}
	});
 
	return {
		close: async () => {
			try {
				sock.ws?.close();
			} catch (err) {
				logVerbose(`Socket close failed: ${String(err)}`);
			}
		},
	};
}
 
function extractText(message: proto.IMessage | undefined): string | undefined {
	Iif (!message) return undefined;
	Eif (typeof message.conversation === "string" && message.conversation.trim()) {
		return message.conversation.trim();
	}
	const extended = message.extendedTextMessage?.text;
	Iif (extended?.trim()) return extended.trim();
	const caption = message.imageMessage?.caption ?? message.videoMessage?.caption;
	Iif (caption?.trim()) return caption.trim();
	return undefined;
}
 
function getStatusCode(err: unknown) {
	return (
		(err as { output?: { statusCode?: number } })?.output?.statusCode ??
		(err as { status?: number })?.status
	);
}
 
function formatError(err: unknown): string {
	if (err instanceof Error) return err.message;
	if (typeof err === "string") return err;
	const status = getStatusCode(err);
	const code = (err as { code?: unknown })?.code;
	if (status || code) return `status=${status ?? "unknown"} code=${code ?? "unknown"}`;
	return String(err);
}