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,18 +1,19 @@
import { redirect } from "react-router";
import {
consumeMcpOAuthAuthorizationCode,
consumeMcpOAuthRefreshToken,
consumeMcpOAuthAuthorizationCodeWithRlsBootstrap,
consumeMcpOAuthRefreshTokenWithRlsBootstrap,
createMcpOAuthAuthorizationCode,
findMcpOAuthClient,
issueMcpOAuthTokenPair,
registerMcpOAuthClient,
revokeMcpOAuthToken,
verifyMcpOAuthPkceS256,
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 { getTenantByIdOrSlug, getTenantMembershipByIds, getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
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",
@@ -23,11 +24,28 @@ export const MCP_OAUTH_SUPPORTED_SCOPES = [
"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";
@@ -141,6 +159,7 @@ export async function resolveAuthorizeRequest(url: URL, userId: string): Promise
}
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"]) {
@@ -154,35 +173,64 @@ export async function approveAuthorizeRequest(request: Request, userId: string):
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(),
});
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 scopes = parseScopes(typeof body.scope === "string" ? body.scope : undefined);
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: typeof body.client_name === "string" && body.client_name.trim() ? body.client_name.trim() : "MCP Client",
clientName,
redirectUris,
scopes,
grantTypes,
contacts: Array.isArray(body.contacts) ? body.contacts.filter((item): item is string => typeof item === "string") : undefined,
metadata: body as Prisma.InputJsonObject,
contacts,
metadata,
});
return json(
{
@@ -195,27 +243,49 @@ export async function registerOAuthClientFromRequest(request: Request): Promise<
token_endpoint_auth_method: "none",
scope: client.scopes.join(" "),
},
201,
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);
return exchangeAuthorizationCode(form, tokenHashSecret);
}
if (grantType === "refresh_token") {
return exchangeRefreshToken(form);
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 revokeMcpOAuthToken(token, getMcpOAuthTokenHashSecret());
await revokeMcpOAuthTokenWithRlsBootstrap(token, tokenHashSecret);
}
return new Response(null, { status: 200 });
}
@@ -224,52 +294,69 @@ export function oauthJsonError(error: string, description: string, status = 400)
return json({ error, error_description: description }, status);
}
async function exchangeAuthorizationCode(form: FormData): Promise<Response> {
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 consumeMcpOAuthAuthorizationCode(code, getMcpOAuthTokenHashSecret());
if (!consumed || consumed.client.clientId !== clientId || consumed.redirectUri !== redirectUri) {
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);
}
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(),
});
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): Promise<Response> {
async function exchangeRefreshToken(form: FormData, tokenHashSecret: string): Promise<Response> {
const refreshToken = requiredFormValue(form, "refresh_token");
const clientId = requiredFormValue(form, "client_id");
const consumed = await consumeMcpOAuthRefreshToken(refreshToken, getMcpOAuthTokenHashSecret());
if (!consumed || consumed.client.clientId !== clientId) {
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 getTenantByIdOrSlug(consumed.tenantId);
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 issueMcpOAuthTokenPair({
clientId: consumed.client.id,
userId: consumed.userId,
tenantId: consumed.tenantId,
tenantSlug: consumed.tenantSlug,
scopes: consumed.scopes,
resource: consumed.resource,
secret: getMcpOAuthTokenHashSecret(),
});
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);
}
@@ -284,8 +371,14 @@ function tokenResponse(accessToken: string, refreshToken: string, expiresIn: num
});
}
function getMcpOAuthTokenHashSecret(): string | undefined {
return process.env.MCP_OAUTH_TOKEN_HASH_SECRET ?? process.env.API_KEY_HASH_SECRET;
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 }> {
@@ -301,8 +394,19 @@ async function resolveAuthorizeTenant(tenantParam: string | null, userId: string
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);
const tenant = tenants[0];
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);
}
@@ -336,7 +440,10 @@ 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 (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.");
}
@@ -347,17 +454,24 @@ function normalizeRedirectUris(value: unknown): string[] {
}
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 {
const parsed = new URL(uri);
if (parsed.protocol === "https:") {
return;
}
if (parsed.protocol === "http:" && ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname)) {
return;
}
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.");
}
@@ -365,11 +479,77 @@ 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");
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) {