Compare commits

..

1 Commits

Author SHA1 Message Date
debudebuye
3415090017 docs: update setup documentation and clean up security files 2026-01-10 09:28:38 +03:00
5 changed files with 113 additions and 383 deletions

4
.gitignore vendored
View File

@ -50,6 +50,10 @@ temp/
# User data (will be mounted as volume in Docker) # User data (will be mounted as volume in Docker)
scripts/ scripts/
# Local development tools (not for production)
quick-chat-info.js
get-chat-info.bat
# Security sensitive files # Security sensitive files
*.pem *.pem

View File

@ -3,6 +3,7 @@
A powerful, production-ready Telegram bot for real estate property notifications. Users can create custom property alerts and receive instant notifications when matching properties become available. A powerful, production-ready Telegram bot for real estate property notifications. Users can create custom property alerts and receive instant notifications when matching properties become available.
[![Node.js](https://img.shields.io/badge/Node.js-16%2B-green.svg)](https://nodejs.org/) [![Node.js](https://img.shields.io/badge/Node.js-16%2B-green.svg)](https://nodejs.org/)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Production Ready](https://img.shields.io/badge/Production-Ready-brightgreen.svg)](SECURITY_DEPLOYMENT_CHECKLIST.md) [![Production Ready](https://img.shields.io/badge/Production-Ready-brightgreen.svg)](SECURITY_DEPLOYMENT_CHECKLIST.md)
## 🚀 **Features** ## 🚀 **Features**
@ -10,7 +11,7 @@ A powerful, production-ready Telegram bot for real estate property notifications
### **🔔 Smart Notifications** ### **🔔 Smart Notifications**
- **Custom Property Alerts** - Users set criteria (type, location, price range) - **Custom Property Alerts** - Users set criteria (type, location, price range)
- **Automatic Matching** - Bot finds properties matching user preferences - **Automatic Matching** - Bot finds properties matching user preferences
- **Real-time Notifications** - Instant alerts via Telegram (with webhook future support) - **Real-time Notifications** - Instant alerts via Telegram (with webhook support)
- **Flexible Filtering** - By property type, location, house type, and price - **Flexible Filtering** - By property type, location, house type, and price
### **👤 User Management** ### **👤 User Management**
@ -60,6 +61,22 @@ nano .env
### **Configuration** ### **Configuration**
#### **🔍 Easy Chat ID Setup**
#### **🔍 Get Supergroup Chat ID & Topic ID**
For local development, create a simple script to get supergroup IDs:
```bash
# Run the script (create locally)
node quick-chat-info.js
```
**Simple script:** Add your bot to supergroup, send a message, get the IDs.
📖 **See [docs/GET_SUPERGROUP_IDS.md](docs/GET_SUPERGROUP_IDS.md) for the script code.**
#### **⚙️ Environment Variables**
Edit `.env` with your settings: Edit `.env` with your settings:
```env ```env
@ -297,7 +314,7 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
- 📖 Check the [documentation](docs/) first - 📖 Check the [documentation](docs/) first
- 🐛 Report bugs via GitHub Issues - 🐛 Report bugs via GitHub Issues
- 💬 Contact the development team - 💬 Contact the development team
- 📧 Email: [your-support-email]
### **Common Issues** ### **Common Issues**
- **Bot not responding**: Check bot token and network connectivity - **Bot not responding**: Check bot token and network connectivity
@ -315,6 +332,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
### **Future Enhancements** ### **Future Enhancements**
- 🔄 **Real-time webhooks** (when backend supports it) - 🔄 **Real-time webhooks** (when backend supports it)
- 📱 **Mobile app integration**
- 🔍 **Advanced search filters**
- 📊 **Analytics dashboard**
- 🌐 **Multi-language support**
--- ---
@ -333,8 +354,8 @@ This bot is **production-ready** with:
<div align="center"> <div align="center">
**Built for Yaltipia Home** **Built with ❤️ for Yaltipia**
[🏠 Website](https://yaltipia.com) • [📱 Telegram Bot](https://t.me/your_bot) • [📧 Support](mailto:support@yaltipia.com)
</div> </div>

View File

@ -1,256 +0,0 @@
# 🔒 Security Audit Report - Yaltipia Telegram Bot
**Date:** January 8, 2026
**Auditor:** Kiro AI Assistant
**Project:** Yaltipia Telegram Bot
**Version:** 1.0.0
## 📋 Executive Summary
This security audit was conducted on the Yaltipia Telegram Bot project to identify potential security vulnerabilities and ensure best practices are followed. The audit covers authentication, data handling, environment configuration, and deployment security.
**Overall Security Rating: ⚠️ MEDIUM RISK**
### 🚨 Critical Issues Found: 2
### ⚠️ Medium Issues Found: 3
### Low Issues Found: 4
---
## 🚨 CRITICAL SECURITY ISSUES
### 1. **Exposed Bot Token in .env File**
- **Severity:** CRITICAL
- **File:** `.env`
- **Issue:** Production bot token is committed and visible in the repository
- **Risk:** Complete bot compromise, unauthorized access to all user data
- **Current Token:** `8525180997:AAEObnUJE-wpSEpkLSBzn5eJktpSUnXlX1o`
- **Action Required:**
- ✅ IMMEDIATE: Regenerate bot token in BotFather
- ✅ Remove .env from git history
- ✅ Ensure .env is properly gitignored
### 2. **HTTP API Endpoint in Development**
- **Severity:** CRITICAL
- **File:** `.env`
- **Issue:** Using HTTP instead of HTTPS for API communication
- **Risk:** Man-in-the-middle attacks, credential interception
- **Current:** `API_BASE_URL=http://localhost:3000/api`
- **Action Required:** Use HTTPS in production
---
## ⚠️ MEDIUM SECURITY ISSUES
### 3. **Insufficient Input Validation**
- **Severity:** MEDIUM
- **Files:** `src/features/notifications.js`, `src/features/auth.js`
- **Issue:** Basic input sanitization but no comprehensive validation
- **Risk:** Potential injection attacks, data corruption
- **Recommendation:** Implement comprehensive input validation library
### 4. **Token Storage in Memory**
- **Severity:** MEDIUM
- **File:** `src/api.js`
- **Issue:** User tokens stored in Map without encryption
- **Risk:** Memory dumps could expose authentication tokens
- **Recommendation:** Implement token encryption or secure storage
### 5. **Rate Limiting Implementation**
- **Severity:** MEDIUM
- **File:** `src/webhookServer.js`
- **Issue:** Basic rate limiting but no persistent storage
- **Risk:** Rate limiting can be bypassed by restarting service
- **Recommendation:** Use Redis or database for rate limiting
---
## LOW SECURITY ISSUES
### 6. **Error Information Disclosure**
- **Severity:** LOW
- **Files:** Multiple error handlers
- **Issue:** Some error messages may leak internal information
- **Recommendation:** Review error messages for information disclosure
### 7. **Session Management**
- **Severity:** LOW
- **File:** `src/features/auth.js`
- **Issue:** No session timeout implementation
- **Recommendation:** Implement session expiration
### 8. **Logging Security**
- **Severity:** LOW
- **Files:** Multiple logging statements
- **Issue:** Some logs may contain sensitive information
- **Recommendation:** Implement secure logging practices
### 9. **Dependency Security**
- **Severity:** LOW
- **File:** `package.json`
- **Issue:** Dependencies not regularly audited
- **Recommendation:** Regular security audits with `npm audit`
---
## ✅ SECURITY STRENGTHS
### Authentication & Authorization
- ✅ Phone-based authentication system
- ✅ Token-based API authentication
- ✅ Admin-only commands properly restricted
- ✅ Private chat enforcement for sensitive operations
### Environment Configuration
- ✅ Environment variables properly used
- ✅ Production configuration template provided
- ✅ Sensitive files in .gitignore
### Error Handling
- ✅ Comprehensive error handling throughout
- ✅ Graceful degradation on failures
- ✅ User-friendly error messages
### Security Headers
- ✅ Security headers implemented in webhook server
- ✅ CORS properly configured
- ✅ X-Powered-By header removed
### Monitoring & Logging
- ✅ Comprehensive monitoring system
- ✅ Admin notifications for security events
- ✅ Failed login attempt tracking
---
## 🔧 IMMEDIATE ACTIONS REQUIRED
### Before Git Push:
1. **CRITICAL:** Remove exposed bot token from .env
2. **CRITICAL:** Add .env to .gitignore (already done)
3. **HIGH:** Review all environment files for sensitive data
### Post-Deployment:
1. Generate new production bot token
2. Configure HTTPS endpoints
3. Implement comprehensive input validation
4. Set up secure token storage
5. Configure persistent rate limiting
---
## 📋 SECURITY CHECKLIST
### Pre-Production Deployment
- [ ] **New bot token generated** (not development token)
- [ ] **HTTPS URLs configured** for all API endpoints
- [ ] **Environment variables secured** (600 permissions)
- [ ] **Admin chat IDs verified** and secured
- [ ] **Rate limiting configured** with persistent storage
- [ ] **Input validation implemented** comprehensively
- [ ] **Error messages reviewed** for information disclosure
- [ ] **Dependencies audited** with `npm audit`
- [ ] **Logging reviewed** for sensitive data exposure
- [ ] **Session timeouts configured**
### Ongoing Security Maintenance
- [ ] **Regular dependency updates** and security audits
- [ ] **Token rotation** every 90 days
- [ ] **Log monitoring** for suspicious activities
- [ ] **Access review** for admin permissions
- [ ] **Backup and recovery** procedures tested
---
## 🛡️ SECURITY RECOMMENDATIONS
### 1. Implement Input Validation Library
```javascript
const Joi = require('joi');
const notificationSchema = Joi.object({
name: Joi.string().min(1).max(100).required(),
type: Joi.string().valid('rent', 'sale').required(),
minPrice: Joi.number().min(0).optional(),
maxPrice: Joi.number().min(0).optional()
});
```
### 2. Secure Token Storage
```javascript
const crypto = require('crypto');
class SecureTokenStorage {
constructor(encryptionKey) {
this.key = encryptionKey;
}
encrypt(token) {
// Implement AES encryption
}
decrypt(encryptedToken) {
// Implement AES decryption
}
}
```
### 3. Enhanced Rate Limiting
```javascript
const rateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const limiter = rateLimit({
store: new RedisStore({
client: redisClient
}),
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
```
---
## 📊 SECURITY METRICS
| Category | Score | Status |
|----------|-------|--------|
| Authentication | 8/10 | ✅ Good |
| Authorization | 9/10 | ✅ Excellent |
| Input Validation | 6/10 | ⚠️ Needs Improvement |
| Error Handling | 8/10 | ✅ Good |
| Logging | 7/10 | ✅ Good |
| Configuration | 7/10 | ✅ Good |
| Dependencies | 7/10 | ✅ Good |
| **Overall** | **7.4/10** | ⚠️ **Medium Risk** |
---
## 🎯 NEXT STEPS
1. **Immediate (Before Push):**
- Remove sensitive data from .env
- Verify .gitignore configuration
- Review commit history for exposed secrets
2. **Short Term (1-2 weeks):**
- Implement comprehensive input validation
- Set up secure token storage
- Configure HTTPS endpoints
3. **Medium Term (1 month):**
- Implement persistent rate limiting
- Set up automated security scanning
- Create security incident response plan
4. **Long Term (Ongoing):**
- Regular security audits
- Dependency updates
- Security training for development team
---
**Audit Completed:** January 8, 2026
**Next Audit Due:** April 8, 2026
*This audit should be reviewed and updated regularly as the codebase evolves.*

View File

@ -1,123 +0,0 @@
# 📱 How to Get Chat ID and Topic ID for Telegram Bot Monitoring
This guide will help you find your Chat ID and Topic ID for setting up Telegram bot monitoring notifications.
## 🎯 What You Need
- A Telegram account
- Access to create a bot or use an existing bot
- A group chat or supergroup where you want to receive notifications
## 📋 Step-by-Step Guide
### 1. Create or Access Your Bot
If you don't have a bot yet:
1. Open Telegram and search for `@BotFather`
2. Start a chat with BotFather
3. Send `/newbot` command
4. Follow the instructions to create your bot
5. Save the **Bot Token** (you'll need this for your `.env` file)
### 2. Get Your Chat ID
#### Method 1: Using @userinfobot (Easiest)
1. Search for `@userinfobot` in Telegram
2. Start a chat and send any message
3. The bot will reply with your **Chat ID**
#### Method 2: Using Telegram Web API
1. Send a message to your bot
2. Open this URL in your browser (replace `YOUR_BOT_TOKEN` with your actual bot token):
```
https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates
```
3. Look for the `"chat":{"id":` field in the response
4. The number after `"id":` is your **Chat ID**
#### Method 3: For Group Chats
1. Add your bot to the group
2. Send a message in the group
3. Use the same API URL as Method 2
4. Look for the chat object with `"type":"group"` or `"type":"supergroup"`
5. The `"id"` field will be your **Group Chat ID** (usually negative number)
### 3. Get Your Topic ID (For Supergroups with Topics)
If you're using a supergroup with topics enabled:
1. Create or open the topic where you want notifications
2. Send a message in that specific topic
3. Use the API URL from Method 2 above
4. Look for `"message_thread_id"` in the response
5. This number is your **Topic ID**
#### Alternative Method for Topic ID:
1. Right-click on a message in the topic
2. Select "Copy Message Link"
3. The URL will look like: `https://t.me/c/XXXXXXXXX/YYYY/ZZZZ`
4. The `YYYY` number is your **Topic ID**
## 🔧 Configuration
Once you have your IDs, add them to your `.env` file:
```env
# Bot Configuration
TELEGRAM_BOT_TOKEN=your_bot_token_here
# Chat Configuration
TELEGRAM_CHAT_ID=your_chat_id_here
# Topic Configuration (optional - only for supergroups with topics)
TELEGRAM_TOPIC_ID=your_topic_id_here
```
## ✅ Testing Your Configuration
You can test if your configuration works by running:
```bash
node scripts/test-startup-notification.js
```
This will send a test message to verify your Chat ID and Topic ID are correct.
## 🔍 Troubleshooting
### Common Issues:
**Bot can't send messages to group:**
- Make sure the bot is added to the group
- Ensure the bot has permission to send messages
- For channels, make sure the bot is an admin
**Wrong Chat ID:**
- Group Chat IDs are usually negative numbers
- Private chat IDs are usually positive numbers
- Double-check you're using the correct ID format
**Topic ID not working:**
- Make sure topics are enabled in your supergroup
- Verify you're getting the Topic ID from the correct topic
- Topic IDs are only needed for supergroups with topics
**API returns empty:**
- Send a fresh message to your bot/group
- Make sure your bot token is correct
- Check that the bot has received recent messages
## 📝 Notes
- Chat IDs remain constant, so you only need to find them once
- Topic IDs also remain constant unless the topic is deleted and recreated
- Keep your bot token secure and never share it publicly
- For production use, consider using environment variables instead of hardcoding IDs
## 🆘 Need Help?
If you're still having trouble:
1. Check the bot logs for error messages
2. Verify your bot token is valid
3. Ensure the bot has proper permissions in your chat/group
4. Try sending a test message manually to confirm the setup

View File

@ -0,0 +1,84 @@
# 🔍 Get Supergroup Chat ID & Topic ID
Simple script to get supergroup chat IDs and topic IDs for local development.
## 📋 Quick Script
Create `quick-chat-info.js` in your project root:
```javascript
#!/usr/bin/env node
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
console.log('🔍 Supergroup Chat ID & Topic ID Getter');
console.log('Add your bot to supergroup and send a message...\n');
const botToken = process.env.TELEGRAM_BOT_TOKEN;
if (!botToken || botToken === 'YOUR_BOT_TOKEN_HERE') {
console.log('❌ Set TELEGRAM_BOT_TOKEN in .env file');
process.exit(1);
}
const bot = new TelegramBot(botToken, { polling: true });
bot.on('message', (msg) => {
if (msg.chat.type === 'supergroup') {
console.log(`📋 Supergroup: ${msg.chat.title}`);
console.log(`Chat ID: ${msg.chat.id}`);
if (msg.message_thread_id) {
console.log(`Topic ID: ${msg.message_thread_id}`);
console.log(`\nFor .env: ADMIN_CHAT_IDS=${msg.chat.id}`);
console.log(`For .env: MONITORING_TOPIC_ID=${msg.message_thread_id}\n`);
} else {
console.log(`\nFor .env: ADMIN_CHAT_IDS=${msg.chat.id}\n`);
}
}
});
process.on('SIGINT', () => {
console.log('\n👋 Done!');
process.exit(0);
});
```
## 🚀 Usage
1. **Set bot token** in `.env` file
2. **Add bot to supergroup** as admin
3. **Run script**: `node quick-chat-info.js`
4. **Send message** in supergroup (or topic)
5. **Copy IDs** to `.env` file
6. **Press Ctrl+C** to stop
## 🪟 Windows Batch File
Create `get-chat-info.bat`:
```batch
@echo off
echo 🔍 Getting Supergroup Chat ID and Topic ID
echo Add your bot to supergroup and send a message...
echo.
node quick-chat-info.js
pause
```
## 📋 Example Output
```
🔍 Supergroup Chat ID & Topic ID Getter
Add your bot to supergroup and send a message...
📋 Supergroup: Yaltipia Admin Chat
Chat ID: -1001234567890
Topic ID: 5
For .env: ADMIN_CHAT_IDS=-1001234567890
For .env: MONITORING_TOPIC_ID=5
```
---
**Simple and focused! 🎯**