Files
Kaname/src/lib/api-keys.ts
T
Pascal LinxweilerandClaude Opus 5.5 ea1f18cc74 Deployments: API keys, deploy from the library, reorganized form
- Settings → API keys (generate or paste, show again, delete). Deployments with
  "Require an API key" get them via LLAMA_API_KEY / VLLM_API_KEY (--api-key for
  several vLLM keys); values are masked in the stored/shown command and in logs.
  The chat proxy sends a key.
- "Deploy" in the library and on the model page preselects the model and a
  runtime that can serve it; library rows and the model page link to the
  model's deployments.
- Deployment form: grouped launch options with flags next to labels, command in
  its own step, extra arguments as flag/value rows (runtime form too).
- Native selects follow the dark theme (color-scheme), fixing unreadable options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:28:25 +02:00

68 lines
2.7 KiB
TypeScript

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<ApiKeyRow[]> {
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<typeof ApiKeyBody>) {
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<string[]> {
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<string> {
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;
}