Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

11.3 KB
Raw Blame
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import {
  isJsonContentType,
  isLegacyRequest,
} from "@modelcontextprotocol/server";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { auth } from "../auth";
import { apiRouter, createRoute, jsonResponse } from "../openapi";
import { type BanState, isBanActive } from "../utils/user-ban";
import {
  beginMcpAuthorization,
  decideMcpAuthorizationRequest,
  getMcpAuthorizationRequest,
  registerMcpClient,
} from "./controllers/oauth-consent";
import { createModernMcpHandler } from "./modern";
import { exchangeCode } from "./oauth";
import {
  MCP_BODY_BYTES,
  mcpRequestBounds,
  oauthRequestBounds,
} from "./request-bounds";
import {
  authorizationDecisionResponseSchema,
  authorizationDecisionSchema,
  authorizationQuerySchema,
  authorizationRequestParamSchema,
  authorizationRequestResponseSchema,
  clientRegistrationResponseSchema,
  clientRegistrationSchema,
  oauthErrorSchema,
} from "./schemas";
import { createMcpServerForUser } from "./legacy-server";

const publicApiUrl = (process.env.KANEO_API_URL || "http://localhost:1337")
  .replace(/\/api\/?$/, "")
  .replace(/\/+$/, "");
const internalApiUrl = (
  process.env.KANEO_INTERNAL_API_URL || "http://127.0.0.1:1337"
)
  .replace(/\/api\/?$/, "")
  .replace(/\/+$/, "");

async function validateBearerToken(
  req: Request,
): Promise<{ userId: string; token: string } | null> {
  const authHeader = req.headers.get("authorization");
  if (!authHeader) return null;
  const match = authHeader.match(/^Bearer\s+(\S+)$/i);
  if (!match?.[1]) return null;
  const token = match[1];

  const headers = new Headers();
  headers.set("authorization", `Bearer ${token}`);
  const session = await auth.api.getSession({ headers });

  if (!session?.user?.id) return null;
  if (isBanActive(session.user as BanState)) return null;
  return { userId: session.user.id, token };
}

const mcp = apiRouter();
for (const path of [
  "/mcp/register",
  "/mcp/authorize",
  "/mcp/authorize/request/*",
  "/mcp/token",
]) {
  mcp.use(path, oauthRequestBounds);
}

const jsonError = (description: string) =>
  jsonResponse(description, oauthErrorSchema);

// OAuth clients parse validation failures, so these routes answer with the
// RFC 6749 / RFC 7591 JSON error shape instead of the router's text default.
type ValidationResult = { success: boolean; error?: { issues: unknown[] } };

const oauthValidationHook =
  (error: "invalid_request" | "invalid_client_metadata") =>
  (result: ValidationResult): undefined => {
    if (result.success) return;
    const issue = result.error?.issues[0] as
      | { path?: PropertyKey[]; message?: string }
      | undefined;
    const field = issue?.path?.map(String).join(".");
    throw new HTTPException(400, {
      res: Response.json(
        {
          error: field?.startsWith("redirect_uri")
            ? "invalid_redirect_uri"
            : error,
          error_description: issue
            ? `${field || "request"}: ${issue.message}`
            : "Invalid request",
        },
        { status: 400 },
      ),
    });
  };

const registerRoute = createRoute({
  method: "post",
  operationId: "registerMcpOAuthClient",
  path: "/mcp/register",
  tags: ["MCP"],
  summary: "Register MCP OAuth client",
  description:
    "Dynamically register a public OAuth client for the MCP endpoint. Public clients hold no secret, so authorization is protected by PKCE and an explicit consent step.",
  security: [],
  request: {
    body: {
      required: true,
      content: { "application/json": { schema: clientRegistrationSchema } },
    },
  },
  responses: {
    200: jsonResponse(
      "Registered OAuth client",
      clientRegistrationResponseSchema,
    ),
    400: jsonError("Invalid client metadata"),
  },
});

const authorizeRoute = createRoute({
  method: "get",
  operationId: "authorizeMcpOAuthClient",
  path: "/mcp/authorize",
  tags: ["MCP"],
  summary: "Start MCP authorization",
  description:
    "Begin an MCP OAuth authorization. Redirects the browser to the Kaneo consent page, which then approves or denies the request.",
  security: [],
  request: { query: authorizationQuerySchema },
  responses: {
    302: { description: "Redirect to the Kaneo consent page" },
    400: jsonError("Invalid authorization request"),
  },
});

const getAuthorizationRequestRoute = createRoute({
  method: "get",
  operationId: "getMcpAuthorizationRequest",
  path: "/mcp/authorize/request/{requestId}",
  tags: ["MCP"],
  summary: "Get consent request",
  description:
    "Get the client name and redirect URI for a pending consent request, so the consent page can show who is asking.",
  security: [],
  request: { params: authorizationRequestParamSchema },
  responses: {
    200: jsonResponse(
      "Authorization request details",
      authorizationRequestResponseSchema,
    ),
    400: jsonError("Invalid OAuth client"),
    404: jsonError("Unknown or expired authorization request"),
  },
});

const decideAuthorizationRequestRoute = createRoute({
  method: "post",
  operationId: "decideMcpAuthorizationRequest",
  path: "/mcp/authorize/request/{requestId}",
  tags: ["MCP"],
  summary: "Decide consent request",
  description:
    "Approve or deny a pending consent request and get the URL to send the browser back to.",
  request: {
    params: authorizationRequestParamSchema,
    body: {
      required: true,
      content: { "application/json": { schema: authorizationDecisionSchema } },
    },
  },
  responses: {
    200: jsonResponse(
      "OAuth client redirect",
      authorizationDecisionResponseSchema,
    ),
    400: jsonError("Invalid request or OAuth client"),
    401: jsonError("Authentication required"),
    403: jsonError("Untrusted request origin"),
    404: jsonError("Unknown or expired authorization request"),
  },
});

mcp
  .openapi(
    registerRoute,
    async (c) => c.json(await registerMcpClient(c.req.valid("json")), 200),
    oauthValidationHook("invalid_client_metadata"),
  )
  .openapi(
    authorizeRoute,
    async (c) => c.redirect(await beginMcpAuthorization(c.req.valid("query"))),
    oauthValidationHook("invalid_request"),
  )
  .openapi(
    getAuthorizationRequestRoute,
    async (c) =>
      c.json(
        await getMcpAuthorizationRequest(c.req.valid("param").requestId),
        200,
      ),
    oauthValidationHook("invalid_request"),
  )
  .openapi(
    decideAuthorizationRequestRoute,
    async (c) => {
      const redirect = await decideMcpAuthorizationRequest({
        requestId: c.req.valid("param").requestId,
        decision: c.req.valid("json"),
        headers: c.req.raw.headers,
        origin: c.req.header("origin"),
      });
      return c.json({ redirect }, 200);
    },
    oauthValidationHook("invalid_request"),
  );

mcp.post("/mcp/token", async (c) => {
  const contentType = c.req.header("content-type") || "";
  let params: Record<string, unknown>;

  try {
    if (contentType.includes("application/x-www-form-urlencoded")) {
      params = Object.fromEntries(new URLSearchParams(await c.req.text()));
    } else {
      const input: unknown = await c.req.json();
      if (!input || typeof input !== "object" || Array.isArray(input))
        return c.json({ error: "invalid_request" }, 400);
      params = input as Record<string, unknown>;
    }
  } catch {
    return c.json({ error: "invalid_request" }, 400);
  }

  const { grant_type, code, client_id, code_verifier, redirect_uri } = params;

  if (grant_type !== "authorization_code") {
    return c.json({ error: "unsupported_grant_type" }, 400);
  }
  if (
    typeof code !== "string" ||
    !code ||
    code.length > 128 ||
    typeof client_id !== "string" ||
    !client_id ||
    client_id.length > 128 ||
    typeof code_verifier !== "string" ||
    !code_verifier ||
    code_verifier.length > 128 ||
    typeof redirect_uri !== "string" ||
    !redirect_uri ||
    redirect_uri.length > 2048
  ) {
    return c.json({ error: "invalid_request" }, 400);
  }

  const result = await exchangeCode(
    code,
    client_id,
    code_verifier,
    redirect_uri,
  );
  if (!result) {
    return c.json({ error: "invalid_grant" }, 400);
  }

  return c.json({
    access_token: result.accessToken,
    token_type: "bearer",
    expires_in: result.expiresIn,
  });
});

mcp.get("/.well-known/oauth-protected-resource/api/mcp", (c) =>
  c.json({
    resource: `${publicApiUrl}/api/mcp`,
    authorization_servers: [`${publicApiUrl}/api`],
  }),
);

mcp.get("/.well-known/oauth-authorization-server/api", (c) =>
  c.json({
    issuer: `${publicApiUrl}/api`,
    authorization_endpoint: `${publicApiUrl}/api/mcp/authorize`,
    token_endpoint: `${publicApiUrl}/api/mcp/token`,
    registration_endpoint: `${publicApiUrl}/api/mcp/register`,
    response_types_supported: ["code"],
    grant_types_supported: ["authorization_code"],
    code_challenge_methods_supported: ["S256"],
    token_endpoint_auth_methods_supported: ["none"],
  }),
);

mcp.all("/mcp", async (c) => {
  const authResult = await validateBearerToken(c.req.raw);
  if (!authResult) {
    // Canonical RFC 9728 URL: the well-known path goes before the resource
    // path. MCP clients discover from this header, so it must be the URL
    // auditors accept; the /api/.well-known alias below stays for clients
    // that cached the previously advertised URL.
    const prmUrl = `${publicApiUrl}/.well-known/oauth-protected-resource/api/mcp`;
    c.header("WWW-Authenticate", `Bearer resource_metadata="${prmUrl}"`);
    return c.json(
      {
        error: "invalid_token",
        error_description: "Missing or invalid token",
      },
      401,
    );
  }

  if (c.req.method !== "POST") {
    return c.json({ error: "Method not allowed" }, 405);
  }

  if (!isJsonContentType(c.req.header("content-type"))) {
    return c.json({ error: "Unsupported Media Type" }, 415);
  }

  await mcpRequestBounds(c, async () => {});

  if (
    !(await isLegacyRequest(c.req.raw.clone(), undefined, {
      maxRequestBodySize: MCP_BODY_BYTES,
    }))
  ) {
    const modern = createModernMcpHandler(authResult.token, internalApiUrl);
    return modern.fetch(c.req.raw);
  }

  // A fresh stateless transport lets legacy POSTs reach any replica. It also
  // accepts session IDs issued before this change after their owner is gone.
  const transport = new WebStandardStreamableHTTPServerTransport({
    sessionIdGenerator: undefined,
    maxRequestBodySize: MCP_BODY_BYTES,
  });
  const server = createMcpServerForUser(authResult.token, internalApiUrl);
  await server.connect(transport);
  return transport.handleRequest(c.req.raw);
});

export default mcp;

export function mcpWellKnownRoutes(baseUrl: string) {
  const wellKnown = new Hono();

  wellKnown.get("/.well-known/oauth-protected-resource/api/mcp", (c) =>
    c.json({
      resource: `${baseUrl}/api/mcp`,
      authorization_servers: [`${baseUrl}/api`],
    }),
  );

  wellKnown.get("/.well-known/oauth-authorization-server/api", (c) =>
    c.json({
      issuer: `${baseUrl}/api`,
      authorization_endpoint: `${baseUrl}/api/mcp/authorize`,
      token_endpoint: `${baseUrl}/api/mcp/token`,
      registration_endpoint: `${baseUrl}/api/mcp/register`,
      response_types_supported: ["code"],
      grant_types_supported: ["authorization_code"],
      code_challenge_methods_supported: ["S256"],
      token_endpoint_auth_methods_supported: ["none"],
    }),
  );

  return wellKnown;
}