When developing Telegram Mini Apps (TMA), one of the most common and dangerous mistakes is blindly trusting data coming from the frontend. The window.Telegram.WebApp.initDataUnsafe object provides convenient access to the user profile, but this object is entirely controlled by the client. Any attacker can edit user.id in the DevTools browser console or send an arbitrary HTTP request to your API, impersonating an administrator or another user.
In this article, we will examine in detail the attack vector via initDataUnsafe spoofing, demonstrate a working fake payload, and then build a reliable security contour on Node.js and PHP with timing-safe HMAC-SHA256 validation and signature lifetime restriction (auth_date). On the React client side, we will implement a pattern where the Telegram main button (MainButton) is activated strictly after successful verification of the token by the server.
Attack Vector: How initDataUnsafe Differs from the Raw initData String
The initDataUnsafe object is a parsed JSON formed by Telegram's client JavaScript context. Due to the absence of a cryptographic signature inside the initDataUnsafe object itself, the backend cannot verify whether Telegram actually generated this object or if the data was modified directly in browser memory.
The true source of truth is window.Telegram.WebApp.initData — a raw URL-encoded string. It contains a set of parameters (including user, auth_date, query_id) and a mandatory hash field. The hash field is a подпись HMAC-SHA256 generated by Telegram servers using a secret key derived from your bot token.
// Демонстрация спуфинга: злоумышленник подменяет user.id в initDataUnsafe
const forgedPayload = {
query_id: "AAH...",
user: {
id: 999999999, // Поддельный ID администратора или жертвы
first_name: "Attacker",
username: "fake_account"
},
auth_date: Math.floor(Date.now() / 1000)
};
// Если бэкенд принимает user.id из тела POST-запроса без проверки HMAC:
// fetch('/api/user/balance', { method: 'POST', body: JSON.stringify({ userId: forgedPayload.user.id }) });
// Сервер вернет данные чужого аккаунта!If the server relies on the passed client user.id without validating the hash signature, the system becomes vulnerable to unauthorized access, balance deductions, and theft of personal data.
Client-Side Logic in React: Blocking MainButton Until auth 200 OK
To prevent unauthorized user actions, the application interface must remain locked until the server confirms the authenticity of the session. We will hide and deactivate MainButton on application startup, send tg.initData to the /api/auth endpoint, and enable the button only after receiving an HTTP status of 200 OK.
import React, { useEffect, useState } from 'react';
// Доступ к объектной модели Telegram WebApp
const tg = window.Telegram?.WebApp;
export const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
if (!tg) {
setError('Открывайте приложение внутри Telegram');
return;
}
// Блокируем MainButton по умолчанию
tg.MainButton.hide();
tg.MainButton.disable();
const rawInitData = tg.initData;
if (!rawInitData) {
setError('Отсутствуют данные инициализации Telegram (initData)');
return;
}
// Передаем сырую строку initData на бэкенд
fetch('/api/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ initData: rawInitData }),
})
.then(async (res) => {
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.message || 'Ошибка аутентификации');
}
return res.json();
})
.then((data) => {
setIsAuthenticated(true);
// Включаем и показываем MainButton ТОЛЬКО после ответа 200 OK от сервера
tg.MainButton.setText('Оформить заказ');
tg.MainButton.onClick(() => {
tg.sendData(JSON.stringify({ action: 'create_order', userId: data.userId }));
});
tg.MainButton.enable();
tg.MainButton.show();
})
.catch((err) => {
setError(err.message);
tg.MainButton.hide();
tg.MainButton.disable();
});
}, []);
if (error) {
return <div className="error-screen">Доступ ограничен: {error}</div>;
}
return (
<div className="app-container">
<h2>{isAuthenticated ? 'Сессия подтверждена' : 'Проверка авторизации...'}</h2>
</div>
);
};initData Validation in Node.js: HMAC-SHA256, Timing-Safe Compare, and auth_date
The initData verification algorithm on the backend consists of five steps:
- Extract the
hashparameter from theinitDataquery string. - Exclude the
hashkey from the parameter list. - Sort the remaining
key=valuepairs alphabetically and join them with a newline character (), formingdata_check_string. - Calculate секретный ключ:
HMAC-SHA256("WebAppData", bot_token). - Generate the final HMAC hash of
data_check_stringusing the derived secret key and compare it withhashviacrypto.timingSafeEqual(to protect against timing attacks).
Additionally, the age of the auth_date timestamp must be checked. If the signature was generated a long time ago (for example, more than 86,400 seconds ago), the request is rejected, protecting against replay attacks.
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
const BOT_TOKEN = process.env.BOT_TOKEN;
const MAX_AUTH_AGE_SECONDS = 86400; // 24 часа
function verifyTelegramInitData(initDataRaw) {
if (!initDataRaw || !BOT_TOKEN) return { valid: false };
const params = new URLSearchParams(initDataRaw);
const hash = params.get('hash');
if (!hash) return { valid: false };
params.delete('hash');
// Сортировка ключей по алфавиту и сборка data_check_string
const dataCheckArr = [];
for (const [key, value] of params.entries()) {
dataCheckArr.push(`${key}=${value}`);
}
dataCheckArr.sort();
const dataCheckString = dataCheckArr.join('
');
// 1. Secret key = HMAC-SHA256("WebAppData", BOT_TOKEN)
const secretKey = crypto
.createHmac('sha256', 'WebAppData')
.update(BOT_TOKEN)
.digest();
// 2. Calculated hash = HMAC-SHA256(dataCheckString, secretKey)
const calculatedHash = crypto
.createHmac('sha256', secretKey)
.update(dataCheckString)
.digest('hex');
// 3. Timing-safe сравнение хешей
const hashBuffer = Buffer.from(hash, 'hex');
const calcBuffer = Buffer.from(calculatedHash, 'hex');
if (hashBuffer.length !== calcBuffer.length || !crypto.timingSafeEqual(hashBuffer, calcBuffer)) {
return { valid: false };
}
// 4. Проверка времени жизни подписи auth_date
const authDate = parseInt(params.get('auth_date') || '0', 10);
const currentTime = Math.floor(Date.now() / 1000);
if (currentTime - authDate > MAX_AUTH_AGE_SECONDS) {
return { valid: false, expired: true };
}
const user = JSON.parse(params.get('user') || '{}');
return { valid: true, user };
}
app.post('/api/auth', (req, res) => {
const { initData } = req.body;
const result = verifyTelegramInitData(initData);
if (!result.valid) {
return res.status(401).json({
ok: false,
message: result.expired ? 'Срок действия подписи истек' : 'Поддельная подпись initData'
});
}
// Авторизация успешна. Выдаем JWT или открываем сессию по result.user.id
return res.json({ ok: true, userId: result.user.id });
});
app.listen(3000, () => console.log('Auth API running on port 3000'));Server-Side Verification Implementation in PHP
If the backend is written in PHP (Yii2, Laravel, or чистый PHP), the verification logic is identical. For safe timing-safe comparison, we use the built-in function hash_equals().
<?php
declare(strict_types=1);
$botToken = getenv('BOT_TOKEN') ?: '';
$input = json_decode(file_get_contents('php://input'), true);
$initData = $input['initData'] ?? '';
function validateInitData(string $initData, string $botToken, int $maxAge = 86400): ?array {
if (empty($initData) || empty($botToken)) {
return null;
}
parse_str($initData, $params);
$hash = $params['hash'] ?? null;
if (!$hash) {
return null;
}
unset($params['hash']);
// Сортировка ключей по алфавиту
ksort($params);
$dataCheckArr = [];
foreach ($params as $key => $val) {
$dataCheckArr[] = $key . '=' . $val;
}
$dataCheckString = implode("
", $dataCheckArr);
// Расчет secret_key и хеша
$secretKey = hash_hmac('sha256', $botToken, 'WebAppData', true);
$calculatedHash = hash_hmac('sha256', $dataCheckString, $secretKey);
// Сравнение хешей без уязвимости к timing-атакам
if (!hash_equals($calculatedHash, $hash)) {
return null;
}
// Проверка свежести auth_date
$authDate = (int)($params['auth_date'] ?? 0);
if ((time() - $authDate) > $maxAge) {
return null;
}
return json_decode($params['user'] ?? '{}', true);
}
$user = validateInitData($initData, $botToken);
if (!$user) {
http_response_code(401);
echo json_encode(['ok' => false, 'error' => 'Invalid initData signature']);
exit;
}
http_response_code(200);
echo json_encode(['ok' => true, 'userId' => $user['id']]);Common Mistakes When Working with initData in Mini Apps
- Using standard
==or===operators: Using standard string comparison makes the system vulnerable to timing attacks. Always usecrypto.timingSafeEqualin Node.js orhash_equals()in PHP. - Ignoring auth_date: Without checking the expiration time, an intercepted valid
initDatastring can be used indefinitely by an attacker (Replay Attack). - Parsing initDataUnsafe on the backend: The backend should only accept the raw
initDatastring and parse theuserparameter only after validating the hash. - Trusting the client before receiving HTTP 200: Displaying sensitive interface elements or unlocking
MainButtonbefore the server responds allows frontend restrictions to be bypassed.
Developing reliable Telegram-бот s and Mini Apps requires strict adherence to security rules. If you need professional development or auditing of Telegram systems, contact the experts at BotCreator.