Lovia / src /common /utils /telegram-init-data.util.ts
shizoki's picture
init
fb13f0c
Raw History Blame Contribute Delete
3.37 kB
import { createHmac, timingSafeEqual } from 'node:crypto';
export type TelegramWebAppUser = {
id: number;
is_bot?: boolean;
first_name?: string;
last_name?: string;
username?: string;
language_code?: string;
is_premium?: boolean;
added_to_attachment_menu?: boolean;
allows_write_to_pm?: boolean;
photo_url?: string;
};
export type ValidatedTelegramInitData = {
user: TelegramWebAppUser;
authDate: Date;
queryId?: string;
startParam?: string;
raw: Record<string, string>;
};
export class TelegramInitDataError extends Error {
constructor(message: string) {
super(message);
this.name = 'TelegramInitDataError';
}
}
function safeCompareHex(aHex: string, bHex: string): boolean {
const a = Buffer.from(aHex, 'hex');
const b = Buffer.from(bHex, 'hex');
if (a.length === 0 || b.length === 0 || a.length !== b.length) {
return false;
}
return timingSafeEqual(a, b);
}
export function validateTelegramInitData(
rawInitData: string,
botToken: string,
maxAgeSec = 86400
): ValidatedTelegramInitData {
if (!rawInitData) {
throw new TelegramInitDataError('Missing Telegram initData');
}
if (!botToken || botToken === 'replace_me') {
throw new TelegramInitDataError('BOT_TOKEN is not configured');
}
const params = new URLSearchParams(rawInitData);
const hash = params.get('hash');
if (!hash) {
throw new TelegramInitDataError('Missing hash in Telegram initData');
}
params.delete('hash');
const sortedPairs = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
const dataCheckString = sortedPairs.map(([key, value]) => `${key}=${value}`).join('\n');
const secretKey = createHmac('sha256', 'WebAppData').update(botToken).digest();
const computedHash = createHmac('sha256', secretKey).update(dataCheckString).digest('hex');
if (!safeCompareHex(hash, computedHash)) {
throw new TelegramInitDataError('Invalid Telegram initData hash');
}
const authDateRaw = params.get('auth_date');
if (!authDateRaw) {
throw new TelegramInitDataError('Missing auth_date in Telegram initData');
}
const authDateSeconds = Number(authDateRaw);
if (!Number.isFinite(authDateSeconds)) {
throw new TelegramInitDataError('Invalid auth_date in Telegram initData');
}
const authDate = new Date(authDateSeconds * 1000);
const ageSec = Math.floor((Date.now() - authDate.getTime()) / 1000);
if (maxAgeSec > 0 && ageSec > maxAgeSec) {
throw new TelegramInitDataError('Telegram initData is expired');
}
const userRaw = params.get('user');
if (!userRaw) {
throw new TelegramInitDataError('Missing user in Telegram initData');
}
let user: TelegramWebAppUser;
try {
user = JSON.parse(userRaw) as TelegramWebAppUser;
} catch {
throw new TelegramInitDataError('Invalid user JSON in Telegram initData');
}
if (!user.id) {
throw new TelegramInitDataError('Missing Telegram user id');
}
return {
user,
authDate,
queryId: params.get('query_id') ?? undefined,
startParam: params.get('start_param') ?? undefined,
raw: Object.fromEntries(params.entries())
};
}
export function getDevMockTelegramUser(): TelegramWebAppUser {
return {
id: 777000111,
first_name: 'Leandro',
last_name: '',
username: 'leandrowadevjxr',
language_code: 'ru',
is_premium: true
};
}