Created
April 17, 2022 03:33
-
-
Save zubiden/175bfed36ac186664de41f54c55e4327 to your computer and use it in GitHub Desktop.
Telegram Web Bots data validation in JavaScript via Web Crypto API (dependency-free)
This file contains hidden or 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
// Thanks to @MarvinMiles for Telegram Widget Login check function https://gist.github.com/MarvinMiles/f041205d872b0d8547d054eafeafe2a5 | |
// This function validates Web App input https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app | |
// Transforms Telegram.WebApp.initData string into object | |
function transformInitData(initData) { | |
return Object.fromEntries(new URLSearchParams(initData)); | |
} | |
// Accepts init data object and bot token | |
async function validate(data, botToken) { | |
const encoder = new TextEncoder() | |
const checkString = await Object.keys(data) | |
.filter((key) => key !== "hash") | |
.map((key) => `${key}=${data[key]}`) | |
.sort() | |
.join("\n") | |
// console.log('computed string:', checkString) | |
const secretKey = await crypto.subtle.importKey("raw", encoder.encode('WebAppData'), { name: "HMAC", hash: "SHA-256" }, true, ["sign"]) | |
const secret = await crypto.subtle.sign("HMAC", secretKey, encoder.encode(botToken)) | |
const signatureKey = await crypto.subtle.importKey("raw", secret, { name: "HMAC", hash: "SHA-256" }, true, ["sign"]) | |
const signature = await crypto.subtle.sign("HMAC", signatureKey, encoder.encode(checkString)) | |
const hex = [...new Uint8Array(signature)].map(b => b.toString(16).padStart(2, '0')).join('') | |
// console.log('original hash:', data.hash) | |
// console.log('computed hash:', hex) | |
return data.hash === hex | |
} |
Thank you so much for this! It helped a lot.
Thanks for the code.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this - it worked great for me!!