import type { IncomingMessage } from "node:http"; import { featureKeys, getDefaultProductBlueprint, getProductBlueprint, type ProductBlueprintId, type TenantFeatureOverride } from "@hivegrid/entitlements"; import { findLegacyApiKeyByKeyWithRlsBootstrap, type LegacyApiKeySimple } from "@hivegrid/db/api-keys.server"; import { getReadDbClient } from "@hivegrid/db/client.server"; import type { DbClient } from "@hivegrid/db/client.server"; import { findActiveMcpOAuthAccessTokenWithRlsBootstrap } from "@hivegrid/db/mcp-oauth.server"; import { runWithRlsContext } from "@hivegrid/db/rls-context.server"; import type { McpRuntimeConfig } from "./config.js"; import { McpHttpError } from "./errors.js"; import { getHeader } from "./http.js"; import { checkMcpRateLimit } from "./rate-limit.js"; import { normalizeMcpScopes } from "./scopes.js"; export type McpPrincipal = { apiKey?: LegacyApiKeySimple; credential: { kind: "oauth" | "api_key"; id: string; name: string; }; tenantId: string; tenantSlug: string; userId: string; scopes: readonly string[]; permissions: readonly string[]; }; export async function authenticateMcpRequest( req: IncomingMessage, config: McpRuntimeConfig, client: DbClient = getReadDbClient(), operationCount = 1 ): Promise { const token = parseBearerToken(getHeader(req, "authorization")); const authenticateHeader = authenticateChallenge(config); if (!token) { throw new McpHttpError(401, "missing_token", "MCP requests require a bearer access token.", { "WWW-Authenticate": authenticateHeader, }); } const oauthToken = await findActiveMcpOAuthAccessTokenWithRlsBootstrap(token, config.oauth.tokenHashSecret, new Date(), client); if (oauthToken) { return runWithRlsContext({ tenantId: oauthToken.tenantId, userId: oauthToken.userId }, async () => { if (oauthToken.resource !== config.oauth.resourceUrl) { throw new McpHttpError(401, "invalid_token", "OAuth token audience does not match this MCP resource.", { "WWW-Authenticate": `${authenticateHeader}, error="invalid_token"`, }); } const rateLimit = await checkMcpRateLimit({ apiKeyId: oauthToken.id, tenantId: oauthToken.tenantId, bucketKeySecret: config.oauth.tokenHashSecret, weight: operationCount, }); if (!rateLimit.allowed) { throw new McpHttpError(rateLimit.status, rateLimit.code, rateLimit.message, rateLimit.headers); } const permissionsPromise = getPermissionsByUser(client, oauthToken.userId, oauthToken.tenantId); const [permissions, moduleAllowed, tenant] = await Promise.all([ permissionsPromise, tenantHasMcpModule(client, oauthToken.tenantId, permissionsPromise), client.tenant.findUnique({ where: { id: oauthToken.tenantId }, select: { deactivatedReason: true } }), ]); // Mirror the API-key branch: a deactivated tenant is an operator kill-switch // that must also cut off still-valid OAuth access tokens. if (tenant?.deactivatedReason) { throw new McpHttpError(401, "invalid_token", "Tenant is deactivated.", { "WWW-Authenticate": `${authenticateHeader}, error="invalid_token"`, }); } if (!moduleAllowed) { throw new McpHttpError(403, "mcp_not_enabled", "MCP is not enabled for this tenant or OAuth user."); } return { credential: { kind: "oauth" as const, id: oauthToken.id, name: oauthToken.clientName, }, tenantId: oauthToken.tenantId, tenantSlug: oauthToken.tenantSlug, userId: oauthToken.userId, scopes: normalizeMcpScopes(oauthToken.scopes), permissions, }; }); } const apiKey = await findLegacyApiKeyByKeyWithRlsBootstrap(token, client, config.apiKeys.hashSecret, { allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback, }); if (!apiKey || !apiKey.active || apiKey.tenant.deactivatedReason) { throw new McpHttpError(401, "invalid_token", "API key is invalid or inactive.", { "WWW-Authenticate": `${authenticateHeader}, error="invalid_token"`, }); } if (apiKey.expires && apiKey.expires.getTime() <= Date.now()) { throw new McpHttpError(401, "expired_token", "API key is expired.", { "WWW-Authenticate": `${authenticateHeader}, error="invalid_token"`, }); } const rateLimit = await checkMcpRateLimit({ apiKeyId: apiKey.id, tenantId: apiKey.tenantId, bucketKeySecret: config.oauth.tokenHashSecret, weight: operationCount, }); if (!rateLimit.allowed) { throw new McpHttpError(rateLimit.status, rateLimit.code, rateLimit.message, rateLimit.headers); } return runWithRlsContext({ tenantId: apiKey.tenantId, userId: apiKey.createdByUserId }, async () => { const permissionsPromise = getPermissionsByUser(client, apiKey.createdByUserId, apiKey.tenantId); const [permissions, moduleAllowed] = await Promise.all([permissionsPromise, tenantHasMcpModule(client, apiKey.tenantId, permissionsPromise)]); if (!moduleAllowed) { throw new McpHttpError(403, "mcp_not_enabled", "MCP is not enabled for this tenant or API-key user."); } return { apiKey, credential: { kind: "api_key" as const, id: apiKey.id, name: apiKey.alias, }, tenantId: apiKey.tenantId, tenantSlug: apiKey.tenant.slug, userId: apiKey.createdByUserId, scopes: normalizeMcpScopes(apiKey.scopes), permissions, }; }); } function authenticateChallenge(config: McpRuntimeConfig): string { return `Bearer realm="HiveGrid MCP", resource_metadata="${config.oauth.resourceUrl}/.well-known/oauth-protected-resource"`; } export function parseBearerToken(header: string | undefined): string | null { const match = header?.match(/^Bearer\s+(.+)$/i); const token = match?.[1]?.trim(); return token ? token : null; } async function getPermissionsByUser(client: DbClient, userId: string, tenantId: string): Promise { const userRoles = await client.userRole.findMany({ where: { userId, tenantId }, include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } }, }); const names = new Set(); for (const assignment of userRoles) { for (const rolePermission of assignment.role.permissions) { names.add(rolePermission.permission.name); } } return [...names].sort(); } async function tenantHasMcpModule(client: DbClient, tenantId: string, permissionsPromise: Promise): Promise { const [configuration, override, subscription, permissions] = await Promise.all([ client.tenantProductConfiguration.findUnique({ where: { tenantId }, select: { blueprintId: true }, }), client.tenantFeatureOverride.findUnique({ where: { tenantId_featureKey: { tenantId, featureKey: featureKeys.mcp } }, select: { override: true }, }), client.tenantSubscription.findUnique({ where: { tenantId }, include: { products: { where: { cancelledAt: null, endsAt: null }, include: { subscriptionProduct: { include: { features: true } }, }, }, }, }), permissionsPromise, ]); const blueprintId = (configuration?.blueprintId as ProductBlueprintId | undefined) ?? getDefaultProductBlueprint().id; const blueprintFeature = getProductBlueprint(blueprintId)?.features.find((feature) => feature.featureKey === featureKeys.mcp); if (!blueprintFeature?.defaultEnabled) { return false; } const tenantOverride = normalizeTenantOverride(override?.override); if (tenantOverride === "disabled") { return false; } if (tenantOverride === "enabled" && blueprintFeature.tenantToggleable && hasRequiredPermission(blueprintFeature.requiresTenantRolePermission, permissions)) { return true; } const hasSubscriptionFeature = Boolean( subscription?.products?.some((product) => product.subscriptionProduct.features.some((feature) => (feature.code ?? feature.name) === featureKeys.mcp && feature.type !== 0 && feature.value !== 0) ) ); return hasSubscriptionFeature && hasRequiredPermission(blueprintFeature.requiresTenantRolePermission, permissions); } function hasRequiredPermission(requiredPermission: string | undefined, permissions: readonly string[]): boolean { return !requiredPermission || permissions.includes(requiredPermission); } function normalizeTenantOverride(value: string | null | undefined): TenantFeatureOverride { return value === "enabled" || value === "disabled" || value === "inherit" ? value : "inherit"; }