Help, when checking the hash it gives the error “Invalid Telegram data hash.” Perhaps someone has encountered this, I would be very grateful for your help..............................................................................................................................................................................
import https from 'https';
import express from 'express';
import crypto from 'crypto';
import jwt from 'jsonwebtoken';
import fs from 'fs';
import cors from 'cors';
const app = express();
const PORT = process.env.PORT || 3005;
const TELEGRAM_BOT_TOKEN = '';
const JWT_SECRET = '123123';
app.use(cors());
app.use(express.json());
const verifyTelegramData = (data) => {
const secret = crypto.createHash('sha256').update(TELEGRAM_BOT_TOKEN).digest();
const checkString = Object.entries(data)
.filter(([key]) => key !== 'hash')
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, value]) => `${key}=${typeof value === 'object' ? JSON.stringify(value) : value}`)
.join('\n');
const hash = crypto.createHmac('sha256', secret).update(checkString).digest('hex');
console.log('Check String:', checkString);
console.log('Calculated Hash:', hash);
console.log('Received Hash:', data.hash);
return hash === data.hash;
};
app.post('/auth/telegram', (req, res) => {
const { id, first_name, username, photo_url, auth_date, hash } = req.body;
console.log('Received Telegram data:', req.body);
if (!verifyTelegramData(req.body)) {
console.log('Invalid Telegram data hash');
return res.status(401).send('Unauthorized');
}
const token = jwt.sign({ id, first_name, username, photo_url }, JWT_SECRET, { expiresIn: '1h' });
res.json({ token, user: { id, first_name, username, photo_url } });
});
const options = {
key: fs.readFileSync('/etc/letsencrypt/live/cloa.xyz/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/cloa.xyz/fullchain.pem')
};
https.createServer(options, app).listen(PORT, () => {
console.log(`Server is running on https://localhost:${PORT}`);
});