peppa/apps/web/app/auth/callback/route.ts
Асель 73966e7e99 PEP-16: only allowlisted people can log into Peppa
- platform.allowed_logins (default asel, 7601978, dana): allowlisted logins,
  project invitees and members, and local CLI accounts may log in
- enforced in the Gitea OAuth callback, on every web request (removal takes
  effect at once) and on every remote MCP request (401)
- CLI: peppa platform allowlist | allow <login> | deny <login>
- tests: one per spec scenario (69 e2e total, green)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 03:38:08 +05:00

35 lines
2.0 KiB
TypeScript
Raw Permalink 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, getUserByLogin, GiteaClient, isLoginAllowed, isUserAllowed, 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 existing = await getUserByLogin(db, me.login);
if (!(await isLoginAllowed(db, me.login)) && !(existing && (await isUserAllowed(db, existing)))) {
return fail("Нет доступа к Пеппе — попросите администратора");
}
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}`);
}
}