Update files

This commit is contained in:
glpshchn 2025-11-11 02:22:34 +03:00
parent 08ab000290
commit a4bae70823
7 changed files with 69 additions and 85 deletions

View File

@ -103,18 +103,31 @@ function validateAndParseInitData(initDataRaw, botToken = null) {
userId: payload?.user?.id, userId: payload?.user?.id,
auth_date: payload?.auth_date, auth_date: payload?.auth_date,
authDate: payload?.authDate, authDate: payload?.authDate,
allKeys: Object.keys(payload) allKeys: Object.keys(payload),
fullPayload: JSON.stringify(payload, null, 2)
}); });
if (!payload || !payload.user) { if (!payload || !payload.user) {
throw new Error('Отсутствует пользователь в initData'); throw new Error('Отсутствует пользователь в initData');
} }
// Check for authDate (camelCase from library) or auth_date (snake_case) // Check if this is signature-based validation (Ed25519) or hash-based (HMAC-SHA256)
const hasSignature = 'signature' in payload;
const hasHash = 'hash' in payload;
console.log('[Telegram] Validation method:', {
hasSignature,
hasHash,
method: hasSignature ? 'Ed25519 (signature)' : 'HMAC-SHA256 (hash)'
});
// Only check auth_date for hash-based validation (old method)
// Signature-based validation (new method) doesn't include auth_date
if (hasHash && !hasSignature) {
const authDate = Number(payload.authDate || payload.auth_date); const authDate = Number(payload.authDate || payload.auth_date);
if (!authDate) { if (!authDate) {
console.error('[Telegram] Missing authDate in payload:', payload); console.error('[Telegram] Missing authDate in hash-based payload:', payload);
throw new Error('Отсутствует auth_date в initData'); throw new Error('Отсутствует auth_date в initData');
} }
@ -132,6 +145,9 @@ function validateAndParseInitData(initDataRaw, botToken = null) {
if (age > MAX_AUTH_AGE_SECONDS) { if (age > MAX_AUTH_AGE_SECONDS) {
throw new Error(`Данные авторизации устарели (возраст: ${age}с, макс: ${MAX_AUTH_AGE_SECONDS}с)`); throw new Error(`Данные авторизации устарели (возраст: ${age}с, макс: ${MAX_AUTH_AGE_SECONDS}с)`);
} }
} else if (hasSignature) {
console.log('[Telegram] Signature-based validation detected, skipping auth_date check');
}
console.log('[Telegram] initData validation complete'); console.log('[Telegram] initData validation complete');

View File

@ -6,21 +6,8 @@
<meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes">
<title>NakamaHost</title> <title>NakamaHost</title>
<script> <!-- Telegram Web App SDK - прямая загрузка -->
(function () { <script src="https://telegram.org/js/telegram-web-app.js"></script>
if (window.Telegram && window.Telegram.WebApp) {
return;
}
const script = document.createElement('script');
script.src = 'https://telegram.org/js/telegram-web-app.js';
script.onload = () => {
if (window.Telegram && window.Telegram.WebApp) {
window.Telegram.WebApp.ready?.();
}
};
document.head.appendChild(script);
})();
</script>
<style> <style>
/* Предотвращение resize при открытии клавиатуры */ /* Предотвращение resize при открытии клавиатуры */
html, body { html, body {

View File

@ -38,29 +38,21 @@ function AppContent() {
} }
}, []) }, [])
const waitForInitData = async () => {
const start = Date.now()
const timeout = 5000
while (Date.now() - start < timeout) {
const tg = window.Telegram?.WebApp
if (tg?.initData && tg.initData.length > 0) {
return tg
}
await new Promise(resolve => setTimeout(resolve, 100))
}
throw new Error('Telegram не передал initData. Откройте приложение в официальном клиенте.')
}
const initApp = async () => { const initApp = async () => {
try { try {
initTelegramApp() initTelegramApp()
const tg = await waitForInitData() const tg = window.Telegram?.WebApp
if (!tg) {
throw new Error('Откройте приложение из Telegram.')
}
if (!tg.initData) {
throw new Error('Telegram не передал initData. Откройте приложение из официального клиента.')
}
tg.disableVerticalSwipes?.() tg.disableVerticalSwipes?.()
tg.ready?.()
tg.expand?.() tg.expand?.()
const userData = await verifyAuth() const userData = await verifyAuth()

View File

@ -3,6 +3,14 @@ import ReactDOM from 'react-dom/client'
import App from './App.jsx' import App from './App.jsx'
import './styles/index.css' import './styles/index.css'
// Убедиться, что Telegram Web App инициализирован
if (window.Telegram?.WebApp) {
window.Telegram.WebApp.ready();
console.log('[Nakama] Telegram WebApp initialized');
} else {
console.error('[Nakama] Telegram WebApp not found!');
}
ReactDOM.createRoot(document.getElementById('root')).render( ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode> <React.StrictMode>
<App /> <App />

View File

@ -5,21 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="theme-color" content="#000000" /> <meta name="theme-color" content="#000000" />
<title>Nakama Moderation</title> <title>Nakama Moderation</title>
<script> <!-- Telegram Web App SDK - прямая загрузка -->
(function () { <script src="https://telegram.org/js/telegram-web-app.js"></script>
if (window.Telegram && window.Telegram.WebApp) {
return;
}
const script = document.createElement('script');
script.src = 'https://telegram.org/js/telegram-web-app.js';
script.onload = () => {
if (window.Telegram && window.Telegram.WebApp) {
window.Telegram.WebApp.ready?.();
}
};
document.head.appendChild(script);
})();
</script>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>

View File

@ -100,20 +100,6 @@ export default function App() {
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
const waitForInitData = async () => {
const start = Date.now();
const timeout = 5000;
while (Date.now() - start < timeout) {
const app = window.Telegram?.WebApp;
if (app?.initData && app.initData.length > 0) {
return app;
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error('Telegram initData не передан (timeout)');
};
const init = async () => { const init = async () => {
try { try {
const telegramApp = window.Telegram?.WebApp; const telegramApp = window.Telegram?.WebApp;
@ -122,12 +108,12 @@ export default function App() {
throw new Error('Откройте модераторский интерфейс из Telegram (бот @rbachbot).'); throw new Error('Откройте модераторский интерфейс из Telegram (бот @rbachbot).');
} }
telegramApp.disableVerticalSwipes?.(); if (!telegramApp.initData) {
telegramApp.ready?.(); throw new Error('Telegram не передал initData. Откройте приложение из официального клиента.');
telegramApp.expand?.(); }
const app = await waitForInitData(); telegramApp.disableVerticalSwipes?.();
if (cancelled) return; telegramApp.expand?.();
const userData = await verifyAuth(); const userData = await verifyAuth();
if (cancelled) return; if (cancelled) return;

View File

@ -3,6 +3,14 @@ import ReactDOM from 'react-dom/client';
import App from './App'; import App from './App';
import './styles.css'; import './styles.css';
// Убедиться, что Telegram Web App инициализирован
if (window.Telegram?.WebApp) {
window.Telegram.WebApp.ready();
console.log('[Moderation] Telegram WebApp initialized');
} else {
console.error('[Moderation] Telegram WebApp not found!');
}
ReactDOM.createRoot(document.getElementById('root')).render( ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode> <React.StrictMode>
<App /> <App />