// src/lib/mcp/keys.ts — MCP API key generation + hashing (server-only).
// Keys are "eli_" + 32 random bytes (base64url). Only the sha256 hex of the full
// key is ever persisted; the clear key is shown once at creation. `prefix` is a
// display-only fragment ("eli_" + the 4 chars after the prefix).
import "server-only";
import { createHash, randomBytes } from "node:crypto";

/** sha256 hex of an MCP API key — used for storage + validation lookups. */
export function hashApiKey(key: string): string {
  return createHash("sha256").update(key).digest("hex");
}

/** Generate a fresh API key: the clear `key` (return once), its display `prefix`,
 *  and the `hash` to persist. */
export function generateApiKey(): {
  key: string;
  prefix: string;
  hash: string;
} {
  const key = `eli_${randomBytes(32).toString("base64url")}`;
  const prefix = `eli_${key.slice(4, 8)}`;
  return { key, prefix, hash: hashApiKey(key) };
}
