peppa/apps/web/app/auth/callback/route.ts
Асель 39367b1d82 PEP-8: remote MCP for ChatGPT with Peppa as OAuth 2.1 server
- OAuth: RFC 8414/9728 metadata, RFC 7591 dynamic registration,
  authorization code + PKCE S256 with a consent screen after Gitea login,
  refresh token rotation; tokens and codes stored hashed; revoke in web
- /mcp: stateless Streamable HTTP, Bearer → user; PM tools from
  @peppa/mcp/manager: projects, goals, tasks, create, move (board
  semantics, starts agents), inbox, answer/accept — owner-scoped
- login keeps ?next= through Gitea OAuth; Settings page with MCP URL and
  connected apps
- 5 new tests (53 e2e total, green); verified on prod as a client:
  DCR → consent → token → MCP over HTTPS → revoke → 401
- OpenSpec: pep-8 archived into spec remote-mcp

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:38:09 +05:00

31 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { exchangeOAuthCode, GiteaClient, upsertUserFromGitea } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { cookies } from "next/headers";
import { NextResponse, type NextRequest } from "next/server";
import { NEXT_COOKIE, publicOrigin, safeNext, sessionCookie, STATE_COOKIE } from "@/lib/auth";
import { db } from "@/lib/db";
export async function GET(req: NextRequest) {
const env = loadEnv();
const origin = await publicOrigin();
const fail = (msg: string) => NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(msg)}`);
const code = req.nextUrl.searchParams.get("code");
const state = req.nextUrl.searchParams.get("state");
const expected = (await cookies()).get(STATE_COOKIE)?.value;
if (!code || !state || !expected || state !== expected) return fail("Вход не подтверждён (state не совпал) — попробуйте ещё раз");
if (!env.GITEA_OAUTH_CLIENT_ID || !env.GITEA_OAUTH_CLIENT_SECRET) return fail("OAuth не настроен");
try {
const tokens = await exchangeOAuthCode(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, code, `${origin}/auth/callback`);
const me = await new GiteaClient(env.GITEA_URL, tokens.access_token).me();
const user = await upsertUserFromGitea(db, me, tokens);
const res = NextResponse.redirect(`${origin}${safeNext((await cookies()).get(NEXT_COOKIE)?.value)}`);
res.cookies.delete({ name: NEXT_COOKIE, path: "/auth" });
const c = sessionCookie(user.id);
res.cookies.set(c.name, c.value, c.options);
res.cookies.delete({ name: STATE_COOKIE, path: "/auth" });
return res;
} catch (e) {
return fail(`Не удалось войти: ${(e as Error).message}`);
}
}