Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(security): bind WhatsApp bridge to localhost + optional token auth
Re-binfd7e477b1886
diff --git a/SECURITY.md b/SECURITY.mdindex ac15ba412..af3448c44 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -95,8 +95,8 @@ File operations have path traversal protection, but:- Consider using a firewall to restrict outbound connections if needed**WhatsApp Bridge:**-- The bridge runs on `localhost:3001` by default-- If exposing to network, use proper authentication and TLS+- The bridge binds to `127.0.0.1:3001` (localhost only, not accessible from external network)+- Set `bridgeToken` in config to enable shared-secret authentication between Python and Node.js- Keep authentication data in `~/.nanobot/whatsapp-auth` secure (mode 0700)### 6. Dependency Security@@ -224,7 +224,7 @@ If you suspect a security breach:β **Secure Communication**- HTTPS for all external API calls- TLS for Telegram API-- WebSocket security for WhatsApp bridge+- WhatsApp bridge: localhost-only binding + optional token auth## Known Limitationsdiff --git a/bridge/src/index.ts b/bridge/src/index.tsindex 8db63ef58..e8f3db9b9 100644--- a/bridge/src/index.ts+++ b/bridge/src/index.ts@@ -25,11 +25,12 @@ import { join } from 'path';const PORT = parseInt(process.env.BRIDGE_PORT || '3001', 10);const AUTH_DIR = process.env.AUTH_DIR || join(homedir(), '.nanobot', 'whatsapp-auth');+const TOKEN = process.env.BRIDGE_TOKEN || undefined;console.log('π nanobot WhatsApp Bridge');console.log('========================\n');-const server = new BridgeServer(PORT, AUTH_DIR);+const server = new BridgeServer(PORT, AUTH_DIR, TOKEN);// Handle graceful shutdownprocess.on('SIGINT', async () => {diff --git a/bridge/src/server.ts b/bridge/src/server.tsindex c6fd59932..7d48f5e1c 100644--- a/bridge/src/server.ts+++ b/bridge/src/server.ts@@ -1,5 +1,6 @@/*** WebSocket server for Python-Node.js bridge communication.+ * Security: binds to 127.0.0.1 only; optional BRIDGE_TOKEN auth.*/import { WebSocketServer, WebSocket } from 'ws';@@ -21,12 +22,13 @@ export class BridgeServer {private wa: WhatsAppClient | null = null;private clients: Set<WebSocket> = new Set();- constructor(private port: number, private authDir: string) {}+ constructor(private port: number, private authDir: string, private token?: string) {}async start(): Promise<void> {- // Create WebSocket server- this.wss = new WebSocketServer({ port: this.port });- console.log(`π Bridge server listening on ws://localhost:${this.port}`);+ // Bind to localhost only β never expose to external network+ this.wss = new WebSocketServer({ host: '127.0.0.1', port: this.port });+ console.log(`π Bridge server listening on ws://127.0.0.1:${this.port}`);+ if (this.token) console.log('π Token authentication enabled');// Initialize WhatsApp clientthis.wa = new WhatsAppClient({@@ -38,35 +40,58 @@ export class BridgeServer {// Handle WebSocket connectionsthis.wss.on('connection', (ws) => {- console.log('π Python client connected');- this.clients.add(ws);-- ws.on('message', async (data) => {- try {- const cmd = JSON.parse(data.toString()) as SendCommand;- await this.handleCommand(cmd);- ws.send(JSON.stringify({ type: 'sent', to: cmd.to }));- } catch (error) {- console.error('Error handling command:', error);- ws.send(JSON.stringify({ type: 'error', error: String(error) }));- }- });-- ws.on('close', () => {- console.log('π Python client disconnected');- this.clients.delete(ws);- });-- ws.on('error', (error) => {- console.error('WebSocket error:', error);- this.clients.delete(ws);- });+ if (this.token) {+ // Require auth handshake as first message+ const timeout = setTimeout(() => ws.close(4001, 'Auth timeout'), 5000);+ ws.once('message', (data) => {+ clearTimeout(timeout);+ try {+ const msg = JSON.parse(data.toString());+ if (msg.type === 'auth' && msg.token === this.token) {+ console.log('π Python client authenticated');+ this.setupClient(ws);+ } else {+ ws.close(4003, 'Invalid token');+ }+ } catch {+ ws.close(4003, 'Invalid auth message');+ }+ });+ } else {+ console.log('π Python client connected');+ this.setupClient(ws);+ }});// Connect to WhatsAppawait this.wa.connect();}+ private setupClient(ws: WebSocket): void {+ this.clients.add(ws);++ ws.on('message', async (data) => {+ try {+ const cmd = JSON.parse(data.toString()) as SendCommand;+ await this.handleCommand(cmd);+ ws.send(JSON.stringify({ type: 'sent', to: cmd.to }));+ } catch (error) {+ console.error('Error handling command:', error);+ ws.send(JSON.stringify({ type: 'error', error: String(error) }));+ }+ });++ ws.on('close', () => {+ console.log('π Python client disconnected');+ this.clients.delete(ws);+ });++ ws.on('error', (error) => {+ console.error('WebSocket error:', error);+ this.clients.delete(ws);+ });+ }+private async handleCommand(cmd: SendCommand): Promise<void> {if (cmd.type === 'send' && this.wa) {await this.wa.sendMessage(cmd.to, cmd.text);diff --git a/nanobot/channels/whatsapp.py b/nanobot/channels/whatsapp.pyindex 6e00e9dc1..0cf2dd742 100644--- a/nanobot/channels/whatsapp.py+++ b/nanobot/channels/whatsapp.py@@ -42,6 +42,9 @@ class WhatsAppChannel(BaseChannel):try:async with websockets.connect(bridge_url) as ws:self._ws = ws+ # Send auth token if configured+ if self.config.bridge_token:+ await ws.send(json.dumps({"type": "auth", "token": self.config.bridge_token}))self._connected = Truelogger.info("Connected to WhatsApp bridge")diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.pyindex 3158d2963..92c017ed4 100644--- a/nanobot/cli/commands.py+++ b/nanobot/cli/commands.py@@ -636,14 +636,20 @@ def _get_bridge_dir() -> Path:def channels_login():"""Link device via QR code."""import subprocess+ from nanobot.config.loader import load_config+ config = load_config()bridge_dir = _get_bridge_dir()console.print(f"{__logo__} Starting bridge...")console.print("Scan the QR code to connect.\n")+ env = {**os.environ}+ if config.channels.whatsapp.bridge_token:+ env["BRIDGE_TOKEN"] = config.channels.whatsapp.bridge_token+try:- subprocess.run(["npm", "start"], cwd=bridge_dir, check=True)+ subprocess.run(["npm", "start"], cwd=bridge_dir, check=True, env=env)except subprocess.CalledProcessError as e:console.print(f"[red]Bridge failed: {e}[/red]")except FileNotFoundError:diff --git a/nanobot/config/schema.py b/nanobot/config/schema.pyindex fdf1868be..ef999b74c 100644--- a/nanobot/config/schema.py+++ b/nanobot/config/schema.py@@ -9,6 +9,7 @@ class WhatsAppConfig(BaseModel):"""WhatsApp channel configuration."""enabled: bool = Falsebridge_url: str = "ws://localhost:3001"+ bridge_token: str = "" # Shared token for bridge auth (optional, recommended)allow_from: list[str] = Field(default_factory=list) # Allowed phone numbers