Generates cryptographic API keys, hashes them with SHA-256, validates key formats, and extracts keys from authorization headers for API key management and authentication.
import { createHash, randomBytes } from 'crypto'
// API key format: slai_[64-character-hex]
export const API_KEY_PREFIX = 'slai_'
export const API_KEY_LENGTH = 64 // Length of the hex part
export const FULL_API_KEY_LENGTH = API_KEY_PREFIX.length + API_KEY_LENGTH
export interface ApiKeyData {
fullKey: string
prefix: string
hash: string
}
/**
* Generate a new API key with the format: slai_[64-character-hex]
*/
export function generateApiKey(): ApiKeyData {
// Generate 32 random bytes (which will be 64 hex characters)
const randomPart = randomBytes(32).toString('hex')
const fullKey = API_KEY_PREFIX + randomPart
// Extract prefix (first 12 characters for display purposes)
const prefix = fullKey.substring(0, 12)
// Hash the full key for database storage
const hash
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key