Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8169b6474a | ||
|
|
693840d662 | ||
|
|
309e3416d6 | ||
|
|
e6a440e3f3 |
@@ -25,6 +25,9 @@ jobs:
|
|||||||
echo "${{ secrets.KUBE_CONFIG }}" > ~/.kube/config
|
echo "${{ secrets.KUBE_CONFIG }}" > ~/.kube/config
|
||||||
chmod 600 ~/.kube/config
|
chmod 600 ~/.kube/config
|
||||||
|
|
||||||
|
- name: Install Helm
|
||||||
|
uses: azure/setup-helm@v4
|
||||||
|
|
||||||
- name: Log in to Helm registry
|
- name: Log in to Helm registry
|
||||||
run: |
|
run: |
|
||||||
helm registry login ${{ env.REGISTRY }} \
|
helm registry login ${{ env.REGISTRY }} \
|
||||||
|
|||||||
@@ -34,5 +34,12 @@ spec:
|
|||||||
- name: Bot__MiniAppUrl
|
- name: Bot__MiniAppUrl
|
||||||
value: {{ .Values.telegram.miniAppUrl }}
|
value: {{ .Values.telegram.miniAppUrl }}
|
||||||
{{- end }}
|
{{- end }}
|
||||||
|
- name: Jwt__SecretKey
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ .Values.secretName }}
|
||||||
|
key: jwt-secret-key
|
||||||
|
- name: Jwt__ExpiryHours
|
||||||
|
value: {{ .Values.jwt.expiryHours | quote }}
|
||||||
resources:
|
resources:
|
||||||
{{- toYaml .Values.bot.resources | nindent 12 }}
|
{{- toYaml .Values.bot.resources | nindent 12 }}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
{{- if .Values.ingress.tls.certResolver }}
|
{{- if .Values.ingress.tls.certResolver }}
|
||||||
# ACME-резолвер (Let's Encrypt и т.п.) — Traefik сам получает сертификат.
|
# ACME-резолвер (Let's Encrypt и т.п.) — Traefik сам получает сертификат.
|
||||||
certResolver: {{ .Values.ingress.tls.certResolver }}
|
certResolver: {{ .Values.ingress.tls.certResolver }}
|
||||||
{{- else if .Values.ingress.tls.store }}
|
{{- else if .Values.ingress.tls.store.name }}
|
||||||
# TLSStore из произвольного неймспейса (требует allowCrossNamespace=true).
|
# TLSStore из произвольного неймспейса (требует allowCrossNamespace=true).
|
||||||
store:
|
store:
|
||||||
name: {{ .Values.ingress.tls.store.name }}
|
name: {{ .Values.ingress.tls.store.name }}
|
||||||
|
|||||||
+32
-1
@@ -14,6 +14,22 @@
|
|||||||
let authError = null
|
let authError = null
|
||||||
let authing = true
|
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() {
|
function devTokenFromHash() {
|
||||||
if (!import.meta.env.DEV) return null
|
if (!import.meta.env.DEV) return null
|
||||||
const params = new URLSearchParams(window.location.hash.slice(1))
|
const params = new URLSearchParams(window.location.hash.slice(1))
|
||||||
@@ -23,7 +39,7 @@
|
|||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
applyTheme()
|
applyTheme()
|
||||||
|
|
||||||
// Dev-режим: #token=<jwt> в URL — пропускаем обмен initData
|
// Dev-режим: #token=<jwt>
|
||||||
const devToken = devTokenFromHash()
|
const devToken = devTokenFromHash()
|
||||||
if (devToken) {
|
if (devToken) {
|
||||||
jwt.set(devToken)
|
jwt.set(devToken)
|
||||||
@@ -31,6 +47,21 @@
|
|||||||
return
|
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 {
|
try {
|
||||||
const { token } = await api.auth(initData)
|
const { token } = await api.auth(initData)
|
||||||
jwt.set(token)
|
jwt.set(token)
|
||||||
|
|||||||
@@ -33,7 +33,8 @@ async function request(method, path, body) {
|
|||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
// ── 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 ────────────────────────────────────────────────────────────────────
|
// ── Me ────────────────────────────────────────────────────────────────────
|
||||||
// GET /api/me → { telegramId, username, firstName, inboxCollectionId }
|
// 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]")]
|
[Route("api/[controller]")]
|
||||||
public sealed class AuthController(
|
public sealed class AuthController(
|
||||||
TelegramInitDataValidator validator,
|
TelegramInitDataValidator validator,
|
||||||
|
InlineAuthValidator inlineValidator,
|
||||||
JwtTokenService jwt) : ControllerBase
|
JwtTokenService jwt) : ControllerBase
|
||||||
{
|
{
|
||||||
|
/// <summary>Стандартная авторизация через Telegram initData (обычный WebApp).</summary>
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpPost("telegram")]
|
[HttpPost("telegram")]
|
||||||
public IActionResult Telegram([FromBody] TelegramAuthRequest request)
|
public IActionResult Telegram([FromBody] TelegramAuthRequest request)
|
||||||
@@ -20,6 +22,23 @@ public sealed class AuthController(
|
|||||||
var token = jwt.IssueToken(userId, username);
|
var token = jwt.IssueToken(userId, username);
|
||||||
return Ok(new { token });
|
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 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.Configuration.GetSection(JwtOptions.Section));
|
||||||
|
|
||||||
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
||||||
|
builder.Services.AddSingleton<InlineAuthValidator>();
|
||||||
builder.Services.AddSingleton<JwtTokenService>();
|
builder.Services.AddSingleton<JwtTokenService>();
|
||||||
builder.Services.AddHttpContextAccessor();
|
builder.Services.AddHttpContextAccessor();
|
||||||
builder.Services.AddScoped<CurrentUser>();
|
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 MemeVault.Bot.Telemetry;
|
||||||
using Prometheus;
|
using Prometheus;
|
||||||
using MemeVault.Bot.Options;
|
using MemeVault.Bot.Options;
|
||||||
@@ -22,7 +23,8 @@ builder.Services.AddInfrastructure(builder.Configuration);
|
|||||||
builder.Services.AddSingleton<BotMetrics>();
|
builder.Services.AddSingleton<BotMetrics>();
|
||||||
|
|
||||||
builder.Services.Configure<BotOptions>(builder.Configuration.GetSection(BotOptions.Section));
|
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<MessageHandler>();
|
||||||
builder.Services.AddScoped<InlineQueryHandler>();
|
builder.Services.AddScoped<InlineQueryHandler>();
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using MediatR;
|
using MediatR;
|
||||||
using MemeVault.Application.Queries.GetMediaItem;
|
using MemeVault.Application.Queries.GetMediaItem;
|
||||||
using MemeVault.Application.Queries.SearchMedia;
|
using MemeVault.Application.Queries.SearchMedia;
|
||||||
|
using MemeVault.Bot.Auth;
|
||||||
using MemeVault.Bot.Options;
|
using MemeVault.Bot.Options;
|
||||||
using MemeVault.Domain.Enums;
|
using MemeVault.Domain.Enums;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
@@ -17,20 +18,33 @@ namespace MemeVault.Bot.Telegram.InlineMode;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class InlineQueryHandler
|
public sealed class InlineQueryHandler
|
||||||
{
|
{
|
||||||
|
// cacheTime для результатов поиска (секунды).
|
||||||
|
// Если кэш инлайна мешает тестированию — уменьшить или поставить 0.
|
||||||
|
private const int SearchCacheTime = 10;
|
||||||
|
|
||||||
|
// cacheTime для точечной отправки — всегда 0, результат персональный.
|
||||||
|
private const int SendCacheTime = 0;
|
||||||
|
|
||||||
private readonly IMediator _mediator;
|
private readonly IMediator _mediator;
|
||||||
private readonly ITelegramBotClient _bot;
|
private readonly ITelegramBotClient _bot;
|
||||||
private readonly BotOptions _options;
|
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;
|
_mediator = mediator;
|
||||||
_bot = bot;
|
_bot = bot;
|
||||||
_options = options.Value;
|
_options = options.Value;
|
||||||
|
_signer = signer;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var userId = inlineQuery.From.Id;
|
var userId = inlineQuery.From.Id;
|
||||||
var rawQuery = inlineQuery.Query ?? string.Empty;
|
var rawQuery = inlineQuery.Query ?? string.Empty;
|
||||||
|
|
||||||
// Режим точечной отправки: Mini App выбрала конкретный элемент
|
// Режим точечной отправки: Mini App выбрала конкретный элемент
|
||||||
@@ -58,7 +72,7 @@ public sealed class InlineQueryHandler
|
|||||||
await _bot.AnswerInlineQuery(
|
await _bot.AnswerInlineQuery(
|
||||||
queryId,
|
queryId,
|
||||||
answers.OfType<InlineQueryResult>(),
|
answers.OfType<InlineQueryResult>(),
|
||||||
cacheTime: 0,
|
cacheTime: SendCacheTime,
|
||||||
isPersonal: true,
|
isPersonal: true,
|
||||||
cancellationToken: ct);
|
cancellationToken: ct);
|
||||||
}
|
}
|
||||||
@@ -75,24 +89,36 @@ public sealed class InlineQueryHandler
|
|||||||
.OfType<InlineQueryResult>()
|
.OfType<InlineQueryResult>()
|
||||||
.ToArray();
|
.ToArray();
|
||||||
|
|
||||||
// Кнопка над результатами — открывает Mini App в inline-режиме
|
// Кнопка над результатами — открывает Mini App в inline-режиме.
|
||||||
|
// Telegram не предоставляет initData в этом режиме, поэтому бот подписывает
|
||||||
|
// userId + timestamp и передаёт в query-строке для обмена на JWT.
|
||||||
InlineQueryResultsButton? button = string.IsNullOrEmpty(_options.MiniAppUrl)
|
InlineQueryResultsButton? button = string.IsNullOrEmpty(_options.MiniAppUrl)
|
||||||
? null
|
? null
|
||||||
: new InlineQueryResultsButton
|
: BuildButton(userId);
|
||||||
{
|
|
||||||
Text = "Открыть MemeVault",
|
|
||||||
WebApp = new WebAppInfo { Url = _options.MiniAppUrl + "?mode=inline" }
|
|
||||||
};
|
|
||||||
|
|
||||||
await _bot.AnswerInlineQuery(
|
await _bot.AnswerInlineQuery(
|
||||||
queryId,
|
queryId,
|
||||||
answers,
|
answers,
|
||||||
button: button,
|
button: button,
|
||||||
cacheTime: 10,
|
cacheTime: SearchCacheTime,
|
||||||
isPersonal: true,
|
isPersonal: true,
|
||||||
cancellationToken: ct);
|
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)
|
private static InlineQueryResult? ToInlineResult(MediaItemDto item)
|
||||||
@@ -107,8 +133,8 @@ public sealed class InlineQueryHandler
|
|||||||
{
|
{
|
||||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
||||||
{
|
{
|
||||||
Caption = item.Caption,
|
Caption = item.Caption,
|
||||||
Title = item.InlineTitle,
|
Title = item.InlineTitle,
|
||||||
Description = item.InlineDescription ?? tagsLine,
|
Description = item.InlineDescription ?? tagsLine,
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -117,7 +143,7 @@ public sealed class InlineQueryHandler
|
|||||||
item.FileId!,
|
item.FileId!,
|
||||||
title: item.InlineTitle ?? item.Caption ?? "Video")
|
title: item.InlineTitle ?? item.Caption ?? "Video")
|
||||||
{
|
{
|
||||||
Caption = item.Caption,
|
Caption = item.Caption,
|
||||||
Description = item.InlineDescription ?? tagsLine,
|
Description = item.InlineDescription ?? tagsLine,
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -126,7 +152,7 @@ public sealed class InlineQueryHandler
|
|||||||
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
||||||
{
|
{
|
||||||
Caption = item.Caption,
|
Caption = item.Caption,
|
||||||
Title = item.InlineTitle,
|
Title = item.InlineTitle,
|
||||||
},
|
},
|
||||||
|
|
||||||
MediaType.Text => new InlineQueryResultArticle(
|
MediaType.Text => new InlineQueryResultArticle(
|
||||||
|
|||||||
Reference in New Issue
Block a user