import "server-only"; import { randomBytes } from "node:crypto"; import { asc, eq } from "drizzle-orm"; import { z } from "zod"; import { db } from "@/lib/db/client"; import { apiKeys } from "@/lib/db/schema"; export class ApiKeyError extends Error { constructor( public code: "invalid" | "not_found" | "conflict", message: string, public status: number, ) { super(message); } } // No whitespace or commas: llama.cpp takes several keys as one comma-separated list. export const ApiKeyBody = z.object({ name: z.string().trim().min(1).max(80), key: z .string() .trim() .min(16, "at least 16 characters") .max(256) .regex(/^[\x21-\x7e]+$/, "printable characters without spaces") .refine((k) => !k.includes(","), "no commas") .optional(), }); export const generateApiKey = () => `sk-kaname-${randomBytes(24).toString("base64url")}`; /** "…" plus the last 4 characters: enough to tell keys apart without showing them. */ const mask = (key: string) => `…${key.slice(-4)}`; export type ApiKeyRow = { id: string; name: string; hint: string; createdAt: number }; export async function listApiKeys(): Promise { const rows = await db().select().from(apiKeys).orderBy(asc(apiKeys.createdAt)); return rows.map((r) => ({ id: r.id, name: r.name, hint: mask(r.key), createdAt: r.createdAt.getTime() })); } /** Returns the full key once, so the user can copy it. */ export async function createApiKey(input: z.infer) { const key = input.key ?? generateApiKey(); const clash = await db().query.apiKeys.findFirst({ columns: { id: true }, where: eq(apiKeys.key, key) }); if (clash) throw new ApiKeyError("conflict", "This key already exists.", 409); const [row] = await db().insert(apiKeys).values({ name: input.name, key }).returning(); return { id: row.id, name: row.name, key, hint: mask(key), createdAt: row.createdAt.getTime() }; } export async function deleteApiKey(id: string) { const res = await db().delete(apiKeys).where(eq(apiKeys.id, id)).returning({ id: apiKeys.id }); if (res.length === 0) throw new ApiKeyError("not_found", "API key not found.", 404); } /** All key values (for runtime containers and Kaname's own requests to them). */ export async function apiKeyValues(): Promise { return (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key); } /** One key's value, for "show key" in Settings. */ export async function revealApiKey(id: string): Promise { const row = await db().query.apiKeys.findFirst({ columns: { key: true }, where: eq(apiKeys.id, id) }); if (!row) throw new ApiKeyError("not_found", "API key not found.", 404); return row.key; }