summaryrefslogtreecommitdiff
path: root/apps/web/lib/api-key.ts
blob: f5beaac75e83524fff0a3ba6e9c11ed4665e3e6f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { randomBytes, createHash } from "crypto"

const API_KEY_PREFIX = "asa_"

export function generateApiKey(): {
  fullKey: string
  keyHash: string
  keyPrefix: string
} {
  const randomPart = randomBytes(20).toString("hex")
  const fullKey = `${API_KEY_PREFIX}${randomPart}`
  const keyHash = hashApiKey(fullKey)
  const keyPrefix = fullKey.slice(0, 8)

  return { fullKey, keyHash, keyPrefix }
}

export function hashApiKey(key: string): string {
  return createHash("sha256").update(key).digest("hex")
}