-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb-server.js
More file actions
277 lines (234 loc) · 8.09 KB
/
Copy pathweb-server.js
File metadata and controls
277 lines (234 loc) · 8.09 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
const express = require('express');
const path = require('path');
const BotManager = require('./bot.js');
const crypto = require('crypto');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname)));
// OAuth state storage (in production, use Redis/session store)
const oauthStates = new Map();
// API routes
app.get('/api/guilds', async (req, res) => {
try {
const guilds = botManager.getGuilds();
res.json(guilds);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/channels/:guildId', async (req, res) => {
try {
const channels = botManager.getChannels(req.params.guildId);
res.json(channels);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/send-message', express.json(), async (req, res) => {
try {
const { channelId, message } = req.body;
const success = await botManager.sendMessage(channelId, message);
res.json({ success });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/logs', (req, res) => {
const logs = botManager.getLogs();
res.json(logs);
});
app.get('/api/bots', (req, res) => {
const bots = botManager.getBotConfigs();
res.json(bots);
});
app.post('/api/save-bot-config', express.json(), (req, res) => {
try {
const { token, name } = req.body;
const success = botManager.saveBotConfig(token, name);
res.json({ success });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/stored-tokens', (req, res) => {
try {
const tokens = botManager.getStoredTokens();
res.json(tokens);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/clear-data', (req, res) => {
try {
const success = botManager.clearAllData();
res.json({ success });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/oauth/callback', async (req, res) => {
const { code, state } = req.query;
try {
// Verify state parameter for security
if (!state || !oauthStates.has(state)) {
return res.status(400).send('<p>Invalid OAuth state. Please try again.</p>');
}
// Remove used state
oauthStates.delete(state);
if (!code) {
return res.status(400).send('<p>Authorization code not provided.</p>');
}
// Exchange code for access token
const tokenResponse = await exchangeCodeForToken(code);
if (tokenResponse.error) {
return res.status(400).send(`<p>OAuth Error: ${tokenResponse.error_description}</p>`);
}
// Get user info
const userInfo = await getDiscordUserInfo(tokenResponse.access_token);
// Store authentication data
const authData = {
access_token: tokenResponse.access_token,
refresh_token: tokenResponse.refresh_token,
expires_at: Date.now() + (tokenResponse.expires_in * 1000),
user: userInfo
};
// In production, store in secure session/database
// For now, we'll use a simple in-memory store (not secure for production)
global.discordAuth = authData;
// Return success page
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Discord Authentication</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; background: #36393f; color: #dcddde; }
.success { color: #3ba55c; }
button { background: #5865f2; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; }
</style>
</head>
<body>
<h1 class="success">✅ Authentication Successful!</h1>
<p>Welcome, ${userInfo.username}#${userInfo.discriminator}!</p>
<p>You can now close this window and return to the app.</p>
<button onclick="window.close()">Close Window</button>
<script>
// Notify parent window if opened in popup
if (window.opener) {
window.opener.postMessage({ type: 'DISCORD_AUTH_SUCCESS', user: ${JSON.stringify(userInfo)} }, '*');
}
// Auto-close after 3 seconds
setTimeout(() => window.close(), 3000);
</script>
</body>
</html>
`);
} catch (error) {
console.error('OAuth callback error:', error);
res.status(500).send('<p>Authentication failed. Please try again.</p>');
}
});
// Start OAuth flow
app.get('/api/oauth/start', (req, res) => {
const clientId = process.env.DISCORD_CLIENT_ID;
const redirectUri = encodeURIComponent(process.env.DISCORD_REDIRECT_URI || 'http://localhost:3000/oauth/callback');
const scope = encodeURIComponent(process.env.DISCORD_SCOPES || 'identify');
// Generate secure state parameter
const state = crypto.randomBytes(32).toString('hex');
oauthStates.set(state, { timestamp: Date.now() });
// Clean up old states (older than 10 minutes)
for (const [key, value] of oauthStates.entries()) {
if (Date.now() - value.timestamp > 10 * 60 * 1000) {
oauthStates.delete(key);
}
}
const oauthUrl = `https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}`;
res.json({ url: oauthUrl });
});
// Get OAuth status
app.get('/api/oauth/status', (req, res) => {
const isAuthenticated = !!(global.discordAuth && global.discordAuth.expires_at > Date.now());
res.json({
authenticated: isAuthenticated,
user: isAuthenticated ? global.discordAuth.user : null
});
});
// Logout
app.post('/api/oauth/logout', (req, res) => {
global.discordAuth = null;
res.json({ success: true });
});
// Helper functions for OAuth
async function exchangeCodeForToken(code) {
const clientId = process.env.DISCORD_CLIENT_ID;
const clientSecret = process.env.DISCORD_CLIENT_SECRET;
const redirectUri = process.env.DISCORD_REDIRECT_URI || 'http://localhost:3000/oauth/callback';
const response = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
grant_type: 'authorization_code',
code: code,
redirect_uri: redirectUri,
}),
});
return response.json();
}
async function getDiscordUserInfo(accessToken) {
const response = await fetch('https://discord.com/api/users/@me', {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
if (!response.ok) {
throw new Error('Failed to get user info');
}
return response.json();
}
// Initialize bot manager
const botManager = new BotManager();
botManager.init();
// Start server
app.listen(PORT, () => {
console.log(`Local Bot Client web server running on http://localhost:${PORT}`);
console.log('Access from mobile devices on the same network');
});
app.post('/api/switch-bot', express.json(), (req, res) => {
try {
const { botId } = req.body;
botManager.switchBot(botId);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/reconnect', (req, res) => {
try {
botManager.reconnect();
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Serve index.html for all other routes (SPA)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Initialize bot manager
const botManager = new BotManager();
botManager.init();
// Start server
app.listen(PORT, () => {
console.log(`Local Bot Client web server running on http://localhost:${PORT}`);
console.log('Access from mobile devices on the same network');
});