From 12950d322a680bcc6803152ed3f7568fe5b33752 Mon Sep 17 00:00:00 2001 From: "i.seliverstov" Date: Fri, 9 Oct 2026 18:27:36 +0500 Subject: [PATCH 1/4] feat(auth): expose profile token management API --- .../src/modules/auth/api-tokens.controller.ts | 48 +++++++ alfy-bot/src/modules/auth/auth.module.ts | 3 +- .../modules/auth/dto/create-api-token.dto.ts | 11 ++ alfy-bot/test/api-tokens.e2e-spec.ts | 121 ++++++++++++++++++ 4 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 alfy-bot/src/modules/auth/api-tokens.controller.ts create mode 100644 alfy-bot/src/modules/auth/dto/create-api-token.dto.ts create mode 100644 alfy-bot/test/api-tokens.e2e-spec.ts diff --git a/alfy-bot/src/modules/auth/api-tokens.controller.ts b/alfy-bot/src/modules/auth/api-tokens.controller.ts new file mode 100644 index 0000000..80c9398 --- /dev/null +++ b/alfy-bot/src/modules/auth/api-tokens.controller.ts @@ -0,0 +1,48 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + Header, + HttpCode, + Param, + ParseIntPipe, + Post, + Request, + UseGuards, +} from '@nestjs/common'; +import { ApiTokenService } from './application/api-token.service'; +import { CreateApiTokenDto } from './dto/create-api-token.dto'; +import { JwtAuthGuard } from './guards/jwt-auth.guard'; +import { JwtPayload } from './strategies/jwt.strategy'; + +interface AuthRequest extends Request { + user: JwtPayload; +} + +@Controller('auth/api-tokens') +@UseGuards(JwtAuthGuard) +export class ApiTokensController { + constructor(private readonly apiTokenService: ApiTokenService) {} + + @Post() + @Header('Cache-Control', 'no-store') + create(@Request() req: AuthRequest, @Body() dto: CreateApiTokenDto) { + return this.apiTokenService.generate(req.user.sub, dto.name); + } + + @Get() + @Header('Cache-Control', 'no-store') + list(@Request() req: AuthRequest) { + return this.apiTokenService.list(req.user.sub); + } + + @Delete(':id') + @HttpCode(204) + @Header('Cache-Control', 'no-store') + revoke(@Request() req: AuthRequest, @Param('id', ParseIntPipe) id: number) { + if (id < 1) throw new BadRequestException('Invalid token ID'); + return this.apiTokenService.revoke(id, req.user.sub); + } +} diff --git a/alfy-bot/src/modules/auth/auth.module.ts b/alfy-bot/src/modules/auth/auth.module.ts index 99ef874..5161c2e 100644 --- a/alfy-bot/src/modules/auth/auth.module.ts +++ b/alfy-bot/src/modules/auth/auth.module.ts @@ -4,6 +4,7 @@ import { PassportModule } from '@nestjs/passport'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { AuthController } from './auth.controller'; +import { ApiTokensController } from './api-tokens.controller'; import { AuthService } from './auth.service'; import { JwtStrategy } from './strategies/jwt.strategy'; import { JwtAuthGuard } from './guards/jwt-auth.guard'; @@ -36,7 +37,7 @@ import { EmailService } from '../email/email.service'; UserModule, EmailModule, ], - controllers: [AuthController], + controllers: [AuthController, ApiTokensController], providers: [ AuthService, JwtStrategy, diff --git a/alfy-bot/src/modules/auth/dto/create-api-token.dto.ts b/alfy-bot/src/modules/auth/dto/create-api-token.dto.ts new file mode 100644 index 0000000..5acb56c --- /dev/null +++ b/alfy-bot/src/modules/auth/dto/create-api-token.dto.ts @@ -0,0 +1,11 @@ +import { Transform } from 'class-transformer'; +import { IsString, Length } from 'class-validator'; + +export class CreateApiTokenDto { + @Transform(({ value }: { value: unknown }) => + typeof value === 'string' ? value.trim() : value, + ) + @IsString() + @Length(1, 100) + name: string; +} diff --git a/alfy-bot/test/api-tokens.e2e-spec.ts b/alfy-bot/test/api-tokens.e2e-spec.ts new file mode 100644 index 0000000..c49b7cd --- /dev/null +++ b/alfy-bot/test/api-tokens.e2e-spec.ts @@ -0,0 +1,121 @@ +import request from 'supertest'; +import { INestApplication } from '@nestjs/common'; +import { JwtService } from '@nestjs/jwt'; +import { DataSource } from 'typeorm'; +import { createTestApp } from './helpers/test-app'; +import { User } from '../src/shared/entities'; + +describe('API tokens (e2e)', () => { + let app: INestApplication; + let token: string; + let otherToken: string; + const url = '/api/auth/api-tokens'; + const auth = (value: string) => ({ Authorization: `Bearer ${value}` }); + + beforeAll(async () => { + const context = await createTestApp(); + app = context.app; + token = context.token; + const other = await app + .get(DataSource) + .getRepository(User) + .save({ telegramId: 998, username: 'other' }); + otherToken = app.get(JwtService).sign({ telegramId: 998, sub: other.id }); + }); + + afterAll(async () => { + await app.close(); + }); + + it('creates a token once and exposes plaintext only in the creation response', async () => { + const created = await request(app.getHttpServer()) + .post(url) + .set(auth(token)) + .send({ name: ' Codex ', userId: 999 }) + .expect(201); + expect(created.headers['cache-control']).toBe('no-store'); + expect(created.body).toEqual({ + id: expect.any(Number), + plaintext: expect.stringMatching(/^[a-f0-9]{48}$/), + }); + + const listed = await request(app.getHttpServer()) + .get(url) + .set(auth(token)) + .expect(200); + expect(listed.headers['cache-control']).toBe('no-store'); + expect(listed.body).toContainEqual({ + id: created.body.id, + name: 'Codex', + prefix: created.body.plaintext.slice(0, 10), + created_at: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/), + last_used_at: null, + }); + expect(JSON.stringify(listed.body)).not.toContain(created.body.plaintext); + }); + + it('lists only the owner’s tokens', async () => { + const own = await request(app.getHttpServer()) + .post(url) + .set(auth(otherToken)) + .send({ name: 'Other token' }) + .expect(201); + const listed = await request(app.getHttpServer()) + .get(url) + .set(auth(token)) + .expect(200); + expect(listed.body.some((entry: { id: number }) => entry.id === own.body.id)).toBe(false); + }); + + it('rejects foreign and repeated revocation', async () => { + const created = await request(app.getHttpServer()) + .post(url) + .set(auth(token)) + .send({ name: 'Revoke me' }) + .expect(201); + const target = `${url}/${created.body.id}`; + await request(app.getHttpServer()).delete(target).set(auth(otherToken)).expect(404); + const revoked = await request(app.getHttpServer()) + .delete(target) + .set(auth(token)) + .expect(204); + expect(revoked.headers['cache-control']).toBe('no-store'); + await request(app.getHttpServer()).delete(target).set(auth(token)).expect(404); + }); + + it.each(['', ' ', 'x'.repeat(101), 123, null])('rejects invalid token name %j', async (name) => { + await request(app.getHttpServer()) + .post(url) + .set(auth(token)) + .send({ name }) + .expect(400); + }); + + it.each(['abc', '0', '-1', '1.2'])('rejects invalid token id %s', async (id) => { + await request(app.getHttpServer()) + .delete(`${url}/${id}`) + .set(auth(token)) + .expect(400); + }); + + it('rejects missing JWT on every method', async () => { + await request(app.getHttpServer()).get(url).expect(401); + await request(app.getHttpServer()).post(url).send({ name: 'Denied' }).expect(401); + await request(app.getHttpServer()).delete(`${url}/1`).expect(401); + }); + + it('allows task access until revocation but never token management with an API token', async () => { + const created = await request(app.getHttpServer()) + .post(url) + .set(auth(token)) + .send({ name: 'Agent' }) + .expect(201); + const apiToken = created.body.plaintext as string; + await request(app.getHttpServer()).get('/api/tasks').set(auth(apiToken)).expect(200); + await request(app.getHttpServer()).get(url).set(auth(apiToken)).expect(401); + await request(app.getHttpServer()).post(url).set(auth(apiToken)).send({ name: 'Denied' }).expect(401); + await request(app.getHttpServer()).delete(`${url}/${created.body.id}`).set(auth(apiToken)).expect(401); + await request(app.getHttpServer()).delete(`${url}/${created.body.id}`).set(auth(token)).expect(204); + await request(app.getHttpServer()).get('/api/tasks').set(auth(apiToken)).expect(401); + }); +}); From 84333db91d8f868470e19a54f49accdeeb636452 Mon Sep 17 00:00:00 2001 From: "i.seliverstov" Date: Fri, 9 Oct 2026 18:29:07 +0500 Subject: [PATCH 2/4] feat(settings): add MCP tokens and agent setup guide --- CLAUDE.md | 4 +- README.md | 2 +- alfy-bot-frontend/.env.example | 1 + .../src/features/mcp/api/tokens.ts | 18 +++ .../src/features/mcp/lib/connection-guide.ts | 28 ++++ .../src/features/mcp/model/types.ts | 12 ++ .../src/features/mcp/model/useMcpTokens.ts | 78 +++++++++ .../features/mcp/ui/McpConnectionGuide.vue | 76 +++++++++ .../src/features/mcp/ui/McpSettings.vue | 153 ++++++++++++++++++ alfy-bot-frontend/src/views/SettingsView.vue | 3 + alfy-bot-frontend/src/vite-env.d.ts | 1 + .../tests/features/mcp/McpSettings.spec.ts | 125 ++++++++++++++ .../features/mcp/connection-guide.spec.ts | 32 ++++ .../tests/views/SettingsView.spec.ts | 7 + alfy-mcp/README.md | 26 ++- 15 files changed, 559 insertions(+), 7 deletions(-) create mode 100644 alfy-bot-frontend/src/features/mcp/api/tokens.ts create mode 100644 alfy-bot-frontend/src/features/mcp/lib/connection-guide.ts create mode 100644 alfy-bot-frontend/src/features/mcp/model/types.ts create mode 100644 alfy-bot-frontend/src/features/mcp/model/useMcpTokens.ts create mode 100644 alfy-bot-frontend/src/features/mcp/ui/McpConnectionGuide.vue create mode 100644 alfy-bot-frontend/src/features/mcp/ui/McpSettings.vue create mode 100644 alfy-bot-frontend/tests/features/mcp/McpSettings.spec.ts create mode 100644 alfy-bot-frontend/tests/features/mcp/connection-guide.spec.ts diff --git a/CLAUDE.md b/CLAUDE.md index e679650..3c80792 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co - `alfy-bot/` — NestJS-бэкенд (порт 3002): REST API под `/api`, Swagger на `/api/docs`, Telegram-бот (telegraf), TypeORM + SQLite (`data/database.sqlite`, `synchronize: true`), JWT + API-token auth (`JwtOrApiTokenGuard`), web-push. - `alfy-bot-frontend/` — Vue 3 + Vite + TS + Tailwind v4 + Pinia + vue-router. PWA (`vite-plugin-pwa`, кастомный `sw.ts`). Запускается как обычный SPA и как Telegram WebApp. -- `alfy-mcp/` — MCP-сервер (порт 3003, ESM, Node 22+): тонкая обёртка над REST `alfy-bot` для Claude Desktop/Code и удалённых MCP-клиентов. Транспорты: stdio + Streamable HTTP (endpoint `/mcp`). Auth — API-токены, выдаваемые ботом (`/mcp_token `). Не ходит в БД напрямую. +- `alfy-mcp/` — MCP-сервер (порт 3003, ESM, Node 22+): тонкая обёртка над REST `alfy-bot` для Claude Desktop/Code и удалённых MCP-клиентов. Транспорты: stdio + Streamable HTTP (endpoint `/mcp`). Auth — API-токены, выдаваемые в настройках веб-приложения или ботом (`/mcp_token `). Не ходит в БД напрямую. - `docker-compose.yml` + `Caddyfile` — прод: Caddy на 80/443 раздаёт `tracker.rocketup.tech`, проксирует `/api/*` на backend, `/mcp` + `/mcp/*` на alfy-mcp, остальное на frontend (nginx). - `scripts/tunnels.sh` — Cloudflare Quick Tunnels для dev (см. README). @@ -57,7 +57,7 @@ npm run test # vitest run npm run lint # eslint . ``` -ESM-пакет, Node 22+. SDK — `@modelcontextprotocol/sdk` (`McpServer` + `StreamableHTTPServerTransport`). Auth — API-токены через бот (`/mcp_token `), хранятся как bcrypt-хеш + 10-char prefix-index в БД (`api_token` entity). Tools — тонкая обёртка над REST `alfy-bot` (1 HTTP-вызов на tool, кроме `get_progress` — 3 параллельных). См. `alfy-mcp/README.md` для подключения из клиентов. +ESM-пакет, Node 22+. SDK — `@modelcontextprotocol/sdk` (`McpServer` + `StreamableHTTPServerTransport`). Auth — API-токены из настроек профиля или Telegram-команды `/mcp_token `, хранятся как bcrypt-хеш + 10-char prefix-index в БД (`api_token` entity). В настройках токен показывается только при выдаче, затем доступен только его префикс; отзыв прекращает доступ. Управление токенами через `/api/auth/api-tokens` доступно только с JWT, не с API-токеном. Для HTTP-клиентов адрес в production — `https://tracker.rocketup.tech/mcp`, локально — `http://localhost:3003/mcp`; `VITE_MCP_URL` задаёт адрес в инструкции фронта, без неё используется `/mcp` текущего origin. Tools — тонкая обёртка над REST `alfy-bot` (1 HTTP-вызов на tool, кроме `get_progress` — 3 параллельных). См. `alfy-mcp/README.md` для подключения из клиентов. **MCP-планирование спринтов.** `tools/sprints.ts` регистрируется в общем `createServer` для обоих транспортов. Контроллеры спринтов и групп используют `JwtOrApiTokenGuard`, иначе MCP API-токен получает 401. `move_story_to_sprint` вызывает атомарный серверный перенос; не заменять его циклом обновления задач. `complete_sprint` требует явный `moveTo`, `delete_sprint` — `confirm: true`. У задач доступны `groupId`/`sprintId` и фильтр `sprint_id`; создание без `sprintId` наследует спринт истории. Контракты проверяются через реальный MCP SDK в `alfy-mcp/tests/tools/sprints.spec.ts` и HTTP-тест API-токена в `alfy-bot/test/story-sprint.e2e-spec.ts`. diff --git a/README.md b/README.md index 0908884..b4a9798 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ ## Чем интересен проект -- **🤖 AI-native через MCP.** Отдельный [MCP-сервер](alfy-mcp/) даёт Claude Desktop / Claude Code полный набор инструментов для управления задачами, целями и привычками. Можно сказать ассистенту «создай цель на квартал и распиши привычки» — и он сделает это через типизированные tools, а не парсинг текста. Транспорты stdio и Streamable HTTP, авторизация по API-токенам из бота. +- **🤖 AI-native через MCP.** Отдельный [MCP-сервер](alfy-mcp/) даёт Claude Desktop / Claude Code полный набор инструментов для управления задачами, целями и привычками. Можно сказать ассистенту «создай цель на квартал и распиши привычки» — и он сделает это через типизированные tools, а не парсинг текста. Транспорты stdio и Streamable HTTP, авторизация по API-токенам из настроек профиля или бота. - **🎯 Цели → привычки → честный self-report.** Цель раскладывается на вопросы-привычки с расписанием (ежедневно / по дням недели / с интервалом). Семь типов вопросов: текст, оценка числом, оценка смайликами, да/нет, число, затраченное время, фото. Данные опроса — основа для аналитики и коучинга, а не «галочка выполнено». - **📱 Три поверхности, один бэкенд.** Telegram-бот (telegraf), Telegram WebApp и обычный SPA — всё работает поверх одного REST API. Веб собран как PWA (offline, web-push, установка на домашний экран). - **🧱 Чистая архитектура.** Бэкенд — Clean Architecture по модулям (порты в `domain/`, адаптеры в `infrastructure/`, оркестрация в сервисах). Фронтенд — Feature-Sliced Design. Границы слоёв реальны, а не декоративны. diff --git a/alfy-bot-frontend/.env.example b/alfy-bot-frontend/.env.example index 410f14d..ee9aa35 100644 --- a/alfy-bot-frontend/.env.example +++ b/alfy-bot-frontend/.env.example @@ -1,4 +1,5 @@ VITE_API_URL=http://localhost:3002/api +VITE_MCP_URL=http://localhost:3003/mcp # Dev auth (no WebApp): VITE_DEV_USE_WIDGET=true|false # true: Login Widget on /login (backend: BOT_TOKEN for widget validation) diff --git a/alfy-bot-frontend/src/features/mcp/api/tokens.ts b/alfy-bot-frontend/src/features/mcp/api/tokens.ts new file mode 100644 index 0000000..6ad4994 --- /dev/null +++ b/alfy-bot-frontend/src/features/mcp/api/tokens.ts @@ -0,0 +1,18 @@ +import type { CreatedMcpToken, McpToken } from '../model/types' +import { api } from '@/api/client' + +const path = '/auth/api-tokens' + +export async function listTokens(): Promise { + const { data } = await api.get(path) + return data +} + +export async function createToken(name: string): Promise { + const { data } = await api.post(path, { name }) + return data +} + +export async function revokeToken(id: number): Promise { + await api.delete(`${path}/${id}`) +} diff --git a/alfy-bot-frontend/src/features/mcp/lib/connection-guide.ts b/alfy-bot-frontend/src/features/mcp/lib/connection-guide.ts new file mode 100644 index 0000000..7520d3f --- /dev/null +++ b/alfy-bot-frontend/src/features/mcp/lib/connection-guide.ts @@ -0,0 +1,28 @@ +export interface ConnectionGuide { + codex: string + claudeCode: string + generic: string +} + +const singleQuote = /'/g + +export function resolveMcpUrl(override: string | undefined, origin: string): string { + const url = override?.trim() ? new URL(override.trim()) : new URL('/mcp', origin) + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash) { + throw new Error('Адрес MCP должен использовать HTTP или HTTPS без логина и фрагмента') + } + return url.toString() +} + +function shellQuote(value: string): string { + return `'${value.replace(singleQuote, '\'\\\'\'')}'` +} + +export function buildConnectionGuide(url: string): ConnectionGuide { + const encodedUrl = JSON.stringify(url) + return { + codex: `[mcp_servers.alfy]\nurl = ${encodedUrl}\nbearer_token_env_var = "ALFY_MCP_TOKEN"`, + claudeCode: `claude mcp add --transport http alfy ${shellQuote(url)} --header 'Authorization: Bearer YOUR_ALFY_TOKEN'`, + generic: JSON.stringify({ type: 'http', url, headers: { Authorization: 'Bearer YOUR_ALFY_TOKEN' } }, null, 2), + } +} diff --git a/alfy-bot-frontend/src/features/mcp/model/types.ts b/alfy-bot-frontend/src/features/mcp/model/types.ts new file mode 100644 index 0000000..7a1c9f9 --- /dev/null +++ b/alfy-bot-frontend/src/features/mcp/model/types.ts @@ -0,0 +1,12 @@ +export interface McpToken { + id: number + name: string + prefix: string + created_at: string + last_used_at: string | null +} + +export interface CreatedMcpToken { + id: number + plaintext: string +} diff --git a/alfy-bot-frontend/src/features/mcp/model/useMcpTokens.ts b/alfy-bot-frontend/src/features/mcp/model/useMcpTokens.ts new file mode 100644 index 0000000..552544f --- /dev/null +++ b/alfy-bot-frontend/src/features/mcp/model/useMcpTokens.ts @@ -0,0 +1,78 @@ +import type { CreatedMcpToken, McpToken } from './types' +import { ref } from 'vue' +import { createToken, listTokens, revokeToken } from '../api/tokens' + +export function useMcpTokens() { + const tokens = ref([]) + const revealed = ref(null) + const loading = ref(false) + const creating = ref(false) + const revokingId = ref(null) + const loadError = ref(null) + const createError = ref(null) + const revokeError = ref(null) + + async function fetchTokens(): Promise { + if (loading.value) + return + loading.value = true + loadError.value = null + try { + tokens.value = await listTokens() + } + catch { + loadError.value = 'Не удалось загрузить список токенов' + } + finally { + loading.value = false + } + } + + async function refresh(): Promise { + if (creating.value || revokingId.value !== null) + return + await fetchTokens() + } + + async function create(name: string): Promise { + if (creating.value || loading.value || revokingId.value !== null || !name.trim()) + return + creating.value = true + createError.value = null + try { + revealed.value = await createToken(name.trim()) + await fetchTokens() + } + catch { + createError.value = 'Не удалось создать токен. Обновите список и отзовите лишний токен, если запрос всё же прошёл.' + } + finally { + creating.value = false + } + } + + async function revoke(id: number): Promise { + if (revokingId.value !== null || loading.value || creating.value) + return + revokingId.value = id + revokeError.value = null + try { + await revokeToken(id) + tokens.value = tokens.value.filter(token => token.id !== id) + if (revealed.value?.id === id) + revealed.value = null + } + catch { + revokeError.value = 'Не удалось отозвать токен' + } + finally { + revokingId.value = null + } + } + + function dismissSecret(): void { + revealed.value = null + } + + return { tokens, revealed, loading, creating, revokingId, loadError, createError, revokeError, refresh, create, revoke, dismissSecret } +} diff --git a/alfy-bot-frontend/src/features/mcp/ui/McpConnectionGuide.vue b/alfy-bot-frontend/src/features/mcp/ui/McpConnectionGuide.vue new file mode 100644 index 0000000..b79862b --- /dev/null +++ b/alfy-bot-frontend/src/features/mcp/ui/McpConnectionGuide.vue @@ -0,0 +1,76 @@ + + + diff --git a/alfy-bot-frontend/src/features/mcp/ui/McpSettings.vue b/alfy-bot-frontend/src/features/mcp/ui/McpSettings.vue new file mode 100644 index 0000000..8f9ddaf --- /dev/null +++ b/alfy-bot-frontend/src/features/mcp/ui/McpSettings.vue @@ -0,0 +1,153 @@ + + +