Last active
March 12, 2024 15:06
-
-
Save Pitasi/574cb19348141d7bf8de83a0555fd2dc to your computer and use it in GitHub Desktop.
Telegram website login widget, signature check sample using Node.js
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
// Copied by https://gist.github.com/dotcypress/8fd12d6e886cd74bba8f1aa8dbd346aa, | |
// thanks for improving code style | |
const { createHash, createHmac } = require('crypto'); | |
const TOKEN = "ABC:12345..."; | |
// I prefer get the secret's hash once but check the gist linked | |
// on line 1 if you prefer passing the bot token as a param | |
const secret = createHash('sha256') | |
.update(TOKEN) | |
.digest() | |
function checkSignature ({ hash, ...data }) { | |
const checkString = Object.keys(data) | |
.sort() | |
.filter((k) => data[k]) | |
.map(k => (`${k}=${data[k]}`)) | |
.join('\n'); | |
const hmac = createHmac('sha256', secret) | |
.update(checkString) | |
.digest('hex'); | |
return hmac === hash; | |
} | |
// Sample usage | |
const payload = { | |
id: '424242424242', | |
first_name: 'John', | |
last_name: 'Doe', | |
username: 'username', | |
photo_url: 'https://t.me/i/userpic/320/username.jpg', | |
auth_date: '1519400000', | |
hash: '87e5a7e644d0ee362334d92bc8ecc981ca11ffc11eca809505' | |
} | |
checkSignature(payload) |
ImTheDeveloper
commented
Nov 17, 2022
via email
Perfect!
…On 17 Nov 2022, 02:35 +0000, Liubov Pitko ***@***.***>, wrote:
@lub0v commented on this gist.
@ImTheDeveloper I had the same issue and found out that when users do not specify their last_name the hash does not match. To fix the error, I've filtered out empty data for checkString:
const checkString = Object.keys(data)
.sort()
.filter((k) => data[k])
.map(k => (`${k}=${data[k]}`))
.join('\n');
—
Reply to this email directly, view it on GitHub or unsubscribe.
You are receiving this email because you were mentioned.
Triage notifications on the go with GitHub Mobile for iOS or Android.
Thanks @lub0v, I updated the gist with your suggestion :)
Updated version
const secret = crypto.createHash('sha256')
.update(botToken?.trim())
.digest();
const checkString = Object.keys(data)
.sort()
.filter((k) => data[k])
.filter((k) => ![ 'hash' ].includes(k))
.map(k => (`${k}=${data[k]}`))
.join('\n');
const hmac = crypto.createHmac('sha256', secret)
.update(checkString)
.digest('hex');
return hmac === data.hash;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment