-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathindex.ts
208 lines (195 loc) · 5.18 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
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
import type { NextFunction, Request, Response } from 'express';
import { concatUint8Arrays, subtleCrypto, valueToUint8Array } from './util';
/**
* The type of interaction this request is.
*/
export enum InteractionType {
/**
* A ping.
*/
PING = 1,
/**
* A command invocation.
*/
APPLICATION_COMMAND = 2,
/**
* Usage of a message's component.
*/
MESSAGE_COMPONENT = 3,
/**
* An interaction sent when an application command option is filled out.
*/
APPLICATION_COMMAND_AUTOCOMPLETE = 4,
/**
* An interaction sent when a modal is submitted.
*/
MODAL_SUBMIT = 5,
}
/**
* The type of response that is being sent.
*/
export enum InteractionResponseType {
/**
* Acknowledge a `PING`.
*/
PONG = 1,
/**
* Respond with a message, showing the user's input.
*/
CHANNEL_MESSAGE_WITH_SOURCE = 4,
/**
* Acknowledge a command without sending a message, showing the user's input. Requires follow-up.
*/
DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5,
/**
* Acknowledge an interaction and edit the original message that contains the component later; the user does not see a loading state.
*/
DEFERRED_UPDATE_MESSAGE = 6,
/**
* Edit the message the component was attached to.
*/
UPDATE_MESSAGE = 7,
/*
* Callback for an app to define the results to the user.
*/
APPLICATION_COMMAND_AUTOCOMPLETE_RESULT = 8,
/*
* Respond with a modal.
*/
MODAL = 9,
/*
* Respond with an upgrade prompt.
*/
PREMIUM_REQUIRED = 10,
/**
* Launch an Activity.
*/
LAUNCH_ACTIVITY = 12,
}
/**
* Flags that can be included in an Interaction Response.
*/
export enum InteractionResponseFlags {
/**
* Show the message only to the user that performed the interaction. Message
* does not persist between sessions.
*/
EPHEMERAL = 1 << 6,
}
/**
* Validates a payload from Discord against its signature and key.
*
* @param rawBody - The raw payload data
* @param signature - The signature from the `X-Signature-Ed25519` header
* @param timestamp - The timestamp from the `X-Signature-Timestamp` header
* @param clientPublicKey - The public key from the Discord developer dashboard
* @returns Whether or not validation was successful
*/
export async function verifyKey(
rawBody: Uint8Array | ArrayBuffer | Buffer | string,
signature: string,
timestamp: string,
clientPublicKey: string | CryptoKey,
): Promise<boolean> {
try {
const timestampData = valueToUint8Array(timestamp);
const bodyData = valueToUint8Array(rawBody);
const message = concatUint8Arrays(timestampData, bodyData);
const publicKey =
typeof clientPublicKey === 'string'
? await subtleCrypto.importKey(
'raw',
valueToUint8Array(clientPublicKey, 'hex'),
{
name: 'ed25519',
namedCurve: 'ed25519',
},
false,
['verify'],
)
: clientPublicKey;
const isValid = await subtleCrypto.verify(
{
name: 'ed25519',
},
publicKey,
valueToUint8Array(signature, 'hex'),
message,
);
return isValid;
} catch (ex) {
return false;
}
}
/**
* Creates a middleware function for use in Express-compatible web servers.
*
* @param clientPublicKey - The public key from the Discord developer dashboard
* @returns The middleware function
*/
export function verifyKeyMiddleware(
clientPublicKey: string,
): (req: Request, res: Response, next: NextFunction) => void {
if (!clientPublicKey) {
throw new Error('You must specify a Discord client public key');
}
return async (req: Request, res: Response, next: NextFunction) => {
const timestamp = req.header('X-Signature-Timestamp') || '';
const signature = req.header('X-Signature-Ed25519') || '';
if (!timestamp || !signature) {
res.statusCode = 401;
res.end('[discord-interactions] Invalid signature');
return;
}
async function onBodyComplete(rawBody: Buffer) {
const isValid = await verifyKey(
rawBody,
signature,
timestamp,
clientPublicKey,
);
if (!isValid) {
res.statusCode = 401;
res.end('[discord-interactions] Invalid signature');
return;
}
const body = JSON.parse(rawBody.toString('utf-8')) || {};
if (body.type === InteractionType.PING) {
res.setHeader('Content-Type', 'application/json');
res.end(
JSON.stringify({
type: InteractionResponseType.PONG,
}),
);
return;
}
req.body = body;
next();
}
if (req.body) {
if (Buffer.isBuffer(req.body)) {
await onBodyComplete(req.body);
} else if (typeof req.body === 'string') {
await onBodyComplete(Buffer.from(req.body, 'utf-8'));
} else {
console.warn(
'[discord-interactions]: req.body was tampered with, probably by some other middleware. We recommend disabling middleware for interaction routes so that req.body is a raw buffer.',
);
// Attempt to reconstruct the raw buffer. This works but is risky
// because it depends on JSON.stringify matching the Discord backend's
// JSON serialization.
await onBodyComplete(Buffer.from(JSON.stringify(req.body), 'utf-8'));
}
} else {
const chunks: Array<Buffer> = [];
req.on('data', (chunk) => {
chunks.push(chunk);
});
req.on('end', async () => {
const rawBody = Buffer.concat(chunks);
await onBodyComplete(rawBody);
});
}
};
}
export * from './components';