peppa/packages/core/src/oauth.ts

205 lines
9.5 KiB
TypeScript

// OAuth 2.1 authorization server for Peppa's remote MCP (ChatGPT connectors etc.):
// dynamic client registration, authorization code + PKCE (S256), access/refresh tokens.
import { m as tr } from "@peppa/shared/i18n";
import { createHash, randomBytes } from "node:crypto";
import { oauthClients, oauthCodes, oauthTokens, type Db } from "@peppa/db";
import { and, desc, eq, gt, inArray, isNull, lt, or } from "drizzle-orm";
import { hashToken, hashTokenCandidates } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
export type OAuthClient = typeof oauthClients.$inferSelect;
export const ACCESS_TTL_SEC = 3600;
const REFRESH_TTL_SEC = 30 * 86400;
const CODE_TTL_MS = 10 * 60_000;
type OAuthErrorCode = "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied";
export class OAuthError extends PeppaError {
readonly error: OAuthErrorCode;
constructor(error: OAuthErrorCode, description: string) {
super(description);
this.error = error;
}
}
const random = () => randomBytes(32).toString("base64url");
function validRedirect(uri: string): boolean {
try {
const u = new URL(uri);
if (u.hash) return false;
return u.protocol === "https:" || (u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname));
} catch {
return false;
}
}
/** RFC 7591 dynamic client registration (public clients, PKCE required). */
export async function registerClient(db: Db, name: string | undefined, redirectUris: unknown): Promise<OAuthClient> {
if (!Array.isArray(redirectUris) || !redirectUris.length || !redirectUris.every((u) => typeof u === "string" && validRedirect(u))) {
throw new OAuthError("invalid_redirect_uri", "redirect_uris must be https (or http://localhost) URLs");
}
const [row] = await db
.insert(oauthClients)
.values({ id: `peppa-${randomBytes(12).toString("base64url")}`, name: (name || "MCP client").slice(0, 100), redirectUris })
.returning();
return row!;
}
export async function getClient(db: Db, id: string): Promise<OAuthClient | null> {
const [row] = await db.select().from(oauthClients).where(eq(oauthClients.id, id));
return row ?? null;
}
export interface AuthorizeRequest {
clientId: string;
redirectUri: string;
codeChallenge: string;
codeChallengeMethod: string;
responseType: string;
scope?: string;
}
/** Validates an /authorize request; throws OAuthError (shown to the user, not redirected). */
export async function checkAuthorizeRequest(db: Db, r: AuthorizeRequest): Promise<OAuthClient> {
const client = await getClient(db, r.clientId);
if (!client) throw new OAuthError("invalid_client", tr("Неизвестное приложение (client_id)"));
if (!client.redirectUris.includes(r.redirectUri)) throw new OAuthError("invalid_redirect_uri", tr("redirect_uri не зарегистрирован для приложения"));
if (r.responseType !== "code") throw new OAuthError("invalid_request", tr("response_type должен быть code"));
if (r.codeChallengeMethod !== "S256" || !/^[A-Za-z0-9_-]{43,128}$/.test(r.codeChallenge)) {
throw new OAuthError("invalid_request", tr("Нужен PKCE (code_challenge, метод S256)"));
}
return client;
}
/** Issues a one-time authorization code after the user consented. */
export async function issueCode(db: Db, r: AuthorizeRequest, userId: number): Promise<string> {
await checkAuthorizeRequest(db, r);
const code = random();
await db.insert(oauthCodes).values({
codeHash: hashToken(code),
clientId: r.clientId,
userId,
redirectUri: r.redirectUri,
codeChallenge: r.codeChallenge,
scope: r.scope ?? null,
expiresAt: new Date(Date.now() + CODE_TTL_MS),
});
return code;
}
export interface TokenResponse {
access_token: string;
token_type: "Bearer";
expires_in: number;
refresh_token: string;
scope?: string;
}
async function issueTokens(db: Db, clientId: string, userId: number, scope: string | null): Promise<TokenResponse> {
const access = random();
const refresh = random();
await db.insert(oauthTokens).values([
{ tokenHash: hashToken(access), kind: "access", clientId, userId, scope, expiresAt: new Date(Date.now() + ACCESS_TTL_SEC * 1000) },
{ tokenHash: hashToken(refresh), kind: "refresh", clientId, userId, scope, expiresAt: new Date(Date.now() + REFRESH_TTL_SEC * 1000) },
]);
return { access_token: access, token_type: "Bearer", expires_in: ACCESS_TTL_SEC, refresh_token: refresh, ...(scope ? { scope } : {}) };
}
const s256 = (verifier: string) => createHash("sha256").update(verifier).digest("base64url");
/** POST /oauth/token for authorization_code and refresh_token grants. */
export async function exchangeToken(db: Db, p: Record<string, string | undefined>): Promise<TokenResponse> {
if (p.grant_type === "authorization_code") {
if (!p.code || !p.client_id || !p.redirect_uri || !p.code_verifier) throw new OAuthError("invalid_request", "code, client_id, redirect_uri and code_verifier are required");
// Mark used atomically: a replayed code never yields tokens.
const [c] = await db
.update(oauthCodes)
.set({ usedAt: new Date() })
.where(and(inArray(oauthCodes.codeHash, hashTokenCandidates(p.code)), isNull(oauthCodes.usedAt), gt(oauthCodes.expiresAt, new Date())))
.returning();
if (!c) throw new OAuthError("invalid_grant", "code is invalid, expired or already used");
if (c.clientId !== p.client_id || c.redirectUri !== p.redirect_uri) throw new OAuthError("invalid_grant", "client_id or redirect_uri mismatch");
if (s256(p.code_verifier) !== c.codeChallenge) throw new OAuthError("invalid_grant", "PKCE verification failed");
return issueTokens(db, c.clientId, c.userId, c.scope);
}
if (p.grant_type === "refresh_token") {
if (!p.refresh_token) throw new OAuthError("invalid_request", "refresh_token is required");
const [t] = await db
.update(oauthTokens)
.set({ revokedAt: new Date() })
.where(
and(
inArray(oauthTokens.tokenHash, hashTokenCandidates(p.refresh_token)),
eq(oauthTokens.kind, "refresh"),
isNull(oauthTokens.revokedAt),
gt(oauthTokens.expiresAt, new Date()),
),
)
.returning();
if (!t || (p.client_id && p.client_id !== t.clientId)) throw new OAuthError("invalid_grant", "refresh_token is invalid");
return issueTokens(db, t.clientId, t.userId, t.scope);
}
throw new OAuthError("unsupported_grant_type", `grant_type ${p.grant_type ?? "(none)"} is not supported`);
}
/** Bearer token → { userId, clientId }, or null. */
export async function verifyAccessToken(db: Db, token: string | undefined | null): Promise<{ userId: number; clientId: string } | null> {
if (!token) return null;
const [t] = await db
.update(oauthTokens)
.set({ lastUsedAt: new Date() })
.where(and(inArray(oauthTokens.tokenHash, hashTokenCandidates(token)), eq(oauthTokens.kind, "access"), isNull(oauthTokens.revokedAt), gt(oauthTokens.expiresAt, new Date())))
.returning();
return t ? { userId: t.userId, clientId: t.clientId } : null;
}
/** Apps the user has granted access to (live refresh tokens), most recent first. */
export async function connectedApps(db: Db, userId: number) {
const rows = await db
.select({ clientId: oauthTokens.clientId, name: oauthClients.name, createdAt: oauthTokens.createdAt, lastUsedAt: oauthTokens.lastUsedAt })
.from(oauthTokens)
.innerJoin(oauthClients, eq(oauthTokens.clientId, oauthClients.id))
.where(and(eq(oauthTokens.userId, userId), isNull(oauthTokens.revokedAt), gt(oauthTokens.expiresAt, new Date())))
.orderBy(desc(oauthTokens.createdAt));
const byClient = new Map<string, { clientId: string; name: string; since: Date; lastUsedAt: Date | null }>();
for (const r of rows) {
const cur = byClient.get(r.clientId);
if (!cur) byClient.set(r.clientId, { clientId: r.clientId, name: r.name, since: r.createdAt, lastUsedAt: r.lastUsedAt });
else if (r.lastUsedAt && (!cur.lastUsedAt || r.lastUsedAt > cur.lastUsedAt)) cur.lastUsedAt = r.lastUsedAt;
}
return [...byClient.values()];
}
/** Revokes every token of `clientId` for this user. */
export async function revokeApp(db: Db, userId: number, clientId: string): Promise<number> {
const rows = await db
.update(oauthTokens)
.set({ revokedAt: new Date() })
.where(and(eq(oauthTokens.userId, userId), eq(oauthTokens.clientId, clientId), isNull(oauthTokens.revokedAt)))
.returning();
return rows.length;
}
/** PEP-294: days dead tokens and codes are kept for a look before they are deleted (PEPPA_OAUTH_KEEP_DAYS, default 7). */
export function oauthKeepDays(): number {
const n = Number(process.env.PEPPA_OAUTH_KEEP_DAYS);
return Number.isFinite(n) && n >= 0 && process.env.PEPPA_OAUTH_KEEP_DAYS?.trim() ? n : 7;
}
/**
* PEP-294: deletes MCP tokens that expired or were revoked more than `oauthKeepDays` ago, and
* authorization codes past the same age. A revoked refresh token is refused anyway (no family
* lookup), so dropping the row weakens nothing. The watchdog calls it once an hour.
*/
export async function pruneOAuth(db: Db, o: { now?: Date } = {}): Promise<{ tokens: number; codes: number }> {
const cut = new Date((o.now ?? new Date()).getTime() - oauthKeepDays() * 86_400_000);
const tokens = await db
.delete(oauthTokens)
.where(or(lt(oauthTokens.expiresAt, cut), lt(oauthTokens.revokedAt, cut)))
.returning({ h: oauthTokens.tokenHash });
const codes = await db.delete(oauthCodes).where(lt(oauthCodes.expiresAt, cut)).returning({ h: oauthCodes.codeHash });
return { tokens: tokens.length, codes: codes.length };
}