diff --git a/package.json b/package.json index 56e761b8..309096e2 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "lint": "cross-env NODE_OPTIONS=--no-deprecation next lint", "payload": "cross-env NODE_OPTIONS=--no-deprecation payload", "migrate": "bun run src/scripts/run-migrations.ts", + "mcp:key": "bun run src/tools/cli/create-mcp-key.ts", "db": "cross-env NODE_OPTIONS=--no-deprecation pnpm drizzle-kit", "start": "cross-env NODE_OPTIONS=--no-deprecation next start", "staging": "cross-env NODE_ENV=test NODE_OPTIONS=--no-deprecation next start", diff --git a/src/tools/cli/create-mcp-key.ts b/src/tools/cli/create-mcp-key.ts new file mode 100644 index 00000000..d106a914 --- /dev/null +++ b/src/tools/cli/create-mcp-key.ts @@ -0,0 +1,419 @@ +#!/usr/bin/env bun +/** + * create-mcp-key.ts — provision a read-only MCP API key against a chosen + * environment database (dev / stg / prd). + * + * The key is bound to a superuser account so it can read every collection, and + * only the per-collection `find` capability is enabled, so the key can never + * create, update, or delete anything. It is idempotent: re-running with the + * same label does nothing unless you pass --rotate. + * + * Usage: + * bun run mcp:key prd # target production (.env.prd) + * bun run mcp:key stg --user jason # target staging, bind to a user + * bun run mcp:key prd --label "AI reader" # custom label + * bun run mcp:key prd --rotate # replace an existing key + * bun run mcp:key prd --user 3 # bind by user id + * bun run mcp:key --help + * + * Environment files (gitignored), same layout as `bun run migrate`: + * dev → .env · stg → .env.stg · prd → .env.prd + * Each needs DATABASE_URI and PAYLOAD_SECRET. With no env argument the script + * uses DATABASE_URI / PAYLOAD_SECRET already exported in the shell. + * + * IMPORTANT: PAYLOAD_SECRET must match the target deployment's secret. Keys + * authenticate by an HMAC-SHA256 index computed with that secret, so a mismatched + * secret produces a key the running app rejects with 401. + */ + +import { randomUUID } from "node:crypto"; +import { existsSync, readFileSync } from "node:fs"; +import * as path from "node:path"; +import { getPayload } from "payload"; +import type { Payload } from "payload"; +import type { Role, User } from "@/payload-types"; + +const API_KEY_COLLECTION = "payload-mcp-api-keys"; +const DEFAULT_LABEL = "MCP read-only (all collections)"; +const DEFAULT_DESCRIPTION = + "Read-only access to every collection. Provisioned by src/tools/cli/create-mcp-key.ts."; + +type EnvName = "dev" | "stg" | "prd"; + +const ENV_FILES: Record = { + dev: ".env", + stg: ".env.stg", + prd: ".env.prd", +}; + +const ENV_LABELS: Record = { + dev: "development", + stg: "staging", + prd: "PRODUCTION", +}; + +// ── Console helpers ────────────────────────────────────────────────────── + +const RED = "\x1b[31m"; +const GREEN = "\x1b[32m"; +const YELLOW = "\x1b[33m"; +const CYAN = "\x1b[36m"; +const RESET = "\x1b[0m"; + +const log = (message = ""): void => console.log(message); +const info = (message: string): void => log(`${CYAN}[info]${RESET} ${message}`); +const ok = (message: string): void => log(`${GREEN}[ok]${RESET} ${message}`); +const warn = (message: string): void => log(`${YELLOW}[warn]${RESET} ${message}`); + +function fail(message: string): never { + console.error(`${RED}[error]${RESET} ${message}`); + process.exit(1); +} + +const HELP = `Provision a read-only MCP API key. + +Usage: + bun run mcp:key [dev|stg|prd] [options] + +Options: + --env Environment to target (or pass it as the first argument). + --user Bind the key to this user. Defaults to the lowest-id + dynamic superuser. + --label Key label; also the idempotency key. Default: + "${DEFAULT_LABEL}". + --rotate Delete an existing key with the same label and mint a + new one (prints a fresh secret). + -h, --help Show this help.`; + +// ── Argument parsing ───────────────────────────────────────────────────── + +interface ParsedArgs { + env?: string; + user?: string; + label?: string; + rotate: boolean; + help: boolean; +} + +function parseArgs(argv: string[]): ParsedArgs { + const parsed: ParsedArgs = { rotate: false, help: false }; + const positionals: string[] = []; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === "--rotate") { + parsed.rotate = true; + } else if (arg === "--help" || arg === "-h") { + parsed.help = true; + } else if (arg.startsWith("--env=")) { + parsed.env = arg.slice("--env=".length); + } else if (arg.startsWith("--user=")) { + parsed.user = arg.slice("--user=".length); + } else if (arg.startsWith("--label=")) { + parsed.label = arg.slice("--label=".length); + } else if (arg === "--env") { + parsed.env = argv[++i]; + } else if (arg === "--user") { + parsed.user = argv[++i]; + } else if (arg === "--label") { + parsed.label = argv[++i]; + } else if (arg.startsWith("-")) { + fail(`Unknown option: ${arg} (try --help)`); + } else { + positionals.push(arg); + } + } + + if (!parsed.env && positionals.length > 0) parsed.env = positionals[0]; + return parsed; +} + +// ── Environment loading ────────────────────────────────────────────────── + +interface TargetEnv { + label: string; + uri: string; + secretSource: string; + appUrl?: string; +} + +function parseEnvFile(filePath: string): Record { + const vars: Record = {}; + for (const rawLine of readFileSync(filePath, "utf-8").split("\n")) { + const line = rawLine.trim(); + if (!line || line.startsWith("#")) continue; + const eq = line.indexOf("="); + if (eq === -1) continue; + const key = line.slice(0, eq).trim(); + const value = line.slice(eq + 1).trim().replace(/^["']|["']$/g, ""); + vars[key] = value; + } + return vars; +} + +function loadEnv(name: string | undefined): TargetEnv { + if (!name) { + if (!process.env.DATABASE_URI) { + fail( + "No environment given and DATABASE_URI is not set. Pass dev|stg|prd, or export DATABASE_URI and PAYLOAD_SECRET.", + ); + } + if (!process.env.PAYLOAD_SECRET) { + fail("PAYLOAD_SECRET is not set in the environment."); + } + return { + label: "current environment", + uri: process.env.DATABASE_URI, + secretSource: "the environment", + appUrl: process.env.APP_URL, + }; + } + + if (!(name in ENV_FILES)) { + fail(`Unknown environment "${name}". Choose dev, stg, or prd.`); + } + + const envName = name as EnvName; + const file = ENV_FILES[envName]; + const filePath = path.resolve(process.cwd(), file); + if (!existsSync(filePath)) { + fail(`Missing ${file}. Create it with DATABASE_URI and PAYLOAD_SECRET.`); + } + + const vars = parseEnvFile(filePath); + if (!vars.DATABASE_URI) fail(`${file} has no DATABASE_URI.`); + if (!vars.PAYLOAD_SECRET) fail(`${file} has no PAYLOAD_SECRET.`); + + // payload.config.ts reads these at import time, so set them before the + // dynamic import below. + process.env.DATABASE_URI = vars.DATABASE_URI; + process.env.PAYLOAD_SECRET = vars.PAYLOAD_SECRET; + + return { + label: ENV_LABELS[envName], + uri: vars.DATABASE_URI, + secretSource: file, + // Only the file's own APP_URL: Bun may have auto-loaded a different + // environment's .env (e.g. dev) into process.env, which would misreport + // the endpoint for this target. + appUrl: vars.APP_URL, + }; +} + +const redactUri = (uri: string): string => uri.replace(/(\/\/[^:/@]+:)[^@]*@/, "$1****@"); + +// ── MCP field introspection ────────────────────────────────────────────── + +interface FieldLike { + name?: string; + type?: string; + fields?: FieldLike[]; +} + +/** + * Collects the names of the MCP capability groups that belong to collections. + * Collection groups expose find/create/update/delete; globals only expose + * find/update. Restricting to groups that carry `create` excludes globals and + * the experimental tool groups. + */ +function collectCollectionCapabilityGroups(fields: FieldLike[] | undefined, groups: Set): void { + for (const field of fields ?? []) { + if (field.type === "group" && typeof field.name === "string") { + const childNames = (field.fields ?? []).map((child) => child.name); + if (childNames.includes("find") && childNames.includes("create")) { + groups.add(field.name); + } + } + if (field.fields) { + collectCollectionCapabilityGroups(field.fields, groups); + } + } +} + +/** Mirrors the plugin's own toCamelCase so group names match exactly. */ +const toCamelCase = (value: string): string => + value + .replace(/[-_\s]+(.)?/g, (_, chr: string | undefined) => (chr ? chr.toUpperCase() : "")) + .replace(/^(.)/, (_, chr: string) => chr.toLowerCase()); + +// ── User resolution ────────────────────────────────────────────────────── + +const isDynamicSuperuser = (user: User): boolean => + (user.roleDocs ?? []).some( + (role) => typeof role === "object" && role !== null && (role as Role).isSuperuser === true, + ); + +async function resolveTargetUser(payload: Payload, spec: string | undefined): Promise { + if (spec) { + if (/^\d+$/.test(spec)) { + const user = await payload.findByID({ + collection: "users", + id: Number(spec), + depth: 1, + overrideAccess: true, + }); + if (!user) fail(`No user with id ${spec}.`); + return user; + } + const byUsername = await payload.find({ + collection: "users", + where: { username: { equals: spec } }, + limit: 1, + depth: 1, + overrideAccess: true, + }); + if (byUsername.docs.length === 0) fail(`No user with username "${spec}".`); + return byUsername.docs[0]; + } + + const superRoles = await payload.find({ + collection: "roles", + where: { isSuperuser: { equals: true } }, + limit: 100, + depth: 0, + overrideAccess: true, + }); + const roleIds = superRoles.docs.map((role) => role.id); + if (roleIds.length === 0) { + fail("No superuser role (isSuperuser = true) found. Pass --user ."); + } + + const users = await payload.find({ + collection: "users", + where: { roleDocs: { in: roleIds } }, + limit: 100, + sort: "id", + depth: 1, + overrideAccess: true, + }); + if (users.docs.length === 0) { + fail("No superuser account found. Pass --user ."); + } + if (users.docs.length > 1) { + warn( + `${users.docs.length} superuser accounts found; using the lowest id. Pass --user to pick another:`, + ); + for (const candidate of users.docs) { + log(` #${candidate.id} ${candidate.username}`); + } + } + return users.docs[0]; +} + +// ── Main ───────────────────────────────────────────────────────────────── + +async function main(): Promise { + const args = parseArgs(process.argv.slice(2)); + if (args.help) { + log(HELP); + return; + } + + const env = loadEnv(args.env); + const label = args.label?.trim() || DEFAULT_LABEL; + + log(""); + log(`${CYAN}MCP key provisioner${RESET}`); + log(` target: ${env.label}`); + log(` db: ${redactUri(env.uri)}`); + log(` secret: ${env.secretSource}`); + log(` label: ${label}`); + log(""); + + const { default: config } = await import("@payload-config"); + const resolvedConfig = await config; + const payload = await getPayload({ config: resolvedConfig }); + + const apiKeyCollection = payload.config.collections.find((c) => c.slug === API_KEY_COLLECTION); + if (!apiKeyCollection) { + fail("The payload-mcp-api-keys collection was not found. Is the MCP plugin enabled?"); + } + + const capabilityGroups = new Set(); + collectCollectionCapabilityGroups( + apiKeyCollection.fields as unknown as FieldLike[], + capabilityGroups, + ); + + const user = await resolveTargetUser(payload, args.user); + const username = user.username ?? `#${user.id}`; + if (!isDynamicSuperuser(user)) { + warn(`${username} is not a dynamic superuser; the key may not be able to read every collection.`); + } + + const apiKey = randomUUID(); + const createData: Record = { + user: user.id, + label, + description: DEFAULT_DESCRIPTION, + enableAPIKey: true, + apiKey, + }; + + const enabledSlugs: string[] = []; + for (const collection of payload.config.collections) { + if (collection.slug === API_KEY_COLLECTION) continue; + const group = toCamelCase(collection.slug); + if (capabilityGroups.has(group)) { + createData[group] = { find: true, create: false, update: false, delete: false }; + enabledSlugs.push(collection.slug); + } + } + if (enabledSlugs.length === 0) { + fail("No MCP collection capability fields were found; nothing to enable."); + } + + const existing = await payload.find({ + collection: API_KEY_COLLECTION, + where: { label: { equals: label } }, + limit: 100, + depth: 0, + overrideAccess: true, + }); + + if (existing.docs.length > 0 && !args.rotate) { + warn( + `${existing.docs.length} key(s) already use the label "${label}" (ids: ${existing.docs + .map((doc) => doc.id) + .join(", ")}).`, + ); + info("Nothing created (the secret is only shown at creation)."); + info("Re-run with --rotate to replace it, or --label for a separate key."); + return; + } + + for (const doc of existing.docs) { + await payload.delete({ collection: API_KEY_COLLECTION, id: doc.id, overrideAccess: true }); + info(`Deleted existing key id ${doc.id}.`); + } + + const created = await payload.create({ + collection: API_KEY_COLLECTION, + // The capability groups are assembled dynamically from the live schema. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data: createData as any, + overrideAccess: true, + }); + + ok(`Created MCP API key #${created.id}, bound to ${username}.`); + info( + `Read (find) enabled on ${enabledSlugs.length} collection(s); create/update/delete disabled everywhere.`, + ); + log(""); + log(`${GREEN}${"─".repeat(64)}${RESET}`); + log(` API key (shown once, store it now):`); + log(""); + log(` ${apiKey}`); + log(`${GREEN}${"─".repeat(64)}${RESET}`); + log(""); + log(` MCP clients authenticate with it as a bearer token:`); + log(` Authorization: Bearer `); + log(` POST ${env.appUrl ?? ""}/api/mcp`); +} + +main() + .then(() => process.exit(0)) + .catch((error: unknown) => { + console.error(`${RED}[error]${RESET} ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); + });