peppa/apps/web/lib/auth.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

55 lines
2.0 KiB
TypeScript

import { getUser, sign, verify, type User } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { db } from "./db";
export const SESSION_COOKIE = "peppa_session";
export const STATE_COOKIE = "peppa_oauth_state";
export const NEXT_COOKIE = "peppa_next";
/** Only same-site relative paths are allowed as a post-login destination. */
export const safeNext = (n: string | null | undefined) => (n && n.startsWith("/") && !n.startsWith("//") ? n : "/");
const SESSION_DAYS = 30;
interface SessionPayload {
uid: number;
exp: number;
}
export async function currentUser(): Promise<User | null> {
const p = verify<SessionPayload>((await cookies()).get(SESSION_COOKIE)?.value);
if (!p || p.exp < Date.now()) return null;
return getUser(db, p.uid);
}
/** For pages and server actions: the logged-in user, or a redirect to /login. */
export async function requireUser(): Promise<User> {
const u = await currentUser();
if (!u) redirect("/login");
return u;
}
export function sessionCookie(uid: number) {
const exp = Date.now() + SESSION_DAYS * 86400_000;
return {
name: SESSION_COOKIE,
value: sign({ uid, exp } satisfies SessionPayload),
options: { httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/", maxAge: SESSION_DAYS * 86400 },
};
}
const isHttps = () => loadEnv().PEPPA_WEB_URL.startsWith("https://");
/**
* Public origin of this request. Behind Cloudflare → Traefik the proto header says http,
* so the configured PEPPA_WEB_URL wins when the host matches it.
*/
export async function publicOrigin(): Promise<string> {
const h = await headers();
const host = h.get("x-forwarded-host") ?? h.get("host") ?? "localhost:3100";
const configured = new URL(loadEnv().PEPPA_WEB_URL);
if (host === configured.host) return configured.origin;
return `${host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https"}://${host}`;
}