global update and global fix
This commit is contained in:
31
apps/docs/components/bot-code-tabs.tsx
Normal file
31
apps/docs/components/bot-code-tabs.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { buildBotExamples } from '@/lib/bot-examples';
|
||||
import { fetchPublicSettingsClient } from '@/lib/api';
|
||||
import { resolveOAuthApiBase } from '@/lib/oauth-url';
|
||||
import { CodeExampleTabs } from '@/components/code-example-tabs';
|
||||
|
||||
export function BotCodeTabs() {
|
||||
const [apiBase, setApiBase] = useState('http://localhost:3000');
|
||||
|
||||
useEffect(() => {
|
||||
void fetchPublicSettingsClient()
|
||||
.then((settings) => setApiBase(resolveOAuthApiBase(settings)))
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const examples = useMemo(() => buildBotExamples(apiBase), [apiBase]);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-zinc-500 dark:text-zinc-400">
|
||||
Базовый URL Bot API:{' '}
|
||||
<code className="rounded bg-zinc-100 px-1.5 py-0.5 dark:bg-zinc-800">{apiBase}/bot{'{token}'}/{'{method}'}</code>
|
||||
{' — '}
|
||||
подставляется из <strong>PUBLIC_API_URL</strong> (как для OAuth).
|
||||
</p>
|
||||
<CodeExampleTabs examples={examples} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { DocBlock } from '@/lib/docs-pages';
|
||||
import { OAuthCodeTabs } from '@/components/oauth-code-tabs';
|
||||
import { AuthLoginCodeTabs } from '@/components/auth-code-tabs';
|
||||
import { AuthLdapCodeTabs } from '@/components/auth-ldap-code-tabs';
|
||||
import { BotCodeTabs } from '@/components/bot-code-tabs';
|
||||
import { ApiReferenceSection } from '@/components/api-endpoint-card';
|
||||
import { CodeBlock } from '@/components/code-block';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -70,6 +71,8 @@ export function DocBlockRenderer({ block }: { block: DocBlock }) {
|
||||
return <AuthLoginCodeTabs />;
|
||||
case 'auth-ldap-examples':
|
||||
return <AuthLdapCodeTabs />;
|
||||
case 'bot-examples':
|
||||
return <BotCodeTabs />;
|
||||
case 'api-reference':
|
||||
return <ApiReferenceSection />;
|
||||
default:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { ArrowRight, BookOpen, Code2, Rocket, Shield } from 'lucide-react';
|
||||
import { ArrowRight, BookOpen, Bot, Code2, Rocket, Shield } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { docNavigation, groupDocNavigation } from '@/lib/navigation';
|
||||
@@ -16,10 +16,16 @@ const highlights = [
|
||||
},
|
||||
{
|
||||
icon: Code2,
|
||||
title: 'OAuth 2.0',
|
||||
description: 'Примеры интеграции на JavaScript, Python, PHP, Go и других языках.',
|
||||
title: 'OAuth 2.0 / OIDC',
|
||||
description: 'Стандартный OpenID Connect: Discovery, client_id, PKCE, form-urlencoded token. Примеры для PHP без доработки OidcProvider.',
|
||||
href: '/docs/oauth'
|
||||
},
|
||||
{
|
||||
icon: Bot,
|
||||
title: 'Telegram Bot API',
|
||||
description: 'Telegraf, BotFather, профиль бота, setChatMenuButton и Mini Apps — совместимость с Telegram без смены кода.',
|
||||
href: '/docs/bot-api'
|
||||
},
|
||||
{
|
||||
icon: Shield,
|
||||
title: 'Безопасность',
|
||||
|
||||
@@ -31,12 +31,39 @@ export const apiReference: ApiTagGroup[] = [
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'OAuth 2.0',
|
||||
tag: 'OAuth 2.0 / OIDC',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/.well-known/openid-configuration', summary: 'OpenID Connect Discovery' },
|
||||
{ method: 'GET', path: '/oauth/authorize', summary: 'Создать authorization code' },
|
||||
{ method: 'POST', path: '/oauth/token', summary: 'Выдать OAuth токены (code / refresh_token)' },
|
||||
{ method: 'GET', path: '/oauth/userinfo', summary: 'Профиль по OAuth access token', auth: true }
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/.well-known/openid-configuration',
|
||||
summary: 'OpenID Connect Discovery',
|
||||
description: 'Метаданные провайдера: issuer, authorization_endpoint, token_endpoint, userinfo_endpoint, scopes_supported, code_challenge_methods_supported.'
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/oauth/authorize',
|
||||
summary: 'Authorization endpoint (OIDC)',
|
||||
description:
|
||||
'Стандартные query: client_id, redirect_uri, response_type=code, scope, state, code_challenge, code_challenge_method. ' +
|
||||
'HTTP 302 на redirect_uri?code=... или редирект на экран входа/подтверждения. Legacy: clientId, redirectUri, userId.'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/oauth/token',
|
||||
summary: 'Token endpoint',
|
||||
description:
|
||||
'Content-Type: application/x-www-form-urlencoded или JSON. ' +
|
||||
'Поля: grant_type, code, client_id, client_secret, redirect_uri, refresh_token. ' +
|
||||
'Ответ (snake_case): access_token, token_type, expires_in, refresh_token, id_token. ' +
|
||||
'Поддерживается Authorization: Basic (client_id:client_secret).'
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/oauth/userinfo',
|
||||
summary: 'UserInfo endpoint',
|
||||
description: 'Профиль по Bearer access_token. Поля: sub, email, phone, name, picture.',
|
||||
auth: true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -47,6 +74,20 @@ export const apiReference: ApiTagGroup[] = [
|
||||
{ method: 'PATCH', path: '/profile/users/{userId}/avatar', summary: 'Обновить аватар', auth: true },
|
||||
{ method: 'PATCH', path: '/profile/users/{userId}/contacts', summary: 'Обновить контакты', auth: true },
|
||||
{ method: 'POST', path: '/profile/users/{userId}/password', summary: 'Установить пароль', auth: true },
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/profile/users/{userId}/e2e-public-key',
|
||||
summary: 'Публичный E2E-ключ пользователя',
|
||||
description: 'SPKI base64 для ECDH P-256. Нужен перед созданием секретного чата.',
|
||||
auth: false
|
||||
},
|
||||
{
|
||||
method: 'PATCH',
|
||||
path: '/profile/users/{userId}/e2e-public-key',
|
||||
summary: 'Сохранить свой E2E-ключ',
|
||||
description: 'Тело: { "publicKey": "..." }. Только для своего userId.',
|
||||
auth: true
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/profile/users/{userId}/self-delete',
|
||||
@@ -133,15 +174,63 @@ export const apiReference: ApiTagGroup[] = [
|
||||
{ method: 'GET', path: '/family/groups/{groupId}/invite-search', summary: 'Поиск пользователей для приглашения', auth: true },
|
||||
{ method: 'GET', path: '/family/invites', summary: 'Входящие приглашения', auth: true },
|
||||
{ method: 'POST', path: '/family/invites/{inviteId}/respond', summary: 'Принять или отклонить приглашение', auth: true },
|
||||
{ method: 'GET', path: '/family/groups/{groupId}/presence', summary: 'Онлайн-статус участников семьи', auth: true }
|
||||
{ method: 'GET', path: '/family/groups/{groupId}/presence', summary: 'Онлайн-статус участников семьи', auth: true },
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/family/groups/{groupId}/botfather',
|
||||
summary: 'Добавить BotFather в семью',
|
||||
description: 'Создаёт BOT-чат с системным ботом BotFather для управления Telegram-ботами.',
|
||||
auth: true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Чат',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/chat/groups/{groupId}/rooms', summary: 'Список чатов семьи', auth: true },
|
||||
{ method: 'POST', path: '/chat/rooms/{roomId}/messages', summary: 'Отправить сообщение', auth: true },
|
||||
{ method: 'GET', path: '/chat/rooms/{roomId}/messages', summary: 'Сообщения чата', auth: true }
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/chat/groups/{groupId}/rooms',
|
||||
summary: 'Список чатов семьи',
|
||||
description: 'Автосинхронизация DIRECT/BOT через syncFamilyChats. Поля: type, peerUserId, botUsername, isE2E.',
|
||||
auth: true
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/chat/groups/{groupId}/rooms',
|
||||
summary: 'Создать групповой чат',
|
||||
description: 'Минимум 3 участника. Личные DIRECT создаются автоматически.',
|
||||
auth: true
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/chat/groups/{groupId}/e2e-rooms',
|
||||
summary: 'Создать секретный E2E-чат',
|
||||
description: 'Тело: { "peerUserId": "..." }. Только с участниками семьи (не ботами).',
|
||||
auth: true
|
||||
},
|
||||
{ method: 'PATCH', path: '/chat/rooms/{roomId}', summary: 'Настройки чата (название, mute)', auth: true },
|
||||
{ method: 'DELETE', path: '/chat/rooms/{roomId}', summary: 'Удалить чат', description: 'GENERAL удалить нельзя. E2E, DIRECT, BOT, GROUP — доступно участникам.', auth: true },
|
||||
{ method: 'POST', path: '/chat/rooms/{roomId}/members', summary: 'Добавить участника в групповой чат', auth: true },
|
||||
{ method: 'DELETE', path: '/chat/rooms/{roomId}/members/{memberUserId}', summary: 'Удалить участника из чата', auth: true },
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/chat/rooms/{roomId}/messages',
|
||||
summary: 'Сообщения чата',
|
||||
description: 'Query: limit (по умолчанию 50), beforeMessageId. Поле isEncrypted на сообщениях E2E.',
|
||||
auth: true
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/chat/rooms/{roomId}/messages',
|
||||
summary: 'Отправить сообщение',
|
||||
description: 'type: TEXT|IMAGE|AUDIO|VOICE|FILE|EMOJI|POLL. isEncrypted обязателен для E2E. BOT — только через /bots/...',
|
||||
auth: true
|
||||
},
|
||||
{ method: 'PATCH', path: '/chat/messages/{messageId}', summary: 'Редактировать сообщение', auth: true },
|
||||
{ method: 'DELETE', path: '/chat/messages/{messageId}', summary: 'Удалить сообщение', auth: true },
|
||||
{ method: 'POST', path: '/chat/messages/{messageId}/vote', summary: 'Голос в опросе', auth: true },
|
||||
{ method: 'POST', path: '/chat/rooms/{roomId}/read', summary: 'Отметить чат прочитанным', auth: true },
|
||||
{ method: 'POST', path: '/chat/rooms/{roomId}/mute', summary: 'Включить/выключить уведомления', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -152,6 +241,123 @@ export const apiReference: ApiTagGroup[] = [
|
||||
{ method: 'POST', path: '/media/chat/{roomId}/media/upload-url', summary: 'URL для медиа чата', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Telegram Bot API',
|
||||
endpoints: [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/sendMessage',
|
||||
summary: 'Отправить текстовое сообщение',
|
||||
description: 'Параметры: chat_id, text, reply_markup? (inline/reply/remove).'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/editMessageText',
|
||||
summary: 'Редактировать текст сообщения',
|
||||
description: 'Параметры: chat_id, message_id, text, reply_markup?'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/editMessageReplyMarkup',
|
||||
summary: 'Редактировать клавиатуру сообщения',
|
||||
description: 'Параметры: chat_id, message_id, reply_markup'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/answerCallbackQuery',
|
||||
summary: 'Ответ на callback_query',
|
||||
description: 'Параметры: callback_query_id, text?, show_alert?, url?'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/sendPhoto',
|
||||
summary: 'Отправить фото',
|
||||
description: 'Параметры: chat_id, photo (URL или file_id), caption?, reply_markup?'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/sendDocument',
|
||||
summary: 'Отправить документ',
|
||||
description: 'Параметры: chat_id, document (URL или file_id), caption?, reply_markup?'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/getMe',
|
||||
summary: 'Информация о боте',
|
||||
description: 'Telegram-совместимый формат ответа { ok, result }. Авторизация — токен в URL.'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/getUpdates',
|
||||
summary: 'Long polling входящих Update',
|
||||
description: 'Параметры: offset, limit (до 100), timeout (до 50 сек). Недоступен при активном webhook.'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/setWebhook',
|
||||
summary: 'Установить webhook URL',
|
||||
description: 'Тело: url, secret_token?, drop_pending_updates?'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/deleteWebhook',
|
||||
summary: 'Удалить webhook'
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bot{token}/getWebhookInfo',
|
||||
summary: 'Информация о webhook'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'BotFather',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/bots', summary: 'Список моих ботов', auth: true },
|
||||
{ method: 'POST', path: '/bots', summary: 'Создать бота', description: 'Возвращает token один раз.', auth: true },
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/bots/by-username/{botRef}/messages',
|
||||
summary: 'История чата с ботом',
|
||||
description: 'Сообщения пользователя с ботом в хронологическом порядке.',
|
||||
auth: true
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bots/by-username/{botRef}/messages',
|
||||
summary: 'Написать боту',
|
||||
description: 'Inbound-сообщение пользователя → RabbitMQ → webhook/getUpdates',
|
||||
auth: true
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bots/by-username/{botRef}/callback',
|
||||
summary: 'Нажатие inline-кнопки',
|
||||
description: 'Тело: { messageId, callbackData } → callback_query Update → webhook/getUpdates',
|
||||
auth: true
|
||||
},
|
||||
{ method: 'GET', path: '/bots/{botId}', summary: 'Получить бота', auth: true },
|
||||
{ method: 'PATCH', path: '/bots/{botId}', summary: 'Обновить name / username', auth: true },
|
||||
{ method: 'DELETE', path: '/bots/{botId}', summary: 'Удалить бота', auth: true },
|
||||
{ method: 'POST', path: '/bots/{botId}/revoke-token', summary: 'Перевыпустить токен', auth: true },
|
||||
{ method: 'PATCH', path: '/bots/{botId}/web-app', summary: 'Настроить Mini App URL', auth: true },
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/bots/web-app/validate',
|
||||
summary: 'Проверить initData Mini App',
|
||||
description: 'HMAC-SHA256 валидация как в Telegram Web Apps.'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Администрирование ботов',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/admin/bots', summary: 'Список всех ботов', description: 'Требует bots.manage.all', auth: true },
|
||||
{ method: 'GET', path: '/admin/bots/metrics', summary: 'Метрики ботов', auth: true },
|
||||
{ method: 'GET', path: '/admin/bots/{botId}', summary: 'Получить бота (админ)', auth: true },
|
||||
{ method: 'PATCH', path: '/admin/bots/{botId}/active', summary: 'Заблокировать / разблокировать бота', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Уведомления',
|
||||
endpoints: [
|
||||
|
||||
186
apps/docs/lib/bot-examples.ts
Normal file
186
apps/docs/lib/bot-examples.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
import type { OAuthExample } from '@/lib/oauth-examples';
|
||||
|
||||
export function buildBotExamples(apiBase: string): OAuthExample[] {
|
||||
const API_BASE = apiBase.replace(/\/+$/, '');
|
||||
const BOT_TOKEN = '123456789:AAHdqTcvCH1vGWJxfSeofS0As2XJarzRz5Q';
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'telegraf',
|
||||
label: 'Telegraf',
|
||||
language: 'javascript',
|
||||
code: `import { Telegraf } from 'telegraf';
|
||||
|
||||
// Достаточно сменить apiRoot — код бота остаётся без изменений
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN, {
|
||||
telegram: {
|
||||
apiRoot: '${API_BASE}/bot'
|
||||
}
|
||||
});
|
||||
|
||||
bot.start((ctx) => ctx.reply('Привет! Бот работает через Lendry Bot API.'));
|
||||
bot.command('ping', (ctx) => ctx.reply('pong'));
|
||||
|
||||
// Inline-клавиатура и callback_query
|
||||
bot.command('menu', (ctx) =>
|
||||
ctx.reply('Выберите действие:', {
|
||||
reply_markup: {
|
||||
inline_keyboard: [
|
||||
[{ text: '✅ OK', callback_data: 'ok' }, { text: '❌ Cancel', callback_data: 'cancel' }]
|
||||
]
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
bot.action('ok', async (ctx) => {
|
||||
await ctx.answerCbQuery('Принято!');
|
||||
await ctx.editMessageText('Вы нажали OK ✅');
|
||||
});
|
||||
|
||||
bot.launch();`
|
||||
},
|
||||
{
|
||||
id: 'node-telegram-bot-api',
|
||||
label: 'node-telegram-bot-api',
|
||||
language: 'javascript',
|
||||
code: `import TelegramBot from 'node-telegram-bot-api';
|
||||
|
||||
const token = process.env.BOT_TOKEN;
|
||||
const bot = new TelegramBot(token, {
|
||||
polling: true,
|
||||
baseApiUrl: '${API_BASE}/bot'
|
||||
});
|
||||
|
||||
bot.on('message', (msg) => {
|
||||
bot.sendMessage(msg.chat.id, \`Вы написали: \${msg.text}\`);
|
||||
});`
|
||||
},
|
||||
{
|
||||
id: 'curl',
|
||||
label: 'cURL',
|
||||
language: 'bash',
|
||||
code: `# getMe — проверка токена
|
||||
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/getMe' | jq
|
||||
|
||||
# sendMessage — chat_id = UUID пользователя Lendry ID
|
||||
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/sendMessage' \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{
|
||||
"chat_id": "USER_UUID",
|
||||
"text": "Привет из Bot API!"
|
||||
}' | jq
|
||||
|
||||
# sendMessage с inline-клавиатурой
|
||||
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/sendMessage' \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{
|
||||
"chat_id": "USER_UUID",
|
||||
"text": "Выберите:",
|
||||
"reply_markup": {
|
||||
"inline_keyboard": [[{ "text": "OK", "callback_data": "ok" }]]
|
||||
}
|
||||
}' | jq
|
||||
|
||||
# editMessageText
|
||||
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/editMessageText' \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{
|
||||
"chat_id": 1000000000000,
|
||||
"message_id": 1,
|
||||
"text": "Текст обновлён"
|
||||
}' | jq
|
||||
|
||||
# answerCallbackQuery
|
||||
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/answerCallbackQuery' \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{
|
||||
"callback_query_id": "CALLBACK_QUERY_ID",
|
||||
"text": "Готово!"
|
||||
}' | jq
|
||||
|
||||
# setChatMenuButton — глобальная кнопка меню (Web App)
|
||||
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/setChatMenuButton' \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{
|
||||
"menu_button": {
|
||||
"type": "web_app",
|
||||
"text": "Открыть",
|
||||
"web_app": { "url": "https://app.example.com" }
|
||||
}
|
||||
}' | jq
|
||||
|
||||
# setChatMenuButton — per-chat override
|
||||
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/setChatMenuButton' \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{
|
||||
"chat_id": 1000000000000,
|
||||
"menu_button": {
|
||||
"type": "web_app",
|
||||
"text": "Персонально",
|
||||
"web_app": { "url": "https://app.example.com/user" }
|
||||
}
|
||||
}' | jq`
|
||||
},
|
||||
{
|
||||
id: 'python',
|
||||
label: 'Python',
|
||||
language: 'python',
|
||||
code: `import os
|
||||
import requests
|
||||
|
||||
API_BASE = '${API_BASE}'
|
||||
TOKEN = os.environ['BOT_TOKEN']
|
||||
CHAT_ID = 'USER_UUID'
|
||||
|
||||
def bot_api(method: str, payload: dict | None = None):
|
||||
url = f"{API_BASE}/bot{TOKEN}/{method}"
|
||||
response = requests.post(url, json=payload or {}, timeout=30)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
print(bot_api('getMe'))
|
||||
print(bot_api('sendMessage', {'chat_id': CHAT_ID, 'text': 'Привет!'}))`
|
||||
},
|
||||
{
|
||||
id: 'botfather',
|
||||
label: 'BotFather (REST)',
|
||||
language: 'bash',
|
||||
code: `# Создание бота (JWT пользователя Lendry ID)
|
||||
curl -s -X POST '${API_BASE}/bots' \\
|
||||
-H 'Authorization: Bearer ACCESS_TOKEN' \\
|
||||
-H 'Content-Type: application/json' \\
|
||||
-d '{
|
||||
"name": "Мой сервисный бот",
|
||||
"username": "my_service"
|
||||
}' | jq
|
||||
|
||||
# Ответ содержит token — сохраните его, повторно не показывается при GET
|
||||
|
||||
# Профиль бота через BotFather в чате (после POST /family/groups/{id}/botfather):
|
||||
# /setdescription my_service Описание перед /start
|
||||
# /setabouttext my_service Краткое описание
|
||||
# /setuserpic my_service https://cdn.example.com/avatar.png
|
||||
# /setmenubutton my_service https://app.example.com|Открыть приложение`
|
||||
},
|
||||
{
|
||||
id: 'webapp',
|
||||
label: 'Mini App initData',
|
||||
language: 'javascript',
|
||||
code: `// На backend Mini App проверяйте initData через Bot API
|
||||
const response = await fetch('${API_BASE}/bots/web-app/validate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
initData: window.Telegram.WebApp.initData,
|
||||
botToken: process.env.BOT_TOKEN
|
||||
})
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
if (!result.valid) {
|
||||
throw new Error(result.error ?? 'Невалидный initData');
|
||||
}
|
||||
const user = result.userJson ? JSON.parse(result.userJson) : null;`
|
||||
}
|
||||
];
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,10 +9,11 @@ export const docNavigation: DocNavItem[] = [
|
||||
{ slug: 'architecture', title: 'Архитектура', group: 'Введение' },
|
||||
{ slug: 'deployment', title: 'Развёртывание на сервере', group: 'Введение' },
|
||||
{ slug: 'authentication', title: 'Аутентификация', group: 'Интеграция' },
|
||||
{ slug: 'oauth', title: 'OAuth 2.0', group: 'Интеграция' },
|
||||
{ slug: 'oauth', title: 'OAuth 2.0 / OIDC', group: 'Интеграция' },
|
||||
{ slug: 'ldap', title: 'LDAP / LDAPS', group: 'Интеграция' },
|
||||
{ slug: 'sessions', title: 'Сессии, PIN и удаление аккаунта', group: 'Безопасность' },
|
||||
{ slug: 'family-chat', title: 'Семья и чат', group: 'Функции' },
|
||||
{ slug: 'bot-api', title: 'Telegram Bot API', group: 'Интеграция' },
|
||||
{ slug: 'api-reference', title: 'Справочник API', group: 'Справочник' }
|
||||
];
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ export function buildOAuthExamples(apiBase: string): OAuthExample[] {
|
||||
id: 'javascript',
|
||||
label: 'JavaScript',
|
||||
language: 'javascript',
|
||||
code: `// Authorization Code Flow (Node.js / браузер)
|
||||
code: `// Authorization Code Flow — стандартный OIDC (RFC 6749)
|
||||
const clientId = 'YOUR_CLIENT_ID';
|
||||
const redirectUri = 'https://app.example.com/oauth/callback';
|
||||
const scope = 'openid profile email';
|
||||
@@ -21,34 +21,63 @@ const state = crypto.randomUUID();
|
||||
|
||||
// Шаг 1: перенаправить пользователя на IdP
|
||||
const authorizeUrl = new URL('${API_BASE}/oauth/authorize');
|
||||
authorizeUrl.searchParams.set('userId', 'USER_ID_AFTER_LOGIN');
|
||||
authorizeUrl.searchParams.set('clientId', clientId);
|
||||
authorizeUrl.searchParams.set('redirectUri', redirectUri);
|
||||
authorizeUrl.searchParams.set('client_id', clientId);
|
||||
authorizeUrl.searchParams.set('redirect_uri', redirectUri);
|
||||
authorizeUrl.searchParams.set('response_type', 'code');
|
||||
authorizeUrl.searchParams.set('scope', scope);
|
||||
authorizeUrl.searchParams.set('state', state);
|
||||
window.location.href = authorizeUrl.toString();
|
||||
|
||||
// OIDC Discovery (issuer = PUBLIC_API_URL из настроек админки)
|
||||
// OIDC Discovery
|
||||
// GET ${API_BASE}/.well-known/openid-configuration
|
||||
|
||||
// Шаг 2: обменять code на токены (на backend!)
|
||||
const tokenResponse = await fetch('${API_BASE}/oauth/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
grantType: 'authorization_code',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'AUTHORIZATION_CODE',
|
||||
clientId,
|
||||
clientSecret: 'YOUR_CLIENT_SECRET',
|
||||
redirectUri
|
||||
client_id: clientId,
|
||||
client_secret: 'YOUR_CLIENT_SECRET',
|
||||
redirect_uri: redirectUri
|
||||
})
|
||||
});
|
||||
const tokens = await tokenResponse.json();
|
||||
// tokens.access_token, tokens.id_token, tokens.refresh_token
|
||||
|
||||
// Шаг 3: получить профиль
|
||||
const profile = await fetch('${API_BASE}/oauth/userinfo', {
|
||||
headers: { Authorization: \`Bearer \${tokens.accessToken}\` }
|
||||
headers: { Authorization: \`Bearer \${tokens.access_token}\` }
|
||||
}).then((r) => r.json());`
|
||||
},
|
||||
{
|
||||
id: 'php',
|
||||
label: 'PHP (OIDC)',
|
||||
language: 'php',
|
||||
code: `<?php
|
||||
// composer require jumbojett/openid-connect-php
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
use Jumbojett\\OpenIDConnectClient;
|
||||
|
||||
$issuer = '${API_BASE}'; // PUBLIC_API_URL из админки Lendry ID
|
||||
$clientId = getenv('OAUTH_CLIENT_ID');
|
||||
$clientSecret = getenv('OAUTH_CLIENT_SECRET');
|
||||
$redirectUri = 'https://app.example.com/oauth/callback';
|
||||
|
||||
$oidc = new OpenIDConnectClient($issuer, $clientId, $clientSecret);
|
||||
$oidc->setRedirectURL($redirectUri);
|
||||
$oidc->addScope(['openid', 'profile', 'email']);
|
||||
|
||||
// Библиотека сама использует discovery, client_id, redirect_uri, response_type=code
|
||||
$oidc->authenticate();
|
||||
|
||||
$sub = $oidc->requestUserInfo('sub');
|
||||
$name = $oidc->requestUserInfo('name');
|
||||
$email = $oidc->requestUserInfo('email');
|
||||
|
||||
// userId передавать НЕ нужно — IdP определяет пользователя после входа`
|
||||
},
|
||||
{
|
||||
id: 'typescript-next',
|
||||
@@ -65,19 +94,19 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const tokenRes = await fetch(\`\${ISSUER}/oauth/token\`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
grantType: 'authorization_code',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
clientId: process.env.OAUTH_CLIENT_ID,
|
||||
clientSecret: process.env.OAUTH_CLIENT_SECRET,
|
||||
redirectUri: process.env.OAUTH_REDIRECT_URI
|
||||
client_id: process.env.OAUTH_CLIENT_ID!,
|
||||
client_secret: process.env.OAUTH_CLIENT_SECRET!,
|
||||
redirect_uri: process.env.OAUTH_REDIRECT_URI!
|
||||
})
|
||||
});
|
||||
|
||||
const tokens = await tokenRes.json();
|
||||
const response = NextResponse.redirect('/dashboard');
|
||||
response.cookies.set('access_token', tokens.accessToken, { httpOnly: true, secure: true });
|
||||
response.cookies.set('access_token', tokens.access_token, { httpOnly: true, secure: true });
|
||||
return response;
|
||||
}`
|
||||
},
|
||||
@@ -86,125 +115,61 @@ export async function GET(request: NextRequest) {
|
||||
label: 'Python',
|
||||
language: 'python',
|
||||
code: `import requests
|
||||
from urllib.parse import urlencode
|
||||
|
||||
API_BASE = '${API_BASE}'
|
||||
CLIENT_ID = 'YOUR_CLIENT_ID'
|
||||
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
|
||||
REDIRECT_URI = 'https://app.example.com/oauth/callback'
|
||||
|
||||
# OIDC Discovery
|
||||
discovery = requests.get(f'{API_BASE}/.well-known/openid-configuration', timeout=15).json()
|
||||
|
||||
params = urlencode({
|
||||
'userId': 'USER_ID',
|
||||
'clientId': CLIENT_ID,
|
||||
'redirectUri': REDIRECT_URI,
|
||||
'scope': 'openid profile email',
|
||||
'state': 'random-state'
|
||||
})
|
||||
authorize_url = f'{API_BASE}/oauth/authorize?{params}'
|
||||
# Authorization URL — стандартные параметры, userId не нужен
|
||||
authorize_url = (
|
||||
f"{discovery['authorization_endpoint']}"
|
||||
f"?client_id={CLIENT_ID}"
|
||||
f"&redirect_uri={requests.utils.quote(REDIRECT_URI, safe='')}"
|
||||
f"&response_type=code"
|
||||
f"&scope=openid%20profile%20email"
|
||||
f"&state=random-state"
|
||||
)
|
||||
|
||||
token_response = requests.post(f'{API_BASE}/oauth/token', json={
|
||||
'grantType': 'authorization_code',
|
||||
'code': 'AUTHORIZATION_CODE',
|
||||
'clientId': CLIENT_ID,
|
||||
'clientSecret': CLIENT_SECRET,
|
||||
'redirectUri': REDIRECT_URI
|
||||
}, timeout=15)
|
||||
token_response = requests.post(
|
||||
discovery['token_endpoint'],
|
||||
data={
|
||||
'grant_type': 'authorization_code',
|
||||
'code': 'AUTHORIZATION_CODE',
|
||||
'client_id': CLIENT_ID,
|
||||
'client_secret': CLIENT_SECRET,
|
||||
'redirect_uri': REDIRECT_URI,
|
||||
},
|
||||
timeout=15,
|
||||
)
|
||||
tokens = token_response.json()
|
||||
|
||||
profile = requests.get(
|
||||
f'{API_BASE}/oauth/userinfo',
|
||||
headers={'Authorization': f"Bearer {tokens['accessToken']}"},
|
||||
timeout=15
|
||||
discovery['userinfo_endpoint'],
|
||||
headers={'Authorization': f"Bearer {tokens['access_token']}"},
|
||||
timeout=15,
|
||||
).json()`
|
||||
},
|
||||
{
|
||||
id: 'php',
|
||||
label: 'PHP',
|
||||
language: 'php',
|
||||
code: `<?php
|
||||
$apiBase = '${API_BASE}'; // issuer = PUBLIC_API_URL из админки
|
||||
$clientId = getenv('OAUTH_CLIENT_ID');
|
||||
$clientSecret = getenv('OAUTH_CLIENT_SECRET');
|
||||
$redirectUri = 'https://app.example.com/oauth/callback';
|
||||
|
||||
// OIDC Discovery — используйте issuer, а не authorization endpoint
|
||||
$discovery = json_decode(file_get_contents($apiBase . '/.well-known/openid-configuration'), true);
|
||||
|
||||
$params = http_build_query([
|
||||
'userId' => 'USER_ID',
|
||||
'clientId' => $clientId,
|
||||
'redirectUri' => $redirectUri,
|
||||
'scope' => 'openid profile email',
|
||||
'state' => bin2hex(random_bytes(16)),
|
||||
]);
|
||||
header('Location: ' . $apiBase . '/oauth/authorize?' . $params);
|
||||
exit;`
|
||||
},
|
||||
{
|
||||
id: 'go',
|
||||
label: 'Go',
|
||||
language: 'go',
|
||||
code: `package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const apiBase = "${API_BASE}"
|
||||
|
||||
func buildAuthorizeURL(userID, clientID, redirectURI, scope, state string) string {
|
||||
q := url.Values{}
|
||||
q.Set("userId", userID)
|
||||
q.Set("clientId", clientID)
|
||||
q.Set("redirectUri", redirectURI)
|
||||
q.Set("scope", scope)
|
||||
q.Set("state", state)
|
||||
return apiBase + "/oauth/authorize?" + q.Encode()
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'csharp',
|
||||
label: 'C#',
|
||||
language: 'csharp',
|
||||
code: `using System.Net.Http.Json;
|
||||
|
||||
var apiBase = "${API_BASE}";
|
||||
var clientId = Environment.GetEnvironmentVariable("OAUTH_CLIENT_ID");
|
||||
var redirectUri = "https://app.example.com/oauth/callback";
|
||||
|
||||
var discovery = await new HttpClient().GetFromJsonAsync<Dictionary<string, object>>(
|
||||
$"{apiBase}/.well-known/openid-configuration");
|
||||
|
||||
var authorizeUrl =
|
||||
$"{apiBase}/oauth/authorize?userId=USER_ID&clientId={clientId}" +
|
||||
$"&redirectUri={Uri.EscapeDataString(redirectUri)}&scope=openid profile email&state=xyz";`
|
||||
},
|
||||
{
|
||||
id: 'curl',
|
||||
label: 'cURL',
|
||||
language: 'bash',
|
||||
code: `# OIDC Discovery (issuer = ${API_BASE})
|
||||
code: `# OIDC Discovery
|
||||
curl ${API_BASE}/.well-known/openid-configuration
|
||||
|
||||
# Authorization (браузер пользователя)
|
||||
open "${API_BASE}/oauth/authorize?userId=USER_ID&clientId=CLIENT_ID&redirectUri=https%3A%2F%2Fapp.example.com%2Fcallback&scope=openid%20profile%20email&state=xyz"
|
||||
# Authorization (браузер пользователя, стандартный OIDC)
|
||||
open "${API_BASE}/oauth/authorize?client_id=CLIENT_ID&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&response_type=code&scope=openid%20profile%20email&state=xyz"
|
||||
|
||||
# Обмен code на токены
|
||||
# Обмен code на токены (form-urlencoded)
|
||||
curl -X POST ${API_BASE}/oauth/token \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"grantType": "authorization_code",
|
||||
"code": "AUTHORIZATION_CODE",
|
||||
"clientId": "CLIENT_ID",
|
||||
"clientSecret": "CLIENT_SECRET",
|
||||
"redirectUri": "https://app.example.com/callback"
|
||||
}'
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \\
|
||||
-d "grant_type=authorization_code" \\
|
||||
-d "code=AUTHORIZATION_CODE" \\
|
||||
-d "client_id=CLIENT_ID" \\
|
||||
-d "client_secret=CLIENT_SECRET" \\
|
||||
-d "redirect_uri=https://app.example.com/callback"
|
||||
|
||||
# UserInfo
|
||||
curl ${API_BASE}/oauth/userinfo \\
|
||||
|
||||
@@ -39,3 +39,18 @@ export function buildOAuthEndpoints(apiBase: string): OAuthEndpoints {
|
||||
jwksUrl: `${base}/.well-known/jwks.json`
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAuthorizeUrl(
|
||||
apiBase: string,
|
||||
params: { clientId: string; redirectUri: string; scope: string; state?: string; codeChallenge?: string; codeChallengeMethod?: string }
|
||||
) {
|
||||
const url = new URL(`${normalizeBaseUrl(apiBase)}/oauth/authorize`);
|
||||
url.searchParams.set('client_id', params.clientId);
|
||||
url.searchParams.set('redirect_uri', params.redirectUri);
|
||||
url.searchParams.set('response_type', 'code');
|
||||
url.searchParams.set('scope', params.scope);
|
||||
if (params.state) url.searchParams.set('state', params.state);
|
||||
if (params.codeChallenge) url.searchParams.set('code_challenge', params.codeChallenge);
|
||||
if (params.codeChallengeMethod) url.searchParams.set('code_challenge_method', params.codeChallengeMethod);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user