Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,10 +1,11 @@
import type { IncomingMessage } from "node:http";
import { featureKeys, getDefaultProductBlueprint, getProductBlueprint, type ProductBlueprintId, type TenantFeatureOverride } from "@hivegrid/entitlements";
import { findLegacyApiKeyByKey, type LegacyApiKeyReaderClient, type LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
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 { findActiveMcpOAuthAccessToken } from "@hivegrid/db/mcp-oauth.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";
@@ -30,7 +31,7 @@ export async function authenticateMcpRequest(
req: IncomingMessage,
config: McpRuntimeConfig,
client: DbClient = getReadDbClient(),
operationCount = 1,
operationCount = 1
): Promise<McpPrincipal> {
const token = parseBearerToken(getHeader(req, "authorization"));
const authenticateHeader = authenticateChallenge(config);
@@ -40,47 +41,55 @@ export async function authenticateMcpRequest(
});
}
const oauthToken = await findActiveMcpOAuthAccessToken(token, config.oauth.tokenHashSecret);
const oauthToken = await findActiveMcpOAuthAccessTokenWithRlsBootstrap(token, config.oauth.tokenHashSecret, new Date(), client);
if (oauthToken) {
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"`,
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,
});
}
const rateLimit = await checkMcpRateLimit({ apiKeyId: oauthToken.id, tenantId: oauthToken.tenantId, weight: operationCount });
if (!rateLimit.allowed) {
throw new McpHttpError(rateLimit.status, rateLimit.code, rateLimit.message, rateLimit.headers);
}
const [permissions, moduleAllowed, tenant] = await Promise.all([
getPermissionsByUser(client, oauthToken.userId, oauthToken.tenantId),
tenantHasMcpModule(client, oauthToken.tenantId, oauthToken.userId),
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",
id: oauthToken.id,
name: oauthToken.clientName,
},
tenantId: oauthToken.tenantId,
tenantSlug: oauthToken.tenantSlug,
userId: oauthToken.userId,
scopes: normalizeMcpScopes(oauthToken.scopes),
permissions,
};
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 findLegacyApiKeyByKey(token, client as unknown as LegacyApiKeyReaderClient, config.apiKeys.hashSecret, {
const apiKey = await findLegacyApiKeyByKeyWithRlsBootstrap(token, client, config.apiKeys.hashSecret, {
allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback,
});
@@ -95,32 +104,37 @@ export async function authenticateMcpRequest(
});
}
const rateLimit = await checkMcpRateLimit({ apiKeyId: apiKey.id, tenantId: apiKey.tenantId, weight: operationCount });
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);
}
const [permissions, moduleAllowed] = await Promise.all([
getPermissionsByUser(client, apiKey.createdByUserId, apiKey.tenantId),
tenantHasMcpModule(client, apiKey.tenantId, apiKey.createdByUserId),
]);
if (!moduleAllowed) {
throw new McpHttpError(403, "mcp_not_enabled", "MCP is not enabled for this tenant or API-key user.");
}
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",
id: apiKey.id,
name: apiKey.alias,
},
tenantId: apiKey.tenantId,
tenantSlug: apiKey.tenant.slug,
userId: apiKey.createdByUserId,
scopes: normalizeMcpScopes(apiKey.scopes),
permissions,
};
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 {
@@ -147,7 +161,7 @@ async function getPermissionsByUser(client: DbClient, userId: string, tenantId:
return [...names].sort();
}
async function tenantHasMcpModule(client: DbClient, tenantId: string, userId: string): Promise<boolean> {
async function tenantHasMcpModule(client: DbClient, tenantId: string, permissionsPromise: Promise<readonly string[]>): Promise<boolean> {
const [configuration, override, subscription, permissions] = await Promise.all([
client.tenantProductConfiguration.findUnique({
where: { tenantId },
@@ -168,7 +182,7 @@ async function tenantHasMcpModule(client: DbClient, tenantId: string, userId: st
},
},
}),
getPermissionsByUser(client, userId, tenantId),
permissionsPromise,
]);
const blueprintId = (configuration?.blueprintId as ProductBlueprintId | undefined) ?? getDefaultProductBlueprint().id;
@@ -185,8 +199,8 @@ async function tenantHasMcpModule(client: DbClient, tenantId: string, userId: st
}
const hasSubscriptionFeature = Boolean(
subscription?.products?.some((product) =>
product.subscriptionProduct.features.some((feature) => (feature.code ?? feature.name) === featureKeys.mcp && feature.type !== 0 && feature.value !== 0),
),
product.subscriptionProduct.features.some((feature) => (feature.code ?? feature.name) === featureKeys.mcp && feature.type !== 0 && feature.value !== 0)
)
);
return hasSubscriptionFeature && hasRequiredPermission(blueprintFeature.requiresTenantRolePermission, permissions);
}