1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
import { describe, it, expect } from "vitest"
import { generateApiKey, hashApiKey } from "./api-key"
describe("generateApiKey", () => {
it("generates a key with the asa_ prefix", () => {
const { fullKey } = generateApiKey()
expect(fullKey.startsWith("asa_")).toBe(true)
})
it("generates a 44-character key", () => {
const { fullKey } = generateApiKey()
expect(fullKey.length).toBe(44)
})
it("returns a key prefix that is the first 8 characters", () => {
const { fullKey, keyPrefix } = generateApiKey()
expect(keyPrefix).toBe(fullKey.slice(0, 8))
})
it("returns a hash that matches hashing the full key", () => {
const { fullKey, keyHash } = generateApiKey()
expect(keyHash).toBe(hashApiKey(fullKey))
})
it("generates unique keys", () => {
const first = generateApiKey()
const second = generateApiKey()
expect(first.fullKey).not.toBe(second.fullKey)
})
})
describe("hashApiKey", () => {
it("returns a 64-character hex string", () => {
const hash = hashApiKey("asa_test")
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
it("is deterministic", () => {
const hashA = hashApiKey("asa_test_key")
const hashB = hashApiKey("asa_test_key")
expect(hashA).toBe(hashB)
})
it("produces different hashes for different keys", () => {
const hashA = hashApiKey("asa_key_one")
const hashB = hashApiKey("asa_key_two")
expect(hashA).not.toBe(hashB)
})
})
|