fix: stabilize mini app login and safe area
This commit is contained in:
@@ -24,6 +24,22 @@
|
||||
<ReconnectModal />
|
||||
<script src="@Assets["_framework/blazor.web.js"]"></script>
|
||||
<script>
|
||||
window.waitForTelegramMiniApp = async function (timeoutMs) {
|
||||
var deadline = Date.now() + (timeoutMs || 3000);
|
||||
|
||||
while (Date.now() <= deadline) {
|
||||
if (window.Telegram && window.Telegram.WebApp) {
|
||||
return window.Telegram.WebApp;
|
||||
}
|
||||
|
||||
await new Promise(function (resolve) {
|
||||
setTimeout(resolve, 100);
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
window.waitForTelegramMiniAppInitData = async function (timeoutMs) {
|
||||
var deadline = Date.now() + (timeoutMs || 3000);
|
||||
|
||||
@@ -40,30 +56,111 @@
|
||||
return null;
|
||||
};
|
||||
|
||||
(async function () {
|
||||
var webApp = await window.waitForTelegramMiniAppInitData(1000);
|
||||
window.syncTelegramMiniAppViewport = function (webApp) {
|
||||
if (!webApp) {
|
||||
return;
|
||||
}
|
||||
|
||||
var root = document.documentElement;
|
||||
var safeArea = webApp.safeAreaInset || {};
|
||||
var contentSafeArea = webApp.contentSafeAreaInset || {};
|
||||
var setPx = function (name, value) {
|
||||
root.style.setProperty(name, Math.max(0, Number(value) || 0) + 'px');
|
||||
};
|
||||
|
||||
setPx('--gm-tg-safe-top', safeArea.top);
|
||||
setPx('--gm-tg-safe-right', safeArea.right);
|
||||
setPx('--gm-tg-safe-bottom', safeArea.bottom);
|
||||
setPx('--gm-tg-safe-left', safeArea.left);
|
||||
setPx('--gm-tg-content-safe-top', contentSafeArea.top);
|
||||
setPx('--gm-tg-content-safe-right', contentSafeArea.right);
|
||||
setPx('--gm-tg-content-safe-bottom', contentSafeArea.bottom);
|
||||
setPx('--gm-tg-content-safe-left', contentSafeArea.left);
|
||||
|
||||
if (webApp.viewportHeight) {
|
||||
root.style.setProperty('--gm-tg-viewport-height', webApp.viewportHeight + 'px');
|
||||
}
|
||||
};
|
||||
|
||||
window.prepareTelegramMiniApp = function (webApp) {
|
||||
if (!webApp) {
|
||||
return;
|
||||
}
|
||||
|
||||
document.body.classList.add('telegram-mini-app');
|
||||
webApp.ready();
|
||||
window.syncTelegramMiniAppViewport(webApp);
|
||||
|
||||
try {
|
||||
webApp.ready();
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
try {
|
||||
webApp.expand();
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
if (webApp.onEvent && !window.gmRelayTelegramMiniAppViewportEventsRegistered) {
|
||||
window.gmRelayTelegramMiniAppViewportEventsRegistered = true;
|
||||
webApp.onEvent('safeAreaChanged', function () {
|
||||
window.syncTelegramMiniAppViewport(webApp);
|
||||
});
|
||||
webApp.onEvent('contentSafeAreaChanged', function () {
|
||||
window.syncTelegramMiniAppViewport(webApp);
|
||||
});
|
||||
webApp.onEvent('viewportChanged', function () {
|
||||
window.syncTelegramMiniAppViewport(webApp);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
(async function () {
|
||||
var webApp = await window.waitForTelegramMiniApp(1000);
|
||||
window.prepareTelegramMiniApp(webApp);
|
||||
})();
|
||||
|
||||
window.loadTelegramWidget = function (botUsername, authUrl) {
|
||||
var container = document.getElementById('telegram-login-container');
|
||||
if (!container) return;
|
||||
container.innerHTML = '';
|
||||
window.gmRelayTelegramLoginAuthUrl = authUrl || '/auth/telegram-login';
|
||||
var script = document.createElement('script');
|
||||
script.async = true;
|
||||
script.src = 'https://telegram.org/js/telegram-widget.js?22';
|
||||
script.setAttribute('data-telegram-login', botUsername);
|
||||
script.setAttribute('data-size', 'large');
|
||||
script.setAttribute('data-auth-url', authUrl);
|
||||
script.setAttribute('data-onauth', 'window.handleTelegramLogin(user)');
|
||||
script.setAttribute('data-request-access', 'write');
|
||||
container.appendChild(script);
|
||||
};
|
||||
|
||||
window.handleTelegramLogin = async function (user) {
|
||||
if (!user) {
|
||||
window.location.href = '/login?error=auth_failed';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
var response = await fetch(window.gmRelayTelegramLoginAuthUrl || '/auth/telegram-login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
body: JSON.stringify(user)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
window.location.href = '/login?error=auth_failed';
|
||||
return;
|
||||
}
|
||||
|
||||
var payload = await response.json();
|
||||
window.location.href = payload.redirectUrl || '/';
|
||||
} catch (error) {
|
||||
window.location.href = '/login?error=auth_failed';
|
||||
}
|
||||
};
|
||||
|
||||
window.watchTelegramMiniAppLogin = function (statusUrl, redirectUrl, reloadOnReturn) {
|
||||
window.gmRelayMiniAppLoginReloadOnReturn =
|
||||
window.gmRelayMiniAppLoginReloadOnReturn || reloadOnReturn === true;
|
||||
@@ -161,29 +258,40 @@
|
||||
};
|
||||
|
||||
window.authenticateTelegramMiniApp = async function (authUrl, redirectUrl) {
|
||||
var webApp = await window.waitForTelegramMiniAppInitData(3000);
|
||||
var webApp = await window.waitForTelegramMiniApp(3000);
|
||||
if (!webApp) {
|
||||
return false;
|
||||
return { authenticated: false, reason: 'telegram-webapp-missing' };
|
||||
}
|
||||
|
||||
document.body.classList.add('telegram-mini-app');
|
||||
webApp.ready();
|
||||
webApp.expand();
|
||||
window.prepareTelegramMiniApp(webApp);
|
||||
|
||||
var response = await fetch(authUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ initData: webApp.initData })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return false;
|
||||
if (!webApp.initData) {
|
||||
return { authenticated: false, reason: 'telegram-init-data-empty' };
|
||||
}
|
||||
|
||||
var payload = await response.json();
|
||||
window.location.href = payload.redirectUrl || redirectUrl || '/';
|
||||
return true;
|
||||
try {
|
||||
var response = await fetch(authUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
body: JSON.stringify({ initData: webApp.initData })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
authenticated: false,
|
||||
reason: 'telegram-auth-failed',
|
||||
status: response.status
|
||||
};
|
||||
}
|
||||
|
||||
var payload = await response.json();
|
||||
window.location.href = payload.redirectUrl || redirectUrl || '/';
|
||||
return { authenticated: true, redirectUrl: payload.redirectUrl || redirectUrl || '/' };
|
||||
} catch (error) {
|
||||
return { authenticated: false, reason: 'telegram-auth-failed' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="nav-version">v1.9.2</div>
|
||||
<div class="nav-version">v1.9.3</div>
|
||||
</div>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
|
||||
@code {
|
||||
private string BotUsername => Configuration["Telegram:BotUsername"] ?? "GmRelayBot";
|
||||
private string AuthUrl => Navigation.ToAbsoluteUri("/auth/telegram").ToString();
|
||||
|
||||
[CascadingParameter]
|
||||
private Task<AuthenticationState>? AuthStateTask { get; set; }
|
||||
@@ -46,8 +45,8 @@
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
await JS.InvokeVoidAsync("loadTelegramWidget", BotUsername, AuthUrl);
|
||||
await JS.InvokeVoidAsync("watchTelegramMiniAppLogin", "/auth/status", "/", true);
|
||||
await JS.InvokeVoidAsync("loadTelegramWidget", BotUsername, "/auth/telegram-login");
|
||||
await JS.InvokeVoidAsync("watchTelegramMiniAppLogin", "/auth/status", "/", false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
@page "/miniapp"
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using System.Text.Json.Serialization
|
||||
@inject IJSRuntime JS
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Mini App Dashboard — GM-Relay</PageTitle>
|
||||
|
||||
<div class="mini-app-page">
|
||||
<div class="mini-app-auth-card">
|
||||
<div class="mini-app-auth-card" data-auth-status="@miniAppAuthStatus">
|
||||
<div class="mini-app-logo">🎲</div>
|
||||
<h1>GM-Relay</h1>
|
||||
<p>@statusMessage</p>
|
||||
@@ -20,6 +21,7 @@
|
||||
|
||||
@code {
|
||||
private string statusMessage = "Открываем dashboard внутри Telegram...";
|
||||
private string miniAppAuthStatus = "starting";
|
||||
private bool showFallback;
|
||||
|
||||
[CascadingParameter]
|
||||
@@ -48,14 +50,17 @@
|
||||
|
||||
try
|
||||
{
|
||||
var authenticated = await JS.InvokeAsync<bool>(
|
||||
var result = await JS.InvokeAsync<MiniAppAuthResult>(
|
||||
"authenticateTelegramMiniApp",
|
||||
"/auth/telegram-webapp",
|
||||
"/");
|
||||
|
||||
if (!authenticated)
|
||||
if (!result.Authenticated)
|
||||
{
|
||||
statusMessage = "Mini App доступен из Telegram. Для браузера используйте обычный вход.";
|
||||
miniAppAuthStatus = string.IsNullOrWhiteSpace(result.Reason)
|
||||
? "telegram-auth-failed"
|
||||
: result.Reason;
|
||||
statusMessage = GetStatusMessage(miniAppAuthStatus);
|
||||
showFallback = true;
|
||||
StateHasChanged();
|
||||
await TryWatchLoginAsync();
|
||||
@@ -63,6 +68,7 @@
|
||||
}
|
||||
catch (JSException)
|
||||
{
|
||||
miniAppAuthStatus = "telegram-auth-failed";
|
||||
statusMessage = "Не удалось получить данные Telegram Mini App. Попробуйте открыть dashboard из бота.";
|
||||
showFallback = true;
|
||||
StateHasChanged();
|
||||
@@ -80,4 +86,18 @@
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetStatusMessage(string reason) => reason switch
|
||||
{
|
||||
"telegram-webapp-missing" => "Mini App API не найден. Если страница открыта в браузере, войдите через Telegram.",
|
||||
"telegram-init-data-empty" => "Telegram открыл страницу без Mini App initData. Попробуйте войти через Telegram на этом экране.",
|
||||
"telegram-auth-failed" => "Не удалось проверить Telegram Mini App. Попробуйте войти через Telegram.",
|
||||
_ => "Mini App доступен из Telegram. Для браузера используйте обычный вход."
|
||||
};
|
||||
|
||||
private sealed record MiniAppAuthResult(
|
||||
[property: JsonPropertyName("authenticated")] bool Authenticated,
|
||||
[property: JsonPropertyName("reason")] string? Reason,
|
||||
[property: JsonPropertyName("status")] int? Status,
|
||||
[property: JsonPropertyName("redirectUrl")] string? RedirectUrl);
|
||||
}
|
||||
|
||||
@@ -117,6 +117,25 @@ app.MapPost("/auth/telegram-webapp", async (
|
||||
return Results.Ok(new { redirectUrl = "/" });
|
||||
}).DisableAntiforgery();
|
||||
|
||||
app.MapPost("/auth/telegram-login", async (
|
||||
HttpContext context,
|
||||
TelegramAuthService authService,
|
||||
TelegramLoginPayload request) =>
|
||||
{
|
||||
if (!authService.VerifyLoginPayload(request, out var telegramId, out var name))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var authProperties = new AuthenticationProperties { IsPersistent = true };
|
||||
await context.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
CreateTelegramPrincipal(telegramId, name),
|
||||
authProperties);
|
||||
|
||||
return Results.Ok(new { redirectUrl = "/" });
|
||||
}).DisableAntiforgery();
|
||||
|
||||
app.MapGet("/auth/status", (HttpContext context) =>
|
||||
Results.Ok(new { authenticated = context.User.Identity?.IsAuthenticated == true }));
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
|
||||
namespace GmRelay.Web.Services;
|
||||
@@ -113,6 +114,69 @@ public sealed class TelegramAuthService(IConfiguration configuration)
|
||||
return TryReadWebAppUser(userJson.ToString(), out telegramId, out name);
|
||||
}
|
||||
|
||||
public bool VerifyLoginPayload(TelegramLoginPayload payload, out long telegramId, out string name)
|
||||
{
|
||||
telegramId = 0;
|
||||
name = string.Empty;
|
||||
|
||||
if (payload.Id <= 0 ||
|
||||
string.IsNullOrWhiteSpace(payload.FirstName) ||
|
||||
payload.AuthDate <= 0 ||
|
||||
string.IsNullOrWhiteSpace(payload.Hash))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var token = configuration["Telegram__BotToken"] ?? configuration["Telegram:BotToken"];
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return false;
|
||||
|
||||
var values = new SortedDictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["auth_date"] = payload.AuthDate.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
["first_name"] = payload.FirstName,
|
||||
["id"] = payload.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(payload.LastName))
|
||||
values["last_name"] = payload.LastName;
|
||||
if (!string.IsNullOrWhiteSpace(payload.PhotoUrl))
|
||||
values["photo_url"] = payload.PhotoUrl;
|
||||
if (!string.IsNullOrWhiteSpace(payload.Username))
|
||||
values["username"] = payload.Username;
|
||||
|
||||
var dataCheckString = string.Join("\n", values.Select(pair => $"{pair.Key}={pair.Value}"));
|
||||
var secretKey = SHA256.HashData(Encoding.UTF8.GetBytes(token));
|
||||
var computedHashBytes = HMACSHA256.HashData(secretKey, Encoding.UTF8.GetBytes(dataCheckString));
|
||||
|
||||
byte[] hashBytes;
|
||||
try
|
||||
{
|
||||
hashBytes = Convert.FromHexString(payload.Hash);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!CryptographicOperations.FixedTimeEquals(computedHashBytes, hashBytes))
|
||||
return false;
|
||||
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
if (now - payload.AuthDate > 86400)
|
||||
return false;
|
||||
|
||||
telegramId = payload.Id;
|
||||
name = string.IsNullOrWhiteSpace(payload.LastName)
|
||||
? payload.FirstName
|
||||
: $"{payload.FirstName} {payload.LastName}";
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadWebAppUser(string userJson, out long telegramId, out string name)
|
||||
{
|
||||
telegramId = 0;
|
||||
@@ -152,3 +216,12 @@ public sealed class TelegramAuthService(IConfiguration configuration)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record TelegramLoginPayload(
|
||||
[property: JsonPropertyName("id")] long Id,
|
||||
[property: JsonPropertyName("first_name")] string FirstName,
|
||||
[property: JsonPropertyName("last_name")] string? LastName,
|
||||
[property: JsonPropertyName("username")] string? Username,
|
||||
[property: JsonPropertyName("photo_url")] string? PhotoUrl,
|
||||
[property: JsonPropertyName("auth_date")] long AuthDate,
|
||||
[property: JsonPropertyName("hash")] string Hash);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* ============================================
|
||||
GM-Relay Design System v1.9.2
|
||||
GM-Relay Design System v1.9.3
|
||||
Dark RPG Dashboard Theme
|
||||
============================================ */
|
||||
|
||||
@@ -69,6 +69,21 @@
|
||||
|
||||
/* Sidebar */
|
||||
--sidebar-width: 260px;
|
||||
|
||||
/* Telegram Mini App safe areas */
|
||||
--gm-tg-safe-top: var(--tg-safe-area-inset-top, env(safe-area-inset-top, 0px));
|
||||
--gm-tg-safe-right: var(--tg-safe-area-inset-right, env(safe-area-inset-right, 0px));
|
||||
--gm-tg-safe-bottom: var(--tg-safe-area-inset-bottom, env(safe-area-inset-bottom, 0px));
|
||||
--gm-tg-safe-left: var(--tg-safe-area-inset-left, env(safe-area-inset-left, 0px));
|
||||
--gm-tg-content-safe-top: var(--tg-content-safe-area-inset-top, 0px);
|
||||
--gm-tg-content-safe-right: var(--tg-content-safe-area-inset-right, 0px);
|
||||
--gm-tg-content-safe-bottom: var(--tg-content-safe-area-inset-bottom, 0px);
|
||||
--gm-tg-content-safe-left: var(--tg-content-safe-area-inset-left, 0px);
|
||||
--gm-mini-app-top-inset: calc(var(--gm-tg-safe-top, 0px) + var(--gm-tg-content-safe-top, 0px));
|
||||
--gm-mini-app-bottom-inset: calc(var(--gm-tg-safe-bottom, 0px) + var(--gm-tg-content-safe-bottom, 0px));
|
||||
--gm-mini-app-left-inset: calc(var(--gm-tg-safe-left, 0px) + var(--gm-tg-content-safe-left, 0px));
|
||||
--gm-mini-app-right-inset: calc(var(--gm-tg-safe-right, 0px) + var(--gm-tg-content-safe-right, 0px));
|
||||
--gm-tg-viewport-height: 100dvh;
|
||||
}
|
||||
|
||||
/* === Reset & Base === */
|
||||
@@ -845,6 +860,7 @@ select option {
|
||||
/* === Telegram Mini App entry === */
|
||||
.mini-app-page {
|
||||
min-height: 100vh;
|
||||
min-height: var(--gm-tg-viewport-height, 100dvh);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -882,6 +898,21 @@ select option {
|
||||
max-width: 720px;
|
||||
}
|
||||
|
||||
body.telegram-mini-app {
|
||||
min-height: var(--gm-tg-viewport-height, 100dvh);
|
||||
}
|
||||
|
||||
body.telegram-mini-app .mini-app-page {
|
||||
padding-top: calc(1rem + var(--gm-mini-app-top-inset, 0px));
|
||||
padding-right: calc(1rem + var(--gm-mini-app-right-inset, 0px));
|
||||
padding-bottom: calc(1rem + var(--gm-mini-app-bottom-inset, 0px));
|
||||
padding-left: calc(1rem + var(--gm-mini-app-left-inset, 0px));
|
||||
}
|
||||
|
||||
body.telegram-mini-app .content {
|
||||
padding-bottom: calc(1.5rem + var(--gm-mini-app-bottom-inset, 0px));
|
||||
}
|
||||
|
||||
/* === Mobile Sessions Cards (instead of table) === */
|
||||
.session-card-mobile {
|
||||
display: none;
|
||||
@@ -970,12 +1001,24 @@ select option {
|
||||
|
||||
.telegram-mini-app .content {
|
||||
padding: 0.75rem;
|
||||
padding-bottom: calc(0.75rem + var(--gm-mini-app-bottom-inset, 0px));
|
||||
}
|
||||
|
||||
.telegram-mini-app .page-container {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
body.telegram-mini-app .nav-header {
|
||||
padding-top: calc(1.25rem + var(--gm-mini-app-top-inset, 0px));
|
||||
padding-left: calc(1rem + var(--gm-mini-app-left-inset, 0px));
|
||||
padding-right: calc(0.75rem + var(--gm-mini-app-right-inset, 0px));
|
||||
}
|
||||
|
||||
body.telegram-mini-app .nav-toggle {
|
||||
top: calc(0.75rem + var(--gm-mini-app-top-inset, 0px));
|
||||
left: calc(0.75rem + var(--gm-mini-app-left-inset, 0px));
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user