import { createHash, randomBytes } from 'crypto'; import { ApiKey } from '@prisma/client'; import { prisma } from './db'; import { requireSecret } from './secrets'; // This secret acts as a hash pepper — it should never be rotated once API // keys exist, since rotating it would invalidate the hash of every key // already issued, silently breaking every integration using them. In production // the server refuses to boot if it isn't set to a strong value (see secrets.ts). const API_KEY_SECRET = requireSecret('API_KEY_SECRET', 'dev-api-key-secret-change-me'); const KEY_PREFIX = 'tsk_'; // "TeamSync key" — recognizable in logs/git-history scanners if leaked /** Generate a new random API key. The raw value is only ever shown once, at * creation time — only its hash (see hashApiKey) is persisted afterwards. */ export function generateApiKey(): { raw: string; prefix: string } { const raw = KEY_PREFIX + randomBytes(24).toString('hex'); const prefix = raw.slice(0, 12); return { raw, prefix }; } /** Hash a raw API key the same way hashToken() in auth.ts hashes refresh * tokens (SHA-256 of raw + a server secret) — but with its own secret. */ export function hashApiKey(raw: string): string { return createHash('sha256').update(raw + API_KEY_SECRET).digest('hex'); } /** Look up a raw key. Returns null if it doesn't exist or has been revoked. * On a valid hit, bumps lastUsedAt without making the caller wait on it. */ export async function verifyApiKey(raw: string): Promise { const record = await prisma.apiKey.findUnique({ where: { keyHash: hashApiKey(raw) } }); if (!record || record.revokedAt) return null; prisma.apiKey .update({ where: { id: record.id }, data: { lastUsedAt: new Date() } }) .catch((e) => console.error('[api-keys] failed to update lastUsedAt', record.id, e)); return record; }