import { expect, test, vi } from "vitest" import { generateApiKey, maskApiKey } from "#Source/credential/index.ts" test("generateApiKey creates a stable sk-prefixed key shape", () => { vi.spyOn(crypto, "getRandomValues").mockImplementation((buffer) => { if (buffer === null) { return buffer } const target = buffer as Uint8Array target.forEach((_, index) => { target[index] = index }) return buffer }) const apiKey = generateApiKey({}) const customApiKey = generateApiKey({ prefix: "pk_", alphabet: "ABC123", bodyLength: 6 }) expect(apiKey.startsWith("sk-")).toBe(true) expect(apiKey).toHaveLength(51) expect(apiKey).toMatch(/^sk-[0-9A-Za-z]{48}$/) expect(customApiKey).toBe("pk_ABC123") expect(() => generateApiKey({ alphabet: "", bodyLength: 6 })).toThrow( "Expected alphabet to contain at least one character", ) }) test("maskApiKey hides the middle of a valid key and rejects malformed input", () => { const apiKey = `sk-${"ab"}${"0".repeat(44)}yz` const customOptions = { prefix: "pk_", alphabet: "ABC123", bodyLength: 6 } as const expect(maskApiKey(apiKey)).toBe("sk-ab********************************************yz") expect(maskApiKey("pk_ABC123", customOptions)).toBe("pk_AB**23") expect(() => maskApiKey("not-an-api-key")).toThrow("Invalid API key format") expect(() => maskApiKey(`sk-${"#".repeat(48)}`)).toThrow("Invalid API key format") })