415 lines
14 KiB
TypeScript
415 lines
14 KiB
TypeScript
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
|
|
import { Prisma } from "../generated/prisma/client/client.js";
|
|
import { getDbClient } from "./client.server.js";
|
|
import { runWithRlsContext } from "./rls-context.server.js";
|
|
import {
|
|
resolveMcpOAuthAccessTokenRlsIdentity,
|
|
resolveMcpOAuthAuthorizationCodeRlsIdentity,
|
|
resolveMcpOAuthRefreshTokenRlsIdentity,
|
|
} from "./rls-resolvers.server.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 ConsumeMcpOAuthAuthorizationCodeInput = {
|
|
code: string;
|
|
secret: string | undefined | null;
|
|
clientId: string;
|
|
redirectUri: string;
|
|
codeVerifier: string;
|
|
now?: Date;
|
|
};
|
|
|
|
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 type ConsumeMcpOAuthRefreshTokenInput = {
|
|
token: string;
|
|
secret: string | undefined | null;
|
|
clientId: string;
|
|
now?: 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 id = randomUUID();
|
|
const clientId = `${CLIENT_ID_PREFIX}${randomToken(24)}`;
|
|
const redirectUris = JSON.stringify([...input.redirectUris]);
|
|
const grantTypes = JSON.stringify([...(input.grantTypes ?? ["authorization_code", "refresh_token"])]);
|
|
const scopes = JSON.stringify([...input.scopes]);
|
|
const contacts = input.contacts ? JSON.stringify([...input.contacts]) : null;
|
|
const metadata = input.metadata === undefined ? null : JSON.stringify(input.metadata);
|
|
const clients = await getDbClient().$queryRaw<
|
|
Array<{
|
|
id: string;
|
|
clientId: string;
|
|
clientName: string;
|
|
redirectUris: Prisma.JsonValue;
|
|
scopes: Prisma.JsonValue;
|
|
active: boolean;
|
|
}>
|
|
>(Prisma.sql`
|
|
SELECT * FROM public.hivegrid_register_mcp_oauth_client(
|
|
${id}, ${clientId}, ${input.clientName}, ${redirectUris}::jsonb,
|
|
${grantTypes}::jsonb, ${scopes}::jsonb, ${contacts}::jsonb, ${metadata}::jsonb
|
|
)
|
|
`);
|
|
if (clients.length !== 1) {
|
|
throw new Error("MCP OAuth client registration capability did not return exactly one row");
|
|
}
|
|
const client = clients[0];
|
|
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(input: ConsumeMcpOAuthAuthorizationCodeInput): Promise<McpOAuthConsumedAuthorizationCode | null> {
|
|
const now = input.now ?? new Date();
|
|
const db = getDbClient();
|
|
const codeHash = hashMcpOAuthToken(input.code, input.secret);
|
|
const row = await db.mcpOAuthAuthorizationCode.findUnique({
|
|
where: { codeHash },
|
|
include: { client: true },
|
|
});
|
|
if (
|
|
!row ||
|
|
row.consumedAt ||
|
|
row.expiresAt.getTime() <= now.getTime() ||
|
|
!row.client.active ||
|
|
row.client.clientId !== input.clientId ||
|
|
row.redirectUri !== input.redirectUri ||
|
|
!verifyMcpOAuthPkceS256(input.codeVerifier, row.codeChallenge)
|
|
) {
|
|
return null;
|
|
}
|
|
const update = await db.mcpOAuthAuthorizationCode.updateMany({
|
|
where: {
|
|
id: row.id,
|
|
clientId: row.clientId,
|
|
redirectUri: input.redirectUri,
|
|
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(input: ConsumeMcpOAuthRefreshTokenInput): Promise<McpOAuthRefreshTokenRecord | null> {
|
|
const now = input.now ?? new Date();
|
|
const db = getDbClient();
|
|
const tokenHash = hashMcpOAuthToken(input.token, input.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 || row.client.clientId !== input.clientId) {
|
|
return null;
|
|
}
|
|
const update = await db.mcpOAuthRefreshToken.updateMany({
|
|
where: { id: row.id, clientId: row.clientId, 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(),
|
|
client = getDbClient()
|
|
): Promise<McpOAuthAccessTokenPrincipal | null> {
|
|
const row = await client.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,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Resolves the opaque credential to its tenant without exposing the token row,
|
|
* then performs the complete lookup under the matching RLS identity.
|
|
*/
|
|
export async function findActiveMcpOAuthAccessTokenWithRlsBootstrap(
|
|
token: string,
|
|
secret: string | undefined | null,
|
|
now = new Date(),
|
|
client = getDbClient()
|
|
): Promise<McpOAuthAccessTokenPrincipal | null> {
|
|
const tokenHash = hashMcpOAuthToken(token, secret);
|
|
const identity = await resolveMcpOAuthAccessTokenRlsIdentity(tokenHash, client);
|
|
if (!identity) return null;
|
|
return runWithRlsContext({ tenantId: identity.tenantId, userId: identity.userId }, () => findActiveMcpOAuthAccessToken(token, secret, now, client));
|
|
}
|
|
|
|
export async function consumeMcpOAuthAuthorizationCodeWithRlsBootstrap(
|
|
input: ConsumeMcpOAuthAuthorizationCodeInput
|
|
): Promise<McpOAuthConsumedAuthorizationCode | null> {
|
|
const codeHash = hashMcpOAuthToken(input.code, input.secret);
|
|
const identity = await resolveMcpOAuthAuthorizationCodeRlsIdentity(codeHash);
|
|
if (!identity) return null;
|
|
return runWithRlsContext({ tenantId: identity.tenantId, userId: identity.userId }, () => consumeMcpOAuthAuthorizationCode(input));
|
|
}
|
|
|
|
export async function consumeMcpOAuthRefreshTokenWithRlsBootstrap(input: ConsumeMcpOAuthRefreshTokenInput): Promise<McpOAuthRefreshTokenRecord | null> {
|
|
const tokenHash = hashMcpOAuthToken(input.token, input.secret);
|
|
const identity = await resolveMcpOAuthRefreshTokenRlsIdentity(tokenHash);
|
|
if (!identity) return null;
|
|
return runWithRlsContext({ tenantId: identity.tenantId, userId: identity.userId }, () => consumeMcpOAuthRefreshToken(input));
|
|
}
|
|
|
|
export async function revokeMcpOAuthTokenWithRlsBootstrap(token: string, secret: string | undefined | null, now = new Date()): Promise<boolean> {
|
|
const tokenHash = hashMcpOAuthToken(token, secret);
|
|
const identity = (await resolveMcpOAuthAccessTokenRlsIdentity(tokenHash)) ?? (await resolveMcpOAuthRefreshTokenRlsIdentity(tokenHash));
|
|
if (!identity) return false;
|
|
return runWithRlsContext({ tenantId: identity.tenantId, userId: identity.userId }, () => revokeMcpOAuthToken(token, secret, now));
|
|
}
|
|
|
|
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);
|
|
}
|