Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8169b6474a | ||
|
|
693840d662 | ||
|
|
309e3416d6 | ||
|
|
e6a440e3f3 |
@@ -25,6 +25,9 @@ jobs:
|
||||
echo "${{ secrets.KUBE_CONFIG }}" > ~/.kube/config
|
||||
chmod 600 ~/.kube/config
|
||||
|
||||
- name: Install Helm
|
||||
uses: azure/setup-helm@v4
|
||||
|
||||
- name: Log in to Helm registry
|
||||
run: |
|
||||
helm registry login ${{ env.REGISTRY }} \
|
||||
|
||||
@@ -34,5 +34,12 @@ spec:
|
||||
- name: Bot__MiniAppUrl
|
||||
value: {{ .Values.telegram.miniAppUrl }}
|
||||
{{- end }}
|
||||
- name: Jwt__SecretKey
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.secretName }}
|
||||
key: jwt-secret-key
|
||||
- name: Jwt__ExpiryHours
|
||||
value: {{ .Values.jwt.expiryHours | quote }}
|
||||
resources:
|
||||
{{- toYaml .Values.bot.resources | nindent 12 }}
|
||||
|
||||
@@ -25,7 +25,7 @@ spec:
|
||||
{{- if .Values.ingress.tls.certResolver }}
|
||||
# ACME-резолвер (Let's Encrypt и т.п.) — Traefik сам получает сертификат.
|
||||
certResolver: {{ .Values.ingress.tls.certResolver }}
|
||||
{{- else if .Values.ingress.tls.store }}
|
||||
{{- else if .Values.ingress.tls.store.name }}
|
||||
# TLSStore из произвольного неймспейса (требует allowCrossNamespace=true).
|
||||
store:
|
||||
name: {{ .Values.ingress.tls.store.name }}
|
||||
|
||||
+32
-1
@@ -14,6 +14,22 @@
|
||||
let authError = null
|
||||
let authing = true
|
||||
|
||||
/**
|
||||
* Возвращает параметры inline-авторизации из query-строки URL,
|
||||
* если они были переданы ботом (?user_id=...&signed_at=...&sign=...).
|
||||
*/
|
||||
function inlineParams() {
|
||||
const p = new URLSearchParams(window.location.search)
|
||||
const userId = p.get('user_id')
|
||||
const signedAt = p.get('signed_at')
|
||||
const sign = p.get('sign')
|
||||
return (userId && signedAt && sign) ? { userId, signedAt, sign } : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Dev-режим: #token=<jwt> в хэш-фрагменте для тестирования без Telegram.
|
||||
* Хэш не отправляется на сервер, поэтому безопасен для локальной отладки.
|
||||
*/
|
||||
function devTokenFromHash() {
|
||||
if (!import.meta.env.DEV) return null
|
||||
const params = new URLSearchParams(window.location.hash.slice(1))
|
||||
@@ -23,7 +39,7 @@
|
||||
onMount(async () => {
|
||||
applyTheme()
|
||||
|
||||
// Dev-режим: #token=<jwt> в URL — пропускаем обмен initData
|
||||
// Dev-режим: #token=<jwt>
|
||||
const devToken = devTokenFromHash()
|
||||
if (devToken) {
|
||||
jwt.set(devToken)
|
||||
@@ -31,6 +47,21 @@
|
||||
return
|
||||
}
|
||||
|
||||
// Inline-режим: бот передал подпись в query-строке
|
||||
const inline = inlineParams()
|
||||
if (inline) {
|
||||
try {
|
||||
const { token } = await api.authInline(inline.userId, inline.signedAt, inline.sign)
|
||||
jwt.set(token)
|
||||
} catch (e) {
|
||||
authError = e.message
|
||||
} finally {
|
||||
authing = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Обычный WebApp: авторизация через initData (Telegram заполняет её)
|
||||
try {
|
||||
const { token } = await api.auth(initData)
|
||||
jwt.set(token)
|
||||
|
||||
@@ -33,7 +33,8 @@ async function request(method, path, body) {
|
||||
|
||||
export const api = {
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
||||
auth: (initData) => request('POST', '/auth/telegram', { initData }),
|
||||
auth: (initData) => request('POST', '/auth/telegram', { initData }),
|
||||
authInline: (userId, signedAt, sign) => request('POST', '/auth/inline', { userId: Number(userId), signedAt: Number(signedAt), sign }),
|
||||
|
||||
// ── Me ────────────────────────────────────────────────────────────────────
|
||||
// GET /api/me → { telegramId, username, firstName, inboxCollectionId }
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using MemeVault.Api.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MemeVault.Api.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Проверяет подпись, которую бот вкладывает в URL Mini App при inline-режиме.
|
||||
/// Telegram не предоставляет initData через InlineQueryResultsButton,
|
||||
/// поэтому используем собственную схему:
|
||||
/// sign = HMAC-SHA256(jwt_secret_key, "{userId}:{signedAt}")
|
||||
/// Окно свежести — 60 секунд (то же, что у TelegramInitDataValidator).
|
||||
/// </summary>
|
||||
public sealed class InlineAuthValidator(IOptions<JwtOptions> options)
|
||||
{
|
||||
private static readonly TimeSpan MaxAge = TimeSpan.FromSeconds(60);
|
||||
|
||||
public bool TryValidate(long userId, long signedAt, string sign)
|
||||
{
|
||||
// Проверка свежести
|
||||
var authDate = DateTimeOffset.FromUnixTimeSeconds(signedAt);
|
||||
if (DateTimeOffset.UtcNow - authDate > MaxAge)
|
||||
return false;
|
||||
|
||||
// Ожидаемая подпись
|
||||
var data = $"{userId}:{signedAt}";
|
||||
var key = Encoding.UTF8.GetBytes(options.Value.SecretKey);
|
||||
var expectedHash = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(data));
|
||||
var expectedHex = Convert.ToHexString(expectedHash).ToLowerInvariant();
|
||||
|
||||
// Constant-time сравнение
|
||||
return CryptographicOperations.FixedTimeEquals(
|
||||
Encoding.UTF8.GetBytes(expectedHex),
|
||||
Encoding.UTF8.GetBytes(sign.ToLowerInvariant()));
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,10 @@ namespace MemeVault.Api.Controllers;
|
||||
[Route("api/[controller]")]
|
||||
public sealed class AuthController(
|
||||
TelegramInitDataValidator validator,
|
||||
InlineAuthValidator inlineValidator,
|
||||
JwtTokenService jwt) : ControllerBase
|
||||
{
|
||||
/// <summary>Стандартная авторизация через Telegram initData (обычный WebApp).</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("telegram")]
|
||||
public IActionResult Telegram([FromBody] TelegramAuthRequest request)
|
||||
@@ -20,6 +22,23 @@ public sealed class AuthController(
|
||||
var token = jwt.IssueToken(userId, username);
|
||||
return Ok(new { token });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Авторизация через HMAC-подпись от бота — для inline-режима,
|
||||
/// где Telegram не передаёт initData.
|
||||
/// </summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("inline")]
|
||||
public IActionResult Inline([FromBody] InlineAuthRequest request)
|
||||
{
|
||||
if (!inlineValidator.TryValidate(request.UserId, request.SignedAt, request.Sign))
|
||||
return Unauthorized();
|
||||
|
||||
// username в этом режиме неизвестен — будет обновлён при следующем сообщении боту
|
||||
var token = jwt.IssueToken(request.UserId, username: null);
|
||||
return Ok(new { token });
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record TelegramAuthRequest(string InitData);
|
||||
public sealed record InlineAuthRequest(long UserId, long SignedAt, string Sign);
|
||||
|
||||
@@ -27,6 +27,7 @@ builder.Services.Configure<JwtOptions>(
|
||||
builder.Configuration.GetSection(JwtOptions.Section));
|
||||
|
||||
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
||||
builder.Services.AddSingleton<InlineAuthValidator>();
|
||||
builder.Services.AddSingleton<JwtTokenService>();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<CurrentUser>();
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using MemeVault.Bot.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MemeVault.Bot.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Генерирует параметры авторизации для передачи в URL Mini App в inline-режиме.
|
||||
/// Telegram не предоставляет initData при открытии через InlineQueryResultsButton,
|
||||
/// поэтому бот самостоятельно подписывает userId + timestamp секретным ключом.
|
||||
///
|
||||
/// Схема: sign = HMAC-SHA256(jwt_secret_key, "{userId}:{signedAt}")
|
||||
/// </summary>
|
||||
public sealed class BotInlineSigner(IOptions<JwtOptions> options)
|
||||
{
|
||||
public (long UserId, long SignedAt, string Sign) CreateParams(long telegramUserId)
|
||||
{
|
||||
var signedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
var data = $"{telegramUserId}:{signedAt}";
|
||||
var key = Encoding.UTF8.GetBytes(options.Value.SecretKey);
|
||||
var hash = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(data));
|
||||
var sign = Convert.ToHexString(hash).ToLowerInvariant();
|
||||
return (telegramUserId, signedAt, sign);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace MemeVault.Bot.Options;
|
||||
|
||||
public sealed class JwtOptions
|
||||
{
|
||||
public const string Section = "Jwt";
|
||||
|
||||
public string SecretKey { get; set; } = string.Empty;
|
||||
public string Issuer { get; set; } = "memevault-api";
|
||||
public string Audience { get; set; } = "memevault-miniapp";
|
||||
public int ExpiryHours { get; set; } = 24;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using MemeVault.Bot.Auth;
|
||||
using MemeVault.Bot.Telemetry;
|
||||
using Prometheus;
|
||||
using MemeVault.Bot.Options;
|
||||
@@ -22,7 +23,8 @@ builder.Services.AddInfrastructure(builder.Configuration);
|
||||
builder.Services.AddSingleton<BotMetrics>();
|
||||
|
||||
builder.Services.Configure<BotOptions>(builder.Configuration.GetSection(BotOptions.Section));
|
||||
|
||||
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection(JwtOptions.Section));
|
||||
builder.Services.AddSingleton<BotInlineSigner>();
|
||||
|
||||
builder.Services.AddScoped<MessageHandler>();
|
||||
builder.Services.AddScoped<InlineQueryHandler>();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Queries.GetMediaItem;
|
||||
using MemeVault.Application.Queries.SearchMedia;
|
||||
using MemeVault.Bot.Auth;
|
||||
using MemeVault.Bot.Options;
|
||||
using MemeVault.Domain.Enums;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -17,20 +18,33 @@ namespace MemeVault.Bot.Telegram.InlineMode;
|
||||
/// </summary>
|
||||
public sealed class InlineQueryHandler
|
||||
{
|
||||
// cacheTime для результатов поиска (секунды).
|
||||
// Если кэш инлайна мешает тестированию — уменьшить или поставить 0.
|
||||
private const int SearchCacheTime = 10;
|
||||
|
||||
// cacheTime для точечной отправки — всегда 0, результат персональный.
|
||||
private const int SendCacheTime = 0;
|
||||
|
||||
private readonly IMediator _mediator;
|
||||
private readonly ITelegramBotClient _bot;
|
||||
private readonly BotOptions _options;
|
||||
private readonly BotInlineSigner _signer;
|
||||
|
||||
public InlineQueryHandler(IMediator mediator, ITelegramBotClient bot, IOptions<BotOptions> options)
|
||||
public InlineQueryHandler(
|
||||
IMediator mediator,
|
||||
ITelegramBotClient bot,
|
||||
IOptions<BotOptions> options,
|
||||
BotInlineSigner signer)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_bot = bot;
|
||||
_options = options.Value;
|
||||
_signer = signer;
|
||||
}
|
||||
|
||||
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
||||
{
|
||||
var userId = inlineQuery.From.Id;
|
||||
var userId = inlineQuery.From.Id;
|
||||
var rawQuery = inlineQuery.Query ?? string.Empty;
|
||||
|
||||
// Режим точечной отправки: Mini App выбрала конкретный элемент
|
||||
@@ -58,7 +72,7 @@ public sealed class InlineQueryHandler
|
||||
await _bot.AnswerInlineQuery(
|
||||
queryId,
|
||||
answers.OfType<InlineQueryResult>(),
|
||||
cacheTime: 0,
|
||||
cacheTime: SendCacheTime,
|
||||
isPersonal: true,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
@@ -75,24 +89,36 @@ public sealed class InlineQueryHandler
|
||||
.OfType<InlineQueryResult>()
|
||||
.ToArray();
|
||||
|
||||
// Кнопка над результатами — открывает Mini App в inline-режиме
|
||||
// Кнопка над результатами — открывает Mini App в inline-режиме.
|
||||
// Telegram не предоставляет initData в этом режиме, поэтому бот подписывает
|
||||
// userId + timestamp и передаёт в query-строке для обмена на JWT.
|
||||
InlineQueryResultsButton? button = string.IsNullOrEmpty(_options.MiniAppUrl)
|
||||
? null
|
||||
: new InlineQueryResultsButton
|
||||
{
|
||||
Text = "Открыть MemeVault",
|
||||
WebApp = new WebAppInfo { Url = _options.MiniAppUrl + "?mode=inline" }
|
||||
};
|
||||
: BuildButton(userId);
|
||||
|
||||
await _bot.AnswerInlineQuery(
|
||||
queryId,
|
||||
answers,
|
||||
button: button,
|
||||
cacheTime: 10,
|
||||
button: button,
|
||||
cacheTime: SearchCacheTime,
|
||||
isPersonal: true,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
// ── Кнопка Mini App ──────────────────────────────────────────────────────
|
||||
|
||||
private InlineQueryResultsButton BuildButton(long userId)
|
||||
{
|
||||
var (uid, ts, sign) = _signer.CreateParams(userId);
|
||||
var url = $"{_options.MiniAppUrl}?mode=inline&user_id={uid}&signed_at={ts}&sign={sign}";
|
||||
|
||||
return new InlineQueryResultsButton
|
||||
{
|
||||
Text = "Открыть MemeVault",
|
||||
WebApp = new WebAppInfo { Url = url },
|
||||
};
|
||||
}
|
||||
|
||||
// ── Конвертер ────────────────────────────────────────────────────────────
|
||||
|
||||
private static InlineQueryResult? ToInlineResult(MediaItemDto item)
|
||||
@@ -107,8 +133,8 @@ public sealed class InlineQueryHandler
|
||||
{
|
||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Title = item.InlineTitle,
|
||||
Caption = item.Caption,
|
||||
Title = item.InlineTitle,
|
||||
Description = item.InlineDescription ?? tagsLine,
|
||||
},
|
||||
|
||||
@@ -117,7 +143,7 @@ public sealed class InlineQueryHandler
|
||||
item.FileId!,
|
||||
title: item.InlineTitle ?? item.Caption ?? "Video")
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Caption = item.Caption,
|
||||
Description = item.InlineDescription ?? tagsLine,
|
||||
},
|
||||
|
||||
@@ -126,7 +152,7 @@ public sealed class InlineQueryHandler
|
||||
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Title = item.InlineTitle,
|
||||
Title = item.InlineTitle,
|
||||
},
|
||||
|
||||
MediaType.Text => new InlineQueryResultArticle(
|
||||
|
||||
Reference in New Issue
Block a user