bridge.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. #!/usr/bin/env node
  2. /**
  3. * Hermes Agent WhatsApp Bridge
  4. *
  5. * Standalone Node.js process that connects to WhatsApp via Baileys
  6. * and exposes HTTP endpoints for the Python gateway adapter.
  7. *
  8. * Endpoints (matches gateway/platforms/whatsapp.py expectations):
  9. * GET /messages - Long-poll for new incoming messages
  10. * POST /send - Send a message { chatId, message, replyTo?, mentions? }
  11. * POST /edit - Edit a sent message { chatId, messageId, message }
  12. * POST /send-media - Send media natively { chatId, filePath, mediaType?, caption?, fileName?, mentions? }
  13. * POST /send-location - Send location pin { chatId, latitude, longitude, name?, address? }
  14. * POST /typing - Send typing indicator { chatId }
  15. * GET /chat/:id - Get chat info
  16. * GET /health - Health check
  17. *
  18. * Usage:
  19. * node bridge.js --port 3000 --session ~/.hermes/whatsapp/session
  20. */
  21. import { makeWASocket, useMultiFileAuthState, DisconnectReason, fetchLatestBaileysVersion, downloadMediaMessage, getAggregateVotesInPollMessage, decryptPollVote, getKeyAuthor, jidNormalizedUser } from '@whiskeysockets/baileys';
  22. import express from 'express';
  23. import { Boom } from '@hapi/boom';
  24. import pino from 'pino';
  25. import path from 'path';
  26. import { mkdirSync, readFileSync, existsSync, readdirSync, unlinkSync } from 'fs';
  27. import { fileURLToPath } from 'url';
  28. import { randomBytes, createHash } from 'crypto';
  29. import { execFileSync } from 'child_process';
  30. import { tmpdir } from 'os';
  31. import qrcode from 'qrcode-terminal';
  32. import { matchesAllowedSender, matchesAllowedUser, matchesInboundWhatsAppGroup, parseAllowedUsers } from './allowlist.js';
  33. import { createOutboundIdTracker } from './outbound_ids.js';
  34. import { classifyOwnerMessageGate } from './owner_message_gate.js';
  35. import {
  36. addMentions,
  37. buildPollPayload,
  38. createReconnectScheduler,
  39. createVersionResolver,
  40. installConsoleStamps,
  41. buildLocationPayload,
  42. buildTextSendPayload,
  43. createBoundedMessageStore,
  44. createQuotedMediaCache,
  45. deliveryStatusEvent,
  46. extractBridgeEvent,
  47. getMessageContent,
  48. inboundReadReceiptKeys,
  49. inferMediaType,
  50. mediaPayloadForFile,
  51. normalizeWhatsAppId,
  52. pollCreationMessageFromPayload,
  53. pollUpdateForAggregation,
  54. writeJsonLine,
  55. } from './bridge_helpers.js';
  56. // First statement: helpers capture console.log as a default at call time below.
  57. installConsoleStamps();
  58. // Parse CLI args
  59. const args = process.argv.slice(2);
  60. function getArg(name, defaultVal) {
  61. const idx = args.indexOf(`--${name}`);
  62. return idx !== -1 && args[idx + 1] ? args[idx + 1] : defaultVal;
  63. }
  64. const WHATSAPP_DEBUG =
  65. typeof process !== 'undefined' &&
  66. process.env &&
  67. typeof process.env.WHATSAPP_DEBUG === 'string' &&
  68. ['1', 'true', 'yes', 'on'].includes(process.env.WHATSAPP_DEBUG.toLowerCase());
  69. // Opt-in: when true (and WHATSAPP_MODE === 'bot'), fromMe inbound messages
  70. // that are NOT echoes of our own /send or /send-media calls are forwarded
  71. // to the Python adapter with `fromOwner: true`. This lets plugins detect
  72. // "owner just typed in this customer chat" — needed for handover / sliding
  73. // TTL flows. Default OFF: existing deployments see no behavior change.
  74. //
  75. // Heuristic limitation: we distinguish bot-API-sent from owner-typed by
  76. // looking up `key.id` in `recentlySentIds` (populated when /send returns).
  77. // On bridge restart that set is empty, so a few in-flight bot replies may
  78. // briefly look like owner-typed until they age out. Acceptable; we don't
  79. // persist the set.
  80. const FORWARD_OWNER_MESSAGES =
  81. typeof process !== 'undefined' &&
  82. process.env &&
  83. typeof process.env.WHATSAPP_FORWARD_OWNER_MESSAGES === 'string' &&
  84. ['1', 'true', 'yes', 'on'].includes(process.env.WHATSAPP_FORWARD_OWNER_MESSAGES.toLowerCase());
  85. const SEND_READ_RECEIPTS =
  86. typeof process !== 'undefined' &&
  87. process.env &&
  88. typeof process.env.WHATSAPP_SEND_READ_RECEIPTS === 'string' &&
  89. ['1', 'true', 'yes', 'on'].includes(process.env.WHATSAPP_SEND_READ_RECEIPTS.toLowerCase());
  90. const PORT = parseInt(getArg('port', '3000'), 10);
  91. const SESSION_DIR = getArg('session', path.join(process.env.HOME || '~', '.hermes', 'whatsapp', 'session'));
  92. // Cache directories: the Python gateway passes the profile-aware paths via
  93. // env (HERMES_HOME-aware, new cache/ layout). Fall back to the legacy
  94. // hardcoded locations for bridges launched outside the gateway.
  95. const IMAGE_CACHE_DIR = process.env.HERMES_IMAGE_CACHE_DIR
  96. || path.join(process.env.HOME || '~', '.hermes', 'image_cache');
  97. const DOCUMENT_CACHE_DIR = process.env.HERMES_DOCUMENT_CACHE_DIR
  98. || path.join(process.env.HOME || '~', '.hermes', 'document_cache');
  99. const AUDIO_CACHE_DIR = process.env.HERMES_AUDIO_CACHE_DIR
  100. || path.join(process.env.HOME || '~', '.hermes', 'audio_cache');
  101. // Self-hash of this script file. Reported in /health so the Python gateway
  102. // can detect a running bridge that predates the current bridge.js and
  103. // restart it instead of silently reusing stale code (stale-bridge trap:
  104. // `hermes update` updates bridge.js on disk but a long-lived bridge process
  105. // keeps serving the old behavior forever).
  106. let SCRIPT_HASH = '';
  107. try {
  108. SCRIPT_HASH = createHash('sha256')
  109. .update(readFileSync(fileURLToPath(import.meta.url)))
  110. .digest('hex')
  111. .slice(0, 16);
  112. } catch {}
  113. const PAIR_ONLY = args.includes('--pair-only');
  114. const PAIR_JSON = args.includes('--pair-json');
  115. const WHATSAPP_MODE = getArg('mode', process.env.WHATSAPP_MODE || 'self-chat'); // "bot" or "self-chat"
  116. const WHATSAPP_DM_POLICY = String(process.env.WHATSAPP_DM_POLICY || 'open').trim().toLowerCase();
  117. const WHATSAPP_GROUP_POLICY = String(process.env.WHATSAPP_GROUP_POLICY || 'pairing').trim().toLowerCase();
  118. const ALLOWED_USERS = parseAllowedUsers(process.env.WHATSAPP_ALLOWED_USERS || '');
  119. // Group authorization is by group JID, not by every participant's JID. The
  120. // Python adapter still applies group policy and mention rules after intake.
  121. const GROUP_ALLOWED_USERS = parseAllowedUsers(process.env.WHATSAPP_GROUP_ALLOWED_USERS || '');
  122. const DEFAULT_REPLY_PREFIX = '☤ *Hermes Agent*\n────────────\n';
  123. const REPLY_PREFIX = process.env.WHATSAPP_REPLY_PREFIX === undefined
  124. ? DEFAULT_REPLY_PREFIX
  125. : process.env.WHATSAPP_REPLY_PREFIX.replace(/\\n/g, '\n');
  126. const MAX_MESSAGE_LENGTH = parseInt(process.env.WHATSAPP_MAX_MESSAGE_LENGTH || '4096', 10);
  127. const CHUNK_DELAY_MS = parseInt(process.env.WHATSAPP_CHUNK_DELAY_MS || '300', 10);
  128. // Per-call timeout for sock.sendMessage(). Baileys occasionally hangs forever
  129. // when uploading media to WhatsApp servers (and, less often, on text sends),
  130. // which pins the bridge's HTTP handler until the upstream aiohttp timeout
  131. // fires. Fail fast instead so the gateway can surface a real error and retry.
  132. const SEND_TIMEOUT_MS = parseInt(process.env.WHATSAPP_SEND_TIMEOUT_MS || '60000', 10);
  133. // --- Send queue: serialise all sock.sendMessage() calls across concurrent
  134. // HTTP handlers so a single Baileys socket never has overlapping sends.
  135. // Overlapping sends are the root cause of cross-chat contamination
  136. // (#33360) — the WhatsApp protocol-level routing can misdeliver when
  137. // two sendMessage() Promises race on the same socket. ---
  138. let _sendQueue = Promise.resolve();
  139. function enqueueSend(fn) {
  140. const task = _sendQueue.then(() => fn(), () => fn());
  141. _sendQueue = task.catch(() => {});
  142. return task;
  143. }
  144. function sleep(ms) {
  145. return new Promise(resolve => setTimeout(resolve, ms));
  146. }
  147. function sendWithTimeout(chatId, payload, options = {}, timeoutMs = SEND_TIMEOUT_MS) {
  148. let timer;
  149. const timeoutPromise = new Promise((_, reject) => {
  150. timer = setTimeout(
  151. () => reject(new Error(`sendMessage timed out after ${timeoutMs / 1000}s`)),
  152. timeoutMs,
  153. );
  154. });
  155. return enqueueSend(() =>
  156. Promise.race([sock.sendMessage(chatId, payload, options), timeoutPromise])
  157. .finally(() => clearTimeout(timer))
  158. );
  159. }
  160. function formatOutgoingMessage(message) {
  161. // In bot mode, messages come from a different number so the prefix is
  162. // redundant — the sender identity is already clear. Only prepend in
  163. // self-chat mode where bot and user share the same number.
  164. if (WHATSAPP_MODE !== 'self-chat') return message;
  165. return REPLY_PREFIX ? `${REPLY_PREFIX}${message}` : message;
  166. }
  167. function splitLongMessage(message, maxLength = MAX_MESSAGE_LENGTH) {
  168. const text = String(message || '');
  169. if (!text) return [];
  170. if (!Number.isFinite(maxLength) || maxLength < 1 || text.length <= maxLength) {
  171. return [text];
  172. }
  173. const chunks = [];
  174. let remaining = text;
  175. while (remaining.length > maxLength) {
  176. let splitAt = remaining.lastIndexOf('\n', maxLength);
  177. if (splitAt < Math.floor(maxLength / 2)) {
  178. splitAt = remaining.lastIndexOf(' ', maxLength);
  179. }
  180. if (splitAt < 1) splitAt = maxLength;
  181. chunks.push(remaining.slice(0, splitAt).trimEnd());
  182. remaining = remaining.slice(splitAt).trimStart();
  183. }
  184. if (remaining) chunks.push(remaining);
  185. return chunks;
  186. }
  187. function rememberSentMessage(sent, payload) {
  188. if (!sent?.key?.id) return;
  189. if (sent.message) {
  190. messageStore.remember(sent);
  191. return;
  192. }
  193. const syntheticMessage = pollCreationMessageFromPayload(payload);
  194. if (syntheticMessage) {
  195. messageStore.remember({ ...sent, message: syntheticMessage });
  196. }
  197. }
  198. function trackSentMessageId(sent) {
  199. rememberSentId(sent?.key?.id);
  200. }
  201. function redactWhatsAppId(value) {
  202. const raw = String(value || '').trim();
  203. if (!raw) return '';
  204. const [userPart, domainPart = ''] = raw.split('@', 2);
  205. const bare = userPart.split(':', 1)[0];
  206. const digits = bare.replace(/\D/g, '');
  207. const suffix = digits ? digits.slice(-4) : bare.slice(-4);
  208. return `${suffix ? `…${suffix}` : '…'}${domainPart ? `@${domainPart}` : ''}`;
  209. }
  210. function emitDebugEvent(payload) {
  211. if (!WHATSAPP_DEBUG) return;
  212. try {
  213. writeJsonLine({ event: 'debug', ...payload });
  214. } catch {}
  215. }
  216. mkdirSync(SESSION_DIR, { recursive: true });
  217. // Build LID → phone reverse map from session files (lid-mapping-{phone}.json)
  218. function buildLidMap() {
  219. const map = {};
  220. try {
  221. for (const f of readdirSync(SESSION_DIR)) {
  222. const m = f.match(/^lid-mapping-(\d+)\.json$/);
  223. if (!m) continue;
  224. const phone = m[1];
  225. const lid = JSON.parse(readFileSync(path.join(SESSION_DIR, f), 'utf8'));
  226. if (lid) map[String(lid)] = phone;
  227. }
  228. } catch {}
  229. return map;
  230. }
  231. let lidToPhone = buildLidMap();
  232. const logger = pino({ level: 'warn' });
  233. // Message queue for polling
  234. const messageQueue = [];
  235. const MAX_QUEUE_SIZE = 100;
  236. // Track recently sent message IDs. Two purposes:
  237. // 1. Prevent echo-back loops with media in self-chat mode.
  238. // 2. (When WHATSAPP_FORWARD_OWNER_MESSAGES=true) distinguish our own
  239. // bot-API outbound messages from owner-typed messages on the linked
  240. // device so we can forward only the latter.
  241. // Capacity bounded (see outbound_ids.js) to keep memory flat under
  242. // sustained sending.
  243. const recentlySentIds = createOutboundIdTracker(512);
  244. const recentlyProcessedPollUpdates = createOutboundIdTracker(512);
  245. const messageStore = createBoundedMessageStore(512);
  246. // Bounded cache of already-downloaded inbound media, so a later reply to an
  247. // uncaptioned photo/video/document/voice note can still surface the original
  248. // file — see createQuotedMediaCache's doc comment in bridge_helpers.js.
  249. const quotedMediaCache = createQuotedMediaCache(512);
  250. function normalizePollUpdateOptions(aggregation, pollUpdateMessage, meId) {
  251. const selected = [];
  252. for (const option of aggregation || []) {
  253. if ((option.voters || []).length > 0 && option.name && option.name !== 'Unknown') {
  254. selected.push(option.name);
  255. }
  256. }
  257. if (selected.length > 0) return selected;
  258. // Fallback for already-decrypted pollUpdateMessage payloads where Baileys did
  259. // not have the creation message available. This may only yield hashes, but
  260. // keeping them in metadata is still better than dropping the vote entirely.
  261. const raw = pollUpdateMessage?.vote?.selectedOptions || [];
  262. return raw.map(option => String(option)).filter(Boolean);
  263. }
  264. function pollAggregationSummary(aggregation) {
  265. return (aggregation || []).map(option => ({
  266. name: option?.name || '',
  267. voterCount: (option?.voters || []).length,
  268. }));
  269. }
  270. function logPollUpdateDiagnostic({ sourcePath, pollId, pollCreation, pollUpdates, selectedOptions, aggregation }) {
  271. const firstUpdate = pollUpdates?.[0] || {};
  272. try {
  273. writeJsonLine({
  274. event: 'poll_update_decode',
  275. sourcePath,
  276. pollId: pollId || '',
  277. pollCreationFound: !!pollCreation,
  278. updateKeys: Object.keys(firstUpdate),
  279. hasVote: !!firstUpdate.vote,
  280. selectedOptionsLength: selectedOptions?.length || 0,
  281. aggregation: pollAggregationSummary(aggregation),
  282. });
  283. } catch {}
  284. }
  285. function enqueuePollUpdateEvent({ key, update, selectedOptions, aggregation }) {
  286. const chatId = normalizeWhatsAppId(key?.remoteJid || update?.pollUpdates?.[0]?.pollUpdateMessageKey?.remoteJid || '');
  287. const senderId = normalizeWhatsAppId(
  288. key?.participant
  289. || update?.pollUpdates?.[0]?.pollUpdateMessageKey?.participant
  290. || chatId
  291. );
  292. const pollId = key?.id
  293. || update?.pollUpdates?.[0]?.pollCreationMessageKey?.id
  294. || update?.pollUpdates?.[0]?.pollUpdateMessageKey?.id
  295. || '';
  296. // Only surface votes on polls Hermes itself created (tracked when
  297. // /send-poll returns). Arbitrary human polls in a group chat must not
  298. // inject agent-visible messages on every vote.
  299. if (!pollId || !recentlySentIds.has(pollId)) {
  300. if (WHATSAPP_DEBUG) {
  301. try { writeJsonLine({ event: 'ignored', reason: 'foreign_poll_update', pollId }); } catch {}
  302. }
  303. return;
  304. }
  305. const chosenText = selectedOptions.length ? selectedOptions.join(', ') : `[Poll update${pollId ? `: ${pollId}` : ''}]`;
  306. const dedupeId = `poll:${pollId}:${senderId}:${selectedOptions.join('|')}`;
  307. if (recentlyProcessedPollUpdates.has(dedupeId)) return;
  308. recentlyProcessedPollUpdates.remember(dedupeId);
  309. const event = {
  310. messageId: `${pollId || 'poll'}:update:${Date.now()}`,
  311. chatId,
  312. senderId,
  313. senderName: senderId.replace(/@.*/, ''),
  314. chatName: chatId.replace(/@.*/, ''),
  315. isGroup: chatId.endsWith('@g.us'),
  316. body: chosenText,
  317. hasMedia: false,
  318. mediaType: 'poll_update',
  319. mime: '',
  320. fileName: '',
  321. nativeType: 'pollUpdateMessage',
  322. nativeMetadata: {
  323. pollUpdate: {
  324. pollId,
  325. selectedOptions,
  326. aggregation,
  327. },
  328. },
  329. mediaUrls: [],
  330. mentionedIds: [],
  331. quotedMessageId: pollId,
  332. quotedParticipant: '',
  333. quotedRemoteJid: chatId,
  334. quotedText: '',
  335. hasQuotedMessage: !!pollId,
  336. botIds: [],
  337. timestamp: Math.floor(Date.now() / 1000),
  338. };
  339. messageQueue.push(event);
  340. if (messageQueue.length > MAX_QUEUE_SIZE) {
  341. messageQueue.shift();
  342. }
  343. }
  344. function rememberSentId(id) {
  345. recentlySentIds.remember(id);
  346. }
  347. // Receipts get their own bound: one reply to a large group brings a receipt per member, and in the
  348. // shared queue that burst evicted inbound messages still waiting for the next poll.
  349. const deliveryQueue = [];
  350. function enqueueDeliveryStatus(args) {
  351. const event = deliveryStatusEvent({ ...args, isOwnSend: id => recentlySentIds.has(id) });
  352. if (!event) return;
  353. deliveryQueue.push(event);
  354. if (deliveryQueue.length > MAX_QUEUE_SIZE) {
  355. deliveryQueue.shift();
  356. }
  357. }
  358. let sock = null;
  359. let connectionState = 'disconnected';
  360. function emitPairEvent(event) {
  361. if (!PAIR_JSON) return;
  362. try {
  363. writeJsonLine({ ts: Date.now(), ...event });
  364. } catch {}
  365. }
  366. const scheduleReconnect = createReconnectScheduler(() => startSocket());
  367. const getWAVersion = createVersionResolver(fetchLatestBaileysVersion);
  368. async function startSocket() {
  369. const { state, saveCreds } = await useMultiFileAuthState(SESSION_DIR);
  370. const version = await getWAVersion();
  371. sock = makeWASocket({
  372. ...(version ? { version } : {}),
  373. auth: state,
  374. logger,
  375. printQRInTerminal: false,
  376. browser: ['Hermes Agent', 'Chrome', '120.0'],
  377. syncFullHistory: false,
  378. markOnlineOnConnect: false,
  379. // Required for Baileys 7.x: without this, incoming messages that need
  380. // E2EE session re-establishment are silently dropped (msg.message === null)
  381. getMessage: async (key) => {
  382. // We don't maintain a message store, so return a placeholder.
  383. // This is enough for Baileys to complete the retry handshake.
  384. return { conversation: '' };
  385. },
  386. });
  387. sock.ev.on('creds.update', () => { saveCreds(); lidToPhone = buildLidMap(); });
  388. sock.ev.on('connection.update', (update) => {
  389. const { connection, lastDisconnect, qr } = update;
  390. if (qr) {
  391. if (PAIR_JSON) {
  392. emitPairEvent({ event: 'qr', qr });
  393. } else {
  394. console.log('\n📱 Scan this QR code with WhatsApp on your phone:\n');
  395. // The QR block is multi-line art; a stamp on its first row would skew it.
  396. qrcode.generate(qr, { small: true }, (code) => process.stdout.write(`${code}\n`));
  397. console.log('\nWaiting for scan...\n');
  398. }
  399. }
  400. if (connection === 'close') {
  401. const reason = new Boom(lastDisconnect?.error)?.output?.statusCode;
  402. connectionState = 'disconnected';
  403. if (reason === DisconnectReason.loggedOut) {
  404. emitPairEvent({ event: 'error', error: 'logged_out', reason });
  405. if (!PAIR_JSON) {
  406. console.log('❌ Logged out. Delete session and restart to re-authenticate.');
  407. }
  408. process.exit(1);
  409. } else {
  410. // 515 = restart requested (common after pairing). Always reconnect.
  411. emitPairEvent({ event: 'disconnected', reason });
  412. if (!PAIR_JSON) {
  413. if (reason === 515) {
  414. console.log('↻ WhatsApp requested restart (code 515). Reconnecting...');
  415. } else {
  416. console.log(`⚠️ Connection closed (reason: ${reason}). Reconnecting in 3s...`);
  417. }
  418. }
  419. scheduleReconnect(reason === 515 ? 1000 : 3000);
  420. }
  421. } else if (connection === 'open') {
  422. connectionState = 'connected';
  423. const connectedUser = sock?.user
  424. ? {
  425. id: sock.user.id || null,
  426. name: sock.user.name || sock.user.verifiedName || null,
  427. }
  428. : null;
  429. emitPairEvent({ event: 'connected', user: connectedUser });
  430. if (!PAIR_JSON) {
  431. console.log('✅ WhatsApp connected!');
  432. }
  433. if (PAIR_ONLY) {
  434. if (!PAIR_JSON) {
  435. console.log('✅ Pairing complete. Credentials saved.');
  436. }
  437. // Give Baileys a moment to flush creds, then exit cleanly
  438. setTimeout(() => process.exit(0), 2000);
  439. }
  440. }
  441. });
  442. sock.ev.on('message-receipt.update', (receipts) => {
  443. for (const { key, receipt } of receipts || []) enqueueDeliveryStatus({ key, receipt });
  444. });
  445. sock.ev.on('messages.update', async (updates) => {
  446. for (const { key, update } of updates || []) {
  447. if (update?.status !== undefined) enqueueDeliveryStatus({ key, update });
  448. if (!update?.pollUpdates) continue;
  449. const pollCreationId = key?.id || update.pollUpdates?.[0]?.pollCreationMessageKey?.id;
  450. const pollCreation = messageStore.get(pollCreationId);
  451. let aggregation = [];
  452. let pollUpdates = update.pollUpdates;
  453. try {
  454. if (pollCreation) {
  455. const meId = jidNormalizedUser(sock.user?.id || 'me');
  456. pollUpdates = update.pollUpdates.map(pollUpdate => (
  457. pollUpdateForAggregation({
  458. pollUpdateMessage: pollUpdate,
  459. pollUpdateMessageKey: pollUpdate.pollUpdateMessageKey,
  460. pollCreation,
  461. decryptPollVote,
  462. getKeyAuthor,
  463. meId,
  464. pollCreatorJids: [
  465. jidNormalizedUser(sock.user?.lid || ''),
  466. jidNormalizedUser(sock.user?.id || ''),
  467. getKeyAuthor(pollUpdate.pollCreationMessageKey || key, jidNormalizedUser(sock.user?.lid || '')),
  468. getKeyAuthor(pollUpdate.pollCreationMessageKey || key, jidNormalizedUser(sock.user?.id || '')),
  469. ],
  470. voterJids: [
  471. normalizeWhatsAppId(pollUpdate.pollUpdateMessageKey?.participant || ''),
  472. normalizeWhatsAppId(pollUpdate.pollUpdateMessageKey?.remoteJid || key?.remoteJid || ''),
  473. ],
  474. }) || pollUpdate
  475. ));
  476. aggregation = getAggregateVotesInPollMessage({
  477. message: pollCreation.message,
  478. pollUpdates,
  479. });
  480. }
  481. } catch (err) {
  482. console.warn('[bridge] failed to aggregate poll update:', err.message);
  483. }
  484. const selectedOptions = normalizePollUpdateOptions(aggregation, pollUpdates?.[0]);
  485. logPollUpdateDiagnostic({
  486. sourcePath: 'messages.update',
  487. pollId: pollCreationId,
  488. pollCreation,
  489. pollUpdates,
  490. selectedOptions,
  491. aggregation,
  492. });
  493. enqueuePollUpdateEvent({ key, update: { ...update, pollUpdates }, selectedOptions, aggregation });
  494. }
  495. });
  496. sock.ev.on('messages.upsert', async ({ messages, type }) => {
  497. // In self-chat mode, your own messages commonly arrive as 'append' rather
  498. // than 'notify'. Accept both and filter agent echo-backs below.
  499. if (type !== 'notify' && type !== 'append') return;
  500. const botIds = Array.from(new Set([
  501. normalizeWhatsAppId(sock.user?.id),
  502. normalizeWhatsAppId(sock.user?.lid),
  503. ].filter(Boolean)));
  504. for (const msg of messages) {
  505. if (!msg.message) continue;
  506. const chatId = msg.key.remoteJid;
  507. const senderId = msg.key.participant || chatId;
  508. // Baileys v7 carries the other form of the sender here (group: key.participantAlt,
  509. // DM: key.remoteJidAlt). A LID sender's phone twin makes a phone allowlist match with no
  510. // lid-mapping file yet (#63415, #72529) and is the identity Python sees, so first
  511. // contacts key the same session they will once the mapping exists.
  512. const senderAltId = normalizeWhatsAppId(msg.key.participantAlt || msg.key.remoteJidAlt || '');
  513. const resolvedSenderId = senderAltId.endsWith('@s.whatsapp.net') ? senderAltId : senderId;
  514. const isGroup = chatId.endsWith('@g.us');
  515. const senderNumber = resolvedSenderId.replace(/@.*/, '');
  516. emitDebugEvent({
  517. stage: 'upsert',
  518. type,
  519. fromMe: !!msg.key.fromMe,
  520. chatId: redactWhatsAppId(chatId),
  521. senderId: redactWhatsAppId(senderId),
  522. messageKeys: Object.keys(msg.message || {}),
  523. });
  524. // Handle fromMe messages based on mode
  525. let fromOwner = false;
  526. if (msg.key.fromMe) {
  527. if (isGroup || chatId.includes('status')) {
  528. emitDebugEvent({
  529. stage: 'ignored',
  530. reason: isGroup ? 'from_me_group' : 'from_me_status',
  531. chatId: redactWhatsAppId(chatId),
  532. });
  533. continue;
  534. }
  535. if (WHATSAPP_MODE === 'bot') {
  536. // Bot mode: separate bot number. fromMe inbound is either
  537. // (a) an echo of our own /send (recentlySentIds will catch it), or
  538. // (b) a message the owner typed from their own phone using the
  539. // linked-device session.
  540. //
  541. // We always drop (a). We drop (b) too unless the operator opts in
  542. // via WHATSAPP_FORWARD_OWNER_MESSAGES so existing deployments see
  543. // no behavior change. When opted in, we still gate on the
  544. // customer chatId allowlist — without that gate, any contact
  545. // the owner replied to would leak into Hermes and trigger
  546. // implicit handover. See `owner_message_gate.js`.
  547. const decision = classifyOwnerMessageGate({
  548. fromMe: true,
  549. fromOwnerEnabled: FORWARD_OWNER_MESSAGES,
  550. recentlySent: recentlySentIds,
  551. allowlistMatches: (id) => matchesAllowedUser(id, ALLOWED_USERS, SESSION_DIR),
  552. messageId: msg.key.id,
  553. chatId,
  554. });
  555. if (decision.action === 'drop_echo') continue;
  556. if (decision.action === 'drop_disabled') continue;
  557. if (decision.action === 'drop_allowlist') {
  558. try {
  559. writeJsonLine({
  560. event: 'ignored',
  561. reason: 'allowlist_mismatch_owner_chat',
  562. chatId,
  563. senderId,
  564. });
  565. } catch {}
  566. continue;
  567. }
  568. fromOwner = true;
  569. } else {
  570. // Self-chat mode: only allow messages in the user's own self-chat.
  571. // WhatsApp now uses LID (Linked Identity Device) format: 67427329167522@lid
  572. // AND classic format: 34652029134@s.whatsapp.net
  573. // sock.user has both: { id: "number:10@s.whatsapp.net", lid: "lid_number:10@lid" }
  574. const myNumber = (sock.user?.id || '').replace(/:.*@/, '@').replace(/@.*/, '');
  575. const myLid = (sock.user?.lid || '').replace(/:.*@/, '@').replace(/@.*/, '');
  576. const chatNumber = chatId.replace(/@.*/, '');
  577. const isSelfChat = (myNumber && chatNumber === myNumber) || (myLid && chatNumber === myLid);
  578. emitDebugEvent({
  579. stage: 'self_chat_check',
  580. matched: !!isSelfChat,
  581. chatId: redactWhatsAppId(chatId),
  582. accountId: redactWhatsAppId(sock.user?.id),
  583. accountLid: redactWhatsAppId(sock.user?.lid),
  584. });
  585. if (!isSelfChat) {
  586. emitDebugEvent({
  587. stage: 'ignored',
  588. reason: 'self_chat_mismatch',
  589. chatId: redactWhatsAppId(chatId),
  590. senderId: redactWhatsAppId(senderId),
  591. });
  592. continue;
  593. }
  594. }
  595. }
  596. // Handle !fromMe messages (from other people) based on mode.
  597. // Self-chat mode only responds to the user's own messages to
  598. // themselves — stranger DMs / group pings must never reach the
  599. // Python gateway, otherwise a pairing-code reply fires in response
  600. // to arbitrary incoming messages (#8389).
  601. if (!msg.key.fromMe) {
  602. if (WHATSAPP_MODE === 'self-chat') {
  603. try {
  604. writeJsonLine({
  605. event: 'ignored',
  606. reason: 'self_chat_mode_rejects_non_self',
  607. chatId,
  608. senderId,
  609. });
  610. } catch {}
  611. continue;
  612. }
  613. const intakeAllowed = isGroup
  614. ? matchesInboundWhatsAppGroup({
  615. chatId,
  616. groupPolicy: WHATSAPP_GROUP_POLICY,
  617. groupAllowedUsers: GROUP_ALLOWED_USERS,
  618. sessionDir: SESSION_DIR,
  619. })
  620. : WHATSAPP_DM_POLICY === 'pairing'
  621. || matchesAllowedSender(senderId, senderAltId, ALLOWED_USERS, SESSION_DIR);
  622. if (!intakeAllowed) {
  623. try {
  624. writeJsonLine({
  625. event: 'ignored',
  626. reason: isGroup ? 'group_policy_rejected' : 'allowlist_mismatch',
  627. chatId,
  628. senderId,
  629. senderAltId,
  630. });
  631. } catch {}
  632. continue;
  633. }
  634. }
  635. const messageContent = getMessageContent(msg);
  636. if (messageContent.pollUpdateMessage) {
  637. const pollUpdateMessage = messageContent.pollUpdateMessage;
  638. const pollKey = pollUpdateMessage.pollCreationMessageKey || {
  639. id: pollUpdateMessage.key?.id || msg.key.id,
  640. remoteJid: chatId,
  641. participant: senderId,
  642. };
  643. const pollCreation = messageStore.get(pollKey.id);
  644. let aggregation = [];
  645. let pollUpdates = [pollUpdateMessage];
  646. try {
  647. if (pollCreation) {
  648. const meId = jidNormalizedUser(sock.user?.id || 'me');
  649. const pollUpdate = pollUpdateForAggregation({
  650. pollUpdateMessage,
  651. pollUpdateMessageKey: msg.key,
  652. pollCreation,
  653. decryptPollVote,
  654. getKeyAuthor,
  655. meId,
  656. pollCreatorJids: [
  657. jidNormalizedUser(sock.user?.lid || ''),
  658. jidNormalizedUser(sock.user?.id || ''),
  659. getKeyAuthor(pollUpdateMessage.pollCreationMessageKey || pollKey, jidNormalizedUser(sock.user?.lid || '')),
  660. getKeyAuthor(pollUpdateMessage.pollCreationMessageKey || pollKey, jidNormalizedUser(sock.user?.id || '')),
  661. ],
  662. voterJids: [
  663. normalizeWhatsAppId(msg.key?.participant || ''),
  664. normalizeWhatsAppId(msg.key?.remoteJid || chatId || ''),
  665. normalizeWhatsAppId(senderId || ''),
  666. ],
  667. });
  668. if (pollUpdate) pollUpdates = [pollUpdate];
  669. aggregation = getAggregateVotesInPollMessage({
  670. message: pollCreation.message,
  671. pollUpdates,
  672. });
  673. }
  674. } catch (err) {
  675. console.warn('[bridge] failed to aggregate poll upsert:', err.message);
  676. }
  677. const selectedOptions = normalizePollUpdateOptions(aggregation, pollUpdates[0]);
  678. logPollUpdateDiagnostic({
  679. sourcePath: 'messages.upsert',
  680. pollId: pollKey.id,
  681. pollCreation,
  682. pollUpdates,
  683. selectedOptions,
  684. aggregation,
  685. });
  686. enqueuePollUpdateEvent({
  687. key: { ...pollKey, remoteJid: pollKey.remoteJid || chatId, participant: pollKey.participant || senderId },
  688. update: { pollUpdates },
  689. selectedOptions,
  690. aggregation,
  691. });
  692. continue;
  693. }
  694. const event = await extractBridgeEvent({
  695. msg,
  696. chatId,
  697. senderId: resolvedSenderId,
  698. senderNumber,
  699. botIds,
  700. isGroup,
  701. downloadMedia: async (mediaMsg) => downloadMediaMessage(mediaMsg, 'buffer', {}, { logger, reuploadRequest: sock.updateMediaMessage }),
  702. cacheDirs: {
  703. image: IMAGE_CACHE_DIR,
  704. document: DOCUMENT_CACHE_DIR,
  705. audio: AUDIO_CACHE_DIR,
  706. },
  707. lookupQuotedMedia: (quotedChatId, quotedMessageId) => quotedMediaCache.get(quotedChatId, quotedMessageId),
  708. });
  709. event.fromOwner = fromOwner;
  710. // Ignore Hermes' own reply messages in self-chat mode to avoid loops.
  711. if (msg.key.fromMe && ((REPLY_PREFIX && event.body.startsWith(REPLY_PREFIX)) || recentlySentIds.has(msg.key.id))) {
  712. if (WHATSAPP_DEBUG) {
  713. emitDebugEvent({
  714. stage: 'ignored',
  715. reason: 'agent_echo',
  716. chatId: redactWhatsAppId(chatId),
  717. messageId: msg.key.id,
  718. });
  719. }
  720. continue;
  721. }
  722. // Skip empty messages (but not a bare quote-reply whose own text/media
  723. // is empty when the quoted message resolved to cached media).
  724. if (!event.body && !event.hasMedia && !event.quotedMediaUrls.length) {
  725. emitDebugEvent({
  726. stage: 'ignored',
  727. reason: 'empty',
  728. chatId: redactWhatsAppId(chatId),
  729. messageKeys: Object.keys(msg.message || {}),
  730. });
  731. continue;
  732. }
  733. messageStore.remember(msg);
  734. // Remember this message's already-downloaded media/text so a later
  735. // reply to it (even uncaptioned media) can resolve the original
  736. // content instead of seeing only a stripped-down quoted-message stub.
  737. quotedMediaCache.remember(chatId, msg.key.id, {
  738. body: event.body,
  739. hasMedia: event.hasMedia,
  740. mediaType: event.mediaType,
  741. mediaUrls: event.mediaUrls,
  742. });
  743. messageQueue.push(event);
  744. emitDebugEvent({
  745. stage: 'queued',
  746. chatId: redactWhatsAppId(chatId),
  747. senderId: redactWhatsAppId(senderId),
  748. fromOwner: !!fromOwner,
  749. bodyLength: event.body.length,
  750. hasMedia: event.hasMedia,
  751. mediaType: event.mediaType,
  752. queueLength: messageQueue.length,
  753. });
  754. if (messageQueue.length > MAX_QUEUE_SIZE) {
  755. messageQueue.shift();
  756. }
  757. }
  758. });
  759. }
  760. // HTTP server
  761. const app = express();
  762. app.use(express.json());
  763. // Host-header validation — defends against DNS rebinding.
  764. // The bridge binds loopback-only (127.0.0.1) but a victim browser on
  765. // the same machine could be tricked into fetching from an attacker
  766. // hostname that TTL-flips to 127.0.0.1. Reject any request whose Host
  767. // header doesn't resolve to a loopback alias.
  768. // See GHSA-ppp5-vxwm-4cf7.
  769. const _ACCEPTED_HOST_VALUES = new Set([
  770. 'localhost',
  771. '127.0.0.1',
  772. '[::1]',
  773. '::1',
  774. ]);
  775. app.use((req, res, next) => {
  776. const raw = (req.headers.host || '').trim();
  777. if (!raw) {
  778. return res.status(400).json({ error: 'Missing Host header' });
  779. }
  780. // Strip port suffix: "localhost:3000" → "localhost"
  781. const hostOnly = (raw.includes(':')
  782. ? raw.substring(0, raw.lastIndexOf(':'))
  783. : raw
  784. ).replace(/^\[|\]$/g, '').toLowerCase();
  785. if (!_ACCEPTED_HOST_VALUES.has(hostOnly)) {
  786. return res.status(400).json({
  787. error: 'Invalid Host header. Bridge accepts loopback hosts only.',
  788. });
  789. }
  790. next();
  791. });
  792. // Poll for new messages (long-poll style)
  793. app.get('/messages', (req, res) => {
  794. const msgs = messageQueue.splice(0, messageQueue.length).concat(deliveryQueue.splice(0, deliveryQueue.length));
  795. res.json(msgs);
  796. });
  797. // Send a message
  798. app.post('/send', async (req, res) => {
  799. if (!sock || connectionState !== 'connected') {
  800. return res.status(503).json({ error: 'Not connected to WhatsApp' });
  801. }
  802. const { chatId, message, replyTo, mentions } = req.body;
  803. if (!chatId || !message) {
  804. return res.status(400).json({ error: 'chatId and message are required' });
  805. }
  806. try {
  807. const chunks = splitLongMessage(formatOutgoingMessage(message));
  808. const messageIds = [];
  809. for (let i = 0; i < chunks.length; i += 1) {
  810. const { content: payload, options } = buildTextSendPayload(chunks[i], {
  811. chatId,
  812. replyTo: i === 0 ? replyTo : undefined,
  813. mentions: i === 0 ? mentions : undefined,
  814. messageStore,
  815. });
  816. const sent = await sendWithTimeout(chatId, payload, options);
  817. trackSentMessageId(sent);
  818. messageStore.remember(sent);
  819. if (sent?.key?.id) messageIds.push(sent.key.id);
  820. if (chunks.length > 1 && i < chunks.length - 1) {
  821. await sleep(CHUNK_DELAY_MS);
  822. }
  823. }
  824. res.json({
  825. success: true,
  826. messageId: messageIds[messageIds.length - 1],
  827. messageIds,
  828. });
  829. } catch (err) {
  830. res.status(500).json({ error: err.message });
  831. }
  832. });
  833. // Edit a previously sent message
  834. app.post('/edit', async (req, res) => {
  835. if (!sock || connectionState !== 'connected') {
  836. return res.status(503).json({ error: 'Not connected to WhatsApp' });
  837. }
  838. const { chatId, messageId, message } = req.body;
  839. if (!chatId || !messageId || !message) {
  840. return res.status(400).json({ error: 'chatId, messageId, and message are required' });
  841. }
  842. try {
  843. const key = { id: messageId, fromMe: true, remoteJid: chatId };
  844. const chunks = splitLongMessage(formatOutgoingMessage(message));
  845. const messageIds = [];
  846. await sendWithTimeout(chatId, { text: chunks[0], edit: key });
  847. if (chunks.length > 1) {
  848. for (let i = 1; i < chunks.length; i += 1) {
  849. const sent = await sendWithTimeout(chatId, { text: chunks[i] });
  850. trackSentMessageId(sent);
  851. if (sent?.key?.id) messageIds.push(sent.key.id);
  852. if (i < chunks.length - 1) {
  853. await sleep(CHUNK_DELAY_MS);
  854. }
  855. }
  856. }
  857. res.json({ success: true, messageIds });
  858. } catch (err) {
  859. res.status(500).json({ error: err.message });
  860. }
  861. });
  862. // Send media (image, video, document) natively
  863. app.post('/send-media', async (req, res) => {
  864. if (!sock || connectionState !== 'connected') {
  865. return res.status(503).json({ error: 'Not connected to WhatsApp' });
  866. }
  867. const { chatId, filePath, mediaType, caption, fileName, mentions } = req.body;
  868. if (!chatId || !filePath) {
  869. return res.status(400).json({ error: 'chatId and filePath are required' });
  870. }
  871. try {
  872. if (!existsSync(filePath)) {
  873. return res.status(404).json({ error: `File not found: ${filePath}` });
  874. }
  875. const buffer = readFileSync(filePath);
  876. const ext = filePath.toLowerCase().split('.').pop();
  877. const type = mediaType || inferMediaType(ext);
  878. let msgPayload;
  879. switch (type) {
  880. case 'image':
  881. if (ext === 'gif') {
  882. // WhatsApp's native animated-GIF UX is an MP4 video payload with
  883. // gifPlayback=true. Convert when ffmpeg is available; otherwise fall
  884. // back to a truthful image/gif send instead of mislabeling GIF bytes
  885. // as video/mp4.
  886. let tmpGifMp4 = null;
  887. try {
  888. tmpGifMp4 = path.join(tmpdir(), `hermes_gif_${randomBytes(6).toString('hex')}.mp4`);
  889. execFileSync(
  890. 'ffmpeg',
  891. ['-y', '-i', filePath, '-movflags', 'faststart', '-pix_fmt', 'yuv420p', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', tmpGifMp4],
  892. { timeout: 30000, stdio: 'pipe' }
  893. );
  894. msgPayload = {
  895. video: readFileSync(tmpGifMp4),
  896. caption: caption || undefined,
  897. mimetype: 'video/mp4',
  898. gifPlayback: true,
  899. };
  900. } catch (gifErr) {
  901. console.warn('[bridge] gif conversion failed, sending as image/gif:', gifErr.message);
  902. msgPayload = mediaPayloadForFile({ buffer, filePath, mediaType: type, caption, fileName });
  903. } finally {
  904. try { if (tmpGifMp4 && existsSync(tmpGifMp4)) unlinkSync(tmpGifMp4); } catch (_) {}
  905. }
  906. } else {
  907. msgPayload = mediaPayloadForFile({ buffer, filePath, mediaType: type, caption, fileName });
  908. }
  909. break;
  910. case 'video':
  911. msgPayload = mediaPayloadForFile({ buffer, filePath, mediaType: type, caption, fileName });
  912. break;
  913. case 'audio': {
  914. // WhatsApp only renders a native voice bubble (ptt) when the file is ogg/opus.
  915. // If the caller passes mp3, wav, m4a etc. (e.g. from Edge TTS / NeuTTS),
  916. // silently convert to ogg/opus via ffmpeg so ptt is always honoured.
  917. let audioBuffer = buffer;
  918. let audioExt = ext;
  919. const needsConversion = !['ogg', 'opus'].includes(ext);
  920. let tmpPath = null;
  921. if (needsConversion) {
  922. tmpPath = path.join(tmpdir(), `hermes_voice_${randomBytes(6).toString('hex')}.ogg`);
  923. try {
  924. execFileSync(
  925. 'ffmpeg',
  926. ['-y', '-i', filePath, '-ar', '48000', '-ac', '1', '-c:a', 'libopus', tmpPath],
  927. { timeout: 30000, stdio: 'pipe' }
  928. );
  929. audioBuffer = readFileSync(tmpPath);
  930. audioExt = 'ogg';
  931. } catch (convErr) {
  932. // ffmpeg not available or conversion failed — fall back to original format
  933. console.warn('[bridge] ffmpeg conversion failed, sending as file attachment:', convErr.message);
  934. } finally {
  935. try { if (tmpPath && existsSync(tmpPath)) unlinkSync(tmpPath); } catch (_) {}
  936. }
  937. }
  938. const audioMime = (audioExt === 'ogg' || audioExt === 'opus') ? 'audio/ogg; codecs=opus' : 'audio/mpeg';
  939. msgPayload = { audio: audioBuffer, mimetype: audioMime, ptt: audioExt === 'ogg' || audioExt === 'opus' };
  940. break;
  941. }
  942. case 'document':
  943. default:
  944. msgPayload = mediaPayloadForFile({ buffer, filePath, mediaType: 'document', caption, fileName });
  945. break;
  946. }
  947. msgPayload = addMentions(msgPayload, mentions);
  948. const sent = await sendWithTimeout(chatId, msgPayload);
  949. trackSentMessageId(sent);
  950. messageStore.remember(sent);
  951. res.json({ success: true, messageId: sent?.key?.id });
  952. } catch (err) {
  953. res.status(500).json({ error: err.message });
  954. }
  955. });
  956. // Send poll primitive. Approval UX is intentionally not wired here; gateway
  957. // approvals need text fallback and explicit confirmation semantics above this
  958. // low-level transport helper.
  959. app.post('/send-poll', async (req, res) => {
  960. if (!sock || connectionState !== 'connected') {
  961. return res.status(503).json({ error: 'Not connected to WhatsApp' });
  962. }
  963. const { chatId, question, options, selectableCount } = req.body;
  964. if (!chatId || !question || !Array.isArray(options)) {
  965. return res.status(400).json({ error: 'chatId, question, and options are required' });
  966. }
  967. try {
  968. const payload = buildPollPayload({ question, options, selectableCount });
  969. const sent = await sendWithTimeout(chatId, payload);
  970. trackSentMessageId(sent);
  971. rememberSentMessage(sent, payload);
  972. res.json({ success: true, messageId: sent?.key?.id });
  973. } catch (err) {
  974. res.status(400).json({ error: err.message });
  975. }
  976. });
  977. // Send native WhatsApp location pin
  978. app.post('/send-location', async (req, res) => {
  979. if (!sock || connectionState !== 'connected') {
  980. return res.status(503).json({ error: 'Not connected to WhatsApp' });
  981. }
  982. const { chatId, latitude, longitude, name, address } = req.body;
  983. if (!chatId || latitude === undefined || longitude === undefined) {
  984. return res.status(400).json({ error: 'chatId, latitude, and longitude are required' });
  985. }
  986. try {
  987. const payload = buildLocationPayload({ latitude, longitude, name, address });
  988. const sent = await sendWithTimeout(chatId, payload);
  989. trackSentMessageId(sent);
  990. messageStore.remember(sent);
  991. res.json({ success: true, messageId: sent?.key?.id });
  992. } catch (err) {
  993. res.status(400).json({ error: err.message });
  994. }
  995. });
  996. // Typing indicator
  997. app.post('/typing', async (req, res) => {
  998. if (!sock || connectionState !== 'connected') {
  999. return res.status(503).json({ error: 'Not connected' });
  1000. }
  1001. const { chatId } = req.body;
  1002. if (!chatId) return res.status(400).json({ error: 'chatId required' });
  1003. try {
  1004. await sock.sendPresenceUpdate('composing', chatId);
  1005. res.json({ success: true });
  1006. } catch (err) {
  1007. res.json({ success: false });
  1008. }
  1009. });
  1010. // Mark an inbound message as read only after the Python adapter has accepted
  1011. // it through the authoritative DM/group/mention intake policy.
  1012. app.post('/read', async (req, res) => {
  1013. if (!sock || connectionState !== 'connected') {
  1014. return res.status(503).json({ error: 'Not connected' });
  1015. }
  1016. const receiptKeys = inboundReadReceiptKeys({
  1017. key: req.body?.key,
  1018. enabled: SEND_READ_RECEIPTS,
  1019. });
  1020. if (receiptKeys.length === 0) {
  1021. return res.json({ success: true, marked: false });
  1022. }
  1023. try {
  1024. await sock.readMessages(receiptKeys);
  1025. return res.json({ success: true, marked: true });
  1026. } catch (err) {
  1027. console.warn('[bridge] failed to send read receipt:', err.message);
  1028. return res.status(500).json({ error: 'Failed to send read receipt' });
  1029. }
  1030. });
  1031. // Chat info
  1032. app.get('/chat/:id', async (req, res) => {
  1033. const chatId = req.params.id;
  1034. const isGroup = chatId.endsWith('@g.us');
  1035. if (isGroup && sock) {
  1036. try {
  1037. const metadata = await sock.groupMetadata(chatId);
  1038. return res.json({
  1039. name: metadata.subject,
  1040. isGroup: true,
  1041. participants: metadata.participants.map(p => p.id),
  1042. });
  1043. } catch {
  1044. // Fall through to default
  1045. }
  1046. }
  1047. res.json({
  1048. name: chatId.replace(/@.*/, ''),
  1049. isGroup,
  1050. participants: [],
  1051. });
  1052. });
  1053. // Health check
  1054. app.get('/health', (req, res) => {
  1055. res.json({
  1056. status: connectionState,
  1057. queueLength: messageQueue.length,
  1058. uptime: process.uptime(),
  1059. scriptHash: SCRIPT_HASH,
  1060. sendReadReceipts: SEND_READ_RECEIPTS,
  1061. // path.resolve, not realpath: the adapter compares against os.path.abspath, which keeps symlinks.
  1062. session: path.resolve(SESSION_DIR),
  1063. capabilities: { outboundMentions: true },
  1064. });
  1065. });
  1066. // Start
  1067. if (PAIR_ONLY) {
  1068. // Pair-only mode: just connect, show QR, save creds, exit. No HTTP server.
  1069. if (PAIR_JSON) {
  1070. emitPairEvent({ event: 'started', session: SESSION_DIR });
  1071. } else {
  1072. console.log('📱 WhatsApp pairing mode');
  1073. console.log(`📁 Session: ${SESSION_DIR}`);
  1074. console.log();
  1075. }
  1076. startSocket().catch((err) => {
  1077. emitPairEvent({ event: 'error', error: err?.message || String(err) });
  1078. if (!PAIR_JSON) {
  1079. console.error(err);
  1080. }
  1081. process.exit(1);
  1082. });
  1083. } else {
  1084. const server = app.listen(PORT, '127.0.0.1', () => {
  1085. console.log(`🌉 WhatsApp bridge listening on port ${PORT} (mode: ${WHATSAPP_MODE})`);
  1086. console.log(`📁 Session stored in: ${SESSION_DIR}`);
  1087. if (ALLOWED_USERS.size > 0) {
  1088. console.log(`🔒 Allowed users: ${Array.from(ALLOWED_USERS).join(', ')}`);
  1089. } else if (WHATSAPP_MODE === 'self-chat') {
  1090. console.log(`🔒 Self-chat mode — only your own messages to yourself are processed.`);
  1091. } else if (WHATSAPP_MODE === 'bot' && WHATSAPP_DM_POLICY === 'pairing') {
  1092. console.log(`🤝 WHATSAPP_DM_POLICY=pairing — unknown DMs are forwarded for gateway pairing.`);
  1093. } else {
  1094. console.log(`🔒 No WHATSAPP_ALLOWED_USERS set — incoming messages are rejected.`);
  1095. console.log(` Set WHATSAPP_ALLOWED_USERS=<phone> to authorize specific users,`);
  1096. console.log(` or WHATSAPP_ALLOWED_USERS=* for an explicit open bot.`);
  1097. }
  1098. if (WHATSAPP_MODE === 'bot' && FORWARD_OWNER_MESSAGES) {
  1099. console.log(`👤 WHATSAPP_FORWARD_OWNER_MESSAGES=true — owner-typed messages will be forwarded with fromOwner:true`);
  1100. }
  1101. console.log();
  1102. scheduleReconnect(0);
  1103. });
  1104. // Without this handler an EADDRINUSE (an old bridge that has not released the port yet) crashes
  1105. // with a bare stack trace; the adapter's reconnect loop retried blind. Fail loudly and fast.
  1106. server.on('error', (err) => {
  1107. if (err && err.code === 'EADDRINUSE') {
  1108. console.error(`FATAL: port ${PORT} already in use on 127.0.0.1 — another bridge or process is listening there.`);
  1109. } else {
  1110. console.error(`FATAL: bridge HTTP server error: ${err && err.message ? err.message : err}`);
  1111. }
  1112. process.exit(1);
  1113. });
  1114. }