Spaces:
Sleeping
Sleeping
File size: 6,247 Bytes
f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb f47ea65 e903adb 11121e3 e903adb 11121e3 f47ea65 11121e3 6890a49 11121e3 bc1774c 6890a49 0a8169b 11121e3 0a8169b 11121e3 6890a49 e903adb 11121e3 f47ea65 e903adb 11121e3 0a8169b 11121e3 e903adb 11121e3 bc1774c 11121e3 6890a49 5aeb8a2 11121e3 e903adb f47ea65 11121e3 f47ea65 e903adb 11121e3 e903adb 11121e3 f47ea65 e903adb 11121e3 f47ea65 11121e3 e903adb 11121e3 e903adb 11121e3 e903adb 11121e3 f47ea65 e903adb f47ea65 e903adb 11121e3 f47ea65 e903adb 0a8169b | 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 | import { Router } from 'express';
import { verifyKey } from 'discord-interactions';
import { generateWelcomeCard } from './canvas/welcomeCard.js';
import { generateLeaveCard } from './canvas/leaveCard.js';
import * as setupCmd from './commands/setup.js';
import * as welcomeMessageCmd from './commands/welcome-message.js';
import * as leaveMessageCmd from './commands/leave-message.js';
import * as welcomeBackgroundCmd from './commands/welcome-background.js';
import * as leaveBackgroundCmd from './commands/leave-background.js';
import * as previewCmd from './commands/preview.js';
import * as resetCmd from './commands/reset.js';
const commands = new Map([
['setup', setupCmd],
['welcome-message', welcomeMessageCmd],
['leave-message', leaveMessageCmd],
['welcome-background', welcomeBackgroundCmd],
['leave-background', leaveBackgroundCmd],
['preview', previewCmd],
['reset', resetCmd],
]);
const router = Router();
// GET /health
router.get('/health', (req, res) => {
res.json({
status: 'ok',
uptime: Math.round(process.uptime()),
timestamp: new Date().toISOString(),
});
});
// POST /generate/welcome
router.post('/generate/welcome', async (req, res) => {
if (req.headers['x-api-secret'] !== process.env.API_SECRET) {
return res.status(401).json({ error: 'unauthorized' });
}
try {
const buffer = await generateWelcomeCard(req.body);
res.set('Content-Type', 'image/png');
res.send(buffer);
} catch (err) {
console.error('[router] /generate/welcome failed:', err.message);
res.status(500).json({ error: 'card generation failed' });
}
});
// POST /generate/leave
router.post('/generate/leave', async (req, res) => {
if (req.headers['x-api-secret'] !== process.env.API_SECRET) {
return res.status(401).json({ error: 'unauthorized' });
}
try {
const buffer = await generateLeaveCard(req.body);
res.set('Content-Type', 'image/png');
res.send(buffer);
} catch (err) {
console.error('[router] /generate/leave failed:', err.message);
res.status(500).json({ error: 'card generation failed' });
}
});
// ==================== FIXED & LOGGED INTERACTIONS ENDPOINT ====================
router.post('/interactions', async (req, res) => {
console.log('[interactions] π₯ Processing /interactions webhook inbound request...');
// Log specific security-critical headers
const signature = req.headers['x-signature-ed25519'];
const timestamp = req.headers['x-signature-timestamp'];
console.log(`[interactions] Headers received -> x-signature-ed25519: ${signature || 'MISSING'}`);
console.log(`[interactions] Headers received -> x-signature-timestamp: ${timestamp || 'MISSING'}`);
if (!signature || !timestamp) {
console.error('[interactions] β Verification aborted: Missing vital security headers.');
return res.status(401).end('Missing headers');
}
if (!req.rawBody) {
console.error('[interactions] β Verification aborted: req.rawBody is undefined or empty.');
return res.status(400).end('Missing request body raw data');
}
const rawBodyString = req.rawBody.toString('utf8');
console.log(`[interactions] Exact Raw Payload Text:\n${rawBodyString}`);
// Perform cryptographic signature verification
let isValid = false;
try {
isValid = verifyKey(
rawBodyString,
signature,
timestamp,
process.env.DISCORD_PUBLIC_KEY
);
} catch (cryptoErr) {
console.error('[interactions] π₯ Library crashed during verifyKey computation:', cryptoErr.message);
}
if (!isValid) {
console.error('[interactions] β INVALID SIGNATURE MATCH. Discord rejection triggered.');
console.error(`[interactions] Verified against Public Key Length: ${process.env.DISCORD_PUBLIC_KEY?.length || 0} characters.`);
return res.status(401).end('Bad request signature');
}
console.log('[interactions] SIGNATURE VALIDATED SUCCESSFULLY.');
const interaction = req.body;
console.log('[interactions] Parsed Interaction Body structure:', JSON.stringify(interaction, null, 2));
// Helper method to wrap response commands so we can audit outgoing packages
const sendLoggedJson = (statusCode, payload) => {
console.log(`[interactions] π€ Outgoing Response [HTTP ${statusCode}]:`, JSON.stringify(payload, null, 2));
res.setHeader('Content-Type', 'application/json');
return res.status(statusCode).json(payload);
};
// === Handle PING Handshake ===
if (interaction.type === 1) {
console.log('[interactions] Detected type: 1 (PING). Processing fast handshake...');
return sendLoggedJson(200, { type: 1 });
}
// === Handle Slash Commands ===
if (interaction.type === 2) {
const commandName = interaction.data?.name;
console.log(`[interactions] π» Detected type: 2 (APPLICATION_COMMAND). Executing: /${commandName}`);
const command = commands.get(commandName);
if (!command) {
console.warn(`[interactions] β οΈ No executable code file matched command map for: /${commandName}`);
return sendLoggedJson(200, {
type: 4,
data: { content: `Unknown command: ${commandName}`, flags: 64 }
});
}
try {
// Intercept the response streaming inside commands
const originalJson = res.json.bind(res);
res.json = (data) => {
console.log(`[interactions] π€ Command [/${commandName}] sent response object:`, JSON.stringify(data, null, 2));
return originalJson(data);
};
await command.execute(interaction, res);
console.log(`[interactions] Finished execution for command file: /${commandName}`);
} catch (err) {
console.error(`[interactions] π₯ Internal error during execution of /${commandName}:`, err.stack);
if (!res.headersSent) {
return sendLoggedJson(200, {
type: 4,
data: { content: 'An unexpected application error occurred inside the bot logic.', flags: 64 }
});
}
}
return;
}
// Handle unexpected interaction types
console.warn(`[interactions] β οΈ Fallback triggered: Type ${interaction.type} is unmapped.`);
return sendLoggedJson(200, { type: 4, data: { content: 'Unsupported interaction structure.', flags: 64 } });
});
export default router;
|