-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
60 lines (51 loc) · 1.48 KB
/
index.ts
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
import 'dotenv/config';
import Fastify, { FastifyReply, FastifyRequest } from 'fastify';
import { APIInteraction, InteractionResponseType, InteractionType } from 'discord-api-types/v10';
import { verify } from 'discord-verify/node';
const PUBLIC_KEY = process.env.PUBLIC_KEY as string;
const fastify = Fastify({
logger: true,
});
fastify.get('/interactions', (req, res) => {
fastify.log.info('Handling GET request');
});
fastify.addHook(
'preHandler',
async (
req: FastifyRequest<{
Body: APIInteraction;
Headers: {
'x-signature-ed25519': string;
'x-signature-timestamp': string;
};
}>,
res: FastifyReply
) => {
if (req.method === 'POST') {
const signature = req.headers['x-signature-ed25519'];
const timestamp = req.headers['x-signature-timestamp'];
const rawBody = JSON.stringify(req.body);
const isValid = await verify(rawBody, signature, timestamp, PUBLIC_KEY, crypto.subtle);
if (!isValid) {
fastify.log.info('Invalid signature');
return res.code(401).send('Invalid signature');
}
}
}
);
fastify.post('/interactions', (req, res) => {
const message = req.body as APIInteraction;
if (message.type === InteractionType.Ping) {
fastify.log.info('Handling Ping Request');
return res.send({ type: InteractionResponseType.Pong });
} else {
fastify.log.error('Unknown Type');
return res.send({ error: 'Unknown Type' });
}
});
fastify.listen({ port: 3000 }, (err, address) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
});