Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,329 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { getDbClient } from "./client.server.js";
import type { Prisma } from "./prisma-browser.js";
const DEFAULT_TOKEN_HASH_SECRET = "mcp-oauth-token-hash-v1";
const CLIENT_ID_PREFIX = "hgomc_";
const AUTH_CODE_PREFIX = "hgoc_";
const ACCESS_TOKEN_PREFIX = "hgoa_";
const REFRESH_TOKEN_PREFIX = "hgor_";
const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000;
const REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const AUTH_CODE_TTL_MS = 10 * 60 * 1000;
export type McpOAuthClientSummary = {
id: string;
clientId: string;
clientName: string;
redirectUris: string[];
scopes: string[];
active: boolean;
};
export type McpOAuthAuthorizationCodeInput = {
clientId: string;
userId: string;
tenantId: string;
tenantSlug: string;
redirectUri: string;
scopes: readonly string[];
resource: string;
codeChallenge: string;
codeChallengeMethod: "S256";
secret: string | undefined | null;
now?: Date;
};
export type McpOAuthConsumedAuthorizationCode = {
id: string;
client: McpOAuthClientSummary;
userId: string;
tenantId: string;
tenantSlug: string;
redirectUri: string;
scopes: string[];
resource: string;
codeChallenge: string;
codeChallengeMethod: string;
};
export type McpOAuthTokenPairInput = {
clientId: string;
userId: string;
tenantId: string;
tenantSlug: string;
scopes: readonly string[];
resource: string;
secret: string | undefined | null;
now?: Date;
};
export type McpOAuthTokenPair = {
accessToken: string;
refreshToken: string;
accessTokenExpiresIn: number;
refreshTokenExpiresAt: Date;
};
export type McpOAuthAccessTokenPrincipal = {
id: string;
clientId: string;
clientName: string;
userId: string;
tenantId: string;
tenantSlug: string;
scopes: string[];
resource: string;
expiresAt: Date;
};
export type McpOAuthRefreshTokenRecord = {
id: string;
client: McpOAuthClientSummary;
userId: string;
tenantId: string;
tenantSlug: string;
scopes: string[];
resource: string;
expiresAt: Date;
};
export function normalizeMcpOAuthTokenHashSecret(secret: string | undefined | null): string {
const normalized = secret?.trim();
return normalized || DEFAULT_TOKEN_HASH_SECRET;
}
export function hashMcpOAuthToken(token: string, secret: string | undefined | null): string {
return createHmac("sha256", normalizeMcpOAuthTokenHashSecret(secret)).update(token).digest("hex");
}
export function verifyMcpOAuthPkceS256(codeVerifier: string, expectedChallenge: string): boolean {
const challenge = createHashBase64Url(codeVerifier);
return timingSafeStringEqual(challenge, expectedChallenge);
}
export async function registerMcpOAuthClient(input: {
clientName: string;
redirectUris: readonly string[];
scopes: readonly string[];
grantTypes?: readonly string[];
contacts?: readonly string[];
metadata?: Prisma.InputJsonValue;
}): Promise<McpOAuthClientSummary> {
const client = await getDbClient().mcpOAuthClient.create({
data: {
clientId: `${CLIENT_ID_PREFIX}${randomToken(24)}`,
clientName: input.clientName,
redirectUris: [...input.redirectUris] as Prisma.InputJsonArray,
scopes: [...input.scopes] as Prisma.InputJsonArray,
grantTypes: [...(input.grantTypes ?? ["authorization_code", "refresh_token"])] as Prisma.InputJsonArray,
contacts: input.contacts ? ([...input.contacts] as Prisma.InputJsonArray) : undefined,
metadata: input.metadata,
},
});
return toClientSummary(client);
}
export async function findMcpOAuthClient(clientId: string): Promise<McpOAuthClientSummary | null> {
const client = await getDbClient().mcpOAuthClient.findUnique({ where: { clientId } });
return client ? toClientSummary(client) : null;
}
export async function createMcpOAuthAuthorizationCode(input: McpOAuthAuthorizationCodeInput): Promise<{ code: string; expiresAt: Date }> {
const now = input.now ?? new Date();
const code = `${AUTH_CODE_PREFIX}${randomToken(32)}`;
const expiresAt = new Date(now.getTime() + AUTH_CODE_TTL_MS);
await getDbClient().mcpOAuthAuthorizationCode.create({
data: {
clientId: input.clientId,
userId: input.userId,
tenantId: input.tenantId,
tenantSlug: input.tenantSlug,
codeHash: hashMcpOAuthToken(code, input.secret),
redirectUri: input.redirectUri,
scopes: [...input.scopes] as Prisma.InputJsonArray,
resource: input.resource,
codeChallenge: input.codeChallenge,
codeChallengeMethod: input.codeChallengeMethod,
expiresAt,
},
});
return { code, expiresAt };
}
export async function consumeMcpOAuthAuthorizationCode(
code: string,
secret: string | undefined | null,
now = new Date(),
): Promise<McpOAuthConsumedAuthorizationCode | null> {
const db = getDbClient();
const codeHash = hashMcpOAuthToken(code, secret);
const row = await db.mcpOAuthAuthorizationCode.findUnique({
where: { codeHash },
include: { client: true },
});
if (!row || row.consumedAt || row.expiresAt.getTime() <= now.getTime() || !row.client.active) {
return null;
}
const update = await db.mcpOAuthAuthorizationCode.updateMany({
where: { id: row.id, consumedAt: null, expiresAt: { gt: now } },
data: { consumedAt: now },
});
if (update.count !== 1) {
return null;
}
return {
id: row.id,
client: toClientSummary(row.client),
userId: row.userId,
tenantId: row.tenantId,
tenantSlug: row.tenantSlug,
redirectUri: row.redirectUri,
scopes: normalizeStringArray(row.scopes),
resource: row.resource,
codeChallenge: row.codeChallenge,
codeChallengeMethod: row.codeChallengeMethod,
};
}
export async function issueMcpOAuthTokenPair(input: McpOAuthTokenPairInput): Promise<McpOAuthTokenPair> {
const now = input.now ?? new Date();
const accessToken = `${ACCESS_TOKEN_PREFIX}${randomToken(32)}`;
const refreshToken = `${REFRESH_TOKEN_PREFIX}${randomToken(40)}`;
const accessTokenExpiresAt = new Date(now.getTime() + ACCESS_TOKEN_TTL_MS);
const refreshTokenExpiresAt = new Date(now.getTime() + REFRESH_TOKEN_TTL_MS);
const db = getDbClient();
const refreshRow = await db.mcpOAuthRefreshToken.create({
data: {
clientId: input.clientId,
userId: input.userId,
tenantId: input.tenantId,
tenantSlug: input.tenantSlug,
tokenHash: hashMcpOAuthToken(refreshToken, input.secret),
scopes: [...input.scopes] as Prisma.InputJsonArray,
resource: input.resource,
expiresAt: refreshTokenExpiresAt,
},
});
await db.mcpOAuthAccessToken.create({
data: {
clientId: input.clientId,
userId: input.userId,
tenantId: input.tenantId,
tenantSlug: input.tenantSlug,
tokenHash: hashMcpOAuthToken(accessToken, input.secret),
scopes: [...input.scopes] as Prisma.InputJsonArray,
resource: input.resource,
expiresAt: accessTokenExpiresAt,
refreshTokenId: refreshRow.id,
},
});
return {
accessToken,
refreshToken,
accessTokenExpiresIn: Math.floor((accessTokenExpiresAt.getTime() - now.getTime()) / 1000),
refreshTokenExpiresAt,
};
}
export async function consumeMcpOAuthRefreshToken(
token: string,
secret: string | undefined | null,
now = new Date(),
): Promise<McpOAuthRefreshTokenRecord | null> {
const db = getDbClient();
const tokenHash = hashMcpOAuthToken(token, secret);
const row = await db.mcpOAuthRefreshToken.findUnique({ where: { tokenHash }, include: { client: true } });
if (!row || row.revokedAt || row.rotatedAt || row.expiresAt.getTime() <= now.getTime() || !row.client.active) {
return null;
}
const update = await db.mcpOAuthRefreshToken.updateMany({
where: { id: row.id, revokedAt: null, rotatedAt: null, expiresAt: { gt: now } },
data: { rotatedAt: now },
});
if (update.count !== 1) {
return null;
}
return {
id: row.id,
client: toClientSummary(row.client),
userId: row.userId,
tenantId: row.tenantId,
tenantSlug: row.tenantSlug,
scopes: normalizeStringArray(row.scopes),
resource: row.resource,
expiresAt: row.expiresAt,
};
}
export async function findActiveMcpOAuthAccessToken(
token: string,
secret: string | undefined | null,
now = new Date(),
): Promise<McpOAuthAccessTokenPrincipal | null> {
const row = await getDbClient().mcpOAuthAccessToken.findUnique({
where: { tokenHash: hashMcpOAuthToken(token, secret) },
include: { client: true },
});
if (!row || row.revokedAt || row.expiresAt.getTime() <= now.getTime() || !row.client.active) {
return null;
}
return {
id: row.id,
clientId: row.client.clientId,
clientName: row.client.clientName,
userId: row.userId,
tenantId: row.tenantId,
tenantSlug: row.tenantSlug,
scopes: normalizeStringArray(row.scopes),
resource: row.resource,
expiresAt: row.expiresAt,
};
}
export async function revokeMcpOAuthToken(token: string, secret: string | undefined | null, now = new Date()): Promise<boolean> {
const tokenHash = hashMcpOAuthToken(token, secret);
const db = getDbClient();
const [access, refresh] = await Promise.all([
db.mcpOAuthAccessToken.updateMany({ where: { tokenHash, revokedAt: null }, data: { revokedAt: now } }),
db.mcpOAuthRefreshToken.updateMany({ where: { tokenHash, revokedAt: null }, data: { revokedAt: now } }),
]);
return access.count + refresh.count > 0;
}
function toClientSummary(client: {
id: string;
clientId: string;
clientName: string;
redirectUris: Prisma.JsonValue;
scopes: Prisma.JsonValue;
active: boolean;
}): McpOAuthClientSummary {
return {
id: client.id,
clientId: client.clientId,
clientName: client.clientName,
redirectUris: normalizeStringArray(client.redirectUris),
scopes: normalizeStringArray(client.scopes),
active: client.active,
};
}
function normalizeStringArray(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string" && item.length > 0) : [];
}
function randomToken(bytes: number): string {
return randomBytes(bytes).toString("base64url");
}
function createHashBase64Url(value: string): string {
return createHash("sha256").update(value).digest().toString("base64url");
}
function timingSafeStringEqual(left: string, right: string): boolean {
const leftBuffer = Buffer.from(left);
const rightBuffer = Buffer.from(right);
return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);
}