Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/services/mcp/connect.server.ts
T

143 lines
5.9 KiB
TypeScript

import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { createAuditEventInExistingTransaction } from "@hivegrid/db/audit-events.server";
import { featureKeys } from "@hivegrid/entitlements";
import { buildMcpConnectVM, type McpConnectTokenInput, type McpConnectVM } from "@hivegrid/view-models";
import type { Params } from "react-router";
import { getMcpOAuthPublicUrls } from "~/services/mcp/oauth.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
/**
* Server side of the app-shell "Mit KI verbinden" dialog.
*
* The MCP runtime lives in its own container on its own host and speaks OAuth
* 2.1 with dynamic client registration, so a client (Claude, ChatGPT, Cursor)
* onboards itself: it discovers the metadata, registers, and sends the user
* through our consent screen. This service therefore never mints credentials —
* it hands out the connector URL, lists what the current user already
* connected, and lets them cut a connection.
*/
export const MCP_MODULE_KEY = featureKeys.mcp;
export type McpConnectContext = {
readonly tenantId: string;
readonly tenantSlug: string;
readonly tenantName: string;
readonly userId: string;
};
export async function loadMcpConnectContext({ request, params }: { request: Request; params: Params }): Promise<McpConnectContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
// A tenant without the MCP module must not even learn that the connector
// exists — 404, not 403 (Bauprinzip A.5.3).
if (!(await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: MCP_MODULE_KEY }))) {
throw new CatalogError(foundationErrors.notFound, { module: MCP_MODULE_KEY });
}
const tenant = await withTenantRLS(tenantId, (tx) => tx.tenant.findUnique({ where: { id: tenantId }, select: { name: true, slug: true } }));
if (!tenant) {
throw new CatalogError(foundationErrors.notFound);
}
return { tenantId, tenantSlug: tenant.slug, tenantName: tenant.name, userId: userInfo.userId };
}
export async function loadMcpConnectVM(ctx: McpConnectContext, now: Date = new Date()): Promise<McpConnectVM> {
const tokens = await withTenantRLS(ctx.tenantId, (tx) =>
tx.mcpOAuthAccessToken.findMany({
// Own connections only: an access token is bound to the user who walked
// through consent, so nobody inspects a colleague's AI clients here.
where: { tenantId: ctx.tenantId, userId: ctx.userId, revokedAt: null },
select: { clientId: true, scopes: true, createdAt: true, expiresAt: true, client: { select: { clientName: true } } },
orderBy: { createdAt: "desc" },
take: 200,
})
);
return buildMcpConnectVM({
connectorUrl: getMcpOAuthPublicUrls().resource,
tenantName: ctx.tenantName,
appName: loadRequiredWebConfig().appName,
docsHref: null,
canRevoke: true,
nowIso: now.toISOString(),
tokens: tokens.map(
(token): McpConnectTokenInput => ({
clientId: token.clientId,
clientName: token.client?.clientName ?? "",
scopes: normalizeScopeJson(token.scopes),
createdAtIso: token.createdAt.toISOString(),
expiresAtIso: token.expiresAt.toISOString(),
revoked: false,
})
),
});
}
export type RevokeMcpConnectionResult = { readonly revokedTokens: number };
/**
* Cutting a connection revokes both halves: leaving the refresh token alive
* would let the client mint a fresh access token minutes later.
*/
export async function revokeMcpConnection(ctx: McpConnectContext, clientId: string, now: Date = new Date()): Promise<RevokeMcpConnectionResult> {
const trimmed = clientId.trim();
if (!trimmed) {
throw new CatalogError(foundationErrors.notFound);
}
return withTenantRLS(ctx.tenantId, async (tx) => {
const scope = { clientId: trimmed, tenantId: ctx.tenantId, userId: ctx.userId, revokedAt: null } as const;
const owned = await tx.mcpOAuthAccessToken.count({ where: scope });
const ownedRefresh = await tx.mcpOAuthRefreshToken.count({ where: scope });
if (owned === 0 && ownedRefresh === 0) {
throw new CatalogError(foundationErrors.notFound);
}
const [access] = await Promise.all([
tx.mcpOAuthAccessToken.updateMany({ where: scope, data: { revokedAt: now } }),
tx.mcpOAuthRefreshToken.updateMany({ where: scope, data: { revokedAt: now } }),
]);
// Same transaction as the revoke itself: a connection must never appear cut
// without the audit record that says who cut it.
await createAuditEventInExistingTransaction(
{
tenantId: ctx.tenantId,
actorId: ctx.userId,
actorType: "user",
action: "mcp.connection.revoke",
targetType: "McpOAuthClient",
targetId: trimmed,
sourceModule: "mcp",
outcome: "success",
dataSensitivity: "internal",
metadata: { revokedAccessTokens: access.count },
},
// Same structural cast the other in-transaction audit writers use: the
// Prisma transaction client is wider than the writer's minimal contract.
tx as unknown as Parameters<typeof createAuditEventInExistingTransaction>[1]
);
return { revokedTokens: access.count };
});
}
function normalizeScopeJson(value: unknown): string[] {
if (Array.isArray(value)) {
return value.filter((entry): entry is string => typeof entry === "string");
}
if (typeof value === "string") {
return value.split(/\s+/).filter(Boolean);
}
return [];
}