Files

620 lines
23 KiB
TypeScript

import { redirect } from "react-router";
import {
consumeMcpOAuthAuthorizationCodeWithRlsBootstrap,
consumeMcpOAuthRefreshTokenWithRlsBootstrap,
createMcpOAuthAuthorizationCode,
findMcpOAuthClient,
issueMcpOAuthTokenPair,
registerMcpOAuthClient,
revokeMcpOAuthTokenWithRlsBootstrap,
type McpOAuthClientSummary,
} from "@hivegrid/db/mcp-oauth.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { getAuthUserWithoutPasswordById, getTenantByIdOrSlug, getTenantMembershipByIds, getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
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:read",
"mcp:activity:write",
"mcp:task:read",
"mcp:task:write",
] as const;
const DEFAULT_SCOPE = "mcp:read";
const SUPPORTED_SCOPE_SET = new Set<string>(MCP_OAUTH_SUPPORTED_SCOPES);
const OAUTH_REGISTRATION_RATE_LIMIT = 60;
const OAUTH_REGISTRATION_RATE_WINDOW_MS = 60 * 60 * 1000;
const OAUTH_TOKEN_RATE_LIMIT = 120;
const OAUTH_TOKEN_RATE_WINDOW_MS = 60 * 1000;
const OAUTH_REVOKE_RATE_LIMIT = 120;
const OAUTH_REVOKE_RATE_WINDOW_MS = 60 * 1000;
const OAUTH_CLIENT_NAME_MAX_LENGTH = 200;
const OAUTH_REDIRECT_URI_MAX_COUNT = 10;
const OAUTH_REDIRECT_URI_MAX_LENGTH = 2_048;
const OAUTH_CONTACT_MAX_COUNT = 10;
const OAUTH_CONTACT_MAX_LENGTH = 320;
const OAUTH_SCOPE_MAX_LENGTH = 1_024;
const OAUTH_METADATA_STRING_MAX_LENGTH = 2_048;
const OAUTH_METADATA_STRING_KEYS = ["client_uri", "logo_uri", "tos_uri", "policy_uri", "software_id", "software_version"] as const;
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<McpOAuthAuthorizeRequest> {
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<Response> {
const tokenHashSecret = resolveMcpOAuthTokenHashSecret();
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 runWithRlsContext({ tenantId: resolved.tenant.id, userId }, () =>
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: tokenHashSecret,
})
);
throw redirect(withOAuthRedirectParams(resolved.redirectUri, { code, state: resolved.state }));
}
export async function registerOAuthClientFromRequest(request: Request): Promise<Response> {
const rateLimit = await checkAuthRateLimit({
request,
action: "oauth-register",
limit: OAUTH_REGISTRATION_RATE_LIMIT,
windowMs: OAUTH_REGISTRATION_RATE_WINDOW_MS,
});
if (!rateLimit.allowed) {
return new Response(JSON.stringify({ error: "rate_limited", error_description: "OAuth client registration rate limit exceeded." }), {
status: 429,
headers: {
"Cache-Control": "no-store",
"Content-Type": "application/json; charset=utf-8",
"Retry-After": String(rateLimit.retryAfterSeconds),
},
});
}
const body = await readJson(request);
const redirectUris = normalizeRedirectUris(body.redirect_uris);
const rawScope = optionalBoundedString(body.scope, "scope", OAUTH_SCOPE_MAX_LENGTH);
const scopes = parseScopes(rawScope);
assertScopesSupported(scopes);
const grantTypes = normalizeGrantTypes(body.grant_types);
const clientName = normalizeClientName(body.client_name);
const contacts = normalizeContacts(body.contacts);
const metadata = normalizeClientMetadata(body, {
clientName,
contacts,
grantTypes,
redirectUris,
scopes,
});
const client = await registerMcpOAuthClient({
clientName,
redirectUris,
scopes,
grantTypes,
contacts,
metadata,
});
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<Response> {
const rateLimit = await checkAuthRateLimit({
request,
action: "oauth-token",
limit: OAUTH_TOKEN_RATE_LIMIT,
windowMs: OAUTH_TOKEN_RATE_WINDOW_MS,
});
if (!rateLimit.allowed) {
return oauthRateLimitedResponse(rateLimit.retryAfterSeconds);
}
const tokenHashSecret = resolveMcpOAuthTokenHashSecret();
const form = await request.formData();
const grantType = stringFormValue(form, "grant_type");
if (grantType === "authorization_code") {
return exchangeAuthorizationCode(form, tokenHashSecret);
}
if (grantType === "refresh_token") {
return exchangeRefreshToken(form, tokenHashSecret);
}
return oauthJsonError("unsupported_grant_type", "Unsupported grant_type.", 400);
}
export async function revokeEndpointFromRequest(request: Request): Promise<Response> {
const rateLimit = await checkAuthRateLimit({
request,
action: "oauth-revoke",
limit: OAUTH_REVOKE_RATE_LIMIT,
windowMs: OAUTH_REVOKE_RATE_WINDOW_MS,
});
if (!rateLimit.allowed) {
return oauthRateLimitedResponse(rateLimit.retryAfterSeconds);
}
const tokenHashSecret = resolveMcpOAuthTokenHashSecret();
const form = await request.formData();
const token = stringFormValue(form, "token");
if (token) {
await revokeMcpOAuthTokenWithRlsBootstrap(token, tokenHashSecret);
}
return new Response(null, { status: 200 });
}
export function oauthJsonError(error: string, description: string, status = 400): Response {
return json({ error, error_description: description }, status);
}
function oauthRateLimitedResponse(retryAfterSeconds: number): Response {
const response = oauthJsonError("rate_limited", "OAuth endpoint rate limit exceeded.", 429);
response.headers.set("Retry-After", String(retryAfterSeconds));
return response;
}
async function exchangeAuthorizationCode(form: FormData, tokenHashSecret: string): Promise<Response> {
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 consumeMcpOAuthAuthorizationCodeWithRlsBootstrap({
code,
secret: tokenHashSecret,
clientId,
redirectUri,
codeVerifier,
});
if (!consumed) {
return oauthJsonError("invalid_grant", "Authorization code is invalid, expired, or already used.", 400);
}
const pair = await runWithRlsContext({ tenantId: consumed.tenantId, userId: consumed.userId }, () =>
issueMcpOAuthTokenPair({
clientId: consumed.client.id,
userId: consumed.userId,
tenantId: consumed.tenantId,
tenantSlug: consumed.tenantSlug,
scopes: consumed.scopes,
resource: consumed.resource,
secret: tokenHashSecret,
})
);
return tokenResponse(pair.accessToken, pair.refreshToken, pair.accessTokenExpiresIn, consumed.scopes, consumed.resource);
}
async function exchangeRefreshToken(form: FormData, tokenHashSecret: string): Promise<Response> {
const refreshToken = requiredFormValue(form, "refresh_token");
const clientId = requiredFormValue(form, "client_id");
const consumed = await consumeMcpOAuthRefreshTokenWithRlsBootstrap({
token: refreshToken,
secret: tokenHashSecret,
clientId,
});
if (!consumed) {
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 runWithRlsContext({ tenantId: consumed.tenantId, userId: consumed.userId }, () => getTenantByIdOrSlug(consumed.tenantId));
if (!tenant || tenant.deactivatedReason) {
return oauthJsonError("invalid_grant", "Tenant is deactivated.", 400);
}
const pair = await runWithRlsContext({ tenantId: consumed.tenantId, userId: consumed.userId }, () =>
issueMcpOAuthTokenPair({
clientId: consumed.client.id,
userId: consumed.userId,
tenantId: consumed.tenantId,
tenantSlug: consumed.tenantSlug,
scopes: consumed.scopes,
resource: consumed.resource,
secret: tokenHashSecret,
})
);
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,
});
}
export function resolveMcpOAuthTokenHashSecret(
env: Partial<Record<"MCP_OAUTH_TOKEN_HASH_SECRET" | "API_KEY_HASH_SECRET", string | undefined>> = process.env
): string {
const secret = (env.MCP_OAUTH_TOKEN_HASH_SECRET ?? env.API_KEY_HASH_SECRET)?.trim();
if (!secret || Buffer.byteLength(secret, "utf8") < 32) {
throw new McpOAuthError("server_error", "OAuth token protection is unavailable.", 503);
}
return 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 };
}
// Claude, ChatGPT and Cursor build the authorize URL from discovery metadata,
// so they never send a `tenant`. Falling back to the first membership would
// silently connect a multi-tenant user to the wrong workspace, so prefer the
// tenant they are actually working in: `User.defaultTenantId` is rewritten on
// every tenant page view (see `app.$tenant.tsx`) and is the closest thing to
// "where the user is right now". Membership is re-checked either way.
const tenants = await getTenantsForUser(userId);
if (tenants.length === 0) {
throw new McpOAuthError("access_denied", "Current user has no active tenant.", 403);
}
const activeTenantId = (await getAuthUserWithoutPasswordById(userId))?.defaultTenantId ?? null;
const tenant = tenants.find((candidate) => candidate.id === activeTenantId) ?? 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.");
}
if (value.length > OAUTH_REDIRECT_URI_MAX_COUNT || value.some((item) => typeof item !== "string")) {
throw new McpOAuthError("invalid_client_metadata", `redirect_uris must contain at most ${OAUTH_REDIRECT_URI_MAX_COUNT} strings.`);
}
const redirectUris = value.map((item) => (item as string).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) {
if (uri.length > OAUTH_REDIRECT_URI_MAX_LENGTH) {
throw new McpOAuthError("invalid_redirect_uri", `redirect_uri must not exceed ${OAUTH_REDIRECT_URI_MAX_LENGTH} characters.`);
}
let parsed: URL;
try {
parsed = new URL(uri);
} catch {
throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must be an absolute URL.");
}
if (parsed.username || parsed.password || parsed.hash) {
throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must not contain credentials or a fragment.");
}
if (parsed.protocol === "https:") {
return;
}
if (parsed.protocol === "http:" && ["localhost", "127.0.0.1", "::1", "[::1]"].includes(parsed.hostname)) {
return;
}
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"];
}
if (value.length > 2 || value.some((item) => typeof item !== "string")) {
throw new McpOAuthError("invalid_client_metadata", "grant_types must contain at most two strings.");
}
const requested = value as string[];
if (requested.some((item) => item !== "authorization_code" && item !== "refresh_token")) {
throw new McpOAuthError("invalid_client_metadata", "grant_types contains an unsupported grant.");
}
const allowed = requested.filter((item) => item === "authorization_code" || item === "refresh_token");
return allowed.includes("authorization_code") ? [...new Set(allowed)] : ["authorization_code", "refresh_token"];
}
function normalizeClientName(value: unknown): string {
if (value === undefined || value === null || value === "") return "MCP Client";
if (typeof value !== "string") {
throw new McpOAuthError("invalid_client_metadata", "client_name must be a string.");
}
const name = value.trim();
if (!name || name.length > OAUTH_CLIENT_NAME_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(name)) {
throw new McpOAuthError("invalid_client_metadata", `client_name must contain 1-${OAUTH_CLIENT_NAME_MAX_LENGTH} printable characters.`);
}
return name;
}
function normalizeContacts(value: unknown): string[] | undefined {
if (value === undefined) return undefined;
if (!Array.isArray(value) || value.length > OAUTH_CONTACT_MAX_COUNT || value.some((item) => typeof item !== "string")) {
throw new McpOAuthError("invalid_client_metadata", `contacts must contain at most ${OAUTH_CONTACT_MAX_COUNT} strings.`);
}
const contacts = value.map((item) => (item as string).trim()).filter(Boolean);
if (contacts.some((contact) => contact.length > OAUTH_CONTACT_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(contact))) {
throw new McpOAuthError("invalid_client_metadata", `contacts entries must not exceed ${OAUTH_CONTACT_MAX_LENGTH} printable characters.`);
}
return [...new Set(contacts)];
}
function optionalBoundedString(value: unknown, field: string, maxLength: number): string | undefined {
if (value === undefined || value === null || value === "") return undefined;
if (typeof value !== "string" || value.length > maxLength || /[\u0000-\u001f\u007f]/u.test(value)) {
throw new McpOAuthError("invalid_client_metadata", `${field} must be a printable string of at most ${maxLength} characters.`);
}
return value;
}
function normalizeClientMetadata(
body: Record<string, unknown>,
normalized: {
clientName: string;
contacts?: string[];
grantTypes: string[];
redirectUris: string[];
scopes: string[];
}
): Prisma.InputJsonObject {
const optionalMetadata = Object.fromEntries(
OAUTH_METADATA_STRING_KEYS.flatMap((key) => {
const value = optionalBoundedString(body[key], key, OAUTH_METADATA_STRING_MAX_LENGTH);
return value === undefined ? [] : [[key, value]];
})
) as Prisma.InputJsonObject;
return {
client_name: normalized.clientName,
redirect_uris: normalized.redirectUris,
scope: normalized.scopes.join(" "),
grant_types: normalized.grantTypes,
response_types: ["code"],
token_endpoint_auth_method: "none",
...(normalized.contacts ? { contacts: normalized.contacts } : {}),
...optionalMetadata,
};
}
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<Record<string, unknown>> {
try {
const body = await request.json();
return body && typeof body === "object" && !Array.isArray(body) ? (body as Record<string, unknown>) : {};
} 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",
},
});
}