\ No newline at end of file
diff --git a/core/nanobot/Dockerfile b/core/nanobot/Dockerfile
new file mode 100644
index 0000000..8132747
--- /dev/null
+++ b/core/nanobot/Dockerfile
@@ -0,0 +1,40 @@
+FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim
+
+# Install Node.js 20 for the WhatsApp bridge
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends curl ca-certificates gnupg git && \
+ mkdir -p /etc/apt/keyrings && \
+ curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg && \
+ echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" > /etc/apt/sources.list.d/nodesource.list && \
+ apt-get update && \
+ apt-get install -y --no-install-recommends nodejs && \
+ apt-get purge -y gnupg && \
+ apt-get autoremove -y && \
+ rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+
+# Install Python dependencies first (cached layer)
+COPY pyproject.toml README.md LICENSE ./
+RUN mkdir -p nanobot bridge && touch nanobot/__init__.py && \
+ uv pip install --system --no-cache . && \
+ rm -rf nanobot bridge
+
+# Copy the full source and install
+COPY nanobot/ nanobot/
+COPY bridge/ bridge/
+RUN uv pip install --system --no-cache .
+
+# Build the WhatsApp bridge
+WORKDIR /app/bridge
+RUN npm install && npm run build
+WORKDIR /app
+
+# Create config directory
+RUN mkdir -p /root/.nanobot
+
+# Gateway default port
+EXPOSE 18790
+
+ENTRYPOINT ["nanobot"]
+CMD ["status"]
diff --git a/core/nanobot/LICENSE b/core/nanobot/LICENSE
new file mode 100644
index 0000000..24bdacc
--- /dev/null
+++ b/core/nanobot/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 nanobot contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/core/nanobot/README.md b/core/nanobot/README.md
new file mode 100644
index 0000000..8dba2d7
--- /dev/null
+++ b/core/nanobot/README.md
@@ -0,0 +1,1321 @@
+
+
+🐈 **nanobot** is an **ultra-lightweight** personal AI assistant inspired by [OpenClaw](https://github.com/openclaw/openclaw).
+
+⚡️ Delivers core agent functionality with **99% fewer lines of code** than OpenClaw.
+
+📏 Real-time line count: run `bash core_agent_lines.sh` to verify anytime.
+
+## 📢 News
+
+- **2026-03-08** 🚀 Released **v0.1.4.post4** — a reliability-packed release with safer defaults, better multi-instance support, sturdier MCP, and major channel and provider improvements. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post4) for details.
+- **2026-03-07** 🚀 Azure OpenAI provider, WhatsApp media, QQ group chats, and more Telegram/Feishu polish.
+- **2026-03-06** 🪄 Lighter providers, smarter media handling, and sturdier memory and CLI compatibility.
+- **2026-03-05** ⚡️ Telegram draft streaming, MCP SSE support, and broader channel reliability fixes.
+- **2026-03-04** 🛠️ Dependency cleanup, safer file reads, and another round of test and Cron fixes.
+- **2026-03-03** 🧠 Cleaner user-message merging, safer multimodal saves, and stronger Cron guards.
+- **2026-03-02** 🛡️ Safer default access control, sturdier Cron reloads, and cleaner Matrix media handling.
+- **2026-03-01** 🌐 Web proxy support, smarter Cron reminders, and Feishu rich-text parsing improvements.
+- **2026-02-28** 🚀 Released **v0.1.4.post3** — cleaner context, hardened session history, and smarter agent. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post3) for details.
+- **2026-02-27** 🧠 Experimental thinking mode support, DingTalk media messages, Feishu and QQ channel fixes.
+- **2026-02-26** 🛡️ Session poisoning fix, WhatsApp dedup, Windows path guard, Mistral compatibility.
+
+
+
+
📈 24/7 Real-Time Market Analysis |
+ 🚀 Full-Stack Software Engineer |
+ 📅 Smart Daily Routine Manager |
+ 📚 Personal Knowledge Assistant |
+
|---|---|---|---|
|
+
|
+
|
+
|
+
| Discovery • Insights • Trends | +Develop • Deploy • Scale | +Schedule • Automate • Organize | +Learn • Memory • Reasoning | +
+ Thanks for visiting ✨ nanobot!
+
+
+ nanobot is for educational, research, and technical exchange purposes only +
diff --git a/core/nanobot/SECURITY.md b/core/nanobot/SECURITY.md new file mode 100644 index 0000000..d98adb6 --- /dev/null +++ b/core/nanobot/SECURITY.md @@ -0,0 +1,263 @@ +# Security Policy + +## Reporting a Vulnerability + +If you discover a security vulnerability in nanobot, please report it by: + +1. **DO NOT** open a public GitHub issue +2. Create a private security advisory on GitHub or contact the repository maintainers (xubinrencs@gmail.com) +3. Include: + - Description of the vulnerability + - Steps to reproduce + - Potential impact + - Suggested fix (if any) + +We aim to respond to security reports within 48 hours. + +## Security Best Practices + +### 1. API Key Management + +**CRITICAL**: Never commit API keys to version control. + +```bash +# ✅ Good: Store in config file with restricted permissions +chmod 600 ~/.nanobot/config.json + +# ❌ Bad: Hardcoding keys in code or committing them +``` + +**Recommendations:** +- Store API keys in `~/.nanobot/config.json` with file permissions set to `0600` +- Consider using environment variables for sensitive keys +- Use OS keyring/credential manager for production deployments +- Rotate API keys regularly +- Use separate API keys for development and production + +### 2. Channel Access Control + +**IMPORTANT**: Always configure `allowFrom` lists for production use. + +```json +{ + "channels": { + "telegram": { + "enabled": true, + "token": "YOUR_BOT_TOKEN", + "allowFrom": ["123456789", "987654321"] + }, + "whatsapp": { + "enabled": true, + "allowFrom": ["+1234567890"] + } + } +} +``` + +**Security Notes:** +- In `v0.1.4.post3` and earlier, an empty `allowFrom` allowed all users. Since `v0.1.4.post4`, empty `allowFrom` denies all access by default — set `["*"]` to explicitly allow everyone. +- Get your Telegram user ID from `@userinfobot` +- Use full phone numbers with country code for WhatsApp +- Review access logs regularly for unauthorized access attempts + +### 3. Shell Command Execution + +The `exec` tool can execute shell commands. While dangerous command patterns are blocked, you should: + +- ✅ Review all tool usage in agent logs +- ✅ Understand what commands the agent is running +- ✅ Use a dedicated user account with limited privileges +- ✅ Never run nanobot as root +- ❌ Don't disable security checks +- ❌ Don't run on systems with sensitive data without careful review + +**Blocked patterns:** +- `rm -rf /` - Root filesystem deletion +- Fork bombs +- Filesystem formatting (`mkfs.*`) +- Raw disk writes +- Other destructive operations + +### 4. File System Access + +File operations have path traversal protection, but: + +- ✅ Run nanobot with a dedicated user account +- ✅ Use filesystem permissions to protect sensitive directories +- ✅ Regularly audit file operations in logs +- ❌ Don't give unrestricted access to sensitive files + +### 5. Network Security + +**API Calls:** +- All external API calls use HTTPS by default +- Timeouts are configured to prevent hanging requests +- Consider using a firewall to restrict outbound connections if needed + +**WhatsApp Bridge:** +- 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 + +**Critical**: Keep dependencies updated! + +```bash +# Check for vulnerable dependencies +pip install pip-audit +pip-audit + +# Update to latest secure versions +pip install --upgrade nanobot-ai +``` + +For Node.js dependencies (WhatsApp bridge): +```bash +cd bridge +npm audit +npm audit fix +``` + +**Important Notes:** +- Keep `litellm` updated to the latest version for security fixes +- We've updated `ws` to `>=8.17.1` to fix DoS vulnerability +- Run `pip-audit` or `npm audit` regularly +- Subscribe to security advisories for nanobot and its dependencies + +### 7. Production Deployment + +For production use: + +1. **Isolate the Environment** + ```bash + # Run in a container or VM + docker run --rm -it python:3.11 + pip install nanobot-ai + ``` + +2. **Use a Dedicated User** + ```bash + sudo useradd -m -s /bin/bash nanobot + sudo -u nanobot nanobot gateway + ``` + +3. **Set Proper Permissions** + ```bash + chmod 700 ~/.nanobot + chmod 600 ~/.nanobot/config.json + chmod 700 ~/.nanobot/whatsapp-auth + ``` + +4. **Enable Logging** + ```bash + # Configure log monitoring + tail -f ~/.nanobot/logs/nanobot.log + ``` + +5. **Use Rate Limiting** + - Configure rate limits on your API providers + - Monitor usage for anomalies + - Set spending limits on LLM APIs + +6. **Regular Updates** + ```bash + # Check for updates weekly + pip install --upgrade nanobot-ai + ``` + +### 8. Development vs Production + +**Development:** +- Use separate API keys +- Test with non-sensitive data +- Enable verbose logging +- Use a test Telegram bot + +**Production:** +- Use dedicated API keys with spending limits +- Restrict file system access +- Enable audit logging +- Regular security reviews +- Monitor for unusual activity + +### 9. Data Privacy + +- **Logs may contain sensitive information** - secure log files appropriately +- **LLM providers see your prompts** - review their privacy policies +- **Chat history is stored locally** - protect the `~/.nanobot` directory +- **API keys are in plain text** - use OS keyring for production + +### 10. Incident Response + +If you suspect a security breach: + +1. **Immediately revoke compromised API keys** +2. **Review logs for unauthorized access** + ```bash + grep "Access denied" ~/.nanobot/logs/nanobot.log + ``` +3. **Check for unexpected file modifications** +4. **Rotate all credentials** +5. **Update to latest version** +6. **Report the incident** to maintainers + +## Security Features + +### Built-in Security Controls + +✅ **Input Validation** +- Path traversal protection on file operations +- Dangerous command pattern detection +- Input length limits on HTTP requests + +✅ **Authentication** +- Allow-list based access control — in `v0.1.4.post3` and earlier empty `allowFrom` allowed all; since `v0.1.4.post4` it denies all (`["*"]` explicitly allows all) +- Failed authentication attempt logging + +✅ **Resource Protection** +- Command execution timeouts (60s default) +- Output truncation (10KB limit) +- HTTP request timeouts (10-30s) + +✅ **Secure Communication** +- HTTPS for all external API calls +- TLS for Telegram API +- WhatsApp bridge: localhost-only binding + optional token auth + +## Known Limitations + +⚠️ **Current Security Limitations:** + +1. **No Rate Limiting** - Users can send unlimited messages (add your own if needed) +2. **Plain Text Config** - API keys stored in plain text (use keyring for production) +3. **No Session Management** - No automatic session expiry +4. **Limited Command Filtering** - Only blocks obvious dangerous patterns +5. **No Audit Trail** - Limited security event logging (enhance as needed) + +## Security Checklist + +Before deploying nanobot: + +- [ ] API keys stored securely (not in code) +- [ ] Config file permissions set to 0600 +- [ ] `allowFrom` lists configured for all channels +- [ ] Running as non-root user +- [ ] File system permissions properly restricted +- [ ] Dependencies updated to latest secure versions +- [ ] Logs monitored for security events +- [ ] Rate limits configured on API providers +- [ ] Backup and disaster recovery plan in place +- [ ] Security review of custom skills/tools + +## Updates + +**Last Updated**: 2026-02-03 + +For the latest security updates and announcements, check: +- GitHub Security Advisories: https://github.com/HKUDS/nanobot/security/advisories +- Release Notes: https://github.com/HKUDS/nanobot/releases + +## License + +See LICENSE file for details. diff --git a/core/nanobot/bridge/package.json b/core/nanobot/bridge/package.json new file mode 100644 index 0000000..e91517c --- /dev/null +++ b/core/nanobot/bridge/package.json @@ -0,0 +1,26 @@ +{ + "name": "nanobot-whatsapp-bridge", + "version": "0.1.0", + "description": "WhatsApp bridge for nanobot using Baileys", + "type": "module", + "main": "dist/index.js", + "scripts": { + "build": "tsc", + "start": "node dist/index.js", + "dev": "tsc && node dist/index.js" + }, + "dependencies": { + "@whiskeysockets/baileys": "7.0.0-rc.9", + "ws": "^8.17.1", + "qrcode-terminal": "^0.12.0", + "pino": "^9.0.0" + }, + "devDependencies": { + "@types/node": "^20.14.0", + "@types/ws": "^8.5.10", + "typescript": "^5.4.0" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/core/nanobot/bridge/src/index.ts b/core/nanobot/bridge/src/index.ts new file mode 100644 index 0000000..e8f3db9 --- /dev/null +++ b/core/nanobot/bridge/src/index.ts @@ -0,0 +1,51 @@ +#!/usr/bin/env node +/** + * nanobot WhatsApp Bridge + * + * This bridge connects WhatsApp Web to nanobot's Python backend + * via WebSocket. It handles authentication, message forwarding, + * and reconnection logic. + * + * Usage: + * npm run build && npm start + * + * Or with custom settings: + * BRIDGE_PORT=3001 AUTH_DIR=~/.nanobot/whatsapp npm start + */ + +// Polyfill crypto for Baileys in ESM +import { webcrypto } from 'crypto'; +if (!globalThis.crypto) { + (globalThis as any).crypto = webcrypto; +} + +import { BridgeServer } from './server.js'; +import { homedir } from 'os'; +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, TOKEN); + +// Handle graceful shutdown +process.on('SIGINT', async () => { + console.log('\n\nShutting down...'); + await server.stop(); + process.exit(0); +}); + +process.on('SIGTERM', async () => { + await server.stop(); + process.exit(0); +}); + +// Start the server +server.start().catch((error) => { + console.error('Failed to start bridge:', error); + process.exit(1); +}); diff --git a/core/nanobot/bridge/src/server.ts b/core/nanobot/bridge/src/server.ts new file mode 100644 index 0000000..7d48f5e --- /dev/null +++ b/core/nanobot/bridge/src/server.ts @@ -0,0 +1,129 @@ +/** + * 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'; +import { WhatsAppClient, InboundMessage } from './whatsapp.js'; + +interface SendCommand { + type: 'send'; + to: string; + text: string; +} + +interface BridgeMessage { + type: 'message' | 'status' | 'qr' | 'error'; + [key: string]: unknown; +} + +export class BridgeServer { + private wss: WebSocketServer | null = null; + private wa: WhatsAppClient | null = null; + private clients: Set