Spaces:
Sleeping
Sleeping
Update src/router.js
Browse files- src/router.js +61 -74
src/router.js
CHANGED
|
@@ -1,14 +1,15 @@
|
|
| 1 |
-
import { Router } from 'express'
|
| 2 |
-
import { verifyKey } from 'discord-interactions'
|
| 3 |
-
import { generateWelcomeCard } from './canvas/welcomeCard.js'
|
| 4 |
-
import { generateLeaveCard } from './canvas/leaveCard.js'
|
| 5 |
-
|
| 6 |
-
import * as
|
| 7 |
-
import * as
|
| 8 |
-
import * as
|
| 9 |
-
import * as
|
| 10 |
-
import * as
|
| 11 |
-
import * as
|
|
|
|
| 12 |
|
| 13 |
const commands = new Map([
|
| 14 |
['setup', setupCmd],
|
|
@@ -18,9 +19,9 @@ const commands = new Map([
|
|
| 18 |
['leave-background', leaveBackgroundCmd],
|
| 19 |
['preview', previewCmd],
|
| 20 |
['reset', resetCmd],
|
| 21 |
-
])
|
| 22 |
|
| 23 |
-
const router = Router()
|
| 24 |
|
| 25 |
// GET /health
|
| 26 |
router.get('/health', (req, res) => {
|
|
@@ -28,122 +29,108 @@ router.get('/health', (req, res) => {
|
|
| 28 |
status: 'ok',
|
| 29 |
uptime: Math.round(process.uptime()),
|
| 30 |
timestamp: new Date().toISOString(),
|
| 31 |
-
})
|
| 32 |
-
})
|
| 33 |
|
| 34 |
// POST /generate/welcome
|
| 35 |
router.post('/generate/welcome', async (req, res) => {
|
| 36 |
if (req.headers['x-api-secret'] !== process.env.API_SECRET) {
|
| 37 |
-
return res.status(401).json({ error: 'unauthorized' })
|
| 38 |
}
|
| 39 |
try {
|
| 40 |
-
const buffer = await generateWelcomeCard(req.body)
|
| 41 |
-
res.set('Content-Type', 'image/png')
|
| 42 |
-
res.send(buffer)
|
| 43 |
} catch (err) {
|
| 44 |
-
console.error('[router] /generate/welcome failed:', err.message)
|
| 45 |
-
res.status(500).json({ error: 'card generation failed' })
|
| 46 |
}
|
| 47 |
-
})
|
| 48 |
|
| 49 |
// POST /generate/leave
|
| 50 |
router.post('/generate/leave', async (req, res) => {
|
| 51 |
if (req.headers['x-api-secret'] !== process.env.API_SECRET) {
|
| 52 |
-
return res.status(401).json({ error: 'unauthorized' })
|
| 53 |
}
|
| 54 |
try {
|
| 55 |
-
const buffer = await generateLeaveCard(req.body)
|
| 56 |
-
res.set('Content-Type', 'image/png')
|
| 57 |
-
res.send(buffer)
|
| 58 |
} catch (err) {
|
| 59 |
-
console.error('[router] /generate/leave failed:', err.message)
|
| 60 |
-
res.status(500).json({ error: 'card generation failed' })
|
| 61 |
}
|
| 62 |
-
})
|
| 63 |
|
| 64 |
-
//
|
| 65 |
router.post('/interactions', async (req, res) => {
|
| 66 |
-
const signature = req.headers['x-signature-ed25519']
|
| 67 |
-
const timestamp = req.headers['x-signature-timestamp']
|
| 68 |
|
| 69 |
-
// Basic headers check
|
| 70 |
if (!signature || !timestamp) {
|
| 71 |
-
console.warn('[interactions] Missing signature or timestamp
|
| 72 |
-
return res.status(401).end('Missing signature headers')
|
| 73 |
}
|
| 74 |
|
| 75 |
-
console.log('[interactions] Verifying signature...')
|
| 76 |
|
| 77 |
const isValid = verifyKey(
|
| 78 |
-
req.rawBody,
|
| 79 |
signature,
|
| 80 |
timestamp,
|
| 81 |
process.env.DISCORD_PUBLIC_KEY
|
| 82 |
-
)
|
| 83 |
|
| 84 |
if (!isValid) {
|
| 85 |
-
console.error('[interactions] ❌ Invalid signature
|
| 86 |
-
|
| 87 |
-
console.error('[interactions] Timestamp:', timestamp)
|
| 88 |
-
return res.status(401).end('Bad request signature')
|
| 89 |
}
|
| 90 |
|
| 91 |
-
console.log('[interactions] ✅ Signature valid')
|
| 92 |
|
| 93 |
-
let interaction
|
| 94 |
try {
|
| 95 |
-
interaction = JSON.parse(req.rawBody)
|
| 96 |
-
} catch (
|
| 97 |
-
console.error('[interactions] Failed to parse interaction JSON')
|
| 98 |
-
return res.status(400).
|
| 99 |
}
|
| 100 |
|
| 101 |
-
// PING
|
| 102 |
if (interaction.type === 1) {
|
| 103 |
-
console.log('[interactions] PING received, sending PONG')
|
| 104 |
-
|
| 105 |
-
// Small delay helps with HF Spaces + Discord validation
|
| 106 |
-
await new Promise(resolve => setTimeout(resolve, 250))
|
| 107 |
-
|
| 108 |
-
return res.status(200).json({ type: 1 })
|
| 109 |
}
|
| 110 |
|
| 111 |
// APPLICATION_COMMAND
|
| 112 |
if (interaction.type === 2) {
|
| 113 |
-
const commandName = interaction.data?.name
|
| 114 |
-
console.log(`[interactions]
|
| 115 |
|
| 116 |
-
const command = commands.get(commandName)
|
| 117 |
if (!command) {
|
| 118 |
-
console.warn(`[interactions] Unknown command: "${commandName}"`)
|
| 119 |
return res.json({
|
| 120 |
type: 4,
|
| 121 |
data: { content: 'Unknown command.', flags: 64 },
|
| 122 |
-
})
|
| 123 |
}
|
| 124 |
|
| 125 |
-
console.log(`[interactions] Executing command: "${commandName}"`)
|
| 126 |
try {
|
| 127 |
-
await command.execute(interaction, res)
|
| 128 |
-
console.log(`[interactions] Command "${commandName}" completed`)
|
| 129 |
} catch (err) {
|
| 130 |
-
console.error(`[
|
| 131 |
if (!res.headersSent) {
|
| 132 |
res.json({
|
| 133 |
type: 4,
|
| 134 |
data: { content: 'An error occurred while running that command.', flags: 64 },
|
| 135 |
-
})
|
| 136 |
}
|
| 137 |
}
|
| 138 |
-
return
|
| 139 |
}
|
| 140 |
|
| 141 |
-
//
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
type: 4,
|
| 145 |
-
data: { content: 'Unsupported interaction type.', flags: 64 }
|
| 146 |
-
})
|
| 147 |
-
})
|
| 148 |
|
| 149 |
-
export default router
|
|
|
|
| 1 |
+
import { Router } from 'express';
|
| 2 |
+
import { verifyKey } from 'discord-interactions';
|
| 3 |
+
import { generateWelcomeCard } from './canvas/welcomeCard.js';
|
| 4 |
+
import { generateLeaveCard } from './canvas/leaveCard.js';
|
| 5 |
+
|
| 6 |
+
import * as setupCmd from './commands/setup.js';
|
| 7 |
+
import * as welcomeMessageCmd from './commands/welcome-message.js';
|
| 8 |
+
import * as leaveMessageCmd from './commands/leave-message.js';
|
| 9 |
+
import * as welcomeBackgroundCmd from './commands/welcome-background.js';
|
| 10 |
+
import * as leaveBackgroundCmd from './commands/leave-background.js';
|
| 11 |
+
import * as previewCmd from './commands/preview.js';
|
| 12 |
+
import * as resetCmd from './commands/reset.js';
|
| 13 |
|
| 14 |
const commands = new Map([
|
| 15 |
['setup', setupCmd],
|
|
|
|
| 19 |
['leave-background', leaveBackgroundCmd],
|
| 20 |
['preview', previewCmd],
|
| 21 |
['reset', resetCmd],
|
| 22 |
+
]);
|
| 23 |
|
| 24 |
+
const router = Router();
|
| 25 |
|
| 26 |
// GET /health
|
| 27 |
router.get('/health', (req, res) => {
|
|
|
|
| 29 |
status: 'ok',
|
| 30 |
uptime: Math.round(process.uptime()),
|
| 31 |
timestamp: new Date().toISOString(),
|
| 32 |
+
});
|
| 33 |
+
});
|
| 34 |
|
| 35 |
// POST /generate/welcome
|
| 36 |
router.post('/generate/welcome', async (req, res) => {
|
| 37 |
if (req.headers['x-api-secret'] !== process.env.API_SECRET) {
|
| 38 |
+
return res.status(401).json({ error: 'unauthorized' });
|
| 39 |
}
|
| 40 |
try {
|
| 41 |
+
const buffer = await generateWelcomeCard(req.body);
|
| 42 |
+
res.set('Content-Type', 'image/png');
|
| 43 |
+
res.send(buffer);
|
| 44 |
} catch (err) {
|
| 45 |
+
console.error('[router] /generate/welcome failed:', err.message);
|
| 46 |
+
res.status(500).json({ error: 'card generation failed' });
|
| 47 |
}
|
| 48 |
+
});
|
| 49 |
|
| 50 |
// POST /generate/leave
|
| 51 |
router.post('/generate/leave', async (req, res) => {
|
| 52 |
if (req.headers['x-api-secret'] !== process.env.API_SECRET) {
|
| 53 |
+
return res.status(401).json({ error: 'unauthorized' });
|
| 54 |
}
|
| 55 |
try {
|
| 56 |
+
const buffer = await generateLeaveCard(req.body);
|
| 57 |
+
res.set('Content-Type', 'image/png');
|
| 58 |
+
res.send(buffer);
|
| 59 |
} catch (err) {
|
| 60 |
+
console.error('[router] /generate/leave failed:', err.message);
|
| 61 |
+
res.status(500).json({ error: 'card generation failed' });
|
| 62 |
}
|
| 63 |
+
});
|
| 64 |
|
| 65 |
+
// ==================== FIXED INTERACTIONS ENDPOINT ====================
|
| 66 |
router.post('/interactions', async (req, res) => {
|
| 67 |
+
const signature = req.headers['x-signature-ed25519'];
|
| 68 |
+
const timestamp = req.headers['x-signature-timestamp'];
|
| 69 |
|
|
|
|
| 70 |
if (!signature || !timestamp) {
|
| 71 |
+
console.warn('[interactions] Missing signature or timestamp');
|
| 72 |
+
return res.status(401).end('Missing signature headers');
|
| 73 |
}
|
| 74 |
|
| 75 |
+
console.log('[interactions] Verifying signature...');
|
| 76 |
|
| 77 |
const isValid = verifyKey(
|
| 78 |
+
req.rawBody, // Must be Buffer
|
| 79 |
signature,
|
| 80 |
timestamp,
|
| 81 |
process.env.DISCORD_PUBLIC_KEY
|
| 82 |
+
);
|
| 83 |
|
| 84 |
if (!isValid) {
|
| 85 |
+
console.error('[interactions] ❌ Invalid signature');
|
| 86 |
+
return res.status(401).end('Bad request signature');
|
|
|
|
|
|
|
| 87 |
}
|
| 88 |
|
| 89 |
+
console.log('[interactions] ✅ Signature valid');
|
| 90 |
|
| 91 |
+
let interaction;
|
| 92 |
try {
|
| 93 |
+
interaction = JSON.parse(req.rawBody.toString());
|
| 94 |
+
} catch (e) {
|
| 95 |
+
console.error('[interactions] Failed to parse interaction JSON');
|
| 96 |
+
return res.status(400).end('Bad JSON');
|
| 97 |
}
|
| 98 |
|
| 99 |
+
// PING
|
| 100 |
if (interaction.type === 1) {
|
| 101 |
+
console.log('[interactions] PING received, sending PONG');
|
| 102 |
+
return res.status(200).json({ type: 1 });
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
}
|
| 104 |
|
| 105 |
// APPLICATION_COMMAND
|
| 106 |
if (interaction.type === 2) {
|
| 107 |
+
const commandName = interaction.data?.name;
|
| 108 |
+
console.log(`[interactions] Command received: "${commandName}"`);
|
| 109 |
|
| 110 |
+
const command = commands.get(commandName);
|
| 111 |
if (!command) {
|
|
|
|
| 112 |
return res.json({
|
| 113 |
type: 4,
|
| 114 |
data: { content: 'Unknown command.', flags: 64 },
|
| 115 |
+
});
|
| 116 |
}
|
| 117 |
|
|
|
|
| 118 |
try {
|
| 119 |
+
await command.execute(interaction, res);
|
|
|
|
| 120 |
} catch (err) {
|
| 121 |
+
console.error(`[router] Command "${commandName}" error:`, err.message);
|
| 122 |
if (!res.headersSent) {
|
| 123 |
res.json({
|
| 124 |
type: 4,
|
| 125 |
data: { content: 'An error occurred while running that command.', flags: 64 },
|
| 126 |
+
});
|
| 127 |
}
|
| 128 |
}
|
| 129 |
+
return;
|
| 130 |
}
|
| 131 |
|
| 132 |
+
// Fallback
|
| 133 |
+
res.json({ type: 4, data: { content: 'Unsupported interaction type.', flags: 64 } });
|
| 134 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
export default router;
|