File size: 16,929 Bytes
faf81ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
7793fcb
faf81ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d11724
faf81ad
4d11724
faf81ad
4d11724
faf81ad
 
4d11724
faf81ad
7b05f8a
 
 
faf81ad
 
 
 
 
 
 
4d11724
faf81ad
 
 
 
4d11724
faf81ad
 
 
 
 
 
 
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
4d11724
faf81ad
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
 
 
 
7793fcb
faf81ad
 
 
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
 
 
 
 
 
 
 
4d11724
 
faf81ad
4d11724
faf81ad
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
 
 
 
 
 
 
48978a7
faf81ad
 
4d11724
faf81ad
 
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
 
 
 
5a6265f
faf81ad
 
 
 
 
 
 
 
 
 
e529984
 
faf81ad
 
 
 
5932290
faf81ad
 
 
 
 
 
4d11724
faf81ad
 
 
 
4d11724
faf81ad
 
 
 
 
 
 
 
 
 
 
4d11724
faf81ad
4d11724
faf81ad
 
 
 
 
 
 
 
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48978a7
7793fcb
faf81ad
 
 
d0850b1
faf81ad
 
d0850b1
3d7c247
faf81ad
 
d0850b1
faf81ad
 
 
 
 
 
 
 
d0850b1
 
faf81ad
d0850b1
faf81ad
973fe1a
faf81ad
 
 
 
 
 
 
4d11724
faf81ad
 
 
4d11724
 
faf81ad
 
 
 
 
4d11724
d0850b1
faf81ad
 
 
 
 
 
5932290
faf81ad
 
 
 
 
 
4d11724
48978a7
7793fcb
faf81ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48978a7
7793fcb
faf81ad
 
 
 
 
4d11724
faf81ad
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d11724
faf81ad
 
 
4d11724
faf81ad
 
4d11724
faf81ad
 
 
 
 
 
 
 
4d11724
faf81ad
 
 
 
 
 
4d11724
faf81ad
 
 
 
fa29984
faf81ad
 
 
4d11724
faf81ad
 
 
 
 
4d11724
faf81ad
4d11724
 
faf81ad
 
7793fcb
fa29984
faf81ad
 
 
4d11724
 
 
faf81ad
48978a7
7793fcb
faf81ad
 
 
 
4d11724
faf81ad
 
 
 
9d9815b
65e21cf
faf81ad
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
const express = require('express');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const app = express();
const port = process.env.PORT || 7860;

// Discord OAuth2 Config — reads from multiple possible env var names
const CLIENT_SECRET = process.env.CLIENT_SECRET || process.env.DISCORD_CLIENT_SECRET || '';
const REDIRECT_URI = process.env.REDIRECT_URI || process.env.DISCORD_REDIRECT_URL || '';

// Store reference to the Discord client (set from index.js)
let discordClient = null;
let commandsDataRef = null;

// Session store (persisted to disk so logins survive restarts)
const SESSION_FILE = path.join(__dirname, 'data', 'sessions.json');
let sessions = new Map();

// Load sessions from disk on startup
try {
    if (fs.existsSync(SESSION_FILE)) {
        const raw = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf8'));
        sessions = new Map(Object.entries(raw));
        console.log(`[*] Dashboard: Loaded ${sessions.size} persistent session(s).`);
    }
} catch (e) {}

function saveSessions() {
    try {
        const dir = path.dirname(SESSION_FILE);
        if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
        const obj = Object.fromEntries(sessions);
        fs.writeFileSync(SESSION_FILE, JSON.stringify(obj), 'utf8');
    } catch (e) {}
}

// In-memory log buffer
const logBuffer = [];
const MAX_LOGS = 200;

// Hijack console.log & console.error to capture logs
const origLog = console.log;
const origErr = console.error;
console.log = (...args) => {
    const line = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
    logBuffer.push(line);
    if (logBuffer.length > MAX_LOGS) logBuffer.shift();
    origLog.apply(console, args);
};
console.error = (...args) => {
    const line = '[Error] ' + args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
    logBuffer.push(line);
    if (logBuffer.length > MAX_LOGS) logBuffer.shift();
    origErr.apply(console, args);
};

app.use(express.json());

function hasDashboardPermissions(permissionBits) {
    try {
        const perms = BigInt(permissionBits || '0');
        return (perms & BigInt(0x20)) !== BigInt(0) || (perms & BigInt(0x8)) !== BigInt(0);
    } catch (e) {
        return false;
    }
}

// --- Helper: Get redirect URI ---
function getRedirectUri() {
    if (REDIRECT_URI) return REDIRECT_URI;
    const spaceId = process.env.SPACE_ID;
    if (spaceId) return `https://${spaceId.replace('/', '-').toLowerCase()}.hf.space/callback`;
    return `http://localhost:${port}/callback`;
}

// --- Helper: Get Client ID from bot ---
function getClientId() {
    return discordClient?.user?.id || process.env.CLIENT_ID || process.env.DISCORD_CLIENT_ID || '';
}

// --- Helper: Parse session cookie ---
function getSession(req) {
    const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
        const [k, v] = c.trim().split('=');
        if (k && v) acc[k] = v;
        return acc;
    }, {});
    const sid = cookies['fb_session'];
    if (sid && sessions.has(sid)) return sessions.get(sid);
    return null;
}

// --- Auth Middleware ---
function requireAuth(req, res, next) {
    const session = getSession(req);
    if (session && session.user) return next();
    res.status(401).json({ error: 'Unauthorized' });
}

// --- Attach user to req ---
app.use((req, res, next) => {
    req.dashSession = getSession(req);
    next();
});

// --- Static Assets ---
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'dashboard.html'));
});
app.get('/logo.png', (req, res) => {
    const logo = path.join(__dirname, 'logo.png');
    if (fs.existsSync(logo)) res.sendFile(logo);
    else res.status(404).send('Not found');
});

// --- Discord OAuth2: Step 1 — Redirect to Discord ---
app.get('/auth/login', (req, res) => {
    const clientId = getClientId();
    const redirect = encodeURIComponent(getRedirectUri());
    const url = `https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`;
    res.redirect(url);
});

async function fetchWithRetry(url, options, retries = 2) {
    for (let i = 0; i <= retries; i++) {
        try {
            const res = await fetch(url, options);
            if (!res.ok && i < retries) throw new Error(`HTTP ${res.status}`);
            return res;
        } catch (err) {
            if (i === retries) throw err;
            console.warn(`[Dashboard] Connection failed, rotating endpoint and retrying... (${i + 1}/${retries})`);
            try {
                require('./network_fix').rotateEndpoint();
            } catch (e) {}
            await new Promise(r => setTimeout(r, 1000));
        }
    }
}

// --- Discord OAuth2: Step 2 — Callback from Discord ---
// Support both /callback and /auth/callback to match any Discord redirect config
async function handleOAuthCallback(req, res) {
    const { code } = req.query;
    if (!code) return res.redirect('/?error=no_code');

    try {
        // Exchange code for token
        const tokenRes = await fetchWithRetry('https://discord.com/api/oauth2/token', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                client_id: getClientId(),
                client_secret: CLIENT_SECRET,
                grant_type: 'authorization_code',
                code,
                redirect_uri: getRedirectUri()
            })
        });
        const tokenData = await tokenRes.json();
        if (!tokenData.access_token) return res.redirect('/?error=token_failed');

        // Fetch user profile
        const userRes = await fetchWithRetry('https://discord.com/api/users/@me', {
            headers: { Authorization: `Bearer ${tokenData.access_token}` }
        });
        const user = await userRes.json();
        if (!user.id) return res.redirect('/?error=user_failed');

        // Fetch user guilds
        console.log(`[Dashboard] Fetching guilds for user ${user.username}...`);
        const guildsRes = await fetchWithRetry('https://discord.com/api/users/@me/guilds', {
            headers: { Authorization: `Bearer ${tokenData.access_token}` }
        });
        const userGuilds = await guildsRes.json();
        
        if (!Array.isArray(userGuilds)) {
            console.error('[Dashboard] Failed to fetch guilds:', userGuilds);
        } else {
            console.log(`[Dashboard] Found ${userGuilds.length} guilds for user.`);
        }

        // Create session
        const sid = crypto.randomBytes(32).toString('hex');
        sessions.set(sid, {
            user: {
                id: user.id,
                username: user.username,
                avatar: user.avatar
                    ? `https://cdn.discord.com/avatars/${user.id}/${user.avatar}.png`
                    : `https://cdn.discord.com/embed/avatars/${parseInt(user.discriminator || '0') % 5}.png`
            },
            guilds: Array.isArray(userGuilds) ? userGuilds : [],
            createdAt: Date.now()
        });

        // Set cookie (7 days)
        res.cookie('fb_session', sid, {
            httpOnly: true,
            maxAge: 7 * 24 * 60 * 60 * 1000,
            sameSite: 'lax'
        });

        res.redirect('/?login=success');
    } catch (err) {
        console.error('[Dashboard] OAuth error:', err);
        res.redirect('/?error=server_error');
    }
}
app.get('/callback', handleOAuthCallback);
app.get('/auth/callback', handleOAuthCallback);

// --- Check Auth Status ---
app.get('/api/me', (req, res) => {
    const session = getSession(req);
    if (session && session.user) {
        res.json({ loggedIn: true, user: session.user });
    } else {
        res.json({ loggedIn: false });
    }
});

// --- Logout ---
app.get('/auth/logout', (req, res) => {
    const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
        const [k, v] = c.trim().split('=');
        if (k && v) acc[k] = v;
        return acc;
    }, {});
    const sid = cookies['fb_session'];
    if (sid) sessions.delete(sid);
    res.clearCookie('fb_session');
    res.redirect('/');
});

// --- Stats ---
app.get('/api/stats', requireAuth, (req, res) => {
    if (!discordClient || !discordClient.isReady()) {
        return res.json({ servers: 0, members: 0, uptime: '—', commands: 0 });
    }
    const up = process.uptime();
    const d = Math.floor(up / 86400);
    const h = Math.floor(up / 3600) % 24;
    const m = Math.floor(up / 60) % 60;
    const upStr = d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;

    const totalMembers = discordClient.guilds.cache.reduce((acc, g) => acc + g.memberCount, 0);
    const botId = discordClient.user?.id;
    const inviteUrl = botId
        ? `https://discord.com/api/oauth2/authorize?client_id=${botId}&permissions=8&scope=bot%20applications.commands`
        : '#';

    res.json({
        servers: discordClient.guilds.cache.size,
        members: totalMembers,
        uptime: upStr,
        commands: commandsDataRef ? commandsDataRef.length : 0,
        inviteUrl
    });
});

// --- Server List ---
// --- Server List (shared with bot + permissions) ---
app.get('/api/servers', requireAuth, async (req, res) => {
    try {
        if (!discordClient || !discordClient.isReady()) {
            return res.json({ pending: true, servers: [] });
        }

        const userGuilds = req.dashSession.guilds || [];
        const app = await discordClient.application.fetch().catch(() => null);

        // Owner recognition for both single-owner apps and team-owned apps.
        const ownerCandidates = new Set();
        if (app?.owner?.id) ownerCandidates.add(app.owner.id);
        if (app?.owner?.ownerId) ownerCandidates.add(app.owner.ownerId);
        if (app?.owner?.members) {
            for (const member of app.owner.members.values()) {
                if (member?.id) ownerCandidates.add(member.id);
                if (member?.user?.id) ownerCandidates.add(member.user.id);
            }
        }
        const isBotOwner = ownerCandidates.has(req.dashSession.user.id);

        console.log(`[Dashboard] Request by ${req.dashSession.user.username} (Owner: ${isBotOwner})`);

        let visibleGuilds = [];
        if (isBotOwner) {
            visibleGuilds = Array.from(discordClient.guilds.cache.values());
        } else {
            const mutualGuilds = userGuilds
                .filter(ug => discordClient.guilds.cache.has(ug.id))
                .filter(Boolean);

            const manageableGuilds = mutualGuilds.filter(ug => {
                const permBits = ug.permissions ?? ug.permissions_new;
                return hasDashboardPermissions(permBits);
            });

            // Fallback: if Discord doesn't return permission bits reliably, still show shared guilds.
            const guildsToShow = manageableGuilds.length > 0 ? manageableGuilds : mutualGuilds;
            visibleGuilds = guildsToShow
                .map(ug => discordClient.guilds.cache.get(ug.id))
                .filter(Boolean);
        }

        const list = visibleGuilds.map(g => ({
            name: g.name,
            id: g.id,
            members: g.memberCount || 0,
            icon: g.iconURL({ size: 64 }) || null
        }));

        if (isBotOwner) console.log(`[Dashboard] Owner access enabled for ${req.dashSession.user.username}`);
        console.log(`[Dashboard] Serving ${list.length} managed servers to ${req.dashSession.user.username}`);
        res.json({ pending: false, servers: list });
    } catch (err) {
        console.error('[Dashboard] /api/servers failed:', err);
        res.status(500).json({ pending: false, servers: [], error: 'Failed to load servers' });
    }
});

// --- Guild Config (Prefix) ---
app.get('/api/config/:guildId', requireAuth, (req, res) => {
    const { guildId } = req.params;
    const userGuilds = req.dashSession.guilds || [];
    const ug = userGuilds.find(g => g.id === guildId);
    
    if (!ug) return res.status(403).json({ error: 'Access denied' });
    const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
    if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });

    const storage = require('./storage');
    const config = storage.data.config[guildId] || {};
    res.json({ 
        prefix: storage.getPrefix(guildId),
        autoFriendlyEnabled: config.autoFriendlyEnabled || false,
        autoFriendlyInterval: config.autoFriendlyInterval || 40,
        autoFriendlyChannel: config.autoFriendlyChannel || null,
        postEnabled: config.postEnabled !== false, // Default to true
        postChannelId: config.postChannelId || null
    });
});

app.get('/api/channels/:guildId', requireAuth, (req, res) => {
    const { guildId } = req.params;
    if (!discordClient) return res.json([]);
    const guild = discordClient.guilds.cache.get(guildId);
    if (!guild) return res.json([]);

    const channels = guild.channels.cache
        .filter(c => c.isTextBased())
        .map(c => ({ id: c.id, name: c.name }));
    res.json(channels);
});

app.post('/api/config/:guildId', requireAuth, (req, res) => {
    const { guildId } = req.params;
    const { prefix, autoFriendlyEnabled, autoFriendlyInterval, autoFriendlyChannel, postEnabled, postChannelId } = req.body;
    const userGuilds = req.dashSession.guilds || [];
    const ug = userGuilds.find(g => g.id === guildId);

    if (!ug) return res.status(403).json({ error: 'Access denied' });
    const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
    if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });

    const storage = require('./storage');
    
    if (prefix) {
        if (prefix.length > 5) return res.status(400).json({ error: 'Invalid prefix' });
        storage.setPrefix(guildId, prefix);
    }

    if (storage.data.config[guildId] === undefined) storage.data.config[guildId] = {};
    
    if (autoFriendlyEnabled !== undefined) storage.data.config[guildId].autoFriendlyEnabled = !!autoFriendlyEnabled;
    if (autoFriendlyInterval !== undefined) storage.data.config[guildId].autoFriendlyInterval = parseInt(autoFriendlyInterval) || 40;
    if (autoFriendlyChannel !== undefined) storage.data.config[guildId].autoFriendlyChannel = autoFriendlyChannel;
    if (postEnabled !== undefined) storage.data.config[guildId].postEnabled = !!postEnabled;
    if (postChannelId !== undefined) storage.data.config[guildId].postChannelId = postChannelId;

    storage.save('config');
    res.json({ success: true, message: 'Settings updated successfully' });
});

// --- Command List ---
app.get('/api/commands', requireAuth, (req, res) => {
    if (!commandsDataRef) return res.json([]);

    const adminCmds = ['setup', 'post', 'clear', 'lock', 'unlock', 'giverole', 'addrole', 'removerole'];
    const staffCmds = ['win', 'loss', 'draw', 'lineup', 'managerlineup', 'leaguematch', 'lineupimage'];

    const list = commandsDataRef.map(c => ({
        name: c.name,
        description: c.description,
        admin: adminCmds.includes(c.name),
        staff: staffCmds.includes(c.name)
    }));
    res.json(list);
});

// --- Invite URL ---
app.get('/api/invite', (req, res) => {
    if (!discordClient || !discordClient.user) return res.redirect('/');
    const url = `https://discord.com/api/oauth2/authorize?client_id=${discordClient.user.id}&permissions=8&scope=bot%20applications.commands`;
    res.redirect(url);
});

// --- Logs ---
app.get('/api/logs', requireAuth, (req, res) => {
    res.json({ logs: logBuffer.slice(-100) });
});

// --- Actions ---
app.post('/api/action/:name', requireAuth, async (req, res) => {
    const action = req.params.name;

    if (action === 'sync' && discordClient && commandsDataRef) {
        let count = 0;
        for (const guild of discordClient.guilds.cache.values()) {
            await guild.commands.set(commandsDataRef).catch(() => {});
            count++;
        }
        return res.json({ message: `✅ Synced commands to ${count} servers!` });
    }

    if (action === 'backup') {
        return res.json({ message: '☁️ Cloud backup triggered! Check Discord for confirmation.' });
    }

    if (action === 'restart') {
        res.json({ message: '🔁 Restarting bot in 2 seconds...' });
        setTimeout(() => process.exit(1), 2000);
        return;
    }

    res.json({ message: 'Unknown action.' });
});

// --- Start ---
function startServer(client, cmdsData) {
    discordClient = client || null;
    commandsDataRef = cmdsData || null;

    app.listen(port, '0.0.0.0', () => {
        console.log(`[*] Web Server running on port ${port}`);
        console.log(`[*] Dashboard: ${getRedirectUri().replace('/auth/callback', '')}`);
    });
}

module.exports = { startServer, app };