import { redirect } from "react-router"; import { consumeMcpOAuthAuthorizationCode, consumeMcpOAuthRefreshToken, createMcpOAuthAuthorizationCode, findMcpOAuthClient, issueMcpOAuthTokenPair, registerMcpOAuthClient, revokeMcpOAuthToken, verifyMcpOAuthPkceS256, type McpOAuthClientSummary, } from "@hivegrid/db/mcp-oauth.server"; import type { Prisma } from "@hivegrid/db/prisma-browser"; import { getTenantByIdOrSlug, getTenantMembershipByIds, getTenantsForUser } from "@hivegrid/db/auth-boundary.server"; import { loadRequiredWebConfig } from "@hivegrid/config"; export const MCP_OAUTH_SUPPORTED_SCOPES = [ "mcp:read", "mcp:write", "mcp:lead:read", "mcp:lead:create", "mcp:contact:read", "mcp:project:read", "mcp:project:write", "mcp:pipeline:read", "mcp:activity:write", ] as const; const DEFAULT_SCOPE = "mcp:read"; const SUPPORTED_SCOPE_SET = new Set(MCP_OAUTH_SUPPORTED_SCOPES); export type McpOAuthAuthorizeRequest = { responseType: "code"; client: McpOAuthClientSummary; redirectUri: string; scopes: string[]; state?: string; codeChallenge: string; codeChallengeMethod: "S256"; resource: string; tenant: { id: string; slug: string; name: string }; }; export type McpOAuthPublicUrls = { issuer: string; resource: string; authorizationEndpoint: string; tokenEndpoint: string; registrationEndpoint: string; revocationEndpoint: string; }; export class McpOAuthError extends Error { readonly error: string; readonly status: number; readonly description: string; constructor(error: string, description: string, status = 400) { super(description); this.name = "McpOAuthError"; this.error = error; this.status = status; this.description = description; } } export function getMcpOAuthPublicUrls(): McpOAuthPublicUrls { const routing = loadRequiredWebConfig().routing; const issuer = trimTrailingSlash(process.env.MCP_AUTHORIZATION_SERVER_URL) ?? `${routing.protocol}://${routing.webAppHost}`; const resource = trimTrailingSlash(process.env.MCP_RESOURCE_URL) ?? deriveMcpResourceOrigin(routing.protocol, routing.webAppHost, routing.appBaseDomain); return { issuer, resource, authorizationEndpoint: `${issuer}/oauth/authorize`, tokenEndpoint: `${issuer}/oauth/token`, registrationEndpoint: `${issuer}/oauth/register`, revocationEndpoint: `${issuer}/oauth/revoke`, }; } export function oauthAuthorizationServerMetadata() { const urls = getMcpOAuthPublicUrls(); return { issuer: urls.issuer, authorization_endpoint: urls.authorizationEndpoint, token_endpoint: urls.tokenEndpoint, registration_endpoint: urls.registrationEndpoint, revocation_endpoint: urls.revocationEndpoint, response_types_supported: ["code"], grant_types_supported: ["authorization_code", "refresh_token"], code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["none"], scopes_supported: MCP_OAUTH_SUPPORTED_SCOPES, resource_indicators_supported: true, }; } export async function resolveAuthorizeRequest(url: URL, userId: string): Promise { if (url.searchParams.get("response_type") !== "code") { throw new McpOAuthError("unsupported_response_type", "MCP OAuth supports response_type=code only."); } const clientId = requiredParam(url, "client_id"); const redirectUri = requiredParam(url, "redirect_uri"); const codeChallenge = requiredParam(url, "code_challenge"); const codeChallengeMethod = requiredParam(url, "code_challenge_method"); if (codeChallengeMethod !== "S256") { throw new McpOAuthError("invalid_request", "Only PKCE S256 is supported."); } const client = await findMcpOAuthClient(clientId); if (!client?.active) { throw new McpOAuthError("invalid_client", "OAuth client is unknown or inactive.", 401); } if (!client.redirectUris.includes(redirectUri)) { throw new McpOAuthError("invalid_request", "redirect_uri is not registered for this client."); } const scopes = parseScopes(url.searchParams.get("scope")); assertScopesSupported(scopes); assertScopesAllowedByClient(scopes, client); const urls = getMcpOAuthPublicUrls(); const resource = trimTrailingSlash(url.searchParams.get("resource")) ?? urls.resource; if (resource !== urls.resource) { throw new McpOAuthError("invalid_target", "resource must match the MCP resource."); } const tenant = await resolveAuthorizeTenant(url.searchParams.get("tenant"), userId); return { responseType: "code", client, redirectUri, scopes, state: url.searchParams.get("state") ?? undefined, codeChallenge, codeChallengeMethod: "S256", resource, tenant, }; } export async function approveAuthorizeRequest(request: Request, userId: string): Promise { const form = await request.formData(); const url = new URL("/oauth/authorize", request.url); for (const key of ["response_type", "client_id", "redirect_uri", "scope", "state", "code_challenge", "code_challenge_method", "resource", "tenant"]) { const value = form.get(key); if (typeof value === "string" && value.length > 0) { url.searchParams.set(key, value); } } const resolved = await resolveAuthorizeRequest(url, userId); if (form.get("decision") !== "approve") { throw redirect(withOAuthRedirectParams(resolved.redirectUri, { error: "access_denied", state: resolved.state })); } const { code } = await createMcpOAuthAuthorizationCode({ clientId: resolved.client.id, userId, tenantId: resolved.tenant.id, tenantSlug: resolved.tenant.slug, redirectUri: resolved.redirectUri, scopes: resolved.scopes, resource: resolved.resource, codeChallenge: resolved.codeChallenge, codeChallengeMethod: "S256", secret: getMcpOAuthTokenHashSecret(), }); throw redirect(withOAuthRedirectParams(resolved.redirectUri, { code, state: resolved.state })); } export async function registerOAuthClientFromRequest(request: Request): Promise { const body = await readJson(request); const redirectUris = normalizeRedirectUris(body.redirect_uris); const scopes = parseScopes(typeof body.scope === "string" ? body.scope : undefined); assertScopesSupported(scopes); const grantTypes = normalizeGrantTypes(body.grant_types); const client = await registerMcpOAuthClient({ clientName: typeof body.client_name === "string" && body.client_name.trim() ? body.client_name.trim() : "MCP Client", redirectUris, scopes, grantTypes, contacts: Array.isArray(body.contacts) ? body.contacts.filter((item): item is string => typeof item === "string") : undefined, metadata: body as Prisma.InputJsonObject, }); return json( { client_id: client.clientId, client_id_issued_at: Math.floor(Date.now() / 1000), client_name: client.clientName, redirect_uris: client.redirectUris, grant_types: grantTypes, response_types: ["code"], token_endpoint_auth_method: "none", scope: client.scopes.join(" "), }, 201, ); } export async function tokenEndpointFromRequest(request: Request): Promise { const form = await request.formData(); const grantType = stringFormValue(form, "grant_type"); if (grantType === "authorization_code") { return exchangeAuthorizationCode(form); } if (grantType === "refresh_token") { return exchangeRefreshToken(form); } return oauthJsonError("unsupported_grant_type", "Unsupported grant_type.", 400); } export async function revokeEndpointFromRequest(request: Request): Promise { const form = await request.formData(); const token = stringFormValue(form, "token"); if (token) { await revokeMcpOAuthToken(token, getMcpOAuthTokenHashSecret()); } return new Response(null, { status: 200 }); } export function oauthJsonError(error: string, description: string, status = 400): Response { return json({ error, error_description: description }, status); } async function exchangeAuthorizationCode(form: FormData): Promise { const code = requiredFormValue(form, "code"); const clientId = requiredFormValue(form, "client_id"); const redirectUri = requiredFormValue(form, "redirect_uri"); const codeVerifier = requiredFormValue(form, "code_verifier"); const consumed = await consumeMcpOAuthAuthorizationCode(code, getMcpOAuthTokenHashSecret()); if (!consumed || consumed.client.clientId !== clientId || consumed.redirectUri !== redirectUri) { return oauthJsonError("invalid_grant", "Authorization code is invalid, expired, or already used.", 400); } if (!verifyMcpOAuthPkceS256(codeVerifier, consumed.codeChallenge)) { return oauthJsonError("invalid_grant", "PKCE verification failed.", 400); } const pair = await issueMcpOAuthTokenPair({ clientId: consumed.client.id, userId: consumed.userId, tenantId: consumed.tenantId, tenantSlug: consumed.tenantSlug, scopes: consumed.scopes, resource: consumed.resource, secret: getMcpOAuthTokenHashSecret(), }); return tokenResponse(pair.accessToken, pair.refreshToken, pair.accessTokenExpiresIn, consumed.scopes, consumed.resource); } async function exchangeRefreshToken(form: FormData): Promise { const refreshToken = requiredFormValue(form, "refresh_token"); const clientId = requiredFormValue(form, "client_id"); const consumed = await consumeMcpOAuthRefreshToken(refreshToken, getMcpOAuthTokenHashSecret()); if (!consumed || consumed.client.clientId !== clientId) { return oauthJsonError("invalid_grant", "Refresh token is invalid, expired, or already rotated.", 400); } // A deactivated tenant is an operator kill-switch — do not let a rotating // refresh token keep minting fresh access tokens for it indefinitely. const tenant = await getTenantByIdOrSlug(consumed.tenantId); if (!tenant || tenant.deactivatedReason) { return oauthJsonError("invalid_grant", "Tenant is deactivated.", 400); } const pair = await issueMcpOAuthTokenPair({ clientId: consumed.client.id, userId: consumed.userId, tenantId: consumed.tenantId, tenantSlug: consumed.tenantSlug, scopes: consumed.scopes, resource: consumed.resource, secret: getMcpOAuthTokenHashSecret(), }); return tokenResponse(pair.accessToken, pair.refreshToken, pair.accessTokenExpiresIn, consumed.scopes, consumed.resource); } function tokenResponse(accessToken: string, refreshToken: string, expiresIn: number, scopes: readonly string[], resource: string): Response { return json({ access_token: accessToken, token_type: "Bearer", expires_in: expiresIn, refresh_token: refreshToken, scope: scopes.join(" "), resource, }); } function getMcpOAuthTokenHashSecret(): string | undefined { return process.env.MCP_OAUTH_TOKEN_HASH_SECRET ?? process.env.API_KEY_HASH_SECRET; } async function resolveAuthorizeTenant(tenantParam: string | null, userId: string): Promise<{ id: string; slug: string; name: string }> { if (tenantParam) { const tenant = await getTenantByIdOrSlug(tenantParam); if (!tenant) { throw new McpOAuthError("invalid_request", "Unknown tenant."); } const membership = await getTenantMembershipByIds(tenant.id, userId); if (!membership) { throw new McpOAuthError("access_denied", "Current user is not a member of this tenant.", 403); } return { id: tenant.id, slug: tenant.slug, name: tenant.name }; } const tenants = await getTenantsForUser(userId); const tenant = tenants[0]; if (!tenant) { throw new McpOAuthError("access_denied", "Current user has no active tenant.", 403); } return { id: tenant.id, slug: tenant.slug, name: tenant.name }; } function parseScopes(raw: string | null | undefined): string[] { const scopes = (raw ?? DEFAULT_SCOPE) .split(/\s+/) .map((scope) => scope.trim()) .filter(Boolean); return scopes.length > 0 ? [...new Set(scopes)] : [DEFAULT_SCOPE]; } function assertScopesSupported(scopes: readonly string[]) { const unsupported = scopes.filter((scope) => !SUPPORTED_SCOPE_SET.has(scope)); if (unsupported.length > 0) { throw new McpOAuthError("invalid_scope", `Unsupported scope: ${unsupported.join(", ")}`); } } function assertScopesAllowedByClient(scopes: readonly string[], client: McpOAuthClientSummary) { const allowed = new Set(client.scopes); const denied = scopes.filter((scope) => !allowed.has(scope)); if (denied.length > 0) { throw new McpOAuthError("invalid_scope", `Scope not registered for this client: ${denied.join(", ")}`); } } function normalizeRedirectUris(value: unknown): string[] { if (!Array.isArray(value)) { throw new McpOAuthError("invalid_client_metadata", "redirect_uris must be an array."); } const redirectUris = value.filter((item): item is string => typeof item === "string").map((item) => item.trim()).filter(Boolean); if (redirectUris.length === 0) { throw new McpOAuthError("invalid_client_metadata", "At least one redirect_uri is required."); } for (const uri of redirectUris) { assertAllowedRedirectUri(uri); } return [...new Set(redirectUris)]; } function assertAllowedRedirectUri(uri: string) { try { const parsed = new URL(uri); if (parsed.protocol === "https:") { return; } if (parsed.protocol === "http:" && ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname)) { return; } } catch { throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must be an absolute URL."); } throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must use https or localhost http."); } function normalizeGrantTypes(value: unknown): string[] { if (!Array.isArray(value)) { return ["authorization_code", "refresh_token"]; } const requested = value.filter((item): item is string => typeof item === "string"); const allowed = requested.filter((item) => item === "authorization_code" || item === "refresh_token"); return allowed.includes("authorization_code") ? [...new Set(allowed)] : ["authorization_code", "refresh_token"]; } function requiredParam(url: URL, name: string): string { const value = url.searchParams.get(name)?.trim(); if (!value) { throw new McpOAuthError("invalid_request", `${name} is required.`); } return value; } function requiredFormValue(form: FormData, name: string): string { const value = stringFormValue(form, name); if (!value) { throw new McpOAuthError("invalid_request", `${name} is required.`); } return value; } function stringFormValue(form: FormData, name: string): string | null { const value = form.get(name); return typeof value === "string" && value.trim() ? value.trim() : null; } async function readJson(request: Request): Promise> { try { const body = await request.json(); return body && typeof body === "object" && !Array.isArray(body) ? (body as Record) : {}; } catch { throw new McpOAuthError("invalid_client_metadata", "Request body must be JSON."); } } function withOAuthRedirectParams(redirectUri: string, params: { code?: string; error?: string; state?: string }): string { const url = new URL(redirectUri); if (params.code) { url.searchParams.set("code", params.code); } if (params.error) { url.searchParams.set("error", params.error); } if (params.state) { url.searchParams.set("state", params.state); } return url.toString(); } function deriveMcpResourceOrigin(protocol: "http" | "https", webAppHost: string, baseDomain: string): string { if (webAppHost.startsWith("staging-app.")) { return `${protocol}://staging-mcp.${webAppHost.slice("staging-app.".length)}`; } if (webAppHost.startsWith("app.")) { return `${protocol}://mcp.${webAppHost.slice("app.".length)}`; } return `${protocol}://mcp.${baseDomain}`; } function trimTrailingSlash(value: string | null | undefined): string | undefined { const trimmed = value?.trim(); return trimmed ? trimmed.replace(/\/+$/, "") : undefined; } function json(body: unknown, status = 200): Response { return Response.json(body, { status, headers: { "Cache-Control": "no-store", }, }); }