import { env } from "cloudflare:workers";
import { z } from "zod";
import { first, run, stmt } from "../db";
import { randomToken, sha256Hex } from "../crypto";
import { loadUserById, toViewer, viewerFromSessionCookie } from "../auth";
import { hasPermission, loadRepo, loadRepoById, repoPermission } from "../repos";
import { enforceRateLimit, requestIp } from "../limits";
import { parseTokenPermissions } from "../token-scope";
import { deleteAccessToken, mintFineGrainedToken, purgeExpiredOAuthTokens, rotateAccessToken } from "./grants";
import type { GrantSpec } from "./grants";
import { OAuthError, redirectMatches, registerClient, resolveClient } from "./oauth-clients";
import type { OAuthClient } from "./oauth-clients";
import { consentPage, errorPage, signInPage } from "./oauth-consent";
import { formatScope, parseScope, SCOPES_SUPPORTED } from "./scopes";
import type { Viewer } from "~/lib/types";
const ACCESS_TTL_MS = 60 * 60 * 1000;
const REFRESH_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const CODE_TTL_MS = 60 * 1000;
const PENDING_TTL_SECONDS = 600;
const PENDING_PREFIX = "mcp-authz:";
const PKCE_VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
export const MCP_PATH = "/mcp";
export function resourceUrl(origin: string): string {
return `${origin}${MCP_PATH}`;
}
export function protectedResourceMetadataUrl(origin: string): string {
return `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;
}
function json(body: unknown, status = 200): Response {
return Response.json(body, {
status,
headers: { "cache-control": "no-store", "access-control-allow-origin": "*" },
});
}