feat: add Telegram account linking UI with CSRF protection

- TelegramLinkWidget component with Login Widget for browser users
- One-click initData linking for Mini App users
- LinkTelegramCallback page with CSRF state validation
- URL credential clearing via history.replaceState
- Merge flow support with replace navigation
- i18n keys for all 4 locales (ru, en, zh, fa)
This commit is contained in:
Fringg
2026-03-04 17:03:48 +03:00
parent 584f00297b
commit a6fabb1d9d
8 changed files with 256 additions and 13 deletions

View File

@@ -41,6 +41,7 @@ const TopUpMethodSelect = lazy(() => import('./pages/TopUpMethodSelect'));
const TopUpAmount = lazy(() => import('./pages/TopUpAmount'));
const ConnectedAccounts = lazy(() => import('./pages/ConnectedAccounts'));
const LinkOAuthCallback = lazy(() => import('./pages/LinkOAuthCallback'));
const LinkTelegramCallback = lazy(() => import('./pages/LinkTelegramCallback'));
const MergeAccounts = lazy(() => import('./pages/MergeAccounts'));
// Admin pages - lazy load (only for admins)
@@ -326,6 +327,16 @@ function App() {
</ProtectedRoute>
}
/>
<Route
path="/auth/link/telegram/callback"
element={
<ProtectedRoute>
<LazyPage>
<LinkTelegramCallback />
</LazyPage>
</ProtectedRoute>
}
/>
<Route
path="/contests"
element={

View File

@@ -233,6 +233,27 @@ export const authApi = {
return response.data;
},
// Link Telegram account (Mini App initData or Login Widget data)
linkTelegram: async (
data:
| { init_data: string }
| {
id: number;
first_name: string;
last_name?: string;
username?: string;
photo_url?: string;
auth_date: number;
hash: string;
},
): Promise<LinkCallbackResponse> => {
const response = await apiClient.post<LinkCallbackResponse>(
'/cabinet/auth/account/link/telegram',
data,
);
return response.data;
},
unlinkProvider: async (provider: string): Promise<{ success: boolean }> => {
const response = await apiClient.post<{ success: boolean }>(
`/cabinet/auth/account/unlink/${encodeURIComponent(provider)}`,

View File

@@ -3615,6 +3615,8 @@
"unlinkError": "Failed to disconnect account",
"goToAccounts": "Connected Accounts",
"linking": "Linking account...",
"linkTelegramWidget": "Sign in with Telegram to connect",
"linkingTelegram": "Connecting Telegram...",
"providers": {
"telegram": "Telegram",
"email": "Email",

View File

@@ -3051,6 +3051,8 @@
"unlinkError": "قطع اتصال ناموفق بود",
"goToAccounts": "حساب‌های متصل",
"linking": "در حال اتصال حساب...",
"linkTelegramWidget": "برای اتصال از طریق تلگرام وارد شوید",
"linkingTelegram": "در حال اتصال تلگرام...",
"providers": {
"telegram": "تلگرام",
"email": "ایمیل",

View File

@@ -4175,6 +4175,8 @@
"unlinkError": "Не удалось отвязать аккаунт",
"goToAccounts": "Привязанные аккаунты",
"linking": "Привязка аккаунта...",
"linkTelegramWidget": "Войдите через Telegram для привязки",
"linkingTelegram": "Привязка Telegram...",
"providers": {
"telegram": "Telegram",
"email": "Email",

View File

@@ -3050,6 +3050,8 @@
"unlinkError": "取消关联失败",
"goToAccounts": "关联账户",
"linking": "正在关联账户...",
"linkTelegramWidget": "通过 Telegram 登录以关联",
"linkingTelegram": "正在关联 Telegram...",
"providers": {
"telegram": "Telegram",
"email": "邮箱",

View File

@@ -1,5 +1,6 @@
import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { motion } from 'framer-motion';
import { authApi } from '../api/auth';
@@ -9,12 +10,63 @@ import { Button } from '@/components/primitives/Button';
import { staggerContainer, staggerItem } from '@/components/motion/transitions';
import ProviderIcon from '../components/ProviderIcon';
import { LINK_OAUTH_STATE_KEY, LINK_OAUTH_PROVIDER_KEY } from './LinkOAuthCallback';
import { isInTelegramWebApp, getTelegramInitData } from '../hooks/useTelegramSDK';
import type { LinkedProvider } from '../types';
const OAUTH_PROVIDERS = ['google', 'yandex', 'discord', 'vk'];
const isOAuthProvider = (provider: string): boolean => OAUTH_PROVIDERS.includes(provider);
const isLinkableProvider = (provider: string): boolean =>
isOAuthProvider(provider) || provider === 'telegram';
// SessionStorage key for Telegram link CSRF state
export const LINK_TELEGRAM_STATE_KEY = 'link_telegram_state';
/** Compact Telegram Login Widget for account linking (browser only). */
function TelegramLinkWidget() {
const containerRef = useRef<HTMLDivElement>(null);
const botUsername = import.meta.env.VITE_TELEGRAM_BOT_USERNAME || '';
useEffect(() => {
if (!containerRef.current || !botUsername) return;
const container = containerRef.current;
while (container.firstChild) {
container.removeChild(container.firstChild);
}
// Generate CSRF state token and store in sessionStorage
const csrfState = crypto.randomUUID();
sessionStorage.setItem(LINK_TELEGRAM_STATE_KEY, csrfState);
const redirectUrl = `${window.location.origin}/auth/link/telegram/callback?csrf_state=${encodeURIComponent(csrfState)}`;
const script = document.createElement('script');
script.src = 'https://telegram.org/js/telegram-widget.js?22';
script.setAttribute('data-telegram-login', botUsername);
script.setAttribute('data-size', 'small');
script.setAttribute('data-radius', '8');
script.setAttribute('data-auth-url', redirectUrl);
script.setAttribute('data-request-access', 'write');
script.async = true;
container.appendChild(script);
return () => {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
};
}, [botUsername]);
if (!botUsername) {
return null;
}
return <div ref={containerRef} className="flex items-center" />;
}
function LoadingSkeleton() {
return (
<div className="space-y-3">
@@ -40,11 +92,14 @@ export default function ConnectedAccounts() {
const { t } = useTranslation();
const { showToast } = useToast();
const queryClient = useQueryClient();
const navigate = useNavigate();
const [confirmingUnlink, setConfirmingUnlink] = useState<string | null>(null);
const [linkingProvider, setLinkingProvider] = useState<string | null>(null);
const blurTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
const inTelegram = isInTelegramWebApp();
useEffect(() => {
return () => {
if (blurTimeoutRef.current) clearTimeout(blurTimeoutRef.current);
@@ -83,7 +138,7 @@ export default function ConnectedAccounts() {
return linkedCount > 1;
};
const handleLink = async (provider: string) => {
const handleLinkOAuth = async (provider: string) => {
if (linkingProvider) return;
setLinkingProvider(provider);
try {
@@ -100,6 +155,35 @@ export default function ConnectedAccounts() {
}
};
const handleLinkTelegram = async () => {
if (linkingProvider) return;
const initData = getTelegramInitData();
if (!initData) return;
setLinkingProvider('telegram');
try {
const response = await authApi.linkTelegram({ init_data: initData });
if (response.merge_required && response.merge_token) {
navigate(`/merge/${response.merge_token}`, { replace: true });
} else {
queryClient.invalidateQueries({ queryKey: ['linked-providers'] });
showToast({ type: 'success', message: t('profile.accounts.linkSuccess') });
}
} catch {
showToast({ type: 'error', message: t('profile.accounts.linkError') });
} finally {
setLinkingProvider(null);
}
};
const handleLink = async (provider: string) => {
if (provider === 'telegram') {
await handleLinkTelegram();
} else {
await handleLinkOAuth(provider);
}
};
const handleUnlink = (provider: string) => {
if (confirmingUnlink === provider) {
setConfirmingUnlink(null);
@@ -109,6 +193,43 @@ export default function ConnectedAccounts() {
}
};
const renderLinkButton = (provider: LinkedProvider) => {
if (provider.provider === 'telegram') {
if (inTelegram && getTelegramInitData()) {
// Mini App: one-click button
return (
<Button
variant="primary"
size="sm"
disabled={linkingProvider !== null}
loading={linkingProvider === 'telegram'}
onClick={() => handleLink('telegram')}
>
{t('profile.accounts.link')}
</Button>
);
}
// Browser: Telegram Login Widget
return <TelegramLinkWidget />;
}
if (isOAuthProvider(provider.provider)) {
return (
<Button
variant="primary"
size="sm"
disabled={linkingProvider !== null}
loading={linkingProvider === provider.provider}
onClick={() => handleLink(provider.provider)}
>
{t('profile.accounts.link')}
</Button>
);
}
return null;
};
return (
<motion.div
className="space-y-6"
@@ -170,7 +291,6 @@ export default function ConnectedAccounts() {
}
onClick={() => handleUnlink(provider.provider)}
onBlur={() => {
// Delay so click on the same button fires before blur resets state
blurTimeoutRef.current = setTimeout(() => {
setConfirmingUnlink((cur) => (cur === provider.provider ? null : cur));
}, 150);
@@ -183,17 +303,7 @@ export default function ConnectedAccounts() {
)}
</>
) : (
isOAuthProvider(provider.provider) && (
<Button
variant="primary"
size="sm"
disabled={linkingProvider !== null}
loading={linkingProvider === provider.provider}
onClick={() => handleLink(provider.provider)}
>
{t('profile.accounts.link')}
</Button>
)
isLinkableProvider(provider.provider) && renderLinkButton(provider)
)}
</div>
</div>

View File

@@ -0,0 +1,93 @@
import { useEffect, useRef } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import { useTranslation } from 'react-i18next';
import { authApi } from '../api/auth';
import { useToast } from '../components/Toast';
import { LINK_TELEGRAM_STATE_KEY } from './ConnectedAccounts';
export default function LinkTelegramCallback() {
const { t } = useTranslation();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { showToast } = useToast();
const hasRun = useRef(false);
useEffect(() => {
if (hasRun.current) return;
hasRun.current = true;
// Clear sensitive data from URL immediately
window.history.replaceState({}, '', '/auth/link/telegram/callback');
const linkAccount = async () => {
// 1. Validate CSRF state
const csrfState = searchParams.get('csrf_state');
const savedState = sessionStorage.getItem(LINK_TELEGRAM_STATE_KEY);
sessionStorage.removeItem(LINK_TELEGRAM_STATE_KEY);
if (!csrfState || !savedState || csrfState !== savedState) {
showToast({ type: 'error', message: t('profile.accounts.linkError') });
navigate('/profile/accounts', { replace: true });
return;
}
// 2. Validate required Telegram fields
const id = searchParams.get('id');
const firstName = searchParams.get('first_name');
const authDate = searchParams.get('auth_date');
const hash = searchParams.get('hash');
if (!id || !firstName || !authDate || !hash) {
showToast({ type: 'error', message: t('profile.accounts.linkError') });
navigate('/profile/accounts', { replace: true });
return;
}
const parsedId = parseInt(id, 10);
const parsedAuthDate = parseInt(authDate, 10);
if (Number.isNaN(parsedId) || Number.isNaN(parsedAuthDate)) {
showToast({ type: 'error', message: t('profile.accounts.linkError') });
navigate('/profile/accounts', { replace: true });
return;
}
try {
const response = await authApi.linkTelegram({
id: parsedId,
first_name: firstName,
last_name: searchParams.get('last_name') || undefined,
username: searchParams.get('username') || undefined,
photo_url: searchParams.get('photo_url') || undefined,
auth_date: parsedAuthDate,
hash,
});
if (response.merge_required && response.merge_token) {
navigate(`/merge/${response.merge_token}`, { replace: true });
} else {
showToast({ type: 'success', message: t('profile.accounts.linkSuccess') });
navigate('/profile/accounts', { replace: true });
}
} catch {
showToast({ type: 'error', message: t('profile.accounts.linkError') });
navigate('/profile/accounts', { replace: true });
}
};
linkAccount();
}, [searchParams, navigate, showToast, t]);
return (
<div className="flex min-h-screen items-center justify-center">
<div className="fixed inset-0 bg-gradient-to-br from-dark-950 via-dark-900 to-dark-950" />
<div className="relative text-center">
<div className="mx-auto mb-4 h-10 w-10 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
<h2 className="text-lg font-semibold text-dark-50">
{t('profile.accounts.linkingTelegram')}
</h2>
<p className="mt-2 text-sm text-dark-400">{t('common.loading')}</p>
</div>
</div>
);
}