generateApiKey (lib/api-key.ts)

prompts.chat · src/lib/api-key.ts · typescript · CC0-1.0
auth

Generates and validates secure API keys with a fixed prefix, using crypto random bytes and hex encoding.

// Source: https://github.com/f/prompts.chat | License: CC0-1.0
// Provided via justclaw.it.com; keep this notice with the code.
import { randomBytes } from "crypto";

const API_KEY_PREFIX = "pchat_";
const API_KEY_LENGTH = 32;

/**
 * Generate a secure API key with the pchat_ prefix
 */
export function generateApiKey(): string {
  const randomPart = randomBytes(API_KEY_LENGTH).toString("hex");
  return `${API_KEY_PREFIX}${randomPart}`;
}

/**
 * Validate that an API key has the correct format
 */
export function isValidApiKeyFormat(apiKey: string): boolean {
  if (!apiKey.startsWith(API_KEY_PREFIX)) {
    return false;
  }
  const randomPart = apiKey.slice(API_KEY_PREFIX.length);
  // Should be 64 hex characters (32 bytes)
  return /^[a-f0-9]{64}$/.test(randomPart);
}

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key