Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d58fff4a7 | ||
|
|
f67a544d7a | ||
|
|
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)
|
||||
|
||||
@@ -34,6 +34,7 @@ async function request(method, path, body) {
|
||||
export const api = {
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
||||
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 }
|
||||
@@ -65,6 +66,9 @@ export const api = {
|
||||
joinCollection: (id) => request('POST', `/collections/${id}/join`),
|
||||
regenerateShareLink: (id) => request('POST', `/collections/${id}/share-link/regenerate`),
|
||||
|
||||
// ── Bot ───────────────────────────────────────────────────────────────────
|
||||
getBotInfo: () => request('GET', '/bot/info'),
|
||||
|
||||
// ── Invites ───────────────────────────────────────────────────────────────
|
||||
getInvites: (collectionId) => request('GET', `/collections/${collectionId}/invites`),
|
||||
createInvite: (collectionId, role, expiresAt) =>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte'
|
||||
import { Pencil, Trash2, Star, Check, X, EyeOff, Copy } from 'lucide-svelte'
|
||||
import { Pencil, Trash2, Star, Check, X, EyeOff, Copy, Link, Plus, UserCheck } from 'lucide-svelte'
|
||||
import { api } from '../lib/api.js'
|
||||
import { showAlert } from '../lib/telegram.js'
|
||||
|
||||
let botUsername = $state('')
|
||||
|
||||
let collections = $state([])
|
||||
let loading = $state(true)
|
||||
let error = $state(null)
|
||||
@@ -23,9 +25,35 @@
|
||||
// Клонирование: id коллекции, которая клонируется прямо сейчас
|
||||
let cloning = $state(null)
|
||||
|
||||
// Управление инвайтами: id раскрытой коллекции
|
||||
let invitesPanelId = $state(null)
|
||||
// { [collectionId]: CollectionInviteDto[] }
|
||||
let invitesByCol = $state({})
|
||||
let invitesLoading = $state(false)
|
||||
// Форма создания инвайта: { role: 0|1, expiresAt: string|null }
|
||||
let newInvite = $state({ role: 0, expiresAt: '' })
|
||||
let creatingInvite = $state(false)
|
||||
|
||||
let deleteTarget = $derived(collections.find(c => c.id === confirmDelete))
|
||||
let inboxTarget = $derived(collections.find(c => c.id === confirmInbox))
|
||||
|
||||
// CollectionRole: Viewer=0, Manager=1, Owner=2
|
||||
const ROLE_OWNER = 2
|
||||
|
||||
function inviteLink(token) {
|
||||
if (!botUsername) return null
|
||||
return `https://t.me/${botUsername}?start=inv_${token}`
|
||||
}
|
||||
|
||||
function roleLabel(role) {
|
||||
return role === 0 ? 'Читатель' : 'Менеджер'
|
||||
}
|
||||
|
||||
function formatExpiry(expiresAt) {
|
||||
if (!expiresAt) return null
|
||||
return new Date(expiresAt).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' })
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading = true; error = null
|
||||
try { collections = await api.getCollections() }
|
||||
@@ -50,6 +78,7 @@
|
||||
itemCount: 0,
|
||||
visibility: 0,
|
||||
shareToken: null,
|
||||
myRole: ROLE_OWNER,
|
||||
createdAt: new Date().toISOString(),
|
||||
}]
|
||||
} catch (e) {
|
||||
@@ -129,7 +158,87 @@
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
// ── Инвайты ────────────────────────────────────────────────────────────────
|
||||
async function toggleInvitesPanel(colId) {
|
||||
if (invitesPanelId === colId) {
|
||||
invitesPanelId = null
|
||||
return
|
||||
}
|
||||
invitesPanelId = colId
|
||||
newInvite = { role: 0, expiresAt: '' }
|
||||
if (invitesByCol[colId]) return // уже загружены
|
||||
|
||||
invitesLoading = true
|
||||
try {
|
||||
invitesByCol = { ...invitesByCol, [colId]: await api.getInvites(colId) }
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
invitesPanelId = null
|
||||
} finally {
|
||||
invitesLoading = false
|
||||
}
|
||||
}
|
||||
|
||||
async function createInvite(colId) {
|
||||
creatingInvite = true
|
||||
try {
|
||||
const expiresAt = newInvite.expiresAt
|
||||
? new Date(newInvite.expiresAt).toISOString()
|
||||
: null
|
||||
const { token } = await api.createInvite(colId, newInvite.role, expiresAt)
|
||||
const created = {
|
||||
id: crypto.randomUUID(), // placeholder до перезагрузки
|
||||
token,
|
||||
role: newInvite.role,
|
||||
isRevoked: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
revokedAt: null,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
invitesByCol = {
|
||||
...invitesByCol,
|
||||
[colId]: [created, ...(invitesByCol[colId] ?? [])],
|
||||
}
|
||||
newInvite = { role: 0, expiresAt: '' }
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
} finally {
|
||||
creatingInvite = false
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeInvite(colId, inviteId) {
|
||||
try {
|
||||
await api.revokeInvite(colId, inviteId)
|
||||
invitesByCol = {
|
||||
...invitesByCol,
|
||||
[colId]: invitesByCol[colId].filter(i => i.id !== inviteId),
|
||||
}
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyToClipboard(text) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
} catch {
|
||||
// fallback для старых WebView
|
||||
const el = document.createElement('textarea')
|
||||
el.value = text
|
||||
document.body.appendChild(el)
|
||||
el.select()
|
||||
document.execCommand('copy')
|
||||
document.body.removeChild(el)
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
load()
|
||||
api.getBotInfo()
|
||||
.then(r => { botUsername = r?.username ?? '' })
|
||||
.catch(() => {})
|
||||
})
|
||||
</script>
|
||||
|
||||
<div class="page">
|
||||
@@ -208,6 +317,16 @@
|
||||
>
|
||||
<Copy size={16}/>
|
||||
</button>
|
||||
{#if col.myRole === ROLE_OWNER}
|
||||
<button
|
||||
class="icon-btn invite"
|
||||
class:invite--on={invitesPanelId === col.id}
|
||||
onclick={() => toggleInvitesPanel(col.id)}
|
||||
title="Управление приглашениями"
|
||||
>
|
||||
<Link size={16}/>
|
||||
</button>
|
||||
{/if}
|
||||
{#if !col.isInbox}
|
||||
<button class="icon-btn" onclick={() => startEdit(col)} title="Переименовать">
|
||||
<Pencil size={16}/>
|
||||
@@ -223,6 +342,91 @@
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<!-- Панель инвайтов -->
|
||||
{#if invitesPanelId === col.id}
|
||||
<li class="invites-panel">
|
||||
<div class="invites-header">
|
||||
<UserCheck size={14}/> Приглашения
|
||||
</div>
|
||||
|
||||
{#if invitesLoading}
|
||||
<div class="invites-loading">Загрузка…</div>
|
||||
{:else}
|
||||
<!-- Список активных инвайтов -->
|
||||
{#if invitesByCol[col.id]?.length > 0}
|
||||
<ul class="invites-list">
|
||||
{#each invitesByCol[col.id] as inv (inv.id)}
|
||||
<li class="invite-item">
|
||||
<span class="invite-role-badge">{roleLabel(inv.role)}</span>
|
||||
{#if inviteLink(inv.token)}
|
||||
<button
|
||||
class="invite-link-btn"
|
||||
onclick={() => copyToClipboard(inviteLink(inv.token))}
|
||||
title="Скопировать ссылку"
|
||||
>
|
||||
<Copy size={12}/> Копировать
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
class="invite-link-btn"
|
||||
onclick={() => copyToClipboard(inv.token)}
|
||||
title="Скопировать токен"
|
||||
>
|
||||
<Copy size={12}/> Токен
|
||||
</button>
|
||||
{/if}
|
||||
{#if inv.expiresAt}
|
||||
<span class="invite-expiry">до {formatExpiry(inv.expiresAt)}</span>
|
||||
{/if}
|
||||
<button
|
||||
class="icon-btn del invite-revoke"
|
||||
onclick={() => revokeInvite(col.id, inv.id)}
|
||||
title="Отозвать"
|
||||
>
|
||||
<X size={14}/>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{:else}
|
||||
<div class="invites-empty">Нет активных приглашений</div>
|
||||
{/if}
|
||||
|
||||
<!-- Форма создания нового инвайта -->
|
||||
<div class="invite-create">
|
||||
<div class="invite-create-row">
|
||||
<div class="role-toggle">
|
||||
<button
|
||||
class="role-btn"
|
||||
class:role-btn--active={newInvite.role === 0}
|
||||
onclick={() => newInvite = { ...newInvite, role: 0 }}
|
||||
>Читатель</button>
|
||||
<button
|
||||
class="role-btn"
|
||||
class:role-btn--active={newInvite.role === 1}
|
||||
onclick={() => newInvite = { ...newInvite, role: 1 }}
|
||||
>Менеджер</button>
|
||||
</div>
|
||||
<input
|
||||
class="expiry-input"
|
||||
type="date"
|
||||
bind:value={newInvite.expiresAt}
|
||||
title="Срок действия (необязательно)"
|
||||
/>
|
||||
<button
|
||||
class="invite-add-btn"
|
||||
onclick={() => createInvite(col.id)}
|
||||
disabled={creatingInvite}
|
||||
title="Создать ссылку-приглашение"
|
||||
>
|
||||
<Plus size={14}/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</li>
|
||||
{/if}
|
||||
|
||||
<!-- Подтверждение удаления -->
|
||||
{#if confirmDelete === col.id && deleteTarget}
|
||||
<li class="confirm-panel">
|
||||
@@ -335,6 +539,9 @@
|
||||
.icon-btn.nsfw { color: var(--tg-hint, #999); }
|
||||
.icon-btn.nsfw:hover { color: #e53935; background: var(--tg-secondary-bg, #e8e8e8); }
|
||||
.icon-btn.nsfw--on { color: #e53935; }
|
||||
.icon-btn.invite { color: var(--tg-hint, #999); }
|
||||
.icon-btn.invite:hover { color: var(--tg-button, #2196f3); }
|
||||
.icon-btn.invite--on { color: var(--tg-button, #2196f3); }
|
||||
|
||||
/* Подтверждение */
|
||||
.confirm-panel {
|
||||
@@ -353,4 +560,97 @@
|
||||
.btn-primary { background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff); }
|
||||
.btn-ghost { background: none; color: var(--tg-hint, #888); }
|
||||
.btn-ghost:hover { background: var(--tg-secondary-bg, #e8e8e8); }
|
||||
|
||||
/* ── Панель инвайтов ─────────────────────────────────────────────────────── */
|
||||
.invites-panel {
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 12px;
|
||||
border-left: 3px solid var(--tg-button, #2196f3);
|
||||
display: flex; flex-direction: column; gap: 8px;
|
||||
}
|
||||
|
||||
.invites-header {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
font-size: 12px; font-weight: 600; color: var(--tg-hint, #888);
|
||||
text-transform: uppercase; letter-spacing: .05em;
|
||||
}
|
||||
|
||||
.invites-loading { font-size: 13px; color: var(--tg-hint, #888); }
|
||||
.invites-empty { font-size: 13px; color: var(--tg-hint, #888); text-align: center; padding: 4px 0; }
|
||||
|
||||
.invites-list {
|
||||
list-style: none; margin: 0; padding: 0;
|
||||
display: flex; flex-direction: column; gap: 4px;
|
||||
}
|
||||
|
||||
.invite-item {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
background: var(--tg-bg, #fff);
|
||||
border-radius: 8px; padding: 6px 8px;
|
||||
}
|
||||
|
||||
.invite-role-badge {
|
||||
font-size: 11px; font-weight: 600;
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
border-radius: 4px; padding: 1px 6px;
|
||||
white-space: nowrap; flex-shrink: 0;
|
||||
}
|
||||
|
||||
.invite-link-btn {
|
||||
display: flex; align-items: center; gap: 4px;
|
||||
padding: 3px 8px; border-radius: 6px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-text, #000); font-size: 12px; cursor: pointer;
|
||||
white-space: nowrap; flex-shrink: 0;
|
||||
transition: background .12s;
|
||||
}
|
||||
.invite-link-btn:hover { background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff); }
|
||||
|
||||
.invite-expiry {
|
||||
font-size: 11px; color: var(--tg-hint, #888);
|
||||
white-space: nowrap; flex-shrink: 0; margin-left: auto;
|
||||
}
|
||||
|
||||
.invite-revoke {
|
||||
width: 26px; height: 26px; flex-shrink: 0;
|
||||
color: var(--tg-hint, #999);
|
||||
}
|
||||
.invite-revoke:hover { color: #e53935; }
|
||||
|
||||
/* Форма создания инвайта */
|
||||
.invite-create { margin-top: 2px; }
|
||||
.invite-create-row {
|
||||
display: flex; gap: 6px; align-items: center;
|
||||
}
|
||||
|
||||
.role-toggle {
|
||||
display: flex; border-radius: 8px; overflow: hidden;
|
||||
border: 1px solid var(--tg-hint, #ccc);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.role-btn {
|
||||
padding: 5px 10px; border: none; font-size: 12px; font-weight: 500;
|
||||
background: none; color: var(--tg-hint, #888); cursor: pointer;
|
||||
transition: background .12s, color .12s;
|
||||
}
|
||||
.role-btn:first-child { border-right: 1px solid var(--tg-hint, #ccc); }
|
||||
.role-btn--active {
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
}
|
||||
|
||||
.expiry-input {
|
||||
flex: 1; min-width: 0; padding: 5px 8px; border-radius: 8px;
|
||||
border: 1px solid var(--tg-hint, #ccc);
|
||||
background: var(--tg-bg, #fff); color: var(--tg-text, #000);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.invite-add-btn {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; border-radius: 8px; border: none;
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
cursor: pointer; flex-shrink: 0;
|
||||
transition: opacity .12s;
|
||||
}
|
||||
.invite-add-btn:disabled { opacity: .4; cursor: default; }
|
||||
</style>
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
let items = $state([])
|
||||
let query = $state('')
|
||||
let includeNsfw = $state(false)
|
||||
let loading = $state(true)
|
||||
let error = $state(null)
|
||||
let sending = $state(null) // id медиа, которое сейчас отправляется
|
||||
@@ -26,7 +27,7 @@
|
||||
async function load() {
|
||||
loading = true; error = null; previews = {}
|
||||
try {
|
||||
items = await api.getMedia(query)
|
||||
items = await api.getMedia(query, includeNsfw)
|
||||
for (const item of items) {
|
||||
if (PREVIEWABLE.has(item.mediaType)) loadPreview(item.id)
|
||||
}
|
||||
@@ -76,6 +77,11 @@
|
||||
searchTimer = setTimeout(load, 400)
|
||||
}
|
||||
|
||||
function toggleNsfw() {
|
||||
includeNsfw = !includeNsfw
|
||||
load()
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
</script>
|
||||
|
||||
@@ -96,12 +102,20 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="search-row">
|
||||
<input
|
||||
class="search"
|
||||
placeholder="Поиск: #мем -#кот слово"
|
||||
bind:value={query}
|
||||
oninput={onSearch}
|
||||
/>
|
||||
<button
|
||||
class="nsfw-btn"
|
||||
class:nsfw-btn--active={includeNsfw}
|
||||
onclick={toggleNsfw}
|
||||
title={includeNsfw ? 'Скрыть 18+' : 'Показать 18+'}
|
||||
>18+</button>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="hint">Загрузка…</div>
|
||||
@@ -180,13 +194,30 @@
|
||||
}
|
||||
.chat-name :global(svg) { flex-shrink: 0; color: var(--tg-hint, #888); }
|
||||
|
||||
.search-row {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
margin: 4px 8px 6px;
|
||||
}
|
||||
.search {
|
||||
margin: 4px 8px 6px; width: calc(100% - 16px);
|
||||
flex: 1; min-width: 0;
|
||||
padding: 8px 12px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-text, #000); font-size: 14px;
|
||||
}
|
||||
|
||||
.nsfw-btn {
|
||||
flex-shrink: 0;
|
||||
padding: 8px 10px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-hint, #888); font-size: 13px; font-weight: 600;
|
||||
cursor: pointer; transition: background .15s, color .15s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.nsfw-btn--active {
|
||||
background: var(--tg-button, #2196f3);
|
||||
color: var(--tg-btn-text, #fff);
|
||||
}
|
||||
|
||||
.hint { text-align: center; padding: 32px; color: var(--tg-hint, #888); }
|
||||
.error { color: #e53935; }
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using MemeVault.Api.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace MemeVault.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/bot")]
|
||||
public sealed class BotController(BotInfoService botInfo) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Возвращает публичный username бота.
|
||||
/// Не требует авторизации — username бота публичен.
|
||||
/// </summary>
|
||||
[HttpGet("info")]
|
||||
public async Task<IActionResult> GetInfo(CancellationToken ct)
|
||||
{
|
||||
var username = await botInfo.GetBotUsernameAsync();
|
||||
return Ok(new { username });
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using MemeVault.Api.Middleware;
|
||||
using MemeVault.Api.Auth;
|
||||
using MemeVault.Api.Services;
|
||||
using System.Text;
|
||||
using MemeVault.Api.Options;
|
||||
using MemeVault.Infrastructure;
|
||||
@@ -27,7 +28,9 @@ builder.Services.Configure<JwtOptions>(
|
||||
builder.Configuration.GetSection(JwtOptions.Section));
|
||||
|
||||
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
||||
builder.Services.AddSingleton<InlineAuthValidator>();
|
||||
builder.Services.AddSingleton<JwtTokenService>();
|
||||
builder.Services.AddSingleton<BotInfoService>();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<CurrentUser>();
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using Telegram.Bot;
|
||||
|
||||
namespace MemeVault.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Кэширует username бота на весь lifetime процесса.
|
||||
/// GetMeAsync вызывается ровно один раз при первом обращении.
|
||||
/// </summary>
|
||||
public sealed class BotInfoService
|
||||
{
|
||||
private readonly Lazy<Task<string>> _username;
|
||||
|
||||
public BotInfoService(ITelegramBotClient botClient)
|
||||
{
|
||||
_username = new Lazy<Task<string>>(
|
||||
() => FetchAsync(botClient),
|
||||
LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
}
|
||||
|
||||
private static async Task<string> FetchAsync(ITelegramBotClient botClient)
|
||||
{
|
||||
var me = await botClient.GetMe();
|
||||
return me.Username ?? string.Empty;
|
||||
}
|
||||
|
||||
public Task<string> GetBotUsernameAsync() => _username.Value;
|
||||
}
|
||||
@@ -15,5 +15,6 @@ public sealed record CollectionDto(
|
||||
bool IsNsfw,
|
||||
string? ShareToken,
|
||||
int ItemCount,
|
||||
DateTimeOffset CreatedAt
|
||||
DateTimeOffset CreatedAt,
|
||||
CollectionRole MyRole
|
||||
);
|
||||
|
||||
+3
-1
@@ -1,4 +1,5 @@
|
||||
using MediatR;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetUserCollections;
|
||||
@@ -35,7 +36,8 @@ public sealed class GetUserCollectionsQueryHandler(
|
||||
c.IsNsfw,
|
||||
c.ShareToken,
|
||||
countByCollection.GetValueOrDefault(c.Id, 0),
|
||||
c.CreatedAt
|
||||
c.CreatedAt,
|
||||
c.GetRole(request.OwnerTelegramId) ?? CollectionRole.Viewer
|
||||
)).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,15 +18,28 @@ 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)
|
||||
@@ -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,
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user