-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
validate-hash.ts
63 lines (48 loc) · 1.64 KB
/
validate-hash.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
import { webcrypto } from 'crypto';
import type { NextApiRequest, NextApiResponse } from 'next';
type Data = { ok: boolean } | { error: string };
export default async function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
if (!req.body.hash) {
return res.status(400).json({
error: 'Missing required field hash',
});
}
if (!process.env.BOT_TOKEN) {
return res.status(500).json({ error: 'Internal server error' });
}
const data = Object.fromEntries(new URLSearchParams(req.body.hash));
const isValid = await isHashValid(data, process.env.BOT_TOKEN);
if (isValid) {
return res.status(200).json({ ok: true });
}
return res.status(403).json({ error: 'Invalid hash' });
}
async function isHashValid(data: Record<string, string>, botToken: string) {
const encoder = new TextEncoder();
const checkString = Object.keys(data)
.filter((key) => key !== 'hash')
.map((key) => `${key}=${data[key]}`)
.sort()
.join('\n');
const secretKey = await webcrypto.subtle.importKey(
'raw',
encoder.encode('WebAppData'),
{ name: 'HMAC', hash: 'SHA-256' },
true,
['sign']
);
const secret = await webcrypto.subtle.sign('HMAC', secretKey, encoder.encode(botToken));
const signatureKey = await webcrypto.subtle.importKey(
'raw',
secret,
{ name: 'HMAC', hash: 'SHA-256' },
true,
['sign']
);
const signature = await webcrypto.subtle.sign('HMAC', signatureKey, encoder.encode(checkString));
const hex = Buffer.from(signature).toString('hex');
return data.hash === hex;
}