Last active
April 28, 2022 08:27
-
-
Save shlyk/0facaccd939c613da736d677bb41b3fa to your computer and use it in GitHub Desktop.
Web Apps for Telegram Bots: Validating data received via the Web App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createHmac } from 'crypto'; | |
function isValidSignature(checkString) { | |
const decoded = decodeURIComponent(checkString) | |
.split('&') | |
.map(chunk => chunk.split('=')) | |
.reduce((accumulator, [key, value]) => ({ ...accumulator, [key]: value }), {}); | |
const user = JSON.parse(decoded.user); | |
const dataCheckString = Object.entries(decoded) | |
.filter(([key]) => key !== 'hash') | |
.map(([key, value]) => `${key}=${value}`) | |
.sort() | |
.join('\n'); | |
const secretKey = createHmac('sha256', 'WebAppData') | |
.update(process.env.TELEGRAM_BOT_TOKEN) | |
.digest(); | |
const hmac = createHmac('sha256', secretKey) | |
.update(dataCheckString, 'utf-8') | |
.digest('hex'); | |
const isValid = hmac === decoded.hash; | |
return { isValid, user }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment