File size: 6,432 Bytes
bbf51df
 
 
 
 
 
 
60f5fc7
 
 
 
bbf51df
 
60f5fc7
bbf51df
60f5fc7
bbf51df
 
 
 
60f5fc7
 
 
 
 
 
 
 
 
ddbaf47
60f5fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbf51df
 
 
60f5fc7
 
 
 
 
bbf51df
 
 
 
60f5fc7
bbf51df
60f5fc7
 
 
 
 
bbf51df
60f5fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbf51df
 
60f5fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbf51df
 
60f5fc7
 
 
cbe1311
60f5fc7
 
 
 
 
cbe1311
60f5fc7
cbe1311
60f5fc7
cbe1311
 
60f5fc7
 
baf28ec
60f5fc7
bbf51df
 
 
60f5fc7
 
 
 
 
 
 
 
 
bbf51df
 
60f5fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbf51df
60f5fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
const express = require('express');
const { spawn } = require('child_process');
const { MongoClient } = require('mongodb');
const path = require('path');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});
const crypto = require('crypto');
const fs = require('fs');

// MongoDB Connection
const MONGO_URI = process.env.MONGO_URI || "mongodb://localhost:27017";
let db;

async function connectDB() {
    try {
        const client = new MongoClient(MONGO_URI);
        await client.connect();
        db = client.db('whatsapp-bots');
        console.log("βœ… Connected to MongoDB");
        
        // Initialize collections
        const collections = ['users', 'bots', 'sessions'];
        for (const colName of collections) {
            if (!(await db.listCollections({ name: colName }).hasNext())) {
                await db.createCollection(colName);
                console.log(`Created collection: ${colName}`);
            }
        }
        
        // Create admin user if not exists
        const adminExists = await db.collection('users').findOne({ username: 'admin' });
        if (!adminExists) {
            await db.collection('users').insertOne({
                username: 'admin',
                password: hashPassword('admin123'),
                isAdmin: true,
                createdAt: new Date()
            });
            console.log("πŸ‘‘ Created admin user (password: admin123)");
        }
    } catch (err) {
        console.error("❌ MongoDB connection error:", err);
        process.exit(1);
    }
}

function hashPassword(password) {
    return crypto
        .createHash('sha256')
        .update(password + (process.env.PEPPER || 'defaultPepper'))
        .digest('hex');
}

// Socket.IO
io.on('connection', (socket) => {
    console.log(`New connection: ${socket.id}`);
    
    // Force terminal initialization
    socket.emit('terminal-init', { 
        status: 'ready',
        timestamp: Date.now() 
    });
    
    // Terminal command handler
    socket.on('terminal-command', async (data) => {
        try {
            const { command, userId } = data;
            console.log(`Command from ${userId}: ${command}`);
            
            // Execute command in user's directory
            const userDir = `/persistent/storage/${userId}`;
            const child = spawn(command.split(' ')[0], command.split(' ').slice(1), {
                cwd: userDir
            });
            
            child.stdout.on('data', (data) => {
                socket.emit('terminal-output', data.toString());
            });
            
            child.stderr.on('data', (data) => {
                socket.emit('terminal-output', `ERROR: ${data.toString()}`);
            });
            
            child.on('close', (code) => {
                socket.emit('terminal-output', `Process exited with code ${code}\n`);
            });
        } catch (err) {
            socket.emit('terminal-output', `ERROR: ${err.message}\n`);
        }
    });
    
    // Authentication handlers
    socket.on('login', async (data) => {
        try {
            const { username, password } = data;
            const user = await db.collection('users').findOne({ 
                username,
                password: hashPassword(password)
            });
            
            if (user) {
                currentUser = user._id.toString();
                socket.emit('login-success', { 
                    userId: currentUser,
                    isAdmin: user.isAdmin 
                });
                
                // Ensure user directory exists
                const userDir = `/persistent/storage/${currentUser}`;
                if (!fs.existsSync(userDir)) {
                    fs.mkdirSync(userDir, { recursive: true });
                }
            } else {
                socket.emit('login-error', 'Invalid credentials');
            }
        } catch (err) {
            socket.emit('login-error', 'Authentication failed');
        }
    });
});

// Express middleware
app.use(express.static('public'));
app.use(express.json());

// Health check endpoint
app.get('/health', (req, res) => {
    res.status(200).json({ 
        status: 'healthy',
        timestamp: Date.now() 
    });
});

// Error handling
app.use((err, req, res, next) => {
    console.error('Global error:', err);
    io.emit('terminal-output', `SYSTEM ERROR: ${err.message}\n`);
    res.status(500).json({ error: err.message });
});

// Start server
const PORT = process.env.PORT || 7860;
connectDB().then(() => {
    http.listen(PORT, () => {
        console.log(`πŸš€ Server running on port ${PORT}`);
        
        // Restart any previously running bots
        db.collection('bots').find({ status: 'running' }).forEach(bot => {
            console.log(`Restarting bot for user ${bot.userId}`);
            startBotProcess(bot.userId, bot.repoUrl, bot.entryFile);
        });
    });
});

// Helper function to start bot processes
function startBotProcess(userId, repoUrl, entryFile) {
    const botDir = `/persistent/storage/${userId}`;
    
    // Clone repo if needed
    if (!fs.existsSync(botDir)) {
        const clone = spawn('git', ['clone', repoUrl, botDir]);
        clone.on('close', (code) => {
            if (code === 0) installDependencies(botDir, userId, repoUrl, entryFile);
        });
    } else {
        installDependencies(botDir, userId, repoUrl, entryFile);
    }
}

function installDependencies(botDir, userId, repoUrl, entryFile) {
    const install = spawn('npm', ['install'], { cwd: botDir });
    install.on('close', (code) => {
        if (code === 0) runBot(botDir, userId, repoUrl, entryFile);
    });
}

function runBot(botDir, userId, repoUrl, entryFile) {
    const botProcess = spawn('node', [entryFile], { cwd: botDir });
    
    // Save to database
    db.collection('bots').updateOne(
        { userId },
        { $set: { 
            status: 'running',
            repoUrl,
            entryFile,
            pid: botProcess.pid,
            lastStarted: new Date()
        }},
        { upsert: true }
    );
    
    // Handle process events
    botProcess.on('exit', (code) => {
        db.collection('bots').updateOne(
            { userId },
            { $set: { status: 'stopped', exitCode: code } }
        );
    });
}