gateway-services / src /router.js
Archnemix's picture
Update src/router.js
11121e3 verified
Raw History Blame Contribute Delete
6.25 kB
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;