|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * OpenCoworker WhatsApp Personal bridge — EXPERIMENTAL, use at your own risk. |
| 4 | + * |
| 5 | + * Connects to WhatsApp as a personal account over the unofficial WhatsApp Web protocol |
| 6 | + * (Baileys) and exposes a localhost-only HTTP API for the Python adapter. Architecture |
| 7 | + * modeled on the Hermes Agent bridge (MIT, (c) 2025 Nous Research), reimplemented with a |
| 8 | + * smaller surface and no Express dependency. |
| 9 | + * |
| 10 | + * Endpoints: |
| 11 | + * GET /health -> { ok, status, me } status: starting|pairing|open|closed |
| 12 | + * GET /qr -> { qr } raw QR string while pairing, else null |
| 13 | + * GET /messages -> { messages: [...] } drains the inbound queue (long-poll ~25s) |
| 14 | + * POST /send -> { ok, messageId } body: { chatId, text } |
| 15 | + * |
| 16 | + * Usage: node bridge.js --port 3941 --session <dir> --mode self-chat|bot |
| 17 | + */ |
| 18 | + |
| 19 | +import http from "node:http"; |
| 20 | +import { mkdirSync } from "node:fs"; |
| 21 | + |
| 22 | +import makeWASocket, { |
| 23 | + useMultiFileAuthState, |
| 24 | + fetchLatestBaileysVersion, |
| 25 | + DisconnectReason, |
| 26 | +} from "@whiskeysockets/baileys"; |
| 27 | + |
| 28 | +const args = process.argv.slice(2); |
| 29 | +const getArg = (name, dflt) => { |
| 30 | + const i = args.indexOf(`--${name}`); |
| 31 | + return i !== -1 && args[i + 1] ? args[i + 1] : dflt; |
| 32 | +}; |
| 33 | + |
| 34 | +const PORT = parseInt(getArg("port", "3941"), 10); |
| 35 | +const SESSION_DIR = getArg("session", "./wa-session"); |
| 36 | +const MODE = getArg("mode", "self-chat"); // "self-chat": only your message-yourself thread |
| 37 | +const MAX_TEXT = 4096; |
| 38 | +const QUEUE_CAP = 500; |
| 39 | +const LONG_POLL_MS = 25000; |
| 40 | + |
| 41 | +mkdirSync(SESSION_DIR, { recursive: true }); |
| 42 | + |
| 43 | +let sock = null; |
| 44 | +let status = "starting"; |
| 45 | +let qrString = null; |
| 46 | +let meJid = null; |
| 47 | +const inbound = []; // queued message dicts for the Python adapter |
| 48 | +const sentByBridge = new Set(); // ids of our own sends, to drop echoes in self-chat mode |
| 49 | +let waiters = []; // pending long-poll resolvers |
| 50 | + |
| 51 | +const bareJid = (jid) => String(jid || "").split(":")[0].split("@")[0]; |
| 52 | + |
| 53 | +function pushInbound(msg) { |
| 54 | + inbound.push(msg); |
| 55 | + if (inbound.length > QUEUE_CAP) inbound.shift(); |
| 56 | + for (const w of waiters.splice(0)) w(); |
| 57 | +} |
| 58 | + |
| 59 | +function mapMessage(m) { |
| 60 | + const text = |
| 61 | + m.message?.conversation || |
| 62 | + m.message?.extendedTextMessage?.text || |
| 63 | + m.message?.imageMessage?.caption || |
| 64 | + ""; |
| 65 | + if (!text) return null; |
| 66 | + const chatId = m.key.remoteJid || ""; |
| 67 | + if (chatId === "status@broadcast") return null; |
| 68 | + const fromMe = Boolean(m.key.fromMe); |
| 69 | + const selfChat = bareJid(chatId) === bareJid(meJid); |
| 70 | + if (MODE === "self-chat" && !selfChat) return null; |
| 71 | + // In self-chat the user's own messages are fromMe — keep them, but never our own sends. |
| 72 | + if (fromMe && (!selfChat || sentByBridge.has(m.key.id))) return null; |
| 73 | + return { |
| 74 | + id: m.key.id || "", |
| 75 | + chatId, |
| 76 | + senderId: bareJid(fromMe ? meJid : m.key.participant || chatId), |
| 77 | + senderName: m.pushName || "", |
| 78 | + isGroup: chatId.endsWith("@g.us"), |
| 79 | + text, |
| 80 | + timestamp: Number(m.messageTimestamp) || 0, |
| 81 | + }; |
| 82 | +} |
| 83 | + |
| 84 | +async function startSocket() { |
| 85 | + const { state, saveCreds } = await useMultiFileAuthState(SESSION_DIR); |
| 86 | + const { version } = await fetchLatestBaileysVersion().catch(() => ({ version: undefined })); |
| 87 | + sock = makeWASocket({ auth: state, version, printQRInTerminal: false }); |
| 88 | + |
| 89 | + sock.ev.on("creds.update", saveCreds); |
| 90 | + sock.ev.on("connection.update", ({ connection, lastDisconnect, qr }) => { |
| 91 | + if (qr) { |
| 92 | + qrString = qr; |
| 93 | + status = "pairing"; |
| 94 | + console.log("[bridge] pairing required — fetch GET /qr and scan it in WhatsApp"); |
| 95 | + } |
| 96 | + if (connection === "open") { |
| 97 | + qrString = null; |
| 98 | + status = "open"; |
| 99 | + meJid = sock.user?.id || null; |
| 100 | + console.log(`[bridge] connected as ${meJid}`); |
| 101 | + } |
| 102 | + if (connection === "close") { |
| 103 | + const code = lastDisconnect?.error?.output?.statusCode; |
| 104 | + if (code === DisconnectReason.loggedOut) { |
| 105 | + status = "closed"; |
| 106 | + console.error("[bridge] logged out — delete the session dir and re-pair"); |
| 107 | + } else { |
| 108 | + status = "starting"; |
| 109 | + console.log(`[bridge] connection closed (code ${code}) — reconnecting`); |
| 110 | + setTimeout(() => startSocket().catch((e) => console.error("[bridge]", e)), 2000); |
| 111 | + } |
| 112 | + } |
| 113 | + }); |
| 114 | + sock.ev.on("messages.upsert", ({ messages, type }) => { |
| 115 | + if (type !== "notify") return; |
| 116 | + for (const m of messages) { |
| 117 | + const mapped = mapMessage(m); |
| 118 | + if (mapped) pushInbound(mapped); |
| 119 | + } |
| 120 | + }); |
| 121 | +} |
| 122 | + |
| 123 | +const json = (res, code, body) => { |
| 124 | + res.writeHead(code, { "content-type": "application/json" }); |
| 125 | + res.end(JSON.stringify(body)); |
| 126 | +}; |
| 127 | + |
| 128 | +const readBody = (req) => |
| 129 | + new Promise((resolve, reject) => { |
| 130 | + let data = ""; |
| 131 | + req.on("data", (c) => { |
| 132 | + data += c; |
| 133 | + if (data.length > 1e6) reject(new Error("body too large")); |
| 134 | + }); |
| 135 | + req.on("end", () => resolve(data)); |
| 136 | + req.on("error", reject); |
| 137 | + }); |
| 138 | + |
| 139 | +const server = http.createServer(async (req, res) => { |
| 140 | + const url = new URL(req.url, `http://127.0.0.1:${PORT}`); |
| 141 | + try { |
| 142 | + if (req.method === "GET" && url.pathname === "/health") { |
| 143 | + return json(res, 200, { ok: true, status, me: bareJid(meJid) || null }); |
| 144 | + } |
| 145 | + if (req.method === "GET" && url.pathname === "/qr") { |
| 146 | + return json(res, 200, { qr: qrString }); |
| 147 | + } |
| 148 | + if (req.method === "GET" && url.pathname === "/messages") { |
| 149 | + if (!inbound.length) { |
| 150 | + await new Promise((resolve) => { |
| 151 | + const t = setTimeout(resolve, LONG_POLL_MS); |
| 152 | + waiters.push(() => { |
| 153 | + clearTimeout(t); |
| 154 | + resolve(); |
| 155 | + }); |
| 156 | + }); |
| 157 | + } |
| 158 | + return json(res, 200, { messages: inbound.splice(0) }); |
| 159 | + } |
| 160 | + if (req.method === "POST" && url.pathname === "/send") { |
| 161 | + const { chatId, text } = JSON.parse((await readBody(req)) || "{}"); |
| 162 | + if (!chatId || !text) return json(res, 400, { ok: false, error: "chatId and text required" }); |
| 163 | + if (status !== "open") return json(res, 503, { ok: false, error: `not connected (${status})` }); |
| 164 | + const sent = await sock.sendMessage(String(chatId), { text: String(text).slice(0, MAX_TEXT) }); |
| 165 | + const id = sent?.key?.id || ""; |
| 166 | + if (id) { |
| 167 | + sentByBridge.add(id); |
| 168 | + if (sentByBridge.size > 1000) sentByBridge.delete(sentByBridge.values().next().value); |
| 169 | + } |
| 170 | + return json(res, 200, { ok: true, messageId: id }); |
| 171 | + } |
| 172 | + return json(res, 404, { ok: false, error: "not found" }); |
| 173 | + } catch (e) { |
| 174 | + return json(res, 500, { ok: false, error: String(e?.message || e) }); |
| 175 | + } |
| 176 | +}); |
| 177 | + |
| 178 | +// localhost only — never expose the bridge beyond the machine |
| 179 | +server.listen(PORT, "127.0.0.1", () => { |
| 180 | + console.log(`[bridge] listening on 127.0.0.1:${PORT} (mode=${MODE})`); |
| 181 | + startSocket().catch((e) => { |
| 182 | + console.error("[bridge] fatal:", e); |
| 183 | + process.exit(1); |
| 184 | + }); |
| 185 | +}); |
| 186 | + |
| 187 | +for (const sig of ["SIGINT", "SIGTERM"]) { |
| 188 | + process.on(sig, () => { |
| 189 | + try { |
| 190 | + server.close(); |
| 191 | + sock?.end?.(undefined); |
| 192 | + } finally { |
| 193 | + process.exit(0); |
| 194 | + } |
| 195 | + }); |
| 196 | +} |
0 commit comments